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

AudioPreview.tsx

205 lines7.0 KB

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