Open History to see the last commit
1import type { ShortcutKeyboardLayoutMap } from "@t3tools/shared/keybindings";
2
3interface KeyboardLayoutSource extends Partial<
4 Pick<EventTarget, "addEventListener" | "removeEventListener">
5> {
6 getLayoutMap(): Promise<ShortcutKeyboardLayoutMap>;
7}
8
9let keyboardLayoutMap: ShortcutKeyboardLayoutMap | undefined;
10
11export function getKeyboardLayoutMap() {
12 return keyboardLayoutMap;
13}
14
15// Option changes event.key to a symbol on macOS; the layout map recovers the
16// letter printed on that key without assuming a US physical layout.
17export function trackKeyboardLayout(
18 keyboard = (navigator as Navigator & { keyboard?: KeyboardLayoutSource }).keyboard,
19 focusTarget: EventTarget | undefined = typeof window === "undefined" ? undefined : window,
20) {
21 let revision = 0;
22 const refresh = async (clearMap: boolean) => {
23 const request = ++revision;
24 if (clearMap) keyboardLayoutMap = undefined;
25 try {
26 const layout = await keyboard?.getLayoutMap();
27 if (request === revision) keyboardLayoutMap = layout;
28 } catch {
29 // Unsupported or permission-blocked browsers keep the existing fallback.
30 if (request === revision) keyboardLayoutMap = undefined;
31 }
32 };
33 const onLayoutChange = () => void refresh(true);
34 const onFocus = () => void refresh(false);
35 void refresh(true);
36 keyboard?.addEventListener?.("layoutchange", onLayoutChange);
37 focusTarget?.addEventListener("focus", onFocus);
38 return () => {
39 revision++;
40 keyboardLayoutMap = undefined;
41 keyboard?.removeEventListener?.("layoutchange", onLayoutChange);
42 focusTarget?.removeEventListener("focus", onFocus);
43 };
44}