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