The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 212 lines 7.37 KB
Raw
1 import { LoaderCircleIcon, PauseIcon, PlayIcon, TriangleAlertIcon } from "lucide-react";
2 import { useGT } from "gt-react";
3 import { createContext, useContext, useRef, useState } from "react";
4
5 import { useStableCallback } from "~/hooks/useStableCallback";
6 import { ContextChip, ContextChipAction, ContextChipLabel } from "../ContextChip";
7 import { middleTruncateAttachmentName } from "../composerInlineChip";
8 import { Spinner } from "../ui/spinner";
9
10 export const AudioPreviewUnmountContext = createContext<((audio: HTMLAudioElement) => void) | null>(
11 null,
12 );
13
14 type AudioPreviewProps = {
15 readonly src: string;
16 readonly name: string;
17 readonly revision?: string | null;
18 readonly onError?: () => void;
19 readonly compact?: boolean;
20 readonly variant?: "chip" | "bubble";
21 readonly failed?: boolean;
22 readonly onOpen?: (() => void) | undefined;
23 readonly onRetry?: () => void;
24 };
25
26 export function AudioPreview(props: AudioPreviewProps) {
27 return props.compact ? (
28 <AudioChip key={`${props.revision ?? props.src}:${!!props.failed}`} {...props} />
29 ) : (
30 <StandardAudioPreview {...props} />
31 );
32 }
33
34 function StandardAudioPreview(props: AudioPreviewProps) {
35 const onUnmount = useContext(AudioPreviewUnmountContext);
36 const audioRef = useStableCallback((audio: HTMLAudioElement | null) => {
37 if (audio) return () => onUnmount?.(audio);
38 });
39 const [loadedSource, setLoadedSource] = useState<{ src: string; revision: string } | null>(null);
40 const [playing, setPlaying] = useState(false);
41 const revision = props.revision ?? null;
42 // Changed files load once playback pauses.
43 if (loadedSource !== null && loadedSource.revision !== revision && !playing) {
44 setLoadedSource(revision === null ? null : { src: props.src, revision });
45 }
46 const src = loadedSource?.src ?? props.src;
47 return (
48 <div className="flex min-h-0 flex-1 items-center justify-center p-6">
49 <audio
50 ref={audioRef}
51 controls
52 preload="metadata"
53 src={src}
54 aria-label={props.name}
55 className="w-full max-w-xl"
56 onLoadedMetadata={() => {
57 if (revision !== null && loadedSource === null) setLoadedSource({ src, revision });
58 }}
59 onPlay={() => setPlaying(true)}
60 onPause={() => setPlaying(false)}
61 onEnded={() => setPlaying(false)}
62 onError={() => {
63 setPlaying(false);
64 setLoadedSource(null);
65 if (src === props.src) props.onError?.();
66 }}
67 />
68 </div>
69 );
70 }
71
72 function audioTime(seconds: number) {
73 return `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, "0")}`;
74 }
75
76 function AudioChip(props: AudioPreviewProps) {
77 const gt = useGT();
78 const audio = useRef<HTMLAudioElement | null>(null);
79 const onUnmount = useContext(AudioPreviewUnmountContext);
80 const [loadedSource, setLoadedSource] = useState<string | null>(null);
81 const src = loadedSource ?? props.src;
82 const [playing, setPlaying] = useState(false);
83 const [ready, setReady] = useState(false);
84 const [duration, setDuration] = useState(0);
85 const [elapsed, setElapsed] = useState(0);
86 const audioRef = useStableCallback((element: HTMLAudioElement | null) => {
87 audio.current = element;
88 if (element)
89 return () => {
90 element.pause();
91 onUnmount?.(element);
92 audio.current = null;
93 };
94 });
95 const loading = !props.failed && !ready;
96 const open = props.onOpen ?? (props.failed ? props.onRetry : undefined);
97 const actionLabel = props.failed
98 ? props.onOpen
99 ? gt("Audio unavailable. Open {name}", { name: props.name })
100 : gt("Audio unavailable. Retry {name}", { name: props.name })
101 : loading
102 ? gt("Loading {name}", { name: props.name })
103 : playing
104 ? gt("Pause {name}", { name: props.name })
105 : gt("Play {name}", { name: props.name });
106 const Icon = props.failed
107 ? TriangleAlertIcon
108 : loading
109 ? LoaderCircleIcon
110 : playing
111 ? PauseIcon
112 : PlayIcon;
113
114 return (
115 <ContextChip
116 kind="file"
117 {...(props.failed ? { state: "invalid" as const } : {})}
118 {...(props.variant === "bubble" ? { shape: "bubble" as const } : {})}
119 className="relative isolate overflow-hidden"
120 title={props.failed ? gt("Audio unavailable. Open the file or retry playback.") : props.name}
121 >
122 <span
123 aria-hidden
124 className="pointer-events-none absolute inset-y-0 left-0 -z-10 bg-(--context-chip-accent)/17"
125 style={{ width: `${duration > 0 ? Math.min(100, (elapsed / duration) * 100) : 0}%` }}
126 />
127 <ContextChipAction
128 className="ml-0 [&_svg]:size-[1em]"
129 aria-label={actionLabel}
130 disabled={loading}
131 onClick={() => {
132 if (props.failed) {
133 open?.();
134 return;
135 }
136 const element = audio.current;
137 if (!element) return;
138 if (!element.paused) element.pause();
139 else
140 void element.play().catch((error: unknown) => {
141 if (!(error instanceof DOMException && error.name === "AbortError"))
142 props.onError?.();
143 });
144 }}
145 >
146 {loading && props.src ? <Spinner aria-hidden /> : <Icon aria-hidden />}
147 </ContextChipAction>
148 <ContextChipLabel className={props.variant === "bubble" ? "flex-1" : "max-w-72"}>
149 {open ? (
150 <button
151 type="button"
152 className="block max-w-full cursor-pointer truncate rounded-sm text-left focus-visible:outline-2 focus-visible:outline-foreground"
153 onClick={open}
154 aria-label={
155 props.failed && !props.onOpen
156 ? gt("Retry {name}", { name: props.name })
157 : gt("Preview {name}", { name: props.name })
158 }
159 >
160 {middleTruncateAttachmentName(props.name)}
161 </button>
162 ) : (
163 middleTruncateAttachmentName(props.name)
164 )}
165 </ContextChipLabel>
166 <span dir="ltr" className="shrink-0 self-baseline text-3xs text-current">
167 {props.failed
168 ? gt("Unavailable")
169 : loading
170 ? "..."
171 : duration > 0
172 ? elapsed > 0 || playing
173 ? `${audioTime(elapsed)} / ${audioTime(duration)}`
174 : audioTime(duration)
175 : audioTime(elapsed)}
176 </span>
177 {props.src && !props.failed ? (
178 <audio
179 ref={audioRef}
180 hidden
181 preload="metadata"
182 src={src}
183 aria-label={props.name}
184 onLoadedMetadata={(event) => {
185 setLoadedSource(src);
186 setReady(true);
187 const value = event.currentTarget.duration;
188 setDuration(Number.isFinite(value) ? value : 0);
189 }}
190 onLoadedData={() => setReady(true)}
191 onCanPlay={() => setReady(true)}
192 onDurationChange={(event) => {
193 const value = event.currentTarget.duration;
194 setDuration(Number.isFinite(value) ? value : 0);
195 }}
196 onTimeUpdate={(event) => setElapsed(event.currentTarget.currentTime)}
197 onPlay={() => setPlaying(true)}
198 onPause={() => setPlaying(false)}
199 onEnded={() => setPlaying(false)}
200 onError={() => {
201 if (src === props.src) props.onError?.();
202 else {
203 setPlaying(false);
204 setReady(false);
205 setLoadedSource(null);
206 }
207 }}
208 />
209 ) : null}
210 </ContextChip>
211 );
212 }