Open History to see the last commit
1import type { ClientSettings } from "@t3tools/contracts/settings";
2
3import completionUrl from "./assets/notification-completion.mp3";
4import inputUrl from "./assets/notification-input.mp3";
5
6type NotificationMode = ClientSettings["notificationMode"];
7export const NOTIFICATION_MODE_LABELS = {
8 off: "Off",
9 notifications: "Notifications only",
10 sound: "Sound only",
11 "notifications-and-sound": "Notifications with sound",
12} satisfies Record<NotificationMode, string>;
13
14export function hasNotificationSound(mode: NotificationMode) {
15 return mode === "sound" || mode === "notifications-and-sound";
16}
17
18export function hasDesktopNotifications(mode: NotificationMode) {
19 return mode === "notifications" || mode === "notifications-and-sound";
20}
21
22let audioContext: AudioContext | undefined;
23const buffers = new Map<string, Promise<AudioBuffer>>();
24
25/** Called from a gesture so browsers allow later background playback. */
26export function unlockNotificationAudio() {
27 audioContext ??= new AudioContext();
28 void audioContext.resume().catch(() => undefined);
29}
30
31export async function playNotificationSound(
32 kind: "completion" | "input",
33 shouldPlay: () => boolean,
34) {
35 if (!audioContext || audioContext.state !== "running") return;
36 const context = audioContext;
37 const url = kind === "completion" ? completionUrl : inputUrl;
38 try {
39 let buffer = buffers.get(url);
40 if (!buffer) {
41 buffer = fetch(url)
42 .then((response) => response.arrayBuffer())
43 .then((data) => context.decodeAudioData(data));
44 buffers.set(url, buffer);
45 }
46 const decoded = await buffer;
47 if (!shouldPlay() || context.state !== "running") return;
48 const source = context.createBufferSource();
49 source.buffer = decoded;
50 source.connect(context.destination);
51 source.start();
52 } catch {
53 buffers.delete(url);
54 }
55}