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