@clarusjs/ui-primitives 0.3.3 → 0.4.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 (76) hide show
  1. package/package.json +6 -6
  2. package/src/accordion-item.tscl +9 -3
  3. package/src/autocomplete.tscl +115 -0
  4. package/src/checkbox-group-key.ts +5 -0
  5. package/src/checkbox-group.tscl +96 -0
  6. package/src/checkbox-item.tscl +18 -0
  7. package/src/checkbox.tscl +15 -7
  8. package/src/chip-input.tscl +24 -15
  9. package/src/combobox.tscl +44 -35
  10. package/src/context-menu.tscl +100 -0
  11. package/src/date-field.tscl +140 -0
  12. package/src/date-segments.ts +55 -0
  13. package/src/dialog-close.tscl +7 -2
  14. package/src/dialog-trigger.tscl +7 -2
  15. package/src/dialog.tscl +10 -4
  16. package/src/{dismiss.js → dismiss.ts} +15 -18
  17. package/src/drag-drop.ts +116 -0
  18. package/src/field.tscl +42 -27
  19. package/src/fieldset.tscl +37 -0
  20. package/src/{focus-return.js → focus-return.ts} +2 -4
  21. package/src/form-errors.tscl +40 -0
  22. package/src/{index.js → index.ts} +8 -8
  23. package/src/menu-item.tscl +9 -3
  24. package/src/menu-list.tscl +1 -1
  25. package/src/menu.tscl +8 -5
  26. package/src/menubar.tscl +69 -0
  27. package/src/nav-menu-key.ts +5 -0
  28. package/src/nav-menu-panel.tscl +11 -0
  29. package/src/nav-menu-trigger.tscl +9 -0
  30. package/src/nav-menu.tscl +78 -0
  31. package/src/number-field.tscl +139 -0
  32. package/src/popover-trigger.tscl +7 -2
  33. package/src/popover.tscl +21 -14
  34. package/src/{position.js → position.ts} +21 -17
  35. package/src/preview-card-trigger.tscl +48 -0
  36. package/src/preview-card.tscl +27 -0
  37. package/src/radio-group.tscl +12 -7
  38. package/src/radio.tscl +13 -6
  39. package/src/{resize-column.js → resize-column.ts} +12 -16
  40. package/src/{roving-focus.js → roving-focus.ts} +19 -20
  41. package/src/select.tscl +27 -17
  42. package/src/sidebar-trigger.tscl +9 -6
  43. package/src/{sidebar.js → sidebar.ts} +5 -3
  44. package/src/sidebar.tscl +11 -4
  45. package/src/sortable-list.tscl +50 -0
  46. package/src/swipe.ts +79 -0
  47. package/src/switch.tscl +15 -7
  48. package/src/tab-panel.tscl +9 -4
  49. package/src/tab.tscl +11 -6
  50. package/src/tabs.tscl +12 -7
  51. package/src/time-field.tscl +139 -0
  52. package/src/toast-region.tscl +10 -4
  53. package/src/toast.ts +61 -0
  54. package/src/toggle-group.tscl +15 -9
  55. package/src/toggle-item.tscl +13 -7
  56. package/src/toggle.tscl +4 -1
  57. package/src/toolbar-separator.tscl +9 -0
  58. package/src/toolbar.tscl +30 -0
  59. package/src/tooltip-trigger.tscl +10 -6
  60. package/src/tooltip.tscl +11 -5
  61. package/src/{transition.js → transition.ts} +3 -6
  62. package/src/{typeahead.js → typeahead.ts} +20 -20
  63. package/src/virtual-grid.ts +100 -0
  64. package/src/virtual-keyboard.ts +36 -0
  65. package/src/virtual-list.ts +82 -0
  66. package/src/dismiss.d.ts +0 -27
  67. package/src/focus-return.d.ts +0 -10
  68. package/src/index.d.ts +0 -8
  69. package/src/position.d.ts +0 -36
  70. package/src/resize-column.d.ts +0 -18
  71. package/src/roving-focus.d.ts +0 -39
  72. package/src/sidebar.d.ts +0 -8
  73. package/src/toast.d.ts +0 -48
  74. package/src/toast.js +0 -56
  75. package/src/transition.d.ts +0 -18
  76. package/src/typeahead.d.ts +0 -35
@@ -0,0 +1,100 @@
1
+ {{--
2
+ Context menu (#677): the menu for what's inside it, opened where you right-click; Shift+F10 or the ContextMenu key
3
+ open it under the focused element, and a long press does on touch. It holds its content and a <menu-list> of
4
+ <menu-item>s (the menu's own parts): the list is a popover, so Escape and a click outside close it; arrow keys, Home,
5
+ End and typeahead move through the items; (select) sends the chosen item's value, then it closes ($info.cancel()
6
+ keeps it open). Focus goes back where it was. Make the content focusable (tabindex="0") so the keyboard can reach it.
7
+
8
+ <context-menu id="file" (select)="run($event)">
9
+ <div tabindex="0">report.pdf</div>
10
+ <menu-list>
11
+ <menu-item value="open">Open</menu-item>
12
+ <menu-item value="delete">Delete</menu-item>
13
+ </menu-list>
14
+ </context-menu>
15
+ --}}
16
+ <script lang="ts">
17
+ import { rovingFocus, typeahead } from '@clarusjs/ui-primitives'
18
+ const { id, longPress = 500 } = props<{
19
+ /** Names its list (`<id>-list`) and items. */
20
+ id: string
21
+ /** How long a touch press opens it, in ms (where the browser doesn't open it on its own); 0: never. */
22
+ longPress?: number
23
+ }>()
24
+ const emit = events<{ select: string }>()
25
+ provide('menu', { id })
26
+
27
+ function wire(el: HTMLElement): () => void {
28
+ const own = (node: Element) => node.closest('[data-part="context-menu"]') === el
29
+ const list = [...el.querySelectorAll<HTMLElement>('[role="menu"]')].find(own)
30
+ if (!list) return () => {}
31
+ const items = `[role="menuitem"][data-menu="${CSS.escape(id)}"]:not([aria-disabled="true"])`
32
+ let back: HTMLElement | null = null
33
+ let opened = false // a long press opened it: the browser's contextmenu that follows isn't a second opening
34
+ let keyboard = false // the contextmenu about to come is from Shift+F10 or the ContextMenu key
35
+ const key = (event: KeyboardEvent) => { keyboard = event.key === 'ContextMenu' || (event.key === 'F10' && event.shiftKey) }
36
+
37
+ /** At (x, y) in the viewport, kept inside it. */
38
+ const openAt = (x: number, y: number) => {
39
+ back = document.activeElement instanceof HTMLElement ? document.activeElement : null
40
+ Object.assign(list.style, { positionAnchor: 'none', positionArea: 'none', inset: 'auto', margin: '0', left: `${x}px`, top: `${y}px` })
41
+ if (!list.matches(':popover-open')) list.showPopover()
42
+ const r = list.getBoundingClientRect()
43
+ if (r.right > innerWidth) list.style.left = `${Math.max(0, innerWidth - r.width - 4)}px`
44
+ if (r.bottom > innerHeight) list.style.top = `${Math.max(0, innerHeight - r.height - 4)}px`
45
+ }
46
+ const contextmenu = (event: MouseEvent) => {
47
+ if (list.contains(event.target as Node)) return // the list's own: the browser's menu
48
+ event.preventDefault()
49
+ if (opened) { opened = false; return } // the browser's own, after a long press that opened it already
50
+ // From the keyboard (Shift+F10, the ContextMenu key), under what has focus: the event's own coordinates vary by
51
+ // browser, so the key that sent it decides
52
+ const at = keyboard ? (event.target as Element).getBoundingClientRect() : null
53
+ keyboard = false
54
+ openAt(at ? at.left : event.clientX, at ? at.bottom : event.clientY)
55
+ }
56
+ // A long press on touch, for browsers that don't send contextmenu for it (iOS Safari)
57
+ let timer = 0, startX = 0, startY = 0
58
+ const down = (event: PointerEvent) => {
59
+ if (event.pointerType !== 'touch' || !longPress || list.contains(event.target as Node)) return
60
+ startX = event.clientX; startY = event.clientY; opened = false
61
+ timer = window.setTimeout(() => { opened = true; openAt(startX, startY) }, longPress)
62
+ }
63
+ const move = (event: PointerEvent) => { if (Math.hypot(event.clientX - startX, event.clientY - startY) > 10) clearTimeout(timer) }
64
+ const up = () => clearTimeout(timer)
65
+ const toggle = (event: Event) => {
66
+ if ((event as ToggleEvent).newState === 'open') list.querySelector<HTMLElement>(items)?.focus()
67
+ else if (back && list.contains(document.activeElement)) back.focus()
68
+ }
69
+ const click = (event: Event) => {
70
+ const item = (event.target as Element).closest<HTMLElement>('[role="menuitem"]')
71
+ if (!item || !own(item) || item.getAttribute('aria-disabled') === 'true') return
72
+ if (emit('select', item.dataset.value!, { reason: 'select', event })) list.hidePopover()
73
+ }
74
+ el.addEventListener('keydown', key)
75
+ el.addEventListener('contextmenu', contextmenu)
76
+ el.addEventListener('pointerdown', down)
77
+ el.addEventListener('pointermove', move)
78
+ el.addEventListener('pointerup', up)
79
+ el.addEventListener('pointercancel', up)
80
+ list.addEventListener('toggle', toggle)
81
+ list.addEventListener('click', click)
82
+ const stopKeys = rovingFocus(list, { items, orientation: 'vertical' })
83
+ const stopType = typeahead(list, { items, onMatch: (item) => item.focus() })
84
+ return () => {
85
+ clearTimeout(timer)
86
+ el.removeEventListener('keydown', key)
87
+ el.removeEventListener('contextmenu', contextmenu)
88
+ el.removeEventListener('pointerdown', down)
89
+ el.removeEventListener('pointermove', move)
90
+ el.removeEventListener('pointerup', up)
91
+ el.removeEventListener('pointercancel', up)
92
+ list.removeEventListener('toggle', toggle)
93
+ list.removeEventListener('click', click)
94
+ stopKeys()
95
+ stopType()
96
+ }
97
+ }
98
+ </script>
99
+
100
+ <div data-part="context-menu" [use]="wire"><slot /></div>
@@ -0,0 +1,140 @@
1
+ {{--
2
+ Date field (#678): a date typed in segments (month, day, year), in the locale's order with its separators, each a
3
+ spinbutton: ↑ ↓ step (wrapping), PageUp/PageDown by ten, Home/End to the ends; digits fill a segment and move on when
4
+ it's full; Backspace clears; ← → and Tab go between segments. Bind [(value)]: 'YYYY-MM-DD' once every segment is
5
+ filled, '' until then. The day keeps within its month (31 March → 30 April). [name] sends the value with a form;
6
+ data-invalid marks a date before [min] or after [max]. The locale is fixed ('en-US' unless given) so the server and
7
+ the browser write the same segments.
8
+
9
+ <date-field id="dob" label="Date of birth" name="dob" [(value)]="person.born" />
10
+ --}}
11
+ <script lang="ts">
12
+ import { untrack } from 'clarusjs/runtime'
13
+ import { dateOrder, daysIn, step, typeDigit } from './date-segments.ts'
14
+ const { id, label, name = '', locale = 'en-US', min = '', max = '', disabled = false } = props<{
15
+ /** Its id, unique on the page: its label and segment ids are made from it. */
16
+ id: string
17
+ /** The field's name, for the group and its segments. */
18
+ label: string
19
+ /** Sends the value ('YYYY-MM-DD') with a form. */
20
+ name?: string
21
+ /** The segments' order and separators. */
22
+ locale?: string
23
+ /** The earliest date ('YYYY-MM-DD'); an earlier one is invalid. */
24
+ min?: string
25
+ /** The latest date ('YYYY-MM-DD'). */
26
+ max?: string
27
+ /** Can't be edited or focused. */
28
+ disabled?: boolean
29
+ }>()
30
+ /** 'YYYY-MM-DD', or '' while a segment is empty. */
31
+ let value = model<string>(() => '')
32
+
33
+ type Kind = 'year' | 'month' | 'day'
34
+ const order = dateOrder(locale) as ({ type: Kind } | { type: 'literal'; text: string })[]
35
+ const read = (iso: string): Record<Kind, number | null> => {
36
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso)
37
+ return m ? { year: Number(m[1]), month: Number(m[2]), day: Number(m[3]) } : { year: null, month: null, day: null }
38
+ }
39
+ let parts = state(read(value))
40
+ const pad = (n: number, width: number) => String(n).padStart(width, '0')
41
+ const iso = derived(() => (parts.year !== null && parts.month !== null && parts.day !== null ? `${pad(parts.year, 4)}-${pad(parts.month, 2)}-${pad(parts.day, 2)}` : ''))
42
+ const invalid = derived(() => !!iso && ((!!min && iso < min) || (!!max && iso > max)))
43
+
44
+ const WIDTH: Record<Kind, number> = { year: 4, month: 2, day: 2 }
45
+ const PLACEHOLDER: Record<Kind, string> = { year: 'yyyy', month: 'mm', day: 'dd' }
46
+ const NAME: Record<Kind, string> = { year: 'year', month: 'month', day: 'day' }
47
+ const low = (_k: Kind) => 1
48
+ const high = (k: Kind) => (k === 'year' ? 9999 : k === 'month' ? 12 : daysIn(parts.year, parts.month))
49
+ const monthName = (m: number) => new Intl.DateTimeFormat(locale, { month: 'long', timeZone: 'UTC' }).format(Date.UTC(2000, m - 1, 1))
50
+ const shown = (k: Kind) => (parts[k] === null ? PLACEHOLDER[k] : pad(parts[k]!, WIDTH[k]))
51
+ const spoken = (k: Kind) => (parts[k] === null ? 'Empty' : k === 'month' ? monthName(parts[k]!) : String(parts[k]))
52
+
53
+ /** A segment set; the day kept within its month; the value follows once every segment is filled. */
54
+ function set(k: Kind, n: number | null): void {
55
+ const next = { ...parts, [k]: n }
56
+ if (next.day !== null) next.day = Math.min(next.day, daysIn(next.year, next.month))
57
+ parts = next
58
+ value = iso
59
+ }
60
+ // The parent's new value (a reset, a date picked elsewhere) into the segments. Only value is followed (untrack): a
61
+ // segment typed changes iso before set() writes value, and that's no reason to read the old value back.
62
+ effect(() => {
63
+ const next = value
64
+ untrack(() => { if (next !== iso) parts = read(next) })
65
+ })
66
+
67
+ let typed = ''
68
+ function key(event: KeyboardEvent, k: Kind): void {
69
+ if (disabled) return
70
+ // Handlers are delegated (currentTarget is the island): the segment is the event's target
71
+ const self = (event.target as Element).closest<HTMLElement>('[role="spinbutton"]')!
72
+ const segments = [...(self.parentElement?.querySelectorAll<HTMLElement>('[role="spinbutton"]') ?? [])]
73
+ const at = segments.indexOf(self)
74
+ const move = (by: number) => segments[at + by]?.focus()
75
+ const rtl = self.closest<HTMLElement>('[dir]')?.dir === 'rtl'
76
+ const keys: Record<string, () => void> = {
77
+ ArrowUp: () => set(k, step(parts[k], 1, low(k), high(k))),
78
+ ArrowDown: () => set(k, step(parts[k], -1, low(k), high(k))),
79
+ PageUp: () => set(k, step(parts[k], 10, low(k), high(k))),
80
+ PageDown: () => set(k, step(parts[k], -10, low(k), high(k))),
81
+ Home: () => set(k, low(k)),
82
+ End: () => set(k, high(k)),
83
+ // Right to left (the nearest dir), the next segment is to the left
84
+ ArrowRight: () => move(rtl ? -1 : 1),
85
+ ArrowLeft: () => move(rtl ? 1 : -1),
86
+ Backspace: () => { typed = typed.slice(0, -1); set(k, typed ? Number(typed) || null : null) },
87
+ Delete: () => { typed = ''; set(k, null) },
88
+ }
89
+ if (/^\d$/.test(event.key)) {
90
+ event.preventDefault()
91
+ const t = typeDigit(typed, event.key, low(k), high(k), WIDTH[k])
92
+ typed = t.buffer
93
+ set(k, t.value)
94
+ if (t.done) move(1)
95
+ return
96
+ }
97
+ if (!keys[event.key]) return
98
+ event.preventDefault()
99
+ if (!event.key.startsWith('Arrow') || event.key === 'ArrowUp' || event.key === 'ArrowDown') typed = event.key === 'Backspace' ? typed : ''
100
+ keys[event.key]!()
101
+ }
102
+ const leave = () => { typed = '' }
103
+ </script>
104
+
105
+ <div
106
+ data-part="date-field"
107
+ role="group"
108
+ [aria-labelledby]="id + '-label'"
109
+ [data-filled]="iso ? '' : false"
110
+ [data-invalid]="invalid ? '' : false"
111
+ [data-disabled]="disabled ? '' : false"
112
+ >
113
+ <span [id]="id + '-label'" data-part="label">{{ label }}</span>
114
+ <div data-part="segments">
115
+ @for (seg of order; track $index) {
116
+ @if (seg.type === 'literal') {
117
+ <span data-part="literal" aria-hidden="true">{{ seg.text }}</span>
118
+ } @else {
119
+ <span
120
+ role="spinbutton"
121
+ data-part="segment"
122
+ [data-segment]="seg.type"
123
+ [tabindex]="disabled ? -1 : 0"
124
+ [aria-label]="NAME[seg.type]"
125
+ [aria-valuemin]="low(seg.type)"
126
+ [aria-valuemax]="high(seg.type)"
127
+ [aria-valuenow]="parts[seg.type] ?? undefined"
128
+ [aria-valuetext]="spoken(seg.type)"
129
+ [aria-disabled]="disabled ? 'true' : undefined"
130
+ [data-placeholder]="parts[seg.type] === null ? '' : false"
131
+ (keydown)="key($event, seg.type)"
132
+ (blur)="leave()"
133
+ >{{ shown(seg.type) }}</span>
134
+ }
135
+ }
136
+ </div>
137
+ @if (name) {
138
+ <input type="hidden" [name]="name" [value]="iso" />
139
+ }
140
+ </div>
@@ -0,0 +1,55 @@
1
+ // The date and time fields' segments (#678, #679): their order and separators by locale, and the arithmetic of one
2
+ // segment: stepping (wrapping within its range) and typing digits. Pure functions, shared by date-field and time-field.
3
+
4
+ /** A segment of a date or time field, by Intl.DateTimeFormat's part types. */
5
+ export type SegmentType = 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second' | 'dayPeriod'
6
+ /** A format's piece: an editable segment, or the text between segments ("/", ", "). */
7
+ export type Part = { type: SegmentType } | { type: 'literal'; text: string }
8
+
9
+ /**
10
+ * A format's parts as segments and separators. Formatted in UTC (no time zone shifts a sample day).
11
+ */
12
+ function parts(locale: string, options: Intl.DateTimeFormatOptions): Part[] {
13
+ return new Intl.DateTimeFormat(locale, { ...options, timeZone: 'UTC' }).formatToParts(Date.UTC(2001, 10, 22, 15, 4, 5)).map((p) =>
14
+ // Spaces as plain spaces: ICU versions differ (newer ones put U+202F before AM/PM), and the server's and the
15
+ // browser's must write the same text
16
+ p.type === 'literal' ? { type: 'literal', text: p.value.replace(/\s/g, ' ') } : { type: p.type as SegmentType })
17
+ }
18
+
19
+ /**
20
+ * A date's segments in the locale's order: month/day/year for 'en-US', day.month.year for 'de-DE'.
21
+ */
22
+ export const dateOrder = (locale: string): Part[] => parts(locale, { year: 'numeric', month: '2-digit', day: '2-digit' })
23
+
24
+ /**
25
+ * A time's segments in the locale's order, with AM/PM where it uses a 12-hour clock.
26
+ */
27
+ export const timeOrder = (locale: string, seconds: boolean): Part[] => parts(locale, { hour: '2-digit', minute: '2-digit', ...(seconds ? { second: '2-digit' } : {}) })
28
+
29
+ /**
30
+ * Days in a month (1–12): a leap February while the year is unknown, so the 29th can be typed before the year.
31
+ */
32
+ export const daysIn = (year: number | null, month: number | null) => (month === null ? 31 : new Date(Date.UTC(year ?? 2000, month, 0)).getUTCDate())
33
+
34
+ /**
35
+ * A segment's value moved by `delta`, wrapping within min…max; an empty one starts at min (up) or max (down).
36
+ */
37
+ export function step(value: number | null, delta: number, min: number, max: number) {
38
+ if (value === null) return delta > 0 ? min : max
39
+ const range = max - min + 1
40
+ return ((((value - min + delta) % range) + range) % range) + min
41
+ }
42
+
43
+ /**
44
+ * A digit typed into a segment: its value so far (null while it isn't one yet, like a month's "0"), what's typed
45
+ * (kept for the next digit), and whether it's done (full, or no digit more could fit) so focus moves on.
46
+ * @param buffer what was typed into this segment so far
47
+ * @param digits the segment's width
48
+ */
49
+ export function typeDigit(buffer: string, digit: string, min: number, max: number, digits: number): { value: number | null; buffer: string; done: boolean } {
50
+ let typed = buffer + digit
51
+ if (Number(typed) > max) typed = digit // past the max: start over with this digit
52
+ const n = Number(typed)
53
+ const done = typed.length >= digits || n * 10 > max
54
+ return { value: n >= min ? n : null, buffer: done ? '' : typed, done }
55
+ }
@@ -1,4 +1,9 @@
1
1
  {{-- Closes the dialog whose id is `target` (command="close"): no JavaScript. --}}
2
- @input target: string
2
+ <script lang="ts">
3
+ const props = props<{
4
+ /** The id of the dialog it closes. */
5
+ target: string
6
+ }>()
7
+ </script>
3
8
 
4
- <button type="button" [commandfor]="target" command="close" data-part="close"><slot /></button>
9
+ <button type="button" [commandfor]="props.target" command="close" data-part="close"><slot /></button>
@@ -1,4 +1,9 @@
1
1
  {{-- Opens the dialog whose id is `target`, as a modal (command="show-modal"): no JavaScript. --}}
2
- @input target: string
2
+ <script lang="ts">
3
+ const props = props<{
4
+ /** The id of the dialog it opens. */
5
+ target: string
6
+ }>()
7
+ </script>
3
8
 
4
- <button type="button" [commandfor]="target" command="show-modal" aria-haspopup="dialog" data-part="trigger"><slot /></button>
9
+ <button type="button" [commandfor]="props.target" command="show-modal" aria-haspopup="dialog" data-part="trigger"><slot /></button>
package/src/dialog.tscl CHANGED
@@ -10,10 +10,16 @@
10
10
  <dialog-close target="confirm">Cancel</dialog-close>
11
11
  </dialog>
12
12
  --}}
13
- @input id: string
14
- @input dismissible: boolean = true
13
+ <script lang="ts">
14
+ const props = props<{
15
+ /** Its id, unique on the page: a <dialog-trigger> or <dialog-close> targets it, and its title id is made from it. */
16
+ id: string
17
+ /** A click outside closes it (Escape always does). */
18
+ dismissible?: boolean
19
+ }>(() => ({ dismissible: true }))
20
+ </script>
15
21
 
16
- <dialog [id]="id" [aria-labelledby]="id + '-title'" [closedby]="dismissible ? 'any' : 'closerequest'" data-part="dialog">
17
- <h2 [id]="id + '-title'" data-part="title"><slot name="title" /></h2>
22
+ <dialog [id]="props.id" [aria-labelledby]="props.id + '-title'" [closedby]="props.dismissible ? 'any' : 'closerequest'" data-part="dialog">
23
+ <h2 [id]="props.id + '-title'" data-part="title"><slot name="title" /></h2>
18
24
  <slot />
19
25
  </dialog>
@@ -2,40 +2,37 @@
2
2
  // Escape closes the topmost only, and a press inside a later layer isn't outside an earlier one (Radix's
3
3
  // DismissableLayer). A cancelable cl:dismiss event on the layer goes first, so a page can keep it open.
4
4
 
5
- /** @type {HTMLElement[]} the open layers, oldest first */
6
- const layers = []
5
+ /** the open layers, oldest first */
6
+ const layers: HTMLElement[] = []
7
7
 
8
- /**
9
- * @typedef {object} DismissOptions
10
- * @property {(reason: 'escape-key' | 'outside-press', event: Event) => void} onDismiss Close it.
11
- * @property {() => (Element | null | undefined)[]} [exclude] Elements whose presses aren't outside (its trigger).
12
- */
8
+ /** What dismiss() calls, and what isn't outside the layer. */
9
+ export interface DismissOptions {
10
+ /** Close it. */
11
+ onDismiss: (reason: 'escape-key' | 'outside-press', event: Event) => void
12
+ /** Elements whose presses aren't outside (its trigger). */
13
+ exclude?: () => (Element | null | undefined)[]
14
+ }
13
15
 
14
16
  /**
15
17
  * Calls `onDismiss` when Escape is pressed while `el` is the topmost layer, or when a pointer goes down outside it
16
18
  * (and outside the layers opened after it, and `exclude()`). Before that, `el` gets a cancelable `cl:dismiss`
17
19
  * event (`detail.reason`); preventDefault() keeps it open.
18
- * @param {HTMLElement} el
19
- * @param {DismissOptions} options
20
- * @returns {() => void} Stops it (when the layer closes).
20
+ * @returns Stops it (when the layer closes).
21
21
  * @example
22
22
  * @if (open) { <div [use]="(el) => dismiss(el, { onDismiss: () => (open = false) })">…</div> }
23
23
  * @see https://clarusjs.com/guide/ui-primitives#dismiss
24
24
  */
25
- export function dismiss(el, options) {
25
+ export function dismiss(el: HTMLElement, options: DismissOptions): () => void {
26
26
  layers.push(el)
27
- /** @param {'escape-key' | 'outside-press'} reason @param {Event} event */
28
- const close = (reason, event) => {
27
+ const close = (reason: 'escape-key' | 'outside-press', event: Event) => {
29
28
  if (el.dispatchEvent(new CustomEvent('cl:dismiss', { detail: { reason }, cancelable: true }))) options.onDismiss(reason, event)
30
29
  }
31
- /** @param {KeyboardEvent} event */
32
- const keydown = (event) => {
30
+ const keydown = (event: KeyboardEvent) => {
33
31
  if (event.key !== 'Escape' || layers.at(-1) !== el) return
34
32
  close('escape-key', event)
35
33
  }
36
- /** @param {PointerEvent} event */
37
- const pointerdown = (event) => {
38
- const target = /** @type {Node} */ (event.target)
34
+ const pointerdown = (event: PointerEvent) => {
35
+ const target = event.target as Node
39
36
  const later = layers.slice(layers.indexOf(el))
40
37
  if (later.some((layer) => layer.contains(target))) return
41
38
  if ((options.exclude?.() ?? []).some((x) => x?.contains(target))) return
@@ -0,0 +1,116 @@
1
+ // Drag and drop (#684): items into zones, with the pointer (touch too) and the keyboard, announced as it goes. Pointer
2
+ // Events, not HTML drag and drop (no touch, no keyboard). It moves nothing itself: onDrop says where an item went, and
3
+ // the app's state (a @for) puts it there. Not in the package's index, to keep that small: import
4
+ // '@clarusjs/ui-primitives/drag-drop.js'.
5
+
6
+ /** How dragDrop() reads the zones and items, and what it calls on a drop. */
7
+ export interface DragDropOptions {
8
+ /** The draggable items (a selector). Default '[data-drag]'. */
9
+ items?: string
10
+ /** The drop zones (a selector). Default '[data-drop]'. */
11
+ zones?: string
12
+ /** Whether a zone takes an item. Default: all. */
13
+ accept?: (item: HTMLElement, zone: HTMLElement) => boolean
14
+ /** Where it went: its zone before and after, and its index among the zone's other items. */
15
+ onDrop: (move: { item: HTMLElement; from: HTMLElement; to: HTMLElement; index: number }) => void
16
+ /** Says each step; default: a status region inside `root`. */
17
+ announce?: (message: string) => void
18
+ }
19
+
20
+ /**
21
+ * Items (`[data-drag]`) dragged between zones (`[data-drop]`) inside `root`. The pointer drags after 4 px; the item
22
+ * follows it, the zone under it gets data-over and the item it would land before data-drop-before. On the keyboard:
23
+ * Space or Enter picks the focused item up, ↑ ↓ move its place, ← → the zone, Space drops, Escape cancels. A zone's
24
+ * name is its aria-label.
25
+ * @returns Stops it.
26
+ */
27
+ export function dragDrop(root: HTMLElement, options: DragDropOptions): () => void {
28
+ const { items = '[data-drag]', zones = '[data-drop]', accept = () => true, onDrop } = options
29
+ let status: HTMLElement | null = null
30
+ const say = options.announce ?? ((m: string) => {
31
+ if (!status) { status = document.createElement('div'); status.setAttribute('role', 'status'); status.style.cssText = 'position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)'; root.append(status) }
32
+ status.textContent = m
33
+ })
34
+ let drag: { item: HTMLElement; from: HTMLElement; to: HTMLElement; index: number } | null = null
35
+ const name = (el: Element) => el.getAttribute('aria-label') ?? el.textContent?.trim() ?? ''
36
+ const others = (zone: Element) => ([...zone.querySelectorAll(items)] as HTMLElement[]).filter((i) => i !== drag?.item)
37
+ /** The zones the dragged item can go: its own, and those that accept it. */
38
+ const open = () => ([...root.querySelectorAll(zones)] as HTMLElement[]).filter((z) => drag && (z === drag.from || accept(drag.item, z)))
39
+ const place = () => (drag ? `${name(drag.to)}, position ${drag.index + 1} of ${others(drag.to).length + 1}` : '')
40
+ const mark = () => {
41
+ for (const el of root.querySelectorAll('[data-over],[data-drop-before]')) el.removeAttribute('data-over'), el.removeAttribute('data-drop-before')
42
+ if (!drag) return
43
+ drag.to.setAttribute('data-over', '')
44
+ others(drag.to)[drag.index]?.setAttribute('data-drop-before', '')
45
+ }
46
+ const start = (item: HTMLElement) => {
47
+ const from = item.closest(zones) as HTMLElement
48
+ drag = { item, from, to: from, index: [...from.querySelectorAll(items)].indexOf(item) }
49
+ item.setAttribute('data-grabbed', '')
50
+ mark()
51
+ say(`Picked up ${name(item)}. Arrow keys move it, Space drops it, Escape cancels. ${place()}`)
52
+ }
53
+ const end = (dropped: boolean) => {
54
+ const d = drag
55
+ if (!d) return
56
+ const at = place()
57
+ drag = null
58
+ mark()
59
+ d.item.removeAttribute('data-grabbed')
60
+ d.item.style.transform = ''
61
+ if (!dropped) return say(`Cancelled. ${name(d.item)} is back where it was.`)
62
+ say(`Dropped ${name(d.item)} in ${at}`)
63
+ onDrop({ item: d.item, from: d.from, to: d.to, index: d.index })
64
+ }
65
+ const itemOf = (event: Event) => (event.target as Element).closest?.(items) as HTMLElement | null
66
+
67
+ let x0 = 0, y0 = 0
68
+ let pending: HTMLElement | null = null
69
+ const on: [EventTarget, string, (event: any) => void][] = [
70
+ [root, 'keydown', (event: KeyboardEvent) => {
71
+ const item = itemOf(event), k = event.key
72
+ if (!item || !root.contains(item)) return
73
+ if (!drag) {
74
+ if (k === ' ' || k === 'Enter') event.preventDefault(), start(item)
75
+ return
76
+ }
77
+ if (k === ' ' || k === 'Enter' || k === 'Escape') return event.preventDefault(), end(k !== 'Escape')
78
+ const list = open(), at = list.indexOf(drag.to)
79
+ if (k === 'ArrowUp' || k === 'ArrowDown') drag.index = Math.max(0, Math.min(others(drag.to).length, drag.index + (k === 'ArrowDown' ? 1 : -1)))
80
+ else if (k === 'ArrowLeft' || k === 'ArrowRight') {
81
+ // Right to left (the nearest dir), the next zone is to the left
82
+ const to = list[at + ((k === 'ArrowRight') === (root.closest('[dir]')?.getAttribute('dir') !== 'rtl') ? 1 : -1)]
83
+ if (!to) return
84
+ drag.to = to
85
+ drag.index = Math.min(drag.index, others(to).length)
86
+ } else return
87
+ event.preventDefault()
88
+ mark()
89
+ say(place())
90
+ }],
91
+ [root, 'pointerdown', (event: PointerEvent) => {
92
+ const item = itemOf(event)
93
+ if (item && !drag && !event.button) pending = item, x0 = event.clientX, y0 = event.clientY
94
+ }],
95
+ [root, 'pointermove', (event: PointerEvent) => {
96
+ if (pending && !drag && Math.hypot(event.clientX - x0, event.clientY - y0) > 4) pending.setPointerCapture?.(event.pointerId), start(pending)
97
+ if (!drag) return
98
+ drag.item.style.transform = `translate(${event.clientX - x0}px,${event.clientY - y0}px)`
99
+ // What's under the pointer, past the dragged item itself (it follows the pointer, so it's always on top)
100
+ const zone = document.elementsFromPoint(event.clientX, event.clientY).filter((el) => !drag?.item.contains(el)).map((el) => el.closest(zones)).find((z) => z && open().includes(z as HTMLElement))
101
+ if (!zone) return
102
+ drag.to = zone as HTMLElement
103
+ const rest = others(zone), after = rest.findIndex((i) => { const r = i.getBoundingClientRect(); return event.clientY < r.top + r.height / 2 })
104
+ drag.index = after < 0 ? rest.length : after
105
+ mark()
106
+ }],
107
+ [root, 'pointerup', () => { pending = null; end(true) }],
108
+ [root, 'pointercancel', () => { pending = null; end(false) }],
109
+ [document, 'keydown', (event: KeyboardEvent) => { if (pending && event.key === 'Escape') pending = null, end(false) }],
110
+ ]
111
+ for (const [t, type, fn] of on) t.addEventListener(type, fn)
112
+ return () => {
113
+ for (const [t, type, fn] of on) t.removeEventListener(type, fn)
114
+ status?.remove()
115
+ }
116
+ }
package/src/field.tscl CHANGED
@@ -7,24 +7,39 @@
7
7
  <field id="email" label="Email" type="email" [error]="errors.email" [(value)]="form.email" />
8
8
  autocomplete and inputmode go on the input: autocomplete="cc-number" inputmode="numeric" for a card number.
9
9
  --}}
10
- @input id: string
11
- @input label: string
12
- @input description: string = ''
13
- @input error: string = ''
14
- @input show: boolean = false
15
- @input type: string = 'text'
16
- @input name: string = ''
17
- @input placeholder: string = ''
18
- @input required: boolean = false
19
- @input autocomplete: string = ''
20
- @input inputmode: string = ''
21
- @model value: string = ''
22
- @event blur
23
10
 
24
- <script>
11
+ <script lang="ts">
12
+ const props = props<{
13
+ /** Its id, unique on the page: the input's id; the description and error ids are made from it. */
14
+ id: string
15
+ /** The field's label. */
16
+ label: string
17
+ /** Help text under the field, linked to it (aria-describedby). */
18
+ description?: string
19
+ /** The error message, shown once the field has been left or [show] is true. */
20
+ error?: string
21
+ /** Shows the error before the field has been left (after a submit). */
22
+ show?: boolean
23
+ /** The input's type: text, email, password, and so on. */
24
+ type?: string
25
+ /** Sends the value with a form, under this name. */
26
+ name?: string
27
+ /** Shown while it's empty: an example of what goes in. */
28
+ placeholder?: string
29
+ /** Must be filled in before the form is sent. */
30
+ required?: boolean
31
+ /** The input's autocomplete hint for browsers (e.g. 'email', 'cc-number'). */
32
+ autocomplete?: string
33
+ /** Which on-screen keyboard to show (e.g. 'numeric', 'email'). */
34
+ inputmode?: string
35
+ }>(() => ({ description: '', error: '', show: false, type: 'text', name: '', placeholder: '', required: false, autocomplete: '', inputmode: '' }))
36
+ /** The field's text, bound two ways with [(value)]. */
37
+ let value = model<string>(() => '')
38
+ const emit = events<{ blur: void }>()
39
+
25
40
  let touched = state(false)
26
41
  const initial = value
27
- const invalid = derived(() => !!error && (touched || show))
42
+ const invalid = derived(() => !!props.error && (touched || props.show))
28
43
  </script>
29
44
 
30
45
  <div
@@ -34,25 +49,25 @@
34
49
  [data-filled]="value ? '' : false"
35
50
  [data-invalid]="invalid ? '' : false"
36
51
  >
37
- <label [for]="id" data-part="label">{{ label }}</label>
52
+ <label [for]="props.id" data-part="label">{{ props.label }}</label>
38
53
  <input
39
- [id]="id"
40
- [type]="type"
41
- [name]="name || false"
42
- [placeholder]="placeholder || false"
43
- [required]="required"
44
- [autocomplete]="autocomplete || false"
45
- [inputmode]="inputmode || false"
54
+ [id]="props.id"
55
+ [type]="props.type"
56
+ [name]="props.name || false"
57
+ [placeholder]="props.placeholder || false"
58
+ [required]="props.required"
59
+ [autocomplete]="props.autocomplete || false"
60
+ [inputmode]="props.inputmode || false"
46
61
  [(value)]="value"
47
62
  [aria-invalid]="invalid ? 'true' : false"
48
- [aria-describedby]="[description ? id + '-description' : '', invalid ? id + '-error' : ''].filter(Boolean).join(' ') || false"
63
+ [aria-describedby]="[props.description ? props.id + '-description' : '', invalid ? props.id + '-error' : ''].filter(Boolean).join(' ') || false"
49
64
  (blur)="touched = true; emit('blur')"
50
65
  data-part="control"
51
66
  />
52
- @if (description) {
53
- <p [id]="id + '-description'" data-part="description">{{ description }}</p>
67
+ @if (props.description) {
68
+ <p [id]="props.id + '-description'" data-part="description">{{ props.description }}</p>
54
69
  }
55
70
  @if (invalid) {
56
- <p [id]="id + '-error'" data-part="error" role="alert">{{ error }}</p>
71
+ <p [id]="props.id + '-error'" data-part="error" role="alert">{{ props.error }}</p>
57
72
  }
58
73
  </div>
@@ -0,0 +1,37 @@
1
+ {{--
2
+ Fieldset (#675): a native <fieldset> and <legend> around related fields. [disabled] is the browser's: every control
3
+ inside is disabled and left out of the form. A [description] under the legend describes the group (aria-describedby,
4
+ so give the fieldset an [id]). No JavaScript: the fields' validity rolls up in CSS, [data-part='fieldset']:has([data-invalid]),
5
+ where each <field> marks itself invalid.
6
+
7
+ <fieldset legend="Shipping address" id="ship">
8
+ <field id="street" label="Street" [(value)]="address.street" />
9
+ <field id="city" label="City" [(value)]="address.city" />
10
+ </fieldset>
11
+ --}}
12
+ <script lang="ts">
13
+ const { legend, description = '', disabled = false, id = '' } = props<{
14
+ /** What the fields are, as the group's name. */
15
+ legend: string
16
+ /** More about the group, under the legend. */
17
+ description?: string
18
+ /** Disables every control inside. */
19
+ disabled?: boolean
20
+ /** For the description's id (aria-describedby). */
21
+ id?: string
22
+ }>()
23
+ </script>
24
+
25
+ <fieldset
26
+ data-part="fieldset"
27
+ [id]="id || undefined"
28
+ [disabled]="disabled"
29
+ [data-disabled]="disabled ? '' : false"
30
+ [aria-describedby]="description && id ? id + '-description' : undefined"
31
+ >
32
+ <legend data-part="legend">{{ legend }}</legend>
33
+ @if (description) {
34
+ <p [id]="id ? id + '-description' : undefined" data-part="description">{{ description }}</p>
35
+ }
36
+ <slot />
37
+ </fieldset>