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

AudioPreview.tsx

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