@tanstack/hotkeys
Version:
Type-safe, framework-agnostic keyboard hotkey management for the browser
223 lines • 10.4 kB
TypeScript
import { ParsedHotkeyChord, PlatformHotkeys, RegisterableHotkeyChord, RegisterableHotkeySequence } from "./hotkey.types.js";
import { ResolvableModifier } from "./key.types.js";
import { HotkeyPlatform } from "./platform.js";
/**
* Converts a parsed hotkey back to a string, with each platform modifier
* spelled out, such as `Control+Shift+S`. A parsed chord returns a string, and
* a parsed sequence returns one string per step. To get `Mod` back where the
* platform allows it, use `normalizeHotkey` instead.
*
* @param parsed - A parsed chord, or the parsed steps of a sequence
*
* @example
* ```ts
* formatHotkey(parseHotkey('Mod+Shift+S', 'windows')) // 'Control+Shift+S'
* formatHotkey(parseHotkey(['G', 'Mod+K'], 'mac')) // ['G', 'Meta+K']
* ```
*/
export declare function formatHotkey(parsed: ParsedHotkeyChord): string;
export declare function formatHotkey(parsed: ReadonlyArray<ParsedHotkeyChord>): Array<string>;
export declare function formatHotkey(parsed: ParsedHotkeyChord | ReadonlyArray<ParsedHotkeyChord>): string | Array<string>;
/**
* A single chord to display: a hotkey string, which includes single keys, a
* modifier on its own (including `Mod`, which resolves per platform), a raw
* object such as `{ key }`, or a parsed hotkey.
*/
export type DisplayHotkeyChord = RegisterableHotkeyChord | ParsedHotkeyChord | ResolvableModifier;
/**
* A hotkey to display: a chord, a sequence of chords, or a hotkey per
* platform, which displays its entry for the platform.
*/
export type DisplayHotkey = DisplayHotkeyChord | ReadonlyArray<DisplayHotkeyChord> | PlatformHotkeys;
/**
* Formats a hotkey for display in a user interface.
*
* In a server-rendered app, format labels with your adapter's formatter,
* such as `useFormatForDisplay`, or pass `platform`. Called directly,
* `formatForDisplay` never reads a provider's `platform`. Without a
* `platform` option, it renders Linux labels on the server, so Mac users get
* a different label after hydration.
*
* On macOS, uses symbols (⇧⌘S) in Control, Option, Shift, Command order.
* Display ordering does not change the normalized hotkey used for registration.
* On Windows/Linux, uses text (Ctrl+Shift+S) with `+` separators.
* The separator can be customized with `separatorToken`.
* Physical codes use conventional display labels: `[KeyS]` becomes `S` and
* `[Digit2]` becomes `2`. Keys with no US key use their keycap legends:
* `[IntlBackslash]` and `[IntlRo]` become `\` and `[IntlYen]` becomes `¥`.
* These labels do not infer the active keyboard layout or change matching.
* Supply a resolved `layoutMap` for layout-aware labels; `keyLabels`
* overrides both layout entries and fallback labels.
* Sequence steps are formatted individually and joined with `sequenceSeparator`
* (a space by default).
* A hotkey object formats as its first hotkey for the platform, or as its
* first alternate where the platform has only alternates. With
* `alternatesSeparator`, it formats every hotkey for the platform.
*
* On a right-to-left page, the browser can display a label in reverse order.
* Set `dir="ltr"` on the label's element, or pass `isolate` where the label
* is part of a longer string.
*
* A key reported by a `KeyboardEvent`, such as a held key from
* `KeyStateTracker`, can be outside the key types: pass it as `{ key }`.
*
* @param hotkey - A logical or physical hotkey string, raw object, ParsedHotkeyChord, sequence, or hotkey object
* @param options - Formatting options
* @returns Display text, or individual key labels when parts is true (one array per step for sequences)
*
* @example
* ```ts
* formatForDisplay('Mod+Shift+S', { platform: 'mac' })
* // Returns: '⇧ ⌘ S' (symbols separated by spaces on macOS)
*
* formatForDisplay('Mod+Shift+S', { platform: 'windows' })
* // Returns: 'Ctrl+Shift+S'
*
* formatForDisplay('Escape')
* // Returns: 'Esc' (on all platforms)
*
* formatForDisplay('Shift', { platform: 'mac' })
* // Returns: '⇧'
*
* formatForDisplay({ key: heldKey })
* // A key from a KeyboardEvent, such as a held key
*
* formatForDisplay(['G', 'H'])
* // Returns: 'G H'
*
* formatForDisplay(
* { default: 'Mod+Y', alternates: ['Mod+Shift+Z'] },
* { platform: 'windows', alternatesSeparator: ' or ' },
* )
* // Returns: 'Ctrl+Y or Ctrl+Shift+Z'
*
* formatForDisplay('Mod+[', { platform: 'windows', isolate: true })
* // Returns: 'Ctrl+[' between U+2066 and U+2069
* ```
*/
export declare function formatForDisplay(hotkey: ReadonlyArray<DisplayHotkeyChord>, options: FormatDisplayOptions & {
parts: true;
}): Array<Array<string>>;
export declare function formatForDisplay(hotkey: DisplayHotkeyChord, options: FormatDisplayOptions & {
parts: true;
}): Array<string>;
export declare function formatForDisplay(hotkey: PlatformHotkeys<RegisterableHotkeyChord>, options: FormatDisplayOptions & {
parts: true;
}): Array<string>;
export declare function formatForDisplay(hotkey: PlatformHotkeys<RegisterableHotkeySequence>, options: FormatDisplayOptions & {
parts: true;
}): Array<Array<string>>;
export declare function formatForDisplay(hotkey: PlatformHotkeys, options: FormatDisplayOptions & {
parts: true;
}): Array<string> | Array<Array<string>>;
export declare function formatForDisplay(hotkey: DisplayHotkey, options?: FormatDisplayOptions & {
parts?: false;
}): string;
export declare function formatForDisplay(hotkey: DisplayHotkey, options: FormatDisplayOptions): string | Array<string> | Array<Array<string>>;
/**
* Options for formatting hotkeys for display.
*/
export interface FormatDisplayOptions {
/**
* The target platform. Without it, `formatForDisplay` detects the platform
* in the browser and uses `'linux'` on a server.
*/
platform?: HotkeyPlatform;
/** Whether to use symbols for the display. Defaults to true. */
useSymbols?: boolean | {
modifiers?: boolean;
keys?: boolean;
};
/** Return individual key labels instead of a joined string. Default: false. */
parts?: boolean;
/**
* An already-resolved code-to-key map, such as KeyboardLayoutMap or Map.
* Used only for physical bindings. Mapped keys receive normal display formatting;
* missing or empty entries use conventional fallback labels. The caller owns
* loading and refreshing the map; this formatter never calls browser APIs.
*/
layoutMap?: {
get: (code: string) => string | undefined;
};
/** Final display overrides for logical keys or physical codes; take precedence over layoutMap. Never changes matching. */
keyLabels?: Readonly<Record<string, string>>;
/** Override the separator between display tokens. Defaults to platform-specific formatting when null/undefined. */
separatorToken?: string | null;
/** Separator between sequence steps. Default: a space. */
sequenceSeparator?: string;
/**
* Separator between the hotkeys of a hotkey object with `alternates`, such
* as `' or '`. With it, the label lists every hotkey for the platform.
* Without it, the label shows the first one. Has no effect with
* `parts: true`.
*/
alternatesSeparator?: string;
/**
* Wrap the label in the invisible Unicode characters U+2066 and U+2069,
* which keep its keys in left-to-right order inside right-to-left text.
* Each step of a sequence and each separator between steps is wrapped
* too. Use it on a right-to-left page
* where the label is part of a longer string, such as a `placeholder` or
* the text of an `<option>`. Where the label has its own element, set
* `dir="ltr"` on that element instead. Has no effect with `parts: true`.
* Default: false.
*/
isolate?: boolean;
}
/** Options for formatting a hotkey for `aria-keyshortcuts`. */
export interface FormatAriaOptions {
/**
* The target platform, for resolving `Mod`. Without it, `formatForAria`
* detects the platform in the browser and uses `'linux'` on a server.
*/
platform?: HotkeyPlatform;
/**
* An already-resolved code-to-key map, such as KeyboardLayoutMap or Map.
* Used only for physical bindings, to name the key the user presses.
* Missing or empty entries use the key at that position on a US keyboard.
*/
layoutMap?: {
get: (code: string) => string | undefined;
};
}
/**
* 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'
* ```
*/
export declare function formatForAria(input: DisplayHotkey | null | undefined, options?: FormatAriaOptions): string | undefined;