@prunellejs/ui 0.0.0-stage → 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.
package/src/Menu.tsx ADDED
@@ -0,0 +1,115 @@
1
+ /** @jsxImportSource prunelle */
2
+ // Accessible dropdown Menu primitive with roving menuitem focus, link items, ArrowDown/Up trigger open, Escape/Tab close & click-outside dismiss.
3
+
4
+ import type { ButtonVariant } from './static'
5
+ import { createListPopup, nextUiId } from './behaviors'
6
+
7
+ export interface MenuItemDef {
8
+ id: string
9
+ label: string
10
+ href?: string | undefined
11
+ disabled?: boolean | undefined
12
+ onSelect?: (() => void) | undefined
13
+ }
14
+
15
+ export interface MenuProps {
16
+ id?: string | undefined
17
+ label: string
18
+ items: MenuItemDef[]
19
+ variant?: ButtonVariant | undefined
20
+ onSelect?: ((id: string) => void) | undefined
21
+ }
22
+
23
+ export function Menu(props: MenuProps) {
24
+ const baseId = props.id ?? nextUiId('kui-menu')
25
+ const triggerId = `${baseId}-trigger`
26
+ const menuId = `${baseId}-menu`
27
+ const itemId = (idx: number) => `${baseId}-item-${idx}`
28
+ const variant = props.variant ?? 'outline'
29
+ const label = props.label
30
+
31
+ const activate = (item: MenuItemDef, navigateHref: boolean) => {
32
+ if (item.disabled)
33
+ return
34
+ item.onSelect?.()
35
+ props.onSelect?.(item.id)
36
+ popup.close(item.href === undefined)
37
+ if (navigateHref && item.href !== undefined && typeof location !== 'undefined')
38
+ location.assign(item.href)
39
+ }
40
+
41
+ const popup = createListPopup<MenuItemDef>({
42
+ items: () => props.items,
43
+ itemId,
44
+ isDisabled: it => Boolean(it.disabled),
45
+ onSelect: active => activate(active, true),
46
+ focusActive: true,
47
+ })
48
+
49
+ return (
50
+ <div
51
+ data-ui="menu"
52
+ data-state={popup.open.value ? 'open' : 'closed'}
53
+ ref={(el) => { popup.setRoot(el) }}
54
+ >
55
+ <button
56
+ id={triggerId}
57
+ data-ui="button"
58
+ data-variant={variant}
59
+ data-part="trigger"
60
+ type="button"
61
+ aria-haspopup="menu"
62
+ aria-expanded={popup.open.value ? 'true' : 'false'}
63
+ aria-controls={popup.open.value ? menuId : undefined}
64
+ onClick={e => popup.toggle(e)}
65
+ onKeyDown={e => popup.onTriggerKeyDown(e)}
66
+ >
67
+ {label}
68
+ </button>
69
+ {popup.open.value && (
70
+ <div
71
+ id={menuId}
72
+ data-part="content"
73
+ role="menu"
74
+ aria-labelledby={triggerId}
75
+ popover="auto"
76
+ ref={popup.mountPopup}
77
+ >
78
+ {props.items.map((item, idx) => (
79
+ item.href !== undefined && !item.disabled
80
+ ? (
81
+ <a
82
+ key={item.id}
83
+ id={itemId(idx)}
84
+ data-part="item"
85
+ data-highlighted={popup.highlighted.value === idx ? 'true' : undefined}
86
+ role="menuitem"
87
+ href={item.href}
88
+ tabindex={-1}
89
+ onClick={() => activate(item, false)}
90
+ >
91
+ {item.label}
92
+ </a>
93
+ )
94
+ : (
95
+ <button
96
+ key={item.id}
97
+ id={itemId(idx)}
98
+ data-part="item"
99
+ data-highlighted={popup.highlighted.value === idx ? 'true' : undefined}
100
+ role="menuitem"
101
+ type="button"
102
+ tabindex={-1}
103
+ disabled={item.disabled}
104
+ aria-disabled={item.disabled ? 'true' : undefined}
105
+ onClick={() => activate(item, false)}
106
+ >
107
+ {item.label}
108
+ </button>
109
+ )
110
+ ))}
111
+ </div>
112
+ )}
113
+ </div>
114
+ )
115
+ }
package/src/Select.tsx ADDED
@@ -0,0 +1,114 @@
1
+ /** @jsxImportSource prunelle */
2
+ // Accessible custom Select (listbox) primitive with aria-activedescendant navigation + hidden input for native <form> submission.
3
+
4
+ import type { Signal } from 'prunelle'
5
+ import { signal } from 'prunelle'
6
+ import { createListPopup, nextUiId, useFieldContext } from './behaviors'
7
+
8
+ export interface SelectOption {
9
+ value: string
10
+ label: string
11
+ disabled?: boolean | undefined
12
+ }
13
+
14
+ export interface SelectProps {
15
+ id?: string | undefined
16
+ options: SelectOption[]
17
+ value?: Signal<string> | undefined
18
+ defaultValue?: string | undefined
19
+ name?: string | undefined
20
+ placeholder?: string | undefined
21
+ ariaLabel?: string | undefined
22
+ onChange?: ((value: string) => void) | undefined
23
+ }
24
+
25
+ export function Select(props: SelectProps) {
26
+ const field = useFieldContext()
27
+ const baseId = props.id ?? field?.id ?? nextUiId('kui-select')
28
+ let triggerId = props.id ?? field?.id ?? `${baseId}-trigger`
29
+ const listboxId = `${baseId}-listbox`
30
+ const optionId = (idx: number) => `${baseId}-opt-${idx}`
31
+ const name = props.name
32
+ const placeholder = props.placeholder ?? 'Select…'
33
+ const ariaLabel = props.ariaLabel
34
+
35
+ const selected = props.value ?? signal(props.defaultValue ?? props.options[0]?.value ?? '')
36
+ const currentLabel = () => props.options.find(o => o.value === selected.value)?.label ?? placeholder
37
+
38
+ const pick = (opt: SelectOption) => {
39
+ if (opt.disabled)
40
+ return
41
+ selected.value = opt.value
42
+ props.onChange?.(opt.value)
43
+ popup.close(true)
44
+ }
45
+
46
+ const popup = createListPopup<SelectOption>({
47
+ items: () => props.options,
48
+ itemId: optionId,
49
+ isDisabled: opt => Boolean(opt.disabled),
50
+ onSelect: pick,
51
+ initialIndex: () => props.options.findIndex(o => o.value === selected.value && !o.disabled),
52
+ })
53
+
54
+ return (
55
+ <div
56
+ data-ui="select"
57
+ data-state={popup.open.value ? 'open' : 'closed'}
58
+ ref={(el) => {
59
+ popup.setRoot(el)
60
+ if (!props.id && !field)
61
+ triggerId = el.closest('[data-ui="field"]')?.querySelector('label')?.htmlFor || triggerId
62
+ }}
63
+ >
64
+ {name && <input type="hidden" name={name} value={selected.value} />}
65
+ <button
66
+ id={triggerId}
67
+ data-part="trigger"
68
+ type="button"
69
+ role="combobox"
70
+ aria-label={ariaLabel}
71
+ aria-haspopup="listbox"
72
+ aria-expanded={popup.open.value ? 'true' : 'false'}
73
+ aria-controls={popup.open.value ? listboxId : undefined}
74
+ aria-activedescendant={popup.activeDescendantId()}
75
+ onClick={e => popup.toggle(e)}
76
+ onKeyDown={e => popup.onTriggerKeyDown(e)}
77
+ >
78
+ <span data-part="value">{currentLabel()}</span>
79
+ <span aria-hidden="true">▾</span>
80
+ </button>
81
+ {popup.open.value && (
82
+ <div
83
+ id={listboxId}
84
+ data-part="listbox"
85
+ role="listbox"
86
+ aria-label={ariaLabel}
87
+ aria-labelledby={ariaLabel ? undefined : triggerId}
88
+ popover="auto"
89
+ ref={popup.mountPopup}
90
+ >
91
+ {props.options.map((opt, idx) => (
92
+ <button
93
+ key={opt.value}
94
+ id={optionId(idx)}
95
+ data-part="option"
96
+ data-selected={selected.value === opt.value ? 'true' : undefined}
97
+ data-highlighted={popup.highlighted.value === idx ? 'true' : undefined}
98
+ role="option"
99
+ type="button"
100
+ tabindex={-1}
101
+ disabled={opt.disabled}
102
+ aria-disabled={opt.disabled ? 'true' : undefined}
103
+ aria-selected={selected.value === opt.value ? 'true' : 'false'}
104
+ onClick={() => pick(opt)}
105
+ >
106
+ <span>{opt.label}</span>
107
+ <span aria-hidden="true">{selected.value === opt.value ? '✓' : ''}</span>
108
+ </button>
109
+ ))}
110
+ </div>
111
+ )}
112
+ </div>
113
+ )
114
+ }
package/src/Tabs.tsx ADDED
@@ -0,0 +1,63 @@
1
+ /** @jsxImportSource prunelle */
2
+ // Accessible Tabs primitive with roving arrow-key + Home/End keyboard navigation.
3
+
4
+ import type { PrunelleChild } from 'prunelle'
5
+ import { nextUiId } from './behaviors'
6
+ import { createTabs } from './tabs-state'
7
+
8
+ export interface TabDef {
9
+ id: string
10
+ label: string
11
+ content: PrunelleChild
12
+ }
13
+
14
+ export interface TabsProps {
15
+ id?: string | undefined
16
+ items: TabDef[]
17
+ defaultValue?: string | undefined
18
+ label?: string | undefined
19
+ class?: string | undefined
20
+ }
21
+
22
+ export function Tabs({ id, items, defaultValue, label = 'Tabs', class: cls }: TabsProps) {
23
+ const baseId = id ?? nextUiId('kui-tabs')
24
+ const ids = items.map(i => i.id)
25
+ const tabs = createTabs(defaultValue ?? items[0]?.id ?? '')
26
+
27
+ return (
28
+ <div data-ui="tabs" class={cls}>
29
+ <div data-part="list" role="tablist" aria-label={label}>
30
+ {items.map(item => (
31
+ <button
32
+ key={item.id}
33
+ id={`${baseId}-tab-${item.id}`}
34
+ data-part="trigger"
35
+ data-state={tabs.isActive(item.id) ? 'active' : 'inactive'}
36
+ role="tab"
37
+ type="button"
38
+ aria-selected={tabs.isActive(item.id) ? 'true' : 'false'}
39
+ aria-controls={`${baseId}-panel-${item.id}`}
40
+ tabIndex={tabs.isActive(item.id) ? 0 : -1}
41
+ onClick={() => tabs.select(item.id)}
42
+ onKeyDown={e => tabs.onKeyDown(e, ids)}
43
+ >
44
+ {item.label}
45
+ </button>
46
+ ))}
47
+ </div>
48
+ {items.map(item => (
49
+ <div
50
+ key={item.id}
51
+ id={`${baseId}-panel-${item.id}`}
52
+ data-part="panel"
53
+ data-state={tabs.isActive(item.id) ? 'active' : 'inactive'}
54
+ role="tabpanel"
55
+ aria-labelledby={`${baseId}-tab-${item.id}`}
56
+ hidden={!tabs.isActive(item.id)}
57
+ >
58
+ {item.content}
59
+ </div>
60
+ ))}
61
+ </div>
62
+ )
63
+ }
@@ -0,0 +1,31 @@
1
+ /** @jsxImportSource prunelle */
2
+ // Live-region Toast stack driven by the reactive `toast` store.
3
+
4
+ import { toast } from './toast'
5
+
6
+ export interface ToasterProps {
7
+ dismissLabel?: string | undefined
8
+ }
9
+
10
+ export function Toaster({ dismissLabel = 'Dismiss' }: ToasterProps = {}) {
11
+ return (
12
+ <div data-ui="toaster" aria-live="polite" aria-atomic="false">
13
+ {toast.items.value.map(item => (
14
+ <div key={item.id} data-ui="toast" data-tone={item.tone} role="status">
15
+ <div>
16
+ <strong data-part="title">{item.title}</strong>
17
+ {item.description && <p data-part="description">{item.description}</p>}
18
+ </div>
19
+ <button
20
+ data-part="close"
21
+ type="button"
22
+ aria-label={dismissLabel}
23
+ onClick={() => toast.dismiss(item.id)}
24
+ >
25
+ ✕
26
+ </button>
27
+ </div>
28
+ ))}
29
+ </div>
30
+ )
31
+ }
@@ -0,0 +1,287 @@
1
+ // Headless signal behavior hooks (zero CSS, zero DOM lock-in — standard TSX `{...spread}`).
2
+ // DataTable and Tabs state live in ./table-state.ts and ./tabs-state.ts so lightweight pages don't download them.
3
+
4
+ import type { Signal } from 'prunelle'
5
+ import { effect, onCleanup, signal, useId } from 'prunelle'
6
+ import { useFieldContext } from './field-context'
7
+
8
+ export { createDataTable } from './table-state'
9
+ export type { DataTableOptions, DataTableState } from './table-state'
10
+ export { createTabs } from './tabs-state'
11
+ export type { TabsBehavior } from './tabs-state'
12
+ export { toast } from './toast'
13
+ export type { ToastItem } from './toast'
14
+ export { useFieldContext }
15
+
16
+ // ---- Stable hydration-safe unique IDs for ARIA wiring ----
17
+
18
+ export function nextUiId(prefix: string): string {
19
+ return useId(prefix)
20
+ }
21
+
22
+ // ---- Shared listbox / menu keyboard navigation ----
23
+
24
+ export function findFirstEnabledIndex<T>(items: readonly T[], isDisabled?: (item: T) => boolean): number {
25
+ return findNextEnabledIndex(items, -1, 1, isDisabled)
26
+ }
27
+
28
+ export function findLastEnabledIndex<T>(items: readonly T[], isDisabled?: (item: T) => boolean): number {
29
+ return findNextEnabledIndex(items, items.length, -1, isDisabled)
30
+ }
31
+
32
+ export function findNextEnabledIndex<T>(
33
+ items: readonly T[],
34
+ current: number,
35
+ delta: 1 | -1,
36
+ isDisabled?: (item: T) => boolean,
37
+ ): number {
38
+ const len = items.length
39
+ if (len === 0)
40
+ return -1
41
+ let idx = current < 0 || current >= len ? (delta === 1 ? -1 : len) : current
42
+ for (let step = 0; step < len; step++) {
43
+ idx = (idx + delta + len) % len
44
+ if (!isDisabled?.(items[idx]!))
45
+ return idx
46
+ }
47
+ return -1
48
+ }
49
+
50
+ export interface ListNavigationOptions<T> {
51
+ items: () => readonly T[]
52
+ activeIndex: Signal<number>
53
+ isDisabled?: ((item: T) => boolean) | undefined
54
+ onSelect: (item: T, index: number) => void
55
+ onClose: (returnFocus?: boolean) => void
56
+ selectOnSpace?: boolean | undefined
57
+ homeEnd?: boolean | undefined
58
+ closeOnTab?: boolean | undefined
59
+ }
60
+
61
+ /** Shared keyboard handler for ARIA menu / listbox / combobox popups (ArrowUp/Down, Home/End, Enter/Space, Escape, Tab). */
62
+ export function handleListKeyDown<T>(e: KeyboardEvent, opts: ListNavigationOptions<T>): boolean {
63
+ const list = opts.items()
64
+ if (e.key === 'Escape') {
65
+ opts.onClose(true)
66
+ return true
67
+ }
68
+ if (e.key === 'Tab') {
69
+ if (opts.closeOnTab === false)
70
+ return false
71
+ opts.onClose(false)
72
+ return true
73
+ }
74
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
75
+ e.preventDefault()
76
+ opts.activeIndex.value = findNextEnabledIndex(list, opts.activeIndex.value, e.key === 'ArrowDown' ? 1 : -1, opts.isDisabled)
77
+ return true
78
+ }
79
+ if (opts.homeEnd !== false && (e.key === 'Home' || e.key === 'End')) {
80
+ e.preventDefault()
81
+ opts.activeIndex.value = (e.key === 'Home' ? findFirstEnabledIndex : findLastEnabledIndex)(list, opts.isDisabled)
82
+ return true
83
+ }
84
+ if (e.key === 'Enter' || (opts.selectOnSpace !== false && e.key === ' ')) {
85
+ const idx = opts.activeIndex.value
86
+ const active = idx >= 0 && idx < list.length ? list[idx] : undefined
87
+ if (active !== undefined && !opts.isDisabled?.(active)) {
88
+ e.preventDefault()
89
+ opts.onSelect(active, idx)
90
+ return true
91
+ }
92
+ }
93
+ return false
94
+ }
95
+
96
+ export interface ListPopupOptions<T> {
97
+ items: () => readonly T[]
98
+ itemId: (idx: number) => string
99
+ isDisabled: (item: T) => boolean
100
+ onSelect: (item: T, idx: number) => void
101
+ initialIndex?: () => number
102
+ focusActive?: boolean | undefined
103
+ }
104
+
105
+ export interface ListPopupState {
106
+ readonly open: Signal<boolean>
107
+ readonly highlighted: Signal<number>
108
+ setRoot(el: HTMLElement | undefined): void
109
+ close(returnFocus?: boolean): void
110
+ toggle(e: MouseEvent): void
111
+ onTriggerKeyDown(e: KeyboardEvent): void
112
+ focusActive(): void
113
+ activeDescendantId(): string | undefined
114
+ /** The popup's `ref`: shows it in the top layer, anchored to the trigger. */
115
+ mountPopup(el: HTMLElement | undefined): void
116
+ }
117
+
118
+ // In the top layer no overflow ancestor clips the popup, and the trigger as its `source` is the anchor CSS places it against and a click the browser does not count as outside.
119
+ function showAnchored(el: HTMLElement, trigger: HTMLElement): void {
120
+ if (el.isConnected && !el.matches(':popover-open'))
121
+ el.showPopover({ source: trigger })
122
+ }
123
+
124
+ /** Shared popup open/close and keyboard list navigation for Menu and Select; the browser dismisses the popup on an outside click. */
125
+ export function createListPopup<T>(opts: ListPopupOptions<T>): ListPopupState {
126
+ const open = signal(false)
127
+ const highlighted = signal(findFirstEnabledIndex(opts.items(), opts.isDisabled))
128
+ let rootEl: HTMLElement | undefined
129
+ let lastOpenEvent: Event | undefined
130
+
131
+ const activeDescendantId = (): string | undefined => {
132
+ const idx = highlighted.value
133
+ const list = opts.items()
134
+ return !open.value || idx < 0 || idx >= list.length || opts.isDisabled(list[idx]!) ? undefined : opts.itemId(idx)
135
+ }
136
+
137
+ const focusActive = () => {
138
+ const id = opts.focusActive ? activeDescendantId() : undefined
139
+ if (!id)
140
+ return
141
+ const el = document.getElementById(id)
142
+ if (el)
143
+ el.focus()
144
+ else
145
+ queueMicrotask(() => document.getElementById(id)?.focus())
146
+ }
147
+
148
+ const openWith = (last: boolean) => {
149
+ open.value = true
150
+ const init = opts.initialIndex?.()
151
+ highlighted.value = init !== undefined && init >= 0
152
+ ? init
153
+ : (last ? findLastEnabledIndex : findFirstEnabledIndex)(opts.items(), opts.isDisabled)
154
+ focusActive()
155
+ }
156
+
157
+ const close = (returnFocus = false) => {
158
+ open.value = false
159
+ if (returnFocus)
160
+ rootEl?.querySelector<HTMLElement>('[data-part="trigger"]')?.focus()
161
+ }
162
+
163
+ effect(() => {
164
+ if (!open.value)
165
+ return
166
+ const onKey = (e: KeyboardEvent) => {
167
+ if (e === lastOpenEvent)
168
+ return
169
+ const prev = highlighted.peek()
170
+ handleListKeyDown(e, {
171
+ items: opts.items,
172
+ activeIndex: highlighted,
173
+ isDisabled: opts.isDisabled,
174
+ onSelect: opts.onSelect,
175
+ onClose: close,
176
+ selectOnSpace: true,
177
+ })
178
+ if (open.peek() && highlighted.peek() !== prev)
179
+ focusActive()
180
+ }
181
+ document.addEventListener('keydown', onKey)
182
+ onCleanup(() => document.removeEventListener('keydown', onKey))
183
+ })
184
+
185
+ return {
186
+ open,
187
+ highlighted,
188
+ setRoot(el) { rootEl = el },
189
+ close,
190
+ toggle(e) {
191
+ e.stopPropagation()
192
+ if (open.value)
193
+ close()
194
+ else
195
+ openWith(false)
196
+ },
197
+ onTriggerKeyDown(e) {
198
+ if (!open.value && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
199
+ e.preventDefault()
200
+ e.stopPropagation()
201
+ lastOpenEvent = e
202
+ openWith(e.key === 'ArrowUp')
203
+ }
204
+ },
205
+ focusActive,
206
+ activeDescendantId,
207
+ mountPopup(el) {
208
+ if (el === undefined)
209
+ return
210
+ el.addEventListener('toggle', e => (e as ToggleEvent).newState === 'closed' && close())
211
+ queueMicrotask(() => {
212
+ showAnchored(el, rootEl!.querySelector<HTMLElement>('[data-part="trigger"]')!)
213
+ focusActive()
214
+ })
215
+ },
216
+ }
217
+ }
218
+
219
+ // ---- Shared native <dialog> sync & backdrop click helpers ----
220
+
221
+ /** Syncs a native `<dialog>` element's modal state, handling initial `open={signal(true)}` on mount/hydration. */
222
+ export function syncDialogOpen(
223
+ el: HTMLDialogElement | undefined,
224
+ isOpen: Signal<boolean>,
225
+ wantOpen: boolean,
226
+ onOpened?: () => void,
227
+ ): void {
228
+ if (el === undefined)
229
+ return
230
+ if (wantOpen) {
231
+ if (!el.open) {
232
+ try {
233
+ el.showModal()
234
+ onOpened?.()
235
+ }
236
+ catch {
237
+ queueMicrotask(() => {
238
+ if (isOpen.peek() && !el.open && el.isConnected) {
239
+ el.showModal()
240
+ onOpened?.()
241
+ }
242
+ })
243
+ }
244
+ }
245
+ }
246
+ else if (el.open) {
247
+ el.close()
248
+ }
249
+ }
250
+
251
+ /** Returns true only when a click on `<dialog>` targeted the backdrop outside its inner panel. */
252
+ export function isDialogBackdropClick(e: MouseEvent, dialogEl: HTMLDialogElement | undefined): boolean {
253
+ if (dialogEl === undefined || e.target !== dialogEl)
254
+ return false
255
+ const rect = dialogEl.getBoundingClientRect()
256
+ if (rect.width === 0 && rect.height === 0)
257
+ return true
258
+ return e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom
259
+ }
260
+
261
+ // ---- Dialog behavior ----
262
+
263
+ export interface DialogBehavior {
264
+ readonly open: Signal<boolean>
265
+ show(): void
266
+ close(): void
267
+ toggle(): void
268
+ readonly triggerProps: Record<string, unknown>
269
+ }
270
+
271
+ export function createDialog(initial = false): DialogBehavior {
272
+ const open = signal(initial)
273
+ return {
274
+ open,
275
+ show: () => { open.value = true },
276
+ close: () => { open.value = false },
277
+ toggle: () => { open.value = !open.value },
278
+ get triggerProps() {
279
+ return {
280
+ 'type': 'button',
281
+ 'aria-haspopup': 'dialog',
282
+ 'aria-expanded': open.value ? 'true' : 'false',
283
+ 'onClick': () => { open.value = true },
284
+ }
285
+ },
286
+ }
287
+ }
@@ -0,0 +1,21 @@
1
+ import type { Context } from 'prunelle'
2
+ import { useContext } from 'prunelle'
3
+
4
+ export interface FieldControlWiring {
5
+ id: string
6
+ describedBy: string | undefined
7
+ invalid: boolean
8
+ required: boolean
9
+ }
10
+
11
+ export const FIELD_CONTEXT_ID = Symbol.for('pru.ui.field')
12
+ const FIELD_CONTEXT_REF = { id: FIELD_CONTEXT_ID, defaultValue: undefined } as Context<FieldControlWiring | undefined>
13
+
14
+ export function useFieldContext(): FieldControlWiring | undefined {
15
+ try {
16
+ return useContext(FIELD_CONTEXT_REF)
17
+ }
18
+ catch {
19
+ return undefined
20
+ }
21
+ }