@clarusjs/ui-primitives 0.1.0 → 0.3.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.
- package/README.md +2 -0
- package/package.json +7 -3
- package/src/chip-input.tscl +77 -0
- package/src/combobox.tscl +28 -9
- package/src/field.tscl +5 -0
- package/src/index.d.ts +2 -0
- package/src/index.js +4 -0
- package/src/resize-column.d.ts +18 -0
- package/src/resize-column.js +56 -0
- package/src/roving-focus.d.ts +1 -1
- package/src/roving-focus.js +2 -2
- package/src/sidebar-trigger.tscl +54 -0
- package/src/sidebar.d.ts +8 -0
- package/src/sidebar.js +21 -0
- package/src/sidebar.tscl +13 -0
- package/src/toast-region.tscl +174 -0
- package/src/toast.d.ts +48 -0
- package/src/toast.js +56 -0
- package/src/toggle-group.tscl +48 -0
- package/src/toggle-item.tscl +16 -0
- package/src/toggle.tscl +10 -0
package/README.md
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
Accessible behaviours for [clarusjs](https://clarusjs.com) components, as small DOM functions. Each takes an element
|
|
4
4
|
(and options) and returns how to stop it; a template hands it the element with `[use]`.
|
|
5
5
|
|
|
6
|
+
Styled components built on them, ready to copy into your project: [ui.clarusjs.com](https://ui.clarusjs.com).
|
|
7
|
+
|
|
6
8
|
```sh
|
|
7
9
|
pnpm add @clarusjs/ui-primitives
|
|
8
10
|
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clarusjs/ui-primitives",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Accessible behaviours for clarusjs components: roving focus, typeahead, dismiss, transitions, focus return and positioning, as small DOM functions for [use].",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -10,6 +10,10 @@
|
|
|
10
10
|
"LICENSE",
|
|
11
11
|
"README.md"
|
|
12
12
|
],
|
|
13
|
+
"clarusjs": {
|
|
14
|
+
"components": "./src",
|
|
15
|
+
"prefix": "ui"
|
|
16
|
+
},
|
|
13
17
|
"exports": {
|
|
14
18
|
".": "./src/index.js",
|
|
15
19
|
"./*": "./src/*"
|
|
@@ -18,7 +22,7 @@
|
|
|
18
22
|
"access": "public"
|
|
19
23
|
},
|
|
20
24
|
"peerDependencies": {
|
|
21
|
-
"clarusjs": "^0.
|
|
25
|
+
"clarusjs": "^0.17.0"
|
|
22
26
|
},
|
|
23
27
|
"engines": {
|
|
24
28
|
"node": "^22.12.0 || ^24.0.0 || >=26.0.0"
|
|
@@ -41,7 +45,7 @@
|
|
|
41
45
|
},
|
|
42
46
|
"devDependencies": {
|
|
43
47
|
"@types/node": "^26.6.6",
|
|
44
|
-
"clarusjs": "^0.
|
|
48
|
+
"clarusjs": "^0.17.0",
|
|
45
49
|
"happy-dom": "^21.0.4",
|
|
46
50
|
"typescript": "^7.0.2",
|
|
47
51
|
"vite": "^8.3.8",
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
{{--
|
|
2
|
+
Chip input: values typed into one field, each becoming a chip (tags, email addresses). Enter or a comma adds what's
|
|
3
|
+
typed; Backspace in the empty field removes the last chip; each chip's × removes it. Bind the list with
|
|
4
|
+
[(values)]; with [name], a hidden input per value sends them with a form.
|
|
5
|
+
|
|
6
|
+
<chip-input [id]="'tags'" [label]="'Tags'" [name]="'tag'" [(values)]="post.tags" />
|
|
7
|
+
|
|
8
|
+
Headless: data-part names each element (chip-input, label, control, chip, input, hint). Each add or removal sends
|
|
9
|
+
(change) first, with the value and whether it's now in; $info.reason is 'add' or 'remove', and $info.cancel() keeps it
|
|
10
|
+
from happening: <chip-input … (change)="if ($event.added && !valid($event.value)) $info.cancel()" />
|
|
11
|
+
--}}
|
|
12
|
+
@input id: string = 'chips'
|
|
13
|
+
@input label: string = 'Tags'
|
|
14
|
+
@input name: string = ''
|
|
15
|
+
@input placeholder: string = 'Add…'
|
|
16
|
+
@input hint: string = 'Enter or comma adds; Backspace removes the last.'
|
|
17
|
+
@model values: string[] = []
|
|
18
|
+
@event change: { value: string; added: boolean }
|
|
19
|
+
|
|
20
|
+
<script>
|
|
21
|
+
let text = state('')
|
|
22
|
+
|
|
23
|
+
function add(raw) {
|
|
24
|
+
const value = raw.trim()
|
|
25
|
+
text = ''
|
|
26
|
+
if (!value || values.includes(value)) return
|
|
27
|
+
if (!emit('change', { value, added: true }, { reason: 'add' })) return
|
|
28
|
+
values = [...values, value]
|
|
29
|
+
}
|
|
30
|
+
function remove(value, event) {
|
|
31
|
+
if (!emit('change', { value, added: false }, { reason: 'remove', event })) return
|
|
32
|
+
values = values.filter((v) => v !== value)
|
|
33
|
+
}
|
|
34
|
+
function key(event) {
|
|
35
|
+
if (event.key === 'Enter' || event.key === ',') {
|
|
36
|
+
event.preventDefault()
|
|
37
|
+
add(text)
|
|
38
|
+
} else if (event.key === 'Backspace' && !text && values.length) {
|
|
39
|
+
remove(values[values.length - 1], event)
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
// A comma typed or pasted in: everything before it becomes chips.
|
|
43
|
+
function type(next) {
|
|
44
|
+
const parts = next.split(',')
|
|
45
|
+
const rest = parts.pop()
|
|
46
|
+
for (const p of parts) add(p)
|
|
47
|
+
text = rest
|
|
48
|
+
}
|
|
49
|
+
</script>
|
|
50
|
+
|
|
51
|
+
<div data-part="chip-input">
|
|
52
|
+
<label [for]="id + '-input'" data-part="label">{{ label }}</label>
|
|
53
|
+
<div data-part="control">
|
|
54
|
+
@for (v of values; track v) {
|
|
55
|
+
<span data-part="chip"
|
|
56
|
+
>{{ v }} <button type="button" [aria-label]="'Remove ' + v" (click)="remove(v, $event)">×</button></span
|
|
57
|
+
>
|
|
58
|
+
}
|
|
59
|
+
<input
|
|
60
|
+
[id]="id + '-input'"
|
|
61
|
+
data-part="input"
|
|
62
|
+
autocomplete="off"
|
|
63
|
+
[aria-describedby]="id + '-hint'"
|
|
64
|
+
[placeholder]="placeholder"
|
|
65
|
+
[value]="text"
|
|
66
|
+
(input)="type($event.target.value)"
|
|
67
|
+
(keydown)="key($event)"
|
|
68
|
+
(blur)="add(text)"
|
|
69
|
+
/>
|
|
70
|
+
</div>
|
|
71
|
+
<p [id]="id + '-hint'" data-part="hint">{{ hint }}</p>
|
|
72
|
+
@if (name) {
|
|
73
|
+
@for (v of values; track v) {
|
|
74
|
+
<input type="hidden" [name]="name" [value]="v" />
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
</div>
|
package/src/combobox.tscl
CHANGED
|
@@ -11,6 +11,10 @@
|
|
|
11
11
|
|
|
12
12
|
Remote options: give [src] a URL; typing asks it for `src?q=<search>` (JSON: [{ value, label }]), 200 ms after the
|
|
13
13
|
last key, and the newest search wins. <combobox [id]="'city'" [label]="'City'" [src]="'/api/cities'" [(value)]="city" />
|
|
14
|
+
Or answer each search yourself (an API client, IndexedDB, a worker): (search) brings the term and an AbortSignal (a
|
|
15
|
+
newer search aborts it); respond with the options or a promise of them, from an island's script:
|
|
16
|
+
<combobox [id]="'lang'" (search)="$event.respond(findLanguages($event.term, $event.signal))" />
|
|
17
|
+
Either way, answers are cached by search (by src, or by id for (search)).
|
|
14
18
|
|
|
15
19
|
Keyboard: ↑ ↓ move, Home / End jump, Enter picks, Esc closes, Backspace in an empty search removes the last pick.
|
|
16
20
|
|
|
@@ -38,6 +42,7 @@
|
|
|
38
42
|
@model value: string = ''
|
|
39
43
|
@model values: string[] = []
|
|
40
44
|
@event change: { value: string; label: string; selected: boolean }
|
|
45
|
+
@event search: { term: string; signal: AbortSignal; respond: (options: Option[] | Promise<Option[]>) => void }
|
|
41
46
|
|
|
42
47
|
<script>
|
|
43
48
|
import { json, resource } from 'clarusjs/fetch'
|
|
@@ -49,23 +54,37 @@
|
|
|
49
54
|
let active = state(0)
|
|
50
55
|
// What's chosen, as a list in both modes.
|
|
51
56
|
const chosen = derived(() => (multiple ? values : value ? [value] : []))
|
|
52
|
-
//
|
|
57
|
+
// Answered by a (search) listener (known once one responds) or by src: the answer for the term, cached by it;
|
|
58
|
+
// nothing is asked until the list opens.
|
|
59
|
+
// A plain flag, not state: the fetcher runs while the options are read, where state can't be written.
|
|
60
|
+
let answered = false
|
|
61
|
+
const remotely = () => answered || !!src
|
|
53
62
|
const remote = resource(
|
|
54
|
-
({ signal }) =>
|
|
55
|
-
|
|
56
|
-
|
|
63
|
+
({ signal }) => {
|
|
64
|
+
if (!open) return false
|
|
65
|
+
let answer
|
|
66
|
+
emit('search', { term, signal, respond: (options) => (answer = options) })
|
|
67
|
+
if (answer !== undefined) {
|
|
68
|
+
answered = true
|
|
69
|
+
return Promise.resolve(answer)
|
|
70
|
+
}
|
|
71
|
+
return src ? json(src + (src.includes('?') ? '&' : '?') + 'q=' + encodeURIComponent(term), { signal }) : false
|
|
72
|
+
},
|
|
73
|
+
{ key: () => (open ? ['combobox', src || '#' + id, term] : false) },
|
|
57
74
|
)
|
|
58
75
|
// The options matching what's typed (by label, ignoring case), or the server's.
|
|
59
76
|
const shown = derived(() => {
|
|
60
|
-
|
|
77
|
+
const answer = remote.value // read first, always: the first (search) answer arrives after this runs
|
|
78
|
+
if (remotely()) return answer ?? []
|
|
61
79
|
const q = query.trim().toLowerCase()
|
|
62
80
|
return q ? options.filter((o) => o.label.toLowerCase().includes(q)) : options
|
|
63
81
|
})
|
|
64
82
|
const labelOf = (v) => known[v] ?? options.find((o) => o.value === v)?.label ?? v
|
|
65
83
|
const status = derived(() => {
|
|
66
84
|
if (!open) return ''
|
|
67
|
-
|
|
68
|
-
if (
|
|
85
|
+
const { loading, error } = remote
|
|
86
|
+
if (remotely() && loading) return 'Searching…'
|
|
87
|
+
if (remotely() && error) return "Couldn't load the options."
|
|
69
88
|
return shown.length ? '' : 'No match for "' + query + '"'
|
|
70
89
|
})
|
|
71
90
|
|
|
@@ -86,7 +105,7 @@
|
|
|
86
105
|
)
|
|
87
106
|
)
|
|
88
107
|
return
|
|
89
|
-
if (
|
|
108
|
+
if (remotely()) known = { ...known, [option.value]: option.label }
|
|
90
109
|
if (multiple) {
|
|
91
110
|
values = chosen.includes(option.value) ? chosen.filter((v) => v !== option.value) : [...chosen, option.value]
|
|
92
111
|
} else {
|
|
@@ -105,7 +124,7 @@
|
|
|
105
124
|
open = true
|
|
106
125
|
active = 0
|
|
107
126
|
clearTimeout(timer)
|
|
108
|
-
timer = setTimeout(() => (term = text),
|
|
127
|
+
timer = setTimeout(() => (term = text), remotely() ? 200 : 0)
|
|
109
128
|
}
|
|
110
129
|
function key(event) {
|
|
111
130
|
const last = shown.length - 1
|
package/src/field.tscl
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
parent when it's left: (blur).
|
|
6
6
|
|
|
7
7
|
<field id="email" label="Email" type="email" [error]="errors.email" [(value)]="form.email" />
|
|
8
|
+
autocomplete and inputmode go on the input: autocomplete="cc-number" inputmode="numeric" for a card number.
|
|
8
9
|
--}}
|
|
9
10
|
@input id: string
|
|
10
11
|
@input label: string
|
|
@@ -15,6 +16,8 @@
|
|
|
15
16
|
@input name: string = ''
|
|
16
17
|
@input placeholder: string = ''
|
|
17
18
|
@input required: boolean = false
|
|
19
|
+
@input autocomplete: string = ''
|
|
20
|
+
@input inputmode: string = ''
|
|
18
21
|
@model value: string = ''
|
|
19
22
|
@event blur
|
|
20
23
|
|
|
@@ -38,6 +41,8 @@
|
|
|
38
41
|
[name]="name || false"
|
|
39
42
|
[placeholder]="placeholder || false"
|
|
40
43
|
[required]="required"
|
|
44
|
+
[autocomplete]="autocomplete || false"
|
|
45
|
+
[inputmode]="inputmode || false"
|
|
41
46
|
[(value)]="value"
|
|
42
47
|
[aria-invalid]="invalid ? 'true' : false"
|
|
43
48
|
[aria-describedby]="[description ? id + '-description' : '', invalid ? id + '-error' : ''].filter(Boolean).join(' ') || false"
|
package/src/index.d.ts
CHANGED
|
@@ -4,3 +4,5 @@ export { dismiss } from './dismiss.js';
|
|
|
4
4
|
export { enter, exit } from './transition.js';
|
|
5
5
|
export { focusReturn } from './focus-return.js';
|
|
6
6
|
export { position } from './position.js';
|
|
7
|
+
export { toast, dismissToast, toasts, subscribeToasts, clearToasts } from './toast.js';
|
|
8
|
+
export { SIDEBAR_KEY, SIDEBAR_SCRIPT, toggleSidebar } from './sidebar.js';
|
package/src/index.js
CHANGED
|
@@ -6,3 +6,7 @@ export { dismiss } from './dismiss.js'
|
|
|
6
6
|
export { enter, exit } from './transition.js'
|
|
7
7
|
export { focusReturn } from './focus-return.js'
|
|
8
8
|
export { position } from './position.js'
|
|
9
|
+
export { toast, dismissToast, toasts, subscribeToasts, clearToasts } from './toast.js'
|
|
10
|
+
export { SIDEBAR_KEY, SIDEBAR_SCRIPT, toggleSidebar } from './sidebar.js'
|
|
11
|
+
// ponytail: resizeColumn isn't here, since all of these together are held to 3 KB gzip and it would take them past;
|
|
12
|
+
// import it as '@clarusjs/ui-primitives/resize-column.js'. Add it here with the budget raise, if that comes.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Make `handle` (inside a `<th>`) a vertical separator that resizes its column: drag it, or focus it and use the
|
|
3
|
+
* arrow keys (by `step`), Home and End (to `min` and `max`). Right to left, the arrows and the drag follow the line.
|
|
4
|
+
* @param {HTMLElement} handle
|
|
5
|
+
* @param {{ min?: number, max?: number, step?: number, target?: HTMLElement, onResize?: (width: number) => void }} [options]
|
|
6
|
+
* `target`: the element to size (the handle's `<th>` unless you say).
|
|
7
|
+
* @returns {() => void}
|
|
8
|
+
* @example
|
|
9
|
+
* <th>Name <span [use]="(el) => resizeColumn(el, { onResize: (w) => save('name', w) })" aria-label="Resize Name"></span></th>
|
|
10
|
+
* @see https://clarusjs.com/guide/ui-primitives#resizecolumn
|
|
11
|
+
*/
|
|
12
|
+
export declare function resizeColumn(handle: HTMLElement, { min, max, step, target, onResize }?: {
|
|
13
|
+
min?: number;
|
|
14
|
+
max?: number;
|
|
15
|
+
step?: number;
|
|
16
|
+
target?: HTMLElement;
|
|
17
|
+
onResize?: (width: number) => void;
|
|
18
|
+
}): () => void;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// resizeColumn: a table column's resize handle, dragged or moved with the keyboard (after TanStack Table's column
|
|
2
|
+
// resizing). It sets the column's width as it goes; onResize gets the width to keep (at the end of a drag).
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Make `handle` (inside a `<th>`) a vertical separator that resizes its column: drag it, or focus it and use the
|
|
6
|
+
* arrow keys (by `step`), Home and End (to `min` and `max`). Right to left, the arrows and the drag follow the line.
|
|
7
|
+
* @param {HTMLElement} handle
|
|
8
|
+
* @param {{ min?: number, max?: number, step?: number, target?: HTMLElement, onResize?: (width: number) => void }} [options]
|
|
9
|
+
* `target`: the element to size (the handle's `<th>` unless you say).
|
|
10
|
+
* @returns {() => void}
|
|
11
|
+
* @example
|
|
12
|
+
* <th>Name <span [use]="(el) => resizeColumn(el, { onResize: (w) => save('name', w) })" aria-label="Resize Name"></span></th>
|
|
13
|
+
* @see https://clarusjs.com/guide/ui-primitives#resizecolumn
|
|
14
|
+
*/
|
|
15
|
+
export function resizeColumn(handle, { min = 48, max = 1e4, step = 16, target, onResize } = {}) {
|
|
16
|
+
const col = /** @type {HTMLElement} */ (target ?? handle.closest('th'))
|
|
17
|
+
const sign = () => (handle.closest('[dir]')?.getAttribute('dir') === 'rtl' ? -1 : 1)
|
|
18
|
+
let width = Math.round(col.getBoundingClientRect().width)
|
|
19
|
+
let from = 0
|
|
20
|
+
let start = NaN
|
|
21
|
+
const attrs = { role: 'separator', 'aria-orientation': 'vertical', tabindex: '0', 'aria-valuemin': min, 'aria-valuemax': max }
|
|
22
|
+
for (const [k, v] of Object.entries(attrs)) if (!handle.hasAttribute(k)) handle.setAttribute(k, String(v))
|
|
23
|
+
const set = (/** @type {number} */ w, /** @type {boolean} */ done) => {
|
|
24
|
+
width = Math.round(Math.min(max, Math.max(min, w)))
|
|
25
|
+
col.style.width = width + 'px'
|
|
26
|
+
handle.setAttribute('aria-valuenow', String(width))
|
|
27
|
+
if (done) onResize?.(width)
|
|
28
|
+
}
|
|
29
|
+
handle.setAttribute('aria-valuenow', String(width))
|
|
30
|
+
/** @param {PointerEvent} e */
|
|
31
|
+
const down = (e) => {
|
|
32
|
+
if (e.button) return
|
|
33
|
+
e.preventDefault()
|
|
34
|
+
start = e.clientX
|
|
35
|
+
from = width
|
|
36
|
+
handle.setPointerCapture?.(e.pointerId)
|
|
37
|
+
}
|
|
38
|
+
/** @param {PointerEvent} e */
|
|
39
|
+
const move = (e) => start === start && set(from + (e.clientX - start) * sign(), false)
|
|
40
|
+
const up = () => {
|
|
41
|
+
if (start !== start) return
|
|
42
|
+
start = NaN
|
|
43
|
+
set(width, true)
|
|
44
|
+
}
|
|
45
|
+
/** @param {KeyboardEvent} e */
|
|
46
|
+
const key = (e) => {
|
|
47
|
+
const by = { ArrowRight: width + step * sign(), ArrowLeft: width - step * sign(), Home: min, End: max }[e.key]
|
|
48
|
+
if (by === undefined) return
|
|
49
|
+
e.preventDefault()
|
|
50
|
+
set(by, true)
|
|
51
|
+
}
|
|
52
|
+
/** @type {[string, (e: any) => void][]} */
|
|
53
|
+
const on = [['pointerdown', down], ['pointermove', move], ['pointerup', up], ['pointercancel', up], ['keydown', key]]
|
|
54
|
+
for (const [t, f] of on) handle.addEventListener(t, f)
|
|
55
|
+
return () => { for (const [t, f] of on) handle.removeEventListener(t, f) }
|
|
56
|
+
}
|
package/src/roving-focus.d.ts
CHANGED
|
@@ -28,7 +28,7 @@ export type RovingFocusOptions = {
|
|
|
28
28
|
/**
|
|
29
29
|
* One Tab stop for the group `el`: its current item has tabindex 0, the others -1; arrow keys (by orientation, flipped
|
|
30
30
|
* in right-to-left text), Home and End move focus between the enabled items. The current item is the one focused last,
|
|
31
|
-
* else one marked aria-selected, aria-checked, aria-current or data-highlighted, else the first enabled one.
|
|
31
|
+
* else one marked aria-selected, aria-checked, aria-pressed, aria-current or data-highlighted, else the first enabled one.
|
|
32
32
|
* @param {HTMLElement} el
|
|
33
33
|
* @param {RovingFocusOptions} [options]
|
|
34
34
|
* @returns {() => void} Stops it.
|
package/src/roving-focus.js
CHANGED
|
@@ -15,7 +15,7 @@ export const disabled = (/** @type {Element} */ el) => el.hasAttribute('disabled
|
|
|
15
15
|
/**
|
|
16
16
|
* One Tab stop for the group `el`: its current item has tabindex 0, the others -1; arrow keys (by orientation, flipped
|
|
17
17
|
* in right-to-left text), Home and End move focus between the enabled items. The current item is the one focused last,
|
|
18
|
-
* else one marked aria-selected, aria-checked, aria-current or data-highlighted, else the first enabled one.
|
|
18
|
+
* else one marked aria-selected, aria-checked, aria-pressed, aria-current or data-highlighted, else the first enabled one.
|
|
19
19
|
* @param {HTMLElement} el
|
|
20
20
|
* @param {RovingFocusOptions} [options]
|
|
21
21
|
* @returns {() => void} Stops it.
|
|
@@ -29,7 +29,7 @@ export function rovingFocus(el, options = {}) {
|
|
|
29
29
|
const enabled = () => all().filter((item) => !disabled(item))
|
|
30
30
|
/** @param {HTMLElement | undefined} current */
|
|
31
31
|
const settle = (current) => { for (const item of all()) item.tabIndex = item === current ? 0 : -1 }
|
|
32
|
-
const marked = all().find((item) => !disabled(item) && ['aria-selected', 'aria-checked', 'aria-current', 'data-highlighted'].some((a) => item.hasAttribute(a) && item.getAttribute(a) !== 'false'))
|
|
32
|
+
const marked = all().find((item) => !disabled(item) && ['aria-selected', 'aria-checked', 'aria-pressed', 'aria-current', 'data-highlighted'].some((a) => item.hasAttribute(a) && item.getAttribute(a) !== 'false'))
|
|
33
33
|
settle(marked ?? enabled()[0])
|
|
34
34
|
|
|
35
35
|
/** @param {KeyboardEvent} event */
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{{--
|
|
2
|
+
Sidebar trigger: collapses the sidebar on a wide screen (min-width 768px); on a phone it is the sidebar's popover
|
|
3
|
+
invoker (popovertarget), so the browser opens it next to the button in the Tab order. aria-expanded follows both.
|
|
4
|
+
--}}
|
|
5
|
+
@input target: string
|
|
6
|
+
|
|
7
|
+
<script>
|
|
8
|
+
import { toggleSidebar } from '@clarusjs/ui-primitives'
|
|
9
|
+
const WIDE = '(min-width: 768px)'
|
|
10
|
+
let self // the button, from wire (events are delegated to the island, so currentTarget isn't it)
|
|
11
|
+
function toggle(event) {
|
|
12
|
+
const nav = document.getElementById(target)
|
|
13
|
+
if (!(nav instanceof HTMLElement) || !matchMedia(WIDE).matches) return // a phone: the popover toggles itself
|
|
14
|
+
event.preventDefault()
|
|
15
|
+
const next = toggleSidebar(nav)
|
|
16
|
+
self?.setAttribute('aria-expanded', String(next === 'open'))
|
|
17
|
+
}
|
|
18
|
+
function wire(button) {
|
|
19
|
+
self = button
|
|
20
|
+
const nav = document.getElementById(target)
|
|
21
|
+
if (!(nav instanceof HTMLElement)) return
|
|
22
|
+
const media = matchMedia(WIDE)
|
|
23
|
+
const sync = () => {
|
|
24
|
+
const open = media.matches
|
|
25
|
+
? (document.documentElement.dataset.sidebar ?? nav.dataset.state) !== 'collapsed'
|
|
26
|
+
: nav.matches(':popover-open')
|
|
27
|
+
button.setAttribute('aria-expanded', String(open))
|
|
28
|
+
}
|
|
29
|
+
// Widened while open as a phone panel: close it, so it doesn't float over the page.
|
|
30
|
+
const resized = () => {
|
|
31
|
+
if (media.matches && nav.matches(':popover-open')) nav.hidePopover()
|
|
32
|
+
sync()
|
|
33
|
+
}
|
|
34
|
+
nav.addEventListener('toggle', sync)
|
|
35
|
+
media.addEventListener?.('change', resized)
|
|
36
|
+
sync()
|
|
37
|
+
return () => {
|
|
38
|
+
nav.removeEventListener('toggle', sync)
|
|
39
|
+
media.removeEventListener?.('change', resized)
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
</script>
|
|
43
|
+
|
|
44
|
+
<button
|
|
45
|
+
type="button"
|
|
46
|
+
[aria-controls]="target"
|
|
47
|
+
[popovertarget]="target"
|
|
48
|
+
aria-expanded="true"
|
|
49
|
+
data-part="sidebar-trigger"
|
|
50
|
+
[use]="wire"
|
|
51
|
+
(click)="toggle($event)"
|
|
52
|
+
>
|
|
53
|
+
<slot />
|
|
54
|
+
</button>
|
package/src/sidebar.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare const SIDEBAR_KEY = "ui-sidebar";
|
|
2
|
+
export declare const SIDEBAR_SCRIPT: string;
|
|
3
|
+
/**
|
|
4
|
+
* Collapse or reopen the sidebar on a wide screen, and remember it.
|
|
5
|
+
* @param {HTMLElement | null} nav the sidebar (its data-state follows)
|
|
6
|
+
* @returns {'open' | 'collapsed'} the new state
|
|
7
|
+
*/
|
|
8
|
+
export declare function toggleSidebar(nav: HTMLElement | null): 'open' | 'collapsed';
|
package/src/sidebar.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// The sidebar's collapsed state, on <html data-sidebar="open|collapsed">, remembered in localStorage. SIDEBAR_SCRIPT
|
|
2
|
+
// goes inline in the <head> so a remembered collapse applies before the first paint (no jump on load).
|
|
3
|
+
|
|
4
|
+
export const SIDEBAR_KEY = 'ui-sidebar'
|
|
5
|
+
|
|
6
|
+
export const SIDEBAR_SCRIPT = `try{var v=localStorage.getItem(${JSON.stringify(SIDEBAR_KEY)});if(v==="collapsed"||v==="open")document.documentElement.setAttribute("data-sidebar",v)}catch(e){}`
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Collapse or reopen the sidebar on a wide screen, and remember it.
|
|
10
|
+
* @param {HTMLElement | null} nav the sidebar (its data-state follows)
|
|
11
|
+
* @returns {'open' | 'collapsed'} the new state
|
|
12
|
+
*/
|
|
13
|
+
export function toggleSidebar(nav) {
|
|
14
|
+
const root = document.documentElement
|
|
15
|
+
const current = root.dataset.sidebar ?? nav?.dataset.state ?? 'open'
|
|
16
|
+
const next = current === 'collapsed' ? 'open' : 'collapsed'
|
|
17
|
+
root.dataset.sidebar = next
|
|
18
|
+
if (nav) nav.dataset.state = next
|
|
19
|
+
try { localStorage.setItem(SIDEBAR_KEY, next) } catch {}
|
|
20
|
+
return next
|
|
21
|
+
}
|
package/src/sidebar.tscl
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{{--
|
|
2
|
+
Sidebar: the app's navigation beside the page. On a wide screen it sits inline and <sidebar-trigger> collapses it
|
|
3
|
+
(remembered; put SIDEBAR_SCRIPT from @clarusjs/ui-primitives in your <head> so a collapse applies before paint).
|
|
4
|
+
On a phone it's a popover the trigger opens: a click outside and Escape close it. No script of its own.
|
|
5
|
+
|
|
6
|
+
<sidebar id="app-nav" label="Main">…links…</sidebar>
|
|
7
|
+
<sidebar-trigger target="app-nav">Menu</sidebar-trigger>
|
|
8
|
+
--}}
|
|
9
|
+
@input id: string
|
|
10
|
+
@input label: string = 'Sidebar'
|
|
11
|
+
@input collapsed: boolean = false
|
|
12
|
+
|
|
13
|
+
<nav [id]="id" [aria-label]="label" popover="auto" data-part="sidebar" [data-state]="collapsed ? 'collapsed' : 'open'"><slot /></nav>
|
|
@@ -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>
|
package/src/toggle.tscl
ADDED
|
@@ -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>
|