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 ActivityIndicator,
5 Linking,
6 Platform,
7 Pressable,
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 { AppText as Text } from "../../components/AppText";
23import { SymbolView, type AppSymbolName } from "../../components/AppSymbol";
24import { cn } from "../../lib/cn";
25import type { VoiceComposerPresentation } from "./voiceInputPresentation";
26import { VOICE_WAVEFORM_SAMPLE_COUNT } from "./voiceInputMetering";
27
28const DICTATION_TIMING = {
29 duration: 220,
30 easing: Easing.out(Easing.cubic),
31 reduceMotion: ReduceMotion.System,
32} as const;
33const DICTATION_LAYOUT =
34 Platform.OS === "android"
35 ? undefined
36 : LinearTransition.duration(DICTATION_TIMING.duration).reduceMotion(ReduceMotion.System);
37const TOOLBAR_FLIP_TIMING = {
38 duration: 260,
39 easing: Easing.inOut(Easing.cubic),
40 reduceMotion: ReduceMotion.System,
41} as const;
42const TOOLBAR_HALF_HEIGHT = 22;
43const TOOLBAR_PERSPECTIVE = 600;
44
45/** Moves each face around the same horizontal axis, keeping their edges together. */
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
96/** Rotates the compact draft away without unmounting or resizing its native editor. */
97export function ComposerDictationDraftContent(props: {
98 readonly children: ReactNode;
99 readonly className?: string;
100 readonly compact: boolean;
101 readonly hidden: boolean;
102}) {
103 const rotation = useSharedValue(props.hidden ? 1 : 0);
104 useLayoutEffect(() => {
105 rotation.value = withTiming(props.hidden ? 1 : 0, TOOLBAR_FLIP_TIMING);
106 }, [props.hidden, rotation]);
107 const compact = props.compact;
108 const animatedStyle = useAnimatedStyle(() => ({
109 opacity: compact ? 1 - rotation.value : 1,
110 transform: compact
111 ? [
112 { perspective: TOOLBAR_PERSPECTIVE },
113 { translateY: -TOOLBAR_HALF_HEIGHT * Math.sin((rotation.value * Math.PI) / 2) },
114 { rotateX: `${rotation.value * 90}deg` },
115 ]
116 : [],
117 }));
118
119 return (
120 <Animated.View
121 accessibilityElementsHidden={props.hidden}
122 importantForAccessibility={props.hidden ? "no-hide-descendants" : "auto"}
123 collapsable={false}
124 className={props.className}
125 layout={DICTATION_LAYOUT}
126 pointerEvents={props.hidden ? "none" : "auto"}
127 style={[animatedStyle, { backfaceVisibility: "hidden" }]}
128 >
129 {props.children}
130 </Animated.View>
131 );
132}
133
134/** Flips the entire row while keeping the outgoing controls intact until it leaves. */
135export function ComposerDictationToolbar(props: {
136 readonly children: ReactNode;
137 readonly showsDictation: boolean;
138 readonly visible?: boolean;
139}) {
140 return (
141 <View className="relative h-[44px] overflow-hidden">
142 {props.visible !== false ? (
143 <Animated.View
144 key={props.showsDictation ? "dictation" : "draft"}
145 className="absolute inset-0"
146 entering={props.showsDictation ? DICTATION_TOOLBAR_ENTERING : DRAFT_TOOLBAR_ENTERING}
147 exiting={props.showsDictation ? DICTATION_TOOLBAR_EXITING : DRAFT_TOOLBAR_EXITING}
148 style={{ backfaceVisibility: "hidden" }}
149 >
150 {props.children}
151 </Animated.View>
152 ) : null}
153 </View>
154 );
155}
156
157const WaveformBar = memo(function WaveformBar(props: {
158 readonly audioLevels: SharedValue<number[]>;
159 readonly sampleIndex: number;
160}) {
161 const { audioLevels, sampleIndex } = props;
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 * (WAVEFORM_BAR_HEIGHT - WAVEFORM_MIN_BAR_HEIGHT)) /
170 WAVEFORM_BAR_HEIGHT,
171 WAVEFORM_TIMING,
172 ),
173 },
174 ],
175 };
176 });
177
178 return (
179 <Animated.View
180 className="w-0.5 rounded-full bg-foreground"
181 style={[{ height: WAVEFORM_BAR_HEIGHT }, animatedStyle]}
182 />
183 );
184});
185
186const VoiceWaveform = memo(function VoiceWaveform(props: {
187 readonly audioLevels: SharedValue<number[]>;
188}) {
189 const [barCount, setBarCount] = useState(0);
190 const handleLayout = useCallback((event: LayoutChangeEvent) => {
191 setBarCount(
192 Math.max(
193 1,
194 Math.min(
195 VOICE_WAVEFORM_SAMPLE_COUNT,
196 Math.floor(event.nativeEvent.layout.width / WAVEFORM_BAR_SPACING),
197 ),
198 ),
199 );
200 }, []);
201
202 return (
203 <View
204 accessibilityElementsHidden
205 importantForAccessibility="no-hide-descendants"
206 className="min-w-0 flex-1 flex-row items-center justify-between overflow-hidden"
207 style={{ height: WAVEFORM_BAR_HEIGHT }}
208 onLayout={handleLayout}
209 >
210 {Array.from({ length: barCount }, (_, index) => (
211 <WaveformBar
212 key={index}
213 audioLevels={props.audioLevels}
214 sampleIndex={VOICE_WAVEFORM_SAMPLE_COUNT - barCount + index}
215 />
216 ))}
217 </View>
218 );
219});
220
221function VoiceActionButton(props: {
222 readonly accessibilityLabel: string;
223 readonly disabled?: boolean;
224 readonly icon: AppSymbolName;
225 readonly loading?: boolean;
226 readonly onPress: () => void;
227 readonly variant?: "plain" | "primary";
228}) {
229 const variant = props.variant ?? "plain";
230 const loadingVisibility = useSharedValue(props.loading ? 1 : 0);
231 useLayoutEffect(() => {
232 loadingVisibility.value = withTiming(props.loading ? 1 : 0, DICTATION_TIMING);
233 }, [loadingVisibility, props.loading]);
234 const primaryStyle = useAnimatedStyle(() => ({ opacity: 1 - loadingVisibility.value }));
235
236 return (
237 <Pressable
238 accessibilityLabel={props.accessibilityLabel}
239 accessibilityRole="button"
240 accessibilityState={{ busy: props.loading, disabled: props.disabled }}
241 className="size-[44px] shrink-0 items-center justify-center active:opacity-70"
242 disabled={props.disabled}
243 onPress={props.onPress}
244 style={{ opacity: props.disabled && !props.loading ? 0.4 : 1 }}
245 >
246 <View
247 className={cn(
248 "items-center justify-center",
249 variant === "primary" ? "size-[30px] rounded-full bg-subtle" : "size-[44px]",
250 )}
251 >
252 {variant === "primary" ? (
253 <Animated.View
254 className="absolute inset-0 rounded-full bg-primary"
255 style={primaryStyle}
256 />
257 ) : null}
258 <View className="absolute inset-0 items-center justify-center">
259 {props.loading ? (
260 <ActivityIndicator size="small" colorClassName="accent-icon-muted" />
261 ) : (
262 <SymbolView
263 name={props.icon}
264 size={variant === "primary" ? 16 : 20}
265 weight={variant === "primary" ? "semibold" : "regular"}
266 tintColorClassName={
267 variant === "primary" ? "accent-primary-foreground" : "accent-icon"
268 }
269 type="monochrome"
270 />
271 )}
272 </View>
273 </View>
274 </Pressable>
275 );
276}
277
278export function ComposerDictationStatus(props: {
279 readonly audioLevels: SharedValue<number[]>;
280 readonly elapsedSeconds: number;
281 readonly phase: VoiceInputPhase;
282 readonly presentation: VoiceComposerPresentation;
283 readonly onDismissError: () => void;
284}) {
285 const recordingVisibility = useSharedValue(props.phase === "recording" ? 1 : 0);
286 useLayoutEffect(() => {
287 recordingVisibility.value = withTiming(props.phase === "recording" ? 1 : 0, DICTATION_TIMING);
288 }, [props.phase, recordingVisibility]);
289 const waveformStyle = useAnimatedStyle(() => ({
290 opacity: recordingVisibility.value,
291 }));
292 const labelStyle = useAnimatedStyle(() => ({
293 opacity: 1 - recordingVisibility.value,
294 }));
295
296 if (!props.presentation.statusLabel) return null;
297 const isError = props.presentation.statusKind === "error";
298 const elapsedLabel = `${Math.floor(props.elapsedSeconds / 60)}:${String(props.elapsedSeconds % 60).padStart(2, "0")}`;
299 return (
300 <View className="relative h-11 min-w-0 flex-1 justify-center">
301 {isError ? (
302 <View className="min-w-0 flex-row items-center gap-1.5 px-2">
303 <Text className="min-w-0 flex-1 text-sm text-danger-foreground" numberOfLines={2}>
304 {props.presentation.statusLabel}
305 </Text>
306 <Pressable
307 accessibilityLabel="Dismiss voice input error"
308 accessibilityRole="button"
309 className="size-7 items-center justify-center active:opacity-70"
310 hitSlop={8}
311 onPress={props.onDismissError}
312 >
313 <SymbolView
314 name="xmark"
315 size={12}
316 tintColorClassName="accent-icon-muted"
317 type="monochrome"
318 />
319 </Pressable>
320 </View>
321 ) : (
322 <View
323 accessible
324 accessibilityLabel={props.presentation.statusLabel}
325 accessibilityLiveRegion={props.phase === "recording" ? "none" : "polite"}
326 className="h-11"
327 >
328 <Animated.View
329 className="absolute inset-0 min-w-0 flex-row items-center gap-2 px-1"
330 style={waveformStyle}
331 >
332 <VoiceWaveform audioLevels={props.audioLevels} />
333 <Text
334 className="text-xs text-foreground-muted"
335 numberOfLines={1}
336 style={{ fontVariant: ["tabular-nums"] }}
337 >
338 {elapsedLabel}
339 </Text>
340 </Animated.View>
341 <Animated.View className="absolute inset-0 justify-center px-2" style={labelStyle}>
342 <Text className="text-center text-sm text-foreground-muted" numberOfLines={1}>
343 {props.presentation.statusLabel}
344 </Text>
345 </Animated.View>
346 </View>
347 )}
348 </View>
349 );
350}
351
352export function ComposerDictationCancelAction(props: {
353 readonly presentation: VoiceComposerPresentation;
354 readonly onCancel: () => void;
355}) {
356 if (props.presentation.leadingAction !== "cancel") return null;
357 return (
358 <VoiceActionButton
359 accessibilityLabel="Cancel dictation"
360 icon="xmark"
361 onPress={props.onCancel}
362 />
363 );
364}
365
366export function ComposerDictationPrimaryAction(props: {
367 readonly state: VoiceInputState;
368 readonly presentation: VoiceComposerPresentation;
369 readonly isAvailable: boolean;
370 readonly disabled?: boolean;
371 readonly onStart: () => void;
372 readonly onConfirm: () => void;
373 readonly onCancel: () => void;
374}) {
375 if (props.presentation.trailingAction === "confirm") {
376 return (
377 <VoiceActionButton
378 accessibilityLabel={
379 props.presentation.confirmationEnabled
380 ? "Finish dictation"
381 : (props.presentation.statusLabel ?? "Preparing voice input")
382 }
383 disabled={!props.presentation.confirmationEnabled}
384 icon="checkmark"
385 loading={!props.presentation.confirmationEnabled}
386 onPress={props.onConfirm}
387 variant="primary"
388 />
389 );
390 }
391
392 return <ComposerDictationStartAction {...props} />;
393}
394
395export function ComposerDictationStartAction(props: {
396 readonly state: VoiceInputState;
397 readonly isAvailable: boolean;
398 readonly disabled?: boolean;
399 readonly onStart: () => void;
400 readonly onCancel: () => void;
401}) {
402 if (!props.isAvailable) return null;
403 const openSettings = props.state.phase === "error" && props.state.errorAction === "settings";
404 return (
405 <VoiceActionButton
406 accessibilityLabel={openSettings ? "Open microphone settings" : "Start dictation"}
407 disabled={props.disabled}
408 icon="mic"
409 onPress={
410 openSettings
411 ? () => {
412 props.onCancel();
413 void Linking.openSettings();
414 }
415 : props.onStart
416 }
417 />
418 );
419}