@tanstack/svelte-hotkeys 0.22.1 → 0.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- import type { AppHotkeys, AppHotkeysStore, CustomHotkeys, HotkeyChordRecorderOptions, HotkeyPlatform, HotkeySequenceRecorderOptions } from '@tanstack/hotkeys';
2
- import type { HotkeysProviderScopeProps } from '@tanstack/hotkeys/adapter';
1
+ import type { AppHotkeys, CustomHotkeys, HotkeyPlatform } from '@tanstack/hotkeys';
2
+ import type { HotkeyRecorderDefaults, HotkeysContextValue, HotkeysProviderScopeProps } from '@tanstack/hotkeys/adapter';
3
3
  import type { Snippet } from 'svelte';
4
4
  import type { CreateHotkeyCommonOptions } from './createHotkey.svelte.js';
5
5
  export interface HotkeysProviderOptions {
@@ -9,13 +9,21 @@ export interface HotkeysProviderOptions {
9
9
  * from the request with `detectPlatform(userAgent)`.
10
10
  */
11
11
  platform?: HotkeyPlatform;
12
+ /**
13
+ * Whether labels from `getFormatForDisplay` follow the user's keyboard
14
+ * layout, so `[KeyQ]` reads `A` on a French AZERTY keyboard. The layout
15
+ * loads from the browser when the first label mounts. Only Chromium
16
+ * browsers report one. Set `false` to never ask the browser for it.
17
+ * Default: `true`.
18
+ */
19
+ keyboardLayout?: boolean;
12
20
  /**
13
21
  * Defaults for every hotkey registered by `createHotkey` and `createHotkeys`.
14
22
  * `requireReset` applies to chords and `timeout` applies to sequences.
15
23
  */
16
24
  hotkey?: CreateHotkeyCommonOptions;
17
25
  /** Defaults for every `createHotkeyRecorder`. */
18
- hotkeyRecorder?: Partial<Omit<HotkeyChordRecorderOptions & HotkeySequenceRecorderOptions, 'maxSteps' | 'onRecord' | 'validate'>>;
26
+ hotkeyRecorder?: HotkeyRecorderDefaults;
19
27
  }
20
28
  /** Options for `setHotkeysContext` and props for `HotkeysProvider`. */
21
29
  export interface HotkeysContextOptions extends HotkeysProviderScopeProps {
@@ -41,13 +49,6 @@ export interface HotkeysProviderProps extends HotkeysContextOptions {
41
49
  children: Snippet;
42
50
  }
43
51
  export declare const DEFAULT_OPTIONS: HotkeysProviderOptions;
44
- interface HotkeysContextValue {
45
- readonly appHotkeysStore: AppHotkeysStore | null;
46
- /** Merged with every ancestor's defaults, including `hotkey.scope`. */
47
- readonly defaultOptions: HotkeysProviderOptions;
48
- /** Whether this context and every ancestor are enabled. */
49
- readonly enabled: boolean;
50
- }
51
52
  /**
52
53
  * Sets the hotkeys context for descendants. `HotkeysProvider` calls this; call
53
54
  * it directly in a component's script instead of rendering the provider.
@@ -69,9 +70,8 @@ interface HotkeysContextValue {
69
70
  * </script>
70
71
  * ```
71
72
  */
72
- export declare function setHotkeysContext(options?: HotkeysContextOptions): HotkeysContextValue;
73
+ export declare function setHotkeysContext(options?: HotkeysContextOptions): HotkeysContextValue<HotkeysProviderOptions>;
73
74
  /** Sets the context from a getter, so default options stay reactive. */
74
- export declare function setHotkeysContextSource(source: () => HotkeysContextOptions): HotkeysContextValue;
75
- export declare function getHotkeysContext(): HotkeysContextValue | null;
75
+ export declare function setHotkeysContextSource(source: () => HotkeysContextOptions): HotkeysContextValue<HotkeysProviderOptions>;
76
+ export declare function getHotkeysContext(): HotkeysContextValue<HotkeysProviderOptions> | null;
76
77
  export declare function getDefaultHotkeysOptions(): HotkeysProviderOptions;
77
- export {};
@@ -1,19 +1,5 @@
1
- import type { Hotkey, HotkeyChord, HotkeyChordRecorderOptions, HotkeyRecorderOptions, HotkeySequence, HotkeySequenceRecorderOptions } from '@tanstack/hotkeys';
2
- export interface SvelteHotkeyRecorder<THotkey extends Hotkey = Hotkey> {
3
- /** Whether recording is currently active */
4
- readonly isRecording: boolean;
5
- /** Chords recorded so far in a multi-step recording (for live preview) */
6
- readonly steps: HotkeySequence;
7
- /** The last committed hotkey */
8
- readonly recordedHotkey: THotkey | null;
9
- /** Start recording a new hotkey */
10
- startRecording: () => void;
11
- /** Stop recording without calling onCancel */
12
- stopRecording: () => void;
13
- /** Cancel recording and call onCancel */
14
- cancelRecording: () => void;
15
- /** Commit the recorded steps now (multi-step recordings) */
16
- commitRecording: () => void;
1
+ import type { Hotkey, HotkeyChord, HotkeyChordRecorderOptions, HotkeyRecorderActions, HotkeyRecorderOptions, HotkeyRecorderState, HotkeySequenceRecorderOptions } from '@tanstack/hotkeys';
2
+ export interface SvelteHotkeyRecorder<THotkey extends Hotkey = Hotkey> extends Readonly<HotkeyRecorderState<THotkey>>, HotkeyRecorderActions {
17
3
  }
18
4
  /**
19
5
  * Svelte function for recording keyboard shortcuts. Options may be a getter.
@@ -26,6 +12,7 @@ export interface SvelteHotkeyRecorder<THotkey extends Hotkey = Hotkey> {
26
12
  * @example
27
13
  * ```svelte
28
14
  * <script lang="ts">
15
+ * const formatForDisplay = getFormatForDisplay()
29
16
  * const recorder = createHotkeyRecorder({ onRecord: (hotkey) => (shortcut = hotkey) })
30
17
  * const sequenceRecorder = createHotkeyRecorder({ maxSteps: Infinity, onRecord: save })
31
18
  * </script>
@@ -0,0 +1,11 @@
1
+ import { formatForDisplay as coreFormatForDisplay } from '@tanstack/hotkeys';
2
+ /**
3
+ * Formats a hotkey as a label, without the provider's platform or the user's
4
+ * keyboard layout.
5
+ *
6
+ * @deprecated Use `getFormatForDisplay()` in components. It returns this
7
+ * function with the provider's platform and the user's keyboard layout filled
8
+ * in. Outside a component, keep calling this function and pass `platform`
9
+ * yourself.
10
+ */
11
+ export declare const formatForDisplay: typeof coreFormatForDisplay;
@@ -0,0 +1,11 @@
1
+ import { formatForDisplay as coreFormatForDisplay } from '@tanstack/hotkeys';
2
+ /**
3
+ * Formats a hotkey as a label, without the provider's platform or the user's
4
+ * keyboard layout.
5
+ *
6
+ * @deprecated Use `getFormatForDisplay()` in components. It returns this
7
+ * function with the provider's platform and the user's keyboard layout filled
8
+ * in. Outside a component, keep calling this function and pass `platform`
9
+ * yourself.
10
+ */
11
+ export const formatForDisplay = coreFormatForDisplay;
@@ -1,4 +1,4 @@
1
- import type { AppHotkey, AppHotkeyListItem, CustomHotkeys, Hotkey, RegisteredAppHotkeys } from '@tanstack/hotkeys';
1
+ import type { CustomHotkeyActions, CustomHotkeys, RegisteredAppHotkeyListItem, RegisteredAppHotkeys } from '@tanstack/hotkeys';
2
2
  export interface SvelteAppHotkeys {
3
3
  /** Effective app hotkeys: each declaration with the user's custom hotkey applied. */
4
4
  readonly current: RegisteredAppHotkeys;
@@ -18,7 +18,7 @@ export interface SvelteAppHotkeys {
18
18
  export declare function getAppHotkeys(): SvelteAppHotkeys;
19
19
  export interface SvelteAppHotkeyList {
20
20
  /** Every app hotkey with its live status, in declaration order. */
21
- readonly current: Array<AppHotkeyListItem<RegisteredAppHotkeys[keyof RegisteredAppHotkeys]>>;
21
+ readonly current: Array<RegisteredAppHotkeyListItem>;
22
22
  }
23
23
  /**
24
24
  * Lists every app hotkey with its live status, for cheat sheets and settings
@@ -26,20 +26,9 @@ export interface SvelteAppHotkeyList {
26
26
  * those without a hotkey are `'unbound'`.
27
27
  */
28
28
  export declare function getAppHotkeyList(): SvelteAppHotkeyList;
29
- export interface SvelteCustomHotkeys {
29
+ export interface SvelteCustomHotkeys extends CustomHotkeyActions {
30
30
  /** The user's hotkeys that differ from the defaults. */
31
31
  readonly current: CustomHotkeys;
32
- /**
33
- * Sets the user's hotkey for an app hotkey. `null` unbinds it.
34
- * Returns conflicting app hotkeys; when any exist, nothing changes.
35
- */
36
- setCustomHotkey: (id: keyof RegisteredAppHotkeys & string, hotkey: Hotkey | null) => Array<AppHotkey>;
37
- /** Restores the default hotkey for an app hotkey. */
38
- resetCustomHotkey: (id: keyof RegisteredAppHotkeys & string) => void;
39
- /** Restores every default hotkey. */
40
- resetCustomHotkeys: () => void;
41
- /** Other app hotkeys that would collide if `id` used `hotkey`. */
42
- findConflicts: (id: keyof RegisteredAppHotkeys & string, hotkey: Hotkey) => Array<AppHotkey>;
43
32
  }
44
33
  /**
45
34
  * Reads and changes the user's custom hotkeys. Changes apply to every
@@ -1,17 +1,16 @@
1
+ import { bindCustomHotkeyActions, requireAppHotkeysStore, } from '@tanstack/hotkeys/adapter';
1
2
  import { getHotkeysContext } from './HotkeysCtx.js';
2
3
  import { getHotkeyRegistrations } from './getHotkeyRegistrations.svelte.js';
3
4
  import { createAppHotkeysSource } from './internal.svelte.js';
4
5
  function requireStore(name) {
5
6
  const source = createAppHotkeysSource(getHotkeysContext());
7
+ const message = `${name} requires a HotkeysProvider with appHotkeys`;
6
8
  const initial = source.store;
7
- if (!initial) {
8
- throw new Error(`[hotkeys] ${name} requires a HotkeysProvider with appHotkeys`);
9
- }
9
+ requireAppHotkeysStore(initial, message);
10
10
  return {
11
11
  // The nearest provider's store, which changes if a nested provider gets
12
12
  // its app hotkeys later.
13
- store: () => (source.store ??
14
- initial),
13
+ store: () => requireAppHotkeysStore(source.store ?? initial, message),
15
14
  subscribe: source.subscribe,
16
15
  };
17
16
  }
@@ -63,9 +62,6 @@ export function getCustomHotkeys() {
63
62
  subscribe();
64
63
  return store().customHotkeys;
65
64
  },
66
- setCustomHotkey: (id, hotkey) => store().setCustomHotkey(id, hotkey),
67
- resetCustomHotkey: (id) => store().resetCustomHotkey(id),
68
- resetCustomHotkeys: () => store().resetCustomHotkeys(),
69
- findConflicts: (id, hotkey) => store().findConflicts(id, hotkey),
65
+ ...bindCustomHotkeyActions(store),
70
66
  };
71
67
  }
@@ -1,20 +1,26 @@
1
- import { formatForDisplay } from '@tanstack/hotkeys';
1
+ import type { formatForDisplay } from '@tanstack/hotkeys';
2
2
  /**
3
3
  * Returns `formatForDisplay` with the provider's `platform` as the default,
4
4
  * so labels match the user's platform. Call during component initialization,
5
5
  * like `getContext`; the returned function works anywhere and reads the
6
6
  * provider's current defaults. An explicit `platform` option wins.
7
7
  *
8
+ * Physical bindings such as `[KeyQ]` are labeled with the character the key
9
+ * types for this user in Chromium browsers, once the keyboard layout has
10
+ * loaded, and markup updates when it arrives. See `getKeyboardLayout`. A
11
+ * `layoutMap` passed to the returned function wins. Firefox and Safari report
12
+ * no layout, so labels there keep the key's US character.
13
+ *
8
14
  * Server-rendered apps should set the provider's `defaultOptions.platform`
9
15
  * from the request user agent with `detectPlatform(userAgent)`.
10
16
  *
11
17
  * @example
12
18
  * ```svelte
13
19
  * <script lang="ts">
14
- * const format = getFormatForDisplay()
20
+ * const formatForDisplay = getFormatForDisplay()
15
21
  * </script>
16
22
  *
17
- * <kbd>{format('Mod+S')}</kbd>
23
+ * <kbd>{formatForDisplay('Mod+S')}</kbd>
18
24
  * ```
19
25
  */
20
26
  export declare function getFormatForDisplay(): typeof formatForDisplay;
@@ -1,27 +1,34 @@
1
- import { formatForDisplay } from '@tanstack/hotkeys';
1
+ import { createFormatForDisplay } from '@tanstack/hotkeys/adapter';
2
2
  import { getHotkeysContext } from './HotkeysCtx.js';
3
+ import { getKeyboardLayout } from './getKeyboardLayout.svelte.js';
3
4
  /**
4
5
  * Returns `formatForDisplay` with the provider's `platform` as the default,
5
6
  * so labels match the user's platform. Call during component initialization,
6
7
  * like `getContext`; the returned function works anywhere and reads the
7
8
  * provider's current defaults. An explicit `platform` option wins.
8
9
  *
10
+ * Physical bindings such as `[KeyQ]` are labeled with the character the key
11
+ * types for this user in Chromium browsers, once the keyboard layout has
12
+ * loaded, and markup updates when it arrives. See `getKeyboardLayout`. A
13
+ * `layoutMap` passed to the returned function wins. Firefox and Safari report
14
+ * no layout, so labels there keep the key's US character.
15
+ *
9
16
  * Server-rendered apps should set the provider's `defaultOptions.platform`
10
17
  * from the request user agent with `detectPlatform(userAgent)`.
11
18
  *
12
19
  * @example
13
20
  * ```svelte
14
21
  * <script lang="ts">
15
- * const format = getFormatForDisplay()
22
+ * const formatForDisplay = getFormatForDisplay()
16
23
  * </script>
17
24
  *
18
- * <kbd>{format('Mod+S')}</kbd>
25
+ * <kbd>{formatForDisplay('Mod+S')}</kbd>
19
26
  * ```
20
27
  */
21
28
  export function getFormatForDisplay() {
22
29
  const context = getHotkeysContext();
23
- return ((hotkey, options) => formatForDisplay(hotkey, {
24
- ...options,
25
- platform: options?.platform ?? context?.defaultOptions.platform,
26
- }));
30
+ const keyboard = getKeyboardLayout();
31
+ // Only a position's label reads the layout, so other labels don't render
32
+ // again when it loads.
33
+ return createFormatForDisplay(() => context?.defaultOptions.platform, () => keyboard.layout);
27
34
  }
@@ -1,4 +1,5 @@
1
- import { getHotkeyManager, getKeyStateTracker, isAppHotkey, matchesHeldModifiers, resolveAppHotkey, } from '@tanstack/hotkeys';
1
+ import { getHotkeyManager, getKeyStateTracker } from '@tanstack/hotkeys';
2
+ import { isHotkeyHintVisible } from '@tanstack/hotkeys/adapter';
2
3
  import { createSubscriber } from 'svelte/reactivity';
3
4
  import { getHotkeysContext } from './HotkeysCtx.js';
4
5
  import { resolveMaybeGetter } from './internal.svelte.js';
@@ -18,15 +19,7 @@ export function getHotkeyHint(hotkey, options = {}) {
18
19
  // Read each time: a provider creates its store when its app hotkeys arrive.
19
20
  const getStore = () => context?.appHotkeysStore ?? null;
20
21
  // Resolve current reactive arguments without caching a stale hotkey.
21
- const read = () => {
22
- const value = resolveMaybeGetter(hotkey);
23
- const resolved = isAppHotkey(value)
24
- ? resolveAppHotkey(value, getStore()).hotkey
25
- : value;
26
- return (resolved !== null &&
27
- matchesHeldModifiers(resolved, tracker.store.state.heldKeys, resolveMaybeGetter(options)) &&
28
- manager.hasActiveRegistration(value));
29
- };
22
+ const read = () => isHotkeyHintVisible(resolveMaybeGetter(hotkey), tracker.store.state.heldKeys, resolveMaybeGetter(options), getStore());
30
23
  let previous = false;
31
24
  // Notify Svelte only when visibility changes, not for every unrelated held key.
32
25
  const track = (store) => createSubscriber((update) => {
@@ -1,7 +1,5 @@
1
- import type { HotkeyRegistrationView } from '@tanstack/hotkeys';
2
- export interface SvelteHotkeyRegistrations {
3
- /** Every registration, chords and sequences. Narrow each view with `kind`. */
4
- readonly hotkeys: Array<HotkeyRegistrationView>;
1
+ import type { HotkeyRegistrationsResult } from '@tanstack/hotkeys';
2
+ export interface SvelteHotkeyRegistrations extends HotkeyRegistrationsResult {
5
3
  }
6
4
  /**
7
5
  * Svelte function that returns reactive access to every hotkey registration,
@@ -12,6 +10,7 @@ export interface SvelteHotkeyRegistrations {
12
10
  * @example
13
11
  * ```svelte
14
12
  * <script lang="ts">
13
+ * const formatForDisplay = getFormatForDisplay()
15
14
  * const registrations = getHotkeyRegistrations()
16
15
  * </script>
17
16
  *
@@ -1,11 +1,12 @@
1
- import { getHotkeyManager, toHotkeyRegistrationView } from '@tanstack/hotkeys';
1
+ import { getHotkeyManager } from '@tanstack/hotkeys';
2
+ import { getHotkeyRegistrationViews } from '@tanstack/hotkeys/adapter';
2
3
  import { createStoreSubscriber } from './internal.svelte.js';
3
4
  class HotkeyRegistrationsState {
4
5
  #manager = getHotkeyManager();
5
6
  #subscribe = createStoreSubscriber(this.#manager.registrations);
6
7
  get hotkeys() {
7
8
  this.#subscribe();
8
- return Array.from(this.#manager.registrations.state.values()).map(toHotkeyRegistrationView);
9
+ return getHotkeyRegistrationViews(this.#manager.registrations.state);
9
10
  }
10
11
  }
11
12
  /**
@@ -17,6 +18,7 @@ class HotkeyRegistrationsState {
17
18
  * @example
18
19
  * ```svelte
19
20
  * <script lang="ts">
21
+ * const formatForDisplay = getFormatForDisplay()
20
22
  * const registrations = getHotkeyRegistrations()
21
23
  * </script>
22
24
  *
@@ -0,0 +1,34 @@
1
+ import type { KeyboardLayoutMap } from '@tanstack/hotkeys';
2
+ export interface SvelteKeyboardLayout {
3
+ readonly layout: KeyboardLayoutMap | null;
4
+ }
5
+ /**
6
+ * Svelte function that returns reactive access to the browser's keyboard
7
+ * layout. `layout` is `null` until the layout loads and in browsers that
8
+ * don't report one. The layout maps each physical code to the character it
9
+ * types, such as `KeyQ` to `a` on a French AZERTY keyboard. Only Chromium
10
+ * browsers report one.
11
+ *
12
+ * The layout loads after the first component that uses this function mounts,
13
+ * so server-rendered output hydrates unchanged. `getFormatForDisplay` uses
14
+ * this function, so you only need it for labels you draw yourself.
15
+ *
16
+ * To never ask the browser for the layout, set `keyboardLayout: false` in
17
+ * `HotkeysProvider`'s `defaultOptions`. `layout` then stays `null`.
18
+ *
19
+ * @returns Object with a reactive `layout` property
20
+ *
21
+ * @example
22
+ * ```svelte
23
+ * <script lang="ts">
24
+ * import { getKeyboardLayout } from '@tanstack/svelte-hotkeys'
25
+ *
26
+ * const keyboard = getKeyboardLayout()
27
+ * const label = (code: string) =>
28
+ * (keyboard.layout?.get(code) ?? code).toUpperCase()
29
+ * </script>
30
+ *
31
+ * <kbd>{label('KeyW')}</kbd>
32
+ * ```
33
+ */
34
+ export declare function getKeyboardLayout(): SvelteKeyboardLayout;
@@ -0,0 +1,70 @@
1
+ import { getKeyboardLayoutStore } from '@tanstack/hotkeys';
2
+ import { followKeyboardLayout } from '@tanstack/hotkeys/adapter';
3
+ import { createSubscriber } from 'svelte/reactivity';
4
+ import { getHotkeysContext } from './HotkeysCtx.js';
5
+ class KeyboardLayoutState {
6
+ #context = getHotkeysContext();
7
+ #store = getKeyboardLayoutStore();
8
+ // Loads the layout while an effect or markup reads it. Calls are counted,
9
+ // so every reader can load it.
10
+ #subscribe = createSubscriber((update) => followKeyboardLayout(update));
11
+ // Server HTML never has a layout, so a component that hydrates starts
12
+ // without one, even when the layout has already loaded.
13
+ #mounted = $state(false);
14
+ constructor() {
15
+ try {
16
+ // Effects run after the component mounts, and never on a server.
17
+ $effect(() => {
18
+ this.#mounted = true;
19
+ });
20
+ // Loads the layout even when nothing else reads it reactively.
21
+ $effect(() => {
22
+ void this.layout;
23
+ });
24
+ }
25
+ catch {
26
+ // Outside a component there is no hydration to wait for.
27
+ this.#mounted = true;
28
+ }
29
+ }
30
+ get layout() {
31
+ if (!this.#mounted)
32
+ return null;
33
+ if (this.#context?.defaultOptions.keyboardLayout === false)
34
+ return null;
35
+ this.#subscribe();
36
+ return this.#store.state;
37
+ }
38
+ }
39
+ /**
40
+ * Svelte function that returns reactive access to the browser's keyboard
41
+ * layout. `layout` is `null` until the layout loads and in browsers that
42
+ * don't report one. The layout maps each physical code to the character it
43
+ * types, such as `KeyQ` to `a` on a French AZERTY keyboard. Only Chromium
44
+ * browsers report one.
45
+ *
46
+ * The layout loads after the first component that uses this function mounts,
47
+ * so server-rendered output hydrates unchanged. `getFormatForDisplay` uses
48
+ * this function, so you only need it for labels you draw yourself.
49
+ *
50
+ * To never ask the browser for the layout, set `keyboardLayout: false` in
51
+ * `HotkeysProvider`'s `defaultOptions`. `layout` then stays `null`.
52
+ *
53
+ * @returns Object with a reactive `layout` property
54
+ *
55
+ * @example
56
+ * ```svelte
57
+ * <script lang="ts">
58
+ * import { getKeyboardLayout } from '@tanstack/svelte-hotkeys'
59
+ *
60
+ * const keyboard = getKeyboardLayout()
61
+ * const label = (code: string) =>
62
+ * (keyboard.layout?.get(code) ?? code).toUpperCase()
63
+ * </script>
64
+ *
65
+ * <kbd>{label('KeyW')}</kbd>
66
+ * ```
67
+ */
68
+ export function getKeyboardLayout() {
69
+ return new KeyboardLayoutState();
70
+ }
package/dist/index.d.ts CHANGED
@@ -13,3 +13,5 @@ export { DEFAULT_OPTIONS, getDefaultHotkeysOptions, getHotkeysContext, setHotkey
13
13
  export type { HotkeysContextOptions, HotkeysProviderOptions, HotkeysProviderProps, } from './HotkeysCtx.js';
14
14
  export * from './getHotkeyHint.svelte.js';
15
15
  export * from './getFormatForDisplay.js';
16
+ export { formatForDisplay } from './formatForDisplay.js';
17
+ export * from './getKeyboardLayout.svelte.js';
package/dist/index.js CHANGED
@@ -13,3 +13,6 @@ export { default as HotkeysProvider } from './HotkeysProvider.svelte';
13
13
  export { DEFAULT_OPTIONS, getDefaultHotkeysOptions, getHotkeysContext, setHotkeysContext, } from './HotkeysCtx.js';
14
14
  export * from './getHotkeyHint.svelte.js';
15
15
  export * from './getFormatForDisplay.js';
16
+ // Replaces the core export, to point components to `getFormatForDisplay`
17
+ export { formatForDisplay } from './formatForDisplay.js';
18
+ export * from './getKeyboardLayout.svelte.js';
@@ -1,12 +1,12 @@
1
1
  import type { AppHotkeys, AppHotkeysStore, CustomHotkeys, HotkeyPlatform } from '@tanstack/hotkeys';
2
- export type MaybeGetter<T> = T | (() => T);
2
+ export type { MaybeGetter } from '@tanstack/hotkeys';
3
+ export { resolveMaybeGetter } from '@tanstack/hotkeys/adapter';
3
4
  interface SubscribableStore<TState> {
4
5
  state: TState;
5
6
  subscribe: (listener: () => void) => (() => void) | {
6
7
  unsubscribe: () => void;
7
8
  };
8
9
  }
9
- export declare function resolveMaybeGetter<T>(value: MaybeGetter<T>): T;
10
10
  export declare function createStoreSubscriber<TState>(store: SubscribableStore<TState>): () => void;
11
11
  /**
12
12
  * The nearest provider's app hotkeys store, read from the context each time.
@@ -35,4 +35,3 @@ export declare function syncAppHotkeysStore(getStore: () => AppHotkeysStore | nu
35
35
  * whenever the key from `getHotkeysProviderScopeKey` changes.
36
36
  */
37
37
  export declare function activateScopeWhileMounted(getKey: () => string | null): void;
38
- export {};
@@ -1,9 +1,7 @@
1
1
  import { publishAppHotkeysStore } from '@tanstack/hotkeys';
2
2
  import { activateHotkeysProviderScope } from '@tanstack/hotkeys/adapter';
3
3
  import { createSubscriber } from 'svelte/reactivity';
4
- export function resolveMaybeGetter(value) {
5
- return typeof value === 'function' ? value() : value;
6
- }
4
+ export { resolveMaybeGetter } from '@tanstack/hotkeys/adapter';
7
5
  export function createStoreSubscriber(store) {
8
6
  return createSubscriber((update) => {
9
7
  const subscription = store.subscribe(update);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/svelte-hotkeys",
3
- "version": "0.22.1",
3
+ "version": "0.24.1",
4
4
  "description": "Svelte adapter for TanStack Hotkeys",
5
5
  "author": "Kunal Rao",
6
6
  "license": "MIT",
@@ -41,7 +41,7 @@
41
41
  "skills"
42
42
  ],
43
43
  "dependencies": {
44
- "@tanstack/hotkeys": "0.27.1"
44
+ "@tanstack/hotkeys": "0.30.0"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@sveltejs/package": "^3.0.2",
@@ -49,7 +49,7 @@
49
49
  "@tanstack/hotkeys-test-utils": "0.0.0",
50
50
  "@typescript-eslint/parser": "^8.72.1",
51
51
  "eslint": "^10.14.0",
52
- "eslint-plugin-svelte": "^3.24.0",
52
+ "eslint-plugin-svelte": "^3.24.1",
53
53
  "svelte": "^5.57.3"
54
54
  },
55
55
  "peerDependencies": {
@@ -55,29 +55,29 @@ Before starting, load the `@tanstack/hotkeys#hotkeys-core` skill (`npx @tanstack
55
55
 
56
56
  ## API
57
57
 
58
- | API | What it's for |
59
- | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
60
- | `createHotkey(hotkey, callback, options?)` | Register one chord, sequence, or app hotkey on the document while the component is mounted; pass getters for values that change. |
61
- | `createHotkeys(definitions, commonOptions?)` | Register several hotkeys on the document, or a getter of a list built from data. |
62
- | `createHotkeyAttachment(hotkey, callback, options?)` | Create an attachment for `{@attach}` that listens on one element. |
63
- | `createHotkeysAttachment(definitions, commonOptions?)` | Create an attachment that registers several hotkeys on one element. |
64
- | `<HotkeysProvider>` | Set default options, a scope (`exclusive` for dialogs), `enabled`, and app hotkeys for the components inside it. |
65
- | `setHotkeysContext(options)` | Set the same options from a component's script instead of rendering `HotkeysProvider`; they apply to that component too. |
66
- | `getHotkeysContext()` | Read the nearest context's merged defaults and enabled state, or `null` outside one. |
67
- | `getDefaultHotkeysOptions()` | Read the default options merged from every context above. |
68
- | `getFormatForDisplay()` | Get `formatForDisplay` with the provider's `platform` filled in, for labels in server-rendered apps. Call it during component initialization. |
69
- | `getAppHotkeys()` | Read `.current`, the declared app hotkeys with the user's custom hotkeys applied. |
70
- | `getAppHotkeyList()` | Read `.current`, every app hotkey with its status, for a cheat sheet or settings screen. |
71
- | `getCustomHotkeys()` | Read the user's custom hotkeys from `.current`, change or reset them, and check a new one for conflicts. |
72
- | `createHotkeyRecorder(options)` | Record a chord or sequence the user presses, for a settings screen. |
73
- | `getHotkeyRegistrations()` | Read `.hotkeys`, every registered hotkey with its options, `meta`, and `status` (whether it's enabled and in an active scope). |
74
- | `getHotkeyScopesState()` | Read `.state`, the active scopes and the exclusive scope that owns the keyboard. |
75
- | `getHotkeyHint(hotkey, options?)` | Read `.visible`, whether held modifiers should reveal a shortcut's hint. False unless a registration of the hotkey can fire: enabled, in an active scope, and with focus inside its element target. |
76
- | `getIsKeyHeld(key)` | Read `.held`, whether one key is held. Letters match in any case; other names, such as `Shift`, are case-sensitive. |
77
- | `getHeldKeys()` | Read `.keys`, every key that's held right now. |
78
- | `getHeldKeyCodesMap()` | Read `.codes`, which maps each held key to its physical `event.code`. |
58
+ | API | What it's for |
59
+ | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
60
+ | `createHotkey(hotkey, callback, options?)` | Register one chord, sequence, or app hotkey on the document while the component is mounted; pass getters for values that change. |
61
+ | `createHotkeys(definitions, commonOptions?)` | Register several hotkeys on the document, or a getter of a list built from data. |
62
+ | `createHotkeyAttachment(hotkey, callback, options?)` | Create an attachment for `{@attach}` that listens on one element. |
63
+ | `createHotkeysAttachment(definitions, commonOptions?)` | Create an attachment that registers several hotkeys on one element. |
64
+ | `<HotkeysProvider>` | Set default options, a scope (`exclusive` for dialogs), `enabled`, and app hotkeys for the components inside it. |
65
+ | `setHotkeysContext(options)` | Set the same options from a component's script instead of rendering `HotkeysProvider`; they apply to that component too. |
66
+ | `getHotkeysContext()` | Read the nearest context's merged defaults and enabled state, or `null` outside one. |
67
+ | `getDefaultHotkeysOptions()` | Read the default options merged from every context above. |
68
+ | `getFormatForDisplay()` | Get the function that formats a hotkey as a label, with the provider's `platform` and the user's keyboard layout filled in. Only Chromium browsers report a layout, so physical keys keep their US labels in Firefox and Safari. Use it for every label in a component: `const formatForDisplay = getFormatForDisplay()` during component initialization, then `formatForDisplay(hotkey)`. |
69
+ | `getAppHotkeys()` | Read `.current`, the declared app hotkeys with the user's custom hotkeys applied. |
70
+ | `getAppHotkeyList()` | Read `.current`, every app hotkey with its status, for a cheat sheet or settings screen. |
71
+ | `getCustomHotkeys()` | Read the user's custom hotkeys from `.current`, change or reset them, and check a new one for conflicts. |
72
+ | `createHotkeyRecorder(options)` | Record a chord or sequence the user presses, for a settings screen. |
73
+ | `getHotkeyRegistrations()` | Read `.hotkeys`, every registered hotkey with its options, `meta`, and `status` (whether it's enabled and in an active scope). |
74
+ | `getHotkeyScopesState()` | Read `.state`, the active scopes and the exclusive scope that owns the keyboard. |
75
+ | `getHotkeyHint(hotkey, options?)` | Read `.visible`, whether held modifiers should reveal a shortcut's hint. False unless a registration of the hotkey can fire: enabled, in an active scope, and with focus inside its element target. |
76
+ | `getIsKeyHeld(key)` | Read `.held`, whether one key is held. Letters match in any case; other names, such as `Shift`, are case-sensitive. |
77
+ | `getHeldKeys()` | Read `.keys`, every key that's held right now. |
78
+ | `getHeldKeyCodesMap()` | Read `.codes`, which maps each held key to its physical `event.code`. |
79
79
 
80
- The package also re-exports `@tanstack/hotkeys`, such as `formatForDisplay`, `matchesKeyboardEvent`, and `defineAppHotkeys`.
80
+ The package also re-exports `@tanstack/hotkeys`, such as `matchesKeyboardEvent` and `defineAppHotkeys`. Its plain `formatForDisplay` export is deprecated: use `getFormatForDisplay()` in components. Outside a component, call the plain function and pass `platform`.
81
81
 
82
82
  No provider is required. Call these at the top level of a component's `<script>`.
83
83
 
@@ -89,7 +89,7 @@ No provider is required. Call these at the top level of a component's `<script>`
89
89
  - **Call `setHotkeysContext` before creating the component's hotkeys.** It applies to the component itself, so a hotkey created first lands in the outer scope, which an exclusive context then suspends. It reads its options once; for `enabled` or `exclusive` that change, wrap the component in `<HotkeysProvider>`. Give each open dialog its own scope name.
90
90
  - **The callback isn't tracked.** Read state and props inside it.
91
91
  - **Call the functions directly.** A `createShortcut(keys: string)` wrapper has to cast strings to hotkeys, which turns off type checking and drops sequences, getter options, and app hotkeys.
92
- - **Server-rendered labels need the user's platform.** On the server, `formatForDisplay` can't see the user's OS, so it renders Linux labels that differ after hydration for Mac and Windows users. Set the provider's `defaultOptions.platform` to `detectPlatform(userAgent)` from the request's `User-Agent` header, and format labels with `const format = getFormatForDisplay()` during component initialization, then `format(hotkey)`. Keep plain `formatForDisplay` for labels that render only in the browser, when no provider sets `platform`.
92
+ - **Server-rendered labels need the user's platform.** The server can't see the user's OS, so without a platform it renders Linux labels that differ after hydration for Mac and Windows users. Set the provider's `defaultOptions.platform` to `detectPlatform(userAgent)` from the request's `User-Agent` header. `getFormatForDisplay()` reads it.
93
93
 
94
94
  When declaring app hotkeys, building a cheat sheet, or letting users rebind shortcuts, load `@tanstack/hotkeys#app-hotkeys` and read [app hotkeys in Svelte](references/app-hotkeys.md).
95
95
 
@@ -49,24 +49,25 @@ A settings row records with `createHotkeyRecorder` and saves through `getCustomH
49
49
  <script lang="ts">
50
50
  import {
51
51
  createHotkeyRecorder,
52
- formatForDisplay,
53
52
  getAppHotkeys,
54
53
  getCustomHotkeys,
54
+ getFormatForDisplay,
55
55
  } from '@tanstack/svelte-hotkeys'
56
56
  import type { AppHotkeyId } from '@tanstack/svelte-hotkeys'
57
57
 
58
58
  let { id }: { id: AppHotkeyId } = $props()
59
+ const formatForDisplay = getFormatForDisplay()
59
60
  const appHotkeys = getAppHotkeys()
60
61
  const custom = getCustomHotkeys()
61
62
  const appHotkey = $derived(appHotkeys.current[id])
62
63
 
63
64
  const recorder = createHotkeyRecorder(() => ({
64
65
  maxSteps: Infinity,
65
- validate: (hotkey) => {
66
- const [conflict] = custom.findConflicts(id, hotkey)
66
+ validate: (hotkey, context) => {
67
+ const [conflict] = custom.findConflicts(id, hotkey, context)
67
68
  return conflict ? `Used by ${conflict.meta?.name ?? conflict.id}` : true
68
69
  },
69
- onRecord: (hotkey) => custom.setCustomHotkey(id, hotkey),
70
+ onRecord: (hotkey, context) => custom.setCustomHotkey(id, hotkey, context),
70
71
  onClear: () => custom.setCustomHotkey(id, null),
71
72
  }))
72
73
  </script>