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/**
239 * Renders the recording time in the system font: DM Sans has no tabular
240 * figures, so `tabular-nums` alone would still let the width jitter.
241 */
242export function DictationElapsedTime(props: {
243 readonly seconds: number;
244 readonly className?: string;
245}) {
246 return (
247 <SystemText
248 className={cn("text-xs", props.className)}
249 numberOfLines={1}
250 style={{ fontVariant: ["tabular-nums"] }}
251 >
252 {Math.floor(props.seconds / 60)}:{String(props.seconds % 60).padStart(2, "0")}
253 </SystemText>
254 );
255}
256
257function VoiceActionButton(props: {
258 readonly size?: "regular" | "large";
259 readonly accessibilityLabel: string;
260 readonly disabled?: boolean;
261 readonly icon: AppSymbolName;
262 readonly loading?: boolean;
263 readonly onPress: () => void;
264 readonly variant?: "plain" | "primary";
265}) {
266 const variant = props.variant ?? "plain";
267 const loadingVisibility = useSharedValue(props.loading ? 1 : 0);
268 useLayoutEffect(() => {
269 loadingVisibility.value = withTiming(props.loading ? 1 : 0, DICTATION_TIMING);
270 }, [loadingVisibility, props.loading]);
271 const primaryStyle = useAnimatedStyle(() => ({ opacity: 1 - loadingVisibility.value }));
272
273 return (
274 <Pressable
275 accessibilityLabel={props.accessibilityLabel}
276 accessibilityRole="button"
277 accessibilityState={{ busy: props.loading, disabled: props.disabled }}
278 className="size-[44px] shrink-0 items-center justify-center active:opacity-70"
279 disabled={props.disabled}
280 onPress={props.onPress}
281 style={{ opacity: props.disabled && !props.loading ? 0.4 : 1 }}
282 >
283 <View
284 className={cn(
285 "items-center justify-center",
286 variant === "primary"
287 ? props.size === "large"
288 ? "size-[44px] rounded-full bg-subtle"
289 : "size-[30px] rounded-full bg-subtle"
290 : "size-[44px]",
291 )}
292 >
293 {variant === "primary" ? (
294 <Animated.View
295 className="absolute inset-0 rounded-full bg-primary"
296 style={primaryStyle}
297 />
298 ) : null}
299 <View className="absolute inset-0 items-center justify-center">
300 {props.loading ? (
301 <AppActivityIndicator size="small" colorClassName="accent-icon-muted" />
302 ) : (
303 <SymbolView
304 name={props.icon}
305 size={props.size === "large" ? 24 : variant === "primary" ? 16 : 20}
306 weight={variant === "primary" ? "semibold" : "regular"}
307 tintColorClassName={
308 variant === "primary" ? "accent-primary-foreground" : "accent-icon"
309 }
310 type="monochrome"
311 />
312 )}
313 </View>
314 </View>
315 </Pressable>
316 );
317}
318
319export function ComposerDictationStatus(props: {
320 readonly audioLevels: SharedValue<number[]>;
321 readonly elapsedSeconds: number;
322 readonly phase: VoiceInputPhase;
323 readonly presentation: VoiceComposerPresentation;
324 readonly onDismissError: () => void;
325}) {
326 const recordingVisibility = useSharedValue(props.phase === "recording" ? 1 : 0);
327 useLayoutEffect(() => {
328 recordingVisibility.value = withTiming(props.phase === "recording" ? 1 : 0, DICTATION_TIMING);
329 }, [props.phase, recordingVisibility]);
330 const waveformStyle = useAnimatedStyle(() => ({
331 opacity: recordingVisibility.value,
332 }));
333 const labelStyle = useAnimatedStyle(() => ({
334 opacity: 1 - recordingVisibility.value,
335 }));
336
337 if (!props.presentation.statusLabel) return null;
338 const isError = props.presentation.statusKind === "error";
339 return (
340 <View className="relative h-11 min-w-0 flex-1 justify-center">
341 {isError ? (
342 <View className="min-w-0 flex-row items-center gap-1.5 px-2">
343 <Text className="min-w-0 flex-1 text-sm text-danger-foreground" numberOfLines={2}>
344 {props.presentation.statusLabel}
345 </Text>
346 <Pressable
347 accessibilityLabel="Dismiss voice input error"
348 accessibilityRole="button"
349 className="size-7 items-center justify-center active:opacity-70"
350 hitSlop={8}
351 onPress={props.onDismissError}
352 >
353 <SymbolView
354 name="xmark"
355 size={12}
356 tintColorClassName="accent-icon-muted"
357 type="monochrome"
358 />
359 </Pressable>
360 </View>
361 ) : (
362 <View
363 accessible
364 accessibilityLabel={props.presentation.statusLabel}
365 accessibilityLiveRegion={props.phase === "recording" ? "none" : "polite"}
366 className="h-11"
367 >
368 <Animated.View
369 className="absolute inset-0 min-w-0 flex-row items-center gap-2 px-1"
370 style={waveformStyle}
371 >
372 <VoiceWaveform audioLevels={props.audioLevels} />
373 <DictationElapsedTime
374 className="text-foreground-muted"
375 seconds={props.elapsedSeconds}
376 />
377 </Animated.View>
378 <Animated.View className="absolute inset-0 justify-center px-2" style={labelStyle}>
379 <Text className="text-center text-sm text-foreground-muted" numberOfLines={1}>
380 {props.presentation.statusLabel}
381 </Text>
382 </Animated.View>
383 </View>
384 )}
385 </View>
386 );
387}
388
389export function ComposerDictationCancelAction(props: {
390 readonly size?: "regular" | "large";
391 readonly presentation: VoiceComposerPresentation;
392 readonly onCancel: () => void;
393}) {
394 if (props.presentation.leadingAction !== "cancel") return null;
395 return (
396 <VoiceActionButton
397 size={props.size}
398 accessibilityLabel="Cancel dictation"
399 icon="xmark"
400 onPress={props.onCancel}
401 />
402 );
403}
404
405export function ComposerDictationPrimaryAction(props: {
406 readonly size?: "regular" | "large";
407 readonly state: VoiceInputState;
408 readonly presentation: VoiceComposerPresentation;
409 readonly isAvailable: boolean;
410 readonly disabled?: boolean;
411 readonly onStart: () => void;
412 readonly onConfirm: () => void;
413 readonly onCancel: () => void;
414}) {
415 if (props.presentation.trailingAction === "confirm") {
416 return (
417 <VoiceActionButton
418 size={props.size}
419 accessibilityLabel={
420 props.presentation.confirmationEnabled
421 ? "Finish dictation"
422 : (props.presentation.statusLabel ?? "Preparing voice input")
423 }
424 disabled={!props.presentation.confirmationEnabled}
425 icon="checkmark"
426 loading={!props.presentation.confirmationEnabled}
427 onPress={props.onConfirm}
428 variant="primary"
429 />
430 );
431 }
432
433 return <ComposerDictationStartAction {...props} />;
434}
435
436export function ComposerDictationStartAction(props: {
437 readonly size?: "regular" | "large";
438 readonly state: VoiceInputState;
439 readonly isAvailable: boolean;
440 readonly disabled?: boolean;
441 readonly onStart: () => void;
442 readonly onCancel: () => void;
443}) {
444 if (!props.isAvailable) return null;
445 const openSettings = props.state.phase === "error" && props.state.errorAction === "settings";
446 return (
447 <VoiceActionButton
448 size={props.size}
449 accessibilityLabel={openSettings ? "Open microphone settings" : "Start dictation"}
450 disabled={props.disabled}
451 icon="mic"
452 onPress={
453 openSettings
454 ? () => {
455 props.onCancel();
456 void Linking.openSettings();
457 }
458 : props.onStart
459 }
460 />
461 );
462}