Open History to see the last commit
1import { useSyncExternalStore } from "react";
2
3const emptyLocales: readonly string[] = [];
4let locales = emptyLocales;
5let probe: Promise<void> | undefined;
6const listeners = new Set<() => void>();
7
8export function readAppleSpeechLocales() {
9 return locales;
10}
11
12export function supportsAppleSpeechLocale(available: readonly string[], locale: string) {
13 const language = locale.toLowerCase().split("-")[0];
14 return available.some((candidate) => candidate.toLowerCase().split("-")[0] === language);
15}
16
17export function resolveAppleSpeechLocale(
18 available: readonly string[],
19 preference: string,
20 system: readonly string[],
21) {
22 if (supportsAppleSpeechLocale(available, preference)) return preference;
23 return system.find((locale) => supportsAppleSpeechLocale(available, locale)) ?? system[0];
24}
25
26function probeLocales() {
27 if (locales.length === 0 && !probe && window.desktopBridge?.appleSpeech) {
28 probe = window.desktopBridge.appleSpeech
29 .supportedLocales()
30 .then((value) => {
31 if (value.length === 0) return;
32 locales = value;
33 listeners.forEach((notify) => notify());
34 })
35 .catch(() => {})
36 .finally(() => {
37 probe = undefined;
38 });
39 }
40}
41
42function subscribe(listener: () => void) {
43 if (listeners.size === 0) window.addEventListener("focus", probeLocales);
44 listeners.add(listener);
45 probeLocales();
46 return () => {
47 listeners.delete(listener);
48 if (listeners.size === 0) window.removeEventListener("focus", probeLocales);
49 };
50}
51
52/** Apple Speech runs only in the desktop app on macOS 26 or later. */
53export function useAppleSpeechLocales() {
54 return useSyncExternalStore(subscribe, readAppleSpeechLocales, () => emptyLocales);
55}