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