@rokkit/actions 1.7.0 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -158,6 +158,12 @@ Default mappings: alphabet keys dispatch `add`, Enter dispatches `submit`, Escap
158
158
  | `orientation` | `'vertical' \| 'horizontal'` | `'vertical'` | Arrow key axis for prev/next movement |
159
159
  | `collapsible` | `boolean` | `false` | Enable expand/collapse via arrow keys |
160
160
 
161
+ ### focusItem
162
+
163
+ `focusItem(root, key)` focuses the `[data-path="<key>"]` item inside `root` without scrolling any
164
+ ancestor, then scrolls it into view within `root`. That's what the Navigator does after a key; use
165
+ it when a component moves focus itself.
166
+
161
167
  ### buildKeymap / resolveAction
162
168
 
163
169
  Low-level utilities for constructing custom keymaps:
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from "./types.js";
2
2
  export { Navigator } from "./navigator.js";
3
+ export { focusItem } from "./navigator/focus.js";
3
4
  export { Trigger } from "./trigger.js";
4
5
  export { keyboard } from "./keyboard.svelte.js";
5
6
  export { pannable } from "./pannable.svelte.js";
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Pure DOM questions the Navigator asks about an event target: which item it is in, what a click
3
+ * means, and whether the item — or a control nested inside it — should be left alone.
4
+ */
5
+ /**
6
+ * Determine the action for a mouse click based on modifiers and target.
7
+ * Group headers marked with data-accordion-trigger dispatch 'toggle'.
8
+ *
9
+ * @param {MouseEvent} event
10
+ * @returns {string}
11
+ */
12
+ export function clickAction(event: MouseEvent): string;
13
+ /**
14
+ * True when `target` sits inside an interactive element that is a *descendant*
15
+ * of the nearest [data-path] element — i.e. the interactive is embedded inside
16
+ * the item, not the item itself. In that case Navigator defers.
17
+ *
18
+ * An interactive marked with data-accordion-trigger is treated as a legitimate
19
+ * Navigator hook (custom expand/collapse control) and does NOT trigger the
20
+ * skip — Navigator will still dispatch toggle for it.
21
+ *
22
+ * @param {EventTarget|null} target
23
+ * @param {HTMLElement} root
24
+ * @returns {boolean}
25
+ */
26
+ export function isNestedInteractive(target: EventTarget | null, root: HTMLElement): boolean;
27
+ /**
28
+ * True when the [data-path] element containing `target` is marked disabled
29
+ * via `data-disabled` (attribute present) or `aria-disabled="true"`. Native
30
+ * `<button disabled>` is already blocked by the browser, so this only matters
31
+ * for div/span-based items that opt into disabled via attributes.
32
+ *
33
+ * @param {EventTarget|null} target
34
+ * @param {HTMLElement} root
35
+ * @returns {boolean}
36
+ */
37
+ export function isDisabledItem(target: EventTarget | null, root: HTMLElement): boolean;
38
+ /**
39
+ * Walk up the DOM from target to find the nearest element with data-path.
40
+ * Returns null if none found within root.
41
+ *
42
+ * @param {EventTarget} target
43
+ * @param {HTMLElement} root
44
+ * @returns {string|null}
45
+ */
46
+ export function pathOf(target: EventTarget, root: HTMLElement): string | null;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Moving DOM focus to the wrapper's item after the navigator changed it — pure over `root`.
3
+ *
4
+ * Both halves exist to keep the page still: `preventScroll` stops `focus()` scrolling every
5
+ * scrollable ancestor, and `scrollWithin` scrolls only the root, so a list inside a scrollable
6
+ * panel (a Select dropdown in a canvas body) never drags the page along.
7
+ */
8
+ /**
9
+ * Scroll `el` into view within `root` only — never walk ancestors. Nearest edge wins; a visible
10
+ * item does not move.
11
+ *
12
+ * @param {HTMLElement} root
13
+ * @param {HTMLElement} el
14
+ */
15
+ export function scrollWithin(root: HTMLElement, el: HTMLElement): void;
16
+ /**
17
+ * Focus the item at `key` (unless it already has focus) and scroll it into view within `root`.
18
+ * No key, or no item for it inside the root, is a no-op.
19
+ *
20
+ * @param {HTMLElement} root
21
+ * @param {string | null | undefined} key
22
+ */
23
+ export function focusItem(root: HTMLElement, key: string | null | undefined): void;
24
+ /**
25
+ * Where focus goes when it lands on the root itself (tabbing in before any item is focusable):
26
+ * the wrapper's focused item, else the first enabled one.
27
+ *
28
+ * @param {HTMLElement} root
29
+ * @param {string | null | undefined} key
30
+ * @returns {HTMLElement | null}
31
+ */
32
+ export function entryItem(root: HTMLElement, key: string | null | undefined): HTMLElement | null;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The wrapper action a key maps to, or null when the Navigator leaves the key alone: unmapped;
3
+ * select on a link (the browser fires a click for Enter/Space); or a disabled item has focus
4
+ * (div/span items opt out through attributes — they have no native `disabled`).
5
+ *
6
+ * @param {KeyboardEvent} event
7
+ * @param {HTMLElement} root
8
+ * @param {Record<string, unknown>} keymap
9
+ * @param {Element | null} [active] - the focused element
10
+ * @returns {string | null}
11
+ */
12
+ export function keyAction(event: KeyboardEvent, root: HTMLElement, keymap: Record<string, unknown>, active?: Element | null): string | null;
13
+ /**
14
+ * The action and item path for a click, or null when it is not the Navigator's: off any item,
15
+ * on a disabled one, or meant for a control nested inside the item. `native` marks a link, whose
16
+ * default (navigating) must survive.
17
+ *
18
+ * @param {MouseEvent} event
19
+ * @param {HTMLElement} root
20
+ * @returns {{ action: string, path: string, native: boolean } | null}
21
+ */
22
+ export function clickIntent(event: MouseEvent, root: HTMLElement): {
23
+ action: string;
24
+ path: string;
25
+ native: boolean;
26
+ } | null;
27
+ /**
28
+ * Whether focus moving to `next` (a focusout's relatedTarget) leaves the root.
29
+ *
30
+ * @param {HTMLElement} root
31
+ * @param {Node | null} next
32
+ */
33
+ export function focusLeft(root: HTMLElement, next: Node | null): boolean;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Type-to-find: printable keys accumulate into one search string until the reader pauses for
3
+ * `TYPEAHEAD_RESET_MS`, so typing "ma" finds "Mango" rather than jumping to "M…" then "A…".
4
+ */
5
+ export class Typeahead {
6
+ /**
7
+ * A single printable character with no modifier (shift is fine). Space is excluded — it
8
+ * selects.
9
+ * @param {{ key: string, ctrlKey: boolean, metaKey: boolean, altKey: boolean }} event
10
+ */
11
+ accepts({ key, ctrlKey, metaKey, altKey }: {
12
+ key: string;
13
+ ctrlKey: boolean;
14
+ metaKey: boolean;
15
+ altKey: boolean;
16
+ }): boolean;
17
+ /**
18
+ * Add a character and search. The first key of a search starts after the focused item, so
19
+ * repeating a letter walks through the items that start with it.
20
+ *
21
+ * @param {string} key
22
+ * @param {string | null} focusedKey
23
+ * @param {(text: string, startAfter: string | null) => string | null} find
24
+ * @returns {string | null} the matched item's key
25
+ */
26
+ type(key: string, focusedKey: string | null, find: (text: string, startAfter: string | null) => string | null): string | null;
27
+ /** Drop the search and its pending reset. */
28
+ clear(): void;
29
+ #private;
30
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rokkit/actions",
3
- "version": "1.7.0",
3
+ "version": "1.8.1",
4
4
  "description": "Contains generic actions that can be used in various components.",
5
5
  "repository": {
6
6
  "type": "git",
package/src/index.js CHANGED
@@ -1,6 +1,9 @@
1
1
  // skipcq: JS-E1004 - Needed for exposing all types
2
2
  export * from './types.js'
3
3
  export { Navigator } from './navigator.js'
4
+ // Focus a list item without scrolling any ancestor, then scroll it into view within its root —
5
+ // what the Navigator does after a key; exported for components that move focus themselves.
6
+ export { focusItem } from './navigator/focus.js'
4
7
  export { Trigger } from './trigger.js'
5
8
  export { buildKeymap, resolveAction, ACTIONS } from './keymap.js'
6
9
  export { keyboard } from './keyboard.svelte.js'
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Pure DOM questions the Navigator asks about an event target: which item it is in, what a click
3
+ * means, and whether the item — or a control nested inside it — should be left alone.
4
+ */
5
+
6
+ // ─── Click action resolution ──────────────────────────────────────────────────
7
+
8
+ /**
9
+ * Determine the action for a mouse click based on modifiers and target.
10
+ * Group headers marked with data-accordion-trigger dispatch 'toggle'.
11
+ *
12
+ * @param {MouseEvent} event
13
+ * @returns {string}
14
+ */
15
+ export function clickAction(event) {
16
+ const { shiftKey, ctrlKey, metaKey, target } = event
17
+ if (shiftKey) return 'range'
18
+ if (ctrlKey) return 'extend'
19
+ if (metaKey) return 'extend'
20
+ if (target.closest('[data-accordion-trigger]')) return 'toggle'
21
+ return 'select'
22
+ }
23
+
24
+ // ─── Nested interactive detection ─────────────────────────────────────────────
25
+
26
+ // Elements that own their own click / keyboard activation. When one of these
27
+ // sits *inside* a [data-path] item (e.g. a Toggle / Switch inside a List header
28
+ // or config-style row), Navigator must not hijack the event — the nested
29
+ // control owns it.
30
+ const INTERACTIVE_SELECTOR = [
31
+ 'button',
32
+ 'a[href]',
33
+ 'input',
34
+ 'select',
35
+ 'textarea',
36
+ '[role="button"]',
37
+ '[role="switch"]',
38
+ '[role="checkbox"]',
39
+ '[role="menuitem"]',
40
+ '[role="menuitemcheckbox"]',
41
+ '[role="menuitemradio"]',
42
+ '[role="radio"]',
43
+ '[role="tab"]',
44
+ '[role="link"]',
45
+ '[contenteditable=""]',
46
+ '[contenteditable="true"]'
47
+ ].join(',')
48
+
49
+ /**
50
+ * True when `target` sits inside an interactive element that is a *descendant*
51
+ * of the nearest [data-path] element — i.e. the interactive is embedded inside
52
+ * the item, not the item itself. In that case Navigator defers.
53
+ *
54
+ * An interactive marked with data-accordion-trigger is treated as a legitimate
55
+ * Navigator hook (custom expand/collapse control) and does NOT trigger the
56
+ * skip — Navigator will still dispatch toggle for it.
57
+ *
58
+ * @param {EventTarget|null} target
59
+ * @param {HTMLElement} root
60
+ * @returns {boolean}
61
+ */
62
+ export function isNestedInteractive(target, root) {
63
+ const el = /** @type {HTMLElement|null} */ (target)
64
+ /* v8 ignore start -- a dispatched DOM event always carries a target; the null
65
+ branch exists for the EventTarget|null type, not for a reachable state.
66
+ `ignore next` does not fire on a single-line `if (...) return`. */
67
+ if (!el) return false
68
+ /* v8 ignore stop */
69
+ const interactive = /** @type {HTMLElement|null} */ (el.closest(INTERACTIVE_SELECTOR))
70
+ if (!interactive || !root.contains(interactive)) return false
71
+ // A nested element explicitly declared as an accordion trigger is a
72
+ // Navigator-controlled control, not a stray interactive — let it through.
73
+ if (interactive.hasAttribute('data-accordion-trigger')) return false
74
+ return isStrictlyInsideItem(el, interactive)
75
+ }
76
+
77
+ /**
78
+ * True when `interactive` sits STRICTLY inside the `[data-path]` item that
79
+ * contains `el` — i.e. the item exists, is not the interactive itself, and
80
+ * really is its ancestor. Being the item (a `<button data-path>` list row) is
81
+ * the normal case and must not count as nesting.
82
+ *
83
+ * @param {HTMLElement} el
84
+ * @param {HTMLElement} interactive
85
+ * @returns {boolean}
86
+ */
87
+ function isStrictlyInsideItem(el, interactive) {
88
+ const item = /** @type {HTMLElement|null} */ (el.closest('[data-path]'))
89
+ if (!item || interactive === item) return false
90
+ return item.contains(interactive)
91
+ }
92
+
93
+ /**
94
+ * True when the [data-path] element containing `target` is marked disabled
95
+ * via `data-disabled` (attribute present) or `aria-disabled="true"`. Native
96
+ * `<button disabled>` is already blocked by the browser, so this only matters
97
+ * for div/span-based items that opt into disabled via attributes.
98
+ *
99
+ * @param {EventTarget|null} target
100
+ * @param {HTMLElement} root
101
+ * @returns {boolean}
102
+ */
103
+ export function isDisabledItem(target, root) {
104
+ const el = /** @type {HTMLElement|null} */ (target)
105
+ /* v8 ignore start -- see isNestedInteractive: event.target is never null */
106
+ if (!el) return false
107
+ /* v8 ignore stop */
108
+ const dataPathEl = /** @type {HTMLElement|null} */ (el.closest('[data-path]'))
109
+ if (!dataPathEl || !root.contains(dataPathEl)) return false
110
+ if (dataPathEl.hasAttribute('data-disabled')) return true
111
+ if (dataPathEl.getAttribute('aria-disabled') === 'true') return true
112
+ return false
113
+ }
114
+
115
+ // ─── Path resolution ──────────────────────────────────────────────────────────
116
+
117
+ /**
118
+ * Walk up the DOM from target to find the nearest element with data-path.
119
+ * Returns null if none found within root.
120
+ *
121
+ * @param {EventTarget} target
122
+ * @param {HTMLElement} root
123
+ * @returns {string|null}
124
+ */
125
+ export function pathOf(target, root) {
126
+ let el = /** @type {HTMLElement|null} */ (target)
127
+ while (el && el !== root) {
128
+ if (el.dataset?.path !== undefined) return el.dataset.path
129
+ el = el.parentElement
130
+ }
131
+ return null
132
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Moving DOM focus to the wrapper's item after the navigator changed it — pure over `root`.
3
+ *
4
+ * Both halves exist to keep the page still: `preventScroll` stops `focus()` scrolling every
5
+ * scrollable ancestor, and `scrollWithin` scrolls only the root, so a list inside a scrollable
6
+ * panel (a Select dropdown in a canvas body) never drags the page along.
7
+ */
8
+
9
+ /**
10
+ * Scroll `el` into view within `root` only — never walk ancestors. Nearest edge wins; a visible
11
+ * item does not move.
12
+ *
13
+ * @param {HTMLElement} root
14
+ * @param {HTMLElement} el
15
+ */
16
+ export function scrollWithin(root, el) {
17
+ const itemTop = el.offsetTop
18
+ const itemBottom = itemTop + el.offsetHeight
19
+ const visibleTop = root.scrollTop
20
+ if (itemTop < visibleTop) {
21
+ root.scrollTop = itemTop
22
+ } else if (itemBottom > visibleTop + root.clientHeight) {
23
+ root.scrollTop = itemBottom - root.clientHeight
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Focus the item at `key` (unless it already has focus) and scroll it into view within `root`.
29
+ * No key, or no item for it inside the root, is a no-op.
30
+ *
31
+ * @param {HTMLElement} root
32
+ * @param {string | null | undefined} key
33
+ */
34
+ export function focusItem(root, key) {
35
+ if (!key) return
36
+ const el = /** @type {HTMLElement | null} */ (root.querySelector(`[data-path="${key}"]`))
37
+ if (!el) return
38
+ if (el !== document.activeElement) el.focus({ preventScroll: true })
39
+ scrollWithin(root, el)
40
+ }
41
+
42
+ /**
43
+ * Where focus goes when it lands on the root itself (tabbing in before any item is focusable):
44
+ * the wrapper's focused item, else the first enabled one.
45
+ *
46
+ * @param {HTMLElement} root
47
+ * @param {string | null | undefined} key
48
+ * @returns {HTMLElement | null}
49
+ */
50
+ export function entryItem(root, key) {
51
+ return root.querySelector(key ? `[data-path="${key}"]` : '[data-path]:not([disabled])')
52
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Which events the Navigator claims, and as what — pure decisions over an event and the root.
3
+ * The Navigator acts on the answer; nothing here touches the wrapper.
4
+ */
5
+ import { resolveAction } from '../keymap.js'
6
+ import { pathOf, clickAction, isNestedInteractive, isDisabledItem } from './dom.js'
7
+
8
+ const inLink = (target) => Boolean(target.closest('a[href]'))
9
+
10
+ /**
11
+ * The wrapper action a key maps to, or null when the Navigator leaves the key alone: unmapped;
12
+ * select on a link (the browser fires a click for Enter/Space); or a disabled item has focus
13
+ * (div/span items opt out through attributes — they have no native `disabled`).
14
+ *
15
+ * @param {KeyboardEvent} event
16
+ * @param {HTMLElement} root
17
+ * @param {Record<string, unknown>} keymap
18
+ * @param {Element | null} [active] - the focused element
19
+ * @returns {string | null}
20
+ */
21
+ export function keyAction(event, root, keymap, active = document.activeElement) {
22
+ const action = resolveAction(event, keymap)
23
+ if (!action) return null
24
+ if (action === 'select' && inLink(event.target)) return null
25
+ if (isDisabledItem(active, root)) return null
26
+ return action
27
+ }
28
+
29
+ /**
30
+ * The action and item path for a click, or null when it is not the Navigator's: off any item,
31
+ * on a disabled one, or meant for a control nested inside the item. `native` marks a link, whose
32
+ * default (navigating) must survive.
33
+ *
34
+ * @param {MouseEvent} event
35
+ * @param {HTMLElement} root
36
+ * @returns {{ action: string, path: string, native: boolean } | null}
37
+ */
38
+ export function clickIntent(event, root) {
39
+ if (isNestedInteractive(event.target, root)) return null
40
+ const path = pathOf(event.target, root)
41
+ if (path === null || isDisabledItem(event.target, root)) return null
42
+ return { action: clickAction(event), path, native: inLink(event.target) }
43
+ }
44
+
45
+ /**
46
+ * Whether focus moving to `next` (a focusout's relatedTarget) leaves the root.
47
+ *
48
+ * @param {HTMLElement} root
49
+ * @param {Node | null} next
50
+ */
51
+ export function focusLeft(root, next) {
52
+ return !next || !root.contains(next)
53
+ }
@@ -0,0 +1,47 @@
1
+ import { TYPEAHEAD_RESET_MS } from '../nav-constants.js'
2
+
3
+ /**
4
+ * Type-to-find: printable keys accumulate into one search string until the reader pauses for
5
+ * `TYPEAHEAD_RESET_MS`, so typing "ma" finds "Mango" rather than jumping to "M…" then "A…".
6
+ */
7
+ export class Typeahead {
8
+ #buffer = ''
9
+ #timer = null
10
+
11
+ /**
12
+ * A single printable character with no modifier (shift is fine). Space is excluded — it
13
+ * selects.
14
+ * @param {{ key: string, ctrlKey: boolean, metaKey: boolean, altKey: boolean }} event
15
+ */
16
+ accepts({ key, ctrlKey, metaKey, altKey }) {
17
+ return !ctrlKey && !metaKey && !altKey && key.length === 1 && key !== ' '
18
+ }
19
+
20
+ /**
21
+ * Add a character and search. The first key of a search starts after the focused item, so
22
+ * repeating a letter walks through the items that start with it.
23
+ *
24
+ * @param {string} key
25
+ * @param {string | null} focusedKey
26
+ * @param {(text: string, startAfter: string | null) => string | null} find
27
+ * @returns {string | null} the matched item's key
28
+ */
29
+ type(key, focusedKey, find) {
30
+ const startAfter = this.#buffer.length === 0 ? focusedKey : null
31
+ this.#buffer += key
32
+ this.#restartTimer()
33
+ return find(this.#buffer, startAfter)
34
+ }
35
+
36
+ #restartTimer() {
37
+ clearTimeout(this.#timer)
38
+ this.#timer = setTimeout(() => this.clear(), TYPEAHEAD_RESET_MS)
39
+ }
40
+
41
+ /** Drop the search and its pending reset. */
42
+ clear() {
43
+ this.#buffer = ''
44
+ clearTimeout(this.#timer)
45
+ this.#timer = null
46
+ }
47
+ }
package/src/navigator.js CHANGED
@@ -4,13 +4,15 @@
4
4
  * Wires DOM events on a root element to Wrapper actions.
5
5
  * Designed as a plain class so it works as a Svelte action or standalone.
6
6
  *
7
- * Responsibilities:
8
- * - keydown → keymap lookup → wrapper action (+ scrollIntoView)
9
- * - click → click action lookup → wrapper action
10
- * - focusin → find nearest data-path → wrapper.moveTo(path)
11
- * if no data-path found (tabbed into container) → redirect to focusedKey
12
- * - focusout → detect when focus leaves the list entirely → call wrapper.blur()
13
- * - typeahead → buffer printable chars → wrapper.findByText → wrapper.moveTo
7
+ * Responsibilities, each decided by a pure part and acted on here:
8
+ * - keydown → `intent.keyAction` → wrapper action, then `focus.focusItem` (in-root scroll)
9
+ * - click → `intent.clickIntent` → wrapper action (a link keeps its default)
10
+ * - focusin → nearest data-path → wrapper.moveTo(path); focus on the root itself
11
+ * redirects to `focus.entryItem`
12
+ * - focusout → `intent.focusLeft` → wrapper.blur(), deferred past teardown
13
+ * - typeahead → `Typeahead` buffers printable keys → wrapper.findByText → wrapper.moveTo
14
+ *
15
+ * A control nested inside an item (`dom.isNestedInteractive`) owns its own keys and focus.
14
16
  *
15
17
  * Usage:
16
18
  * const nav = new Navigator(rootEl, wrapper, { collapsible: true })
@@ -24,136 +26,11 @@
24
26
  * })
25
27
  */
26
28
 
27
- import { TYPEAHEAD_RESET_MS } from './nav-constants.js'
28
- import { buildKeymap, resolveAction } from './keymap.js'
29
-
30
- // ─── Click action resolution ──────────────────────────────────────────────────
31
-
32
- /**
33
- * Determine the action for a mouse click based on modifiers and target.
34
- * Group headers marked with data-accordion-trigger dispatch 'toggle'.
35
- *
36
- * @param {MouseEvent} event
37
- * @returns {string}
38
- */
39
- function getClickAction(event) {
40
- const { shiftKey, ctrlKey, metaKey, target } = event
41
- if (shiftKey) return 'range'
42
- if (ctrlKey) return 'extend'
43
- if (metaKey) return 'extend'
44
- if (target.closest('[data-accordion-trigger]')) return 'toggle'
45
- return 'select'
46
- }
47
-
48
- // ─── Nested interactive detection ─────────────────────────────────────────────
49
-
50
- // Elements that own their own click / keyboard activation. When one of these
51
- // sits *inside* a [data-path] item (e.g. a Toggle / Switch inside a List header
52
- // or config-style row), Navigator must not hijack the event — the nested
53
- // control owns it.
54
- const INTERACTIVE_SELECTOR = [
55
- 'button',
56
- 'a[href]',
57
- 'input',
58
- 'select',
59
- 'textarea',
60
- '[role="button"]',
61
- '[role="switch"]',
62
- '[role="checkbox"]',
63
- '[role="menuitem"]',
64
- '[role="menuitemcheckbox"]',
65
- '[role="menuitemradio"]',
66
- '[role="radio"]',
67
- '[role="tab"]',
68
- '[role="link"]',
69
- '[contenteditable=""]',
70
- '[contenteditable="true"]'
71
- ].join(',')
72
-
73
- /**
74
- * True when `target` sits inside an interactive element that is a *descendant*
75
- * of the nearest [data-path] element — i.e. the interactive is embedded inside
76
- * the item, not the item itself. In that case Navigator defers.
77
- *
78
- * An interactive marked with data-accordion-trigger is treated as a legitimate
79
- * Navigator hook (custom expand/collapse control) and does NOT trigger the
80
- * skip — Navigator will still dispatch toggle for it.
81
- *
82
- * @param {EventTarget|null} target
83
- * @param {HTMLElement} root
84
- * @returns {boolean}
85
- */
86
- function isNestedInteractive(target, root) {
87
- const el = /** @type {HTMLElement|null} */ (target)
88
- /* v8 ignore start -- a dispatched DOM event always carries a target; the null
89
- branch exists for the EventTarget|null type, not for a reachable state.
90
- `ignore next` does not fire on a single-line `if (...) return`. */
91
- if (!el) return false
92
- /* v8 ignore stop */
93
- const interactive = /** @type {HTMLElement|null} */ (el.closest(INTERACTIVE_SELECTOR))
94
- if (!interactive || !root.contains(interactive)) return false
95
- // A nested element explicitly declared as an accordion trigger is a
96
- // Navigator-controlled control, not a stray interactive — let it through.
97
- if (interactive.hasAttribute('data-accordion-trigger')) return false
98
- return isStrictlyInsideItem(el, interactive)
99
- }
100
-
101
- /**
102
- * True when `interactive` sits STRICTLY inside the `[data-path]` item that
103
- * contains `el` — i.e. the item exists, is not the interactive itself, and
104
- * really is its ancestor. Being the item (a `<button data-path>` list row) is
105
- * the normal case and must not count as nesting.
106
- *
107
- * @param {HTMLElement} el
108
- * @param {HTMLElement} interactive
109
- * @returns {boolean}
110
- */
111
- function isStrictlyInsideItem(el, interactive) {
112
- const item = /** @type {HTMLElement|null} */ (el.closest('[data-path]'))
113
- if (!item || interactive === item) return false
114
- return item.contains(interactive)
115
- }
116
-
117
- /**
118
- * True when the [data-path] element containing `target` is marked disabled
119
- * via `data-disabled` (attribute present) or `aria-disabled="true"`. Native
120
- * `<button disabled>` is already blocked by the browser, so this only matters
121
- * for div/span-based items that opt into disabled via attributes.
122
- *
123
- * @param {EventTarget|null} target
124
- * @param {HTMLElement} root
125
- * @returns {boolean}
126
- */
127
- function isDisabledItem(target, root) {
128
- const el = /** @type {HTMLElement|null} */ (target)
129
- /* v8 ignore start -- see isNestedInteractive: event.target is never null */
130
- if (!el) return false
131
- /* v8 ignore stop */
132
- const dataPathEl = /** @type {HTMLElement|null} */ (el.closest('[data-path]'))
133
- if (!dataPathEl || !root.contains(dataPathEl)) return false
134
- if (dataPathEl.hasAttribute('data-disabled')) return true
135
- if (dataPathEl.getAttribute('aria-disabled') === 'true') return true
136
- return false
137
- }
138
-
139
- // ─── Path resolution ──────────────────────────────────────────────────────────
140
-
141
- /**
142
- * Walk up the DOM from target to find the nearest element with data-path.
143
- * Returns null if none found within root.
144
- *
145
- * @param {EventTarget} target
146
- * @param {HTMLElement} root
147
- * @returns {string|null}
148
- */
149
- function getPath(target, root) {
150
- let el = /** @type {HTMLElement|null} */ (target)
151
- while (el && el !== root) {
152
- if (el.dataset?.path !== undefined) return el.dataset.path
153
- el = el.parentElement
154
- }
155
- return null
156
- }
29
+ import { buildKeymap } from './keymap.js'
30
+ import { pathOf, isNestedInteractive } from './navigator/dom.js'
31
+ import { keyAction, clickIntent, focusLeft } from './navigator/intent.js'
32
+ import { Typeahead } from './navigator/typeahead.js'
33
+ import { focusItem, entryItem } from './navigator/focus.js'
157
34
 
158
35
  // ─── Navigator ────────────────────────────────────────────────────────────────
159
36
 
@@ -165,9 +42,7 @@ export class Navigator {
165
42
  // Set by destroy() so a deferred focusout can tell it's been torn down.
166
43
  #destroyed = false
167
44
 
168
- // Typeahead state
169
- #buffer = ''
170
- #bufferTimer = null
45
+ #typeahead = new Typeahead()
171
46
 
172
47
  /**
173
48
  * @param {HTMLElement} root
@@ -198,88 +73,47 @@ export class Navigator {
198
73
  if (this.#containScroll) {
199
74
  this.#root.removeEventListener('wheel', this.#onWheel)
200
75
  }
201
- this.#clearTypeahead()
76
+ this.#typeahead.clear()
202
77
  }
203
78
 
204
79
  // ─── Keydown ────────────────────────────────────────────────────────────
205
80
 
206
81
  #onKeydown = (/** @type {KeyboardEvent} */ event) => {
207
- // Defer to a nested interactive descendant (Toggle / Switch / input /
208
- // contenteditable inside an item snippet) — it owns its own keys.
82
+ // A control nested in an item (Toggle, Switch, input, contenteditable) owns its keys.
209
83
  if (isNestedInteractive(event.target, this.#root)) return
210
-
211
- // Typeahead: single printable character (no modifiers except shift for caps)
212
84
  if (this.#tryTypeahead(event)) return
213
-
214
- const action = resolveAction(event, this.#keymap)
85
+ const action = keyAction(event, this.#root, this.#keymap)
215
86
  if (!action) return
216
-
217
- // Links handle Enter/Space natively — browser fires a synthetic click
218
- if (action === 'select' && event.target.closest('a[href]')) return
219
-
220
- // Item explicitly marked disabled via attributes (div/span items opt in
221
- // this way since they cannot use the native `disabled` attribute).
222
- if (isDisabledItem(document.activeElement, this.#root)) return
223
-
224
87
  event.preventDefault()
225
88
  event.stopPropagation()
226
-
227
- // Resolve current path from the focused element so all actions get context
228
- const path = getPath(document.activeElement, this.#root)
229
- this.#dispatch(action, path)
230
-
231
- // Scroll focused item into view after keyboard navigation
89
+ // Every action gets the focused item's path; movement ignores it.
90
+ this.#dispatch(action, pathOf(document.activeElement, this.#root))
232
91
  this.#syncFocus()
233
92
  }
234
93
 
235
94
  // ─── Click ──────────────────────────────────────────────────────────────
236
95
 
237
96
  #onClick = (/** @type {MouseEvent} */ event) => {
238
- // Defer to a nested interactive descendant — the click is meant for it.
239
- if (isNestedInteractive(event.target, this.#root)) return
240
-
241
- const path = getPath(event.target, this.#root)
242
- if (path === null) return
243
-
244
- // Item explicitly marked disabled via attributes.
245
- if (isDisabledItem(event.target, this.#root)) return
246
-
247
- const action = getClickAction(event)
248
-
249
- // Links: let browser navigate naturally, still update state
250
- if (!event.target.closest('a[href]')) {
251
- event.preventDefault()
252
- }
253
-
254
- this.#dispatch(action, path)
255
- // No scrollIntoView — user clicked where they wanted
97
+ const intent = clickIntent(event, this.#root)
98
+ if (!intent) return
99
+ // A link still navigates; state updates either way.
100
+ if (!intent.native) event.preventDefault()
101
+ // No focus sync: the user clicked where they wanted.
102
+ this.#dispatch(intent.action, intent.path)
256
103
  }
257
104
 
258
105
  // ─── Focusin ────────────────────────────────────────────────────────────
259
106
 
260
107
  #onFocusin = (/** @type {FocusEvent} */ event) => {
261
- // Focus landed inside a nested interactive (e.g. tabbed to a Switch
262
- // inside a row) — leave the wrapper's focusedKey alone and let the
263
- // nested control own the focus context.
108
+ // Tabbed into a control nested in a row: it owns the focus context, the wrapper keeps its key.
264
109
  if (isNestedInteractive(event.target, this.#root)) return
265
-
266
- const path = getPath(event.target, this.#root)
267
-
110
+ const path = pathOf(event.target, this.#root)
268
111
  if (path !== null) {
269
- // Focused a specific item (click, programmatic focus, or tab with roving tabindex)
270
112
  this.#wrapper.moveTo(path)
271
113
  return
272
114
  }
273
-
274
- // Focused the container itself (user tabbed in, no roving tabindex item yet)
275
- // Redirect focus to the currently focused item, or first item if none
276
- const targetKey = this.#wrapper.focusedKey
277
- const selector = targetKey ? `[data-path="${targetKey}"]` : '[data-path]:not([disabled])'
278
- const el = /** @type {HTMLElement|null} */ (this.#root.querySelector(selector))
279
- if (el) {
280
- el.focus()
281
- // focusin will re-fire with the item as target, handled above
282
- }
115
+ // Focus landed on the root itself — redirect to an item; focusin re-fires on it.
116
+ entryItem(this.#root, this.#wrapper.focusedKey)?.focus()
283
117
  }
284
118
 
285
119
  // ─── Wheel ──────────────────────────────────────────────────────────────
@@ -293,23 +127,17 @@ export class Navigator {
293
127
  // ─── Focusout ───────────────────────────────────────────────────────────
294
128
 
295
129
  #onFocusout = (/** @type {FocusEvent} */ event) => {
296
- // relatedTarget is the element receiving focus next
297
- // If it's null or outside this root, focus left the list
298
- const next = /** @type {Node|null} */ (event.relatedTarget)
299
- if (!next || !this.#root.contains(next)) {
300
- // Removing a focused element also fires focusout with a null
301
- // relatedTarget, so teardown looks exactly like a real blur here. Calling
302
- // wrapper.blur() synchronously in that case mutates state during Svelte's
303
- // effect-cleanup phase, which throws `state_unsafe_mutation`. Deferring by
304
- // a microtask lets destroy() land first, so a torn-down navigator stays
305
- // quiet while a genuine blur still reaches the wrapper.
306
- // JSDOM never fires focusout on removal, so this only shows up in a real
307
- // browser — see packages/ui/browser/Select.browser.spec.ts.
308
- queueMicrotask(() => {
309
- if (this.#destroyed) return
310
- this.#wrapper.blur?.()
311
- })
312
- }
130
+ if (!focusLeft(this.#root, /** @type {Node | null} */ (event.relatedTarget))) return
131
+ // Removing a focused element also fires focusout with a null relatedTarget, so teardown
132
+ // looks exactly like a real blur here. Calling wrapper.blur() synchronously then mutates
133
+ // state during Svelte's effect-cleanup phase, which throws `state_unsafe_mutation`.
134
+ // Deferring by a microtask lets destroy() land first, so a torn-down navigator stays quiet
135
+ // while a genuine blur still reaches the wrapper. JSDOM never fires focusout on removal, so
136
+ // this only shows up in a real browser — see packages/ui/browser/Select.browser.spec.ts.
137
+ queueMicrotask(() => {
138
+ if (this.#destroyed) return
139
+ this.#wrapper.blur?.()
140
+ })
313
141
  }
314
142
 
315
143
  // ─── Dispatch ───────────────────────────────────────────────────────────
@@ -327,91 +155,32 @@ export class Navigator {
327
155
  this.#wrapper[action]?.(path)
328
156
  }
329
157
 
330
- // ─── Focus + scroll ──────────────────────────────────────────────────────
158
+ // ─── Focus ──────────────────────────────────────────────────────────────
331
159
 
160
+ /** Move DOM focus to the wrapper's item and scroll it into view within the root only. */
332
161
  #syncFocus() {
333
- const key = this.#wrapper.focusedKey
334
- if (!key) return
335
- const el = /** @type {HTMLElement|null} */ (this.#root.querySelector(`[data-path="${key}"]`))
336
- if (!el) return
337
- // preventScroll stops the browser from cascading the focus call
338
- // up the ancestor chain and scrolling outer containers.
339
- if (el !== document.activeElement) el.focus({ preventScroll: true })
340
- this.#scrollItemIntoView(el)
341
- }
342
-
343
- /**
344
- * Scroll `el` into view *within `this.#root`* only — never walk ancestors.
345
- * This prevents page-jumping when the navigator's root is itself inside
346
- * a scrollable container (e.g. a Select dropdown inside a scrollable
347
- * canvas-body).
348
- * @param {HTMLElement} el
349
- */
350
- #scrollItemIntoView(el) {
351
- const root = this.#root
352
- const itemTop = el.offsetTop
353
- const itemBottom = itemTop + el.offsetHeight
354
- const visibleTop = root.scrollTop
355
- const visibleBottom = visibleTop + root.clientHeight
356
- if (itemTop < visibleTop) {
357
- root.scrollTop = itemTop
358
- } else if (itemBottom > visibleBottom) {
359
- root.scrollTop = itemBottom - root.clientHeight
360
- }
162
+ focusItem(this.#root, this.#wrapper.focusedKey)
361
163
  }
362
164
 
363
165
  // ─── Typeahead ───────────────────────────────────────────────────────────
364
166
 
365
- #isPrintableKey(key, ctrlKey, metaKey, altKey) {
366
- if (ctrlKey) return false
367
- if (metaKey) return false
368
- if (altKey) return false
369
- if (key.length !== 1) return false
370
- return key !== ' '
371
- }
372
-
373
- #appendBuffer(key) {
374
- const startAfter = this.#buffer.length === 0 ? this.#wrapper.focusedKey : null
375
- this.#buffer += key
376
- if (this.#bufferTimer) {
377
- clearTimeout(this.#bufferTimer)
378
- this.#bufferTimer = null
379
- }
380
- this.#bufferTimer = setTimeout(() => this.#clearTypeahead(), TYPEAHEAD_RESET_MS)
381
- return startAfter
382
- }
383
-
384
167
  /**
385
- * Handle printable character keys for typeahead search.
386
- * Returns true if the event was consumed.
168
+ * A printable key searches the items by text. True when it matched (and was consumed); a key
169
+ * that matches nothing still extends the search but falls through to the keymap.
387
170
  *
388
171
  * @param {KeyboardEvent} event
389
172
  * @returns {boolean}
390
173
  */
391
174
  #tryTypeahead(event) {
392
- const { key, ctrlKey, metaKey, altKey } = event
393
-
394
- if (!this.#isPrintableKey(key, ctrlKey, metaKey, altKey)) return false
395
-
396
- const startAfter = this.#appendBuffer(key)
397
-
398
- const matchKey = this.#wrapper.findByText(this.#buffer, startAfter)
399
- if (matchKey !== null) {
400
- event.preventDefault()
401
- event.stopPropagation()
402
- this.#wrapper.moveTo(matchKey)
403
- this.#syncFocus()
404
- return true
405
- }
406
-
407
- return false
408
- }
409
-
410
- #clearTypeahead() {
411
- this.#buffer = ''
412
- if (this.#bufferTimer) {
413
- clearTimeout(this.#bufferTimer)
414
- this.#bufferTimer = null
415
- }
175
+ if (!this.#typeahead.accepts(event)) return false
176
+ const match = this.#typeahead.type(event.key, this.#wrapper.focusedKey, (text, after) =>
177
+ this.#wrapper.findByText(text, after)
178
+ )
179
+ if (match === null) return false
180
+ event.preventDefault()
181
+ event.stopPropagation()
182
+ this.#wrapper.moveTo(match)
183
+ this.#syncFocus()
184
+ return true
416
185
  }
417
186
  }