@tanstack/svelte-hotkeys 0.22.0 → 0.24.0

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.
@@ -9,6 +9,14 @@ 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.
@@ -22,8 +30,9 @@ export interface HotkeysContextOptions extends HotkeysProviderScopeProps {
22
30
  /** Merged with the parent context's defaults. */
23
31
  defaultOptions?: HotkeysProviderOptions;
24
32
  /**
25
- * Every app hotkey, from `defineAppHotkeys`. Read when the context is set;
26
- * listed by `getAppHotkeyList` whether or not they are registered.
33
+ * Every app hotkey, from `defineAppHotkeys`. Listed by `getAppHotkeyList`
34
+ * whether or not they are registered. It can start as `undefined` and arrive
35
+ * later, such as from a lazy import.
27
36
  */
28
37
  appHotkeys?: AppHotkeys;
29
38
  /**
@@ -1,7 +1,6 @@
1
- import { publishAppHotkeysStore } from '@tanstack/hotkeys';
2
1
  import { createAppHotkeysStore, getHotkeysProviderScopeKey, mergeHotkeysProviderDefaults, } from '@tanstack/hotkeys/adapter';
3
- import { createContext, onMount } from 'svelte';
4
- import { activateScopeWhileMounted } from './internal.svelte.js';
2
+ import { createContext } from 'svelte';
3
+ import { activateScopeWhileMounted, syncAppHotkeysStore, } from './internal.svelte.js';
5
4
  export const DEFAULT_OPTIONS = {};
6
5
  const [useHotkeysContext, setHotkeysContextValue] = createContext();
7
6
  /**
@@ -31,20 +30,27 @@ export function setHotkeysContext(options = {}) {
31
30
  /** Sets the context from a getter, so default options stay reactive. */
32
31
  export function setHotkeysContextSource(source) {
33
32
  const parent = getHotkeysContext();
34
- const { appHotkeys, customHotkeys, defaultOptions } = source();
35
- const store = appHotkeys
36
- ? createAppHotkeysStore(appHotkeys, {
37
- customHotkeys,
38
- // App hotkeys compare hotkeys, such as for conflicts, on this platform.
39
- platform: defaultOptions?.platform ?? parent?.defaultOptions.platform,
40
- onCustomHotkeysChange: (custom) => source().onCustomHotkeysChange?.(custom),
41
- })
42
- : null;
43
- // Publish the store so devtools can list declared hotkeys.
44
- if (store)
45
- onMount(() => publishAppHotkeysStore(store));
33
+ let store = null;
34
+ // Created when app hotkeys first arrive. That can be after the context is
35
+ // set, such as when a lazy import loads the declarations. A reactive reader
36
+ // tracks the options through `source()`, so it re-runs when they arrive.
37
+ const ownStore = () => {
38
+ const { appHotkeys, customHotkeys, defaultOptions } = source();
39
+ if (!store && appHotkeys) {
40
+ store = createAppHotkeysStore(appHotkeys, {
41
+ customHotkeys,
42
+ // App hotkeys compare hotkeys, such as for conflicts, on this
43
+ // platform.
44
+ platform: defaultOptions?.platform ?? parent?.defaultOptions.platform,
45
+ onCustomHotkeysChange: (custom) => source().onCustomHotkeysChange?.(custom),
46
+ });
47
+ }
48
+ return store;
49
+ };
46
50
  const context = setHotkeysContextValue({
47
- appHotkeysStore: store ?? parent?.appHotkeysStore ?? null,
51
+ get appHotkeysStore() {
52
+ return ownStore() ?? parent?.appHotkeysStore ?? null;
53
+ },
48
54
  get defaultOptions() {
49
55
  const { defaultOptions, scope } = source();
50
56
  return mergeHotkeysProviderDefaults(parent?.defaultOptions, defaultOptions, scope);
@@ -53,6 +59,13 @@ export function setHotkeysContextSource(source) {
53
59
  return (parent?.enabled ?? true) && source().enabled !== false;
54
60
  },
55
61
  });
62
+ // Only this context's own store: a nested context without app hotkeys
63
+ // reads its parent's store and never changes it.
64
+ syncAppHotkeysStore(ownStore, () => ({
65
+ appHotkeys: source().appHotkeys,
66
+ customHotkeys: source().customHotkeys,
67
+ platform: context.defaultOptions.platform,
68
+ }));
56
69
  // Compared by value, so a new `exclusive` object does not reactivate the
57
70
  // scope and lose its precedence.
58
71
  activateScopeWhileMounted(() => {
@@ -13,7 +13,7 @@
13
13
  enabled,
14
14
  }: HotkeysProviderProps = $props()
15
15
 
16
- const context = setHotkeysContextSource(() => ({
16
+ setHotkeysContextSource(() => ({
17
17
  defaultOptions,
18
18
  appHotkeys,
19
19
  customHotkeys,
@@ -22,21 +22,6 @@
22
22
  exclusive,
23
23
  enabled,
24
24
  }))
25
-
26
- // Keep declarations current (for example after hot module replacement).
27
- $effect(() => {
28
- if (appHotkeys) context.appHotkeysStore?.setAppHotkeys(appHotkeys)
29
- })
30
-
31
- // Apply the platform and saved custom hotkeys whose value changes, such as
32
- // data that loads after the first render. Only a provider with appHotkeys
33
- // owns a store.
34
- $effect(() => {
35
- const platform = context.defaultOptions.platform
36
- if (appHotkeys) {
37
- context.appHotkeysStore?.setOptions({ customHotkeys, platform })
38
- }
39
- })
40
25
  </script>
41
26
 
42
27
  {@render children()}
@@ -26,6 +26,7 @@ export interface SvelteHotkeyRecorder<THotkey extends Hotkey = Hotkey> {
26
26
  * @example
27
27
  * ```svelte
28
28
  * <script lang="ts">
29
+ * const formatForDisplay = getFormatForDisplay()
29
30
  * const recorder = createHotkeyRecorder({ onRecord: (hotkey) => (shortcut = hotkey) })
30
31
  * const sequenceRecorder = createHotkeyRecorder({ maxSteps: Infinity, onRecord: save })
31
32
  * </script>
@@ -1,20 +1,20 @@
1
1
  import { createHotkeyBindings, prepareHotkeyDefinitions, } from '@tanstack/hotkeys/adapter';
2
2
  import { getHotkeysContext } from './HotkeysCtx.js';
3
- import { createAppHotkeysSubscriber, resolveMaybeGetter, } from './internal.svelte.js';
3
+ import { createAppHotkeysSource, resolveMaybeGetter, } from './internal.svelte.js';
4
4
  /**
5
5
  * Registers definitions in an effect. With an element, every hotkey listens on
6
6
  * that element; otherwise each uses its own target (document by default).
7
7
  */
8
8
  function bindHotkeys(hotkeys, commonOptions, element) {
9
9
  const context = getHotkeysContext();
10
- const subscribeAppHotkeys = createAppHotkeysSubscriber(context?.appHotkeysStore ?? null);
10
+ const appHotkeys = createAppHotkeysSource(context);
11
11
  const bindings = createHotkeyBindings({ afterDelegatedHandlers: true });
12
12
  $effect(() => {
13
13
  if (typeof document === 'undefined') {
14
14
  return;
15
15
  }
16
16
  // Track app hotkeys so registrations move with custom hotkeys.
17
- subscribeAppHotkeys();
17
+ appHotkeys.subscribe();
18
18
  const definitions = resolveMaybeGetter(hotkeys).map((definition) => ({
19
19
  hotkey: resolveMaybeGetter(definition.hotkey),
20
20
  callback: definition.callback,
@@ -23,7 +23,7 @@ function bindHotkeys(hotkeys, commonOptions, element) {
23
23
  : undefined,
24
24
  }));
25
25
  bindings.update(prepareHotkeyDefinitions(definitions, {
26
- appHotkeysStore: context?.appHotkeysStore,
26
+ appHotkeysStore: appHotkeys.store,
27
27
  defaults: context?.defaultOptions.hotkey,
28
28
  commonOptions: element
29
29
  ? { ...resolveMaybeGetter(commonOptions), target: element }
@@ -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 { AppHotkey, AppHotkeyListItem, CustomHotkeys, Hotkey, RecordedKeyPresses, 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;
@@ -31,15 +31,20 @@ export interface SvelteCustomHotkeys {
31
31
  readonly current: CustomHotkeys;
32
32
  /**
33
33
  * Sets the user's hotkey for an app hotkey. `null` unbinds it.
34
- * Returns conflicting app hotkeys; when any exist, nothing changes.
34
+ * Returns conflicting app hotkeys; when any exist, nothing changes. Pass
35
+ * the recorder's `context` for a recorded hotkey, as for `findConflicts`.
35
36
  */
36
- setCustomHotkey: (id: keyof RegisteredAppHotkeys & string, hotkey: Hotkey | null) => Array<AppHotkey>;
37
+ setCustomHotkey: (id: keyof RegisteredAppHotkeys & string, hotkey: Hotkey | null, recordedWith?: RecordedKeyPresses) => Array<AppHotkey>;
37
38
  /** Restores the default hotkey for an app hotkey. */
38
39
  resetCustomHotkey: (id: keyof RegisteredAppHotkeys & string) => void;
39
40
  /** Restores every default hotkey. */
40
41
  resetCustomHotkeys: () => void;
41
- /** Other app hotkeys that would collide if `id` used `hotkey`. */
42
- findConflicts: (id: keyof RegisteredAppHotkeys & string, hotkey: Hotkey) => Array<AppHotkey>;
42
+ /**
43
+ * Other app hotkeys that would collide if `id` used `hotkey`. Pass the
44
+ * recorder's `context` for a recorded hotkey: it has the key press, which
45
+ * also finds a hotkey written differently that the same press fires.
46
+ */
47
+ findConflicts: (id: keyof RegisteredAppHotkeys & string, hotkey: Hotkey, recordedWith?: RecordedKeyPresses) => Array<AppHotkey>;
43
48
  }
44
49
  /**
45
50
  * Reads and changes the user's custom hotkeys. Changes apply to every
@@ -1,14 +1,18 @@
1
1
  import { getHotkeysContext } from './HotkeysCtx.js';
2
2
  import { getHotkeyRegistrations } from './getHotkeyRegistrations.svelte.js';
3
- import { createStoreSubscriber } from './internal.svelte.js';
3
+ import { createAppHotkeysSource } from './internal.svelte.js';
4
4
  function requireStore(name) {
5
- const store = getHotkeysContext()?.appHotkeysStore;
6
- if (!store) {
5
+ const source = createAppHotkeysSource(getHotkeysContext());
6
+ const initial = source.store;
7
+ if (!initial) {
7
8
  throw new Error(`[hotkeys] ${name} requires a HotkeysProvider with appHotkeys`);
8
9
  }
9
10
  return {
10
- store: store,
11
- subscribe: createStoreSubscriber(store.store),
11
+ // The nearest provider's store, which changes if a nested provider gets
12
+ // its app hotkeys later.
13
+ store: () => (source.store ??
14
+ initial),
15
+ subscribe: source.subscribe,
12
16
  };
13
17
  }
14
18
  /**
@@ -28,7 +32,7 @@ export function getAppHotkeys() {
28
32
  return {
29
33
  get current() {
30
34
  subscribe();
31
- return store.appHotkeys;
35
+ return store().appHotkeys;
32
36
  },
33
37
  };
34
38
  }
@@ -43,7 +47,7 @@ export function getAppHotkeyList() {
43
47
  return {
44
48
  get current() {
45
49
  subscribe();
46
- return store.getList(registrations.hotkeys);
50
+ return store().getList(registrations.hotkeys);
47
51
  },
48
52
  };
49
53
  }
@@ -57,11 +61,11 @@ export function getCustomHotkeys() {
57
61
  return {
58
62
  get current() {
59
63
  subscribe();
60
- return store.customHotkeys;
64
+ return store().customHotkeys;
61
65
  },
62
- setCustomHotkey: (id, hotkey) => store.setCustomHotkey(id, hotkey),
63
- resetCustomHotkey: (id) => store.resetCustomHotkey(id),
64
- resetCustomHotkeys: () => store.resetCustomHotkeys(),
65
- findConflicts: (id, hotkey) => store.findConflicts(id, hotkey),
66
+ setCustomHotkey: (id, hotkey, recordedWith) => store().setCustomHotkey(id, hotkey, recordedWith),
67
+ resetCustomHotkey: (id) => store().resetCustomHotkey(id),
68
+ resetCustomHotkeys: () => store().resetCustomHotkeys(),
69
+ findConflicts: (id, hotkey, recordedWith) => store().findConflicts(id, hotkey, recordedWith),
66
70
  };
67
71
  }
@@ -5,16 +5,22 @@ import { formatForDisplay } from '@tanstack/hotkeys';
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,40 @@
1
1
  import { formatForDisplay } from '@tanstack/hotkeys';
2
+ import { namesPhysicalKey } from '@tanstack/hotkeys/adapter';
2
3
  import { getHotkeysContext } from './HotkeysCtx.js';
4
+ import { getKeyboardLayout } from './getKeyboardLayout.svelte.js';
3
5
  /**
4
6
  * Returns `formatForDisplay` with the provider's `platform` as the default,
5
7
  * so labels match the user's platform. Call during component initialization,
6
8
  * like `getContext`; the returned function works anywhere and reads the
7
9
  * provider's current defaults. An explicit `platform` option wins.
8
10
  *
11
+ * Physical bindings such as `[KeyQ]` are labeled with the character the key
12
+ * types for this user in Chromium browsers, once the keyboard layout has
13
+ * loaded, and markup updates when it arrives. See `getKeyboardLayout`. A
14
+ * `layoutMap` passed to the returned function wins. Firefox and Safari report
15
+ * no layout, so labels there keep the key's US character.
16
+ *
9
17
  * Server-rendered apps should set the provider's `defaultOptions.platform`
10
18
  * from the request user agent with `detectPlatform(userAgent)`.
11
19
  *
12
20
  * @example
13
21
  * ```svelte
14
22
  * <script lang="ts">
15
- * const format = getFormatForDisplay()
23
+ * const formatForDisplay = getFormatForDisplay()
16
24
  * </script>
17
25
  *
18
- * <kbd>{format('Mod+S')}</kbd>
26
+ * <kbd>{formatForDisplay('Mod+S')}</kbd>
19
27
  * ```
20
28
  */
21
29
  export function getFormatForDisplay() {
22
30
  const context = getHotkeysContext();
31
+ const keyboard = getKeyboardLayout();
23
32
  return ((hotkey, options) => formatForDisplay(hotkey, {
24
33
  ...options,
25
34
  platform: options?.platform ?? context?.defaultOptions.platform,
35
+ // Only a position's label follows the layout. Other labels don't read
36
+ // it, so they don't render again when it loads.
37
+ layoutMap: options?.layoutMap ??
38
+ (namesPhysicalKey(hotkey) ? (keyboard.layout ?? undefined) : undefined),
26
39
  }));
27
40
  }
@@ -14,12 +14,14 @@ import { resolveMaybeGetter } from './internal.svelte.js';
14
14
  export function getHotkeyHint(hotkey, options = {}) {
15
15
  const tracker = getKeyStateTracker();
16
16
  const manager = getHotkeyManager();
17
- const store = getHotkeysContext()?.appHotkeysStore ?? null;
17
+ const context = getHotkeysContext();
18
+ // Read each time: a provider creates its store when its app hotkeys arrive.
19
+ const getStore = () => context?.appHotkeysStore ?? null;
18
20
  // Resolve current reactive arguments without caching a stale hotkey.
19
21
  const read = () => {
20
22
  const value = resolveMaybeGetter(hotkey);
21
23
  const resolved = isAppHotkey(value)
22
- ? resolveAppHotkey(value, store).hotkey
24
+ ? resolveAppHotkey(value, getStore()).hotkey
23
25
  : value;
24
26
  return (resolved !== null &&
25
27
  matchesHeldModifiers(resolved, tracker.store.state.heldKeys, resolveMaybeGetter(options)) &&
@@ -27,7 +29,7 @@ export function getHotkeyHint(hotkey, options = {}) {
27
29
  };
28
30
  let previous = false;
29
31
  // Notify Svelte only when visibility changes, not for every unrelated held key.
30
- const subscribe = createSubscriber((update) => {
32
+ const track = (store) => createSubscriber((update) => {
31
33
  previous = read();
32
34
  const check = () => {
33
35
  const next = read();
@@ -45,6 +47,18 @@ export function getHotkeyHint(hotkey, options = {}) {
45
47
  custom?.unsubscribe();
46
48
  };
47
49
  });
50
+ // One subscriber for each store, so a store that arrives later is tracked.
51
+ const withoutStore = track(null);
52
+ const subscribers = new WeakMap();
53
+ const subscribe = () => {
54
+ const store = getStore();
55
+ if (!store)
56
+ return withoutStore();
57
+ let tracked = subscribers.get(store);
58
+ if (!tracked)
59
+ subscribers.set(store, (tracked = track(store)));
60
+ tracked();
61
+ };
48
62
  return {
49
63
  /** Reads visibility and subscribes the current reactive consumer when needed. */
50
64
  get visible() {
@@ -12,6 +12,7 @@ export interface SvelteHotkeyRegistrations {
12
12
  * @example
13
13
  * ```svelte
14
14
  * <script lang="ts">
15
+ * const formatForDisplay = getFormatForDisplay()
15
16
  * const registrations = getHotkeyRegistrations()
16
17
  * </script>
17
18
  *
@@ -17,6 +17,7 @@ class HotkeyRegistrationsState {
17
17
  * @example
18
18
  * ```svelte
19
19
  * <script lang="ts">
20
+ * const formatForDisplay = getFormatForDisplay()
20
21
  * const registrations = getHotkeyRegistrations()
21
22
  * </script>
22
23
  *
@@ -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,76 @@
1
+ import { getKeyboardLayoutStore, loadKeyboardLayout } from '@tanstack/hotkeys';
2
+ import { createSubscriber } from 'svelte/reactivity';
3
+ import { getHotkeysContext } from './HotkeysCtx.js';
4
+ class KeyboardLayoutState {
5
+ #context = getHotkeysContext();
6
+ #store = getKeyboardLayoutStore();
7
+ // Loads the layout while an effect or markup reads it. Calls are counted,
8
+ // so every reader can load it.
9
+ #subscribe = createSubscriber((update) => {
10
+ const stop = loadKeyboardLayout();
11
+ const { unsubscribe } = this.#store.subscribe(update);
12
+ return () => {
13
+ unsubscribe();
14
+ stop();
15
+ };
16
+ });
17
+ // Server HTML never has a layout, so a component that hydrates starts
18
+ // without one, even when the layout has already loaded.
19
+ #mounted = $state(false);
20
+ constructor() {
21
+ try {
22
+ // Effects run after the component mounts, and never on a server.
23
+ $effect(() => {
24
+ this.#mounted = true;
25
+ });
26
+ // Loads the layout even when nothing else reads it reactively.
27
+ $effect(() => {
28
+ void this.layout;
29
+ });
30
+ }
31
+ catch {
32
+ // Outside a component there is no hydration to wait for.
33
+ this.#mounted = true;
34
+ }
35
+ }
36
+ get layout() {
37
+ if (!this.#mounted)
38
+ return null;
39
+ if (this.#context?.defaultOptions.keyboardLayout === false)
40
+ return null;
41
+ this.#subscribe();
42
+ return this.#store.state;
43
+ }
44
+ }
45
+ /**
46
+ * Svelte function that returns reactive access to the browser's keyboard
47
+ * layout. `layout` is `null` until the layout loads and in browsers that
48
+ * don't report one. The layout maps each physical code to the character it
49
+ * types, such as `KeyQ` to `a` on a French AZERTY keyboard. Only Chromium
50
+ * browsers report one.
51
+ *
52
+ * The layout loads after the first component that uses this function mounts,
53
+ * so server-rendered output hydrates unchanged. `getFormatForDisplay` uses
54
+ * this function, so you only need it for labels you draw yourself.
55
+ *
56
+ * To never ask the browser for the layout, set `keyboardLayout: false` in
57
+ * `HotkeysProvider`'s `defaultOptions`. `layout` then stays `null`.
58
+ *
59
+ * @returns Object with a reactive `layout` property
60
+ *
61
+ * @example
62
+ * ```svelte
63
+ * <script lang="ts">
64
+ * import { getKeyboardLayout } from '@tanstack/svelte-hotkeys'
65
+ *
66
+ * const keyboard = getKeyboardLayout()
67
+ * const label = (code: string) =>
68
+ * (keyboard.layout?.get(code) ?? code).toUpperCase()
69
+ * </script>
70
+ *
71
+ * <kbd>{label('KeyW')}</kbd>
72
+ * ```
73
+ */
74
+ export function getKeyboardLayout() {
75
+ return new KeyboardLayoutState();
76
+ }
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,4 +1,4 @@
1
- import type { AppHotkeysStore } from '@tanstack/hotkeys';
1
+ import type { AppHotkeys, AppHotkeysStore, CustomHotkeys, HotkeyPlatform } from '@tanstack/hotkeys';
2
2
  export type MaybeGetter<T> = T | (() => T);
3
3
  interface SubscribableStore<TState> {
4
4
  state: TState;
@@ -9,10 +9,27 @@ interface SubscribableStore<TState> {
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
- * Returns a function that subscribes the current reactive consumer to an app
13
- * hotkeys store, so it re-runs when app hotkeys or custom hotkeys change.
12
+ * The nearest provider's app hotkeys store, read from the context each time.
13
+ * A provider creates its store when its app hotkeys arrive, which can be after
14
+ * a hotkey is created. `subscribe` makes the current reactive consumer re-run
15
+ * when app hotkeys or custom hotkeys change.
14
16
  */
15
- export declare function createAppHotkeysSubscriber(store: AppHotkeysStore | null): () => void;
17
+ export declare function createAppHotkeysSource(context: {
18
+ readonly appHotkeysStore: AppHotkeysStore | null;
19
+ } | null): {
20
+ readonly store: AppHotkeysStore | null;
21
+ subscribe: () => void;
22
+ };
23
+ /**
24
+ * Keeps a provider's own app hotkeys store current while the component is
25
+ * mounted: publishes it for devtools, and applies changed declarations, saved
26
+ * custom hotkeys and platform.
27
+ */
28
+ export declare function syncAppHotkeysStore(getStore: () => AppHotkeysStore | null, getOptions: () => {
29
+ appHotkeys?: AppHotkeys;
30
+ customHotkeys?: CustomHotkeys | null;
31
+ platform?: HotkeyPlatform;
32
+ }): void;
16
33
  /**
17
34
  * Activates a provider's scope while the component is mounted, and again
18
35
  * whenever the key from `getHotkeysProviderScopeKey` changes.
@@ -1,3 +1,4 @@
1
+ import { publishAppHotkeysStore } from '@tanstack/hotkeys';
1
2
  import { activateHotkeysProviderScope } from '@tanstack/hotkeys/adapter';
2
3
  import { createSubscriber } from 'svelte/reactivity';
3
4
  export function resolveMaybeGetter(value) {
@@ -11,13 +12,55 @@ export function createStoreSubscriber(store) {
11
12
  : () => subscription.unsubscribe();
12
13
  });
13
14
  }
14
- const noop = () => { };
15
15
  /**
16
- * Returns a function that subscribes the current reactive consumer to an app
17
- * hotkeys store, so it re-runs when app hotkeys or custom hotkeys change.
16
+ * The nearest provider's app hotkeys store, read from the context each time.
17
+ * A provider creates its store when its app hotkeys arrive, which can be after
18
+ * a hotkey is created. `subscribe` makes the current reactive consumer re-run
19
+ * when app hotkeys or custom hotkeys change.
18
20
  */
19
- export function createAppHotkeysSubscriber(store) {
20
- return store ? createStoreSubscriber(store.store) : noop;
21
+ export function createAppHotkeysSource(context) {
22
+ const subscribers = new WeakMap();
23
+ return {
24
+ get store() {
25
+ return context?.appHotkeysStore ?? null;
26
+ },
27
+ subscribe() {
28
+ const store = context?.appHotkeysStore;
29
+ if (!store)
30
+ return;
31
+ let subscribe = subscribers.get(store);
32
+ if (!subscribe) {
33
+ subscribe = createStoreSubscriber(store.store);
34
+ subscribers.set(store, subscribe);
35
+ }
36
+ subscribe();
37
+ },
38
+ };
39
+ }
40
+ /**
41
+ * Keeps a provider's own app hotkeys store current while the component is
42
+ * mounted: publishes it for devtools, and applies changed declarations, saved
43
+ * custom hotkeys and platform.
44
+ */
45
+ export function syncAppHotkeysStore(getStore, getOptions) {
46
+ // Derived, so an effect runs again only when its own value changes, not for
47
+ // every option the getters read.
48
+ const store = $derived(getStore());
49
+ const appHotkeys = $derived(getOptions().appHotkeys);
50
+ const customHotkeys = $derived(getOptions().customHotkeys);
51
+ const platform = $derived(getOptions().platform);
52
+ // Publish the store so devtools can list declared hotkeys.
53
+ $effect(() => (store ? publishAppHotkeysStore(store) : undefined));
54
+ // Keep declarations current (for example after hot module replacement).
55
+ $effect(() => {
56
+ if (appHotkeys)
57
+ store?.setAppHotkeys(appHotkeys);
58
+ });
59
+ // Apply the platform and saved custom hotkeys whose value changes, such as
60
+ // data that loads after the first render.
61
+ $effect(() => {
62
+ store?.setOptions({ customHotkeys, platform });
63
+ });
21
64
  }
22
65
  /**
23
66
  * Activates a provider's scope while the component is mounted, and again
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/svelte-hotkeys",
3
- "version": "0.22.0",
3
+ "version": "0.24.0",
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.0"
44
+ "@tanstack/hotkeys": "0.29.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>