@clarusjs/ui-primitives 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,41 @@
1
+ // enter and exit: Base UI's state attributes for CSS transitions. data-open / data-closed say the state;
2
+ // data-starting-style is there for the first frame of opening, so a transition from it runs; data-ending-style while
3
+ // closing, until the element's animations finish. Style them:
4
+ // .popup { transition: opacity 150ms } .popup[data-starting-style], .popup[data-ending-style] { opacity: 0 }
5
+
6
+ const frame = () => new Promise((done) => requestAnimationFrame(() => done(undefined)))
7
+
8
+ /**
9
+ * Mark `el` open, with data-starting-style for its first frame so CSS transitions run from there. An element rendered
10
+ * open on the server doesn't need it (nothing to animate in).
11
+ * @param {HTMLElement} el
12
+ * @returns {Promise<void>} When the starting style is gone.
13
+ * @example
14
+ * @if (open) { <div class="popup" [use]="enter">…</div> }
15
+ * @see https://clarusjs.com/guide/ui-primitives#enter-and-exit
16
+ */
17
+ export async function enter(el) {
18
+ el.removeAttribute('data-closed')
19
+ el.removeAttribute('data-ending-style')
20
+ el.setAttribute('data-open', '')
21
+ el.setAttribute('data-starting-style', '')
22
+ await frame()
23
+ await frame() // the start has been styled: now transition from it
24
+ el.removeAttribute('data-starting-style')
25
+ }
26
+
27
+ /**
28
+ * Mark `el` closing: data-closed and data-ending-style, until its animations and transitions finish. Remove or hide
29
+ * it after: `await exit(el)`.
30
+ * @param {HTMLElement} el
31
+ * @returns {Promise<void>}
32
+ * @see https://clarusjs.com/guide/ui-primitives#enter-and-exit
33
+ */
34
+ export async function exit(el) {
35
+ el.removeAttribute('data-open')
36
+ el.setAttribute('data-closed', '')
37
+ el.setAttribute('data-ending-style', '')
38
+ await frame() // the ending style applies, and its transitions start
39
+ await Promise.allSettled((el.getAnimations?.() ?? []).map((a) => a.finished))
40
+ el.removeAttribute('data-ending-style')
41
+ }
@@ -0,0 +1,35 @@
1
+ export type TypeaheadOptions = {
2
+ /**
3
+ * Which descendants are the items (a selector). Default: menu items and options.
4
+ */
5
+ items?: string;
6
+ /**
7
+ * What to do with the match. Default: focus it.
8
+ */
9
+ onMatch?: (item: HTMLElement) => void;
10
+ /**
11
+ * An item's text to match. Default: its textContent.
12
+ */
13
+ text?: (item: HTMLElement) => string;
14
+ /**
15
+ * How long a pause ends the search, in ms. Default 500.
16
+ */
17
+ timeout?: number;
18
+ };
19
+ /**
20
+ * @typedef {object} TypeaheadOptions
21
+ * @property {string} [items] Which descendants are the items (a selector). Default: menu items and options.
22
+ * @property {(item: HTMLElement) => void} [onMatch] What to do with the match. Default: focus it.
23
+ * @property {(item: HTMLElement) => string} [text] An item's text to match. Default: its textContent.
24
+ * @property {number} [timeout] How long a pause ends the search, in ms. Default 500.
25
+ */
26
+ /**
27
+ * Typing a character in `el` moves to the next item whose text starts with what was typed since the last pause.
28
+ * @param {HTMLElement} el
29
+ * @param {TypeaheadOptions} [options]
30
+ * @returns {() => void} Stops it.
31
+ * @example
32
+ * <ul role="listbox" [use]="[(el) => rovingFocus(el, { orientation: 'vertical' }), (el) => typeahead(el)]">…</ul>
33
+ * @see https://clarusjs.com/guide/ui-primitives#typeahead
34
+ */
35
+ export declare function typeahead(el: HTMLElement, options?: TypeaheadOptions): () => void;
@@ -0,0 +1,54 @@
1
+ // typeahead: typing letters moves to the item that starts with them (a menu, a listbox). Ported from Radix's
2
+ // getNextMatch: the search starts after the current item, and a key repeated ("bbb") cycles through the items
3
+ // starting with it.
4
+
5
+ /**
6
+ * @typedef {object} TypeaheadOptions
7
+ * @property {string} [items] Which descendants are the items (a selector). Default: menu items and options.
8
+ * @property {(item: HTMLElement) => void} [onMatch] What to do with the match. Default: focus it.
9
+ * @property {(item: HTMLElement) => string} [text] An item's text to match. Default: its textContent.
10
+ * @property {number} [timeout] How long a pause ends the search, in ms. Default 500.
11
+ */
12
+
13
+ /**
14
+ * Typing a character in `el` moves to the next item whose text starts with what was typed since the last pause.
15
+ * @param {HTMLElement} el
16
+ * @param {TypeaheadOptions} [options]
17
+ * @returns {() => void} Stops it.
18
+ * @example
19
+ * <ul role="listbox" [use]="[(el) => rovingFocus(el, { orientation: 'vertical' }), (el) => typeahead(el)]">…</ul>
20
+ * @see https://clarusjs.com/guide/ui-primitives#typeahead
21
+ */
22
+ export function typeahead(el, options = {}) {
23
+ const { items = '[role="menuitem"],[role="menuitemradio"],[role="menuitemcheckbox"],[role="option"],li', timeout = 500 } = options
24
+ const text = options.text ?? ((/** @type {HTMLElement} */ item) => item.textContent?.trim() ?? '')
25
+ const onMatch = options.onMatch ?? ((/** @type {HTMLElement} */ item) => item.focus())
26
+ let search = ''
27
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
28
+ let timer
29
+ /** @param {KeyboardEvent} event */
30
+ const keydown = (event) => {
31
+ if (event.key.length !== 1 || event.ctrlKey || event.metaKey || event.altKey) return
32
+ if (event.key === ' ' && !search) return // a space starts nothing: it activates the item
33
+ clearTimeout(timer)
34
+ timer = setTimeout(() => (search = ''), timeout)
35
+ search += event.key.toLowerCase()
36
+ const list = /** @type {HTMLElement[]} */ ([...el.querySelectorAll(items)]).filter((item) => !item.hasAttribute('disabled') && item.getAttribute('aria-disabled') !== 'true')
37
+ const current = list.indexOf(/** @type {HTMLElement} */ (document.activeElement))
38
+ // "bbb" is "b" pressed three times: cycle through the b's rather than search for "bbb".
39
+ const repeated = [...search].every((ch) => ch === search[0])
40
+ const query = repeated ? search[0] : search
41
+ // From the item after the current one (from the current one while still typing a longer search), around.
42
+ const from = repeated || current === -1 ? current + 1 : current
43
+ const order = list.map((_, i) => list[(from + i) % list.length])
44
+ const match = order.find((item) => item && text(item).toLowerCase().startsWith(/** @type {string} */ (query)))
45
+ if (!match) return
46
+ event.preventDefault()
47
+ if (match !== document.activeElement) onMatch(match)
48
+ }
49
+ el.addEventListener('keydown', keydown)
50
+ return () => {
51
+ clearTimeout(timer)
52
+ el.removeEventListener('keydown', keydown)
53
+ }
54
+ }