Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ComposerDictationControl.tsx

464 lines14.5 KB

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