@alulore/kumiko 0.17.2 → 0.17.3

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.
@@ -8,8 +8,12 @@ export interface ShortcutAction {
8
8
  section: string;
9
9
  /** The keys that run it by default: one, or several. Written like `"mod+k"`. */
10
10
  keys: string | readonly string[];
11
- /** Runs when one of its keys is pressed, or when a control calls it. */
12
- run: (event?: KeyboardEvent) => void;
11
+ /**
12
+ * Runs when one of its keys is pressed, or when a control calls it. Leave it out to declare the action here
13
+ * and bind it from a component with `useShortcutAction`; until one is mounted the action is listed and
14
+ * rebindable but does nothing.
15
+ */
16
+ run?: (event?: KeyboardEvent) => void;
13
17
  /** Checked on every key press: the action runs only while it returns true. */
14
18
  when?: () => boolean;
15
19
  /** Whether it also runs while focus is in a text field. Keys with Ctrl, Cmd or Alt always do. */
@@ -20,7 +24,17 @@ export interface ShortcutAction {
20
24
  * @defaultValue false
21
25
  */
22
26
  overDialogs?: boolean;
27
+ /**
28
+ * Whether the help sheet lists it only while it could run when the sheet opened, or always. An action that
29
+ * needs focus somewhere (a card) is gone as soon as the sheet's own button takes focus, so "always" keeps it.
30
+ * @defaultValue "available"
31
+ */
32
+ listed?: "available" | "always";
23
33
  }
34
+ /** An action with the code that runs it, as a component gives it to `useShortcutAction`. */
35
+ export type BoundShortcutAction = ShortcutAction & {
36
+ run: NonNullable<ShortcutAction["run"]>;
37
+ };
24
38
  /** The keys people changed, by action id. An action that is not in here uses its defaults. */
25
39
  export type Overrides = Readonly<Record<string, readonly string[]>>;
26
40
  /** How many keys one action can hold. */
@@ -29,8 +43,14 @@ export declare function defaultKeys(action: ShortcutAction): string[];
29
43
  export declare function keysOf(action: ShortcutAction, overrides: Overrides): string[];
30
44
  /** Whether saved bindings have the right shape: an object of action ids to lists of key strings. */
31
45
  export declare function isOverrides(value: unknown): value is Overrides;
32
- /** Keeps what applies to these actions: known ids only, keys written one way, at most `maxKeysPerAction` each. */
46
+ /**
47
+ * Writes the keys of these actions one way and caps them at `maxKeysPerAction`. An id that is not in the list
48
+ * is left exactly as saved: it may belong to an action that is not declared right now, and what a person
49
+ * chose is never dropped because of what happens to be mounted.
50
+ */
33
51
  export declare function sanitizeOverrides(saved: Overrides, actions: readonly ShortcutAction[]): Overrides;
52
+ /** The saved keys of the actions in this list only, for what a reset of everything on screen clears. */
53
+ export declare function withoutActions(overrides: Overrides, actions: readonly ShortcutAction[]): Overrides;
34
54
  /** Who has these keys now, other than `exceptId`. */
35
55
  export declare function ownerOf(actions: readonly ShortcutAction[], overrides: Overrides, keys: string, exceptId: string): ShortcutAction | undefined;
36
56
  export type Resolution = "plain" | "swap" | "replace";
@@ -15,16 +15,22 @@ export function isOverrides(value) {
15
15
  !Array.isArray(value) &&
16
16
  Object.values(value).every((keys) => Array.isArray(keys) && keys.every((key) => typeof key === "string")));
17
17
  }
18
- /** Keeps what applies to these actions: known ids only, keys written one way, at most `maxKeysPerAction` each. */
18
+ /**
19
+ * Writes the keys of these actions one way and caps them at `maxKeysPerAction`. An id that is not in the list
20
+ * is left exactly as saved: it may belong to an action that is not declared right now, and what a person
21
+ * chose is never dropped because of what happens to be mounted.
22
+ */
19
23
  export function sanitizeOverrides(saved, actions) {
20
- const result = {};
21
- for (const action of actions) {
22
- const keys = Object.entries(saved).find(([id]) => id === action.id)?.[1];
23
- if (keys) {
24
- result[action.id] = keys.slice(0, maxKeysPerAction).map((key) => canonicalKeys(key));
25
- }
26
- }
27
- return result;
24
+ const known = new Set(actions.map((action) => action.id));
25
+ return Object.fromEntries(Object.entries(saved).map(([id, keys]) => [
26
+ id,
27
+ known.has(id) ? keys.slice(0, maxKeysPerAction).map((key) => canonicalKeys(key)) : keys
28
+ ]));
29
+ }
30
+ /** The saved keys of the actions in this list only, for what a reset of everything on screen clears. */
31
+ export function withoutActions(overrides, actions) {
32
+ const known = new Set(actions.map((action) => action.id));
33
+ return Object.fromEntries(Object.entries(overrides).filter(([id]) => !known.has(id)));
28
34
  }
29
35
  /** Who has these keys now, other than `exceptId`. */
30
36
  export function ownerOf(actions, overrides, keys, exceptId) {
@@ -0,0 +1,15 @@
1
+ import { type BoundShortcutAction } from "./bindings";
2
+ /**
3
+ * Gives an action the code that runs it, from wherever that code lives in the tree.
4
+ *
5
+ * When the nearest `ShortcutsProvider` declares the same `id`, this binds `run` and `when` to that declaration:
6
+ * the provider's keys, saved changes, section and description win, and its `allowInInput`, `overDialogs` and
7
+ * pause rules apply. The binding goes when the component unmounts. With two bindings for one id, the one
8
+ * mounted last runs, and the other takes over again when it goes. The latest `run` and `when` are read on every
9
+ * key press, so they need not be stable.
10
+ *
11
+ * Without a provider, or when the provider does not declare the id, the action's own default keys are
12
+ * registered plainly, as a shortcut that is not listed and cannot be rebound. A hook can serve an app with
13
+ * a provider and one without.
14
+ */
15
+ export declare function useShortcutAction(action: BoundShortcutAction): void;
@@ -0,0 +1,55 @@
1
+ import { registerShortcut } from "@ui-sdk/react/shortcuts";
2
+ import { useEffect, useRef } from "react";
3
+ import { defaultKeys, maxKeysPerAction } from "./bindings";
4
+ import { holdOverDialogs, overDialogsLayer } from "./over-dialogs";
5
+ import { useOptionalShortcuts } from "./provider";
6
+ /** Registers an action's own keys plainly, as a shortcut that is not listed or rebindable. */
7
+ function usePlain(latest, enabled) {
8
+ const overDialogs = latest.current.overDialogs ?? false;
9
+ useEffect(() => {
10
+ if (!enabled) {
11
+ return undefined;
12
+ }
13
+ const offs = [];
14
+ if (overDialogs) {
15
+ offs.push(holdOverDialogs());
16
+ }
17
+ for (let slot = 0; slot < maxKeysPerAction; slot += 1) {
18
+ offs.push(registerShortcut(() => defaultKeys(latest.current)[slot], (event) => latest.current.run(event), {
19
+ description: latest.current.description,
20
+ allowInInput: latest.current.allowInInput ?? false,
21
+ layer: overDialogs ? overDialogsLayer : undefined,
22
+ when: () => latest.current.when?.() ?? true
23
+ }));
24
+ }
25
+ return () => {
26
+ for (const off of offs) {
27
+ off();
28
+ }
29
+ };
30
+ }, [enabled, overDialogs, latest]);
31
+ }
32
+ /**
33
+ * Gives an action the code that runs it, from wherever that code lives in the tree.
34
+ *
35
+ * When the nearest `ShortcutsProvider` declares the same `id`, this binds `run` and `when` to that declaration:
36
+ * the provider's keys, saved changes, section and description win, and its `allowInInput`, `overDialogs` and
37
+ * pause rules apply. The binding goes when the component unmounts. With two bindings for one id, the one
38
+ * mounted last runs, and the other takes over again when it goes. The latest `run` and `when` are read on every
39
+ * key press, so they need not be stable.
40
+ *
41
+ * Without a provider, or when the provider does not declare the id, the action's own default keys are
42
+ * registered plainly, as a shortcut that is not listed and cannot be rebound. A hook can serve an app with
43
+ * a provider and one without.
44
+ */
45
+ export function useShortcutAction(action) {
46
+ const shortcuts = useOptionalShortcuts();
47
+ const latest = useRef(action);
48
+ useEffect(() => {
49
+ latest.current = action;
50
+ });
51
+ const declared = shortcuts?.actions.some((item) => item.id === action.id) ?? false;
52
+ const bind = shortcuts?.bind;
53
+ useEffect(() => (declared && bind ? bind(action.id, latest) : undefined), [declared, bind, action.id]);
54
+ usePlain(latest, !declared);
55
+ }
@@ -35,5 +35,11 @@ export type ShortcutsHelpProps = TriggerProps & {
35
35
  /** A button that opens the help sheet: what can run now, by section. Its keys (`helpKeys`) open it too. */
36
36
  export declare function ShortcutsHelp({ presentation, editable, label, title, description, className, ...trigger }: ShortcutsHelpProps): React.JSX.Element;
37
37
  /** Rebinding on its own, for apps that keep it in a settings page instead of the help sheet. */
38
- export declare function ShortcutsSettings(): React.JSX.Element;
38
+ export declare function ShortcutsSettings({ notes }: {
39
+ /**
40
+ * Whether fixed keys are listed too, read-only.
41
+ * @defaultValue true
42
+ */
43
+ notes?: boolean;
44
+ }): React.JSX.Element;
39
45
  export {};
@@ -31,6 +31,6 @@ export function ShortcutsHelp({ presentation = "dialog", editable = false, label
31
31
  return (_jsxs(Dialog, { open: helpOpen, onOpenChange: onOpenChange, children: [_jsx(DialogTrigger, { ...trigger, render: render, className: className, children: label }), _jsx(DialogBackdrop, {}), _jsxs(DialogContent, { className: "kumiko-shortcuts-dialog", "data-kumiko-shortcuts": presentation, children: [_jsx(DialogTitle, { children: title }), description ? _jsx(DialogDescription, { children: description }) : null, _jsx(Body, { presentation: presentation, editable: editable, closer: _jsx(DialogClose, { render: _jsx(Button, { variant: "outline", size: "sm" }), children: "Close" }) })] })] }));
32
32
  }
33
33
  /** Rebinding on its own, for apps that keep it in a settings page instead of the help sheet. */
34
- export function ShortcutsSettings() {
35
- return (_jsx("div", { className: "kumiko-shortcuts-sheet", "data-presentation": "settings", children: _jsx(ShortcutsList, { editing: true }) }));
34
+ export function ShortcutsSettings({ notes = true }) {
35
+ return (_jsx("div", { className: "kumiko-shortcuts-sheet", "data-presentation": "settings", children: _jsx(ShortcutsList, { editing: true, notes: notes }) }));
36
36
  }
@@ -1,4 +1,5 @@
1
- export { type ShortcutAction, type Overrides } from "./bindings";
1
+ export { type BoundShortcutAction, type ShortcutAction, type Overrides } from "./bindings";
2
+ export { useShortcutAction } from "./bound";
2
3
  export { reportDrag, useIsDragging, useReportDrag } from "./guard";
3
4
  export { ShortcutsHelp, ShortcutsSettings, type HelpPresentation, type ShortcutsHelpProps } from "./help";
4
5
  export { ShortcutBadgesButton, ShortcutHint, type ShortcutHintProps } from "./hints";
@@ -1,4 +1,5 @@
1
1
  export {} from "./bindings";
2
+ export { useShortcutAction } from "./bound";
2
3
  export { reportDrag, useIsDragging, useReportDrag } from "./guard";
3
4
  export { ShortcutsHelp, ShortcutsSettings } from "./help";
4
5
  export { ShortcutBadgesButton, ShortcutHint } from "./hints";
@@ -1,4 +1,5 @@
1
1
  import { type Overrides, type Resolution, type ShortcutAction } from "./bindings";
2
+ import { type ShortcutNote } from "./notes";
2
3
  /** The reserved-keys and taken-keys choices a verdict depends on. */
3
4
  export interface JudgeOptions {
4
5
  reserved: "block" | "warn";
@@ -39,4 +40,6 @@ export declare function judge(context: {
39
40
  actions: readonly ShortcutAction[];
40
41
  overrides: Overrides;
41
42
  options: JudgeOptions;
43
+ /** Keys a widget handles itself. No action can take them. */
44
+ notes?: readonly ShortcutNote[];
42
45
  }, target: Target, raw: string, allowReserved: boolean): Verdict;
@@ -1,8 +1,9 @@
1
1
  import { keysOf, ownerOf } from "./bindings";
2
2
  import { canonicalKeys, describeKeys } from "./keys";
3
+ import { noteOwning } from "./notes";
3
4
  /** Decides what happens to new keys: used, refused with a reason, or a question first. */
4
5
  export function judge(context, target, raw, allowReserved) {
5
- const { actions, overrides, options } = context;
6
+ const { actions, overrides, options, notes = [] } = context;
6
7
  const action = actions.find((item) => item.id === target.id);
7
8
  const keys = canonicalKeys(raw);
8
9
  const own = action ? keysOf(action, overrides) : [];
@@ -18,6 +19,13 @@ export function judge(context, target, raw, allowReserved) {
18
19
  ? { kind: "refused", message: `${describeKeys(keys)} is reserved. ${reason}` }
19
20
  : { kind: "ask", pending: { kind: "reserved", keys, reason } };
20
21
  }
22
+ const fixed = noteOwning(notes, keys);
23
+ if (fixed) {
24
+ return {
25
+ kind: "refused",
26
+ message: `${describeKeys(keys)} is fixed for “${fixed.description}”.`
27
+ };
28
+ }
21
29
  const owner = ownerOf(actions, overrides, keys, target.id);
22
30
  if (!owner) {
23
31
  return { kind: "bind", keys, how: "plain" };
@@ -11,6 +11,11 @@ export interface ShortcutsListProps {
11
11
  all?: boolean;
12
12
  /** Keeps only actions whose name or section contains this text. */
13
13
  query?: string;
14
+ /**
15
+ * Whether keys that are fixed (`notes` on the provider) are listed too, read-only, with their reason.
16
+ * @defaultValue true
17
+ */
18
+ notes?: boolean;
14
19
  }
15
20
  /** The actions grouped by section, each with its keys. With `editing`, every key can be changed. */
16
- export declare function ShortcutsList({ editing, all, query }: ShortcutsListProps): React.JSX.Element;
21
+ export declare function ShortcutsList({ editing, all, query, notes: showNotes }: ShortcutsListProps): React.JSX.Element;
@@ -33,17 +33,18 @@ function Row({ action, editing, rebinder }) {
33
33
  return (_jsxs("li", { "data-unavailable": available.has(action.id) ? undefined : "", children: [_jsx("span", { className: "kumiko-shortcuts-name", children: action.description }), editing ? (_jsx(KeyEditor, { action: action, rebinder: rebinder })) : (_jsx("span", { className: "kumiko-shortcuts-keys", children: keysFor(action.id).map((key) => (_jsx(Kbd, { keys: key, listen: false }, key))) })), rebinder.target?.id === action.id ? _jsx(Capture, { rebinder: rebinder }) : null] }));
34
34
  }
35
35
  function NoteRow({ note }) {
36
- return (_jsxs("li", { "data-note": "", children: [_jsx("span", { className: "kumiko-shortcuts-name", children: note.description }), _jsx("span", { className: "kumiko-shortcuts-keys", children: noteKeys(note).map((key) => (_jsx(Kbd, { keys: key, listen: false }, key))) })] }));
36
+ return (_jsxs("li", { "data-note": "", children: [_jsx("span", { className: "kumiko-shortcuts-name", children: note.description }), _jsxs("span", { className: "kumiko-shortcuts-keys", children: [note.reason ? (_jsx("span", { className: "kumiko-shortcuts-reason", children: note.reason })) : null, noteKeys(note).map((key) => (_jsx(Kbd, { keys: key, listen: false }, key)))] })] }));
37
37
  }
38
38
  function EditFooter() {
39
- const { resetAll, overrides, options, saveFailed } = useShortcuts();
40
- return (_jsxs(_Fragment, { children: [saveFailed ? (_jsx("p", { className: "kumiko-shortcuts-message", role: "alert", children: "Your changes could not be saved. They last until the page closes." })) : null, Object.keys(overrides).length > 0 ? (_jsx("p", { children: _jsx(Button, { variant: "outline", size: "sm", type: "button", onClick: resetAll, children: "Reset all" }) })) : null, options.multipleKeys ? null : (_jsx("p", { className: "kumiko-shortcuts-empty", children: "Each action has one key." }))] }));
39
+ const { resetAll, overrides, actions, options, saveFailed } = useShortcuts();
40
+ const changed = actions.some((action) => action.id in overrides);
41
+ return (_jsxs(_Fragment, { children: [saveFailed ? (_jsx("p", { className: "kumiko-shortcuts-message", role: "alert", children: "Your changes could not be saved. They last until the page closes." })) : null, changed ? (_jsx("p", { children: _jsx(Button, { variant: "outline", size: "sm", type: "button", onClick: resetAll, children: "Reset all" }) })) : null, options.multipleKeys ? null : (_jsx("p", { className: "kumiko-shortcuts-empty", children: "Each action has one key." }))] }));
41
42
  }
42
43
  /** The actions grouped by section, each with its keys. With `editing`, every key can be changed. */
43
- export function ShortcutsList({ editing = false, all = editing, query = "" }) {
44
+ export function ShortcutsList({ editing = false, all = editing, query = "", notes: showNotes = true }) {
44
45
  const { actions, notes, available } = useShortcuts();
45
46
  const rebinder = useRebinder();
46
47
  const needle = query.trim().toLowerCase();
47
- const sections = sectionRows(actions, notes, (action) => all || available.has(action.id), needle);
48
+ const sections = sectionRows(actions, showNotes ? notes : [], (action) => all || action.listed === "always" || available.has(action.id), needle);
48
49
  return (_jsxs("div", { className: "kumiko-shortcuts-list", "data-editing": editing ? "" : undefined, children: [sections.map(({ section, rows }) => (_jsxs("section", { children: [_jsx("h3", { children: section }), _jsx("ul", { children: rows.map((row) => row.kind === "note" ? (_jsx(NoteRow, { note: row.note }, `note:${row.note.description}`)) : (_jsx(Row, { action: row.action, editing: editing, rebinder: rebinder }, row.action.id))) })] }, section))), sections.length === 0 ? (_jsx("p", { className: "kumiko-shortcuts-empty", children: needle === "" ? "Nothing has a shortcut right now." : "No shortcut matches." })) : null, editing ? _jsx(EditFooter, {}) : null] }));
49
50
  }
@@ -7,6 +7,8 @@ export interface ShortcutNote {
7
7
  section: string;
8
8
  /** The keys, one or several, written like `"mod+k"`. */
9
9
  keys: string | readonly string[];
10
+ /** Why the keys are fixed, shown as muted text beside the note: "Board keys", "System-wide". */
11
+ reason?: string;
10
12
  }
11
13
  /** One line of the help sheet: an action people can rebind, or a note they can only read. */
12
14
  export type ShortcutRow = {
@@ -25,4 +27,6 @@ export interface ShortcutSection {
25
27
  * section the actions come first, then the notes. Notes are always shown, and a search still filters them by text.
26
28
  */
27
29
  export declare function sectionRows(actions: readonly ShortcutAction[], notes: readonly ShortcutNote[], keepAction: (action: ShortcutAction) => boolean, needle: string): ShortcutSection[];
30
+ /** The note that owns these keys, so no action can be rebound onto them. */
31
+ export declare function noteOwning(notes: readonly ShortcutNote[], keys: string): ShortcutNote | undefined;
28
32
  export declare function noteKeys(note: ShortcutNote): string[];
@@ -1,3 +1,4 @@
1
+ import { canonicalKeys } from "./keys";
1
2
  function matches(text, needle) {
2
3
  return needle === "" || text.toLowerCase().includes(needle);
3
4
  }
@@ -22,6 +23,11 @@ export function sectionRows(actions, notes, keepAction, needle) {
22
23
  rows: rows.filter((row) => sectionOf(row) === section)
23
24
  }));
24
25
  }
26
+ /** The note that owns these keys, so no action can be rebound onto them. */
27
+ export function noteOwning(notes, keys) {
28
+ const wanted = canonicalKeys(keys);
29
+ return notes.find((note) => noteKeys(note).some((key) => canonicalKeys(key) === wanted));
30
+ }
25
31
  export function noteKeys(note) {
26
32
  return typeof note.keys === "string" ? [note.keys] : [...note.keys];
27
33
  }
@@ -1,5 +1,5 @@
1
1
  import { type StoredStorage } from "../stored";
2
- import { type Overrides, type ShortcutAction } from "./bindings";
2
+ import { type BoundShortcutAction, type Overrides, type ShortcutAction } from "./bindings";
3
3
  import type { ShortcutNote } from "./notes";
4
4
  export type TakenKeys = "ask" | "refuse" | "newest";
5
5
  export type ReservedMode = "block" | "warn";
@@ -87,8 +87,15 @@ export interface ShortcutsContextValue {
87
87
  saveFailed: boolean;
88
88
  modHeld: boolean;
89
89
  setModHeld: (held: boolean) => void;
90
+ /**
91
+ * Binds code to a declared action. The binding last mounted for an id wins, and the one before it takes
92
+ * over again when that one goes. Returns the way to remove it.
93
+ */
94
+ bind: (id: string, binding: React.RefObject<BoundShortcutAction>) => () => void;
90
95
  }
91
96
  export declare function useShortcuts(): ShortcutsContextValue;
97
+ /** The shortcuts of the nearest provider, or nothing when there is none. */
98
+ export declare function useOptionalShortcuts(): ShortcutsContextValue | null;
92
99
  export type ShortcutsProviderProps = ShortcutsOptions & {
93
100
  /** What the app can do, and the keys that do it. */
94
101
  actions: readonly ShortcutAction[];
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { createContext, use, useCallback, useEffect, useMemo, useRef, useState } from "react";
3
3
  import { defineStored, useStored } from "../stored";
4
- import { isOverrides, keysOf, sanitizeOverrides } from "./bindings";
4
+ import { isOverrides, keysOf, sanitizeOverrides, withoutActions } from "./bindings";
5
5
  import { defaultReservedKeys } from "./keys";
6
6
  import { listAvailable, useModHeld, useRegistration } from "./registration";
7
7
  const ShortcutsContext = createContext(null);
@@ -12,6 +12,10 @@ export function useShortcuts() {
12
12
  }
13
13
  return value;
14
14
  }
15
+ /** The shortcuts of the nearest provider, or nothing when there is none. */
16
+ export function useOptionalShortcuts() {
17
+ return use(ShortcutsContext);
18
+ }
15
19
  /** The saved bindings, followed live, and what to call to change them. A failed save is reported. */
16
20
  function useSavedOverrides(props, actions) {
17
21
  const { storage = "local", storageKey = "kumiko.shortcuts", onSaveError } = props;
@@ -62,6 +66,19 @@ function useResolved(props) {
62
66
  resetEach
63
67
  ]);
64
68
  }
69
+ /** The code components have bound to declared actions, newest last, read afresh on every key press. */
70
+ function useBindings() {
71
+ const stacks = useRef(new Map());
72
+ return useMemo(() => ({
73
+ bind: (id, binding) => {
74
+ stacks.current.set(id, [...(stacks.current.get(id) ?? []), binding]);
75
+ return () => {
76
+ stacks.current.set(id, (stacks.current.get(id) ?? []).filter((item) => item !== binding));
77
+ };
78
+ },
79
+ binding: (id) => stacks.current.get(id)?.at(-1)?.current
80
+ }), []);
81
+ }
65
82
  /** The help sheet's open state. The list of what can run is taken as it opens, because a modal sheet pauses the page. */
66
83
  function useHelpState(live) {
67
84
  const [helpOpen, setHelpOpen] = useState(false);
@@ -73,19 +90,15 @@ function useHelpState(live) {
73
90
  const closeHelp = useCallback(() => setHelpOpen(false), []);
74
91
  return useMemo(() => ({ helpOpen, available, openHelp, closeHelp }), [helpOpen, available, openHelp, closeHelp]);
75
92
  }
76
- /** Wraps the part of the app that has shortcuts: registers every action and holds what the help sheet and hints need. */
77
- export function ShortcutsProvider(props) {
78
- const { actions, children, notes = noNotes } = props;
79
- const options = useResolved(props);
80
- const [overrides, setOverrides, saveFailed] = useSavedOverrides(props, actions);
81
- const live = useRef({ ...options, actions, overrides, toggleHelp: () => { } });
82
- const help = useHelpState(live);
83
- const [modHeld, setModHeld] = useModHeld(options.hints === "badges");
93
+ /** Keeps what the registered shortcuts read fresh, and registers the actions through ui-sdk. */
94
+ function useRegistered(live, now) {
95
+ const { options, actions, overrides, binding, help } = now;
84
96
  useEffect(() => {
85
97
  live.current = {
86
98
  ...options,
87
99
  actions,
88
100
  overrides,
101
+ binding,
89
102
  toggleHelp: () => (help.helpOpen ? help.closeHelp() : help.openHelp())
90
103
  };
91
104
  });
@@ -94,6 +107,17 @@ export function ShortcutsProvider(props) {
94
107
  ...options.helpKeys
95
108
  ].join("|");
96
109
  useRegistration(live, signature);
110
+ }
111
+ /** Wraps the part of the app that has shortcuts: registers every action and holds what the help sheet and hints need. */
112
+ export function ShortcutsProvider(props) {
113
+ const { actions, children, notes = noNotes } = props;
114
+ const options = useResolved(props);
115
+ const [overrides, setOverrides, saveFailed] = useSavedOverrides(props, actions);
116
+ const { bind, binding } = useBindings();
117
+ const live = useRef({ ...options, actions, overrides, toggleHelp: () => { }, binding });
118
+ const help = useHelpState(live);
119
+ const [modHeld, setModHeld] = useModHeld(options.hints === "badges");
120
+ useRegistered(live, { options, actions, overrides, binding, help });
97
121
  const value = useMemo(() => ({
98
122
  ...help,
99
123
  actions,
@@ -107,10 +131,22 @@ export function ShortcutsProvider(props) {
107
131
  : [];
108
132
  },
109
133
  setOverrides,
110
- resetAll: () => setOverrides({}),
134
+ resetAll: () => setOverrides(withoutActions(overrides, actions)),
135
+ bind,
111
136
  saveFailed,
112
137
  modHeld,
113
138
  setModHeld
114
- }), [help, actions, notes, overrides, options, setOverrides, saveFailed, modHeld, setModHeld]);
139
+ }), [
140
+ help,
141
+ actions,
142
+ notes,
143
+ overrides,
144
+ options,
145
+ setOverrides,
146
+ saveFailed,
147
+ modHeld,
148
+ setModHeld,
149
+ bind
150
+ ]);
115
151
  return _jsx(ShortcutsContext, { value: value, children: children });
116
152
  }
@@ -1,4 +1,4 @@
1
- import { type Overrides, type ShortcutAction } from "./bindings";
1
+ import { type BoundShortcutAction, type Overrides, type ShortcutAction } from "./bindings";
2
2
  /** What the registered shortcuts read on every key press, kept fresh by the provider. */
3
3
  export interface Live {
4
4
  actions: readonly ShortcutAction[];
@@ -7,6 +7,8 @@ export interface Live {
7
7
  multipleKeys: boolean;
8
8
  helpKeys: readonly string[];
9
9
  toggleHelp: () => void;
10
+ /** The component bound to an action id right now: the one mounted last. */
11
+ binding: (id: string) => BoundShortcutAction | undefined;
10
12
  }
11
13
  /**
12
14
  * Registers one slot per key an action can hold, through ui-sdk. The keys are read on every key
@@ -15,11 +15,19 @@ function registerSlot(live, action, slot) {
15
15
  return current && (slot === 0 || live.current.multipleKeys)
16
16
  ? keysOf(current, live.current.overrides)[slot]
17
17
  : undefined;
18
- }, (event) => find()?.run(event), {
18
+ }, (event) => (live.current.binding(action.id)?.run ?? find()?.run)?.(event), {
19
19
  description: action.description,
20
20
  allowInInput: action.allowInInput ?? false,
21
21
  layer: action.overDialogs ? overDialogsLayer : undefined,
22
- when: () => calm(live) && (find()?.when?.() ?? true)
22
+ when: () => {
23
+ const bound = live.current.binding(action.id);
24
+ const declared = find();
25
+ /* Nothing to run means the key is left alone for whatever else wants it. */
26
+ return (calm(live) &&
27
+ (bound !== undefined || declared?.run !== undefined) &&
28
+ (declared?.when?.() ?? true) &&
29
+ (bound?.when?.() ?? true));
30
+ }
23
31
  });
24
32
  }
25
33
  /**
@@ -101,6 +101,11 @@
101
101
  border-block-end: 1px solid var(--kumiko-shortcuts-row-border);
102
102
  }
103
103
 
104
+ .kumiko-shortcuts-reason {
105
+ color: var(--kumiko-shortcuts-heading-fg);
106
+ font-size: 0.8125rem;
107
+ }
108
+
104
109
  .kumiko-shortcuts-list li[data-unavailable] .kumiko-shortcuts-name {
105
110
  opacity: 0.55;
106
111
  }
@@ -1,7 +1,7 @@
1
1
  export { DEFAULT_LIMIT, DEFAULT_MERGE_WINDOW, type History, type NewUndoEntry, type UndoEntry } from "./history";
2
2
  export { joinHistory, useUndoAdapter, type UndoAdapter } from "./undo-adapter";
3
3
  export { feedbackHandlers, showUndoToast, type FeedbackActions, type UndoToastTarget } from "./undo-feedback";
4
- export { isTypingTarget, undoFieldKeys, useUndoKeys, type UndoKeysOptions } from "./undo-keys";
4
+ export { isTypingTarget, undoFieldKeys, useUndoKeys, useUndoKeysWhen, type UndoKeysOptions } from "./undo-keys";
5
5
  export { DEFAULT_OPTIONS, type BusyMode, type Direction, type FeedbackMode, type KeyReach, type PlaceMode, type RevealMode, type RunInfo, type ToastUndoMode, type UndoHandlers, type UndoOptions } from "./undo-options";
6
6
  export { UndoButtons, UndoPanel, type PanelMode, type UndoPanelProps } from "./undo-panel";
7
7
  export { UndoProvider, useUndo, type UndoApi, type UndoProviderProps } from "./undo-provider";
@@ -1,7 +1,7 @@
1
1
  export { DEFAULT_LIMIT, DEFAULT_MERGE_WINDOW } from "./history";
2
2
  export { joinHistory, useUndoAdapter } from "./undo-adapter";
3
3
  export { feedbackHandlers, showUndoToast } from "./undo-feedback";
4
- export { isTypingTarget, undoFieldKeys, useUndoKeys } from "./undo-keys";
4
+ export { isTypingTarget, undoFieldKeys, useUndoKeys, useUndoKeysWhen } from "./undo-keys";
5
5
  export { DEFAULT_OPTIONS } from "./undo-options";
6
6
  export { UndoButtons, UndoPanel } from "./undo-panel";
7
7
  export { UndoProvider, useUndo } from "./undo-provider";
@@ -16,6 +16,13 @@ export interface UndoKeysOptions {
16
16
  }
17
17
  /** Whether a target is somewhere the browser has its own undo. */
18
18
  export declare function isTypingTarget(target: EventTarget | null): boolean;
19
+ /**
20
+ * The guard `useUndoKeys` uses, for an app that binds its own undo and redo actions: it says whether the keys
21
+ * may act right now. False while focus is in a text field, while a dialog or menu is open, while `blocked`
22
+ * says so, when `enabled` is false, and, when reach is "area", while focus is outside the area. It also keeps
23
+ * track of the area last touched. The function it returns is stable, and reads the latest options.
24
+ */
25
+ export declare function useUndoKeysWhen(options: UndoKeysOptions): () => boolean;
19
26
  /**
20
27
  * Registers mod+z, mod+shift+z and mod+y through ui-sdk's shortcuts. They stay quiet in text
21
28
  * fields (the browser's own undo keeps working there), while a dialog or menu is open, while a
@@ -1,6 +1,6 @@
1
1
  import { matchesShortcut } from "@ui-sdk/core";
2
2
  import { useShortcut } from "@ui-sdk/react/shortcuts";
3
- import { useEffect, useRef } from "react";
3
+ import { useCallback, useEffect, useRef } from "react";
4
4
  /** Whether a target is somewhere the browser has its own undo. */
5
5
  export function isTypingTarget(target) {
6
6
  return (target instanceof HTMLElement &&
@@ -33,13 +33,16 @@ function allowed(options) {
33
33
  return true;
34
34
  }
35
35
  /**
36
- * Registers mod+z, mod+shift+z and mod+y through ui-sdk's shortcuts. They stay quiet in text
37
- * fields (the browser's own undo keeps working there), while a dialog or menu is open, while a
38
- * drag runs, and, when reach is "area", while focus is outside the area.
36
+ * The guard `useUndoKeys` uses, for an app that binds its own undo and redo actions: it says whether the keys
37
+ * may act right now. False while focus is in a text field, while a dialog or menu is open, while `blocked`
38
+ * says so, when `enabled` is false, and, when reach is "area", while focus is outside the area. It also keeps
39
+ * track of the area last touched. The function it returns is stable, and reads the latest options.
39
40
  */
40
- export function useUndoKeys(actions, options) {
41
+ export function useUndoKeysWhen(options) {
41
42
  const latest = useRef(options);
42
- latest.current = options;
43
+ useEffect(() => {
44
+ latest.current = options;
45
+ });
43
46
  useEffect(() => {
44
47
  const note = (event) => {
45
48
  const area = latest.current.area?.current;
@@ -54,7 +57,15 @@ export function useUndoKeys(actions, options) {
54
57
  document.removeEventListener("focusin", note, true);
55
58
  };
56
59
  }, []);
57
- const when = () => allowed(latest.current);
60
+ return useCallback(() => allowed(latest.current), []);
61
+ }
62
+ /**
63
+ * Registers mod+z, mod+shift+z and mod+y through ui-sdk's shortcuts. They stay quiet in text
64
+ * fields (the browser's own undo keeps working there), while a dialog or menu is open, while a
65
+ * drag runs, and, when reach is "area", while focus is outside the area.
66
+ */
67
+ export function useUndoKeys(actions, options) {
68
+ const when = useUndoKeysWhen(options);
58
69
  useShortcut("mod+z", () => void actions.undo(), { when, description: "Undo" });
59
70
  useShortcut("mod+shift+z", () => void actions.redo(), { when, description: "Redo" });
60
71
  useShortcut("mod+y", () => void actions.redo(), { when, description: "Redo" });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alulore/kumiko",
3
- "version": "0.17.2",
3
+ "version": "0.17.3",
4
4
  "description": "Polished, cozy React components with gentle motion, built on ui-sdk. Every look and behaviour can be switched with props and CSS tokens.",
5
5
  "license": "MIT",
6
6
  "repository": {