UNPKG

@tanstack/hotkeys

Version:

Type-safe, framework-agnostic keyboard hotkey management for the browser

177 lines (175 loc) • 8.92 kB
import { resolveHotkeys } from "./_alternates.js"; import { assertLogicalKey, chordHasKey, modifierAlias, physicalCodeOf, splitChordParts } from "./_chord.js"; import { CODE_ONLY_NAMES, INTL_KEY_LABELS, NUMPAD_KEY_VALUES } from "./_constants.js"; import { codeToLogicalKey } from "./_keyboard-event.js"; import { ownValue } from "./_keys.js"; import { warnServerPlatform } from "./_server.js"; import { MODIFIER_ORDER, normalizeKeyName } from "./constants.js"; import { KEY_DISPLAY_SYMBOLS, LINUX_MODIFIER_LABELS, MAC_MODIFIER_LABELS, MAC_MODIFIER_SYMBOLS, PUNCTUATION_KEY_DISPLAY_LABELS, WINDOWS_MODIFIER_LABELS } from "./display-labels.js"; import { normalizeHotkey, parseHotkey } from "./parse.js"; import { detectPlatform, isPlatformHotkeys } from "./platform.js"; // src/format.ts function formatHotkey(parsed) { return Array.isArray(parsed) ? parsed.map((step) => formatParsedChord(step)) : formatParsedChord(parsed); } function formatParsedChord(parsed) { if (parsed.code === void 0) assertLogicalKey(parsed.key); const parts = []; for (const modifier of MODIFIER_ORDER) if (parsed.modifiers.includes(modifier)) parts.push(modifier); parts.push(parsed.code !== void 0 ? `[${parsed.code}]` : parsed.key); return parts.join("+"); } function formatForDisplay(hotkey, options = {}) { if (isPlatformHotkeys(hotkey)) { const hotkeys = resolveHotkeys(hotkey, options.platform ?? detectDisplayPlatform()); const separator = options.alternatesSeparator; if (options.parts || separator === void 0 || hotkeys.length < 2) return hotkeys[0] ? formatForDisplay(hotkeys[0], options) : options.parts ? [] : ""; return isolateLabel(hotkeys.map((entry) => formatForDisplay(entry, options)).join(isolateLabel(separator, options)), options); } if (Array.isArray(hotkey)) { const steps = hotkey.map((step) => formatChordParts(step, options)); if (options.parts) return steps; const labels = steps.map((parts) => parts.join(chordSeparator(options))); const separator = options.sequenceSeparator ?? " "; return isolateLabel(labels.length > 1 ? labels.map((label) => isolateLabel(label, options)).join(isolateLabel(separator, options)) : labels.join(separator), options); } const parts = formatChordParts(hotkey, options); return options.parts ? parts : isolateLabel(parts.join(chordSeparator(options)), options); } /** * Wraps a label in U+2066 LEFT-TO-RIGHT ISOLATE and U+2069 POP DIRECTIONAL * ISOLATE when `isolate` is set, so right-to-left text around the label * can't reorder its keys or mirror its brackets. */ function isolateLabel(label, options) { return options.isolate && label ? `\u2066${label}\u2069` : label; } /** Detects the platform for a label, warning in development on a server. */ function detectDisplayPlatform() { warnServerPlatform(); return detectPlatform(); } function modifierSymbolsEnabled(options) { const symbols = options.useSymbols ?? true; return typeof symbols === "boolean" ? symbols : symbols.modifiers ?? true; } function chordSeparator(options) { const platform = options.platform ?? detectDisplayPlatform(); return options.separatorToken ?? (platform === "mac" && modifierSymbolsEnabled(options) ? " " : "+"); } function formatChordParts(hotkey, options) { const platform = options.platform ?? detectDisplayPlatform(); const symbols = options.useSymbols ?? true; const modifierSymbols = modifierSymbolsEnabled(options); const keySymbols = typeof symbols === "boolean" ? symbols : symbols.keys ?? true; const normalized = normalizeHotkey(hotkey, platform); const segments = splitChordParts(normalized); const modifierIndex = (segment) => { const index = MODIFIER_ORDER.indexOf(segment === "Mod" ? platform === "mac" ? "Meta" : "Control" : segment); return index === -1 ? MODIFIER_ORDER.length : index; }; segments.sort((a, b) => modifierIndex(a) - modifierIndex(b)); return segments.map((segment) => formatKey(segment, platform, modifierSymbols, keySymbols, options)); } /** * The key a layout map gives for a physical code, or undefined for a missing * or empty entry. Layout entries are what the key types, so their case and * whitespace names are normalized like event keys. */ function layoutKey(code, layoutMap) { const mapped = layoutMap?.get(code); return mapped ? normalizeKeyName(mapped) : void 0; } function formatKey(segment, platform, modifierSymbols, keySymbols, options) { const modifier = modifierAlias(segment); if (modifier) return platform === "mac" ? modifierSymbols ? MAC_MODIFIER_SYMBOLS[modifier] : MAC_MODIFIER_LABELS[modifier] : platform === "windows" ? WINDOWS_MODIFIER_LABELS[modifier] : LINUX_MODIFIER_LABELS[modifier]; const code = physicalCodeOf(segment); const label = ownValue(options.keyLabels, code ?? segment); if (label !== void 0) return label; const numpad = code?.startsWith("Numpad") ?? false; let displayKey = code ?? segment; const mappedKey = code ? layoutKey(code, options.layoutMap) : void 0; if (mappedKey) displayKey = mappedKey; else if (code) { const intl = ownValue(INTL_KEY_LABELS, code); if (intl !== void 0) return intl; displayKey = numpad ? code.slice(6) : codeToLogicalKey(code) ?? code; } const display = ownValue(keySymbols ? KEY_DISPLAY_SYMBOLS : PUNCTUATION_KEY_DISPLAY_LABELS, displayKey) ?? displayKey; return numpad ? `Numpad ${display.replace(/([a-z])([A-Z])/g, "$1 $2")}` : display; } /** * A key as `aria-keyshortcuts` names it, or undefined when it has no name * there. The spec spells the plus key `Plus` and the space bar `Space`, * because `+` and spaces separate its tokens. */ function ariaKeyName(key) { const name = normalizeKeyName(key); if (name === "+") return "Plus"; return name && !/\s/.test(name) ? name : void 0; } /** The key a physical code presses, for `aria-keyshortcuts`. */ function ariaCodeName(code, layoutMap) { const key = layoutKey(code, layoutMap) ?? ownValue(INTL_KEY_LABELS, code) ?? codeToLogicalKey(code) ?? ownValue(NUMPAD_KEY_VALUES, code) ?? (CODE_ONLY_NAMES.test(code) ? void 0 : code); return key === void 0 ? void 0 : ariaKeyName(key); } /** * Formats a hotkey for an `aria-keyshortcuts` attribute so screen readers can * announce the shortcut. `Mod+K` becomes `Meta+K` on macOS and `Control+K` * elsewhere. * * Modifiers use the ARIA names (`Control`, `Alt`, `Shift`, `Meta`) and come * before the key. Keys use `KeyboardEvent.key` values, such as `K`, `/`, * `Escape`, or `ArrowUp`, with `Space` for the space bar and `Plus` for the * plus key. A physical binding names the key at that position, so `[KeyQ]` * becomes `Q`, or the key from `layoutMap` such as `A` on a French AZERTY * keyboard. Logical punctuation stays as written, so `'?'` stays `?` even * where it takes Shift to type. * * Returns `undefined` when the hotkey has no ARIA form, so the attribute is * omitted. This applies to empty or `null` hotkeys, multi-step sequences, * standalone modifiers, and physical codes with no key value such as * `[NumpadMemoryAdd]`. A one-step sequence formats like its chord. * * A hotkey object with `alternates` lists every chord for the platform, * separated by spaces, which is how the attribute names more than one * shortcut. Its sequences are left out. For two unrelated shortcuts on one * control, join both formatted values with a space. * In a server-rendered app, use your adapter's formatter or pass `platform`. * Without a `platform` option, `formatForAria` uses `'linux'` on the server, * like `formatForDisplay`. * * @param input - A hotkey string, raw object, parsed chord, hotkey object, or nothing * @param options - The platform and keyboard layout * @returns The attribute value, or `undefined` when there is none * * @example * ```ts * formatForAria('Mod+K', { platform: 'mac' }) // 'Meta+K' * formatForAria('Mod+Shift+P', { platform: 'windows' }) // 'Control+Shift+P' * formatForAria('Shift+Space') // 'Shift+Space' * formatForAria(['G', 'H']) // undefined * formatForAria({ default: 'Mod+Y', alternates: ['Mod+Shift+Z'] }, { platform: 'windows' }) * // 'Control+Y Control+Shift+Z' * ``` */ function formatForAria(input, options = {}) { if (!input) return void 0; const platform = options.platform ?? detectDisplayPlatform(); const hotkeys = isPlatformHotkeys(input) ? resolveHotkeys(input, platform) : [input]; const shortcuts = /* @__PURE__ */ new Set(); for (const hotkey of hotkeys) { let chord; if (Array.isArray(hotkey)) { if (hotkey.length !== 1) continue; chord = hotkey[0]; } else chord = hotkey; const parsed = parseHotkey(chord, platform); if (!chordHasKey(parsed)) continue; const key = parsed.code !== void 0 ? ariaCodeName(parsed.code, options.layoutMap) : ariaKeyName(parsed.key); if (key === void 0) continue; shortcuts.add([...MODIFIER_ORDER.filter((modifier) => parsed.modifiers.includes(modifier)), key].join("+")); } return shortcuts.size > 0 ? [...shortcuts].join(" ") : void 0; } export { formatForAria, formatForDisplay, formatHotkey };