Open History to see the last commit
1import type { VoiceInputPhase, VoiceInputState } from "@t3tools/client-runtime/voice-input";
2import { memo, useCallback, useLayoutEffect, useState, type ReactNode } from "react";
3import { Linking, Pressable, Text as SystemText, View, type LayoutChangeEvent } from "react-native";
4import Animated, {
5 Easing,
6 ReduceMotion,
7 useAnimatedStyle,
8 useReducedMotion,
9 useSharedValue,
10 withTiming,
11 type EntryExitAnimationFunction,
12 type SharedValue,
13} from "react-native-reanimated";
14
15import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
16import { AppText as Text } from "../../components/ui/AppText";
17import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
18import { cn } from "../../lib/cn";
19import type { VoiceComposerPresentation } from "./voiceInputPresentation";
20import { VOICE_WAVEFORM_SAMPLE_COUNT } from "./voiceInputMetering";
21
22const DICTATION_TIMING = {
23 duration: 220,
24 easing: Easing.out(Easing.cubic),
25 reduceMotion: ReduceMotion.System,
26} as const;
27const TOOLBAR_FLIP_TIMING = {
28 duration: 260,
29 easing: Easing.inOut(Easing.cubic),
30 reduceMotion: ReduceMotion.System,
31} as const;
32const TOOLBAR_HALF_HEIGHT = 22;
33const TOOLBAR_PERSPECTIVE = 600;
34
35function toolbarFlip(fromDegrees: number, toDegrees: number): EntryExitAnimationFunction {
36 return () => {
37 "worklet";
38 const fromRadians = (fromDegrees * Math.PI) / 180;
39 const toRadians = (toDegrees * Math.PI) / 180;
40 const fromSine = Math.sin(fromRadians);
41 const toSine = Math.sin(toRadians);
42 return {
43 initialValues: {
44 opacity: fromDegrees === 0 ? 1 : 0,
45 transform: [
46 { perspective: TOOLBAR_PERSPECTIVE },
47 { translateY: -TOOLBAR_HALF_HEIGHT * fromSine },
48 { rotateX: `${fromDegrees}deg` },
49 ],
50 },
51 animations: {
52 opacity: withTiming(toDegrees === 0 ? 1 : 0, TOOLBAR_FLIP_TIMING),
53 transform: [
54 { perspective: TOOLBAR_PERSPECTIVE },
55 {
56 translateY: withTiming(-TOOLBAR_HALF_HEIGHT * toSine, {
57 ...TOOLBAR_FLIP_TIMING,
58 easing: (time) => {
59 const angle =
60 fromRadians + (toRadians - fromRadians) * TOOLBAR_FLIP_TIMING.easing(time);
61 return (Math.sin(angle) - fromSine) / (toSine - fromSine);
62 },
63 }),
64 },
65 { rotateX: withTiming(`${toDegrees}deg`, TOOLBAR_FLIP_TIMING) },
66 ],
67 },
68 };
69 };
70}
71
72const DRAFT_TOOLBAR_ENTERING = toolbarFlip(90, 0);
73const DRAFT_TOOLBAR_EXITING = toolbarFlip(0, 90);
74const DICTATION_TOOLBAR_ENTERING = toolbarFlip(-90, 0);
75const DICTATION_TOOLBAR_EXITING = toolbarFlip(0, -90);
76const WAVEFORM_BAR_HEIGHT = 32;
77const WAVEFORM_MIN_BAR_HEIGHT = 2;
78const WAVEFORM_BAR_SPACING = 5;
79const WAVEFORM_TIMING = {
80 duration: 100,
81 easing: Easing.out(Easing.quad),
82 reduceMotion: ReduceMotion.System,
83} as const;
84
85export function ComposerDictationDraftContent(props: {
86 readonly children: ReactNode;
87 readonly className?: string;
88 readonly compact: boolean;
89 readonly hidden: boolean;
90}) {
91 const rotation = useSharedValue(props.hidden ? 1 : 0);
92 useLayoutEffect(() => {
93 rotation.value = withTiming(props.hidden ? 1 : 0, TOOLBAR_FLIP_TIMING);
94 }, [props.hidden, rotation]);
95 const compact = props.compact;
96 const animatedStyle = useAnimatedStyle(() => ({
97 opacity: compact ? 1 - rotation.value : 1,
98 transform: compact
99 ? [
100 { perspective: TOOLBAR_PERSPECTIVE },
101 { translateY: -TOOLBAR_HALF_HEIGHT * Math.sin((rotation.value * Math.PI) / 2) },
102 { rotateX: `${rotation.value * 90}deg` },
103 ]
104 : [],
105 }));
106
107 return (
108 <Animated.View
109 accessibilityElementsHidden={props.hidden}
110 importantForAccessibility={props.hidden ? "no-hide-descendants" : "auto"}
111 collapsable={false}
112 className={props.className}
113 pointerEvents={props.hidden ? "none" : "auto"}
114 style={[animatedStyle, { backfaceVisibility: "hidden" }]}
115 >
116 {props.children}
117 </Animated.View>
118 );
119}
120
121export function ComposerDictationToolbar(props: {
122 readonly children: ReactNode;
123 readonly showsDictation: boolean;
124 readonly visible?: boolean;
125}) {
126 // Android can drop the reduced-motion flip's final frame, leaving the toolbar invisible.
127 const reducedMotion = useReducedMotion();
128 const entering = props.showsDictation ? DICTATION_TOOLBAR_ENTERING : DRAFT_TOOLBAR_ENTERING;
129 const exiting = props.showsDictation ? DICTATION_TOOLBAR_EXITING : DRAFT_TOOLBAR_EXITING;
130
131 return (
132 <View className="relative h-[44px] overflow-hidden">
133 {props.visible !== false ? (
134 <Animated.View
135 key={props.showsDictation ? "dictation" : "draft"}
136 className="absolute inset-0"
137 entering={reducedMotion ? undefined : entering}
138 exiting={reducedMotion ? undefined : exiting}
139 style={{ backfaceVisibility: "hidden" }}
140 >
141 {props.children}
142 </Animated.View>
143 ) : null}
144 </View>
145 );
146}
147
148const WaveformBar = memo(function WaveformBar(props: {
149 readonly audioLevels: SharedValue<number[]>;
150 readonly sampleIndex: number;
151 readonly height?: number;
152}) {
153 const { audioLevels, sampleIndex } = props;
154 const height = props.height ?? WAVEFORM_BAR_HEIGHT;
155 const animatedStyle = useAnimatedStyle(() => {
156 const level = audioLevels.value[sampleIndex] ?? 0;
157 return {
158 opacity: withTiming(0.22 + level * 0.78, WAVEFORM_TIMING),
159 transform: [
160 {
161 scaleY: withTiming(
162 (WAVEFORM_MIN_BAR_HEIGHT + level * (height - WAVEFORM_MIN_BAR_HEIGHT)) / height,
163 WAVEFORM_TIMING,
164 ),
165 },
166 ],
167 };
168 });
169
170 return (
171 <Animated.View
172 className="w-0.5 rounded-full bg-foreground"
173 style={[{ height }, animatedStyle]}
174 />
175 );
176});
177
178const COMPACT_WAVEFORM_BAR_COUNT = 8;
179const COMPACT_WAVEFORM_BAR_HEIGHT = 14;
180
181export const CompactVoiceWaveform = memo(function CompactVoiceWaveform(props: {
182 readonly audioLevels: SharedValue<number[]>;
183}) {
184 return (
185 <View
186 accessibilityElementsHidden
187 importantForAccessibility="no-hide-descendants"
188 className="flex-row items-center gap-0.5"
189 style={{ height: COMPACT_WAVEFORM_BAR_HEIGHT }}
190 >
191 {Array.from({ length: COMPACT_WAVEFORM_BAR_COUNT }, (_, index) => (
192 <WaveformBar
193 key={index}
194 audioLevels={props.audioLevels}
195 height={COMPACT_WAVEFORM_BAR_HEIGHT}
196 sampleIndex={VOICE_WAVEFORM_SAMPLE_COUNT - COMPACT_WAVEFORM_BAR_COUNT + index}
197 />
198 ))}
199 </View>
200 );
201});
202
203const VoiceWaveform = memo(function VoiceWaveform(props: {
204 readonly audioLevels: SharedValue<number[]>;
205}) {
206 const [barCount, setBarCount] = useState(0);
207 const handleLayout = useCallback((event: LayoutChangeEvent) => {
208 setBarCount(
209 Math.max(
210 1,
211 Math.min(
212 VOICE_WAVEFORM_SAMPLE_COUNT,
213 Math.floor(event.nativeEvent.layout.width / WAVEFORM_BAR_SPACING),
214 ),
215 ),
216 );
217 }, []);
218
219 return (
220 <View
221 accessibilityElementsHidden
222 importantForAccessibility="no-hide-descendants"
223 className="min-w-0 flex-1 flex-row items-center justify-between overflow-hidden"
224 style={{ height: WAVEFORM_BAR_HEIGHT }}
225 onLayout={handleLayout}
226 >
227 {Array.from({ length: barCount }, (_, index) => (
228 <WaveformBar
229 key={index}
230 audioLevels={props.audioLevels}
231 sampleIndex={VOICE_WAVEFORM_SAMPLE_COUNT - barCount + index}
232 />
233 ))}
234 </View>
235 );
236});
237
238/** Use system tabular figures; DM Sans lacks them and would jitter. */
239export function DictationElapsedTime(props: {
240 readonly seconds: number;
241 readonly className?: string;
242}) {
243 return (
244 <SystemText
245 className={cn("text-xs", props.className)}
246 numberOfLines={1}
247 style={{ fontVariant: ["tabular-nums"] }}
248 >
249 {Math.floor(props.seconds / 60)}:{String(props.seconds % 60).padStart(2, "0")}
250 </SystemText>
251 );
252}
253
254function VoiceActionButton(props: {
255 readonly size?: "regular" | "large";
256 readonly accessibilityLabel: string;
257 readonly disabled?: boolean;
258 readonly icon: AppSymbolName;
259 readonly loading?: boolean;
260 readonly onPress: () => void;
261 readonly variant?: "plain" | "primary";
262}) {
263 const variant = props.variant ?? "plain";
264 const loadingVisibility = useSharedValue(props.loading ? 1 : 0);
265 useLayoutEffect(() => {
266 loadingVisibility.value = withTiming(props.loading ? 1 : 0, DICTATION_TIMING);
267 }, [loadingVisibility, props.loading]);
268 const primaryStyle = useAnimatedStyle(() => ({ opacity: 1 - loadingVisibility.value }));
269
270 return (
271 <Pressable
272 accessibilityLabel={props.accessibilityLabel}
273 accessibilityRole="button"
274 accessibilityState={{ busy: props.loading, disabled: props.disabled }}
275 className="size-[44px] shrink-0 items-center justify-center active:opacity-70"
276 disabled={props.disabled}
277 onPress={props.onPress}
278 style={{ opacity: props.disabled && !props.loading ? 0.4 : 1 }}
279 >
280 <View
281 className={cn(
282 "items-center justify-center",
283 variant === "primary"
284 ? props.size === "large"
285 ? "size-[44px] rounded-full bg-subtle"
286 : "size-[30px] rounded-full bg-subtle"
287 : "size-[44px]",
288 )}
289 >
290 {variant === "primary" ? (
291 <Animated.View
292 className="absolute inset-0 rounded-full bg-primary"
293 style={primaryStyle}
294 />
295 ) : null}
296 <View className="absolute inset-0 items-center justify-center">
297 {props.loading ? (
298 <AppActivityIndicator size="small" colorClassName="accent-icon-muted" />
299 ) : (
300 <SymbolView
301 name={props.icon}
302 size={props.size === "large" ? 24 : variant === "primary" ? 16 : 20}
303 weight={variant === "primary" ? "semibold" : "regular"}
304 tintColorClassName={
305 variant === "primary" ? "accent-primary-foreground" : "accent-icon"
306 }
307 type="monochrome"
308 />
309 )}
310 </View>
311 </View>
312 </Pressable>
313 );
314}
315
316export function ComposerDictationStatus(props: {
317 readonly audioLevels: SharedValue<number[]>;
318 readonly elapsedSeconds: number;
319 readonly phase: VoiceInputPhase;
320 readonly presentation: VoiceComposerPresentation;
321 readonly onDismissError: () => void;
322}) {
323 const recordingVisibility = useSharedValue(props.phase === "recording" ? 1 : 0);
324 useLayoutEffect(() => {
325 recordingVisibility.value = withTiming(props.phase === "recording" ? 1 : 0, DICTATION_TIMING);
326 }, [props.phase, recordingVisibility]);
327 const waveformStyle = useAnimatedStyle(() => ({
328 opacity: recordingVisibility.value,
329 }));
330 const labelStyle = useAnimatedStyle(() => ({
331 opacity: 1 - recordingVisibility.value,
332 }));
333
334 if (!props.presentation.statusLabel) return null;
335 const isError = props.presentation.statusKind === "error";
336 return (
337 <View className="relative h-11 min-w-0 flex-1 justify-center">
338 {isError ? (
339 <View className="min-w-0 flex-row items-center gap-1.5 px-2">
340 <Text className="min-w-0 flex-1 text-sm text-danger-foreground" numberOfLines={2}>
341 {props.presentation.statusLabel}
342 </Text>
343 <Pressable
344 accessibilityLabel="Dismiss voice input error"
345 accessibilityRole="button"
346 className="size-7 items-center justify-center active:opacity-70"
347 hitSlop={8}
348 onPress={props.onDismissError}
349 >
350 <SymbolView
351 name="xmark"
352 size={12}
353 tintColorClassName="accent-icon-muted"
354 type="monochrome"
355 />
356 </Pressable>
357 </View>
358 ) : (
359 <View
360 accessible
361 accessibilityLabel={props.presentation.statusLabel}
362 accessibilityLiveRegion={props.phase === "recording" ? "none" : "polite"}
363 className="h-11"
364 >
365 <Animated.View
366 className="absolute inset-0 min-w-0 flex-row items-center gap-2 px-1"
367 style={waveformStyle}
368 >
369 <VoiceWaveform audioLevels={props.audioLevels} />
370 <DictationElapsedTime
371 className="text-foreground-muted"
372 seconds={props.elapsedSeconds}
373 />
374 </Animated.View>
375 <Animated.View className="absolute inset-0 justify-center px-2" style={labelStyle}>
376 <Text className="text-center text-sm text-foreground-muted" numberOfLines={1}>
377 {props.presentation.statusLabel}
378 </Text>
379 </Animated.View>
380 </View>
381 )}
382 </View>
383 );
384}
385
386export function ComposerDictationCancelAction(props: {
387 readonly size?: "regular" | "large";
388 readonly presentation: VoiceComposerPresentation;
389 readonly onCancel: () => void;
390}) {
391 if (props.presentation.leadingAction !== "cancel") return null;
392 return (
393 <VoiceActionButton
394 size={props.size}
395 accessibilityLabel="Cancel dictation"
396 icon="xmark"
397 onPress={props.onCancel}
398 />
399 );
400}
401
402export function ComposerDictationPrimaryAction(props: {
403 readonly size?: "regular" | "large";
404 readonly state: VoiceInputState;
405 readonly presentation: VoiceComposerPresentation;
406 readonly isAvailable: boolean;
407 readonly disabled?: boolean;
408 readonly onStart: () => void;
409 readonly onConfirm: () => void;
410 readonly onCancel: () => void;
411}) {
412 if (props.presentation.trailingAction === "confirm") {
413 return (
414 <VoiceActionButton
415 size={props.size}
416 accessibilityLabel={
417 props.presentation.confirmationEnabled
418 ? "Finish dictation"
419 : (props.presentation.statusLabel ?? "Preparing voice input")
420 }
421 disabled={!props.presentation.confirmationEnabled}
422 icon="checkmark"
423 loading={!props.presentation.confirmationEnabled}
424 onPress={props.onConfirm}
425 variant="primary"
426 />
427 );
428 }
429
430 return <ComposerDictationStartAction {...props} />;
431}
432
433export function ComposerDictationStartAction(props: {
434 readonly size?: "regular" | "large";
435 readonly state: VoiceInputState;
436 readonly isAvailable: boolean;
437 readonly disabled?: boolean;
438 readonly onStart: () => void;
439 readonly onCancel: () => void;
440}) {
441 if (!props.isAvailable) return null;
442 const openSettings = props.state.phase === "error" && props.state.errorAction === "settings";
443 return (
444 <VoiceActionButton
445 size={props.size}
446 accessibilityLabel={openSettings ? "Open microphone settings" : "Start dictation"}
447 disabled={props.disabled}
448 icon="mic"
449 onPress={
450 openSettings
451 ? () => {
452 props.onCancel();
453 void Linking.openSettings();
454 }
455 : props.onStart
456 }
457 />
458 );
459}