32 lines
1.9 KiB
TypeScript
32 lines
1.9 KiB
TypeScript
// Shortcut labels for the platform: "Ctrl+Shift+P" on Windows and Linux, "⇧⌘P" on macOS.
|
|
|
|
/** One key combination. `mod` is Ctrl, or Cmd on macOS. `ctrl` is the Ctrl key on every platform. */
|
|
export type Shortcut = { key: string; mod?: boolean; ctrl?: boolean; shift?: boolean; alt?: boolean };
|
|
|
|
export function isMac(): boolean {
|
|
if (typeof navigator === 'undefined') return false;
|
|
const platform = (navigator as Navigator & { userAgentData?: { platform?: string } }).userAgentData?.platform || navigator.platform || '';
|
|
return /mac|iphone|ipad/i.test(platform);
|
|
}
|
|
|
|
/** Key names as [Windows and Linux, macOS]. */
|
|
const NAMES: Record<string, [string, string]> = {
|
|
Escape: ['Esc', '⎋'], Enter: ['Enter', '↩'], Tab: ['Tab', '⇥'], Backspace: ['Backspace', '⌫'], Delete: ['Delete', '⌦'],
|
|
ArrowUp: ['Up', '↑'], ArrowDown: ['Down', '↓'], ArrowLeft: ['Left', '←'], ArrowRight: ['Right', '→'], ' ': ['Space', 'Space'],
|
|
};
|
|
|
|
export function shortcutLabel(shortcut: Shortcut, mac = isMac()): string {
|
|
const name = NAMES[shortcut.key]?.[mac ? 1 : 0] ?? (shortcut.key.length === 1 ? shortcut.key.toUpperCase() : shortcut.key);
|
|
// macOS orders the symbols Control, Option, Shift, Command. Windows orders Ctrl, Alt, Shift.
|
|
if (mac) return `${shortcut.ctrl ? '⌃' : ''}${shortcut.alt ? '⌥' : ''}${shortcut.shift ? '⇧' : ''}${shortcut.mod ? '⌘' : ''}${name}`;
|
|
return [shortcut.mod || shortcut.ctrl ? 'Ctrl' : '', shortcut.alt ? 'Alt' : '', shortcut.shift ? 'Shift' : '', name].filter(Boolean).join('+');
|
|
}
|
|
|
|
/** The label of a written combination, such as "Mod+Shift+Z". */
|
|
export function keys(text: string, mac = isMac()): string {
|
|
const parts = text.split('+');
|
|
const key = parts.pop() || '+';
|
|
const modifiers = new Set(parts.map(part => part.toLowerCase()));
|
|
return shortcutLabel({ key, mod: modifiers.has('mod'), ctrl: modifiers.has('ctrl'), shift: modifiers.has('shift'), alt: modifiers.has('alt') }, mac);
|
|
}
|