@alulore/kumiko 0.17.1 → 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
+ }
@@ -1,5 +1,7 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useEffect, useRef, useState } from "react";
3
+ import { Button } from "../button";
4
+ import { Input } from "../input";
3
5
  import { canonicalKeys, describeKeys, isValidKeys, keysFromEvent } from "./keys";
4
6
  import { useShortcuts } from "./provider";
5
7
  /** Keys offered when capturing by picking from a list. */
@@ -40,7 +42,7 @@ function PressCapture({ rebinder }) {
40
42
  window.addEventListener("keydown", onKey, true);
41
43
  return () => window.removeEventListener("keydown", onKey, true);
42
44
  }, [submit, cancel, escapeCancels]);
43
- return (_jsxs("p", { className: "kumiko-shortcuts-capture", "data-mode": "press", children: [escapeCancels ? "Press the new keys. Esc cancels." : "Press the new keys.", _jsx("button", { type: "button", onClick: cancel, children: "Cancel" })] }));
45
+ return (_jsxs("p", { className: "kumiko-shortcuts-capture", "data-mode": "press", children: [escapeCancels ? "Press the new keys. Esc cancels." : "Press the new keys.", _jsx(Button, { variant: "ghost", size: "sm", type: "button", onClick: cancel, children: "Cancel" })] }));
44
46
  }
45
47
  function TypeCapture({ rebinder }) {
46
48
  const [text, setText] = useState("");
@@ -51,17 +53,20 @@ function TypeCapture({ rebinder }) {
51
53
  if (isValidKeys(text)) {
52
54
  rebinder.submit(text);
53
55
  }
54
- }, children: [_jsx("input", { "aria-label": "New keys, like mod+shift+k", placeholder: "mod+shift+k", ref: input, value: text, onChange: (event) => setText(event.target.value) }), _jsx("button", { type: "submit", disabled: !isValidKeys(text), children: "Use" }), _jsx("button", { type: "button", onClick: rebinder.cancel, children: "Cancel" })] }));
56
+ }, children: [_jsx(Input, { "aria-label": "New keys, like mod+shift+k", placeholder: "mod+shift+k", ref: input, value: text, onChange: (event) => setText(event.target.value) }), _jsx(Button, { variant: "solid", size: "sm", type: "submit", disabled: !isValidKeys(text), children: "Use" }), _jsx(Button, { variant: "ghost", size: "sm", type: "button", onClick: rebinder.cancel, children: "Cancel" })] }));
55
57
  }
56
58
  function ListCapture({ rebinder }) {
57
59
  const [choice, setChoice] = useState("");
58
- return (_jsxs("div", { className: "kumiko-shortcuts-capture", "data-mode": "list", children: [_jsxs("select", { "aria-label": "New keys", value: choice, onChange: (event) => setChoice(event.target.value), children: [_jsx("option", { value: "", children: "Pick keys\u2026" }), suggestions.map((keys) => (_jsx("option", { value: keys, children: describeKeys(keys) }, keys)))] }), _jsx("button", { type: "button", disabled: choice === "", onClick: () => rebinder.submit(choice), children: "Use" }), _jsx("button", { type: "button", onClick: rebinder.cancel, children: "Cancel" })] }));
60
+ return (_jsxs("div", { className: "kumiko-shortcuts-capture", "data-mode": "list", children: [_jsxs("select", { "aria-label": "New keys", value: choice, onChange: (event) => setChoice(event.target.value), children: [_jsx("option", { value: "", children: "Pick keys\u2026" }), suggestions.map((keys) => (_jsx("option", { value: keys, children: describeKeys(keys) }, keys)))] }), _jsx(Button, { variant: "solid", size: "sm", type: "button", disabled: choice === "", onClick: () => rebinder.submit(choice), children: "Use" }), _jsx(Button, { variant: "ghost", size: "sm", type: "button", onClick: rebinder.cancel, children: "Cancel" })] }));
61
+ }
62
+ function Answers({ rebinder, kind }) {
63
+ return (_jsx(_Fragment, { children: kind === "taken" ? (_jsxs(_Fragment, { children: [_jsx(Button, { variant: "solid", size: "sm", type: "button", onClick: () => rebinder.resolve("swap"), children: "Swap" }), _jsx(Button, { variant: "outline", size: "sm", type: "button", onClick: () => rebinder.resolve("replace"), children: "Replace" })] })) : (_jsx(Button, { variant: "outline", size: "sm", type: "button", onClick: rebinder.useAnyway, children: "Use anyway" })) }));
59
64
  }
60
65
  function Question({ rebinder, pending }) {
61
66
  const { actions } = useShortcuts();
62
67
  const mine = actions.find((action) => action.id === rebinder.target?.id)?.description ?? "";
63
68
  const keys = describeKeys(pending.keys);
64
- return (_jsxs("div", { className: "kumiko-shortcuts-capture", "data-mode": pending.kind, role: "alert", children: [pending.kind === "taken" ? (_jsxs("p", { children: [keys, " already runs \u201C", pending.owner.description, "\u201D. Swap gives it the keys \u201C", mine, "\u201D had. Replace takes ", keys, " away from it."] })) : (_jsxs("p", { children: [keys, " is reserved. ", pending.reason] })), pending.kind === "taken" ? (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", onClick: () => rebinder.resolve("swap"), children: "Swap" }), _jsx("button", { type: "button", onClick: () => rebinder.resolve("replace"), children: "Replace" })] })) : (_jsx("button", { type: "button", onClick: rebinder.useAnyway, children: "Use anyway" })), _jsx("button", { type: "button", onClick: rebinder.cancel, children: "Cancel" })] }));
69
+ return (_jsxs("div", { className: "kumiko-shortcuts-capture", "data-mode": pending.kind, role: "alert", children: [pending.kind === "taken" ? (_jsxs("p", { children: [keys, " already runs \u201C", pending.owner.description, "\u201D. Swap gives it the keys \u201C", mine, "\u201D had. Replace takes ", keys, " away from it."] })) : (_jsxs("p", { children: [keys, " is reserved. ", pending.reason] })), _jsx(Answers, { rebinder: rebinder, kind: pending.kind }), _jsx(Button, { variant: "ghost", size: "sm", type: "button", onClick: rebinder.cancel, children: "Cancel" })] }));
65
70
  }
66
71
  /** What shows under an action while its key is being changed: the capture, and the answer to a conflict. */
67
72
  export function Capture({ rebinder, bare = false }) {
@@ -19,11 +19,27 @@ export type ShortcutsHelpProps = TriggerProps & {
19
19
  * @defaultValue "Shortcuts"
20
20
  */
21
21
  label?: React.ReactNode;
22
+ /**
23
+ * The heading of the sheet.
24
+ * @defaultValue "Shortcuts"
25
+ */
26
+ title?: React.ReactNode;
27
+ /**
28
+ * A line under the heading. Without it the sheet shows none.
29
+ * @defaultValue undefined
30
+ */
31
+ description?: React.ReactNode;
22
32
  /** A class for the button. */
23
33
  className?: string;
24
34
  };
25
35
  /** A button that opens the help sheet: what can run now, by section. Its keys (`helpKeys`) open it too. */
26
- export declare function ShortcutsHelp({ presentation, editable, label, className, ...trigger }: ShortcutsHelpProps): React.JSX.Element;
36
+ export declare function ShortcutsHelp({ presentation, editable, label, title, description, className, ...trigger }: ShortcutsHelpProps): React.JSX.Element;
27
37
  /** Rebinding on its own, for apps that keep it in a settings page instead of the help sheet. */
28
- 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;
29
45
  export {};
@@ -1,26 +1,36 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useState } from "react";
3
+ import { Button } from "../button";
3
4
  import { Dialog, DialogBackdrop, DialogClose, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from "../dialog";
5
+ import { SearchInput } from "../input";
6
+ import { Kbd } from "../kbd";
4
7
  import { Popover, PopoverContent, PopoverDescription, PopoverTitle, PopoverTrigger } from "../popover";
5
8
  import { ShortcutsList } from "./list";
6
9
  import { useShortcuts } from "./provider";
7
- function Body({ presentation, editable }) {
10
+ /** How the keys that open the sheet read, as the person sees them elsewhere: Shift+? and Ctrl+/. */
11
+ function OpensWith({ keys }) {
12
+ if (keys.length === 0) {
13
+ return null;
14
+ }
15
+ return (_jsxs("p", { className: "kumiko-shortcuts-foot", children: ["Opens with", " ", keys.map((key, index) => (_jsxs("span", { children: [index > 0 ? " or " : null, _jsx(Kbd, { keys: key, listen: false })] }, key)))] }));
16
+ }
17
+ function Body({ presentation, editable, closer }) {
8
18
  const [editing, setEditing] = useState(false);
9
19
  const [query, setQuery] = useState("");
10
20
  const { options } = useShortcuts();
11
- const help = options.helpKeys;
12
- return (_jsxs("div", { className: "kumiko-shortcuts-sheet", "data-presentation": presentation, children: [presentation === "dialog" ? (_jsx("input", { type: "search", "aria-label": "Search shortcuts", placeholder: "Search shortcuts", value: query, onChange: (event) => setQuery(event.target.value) })) : null, _jsx(ShortcutsList, { editing: editing, all: editing, query: query }), help.length > 0 ? (_jsxs("p", { className: "kumiko-shortcuts-foot", children: ["This sheet opens with ", help.join(" or "), "."] })) : null, editable ? (_jsx("button", { type: "button", onClick: () => setEditing((now) => !now), children: editing ? "Done" : "Edit keys" })) : null] }));
21
+ return (_jsxs("div", { className: "kumiko-shortcuts-sheet", "data-presentation": presentation, children: [presentation === "dialog" ? (_jsx(SearchInput, { "aria-label": "Search shortcuts", placeholder: "Search shortcuts", value: query, onValueChange: (value) => setQuery(value) })) : null, _jsx("div", { className: "kumiko-shortcuts-scroll", children: _jsx(ShortcutsList, { editing: editing, all: editing, query: query }) }), _jsxs("div", { className: "kumiko-shortcuts-foot-row", children: [_jsx(OpensWith, { keys: options.helpKeys }), _jsxs("div", { className: "kumiko-shortcuts-actions", children: [editable ? (_jsx(Button, { variant: editing ? "solid" : "outline", size: "sm", onClick: () => setEditing((now) => !now), children: editing ? "Done" : "Edit keys" })) : null, closer] })] })] }));
13
22
  }
14
23
  /** A button that opens the help sheet: what can run now, by section. Its keys (`helpKeys`) open it too. */
15
- export function ShortcutsHelp({ presentation = "dialog", editable = false, label = "Shortcuts", className, ...trigger }) {
24
+ export function ShortcutsHelp({ presentation = "dialog", editable = false, label = "Shortcuts", title = "Shortcuts", description, className, ...trigger }) {
16
25
  const { helpOpen, openHelp, closeHelp } = useShortcuts();
17
26
  const onOpenChange = (open) => (open ? openHelp() : closeHelp());
27
+ const render = trigger.render ?? _jsx(Button, { variant: "outline", size: "sm" });
18
28
  if (presentation === "popover") {
19
- return (_jsxs(Popover, { open: helpOpen, onOpenChange: onOpenChange, children: [_jsx(PopoverTrigger, { ...trigger, className: className, children: label }), _jsxs(PopoverContent, { align: "end", sideOffset: 8, className: "kumiko-shortcuts-popover", children: [_jsx(PopoverTitle, { children: "Keyboard shortcuts" }), _jsx(PopoverDescription, { children: "What works right now." }), _jsx(Body, { presentation: presentation, editable: editable })] })] }));
29
+ return (_jsxs(Popover, { open: helpOpen, onOpenChange: onOpenChange, children: [_jsx(PopoverTrigger, { ...trigger, render: render, className: className, children: label }), _jsxs(PopoverContent, { align: "end", sideOffset: 8, className: "kumiko-shortcuts-popover", children: [_jsx(PopoverTitle, { children: title }), description ? _jsx(PopoverDescription, { children: description }) : null, _jsx(Body, { presentation: presentation, editable: editable })] })] }));
20
30
  }
21
- return (_jsxs(Dialog, { open: helpOpen, onOpenChange: onOpenChange, children: [_jsx(DialogTrigger, { ...trigger, className: className, children: label }), _jsx(DialogBackdrop, {}), _jsxs(DialogContent, { className: "kumiko-shortcuts-dialog", "data-kumiko-shortcuts": presentation, children: [_jsx(DialogTitle, { children: "Keyboard shortcuts" }), _jsx(DialogDescription, { children: "What works right now." }), _jsx(Body, { presentation: presentation, editable: editable }), _jsx(DialogClose, { className: className, children: "Close" })] })] }));
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" }) })] })] }));
22
32
  }
23
33
  /** Rebinding on its own, for apps that keep it in a settings page instead of the help sheet. */
24
- export function ShortcutsSettings() {
25
- 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 }) }));
26
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;
@@ -1,5 +1,6 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { formatShortcut } from "@ui-sdk/react/shortcuts";
3
+ import { Button } from "../button";
3
4
  import { Kbd } from "../kbd";
4
5
  import { defaultKeys, maxKeysPerAction } from "./bindings";
5
6
  import { Capture } from "./capture";
@@ -19,30 +20,31 @@ function KeyChip({ action, slot, removable, rebinder }) {
19
20
  const key = keysFor(action.id)[slot] ?? "";
20
21
  const { target } = rebinder;
21
22
  const changing = target?.id === action.id && target.slot === slot;
22
- 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 ${spoken(key)} for ${action.description}`, onClick: () => rebinder.begin({ id: action.id, slot }), children: "Change" }), removable ? (_jsx("button", { type: "button", "aria-label": `Remove ${spoken(key)} from ${action.description}`, onClick: () => rebinder.remove(action.id, slot), children: "Remove" })) : null] }));
23
+ return (_jsxs("span", { className: "kumiko-shortcuts-key", "data-changing": changing ? "" : undefined, children: [_jsx(Kbd, { keys: key, listen: false }), _jsx(Button, { variant: "outline", size: "sm", "aria-label": `Change ${spoken(key)} for ${action.description}`, onClick: () => rebinder.begin({ id: action.id, slot }), children: "Change" }), removable ? (_jsx(Button, { variant: "destructive-ghost", size: "sm", type: "button", "aria-label": `Remove ${spoken(key)} from ${action.description}`, onClick: () => rebinder.remove(action.id, slot), children: "Remove" })) : null] }));
23
24
  }
24
25
  function KeyEditor({ action, rebinder }) {
25
26
  const { keysFor, options } = useShortcuts();
26
27
  const keys = keysFor(action.id);
27
28
  const canAdd = options.multipleKeys ? keys.length < maxKeysPerAction : keys.length === 0;
28
- 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] }));
29
+ 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, { variant: "ghost", size: "sm", 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, { variant: "ghost", size: "sm", type: "button", onClick: () => rebinder.reset(action.id), children: "Reset" })) : null] }));
29
30
  }
30
31
  function Row({ action, editing, rebinder }) {
31
32
  const { keysFor, available } = useShortcuts();
32
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] }));
33
34
  }
34
35
  function NoteRow({ note }) {
35
- 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)))] })] }));
36
37
  }
37
38
  function EditFooter() {
38
- const { resetAll, overrides, options, saveFailed } = useShortcuts();
39
- 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." }))] }));
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." }))] }));
40
42
  }
41
43
  /** The actions grouped by section, each with its keys. With `editing`, every key can be changed. */
42
- export function ShortcutsList({ editing = false, all = editing, query = "" }) {
44
+ export function ShortcutsList({ editing = false, all = editing, query = "", notes: showNotes = true }) {
43
45
  const { actions, notes, available } = useShortcuts();
44
46
  const rebinder = useRebinder();
45
47
  const needle = query.trim().toLowerCase();
46
- 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);
47
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] }));
48
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
  /**
@@ -1,4 +1,9 @@
1
1
  @import "../motion/motion.css";
2
+ @import "../button/button.css";
3
+ @import "../dialog/dialog.css";
4
+ @import "../input/input.css";
5
+ @import "../kbd/kbd.css";
6
+ @import "../popover/popover.css";
2
7
 
3
8
  @layer kumiko {
4
9
  :where(:root) {
@@ -8,6 +13,7 @@
8
13
  --kumiko-shortcuts-accent: Highlight;
9
14
  --kumiko-shortcuts-danger: #b42318;
10
15
  --kumiko-shortcuts-panel-width: 24rem;
16
+ --kumiko-shortcuts-sheet-height: 30rem;
11
17
  }
12
18
 
13
19
  .kumiko-shortcuts-sheet {
@@ -17,8 +23,53 @@
17
23
  font-size: 0.875rem;
18
24
  }
19
25
 
20
- .kumiko-shortcuts-sheet input[type="search"] {
21
- padding: 0.4rem 0.6rem;
26
+ /*
27
+ * The sheet keeps the height it opened with, so searching never makes it jump: the search and the footer stay
28
+ * put and only the list scrolls between them.
29
+ */
30
+ .kumiko-shortcuts-dialog,
31
+ .kumiko-shortcuts-popover {
32
+ display: flex;
33
+ flex-direction: column;
34
+ overflow: hidden;
35
+ }
36
+
37
+ .kumiko-shortcuts-dialog {
38
+ block-size: min(var(--kumiko-shortcuts-sheet-height), var(--_dialog-room-block));
39
+ }
40
+
41
+ .kumiko-shortcuts-dialog > .kumiko-shortcuts-sheet,
42
+ .kumiko-shortcuts-popover > .kumiko-shortcuts-sheet {
43
+ flex: 1;
44
+ min-block-size: 0;
45
+ }
46
+
47
+ .kumiko-shortcuts-popover {
48
+ gap: 0.75rem;
49
+ }
50
+
51
+ .kumiko-shortcuts-actions {
52
+ display: flex;
53
+ gap: 0.5rem;
54
+ align-items: center;
55
+ margin-inline-start: auto;
56
+ }
57
+
58
+ .kumiko-shortcuts-scroll {
59
+ flex: 1;
60
+ min-block-size: 0;
61
+ overflow-y: auto;
62
+ overscroll-behavior: contain;
63
+ scrollbar-gutter: stable;
64
+ }
65
+
66
+ .kumiko-shortcuts-foot-row {
67
+ display: flex;
68
+ flex: none;
69
+ flex-wrap: wrap;
70
+ gap: var(--kumiko-shortcuts-gap);
71
+ align-items: center;
72
+ justify-content: space-between;
22
73
  }
23
74
 
24
75
  .kumiko-shortcuts-list section + section {
@@ -50,6 +101,11 @@
50
101
  border-block-end: 1px solid var(--kumiko-shortcuts-row-border);
51
102
  }
52
103
 
104
+ .kumiko-shortcuts-reason {
105
+ color: var(--kumiko-shortcuts-heading-fg);
106
+ font-size: 0.8125rem;
107
+ }
108
+
53
109
  .kumiko-shortcuts-list li[data-unavailable] .kumiko-shortcuts-name {
54
110
  opacity: 0.55;
55
111
  }
@@ -74,20 +130,7 @@
74
130
  outline: 2px solid var(--kumiko-shortcuts-accent);
75
131
  }
76
132
 
77
- .kumiko-shortcuts-sheet button {
78
- padding: 0.2rem 0.55rem;
79
- border: 1px solid var(--kumiko-shortcuts-row-border);
80
- border-radius: 0.5rem;
81
- background: transparent;
82
- color: inherit;
83
- font: inherit;
84
- font-size: 0.8125rem;
85
- cursor: var(--kumiko-press-cursor, pointer);
86
- }
87
-
88
133
  @media (pointer: coarse) {
89
- .kumiko-shortcuts-sheet button,
90
- .kumiko-shortcuts-sheet input,
91
134
  .kumiko-shortcuts-sheet select {
92
135
  min-block-size: var(--kumiko-touch-target, 2.75rem);
93
136
  }
@@ -118,6 +161,11 @@
118
161
  color: var(--kumiko-shortcuts-danger);
119
162
  }
120
163
 
164
+ .kumiko-shortcuts-scroll .kumiko-shortcuts-empty {
165
+ padding-block: 2rem;
166
+ text-align: center;
167
+ }
168
+
121
169
  .kumiko-shortcuts-empty,
122
170
  .kumiko-shortcuts-foot,
123
171
  .kumiko-shortcuts-none {
@@ -127,7 +175,7 @@
127
175
 
128
176
  :where([data-slot$="popover-content"].kumiko-shortcuts-popover) {
129
177
  inline-size: min(26rem, 100dvw - 2rem);
130
- max-block-size: 70dvh;
178
+ block-size: min(var(--kumiko-shortcuts-sheet-height), 70dvh);
131
179
  }
132
180
 
133
181
  /* The panel sits against the inline-end edge and takes the page's full height. */
@@ -1,5 +1,6 @@
1
1
  import { disposeMirror, findField, measureCaret } from "./caret-geometry";
2
2
  import { createGlider, prefersReducedMotion } from "./caret-glide";
3
+ import { canJoinTopLayer, isRaised, raiseToTop, topLayerAncestor } from "./top-layer";
3
4
  const GLIDE_LIMIT = 400;
4
5
  const IDLE_MS = 500;
5
6
  const STILL_FRAMES = 12;
@@ -52,6 +53,8 @@ class CaretController {
52
53
  watchTimer = 0;
53
54
  stillFrames = 0;
54
55
  fieldBox = "";
56
+ raisedField = null;
57
+ raisedLayer = null;
55
58
  resizeObserver = new ResizeObserver(() => this.schedule());
56
59
  glider;
57
60
  caret;
@@ -153,12 +156,25 @@ class CaretController {
153
156
  this.visible = false;
154
157
  delete this.caret.dataset.visible;
155
158
  }
159
+ /* Paints the caret above the top-layer element that holds the field, once per field and per holder. */
160
+ raise(field) {
161
+ const layer = topLayerAncestor(field);
162
+ const settled = isRaised(this.caret) &&
163
+ layer === this.raisedLayer &&
164
+ (layer === null || field === this.raisedField);
165
+ if (!settled) {
166
+ raiseToTop(this.caret);
167
+ this.raisedField = field;
168
+ this.raisedLayer = layer;
169
+ }
170
+ }
156
171
  show(rect, follow, field) {
157
172
  const snap = follow ||
158
173
  !this.visible ||
159
174
  !this.last ||
160
175
  Math.hypot(rect.x - this.last.x, rect.y - this.last.y) > GLIDE_LIMIT;
161
176
  const reduced = prefersReducedMotion(field);
177
+ this.raise(field);
162
178
  this.caret.style.setProperty("--_caret-color", colourOf(field));
163
179
  this.glider.to(rect.x, rect.y, rect.height, snap || reduced);
164
180
  this.caret.dataset.visible = "true";
@@ -175,7 +191,11 @@ class CaretController {
175
191
  render(follow) {
176
192
  const usable = document.hasFocus() && !this.composing;
177
193
  const candidate = usable ? findField(document.activeElement) : null;
178
- const field = candidate?.isConnected && hasArea(candidate) ? candidate : null;
194
+ const drawable = candidate !== null &&
195
+ candidate.isConnected &&
196
+ hasArea(candidate) &&
197
+ (canJoinTopLayer(this.caret) || topLayerAncestor(candidate) === null);
198
+ const field = drawable ? candidate : null;
179
199
  this.setTracked(field);
180
200
  this.fieldBox = field ? boxOf(field) : "";
181
201
  const rect = field ? measureCaret(field) : null;
@@ -1,4 +1,5 @@
1
1
  import { startSmoothCaret } from "./caret-controller";
2
+ import { makeTopLayerPopover } from "./top-layer";
2
3
  let users = 0;
3
4
  let stopHost = null;
4
5
  /* Builds the one caret element and starts following the focused field. Returns what undoes both. */
@@ -6,6 +7,8 @@ function mountCaret() {
6
7
  const caret = document.createElement("div");
7
8
  caret.dataset.slot = "smooth-caret";
8
9
  caret.setAttribute("aria-hidden", "true");
10
+ caret.setAttribute("inert", "");
11
+ makeTopLayerPopover(caret);
9
12
  const bar = document.createElement("div");
10
13
  bar.dataset.slot = "smooth-caret-bar";
11
14
  caret.append(bar);
@@ -1,4 +1,5 @@
1
1
  import { createGlider, prefersReducedMotion } from "./caret-glide";
2
+ import { makeTopLayerPopover, openModals, raiseToTop, sameElements } from "./top-layer";
2
3
  /* A nudge under this many pixels is not a move. */
3
4
  const MOVED_BY = 0.5;
4
5
  /* A jump longer than this many pixels snaps instead of gliding. */
@@ -91,6 +92,17 @@ function placeOne(overlay, caret, snap) {
91
92
  show(overlay, entry, caret.spot, snap);
92
93
  }
93
94
  }
95
+ /* A dialog that opened since the layer was raised paints above it, so the layer is raised again. */
96
+ function raiseOverDialogs(overlay) {
97
+ if (overlay.raisedOver === null) {
98
+ return;
99
+ }
100
+ const modals = openModals();
101
+ if (!sameElements(modals, overlay.raisedOver)) {
102
+ raiseToTop(overlay.layer);
103
+ overlay.raisedOver = modals;
104
+ }
105
+ }
94
106
  /**
95
107
  * The overlay for remote collaborators: one gliding caret bar and name tag per person, in a fixed layer over
96
108
  * the page. Framework-free, so any editor can drive it from its own awareness data.
@@ -101,14 +113,21 @@ export function createRemoteCarets(options = {}) {
101
113
  layer.dataset.slot = "remote-carets";
102
114
  layer.setAttribute("aria-hidden", "true");
103
115
  host.append(layer);
116
+ const inTopLayer = host === document.body;
117
+ if (inTopLayer) {
118
+ makeTopLayerPopover(layer);
119
+ raiseToTop(layer);
120
+ }
104
121
  const overlay = {
105
122
  host,
106
123
  layer,
107
124
  stillMs: options.stillMs ?? TAG_STILL_MS,
108
- entries: new Map()
125
+ entries: new Map(),
126
+ raisedOver: inTopLayer ? openModals() : null
109
127
  };
110
128
  return {
111
129
  place(carets, snap) {
130
+ raiseOverDialogs(overlay);
112
131
  const present = new Set();
113
132
  for (const caret of carets) {
114
133
  present.add(caret.id);
@@ -14,10 +14,22 @@
14
14
  caret-color: transparent !important;
15
15
  }
16
16
 
17
+ /*
18
+ * Both are manual popovers, so they sit in the top layer and paint above dialogs and popovers. The
19
+ * resets undo the browser's popover look (centred, bordered, padded, filled).
20
+ */
17
21
  [data-slot="smooth-caret"] {
18
22
  position: fixed;
19
23
  inset-block-start: 0;
20
24
  inset-inline-start: 0;
25
+ inset-block-end: auto;
26
+ inset-inline-end: auto;
27
+ margin: 0;
28
+ padding: 0;
29
+ border: 0;
30
+ overflow: visible;
31
+ background: transparent;
32
+ color: inherit;
21
33
  z-index: var(--kumiko-smooth-caret-z);
22
34
  inline-size: var(--kumiko-smooth-caret-width);
23
35
  block-size: 1rem;
@@ -64,6 +76,13 @@
64
76
  position: fixed;
65
77
  inset: 0;
66
78
  z-index: calc(var(--kumiko-smooth-caret-z) - 1);
79
+ inline-size: auto;
80
+ block-size: auto;
81
+ margin: 0;
82
+ padding: 0;
83
+ border: 0;
84
+ background: transparent;
85
+ color: inherit;
67
86
  overflow: hidden;
68
87
  pointer-events: none;
69
88
  }
@@ -0,0 +1,13 @@
1
+ /** Whether this browser can put the element in the top layer as a popover. */
2
+ export declare function canJoinTopLayer(element: HTMLElement): boolean;
3
+ /** Makes the element a manual popover. A manual one is never closed by light dismiss or by another popover opening. */
4
+ export declare function makeTopLayerPopover(element: HTMLElement): void;
5
+ /** Puts the element on top of the top layer: showing it again moves it above everything opened so far. */
6
+ export declare function raiseToTop(element: HTMLElement): void;
7
+ /** Whether the element is shown in the top layer right now. */
8
+ export declare function isRaised(element: HTMLElement): boolean;
9
+ /** The modal dialog or open popover that holds this element, or `null` when it sits in the page. */
10
+ export declare function topLayerAncestor(element: Element): Element | null;
11
+ /** Every dialog open right now: a native modal one, or a Kumiko dialog, which is a popover. */
12
+ export declare function openModals(): Element[];
13
+ export declare function sameElements(a: readonly Element[], b: readonly Element[]): boolean;
@@ -0,0 +1,56 @@
1
+ /*
2
+ * Modal dialogs and open popovers sit in the browser's top layer, which paints above everything on the page
3
+ * whatever its z-index. The caret and the remote carets are plain page elements, so they have to join the top
4
+ * layer themselves, as manual popovers, and be raised again whenever something opens above them.
5
+ */
6
+ /** Whether this browser can put the element in the top layer as a popover. */
7
+ export function canJoinTopLayer(element) {
8
+ return typeof element.showPopover === "function" && typeof element.hidePopover === "function";
9
+ }
10
+ /** Makes the element a manual popover. A manual one is never closed by light dismiss or by another popover opening. */
11
+ export function makeTopLayerPopover(element) {
12
+ element.setAttribute("popover", "manual");
13
+ }
14
+ function isShown(element) {
15
+ try {
16
+ return element.matches(":popover-open");
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ }
22
+ /** Puts the element on top of the top layer: showing it again moves it above everything opened so far. */
23
+ export function raiseToTop(element) {
24
+ if (!canJoinTopLayer(element) || !element.isConnected) {
25
+ return;
26
+ }
27
+ if (isShown(element)) {
28
+ element.hidePopover();
29
+ }
30
+ element.showPopover();
31
+ }
32
+ /** Whether the element is shown in the top layer right now. */
33
+ export function isRaised(element) {
34
+ return isShown(element);
35
+ }
36
+ /** The modal dialog or open popover that holds this element, or `null` when it sits in the page. */
37
+ export function topLayerAncestor(element) {
38
+ try {
39
+ return element.closest(":modal, :popover-open");
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ /** Every dialog open right now: a native modal one, or a Kumiko dialog, which is a popover. */
46
+ export function openModals() {
47
+ try {
48
+ return [...document.querySelectorAll(':modal, [data-slot$="dialog-content"]:popover-open')];
49
+ }
50
+ catch {
51
+ return [];
52
+ }
53
+ }
54
+ export function sameElements(a, b) {
55
+ return a.length === b.length && a.every((element, index) => element === b[index]);
56
+ }
@@ -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.1",
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": {