@alulore/kumiko 0.15.1 → 0.17.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.
Files changed (91) hide show
  1. package/dist/media-viewer/icons.d.ts +4 -0
  2. package/dist/media-viewer/icons.js +18 -0
  3. package/dist/media-viewer/index.d.ts +4 -0
  4. package/dist/media-viewer/index.js +3 -0
  5. package/dist/media-viewer/media-slide.d.ts +14 -0
  6. package/dist/media-viewer/media-slide.js +67 -0
  7. package/dist/media-viewer/media-viewer.css +611 -0
  8. package/dist/media-viewer/media-viewer.d.ts +17 -0
  9. package/dist/media-viewer/media-viewer.js +241 -0
  10. package/dist/media-viewer/pager-drag.d.ts +10 -0
  11. package/dist/media-viewer/pager-drag.js +53 -0
  12. package/dist/media-viewer/types.d.ts +58 -0
  13. package/dist/media-viewer/types.js +17 -0
  14. package/dist/media-viewer/video-controls.d.ts +3 -0
  15. package/dist/media-viewer/video-controls.js +62 -0
  16. package/dist/media-viewer/view-gesture.d.ts +74 -0
  17. package/dist/media-viewer/view-gesture.js +465 -0
  18. package/dist/media-viewer/viewer-chrome.d.ts +13 -0
  19. package/dist/media-viewer/viewer-chrome.js +35 -0
  20. package/dist/media-viewer/viewer-motion.d.ts +9 -0
  21. package/dist/media-viewer/viewer-motion.js +126 -0
  22. package/dist/media-viewer/zoom-pan.d.ts +35 -0
  23. package/dist/media-viewer/zoom-pan.js +102 -0
  24. package/dist/shortcuts/bindings.d.ts +44 -0
  25. package/dist/shortcuts/bindings.js +71 -0
  26. package/dist/shortcuts/capture.d.ts +7 -0
  27. package/dist/shortcuts/capture.js +92 -0
  28. package/dist/shortcuts/guard.d.ts +9 -0
  29. package/dist/shortcuts/guard.js +48 -0
  30. package/dist/shortcuts/help.d.ts +25 -0
  31. package/dist/shortcuts/help.js +26 -0
  32. package/dist/shortcuts/hints.d.ts +19 -0
  33. package/dist/shortcuts/hints.js +33 -0
  34. package/dist/shortcuts/index.d.ts +11 -0
  35. package/dist/shortcuts/index.js +11 -0
  36. package/dist/shortcuts/judge.d.ts +42 -0
  37. package/dist/shortcuts/judge.js +34 -0
  38. package/dist/shortcuts/keys.d.ts +11 -0
  39. package/dist/shortcuts/keys.js +89 -0
  40. package/dist/shortcuts/list.d.ts +16 -0
  41. package/dist/shortcuts/list.js +43 -0
  42. package/dist/shortcuts/notes.d.ts +28 -0
  43. package/dist/shortcuts/notes.js +27 -0
  44. package/dist/shortcuts/provider.d.ts +98 -0
  45. package/dist/shortcuts/provider.js +116 -0
  46. package/dist/shortcuts/rebinder.d.ts +23 -0
  47. package/dist/shortcuts/rebinder.js +84 -0
  48. package/dist/shortcuts/registration.d.ts +19 -0
  49. package/dist/shortcuts/registration.js +84 -0
  50. package/dist/shortcuts/shortcuts.css +171 -0
  51. package/dist/stored/index.d.ts +4 -0
  52. package/dist/stored/index.js +4 -0
  53. package/dist/stored/storage.d.ts +22 -0
  54. package/dist/stored/storage.js +10 -0
  55. package/dist/stored/stored.d.ts +93 -0
  56. package/dist/stored/stored.js +209 -0
  57. package/dist/stored/use-stored.d.ts +6 -0
  58. package/dist/stored/use-stored.js +12 -0
  59. package/dist/stored/validators.d.ts +6 -0
  60. package/dist/stored/validators.js +13 -0
  61. package/dist/titlebar/index.d.ts +2 -0
  62. package/dist/titlebar/index.js +2 -0
  63. package/dist/titlebar/titlebar-looks.d.ts +53 -0
  64. package/dist/titlebar/titlebar-looks.js +26 -0
  65. package/dist/titlebar/titlebar.css +561 -0
  66. package/dist/titlebar/titlebar.d.ts +54 -0
  67. package/dist/titlebar/titlebar.js +68 -0
  68. package/dist/undo/history.d.ts +62 -0
  69. package/dist/undo/history.js +151 -0
  70. package/dist/undo/index.d.ts +10 -0
  71. package/dist/undo/index.js +10 -0
  72. package/dist/undo/undo-adapter.d.ts +35 -0
  73. package/dist/undo/undo-adapter.js +35 -0
  74. package/dist/undo/undo-feedback.d.ts +28 -0
  75. package/dist/undo/undo-feedback.js +69 -0
  76. package/dist/undo/undo-keys.d.ts +32 -0
  77. package/dist/undo/undo-keys.js +76 -0
  78. package/dist/undo/undo-options.d.ts +51 -0
  79. package/dist/undo/undo-options.js +6 -0
  80. package/dist/undo/undo-panel.d.ts +23 -0
  81. package/dist/undo/undo-panel.js +56 -0
  82. package/dist/undo/undo-provider.d.ts +88 -0
  83. package/dist/undo/undo-provider.js +104 -0
  84. package/dist/undo/undo-reveal.d.ts +9 -0
  85. package/dist/undo/undo-reveal.js +45 -0
  86. package/dist/undo/undo-store.d.ts +89 -0
  87. package/dist/undo/undo-store.js +243 -0
  88. package/dist/undo/undo.css +135 -0
  89. package/dist/undo/use-undo-value.d.ts +43 -0
  90. package/dist/undo/use-undo-value.js +85 -0
  91. package/package.json +42 -1
@@ -0,0 +1,89 @@
1
+ import { formatShortcut } from "@ui-sdk/react/shortcuts";
2
+ /* Modifiers in the order a shortcut writes them, so two spellings of one shortcut compare equal. */
3
+ const modifierOrder = ["mod", "meta", "control", "alt", "shift"];
4
+ const aliases = {
5
+ ctrl: "control",
6
+ cmd: "meta",
7
+ command: "meta",
8
+ option: "alt",
9
+ esc: "escape",
10
+ return: "enter",
11
+ spacebar: "space",
12
+ up: "arrowup",
13
+ down: "arrowdown",
14
+ left: "arrowleft",
15
+ right: "arrowright"
16
+ };
17
+ /** Keys that are never offered to people because they already mean something everywhere, and why. */
18
+ export const defaultReservedKeys = {
19
+ "mod+z": "Undo is on it in every text field.",
20
+ "mod+c": "Copy is on it.",
21
+ "mod+v": "Paste is on it.",
22
+ "mod+x": "Cut is on it.",
23
+ "mod+a": "Select all is on it.",
24
+ tab: "Tab moves focus, so it has to stay free.",
25
+ escape: "Escape closes things and cancels, so it has to stay free."
26
+ };
27
+ function part(raw) {
28
+ const lower = raw.length === 1 ? raw.toLowerCase() : raw.toLowerCase().trim();
29
+ return aliases[lower] ?? lower;
30
+ }
31
+ /** One spelling for a shortcut: lower case, modifiers first in a fixed order, so `mod+k` and `Mod + K` compare equal. */
32
+ export function canonicalKeys(keys) {
33
+ const parts = keys.split("+").map((raw) => part(raw));
34
+ const key = parts.at(-1) ?? "";
35
+ const modifiers = [...new Set(parts.slice(0, -1))].sort((a, b) => modifierOrder.indexOf(a) - modifierOrder.indexOf(b));
36
+ return [...modifiers, key].join("+");
37
+ }
38
+ /** Whether typed text is a usable shortcut: any modifiers, then exactly one key that is not a modifier. */
39
+ export function isValidKeys(keys) {
40
+ const parts = canonicalKeys(keys).split("+");
41
+ const key = parts.at(-1) ?? "";
42
+ return (key !== "" &&
43
+ !modifierOrder.includes(key) &&
44
+ parts.slice(0, -1).every((value) => modifierOrder.includes(value)));
45
+ }
46
+ export function onApple() {
47
+ return formatShortcut("mod").includes("⌘");
48
+ }
49
+ const ignoredKeys = new Set([
50
+ "Shift",
51
+ "Control",
52
+ "Alt",
53
+ "Meta",
54
+ "AltGraph",
55
+ "CapsLock",
56
+ "Dead",
57
+ "Unidentified"
58
+ ]);
59
+ /** The shortcut a key press spells, with `mod` for Command on Apple platforms and Control elsewhere. Null for a lone modifier. */
60
+ export function keysFromEvent(event) {
61
+ if (ignoredKeys.has(event.key)) {
62
+ return null;
63
+ }
64
+ let key = event.key === " " ? "space" : part(event.key);
65
+ /* A letter or digit is named by its physical key, so Option+N on a Mac is still n. */
66
+ const code = /^(?:Key(?<letter>[A-Z])|Digit(?<digit>\d))$/u.exec(event.code);
67
+ if (code) {
68
+ key = (code.groups?.letter ?? code.groups?.digit ?? key).toLowerCase();
69
+ }
70
+ const apple = onApple();
71
+ const modifiers = [];
72
+ if (apple ? event.metaKey : event.ctrlKey) {
73
+ modifiers.push("mod");
74
+ }
75
+ if (apple ? event.ctrlKey : event.metaKey) {
76
+ modifiers.push(apple ? "control" : "meta");
77
+ }
78
+ if (event.altKey) {
79
+ modifiers.push("alt");
80
+ }
81
+ if (event.shiftKey) {
82
+ modifiers.push("shift");
83
+ }
84
+ return canonicalKeys([...modifiers, key].join("+"));
85
+ }
86
+ /** Keys as this platform writes them, for sentences that name them. */
87
+ export function describeKeys(keys) {
88
+ return formatShortcut(keys);
89
+ }
@@ -0,0 +1,16 @@
1
+ export interface ShortcutsListProps {
2
+ /**
3
+ * Whether keys can be changed here: a Change button on every key, Add another, Reset.
4
+ * @defaultValue false
5
+ */
6
+ editing?: boolean;
7
+ /**
8
+ * Whether to list every action. Without it, only the actions that could run when the help sheet opened.
9
+ * @defaultValue true when `editing`, false otherwise
10
+ */
11
+ all?: boolean;
12
+ /** Keeps only actions whose name or section contains this text. */
13
+ query?: string;
14
+ }
15
+ /** 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;
@@ -0,0 +1,43 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Kbd } from "../kbd";
3
+ import { defaultKeys, maxKeysPerAction } from "./bindings";
4
+ import { Capture } from "./capture";
5
+ import { noteKeys, sectionRows } from "./notes";
6
+ import { useShortcuts } from "./provider";
7
+ import { useRebinder } from "./rebinder";
8
+ function sameKeys(action, keys) {
9
+ const defaults = defaultKeys(action);
10
+ return keys.length === defaults.length && keys.every((key, index) => key === defaults[index]);
11
+ }
12
+ function KeyChip({ action, slot, removable, rebinder }) {
13
+ const { keysFor } = useShortcuts();
14
+ const key = keysFor(action.id)[slot] ?? "";
15
+ const { target } = rebinder;
16
+ const changing = target?.id === action.id && target.slot === slot;
17
+ return (_jsxs("span", { className: "kumiko-shortcuts-key", "data-changing": changing ? "" : undefined, children: [_jsx(Kbd, { keys: key, listen: false }), _jsx("button", { type: "button", "aria-label": `Change ${key} for ${action.description}`, onClick: () => rebinder.begin({ id: action.id, slot }), children: "Change" }), removable ? (_jsx("button", { type: "button", "aria-label": `Remove ${key} from ${action.description}`, onClick: () => rebinder.remove(action.id, slot), children: "Remove" })) : null] }));
18
+ }
19
+ function KeyEditor({ action, rebinder }) {
20
+ const { keysFor, options } = useShortcuts();
21
+ const keys = keysFor(action.id);
22
+ const canAdd = options.multipleKeys ? keys.length < maxKeysPerAction : keys.length === 0;
23
+ return (_jsxs("div", { className: "kumiko-shortcuts-editor", children: [keys.map((key, slot) => (_jsx(KeyChip, { action: action, slot: slot, removable: keys.length > 1, rebinder: rebinder }, key))), keys.length === 0 ? _jsx("span", { className: "kumiko-shortcuts-none", children: "No keys" }) : null, canAdd ? (_jsx("button", { type: "button", onClick: () => rebinder.begin({ id: action.id, slot: -1 }), children: keys.length === 0 ? "Set keys" : "Add another" })) : null, options.resetEach && !sameKeys(action, keys) ? (_jsx("button", { type: "button", onClick: () => rebinder.reset(action.id), children: "Reset" })) : null] }));
24
+ }
25
+ function Row({ action, editing, rebinder }) {
26
+ const { keysFor, available } = useShortcuts();
27
+ 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] }));
28
+ }
29
+ function NoteRow({ note }) {
30
+ 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))) })] }));
31
+ }
32
+ function EditFooter() {
33
+ const { resetAll, overrides, options, saveFailed } = useShortcuts();
34
+ 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", { type: "button", onClick: resetAll, children: "Reset all" }) })) : null, options.multipleKeys ? null : (_jsx("p", { className: "kumiko-shortcuts-empty", children: "Each action has one key." }))] }));
35
+ }
36
+ /** The actions grouped by section, each with its keys. With `editing`, every key can be changed. */
37
+ export function ShortcutsList({ editing = false, all = editing, query = "" }) {
38
+ const { actions, notes, available } = useShortcuts();
39
+ const rebinder = useRebinder();
40
+ const needle = query.trim().toLowerCase();
41
+ const sections = sectionRows(actions, notes, (action) => all || available.has(action.id), needle);
42
+ 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] }));
43
+ }
@@ -0,0 +1,28 @@
1
+ import type { ShortcutAction } from "./bindings";
2
+ /** A key listed in the help sheet for people to read. It is never registered or rebound. */
3
+ export interface ShortcutNote {
4
+ /** What the key does, shown in the help sheet. */
5
+ description: string;
6
+ /** The heading it sits under, next to the actions of the same section. */
7
+ section: string;
8
+ /** The keys, one or several, written like `"mod+k"`. */
9
+ keys: string | readonly string[];
10
+ }
11
+ /** One line of the help sheet: an action people can rebind, or a note they can only read. */
12
+ export type ShortcutRow = {
13
+ kind: "action";
14
+ action: ShortcutAction;
15
+ } | {
16
+ kind: "note";
17
+ note: ShortcutNote;
18
+ };
19
+ export interface ShortcutSection {
20
+ section: string;
21
+ rows: ShortcutRow[];
22
+ }
23
+ /**
24
+ * The rows to show, grouped by section in the order sections first appear (actions, then notes). Inside a
25
+ * section the actions come first, then the notes. Notes are always shown, and a search still filters them by text.
26
+ */
27
+ export declare function sectionRows(actions: readonly ShortcutAction[], notes: readonly ShortcutNote[], keepAction: (action: ShortcutAction) => boolean, needle: string): ShortcutSection[];
28
+ export declare function noteKeys(note: ShortcutNote): string[];
@@ -0,0 +1,27 @@
1
+ function matches(text, needle) {
2
+ return needle === "" || text.toLowerCase().includes(needle);
3
+ }
4
+ function sectionOf(row) {
5
+ return row.kind === "action" ? row.action.section : row.note.section;
6
+ }
7
+ /**
8
+ * The rows to show, grouped by section in the order sections first appear (actions, then notes). Inside a
9
+ * section the actions come first, then the notes. Notes are always shown, and a search still filters them by text.
10
+ */
11
+ export function sectionRows(actions, notes, keepAction, needle) {
12
+ const rows = [
13
+ ...actions
14
+ .filter((action) => keepAction(action) && matches(`${action.description} ${action.section}`, needle))
15
+ .map((action) => ({ kind: "action", action })),
16
+ ...notes
17
+ .filter((note) => matches(`${note.description} ${note.section}`, needle))
18
+ .map((note) => ({ kind: "note", note }))
19
+ ];
20
+ return [...new Set(rows.map((row) => sectionOf(row)))].map((section) => ({
21
+ section,
22
+ rows: rows.filter((row) => sectionOf(row) === section)
23
+ }));
24
+ }
25
+ export function noteKeys(note) {
26
+ return typeof note.keys === "string" ? [note.keys] : [...note.keys];
27
+ }
@@ -0,0 +1,98 @@
1
+ import { type StoredStorage } from "../stored";
2
+ import { type Overrides, type ShortcutAction } from "./bindings";
3
+ import type { ShortcutNote } from "./notes";
4
+ export type TakenKeys = "ask" | "refuse" | "newest";
5
+ export type ReservedMode = "block" | "warn";
6
+ export type CaptureMode = "press" | "type" | "list";
7
+ export type HintMode = "tooltip" | "badges" | "none";
8
+ /** Every choice the shortcuts offer. Each one has a default, the one the family leans towards. */
9
+ export interface ShortcutsOptions {
10
+ /**
11
+ * Where changed keys are saved: "local", "session", or a backend factory (see `@alulore/kumiko/stored`).
12
+ * @defaultValue "local"
13
+ */
14
+ storage?: StoredStorage;
15
+ /**
16
+ * The key the changed keys are saved under.
17
+ * @defaultValue "kumiko.shortcuts"
18
+ */
19
+ storageKey?: string;
20
+ /** Called when saving the changed keys fails (storage blocked or full). The sheet also says so. */
21
+ onSaveError?: () => void;
22
+ /**
23
+ * Whether page shortcuts wait while a drag (reported with `reportDrag`) or a menu is open. Modals always pause them.
24
+ * @defaultValue true
25
+ */
26
+ pauseWhileBusy?: boolean;
27
+ /**
28
+ * The keys that open the help sheet. Empty leaves the button as the only way.
29
+ * @defaultValue ["shift+?", "mod+/"]
30
+ */
31
+ helpKeys?: readonly string[];
32
+ /**
33
+ * Where an action's keys are shown on its control: as badges while the mod key is held (a touch app
34
+ * adds `ShortcutBadgesButton`), in a tooltip, or nowhere.
35
+ * @defaultValue "badges"
36
+ */
37
+ hints?: HintMode;
38
+ /**
39
+ * Whether an action can hold more than one key.
40
+ * @defaultValue true
41
+ */
42
+ multipleKeys?: boolean;
43
+ /**
44
+ * What happens when new keys already belong to another action: ask (swap, replace or cancel), refuse, or let the newest win.
45
+ * @defaultValue "ask"
46
+ */
47
+ taken?: TakenKeys;
48
+ /**
49
+ * Whether reserved keys are blocked, or allowed after a warning.
50
+ * @defaultValue "block"
51
+ */
52
+ reserved?: ReservedMode;
53
+ /** The reserved keys and why, in place of the defaults (mod+z, mod+c, mod+v, mod+x, mod+a, tab, escape). */
54
+ reservedKeys?: Readonly<Record<string, string>>;
55
+ /**
56
+ * How new keys are given: press them, type them as text, or pick from a list.
57
+ * @defaultValue "press"
58
+ */
59
+ capture?: CaptureMode;
60
+ /**
61
+ * Whether each action has its own reset, besides Reset all.
62
+ * @defaultValue true
63
+ */
64
+ resetEach?: boolean;
65
+ /**
66
+ * Keys that work only on a focused widget and are handled there. They are listed in the help sheet for people to
67
+ * read, under their section, and are never registered, rebound or hidden by what can run.
68
+ * @defaultValue []
69
+ */
70
+ notes?: readonly ShortcutNote[];
71
+ }
72
+ export interface ShortcutsContextValue {
73
+ actions: readonly ShortcutAction[];
74
+ overrides: Overrides;
75
+ options: Required<Omit<ShortcutsOptions, "storage" | "storageKey" | "onSaveError" | "notes">>;
76
+ /** The read-only entries of the help sheet. */
77
+ notes: readonly ShortcutNote[];
78
+ keysFor: (id: string) => string[];
79
+ setOverrides: (next: Overrides) => void;
80
+ resetAll: () => void;
81
+ helpOpen: boolean;
82
+ openHelp: () => void;
83
+ closeHelp: () => void;
84
+ /** Ids of the actions that could run when the help sheet opened. */
85
+ available: ReadonlySet<string>;
86
+ /** Whether the last attempt to save the changed keys failed. */
87
+ saveFailed: boolean;
88
+ modHeld: boolean;
89
+ setModHeld: (held: boolean) => void;
90
+ }
91
+ export declare function useShortcuts(): ShortcutsContextValue;
92
+ export type ShortcutsProviderProps = ShortcutsOptions & {
93
+ /** What the app can do, and the keys that do it. */
94
+ actions: readonly ShortcutAction[];
95
+ children?: React.ReactNode;
96
+ };
97
+ /** Wraps the part of the app that has shortcuts: registers every action and holds what the help sheet and hints need. */
98
+ export declare function ShortcutsProvider(props: ShortcutsProviderProps): React.JSX.Element;
@@ -0,0 +1,116 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, use, useCallback, useEffect, useMemo, useRef, useState } from "react";
3
+ import { defineStored, useStored } from "../stored";
4
+ import { isOverrides, keysOf, sanitizeOverrides } from "./bindings";
5
+ import { defaultReservedKeys } from "./keys";
6
+ import { listAvailable, useModHeld, useRegistration } from "./registration";
7
+ const ShortcutsContext = createContext(null);
8
+ export function useShortcuts() {
9
+ const value = use(ShortcutsContext);
10
+ if (!value) {
11
+ throw new Error("Shortcuts components need a ShortcutsProvider around them.");
12
+ }
13
+ return value;
14
+ }
15
+ /** The saved bindings, followed live, and what to call to change them. A failed save is reported. */
16
+ function useSavedOverrides(props, actions) {
17
+ const { storage = "local", storageKey = "kumiko.shortcuts", onSaveError } = props;
18
+ const definition = useMemo(() => defineStored({
19
+ key: storageKey,
20
+ fallback: {},
21
+ validate: isOverrides,
22
+ storage
23
+ }), [storageKey, storage]);
24
+ const [saved, set, status, reset] = useStored(definition);
25
+ const overrides = useMemo(() => sanitizeOverrides(saved, actions), [saved, actions]);
26
+ const failure = useRef(onSaveError);
27
+ useEffect(() => {
28
+ failure.current = onSaveError;
29
+ });
30
+ useEffect(() => {
31
+ if (status.writeFailed) {
32
+ failure.current?.();
33
+ }
34
+ }, [status.writeFailed]);
35
+ const write = useCallback((next) => (Object.keys(next).length === 0 ? reset() : set(next)), [set, reset]);
36
+ return [overrides, write, status.writeFailed];
37
+ }
38
+ const defaultHelpKeys = ["shift+?", "mod+/"];
39
+ const noNotes = [];
40
+ /** Fills in every option's default, and keeps the object the same while the choices are. */
41
+ function useResolved(props) {
42
+ const { pauseWhileBusy = true, helpKeys = defaultHelpKeys, hints = "badges", multipleKeys = true, taken = "ask", reserved = "block", reservedKeys = defaultReservedKeys, capture = "press", resetEach = true } = props;
43
+ return useMemo(() => ({
44
+ pauseWhileBusy,
45
+ helpKeys,
46
+ hints,
47
+ multipleKeys,
48
+ taken,
49
+ reserved,
50
+ reservedKeys,
51
+ capture,
52
+ resetEach
53
+ }), [
54
+ pauseWhileBusy,
55
+ helpKeys,
56
+ hints,
57
+ multipleKeys,
58
+ taken,
59
+ reserved,
60
+ reservedKeys,
61
+ capture,
62
+ resetEach
63
+ ]);
64
+ }
65
+ /** 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
+ function useHelpState(live) {
67
+ const [helpOpen, setHelpOpen] = useState(false);
68
+ const [available, setAvailable] = useState(new Set());
69
+ const openHelp = useCallback(() => {
70
+ setAvailable(listAvailable(live));
71
+ setHelpOpen(true);
72
+ }, [live]);
73
+ const closeHelp = useCallback(() => setHelpOpen(false), []);
74
+ return useMemo(() => ({ helpOpen, available, openHelp, closeHelp }), [helpOpen, available, openHelp, closeHelp]);
75
+ }
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");
84
+ useEffect(() => {
85
+ live.current = {
86
+ ...options,
87
+ actions,
88
+ overrides,
89
+ toggleHelp: () => (help.helpOpen ? help.closeHelp() : help.openHelp())
90
+ };
91
+ });
92
+ const signature = [
93
+ ...actions.map((action) => `${action.id}:${action.description}:${action.allowInInput}`),
94
+ ...options.helpKeys
95
+ ].join("|");
96
+ useRegistration(live, signature);
97
+ const value = useMemo(() => ({
98
+ ...help,
99
+ actions,
100
+ notes,
101
+ overrides,
102
+ options,
103
+ keysFor: (id) => {
104
+ const action = actions.find((item) => item.id === id);
105
+ return action
106
+ ? keysOf(action, overrides).slice(0, options.multipleKeys ? undefined : 1)
107
+ : [];
108
+ },
109
+ setOverrides,
110
+ resetAll: () => setOverrides({}),
111
+ saveFailed,
112
+ modHeld,
113
+ setModHeld
114
+ }), [help, actions, notes, overrides, options, setOverrides, saveFailed, modHeld, setModHeld]);
115
+ return _jsx(ShortcutsContext, { value: value, children: children });
116
+ }
@@ -0,0 +1,23 @@
1
+ import { type Resolution } from "./bindings";
2
+ import { type Pending, type Target } from "./judge";
3
+ export type { Pending, Target } from "./judge";
4
+ export interface Rebinder {
5
+ target: Target | null;
6
+ pending: Pending | null;
7
+ /** Why the last keys were not taken. */
8
+ message: string | null;
9
+ begin: (target: Target) => void;
10
+ cancel: () => void;
11
+ /** Offers new keys for the current target. */
12
+ submit: (keys: string, allowReserved?: boolean) => void;
13
+ /** Starts changing a key and offers the new keys at once, for a control that rebinds without capturing. */
14
+ offer: (target: Target, keys: string) => void;
15
+ /** Answers the question about keys another action has: swap, or replace. */
16
+ resolve: (how: Exclude<Resolution, "plain">) => void;
17
+ /** Answers the warning about a reserved key: use it anyway. */
18
+ useAnyway: () => void;
19
+ remove: (id: string, slot: number) => void;
20
+ reset: (id: string) => void;
21
+ }
22
+ /** The state of changing one key: capture, conflicts, reserved keys, and writing the result. */
23
+ export declare function useRebinder(): Rebinder;
@@ -0,0 +1,84 @@
1
+ import { useState } from "react";
2
+ import { bindKeys, resetAction, unbindKey } from "./bindings";
3
+ import { judge } from "./judge";
4
+ import { useShortcuts } from "./provider";
5
+ /** Carries out a verdict: bind the keys, ask the question, or say why not. */
6
+ function settle(verdict, at, handlers) {
7
+ if (verdict.kind === "unchanged") {
8
+ handlers.cancel();
9
+ }
10
+ else if (verdict.kind === "bind") {
11
+ handlers.apply(at, verdict.keys, verdict.how);
12
+ }
13
+ else if (verdict.kind === "ask") {
14
+ handlers.setPending(verdict.pending);
15
+ }
16
+ else {
17
+ handlers.setMessage(verdict.message);
18
+ }
19
+ }
20
+ /** Which key is being changed, the question waiting on an answer, and why the last keys were refused. */
21
+ function useChange() {
22
+ const [target, setTarget] = useState(null);
23
+ const [pending, setPending] = useState(null);
24
+ const [message, setMessage] = useState(null);
25
+ const begin = (next) => {
26
+ setTarget(next);
27
+ setPending(null);
28
+ setMessage(null);
29
+ };
30
+ const cancel = () => {
31
+ setTarget(null);
32
+ setPending(null);
33
+ setMessage(null);
34
+ };
35
+ return { target, pending, message, begin, cancel, setPending, setMessage };
36
+ }
37
+ /** The state of changing one key: capture, conflicts, reserved keys, and writing the result. */
38
+ export function useRebinder() {
39
+ const context = useShortcuts();
40
+ const { actions, overrides, setOverrides } = context;
41
+ const { target, pending, message, begin, cancel, setPending, setMessage } = useChange();
42
+ const apply = (at, keys, how) => {
43
+ if (at) {
44
+ setOverrides(bindKeys(actions, overrides, { ...at, keys, how }));
45
+ }
46
+ cancel();
47
+ };
48
+ const submit = (raw, allowReserved = false, at = target) => {
49
+ if (!at) {
50
+ return;
51
+ }
52
+ settle(judge(context, at, raw, allowReserved), at, {
53
+ apply,
54
+ cancel,
55
+ setPending,
56
+ setMessage
57
+ });
58
+ };
59
+ return {
60
+ target,
61
+ pending,
62
+ message,
63
+ begin,
64
+ cancel,
65
+ submit,
66
+ offer: (at, keys) => {
67
+ begin(at);
68
+ submit(keys, false, at);
69
+ },
70
+ resolve: (how) => {
71
+ if (pending?.kind === "taken") {
72
+ apply(target, pending.keys, how);
73
+ }
74
+ },
75
+ useAnyway: () => {
76
+ if (pending?.kind === "reserved") {
77
+ setPending(null);
78
+ submit(pending.keys, true);
79
+ }
80
+ },
81
+ remove: (id, slot) => setOverrides(unbindKey(actions, overrides, id, slot)),
82
+ reset: (id) => setOverrides(resetAction(overrides, id))
83
+ };
84
+ }
@@ -0,0 +1,19 @@
1
+ import { type Overrides, type ShortcutAction } from "./bindings";
2
+ /** What the registered shortcuts read on every key press, kept fresh by the provider. */
3
+ export interface Live {
4
+ actions: readonly ShortcutAction[];
5
+ overrides: Overrides;
6
+ pauseWhileBusy: boolean;
7
+ multipleKeys: boolean;
8
+ helpKeys: readonly string[];
9
+ toggleHelp: () => void;
10
+ }
11
+ /**
12
+ * Registers one slot per key an action can hold, through ui-sdk. The keys are read on every key
13
+ * press, so rebinding needs no re-registering.
14
+ */
15
+ export declare function useRegistration(live: React.RefObject<Live>, signature: string): void;
16
+ /** The ids of the actions that could run right now, according to ui-sdk's list. */
17
+ export declare function listAvailable(live: React.RefObject<Live>): Set<string>;
18
+ /** Whether the mod key is held, for the badges. Off unless `enabled`. */
19
+ export declare function useModHeld(enabled: boolean): [boolean, (held: boolean) => void];
@@ -0,0 +1,84 @@
1
+ import { registerShortcut, shortcuts } from "@ui-sdk/react/shortcuts";
2
+ import { useEffect, useState } from "react";
3
+ import { keysOf, maxKeysPerAction } from "./bindings";
4
+ import { isDragging, isMenuOpen } from "./guard";
5
+ import { canonicalKeys, onApple } from "./keys";
6
+ /** Whether page shortcuts may run: not while a drag or a menu is open, unless the app turned that off. */
7
+ function calm(live) {
8
+ return !live.current.pauseWhileBusy || (!isDragging() && !isMenuOpen());
9
+ }
10
+ function registerSlot(live, action, slot) {
11
+ const find = () => live.current.actions.find((item) => item.id === action.id);
12
+ return registerShortcut(() => {
13
+ const current = find();
14
+ return current && (slot === 0 || live.current.multipleKeys)
15
+ ? keysOf(current, live.current.overrides)[slot]
16
+ : undefined;
17
+ }, (event) => find()?.run(event), {
18
+ description: action.description,
19
+ allowInInput: action.allowInInput ?? false,
20
+ when: () => calm(live) && (find()?.when?.() ?? true)
21
+ });
22
+ }
23
+ /**
24
+ * Registers one slot per key an action can hold, through ui-sdk. The keys are read on every key
25
+ * press, so rebinding needs no re-registering.
26
+ */
27
+ export function useRegistration(live, signature) {
28
+ useEffect(() => {
29
+ const offs = [];
30
+ for (const action of live.current.actions) {
31
+ for (let slot = 0; slot < maxKeysPerAction; slot += 1) {
32
+ offs.push(registerSlot(live, action, slot));
33
+ }
34
+ }
35
+ for (const [slot] of live.current.helpKeys.entries()) {
36
+ offs.push(registerShortcut(() => live.current.helpKeys[slot], () => live.current.toggleHelp(), { description: "Show keyboard shortcuts", when: () => calm(live) }));
37
+ }
38
+ return () => {
39
+ for (const off of offs) {
40
+ off();
41
+ }
42
+ };
43
+ }, [live, signature]);
44
+ }
45
+ /** The ids of the actions that could run right now, according to ui-sdk's list. */
46
+ export function listAvailable(live) {
47
+ const listed = shortcuts.list();
48
+ return new Set(live.current.actions
49
+ .filter((action) => listed.some((entry) => entry.description === action.description &&
50
+ keysOf(action, live.current.overrides).includes(canonicalKeys(entry.keys))))
51
+ .map((action) => action.id));
52
+ }
53
+ /** Whether the mod key is held, for the badges. Off unless `enabled`. */
54
+ export function useModHeld(enabled) {
55
+ const [held, setHeld] = useState(false);
56
+ useEffect(() => {
57
+ if (!enabled) {
58
+ return undefined;
59
+ }
60
+ const modKey = onApple() ? "Meta" : "Control";
61
+ const down = (event) => {
62
+ if (event.key === modKey) {
63
+ setHeld(true);
64
+ }
65
+ };
66
+ const release = () => setHeld(false);
67
+ /* Only the mod key's own release hides the badges, so a key pressed while it is down changes nothing. */
68
+ const up = (event) => {
69
+ if (event.key === modKey) {
70
+ release();
71
+ }
72
+ };
73
+ window.addEventListener("keydown", down);
74
+ window.addEventListener("keyup", up);
75
+ window.addEventListener("blur", release);
76
+ return () => {
77
+ window.removeEventListener("keydown", down);
78
+ window.removeEventListener("keyup", up);
79
+ window.removeEventListener("blur", release);
80
+ setHeld(false);
81
+ };
82
+ }, [enabled]);
83
+ return [enabled && held, setHeld];
84
+ }