@tanstack/hotkeys
Version:
Type-safe, framework-agnostic keyboard hotkey management for the browser
148 lines (146 loc) • 7.26 kB
JavaScript
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 } 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 (Array.isArray(hotkey)) {
const steps = hotkey.map((step) => formatChordParts(step, options));
return options.parts ? steps : steps.map((parts) => parts.join(chordSeparator(options))).join(options.sequenceSeparator ?? " ");
}
const parts = formatChordParts(hotkey, options);
return options.parts ? parts : parts.join(chordSeparator(options));
}
/** 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.
*
* For a control with two shortcuts, 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 hotkey - A hotkey string, raw object, parsed chord, 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
* ```
*/
function formatForAria(hotkey, options = {}) {
if (!hotkey) return void 0;
let chord;
if (Array.isArray(hotkey)) {
if (hotkey.length !== 1) return void 0;
chord = hotkey[0];
} else chord = hotkey;
const parsed = parseHotkey(chord, options.platform ?? detectDisplayPlatform());
if (!chordHasKey(parsed)) return void 0;
const key = parsed.code !== void 0 ? ariaCodeName(parsed.code, options.layoutMap) : ariaKeyName(parsed.key);
if (key === void 0) return void 0;
return [...MODIFIER_ORDER.filter((modifier) => parsed.modifiers.includes(modifier)), key].join("+");
}
export { formatForAria, formatForDisplay, formatHotkey };