@clarusjs/ui-primitives 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +47 -1
  2. package/package.json +53 -4
  3. package/src/accordion-item.tscl +16 -0
  4. package/src/checkbox.tscl +13 -0
  5. package/src/combobox.tscl +208 -0
  6. package/src/dialog-close.tscl +4 -0
  7. package/src/dialog-trigger.tscl +4 -0
  8. package/src/dialog.tscl +19 -0
  9. package/src/dismiss.d.ts +27 -0
  10. package/src/dismiss.js +51 -0
  11. package/src/field.tscl +58 -0
  12. package/src/focus-return.d.ts +10 -0
  13. package/src/focus-return.js +18 -0
  14. package/src/index.d.ts +8 -0
  15. package/src/index.js +12 -0
  16. package/src/menu-item.tscl +8 -0
  17. package/src/menu-list.tscl +13 -0
  18. package/src/menu-trigger.tscl +15 -0
  19. package/src/menu.tscl +59 -0
  20. package/src/popover-trigger.tscl +4 -0
  21. package/src/popover.tscl +39 -0
  22. package/src/position.d.ts +36 -0
  23. package/src/position.js +61 -0
  24. package/src/radio-group.tscl +53 -0
  25. package/src/radio.tscl +10 -0
  26. package/src/resize-column.d.ts +18 -0
  27. package/src/resize-column.js +56 -0
  28. package/src/roving-focus.d.ts +39 -0
  29. package/src/roving-focus.js +65 -0
  30. package/src/select.tscl +47 -0
  31. package/src/sidebar-trigger.tscl +54 -0
  32. package/src/sidebar.d.ts +8 -0
  33. package/src/sidebar.js +21 -0
  34. package/src/sidebar.tscl +13 -0
  35. package/src/switch.tscl +14 -0
  36. package/src/tab-list.tscl +4 -0
  37. package/src/tab-panel.tscl +17 -0
  38. package/src/tab.tscl +16 -0
  39. package/src/tabs.tscl +59 -0
  40. package/src/toast-region.tscl +174 -0
  41. package/src/toast.d.ts +48 -0
  42. package/src/toast.js +56 -0
  43. package/src/toggle-group.tscl +48 -0
  44. package/src/toggle-item.tscl +16 -0
  45. package/src/toggle.tscl +10 -0
  46. package/src/tooltip-trigger.tscl +59 -0
  47. package/src/tooltip.tscl +21 -0
  48. package/src/transition.d.ts +18 -0
  49. package/src/transition.js +41 -0
  50. package/src/typeahead.d.ts +35 -0
  51. package/src/typeahead.js +54 -0
package/src/tab.tscl ADDED
@@ -0,0 +1,16 @@
1
+ {{-- Tab (#465): one tab inside <tab-list>; [value] names the <tab-panel> it shows. Selected state comes from <tabs>. --}}
2
+ @context tabs: { id: string; value: string }
3
+ @input value: string
4
+
5
+ <button
6
+ type="button"
7
+ role="tab"
8
+ [id]="tabs.id + '-tab-' + value"
9
+ [aria-controls]="tabs.id + '-panel-' + value"
10
+ [aria-selected]="value === tabs.value ? 'true' : 'false'"
11
+ [tabindex]="value === tabs.value ? 0 : -1"
12
+ [data-value]="value"
13
+ data-part="tab"
14
+ >
15
+ <slot />
16
+ </button>
package/src/tabs.tscl ADDED
@@ -0,0 +1,59 @@
1
+ {{--
2
+ Tabs (#465): a tab list over panels, Radix-shaped. The root is a small island; <tab-list>, <tab> and <tab-panel>
3
+ have no script, ship nothing, and read the selection from context, so the server writes every ARIA attribute and
4
+ hidden. Arrow keys, Home and End move between tabs and select them. Bind the selected value with [(value)];
5
+ (change) comes first with the new value, and $info.cancel() keeps the current tab.
6
+
7
+ <tabs id="install" label="Install" value="npm">
8
+ <tab-list>
9
+ <tab value="npm">npm</tab>
10
+ <tab value="pnpm">pnpm</tab>
11
+ </tab-list>
12
+ <tab-panel value="npm">npm i clarusjs</tab-panel>
13
+ <tab-panel value="pnpm">pnpm add clarusjs</tab-panel>
14
+ </tabs>
15
+
16
+ Give each one its own id: its tabs and panels are named after it.
17
+ --}}
18
+ @input id: string
19
+ @input label: string
20
+ @model value: string
21
+ @event change: string
22
+
23
+ <script>
24
+ import { effect } from 'clarusjs/runtime'
25
+ import { rovingFocus } from '@clarusjs/ui-primitives'
26
+ provide('tabs', { id, label, value })
27
+ // The tabs and panels are the page's server HTML (no markers of their own): wired here, by data-value and id.
28
+ // Only this group's: a tabs group nested in a panel has its own.
29
+ function wire(el) {
30
+ const own = (node) => node.closest('[data-part="tabs"]') === el
31
+ const click = (event) => {
32
+ const tab = event.target.closest('[role="tab"]')
33
+ if (!tab || !own(tab)) return
34
+ const next = tab.dataset.value
35
+ if (next !== value && emit('change', next, { reason: 'select', event })) value = next
36
+ }
37
+ el.addEventListener('click', click)
38
+ const list = [...el.querySelectorAll('[role="tablist"]')].find(own)
39
+ const stopKeys = list ? rovingFocus(list, { onMove: (tab) => tab.click() }) : () => {}
40
+ const stopSync = effect(() => {
41
+ const selected = value
42
+ for (const tab of el.querySelectorAll('[role="tab"]')) {
43
+ if (!own(tab)) continue
44
+ tab.setAttribute('aria-selected', String(tab.dataset.value === selected))
45
+ tab.tabIndex = tab.dataset.value === selected ? 0 : -1
46
+ }
47
+ for (const panel of el.querySelectorAll('[role="tabpanel"]')) {
48
+ if (own(panel)) panel.hidden = panel.id !== id + '-panel-' + selected
49
+ }
50
+ })
51
+ return () => {
52
+ el.removeEventListener('click', click)
53
+ stopKeys()
54
+ stopSync()
55
+ }
56
+ }
57
+ </script>
58
+
59
+ <div data-part="tabs" [use]="wire"><slot /></div>
@@ -0,0 +1,174 @@
1
+ {{--
2
+ Toast region: where toast('…') messages appear. Put it once in your layout. Its look is yours: write the markup of
3
+ a toast in @slot('toast') (one root element: it becomes the toast), and a kind's own in @slot('success' | 'error' | 'info' | 'warning'); the region copies it
4
+ for each toast and fills the parts it finds: data-part="toast-message" (the text), "toast-action" (removed when the
5
+ toast has none), "toast-close", "toast-icon" (a default icon when it's empty). Static markup: it's copied, not run. A polite live region: screen readers
6
+ announce new messages without moving focus. Each message stays its duration (paused while hovered or focused);
7
+ Escape dismisses the focused one; an action runs and dismisses.
8
+
9
+ <toast-region /> … import { toast } from '@clarusjs/ui-primitives'; toast('Saved')
10
+ [label] names the region ("Notifications"): give a second region on a page its own.
11
+ --}}
12
+ @input label: string = 'Notifications'
13
+
14
+ <script>
15
+ import { dismissToast, subscribeToasts, toasts } from '@clarusjs/ui-primitives'
16
+ const KINDS = { success: 'Success:', error: 'Error:', info: 'Info:', warning: 'Warning:' }
17
+ const PATHS = {
18
+ success: 'M5 12l5 5 9-10',
19
+ error: 'M6 6l12 12M18 6L6 18',
20
+ info: 'M12 2a10 10 0 1 0 0 20a10 10 0 1 0 0-20M12 16v-4M12 8h.01',
21
+ warning: 'M12 4l9 16H3zM12 10v4M12 17h.01',
22
+ }
23
+ function svg(type) {
24
+ const ns = 'http://www.w3.org/2000/svg'
25
+ const root = document.createElementNS(ns, 'svg')
26
+ root.setAttribute('viewBox', '0 0 24 24')
27
+ root.setAttribute('width', '18')
28
+ root.setAttribute('height', '18')
29
+ root.setAttribute('fill', 'none')
30
+ root.setAttribute('stroke', 'currentColor')
31
+ root.setAttribute('stroke-width', '2')
32
+ const path = document.createElementNS(ns, 'path')
33
+ path.setAttribute('d', PATHS[type])
34
+ root.append(path)
35
+ return root
36
+ }
37
+ function wire(el) {
38
+ // A toast's markup: its kind's template, else the general one, else the default (icon, message, action, close).
39
+ // A template has one root element, which becomes the toast; one with none or several is ignored.
40
+ const usable = (tpl) => {
41
+ if (!(tpl instanceof HTMLTemplateElement) || !tpl.content.childNodes.length) return false
42
+ const loose = [...tpl.content.childNodes].some((n) => n.nodeType === 3 && n.textContent?.trim())
43
+ if (tpl.content.childElementCount === 1 && !loose) return true
44
+ console.warn(
45
+ `[ui-primitives] <toast-region>: the ${tpl.dataset.type} template needs one root element; using the default`,
46
+ )
47
+ return false
48
+ }
49
+ const template = (type) => {
50
+ const own = type && el.querySelector(`template[data-type="${type}"]`)
51
+ if (own && usable(own)) return own
52
+ const general = el.querySelector('template[data-type="toast"]')
53
+ return general && usable(general) ? general : null
54
+ }
55
+ const piece = (t) => {
56
+ const chosen = template(t.type)
57
+ const root = chosen?.content.firstElementChild?.cloneNode(true)
58
+ if (root instanceof HTMLElement) return root
59
+ const make = (tag, part, text = '') => {
60
+ const node = document.createElement(tag)
61
+ node.dataset.part = part
62
+ if (text) node.textContent = text
63
+ return node
64
+ }
65
+ const action = make('button', 'toast-action')
66
+ const close = make('button', 'toast-close', '×')
67
+ action.setAttribute('type', 'button')
68
+ close.setAttribute('type', 'button')
69
+ close.setAttribute('aria-label', 'Dismiss')
70
+ const box = document.createElement('div')
71
+ box.append(make('span', 'toast-icon'), make('p', 'toast-message'), action, close)
72
+ return box
73
+ }
74
+ const list = el.querySelector('[data-part="toast-list"]')
75
+ const timers = new Map()
76
+ let origin // where focus was before it came into the list, to go back to
77
+ const start = (t, item) => {
78
+ clearTimeout(timers.get(t.id))
79
+ if (!Number.isFinite(t.duration)) return
80
+ timers.set(
81
+ t.id,
82
+ setTimeout(() => dismissToast(t.id), t.duration),
83
+ )
84
+ item.dataset.timing = ''
85
+ }
86
+ // Dismissing the focused toast moves focus to the next one, or back where it came from.
87
+ const leave = (id, item) => {
88
+ const next = item.nextElementSibling ?? item.previousElementSibling
89
+ const focused = item.contains(document.activeElement)
90
+ dismissToast(id)
91
+ if (focused) (next instanceof HTMLElement && next.isConnected ? next : origin)?.focus()
92
+ }
93
+ const pause = (id, item) => {
94
+ clearTimeout(timers.get(id))
95
+ delete item.dataset.timing
96
+ }
97
+ let stop = () => {}
98
+ const render = () => {
99
+ // A region taken out of the page (a fragment swap, a re-render) stops listening.
100
+ if (!el.isConnected) {
101
+ for (const id of timers.values()) clearTimeout(id)
102
+ return stop()
103
+ }
104
+ const now = toasts()
105
+ for (const item of [...list.children]) {
106
+ if (!now.some((t) => String(t.id) === item.dataset.id)) {
107
+ clearTimeout(timers.get(Number(item.dataset.id)))
108
+ item.remove()
109
+ }
110
+ }
111
+ for (const t of now) {
112
+ if (list.querySelector(`[data-id="${t.id}"]`)) continue
113
+ const item = piece(t)
114
+ item.dataset.part = 'toast'
115
+ item.dataset.id = String(t.id)
116
+ if (t.type) item.dataset.type = t.type
117
+ item.tabIndex = 0
118
+ const kind = document.createElement('span')
119
+ kind.dataset.part = 'toast-kind'
120
+ kind.textContent = t.type ? KINDS[t.type] : ''
121
+ item.prepend(kind)
122
+ const icon = item.querySelector('[data-part="toast-icon"]')
123
+ if (icon) {
124
+ icon.setAttribute('aria-hidden', 'true')
125
+ if (t.icon === false) icon.replaceChildren()
126
+ else if (!icon.childNodes.length && t.type) icon.append(svg(t.type))
127
+ }
128
+ const message = item.querySelector('[data-part="toast-message"]')
129
+ if (message) message.textContent = t.message
130
+ const action = item.querySelector('[data-part="toast-action"]')
131
+ const act = t.action
132
+ if (action && act) {
133
+ action.textContent = act.label
134
+ action.addEventListener('click', () => {
135
+ act.onClick()
136
+ leave(t.id, item)
137
+ })
138
+ } else action?.remove()
139
+ item.querySelector('[data-part="toast-close"]')?.addEventListener('click', () => leave(t.id, item))
140
+ const hold = () => pause(t.id, item)
141
+ const resume = () => {
142
+ if (!item.matches(':hover') && !item.contains(document.activeElement)) start(t, item)
143
+ }
144
+ item.addEventListener('pointerenter', hold)
145
+ item.addEventListener('focusin', (event) => {
146
+ if (!(event.relatedTarget instanceof Node && list.contains(event.relatedTarget)))
147
+ origin = event.relatedTarget instanceof HTMLElement ? event.relatedTarget : origin
148
+ hold()
149
+ })
150
+ item.addEventListener('pointerleave', resume)
151
+ item.addEventListener('focusout', () => setTimeout(resume))
152
+ item.addEventListener('keydown', (event) => {
153
+ if (event.key === 'Escape') leave(t.id, item)
154
+ })
155
+ list.append(item)
156
+ start(t, item)
157
+ }
158
+ }
159
+ stop = subscribeToasts(render)
160
+ return () => {
161
+ stop()
162
+ for (const id of timers.values()) clearTimeout(id)
163
+ }
164
+ }
165
+ </script>
166
+
167
+ <section [aria-label]="label" data-part="toast-region" [use]="wire">
168
+ <template data-type="toast"><slot name="toast" /></template>
169
+ <template data-type="success"><slot name="success" /></template>
170
+ <template data-type="error"><slot name="error" /></template>
171
+ <template data-type="info"><slot name="info" /></template>
172
+ <template data-type="warning"><slot name="warning" /></template>
173
+ <div aria-live="polite" data-part="toast-list"></div>
174
+ </section>
package/src/toast.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ export type ToastAction = {
2
+ /**
3
+ * The button's text.
4
+ */
5
+ label: string;
6
+ /**
7
+ * Runs when it's pressed; the toast is dismissed after.
8
+ */
9
+ onClick: () => void;
10
+ };
11
+ export type Toast = {
12
+ id: number;
13
+ message: string;
14
+ action?: ToastAction;
15
+ /**
16
+ * Milliseconds shown (paused while hovered or focused); Infinity: until dismissed.
17
+ */
18
+ duration: number;
19
+ /**
20
+ * Its kind: styled by data-type, with an icon and the kind in words.
21
+ */
22
+ type?: 'success' | 'error' | 'info' | 'warning';
23
+ /**
24
+ * false: no icon.
25
+ */
26
+ icon?: boolean;
27
+ };
28
+ /**
29
+ * Show a message for `duration` ms (5000 by default; a toast with an action stays until dismissed, so there's time
30
+ * to reach it), with at most one action. Polite: it never takes focus.
31
+ * @param {string} message
32
+ * @param {{ action?: ToastAction, duration?: number, type?: 'success' | 'error' | 'info' | 'warning', icon?: boolean }} [options]
33
+ * @returns {number} its id, for dismissToast()
34
+ */
35
+ export declare function toast(message: string, options?: {
36
+ action?: ToastAction;
37
+ duration?: number;
38
+ type?: 'success' | 'error' | 'info' | 'warning';
39
+ icon?: boolean;
40
+ }): number;
41
+ /** @param {number} id */
42
+ export declare function dismissToast(id: number): void;
43
+ /** Every toast, oldest first. @returns {Toast[]} */
44
+ export declare const toasts: () => Toast[];
45
+ /** Calls `listener` now and on every change; returns how to stop. @param {() => void} listener */
46
+ export declare function subscribeToasts(listener: () => void): () => void;
47
+ /** Removes every toast (tests, or a page that resets). */
48
+ export declare function clearToasts(): void;
package/src/toast.js ADDED
@@ -0,0 +1,56 @@
1
+ // Toasts: short messages any island can send with toast('Saved'); <toast-region> (once, in the layout) shows them.
2
+ // The list lives on globalThis, so every island's copy of this module shares it however the bundle is split.
3
+
4
+ /**
5
+ * @typedef {object} ToastAction
6
+ * @property {string} label The button's text.
7
+ * @property {() => void} onClick Runs when it's pressed; the toast is dismissed after.
8
+ */
9
+ /**
10
+ * @typedef {object} Toast
11
+ * @property {number} id
12
+ * @property {string} message
13
+ * @property {ToastAction} [action]
14
+ * @property {number} duration Milliseconds shown (paused while hovered or focused); Infinity: until dismissed.
15
+ * @property {'success' | 'error' | 'info' | 'warning'} [type] Its kind: styled by data-type, with an icon and the kind in words.
16
+ * @property {boolean} [icon] false: no icon.
17
+ */
18
+ /** @type {{ items: Toast[], listeners: Set<() => void>, next: number }} */
19
+ const store = /** @type {any} */ (globalThis).__clToasts ??= { items: [], listeners: new Set(), next: 1 }
20
+ const notify = () => { for (const listener of store.listeners) listener() }
21
+
22
+ /**
23
+ * Show a message for `duration` ms (5000 by default; a toast with an action stays until dismissed, so there's time
24
+ * to reach it), with at most one action. Polite: it never takes focus.
25
+ * @param {string} message
26
+ * @param {{ action?: ToastAction, duration?: number, type?: 'success' | 'error' | 'info' | 'warning', icon?: boolean }} [options]
27
+ * @returns {number} its id, for dismissToast()
28
+ */
29
+ export function toast(message, options = {}) {
30
+ const id = store.next++
31
+ store.items = [...store.items, { id, message, action: options.action, type: options.type, icon: options.icon, duration: options.duration ?? (options.action ? Infinity : 5000) }]
32
+ notify()
33
+ return id
34
+ }
35
+
36
+ /** @param {number} id */
37
+ export function dismissToast(id) {
38
+ store.items = store.items.filter((t) => t.id !== id)
39
+ notify()
40
+ }
41
+
42
+ /** Every toast, oldest first. @returns {Toast[]} */
43
+ export const toasts = () => store.items
44
+
45
+ /** Calls `listener` now and on every change; returns how to stop. @param {() => void} listener */
46
+ export function subscribeToasts(listener) {
47
+ store.listeners.add(listener)
48
+ listener()
49
+ return () => { store.listeners.delete(listener) }
50
+ }
51
+
52
+ /** Removes every toast (tests, or a page that resets). */
53
+ export function clearToasts() {
54
+ store.items = []
55
+ notify()
56
+ }
@@ -0,0 +1,48 @@
1
+ {{--
2
+ Toggle group: toggles that belong together, one Tab stop, arrow keys between them (rovingFocus). type="single"
3
+ keeps exactly one pressed once chosen (bind [(value)]); type="multiple" lets each toggle on its own (bind
4
+ [(values)]). <toggle-item>s have no script and read the group from context, so the server writes aria-pressed.
5
+
6
+ <toggle-group label="Alignment" [(value)]="align">
7
+ <toggle-item value="left">Left</toggle-item>
8
+ <toggle-item value="center">Center</toggle-item>
9
+ </toggle-group>
10
+ --}}
11
+ @input label: string
12
+ @input type: 'single' | 'multiple' = 'single'
13
+ @model value: string = ''
14
+ @model values: string[] = []
15
+
16
+ <script>
17
+ import { effect } from 'clarusjs/runtime'
18
+ import { rovingFocus } from '@clarusjs/ui-primitives'
19
+ provide('toggleGroup', { type, value, values })
20
+ const isOn = (v) => (type === 'multiple' ? values.includes(v) : value === v)
21
+ function wire(el) {
22
+ const own = (node) => node.closest('[data-part="toggle-group"]') === el
23
+ const click = (event) => {
24
+ const item = event.target.closest('[data-part="toggle-item"]')
25
+ if (!item || !own(item) || item.disabled) return
26
+ const v = item.dataset.value
27
+ if (type === 'multiple') values = values.includes(v) ? values.filter((x) => x !== v) : [...values, v]
28
+ else if (value !== v) value = v
29
+ }
30
+ el.addEventListener('click', click)
31
+ const stopKeys = rovingFocus(el, { items: '[data-part="toggle-item"]' })
32
+ const stopSync = effect(() => {
33
+ for (const item of el.querySelectorAll('[data-part="toggle-item"]')) {
34
+ if (!own(item)) continue
35
+ const on = isOn(item.dataset.value)
36
+ item.setAttribute('aria-pressed', String(on))
37
+ item.dataset.state = on ? 'on' : 'off'
38
+ }
39
+ })
40
+ return () => {
41
+ el.removeEventListener('click', click)
42
+ stopKeys()
43
+ stopSync()
44
+ }
45
+ }
46
+ </script>
47
+
48
+ <div role="group" [aria-label]="label" data-part="toggle-group" [data-type]="type" [use]="wire"><slot /></div>
@@ -0,0 +1,16 @@
1
+ {{-- Toggle item: one toggle inside <toggle-group>; [value] is what it adds to the group's value. --}}
2
+ @context toggleGroup: { type: string; value: string; values: string[] }
3
+ @input value: string
4
+ @input disabled: boolean = false
5
+
6
+ <button
7
+ type="button"
8
+ [aria-pressed]="String(toggleGroup.type === 'multiple' ? toggleGroup.values.includes(value) : toggleGroup.value === value)"
9
+ [data-state]="(toggleGroup.type === 'multiple' ? toggleGroup.values.includes(value) : toggleGroup.value === value) ? 'on' : 'off'"
10
+ [tabindex]="toggleGroup.type === 'single' && toggleGroup.value !== '' && toggleGroup.value !== value ? -1 : 0"
11
+ [data-value]="value"
12
+ [disabled]="disabled"
13
+ data-part="toggle-item"
14
+ >
15
+ <slot />
16
+ </button>
@@ -0,0 +1,10 @@
1
+ {{--
2
+ Toggle: a button that is on or off (aria-pressed), bound with [(pressed)]. A small island.
3
+
4
+ <toggle [(pressed)]="bold" aria-label="Bold">B</toggle>
5
+ --}}
6
+ @model pressed: boolean = false
7
+
8
+ <button type="button" [aria-pressed]="String(pressed)" [data-state]="pressed ? 'on' : 'off'" data-part="toggle" (click)="pressed = !pressed">
9
+ <slot />
10
+ </button>
@@ -0,0 +1,59 @@
1
+ {{--
2
+ Tooltip trigger (#465): a button described by its <tooltip>, and its anchor. Browsers with interest invokers
3
+ (interestfor) show and hide the tooltip themselves; elsewhere this small island does: on hover (after a short delay)
4
+ and focus, kept open while the pointer is on the tooltip, closed on Escape, blur or leaving.
5
+ --}}
6
+ @input target: string
7
+
8
+ <script>
9
+ function wire(el) {
10
+ if ('interestForElement' in el) return // the browser does it
11
+ const tip = () => document.getElementById(target)
12
+ let timer
13
+ const later = (fn, ms) => {
14
+ clearTimeout(timer)
15
+ timer = setTimeout(fn, ms)
16
+ }
17
+ const open = () => {
18
+ const t = tip()
19
+ if (t && !t.matches(':popover-open')) t.showPopover()
20
+ }
21
+ const close = () => {
22
+ clearTimeout(timer)
23
+ const t = tip()
24
+ if (t?.matches(':popover-open')) t.hidePopover()
25
+ }
26
+ const enter = () => later(open, 300)
27
+ // Focus keeps it open: leaving with the pointer closes it only when the trigger isn't focused.
28
+ const leave = () => document.activeElement === el || later(close, 100)
29
+ const key = (event) => {
30
+ if (event.key === 'Escape') close()
31
+ }
32
+ const t = tip()
33
+ const on = [
34
+ [el, 'pointerenter', enter],
35
+ [el, 'pointerleave', leave],
36
+ [el, 'focus', open],
37
+ [el, 'blur', close],
38
+ [el, 'keydown', key],
39
+ [t, 'pointerenter', () => clearTimeout(timer)],
40
+ [t, 'pointerleave', leave],
41
+ ]
42
+ for (const [node, type, fn] of on) node?.addEventListener(type, fn)
43
+ return () => {
44
+ clearTimeout(timer)
45
+ for (const [node, type, fn] of on) node?.removeEventListener(type, fn)
46
+ }
47
+ }
48
+ </script>
49
+
50
+ <button
51
+ type="button"
52
+ [interestfor]="target"
53
+ [aria-describedby]="target"
54
+ [style]="'anchor-name: --' + target"
55
+ data-part="trigger"
56
+ [use]="wire"
57
+ >
58
+ <slot />
59
+ </button>
@@ -0,0 +1,21 @@
1
+ {{--
2
+ Tooltip (#465): a hint popover (popover="hint": it doesn't close other popovers), placed next to its
3
+ <tooltip-trigger> by CSS anchor positioning, flipping when there's no room. The trigger shows it on hover and focus.
4
+ Short text only; nothing in it can be clicked.
5
+
6
+ <tooltip-trigger target="copy-tip">Copy</tooltip-trigger>
7
+ <tooltip id="copy-tip">Copy the link</tooltip>
8
+ --}}
9
+ @input id: string
10
+ @input side: 'top' | 'bottom' | 'left' | 'right' = 'top'
11
+
12
+ <div
13
+ [id]="id"
14
+ popover="hint"
15
+ role="tooltip"
16
+ data-part="tooltip"
17
+ [data-side]="side"
18
+ [style]="'position-anchor: --' + id + '; position-area: ' + side + '; position-try-fallbacks: flip-block, flip-inline'"
19
+ >
20
+ <slot />
21
+ </div>
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Mark `el` open, with data-starting-style for its first frame so CSS transitions run from there. An element rendered
3
+ * open on the server doesn't need it (nothing to animate in).
4
+ * @param {HTMLElement} el
5
+ * @returns {Promise<void>} When the starting style is gone.
6
+ * @example
7
+ * @if (open) { <div class="popup" [use]="enter">…</div> }
8
+ * @see https://clarusjs.com/guide/ui-primitives#enter-and-exit
9
+ */
10
+ export declare function enter(el: HTMLElement): Promise<void>;
11
+ /**
12
+ * Mark `el` closing: data-closed and data-ending-style, until its animations and transitions finish. Remove or hide
13
+ * it after: `await exit(el)`.
14
+ * @param {HTMLElement} el
15
+ * @returns {Promise<void>}
16
+ * @see https://clarusjs.com/guide/ui-primitives#enter-and-exit
17
+ */
18
+ export declare function exit(el: HTMLElement): Promise<void>;
@@ -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
+ }