@prunellejs/ui 0.6.0 → 0.7.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 (46) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +10 -8
  3. package/package.json +2 -2
  4. package/src/CommandPalette.tsx +14 -12
  5. package/src/DataTable.tsx +106 -43
  6. package/src/Dialog.tsx +4 -4
  7. package/src/Select.tsx +3 -2
  8. package/src/Tabs.tsx +2 -1
  9. package/src/Toaster.tsx +50 -86
  10. package/src/behaviors.ts +3 -7
  11. package/src/fold.ts +7 -0
  12. package/src/labels/dialog.ts +3 -0
  13. package/src/labels/fr/dialog.ts +3 -0
  14. package/src/labels/fr/palette.ts +8 -0
  15. package/src/labels/fr/select.ts +1 -0
  16. package/src/labels/fr/table.ts +13 -0
  17. package/src/labels/fr/toaster.ts +1 -0
  18. package/src/labels/palette.ts +8 -0
  19. package/src/labels/select.ts +1 -0
  20. package/src/labels/table.ts +13 -0
  21. package/src/labels/toaster.ts +1 -0
  22. package/src/plugin.ts +24 -5
  23. package/src/primitives.tsx +3 -2
  24. package/src/static.tsx +11 -6
  25. package/src/styles/bare.css +1 -0
  26. package/src/styles/base.css +6 -0
  27. package/src/styles/components/button.css +1 -1
  28. package/src/styles/components/consent.css +38 -0
  29. package/src/styles/grammars/console.css +1 -0
  30. package/src/styles/grammars/editorial.css +2 -1
  31. package/src/styles/grammars/orbit.css +7 -6
  32. package/src/styles/grammars/prunelle.css +1 -1
  33. package/src/styles/grammars/soft.css +10 -10
  34. package/src/styles/grammars/workshop.css +6 -5
  35. package/src/styles/scan.ts +10 -3
  36. package/src/styles/split.ts +48 -0
  37. package/src/styles/theme.css +1 -0
  38. package/src/styles/themed/button.css +4 -1
  39. package/src/styles/themed/command.css +1 -1
  40. package/src/styles/themed/consent.css +33 -0
  41. package/src/styles/themed/menu.css +2 -2
  42. package/src/styles/themed/select.css +2 -2
  43. package/src/styles/themed/switch.css +5 -0
  44. package/src/styles/themed/tabs.css +4 -1
  45. package/src/table-state.ts +53 -16
  46. package/src/toast.ts +50 -8
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/llms.txt CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  - `@prunellejs/ui`:
8
8
  - Static layout primitives (`0 KB` JS): `Stack`, `Cluster`, `Grid`, `Sidebar`, `Split`
9
- - Static & native-platform primitives (`0 KB` JS): `Button`, `Card`, `CardHeader`, `CardBody`, `CardFooter`, `Badge`, `Notice`, `Field`, `FieldContext`, `useFieldContext`, `Checkbox`, `Switch`, `RadioGroup`, `Progress`, `Accordion`, `AccordionItem`, `Popover`, `Dialog`, `Drawer` (opened by `commandfor`/`command` buttons and closed by Esc or a backdrop click, with no JS; `ui()` adds a fallback that only a browser without invoker commands, `closedby` or anchor positioning loads)
9
+ - Static & native-platform primitives (`0 KB` JS): `Button`, `Card`, `CardHeader`, `CardBody`, `CardFooter`, `Badge`, `Notice`, `Field`, `FieldContext`, `useFieldContext`, `Checkbox`, `Switch`, `RadioGroup`, `Progress`, `Accordion`, `AccordionItem`, `Popover`, `Dialog`, `Drawer` (opened by `commandfor`/`command` buttons and closed by Esc or a backdrop click, with no JS; `ui()` adds a fallback that only a browser without invoker commands, `closedby` or anchor positioning loads). The grammars target Chrome or Edge 123, Firefox 125 and Safari 17.5; from Safari 16.5, Chrome 120 or Firefox 117 on they keep their look, through a `prefers-color-scheme` copy of the `:root` colours each grammar carries for browsers without `light-dark()`, and `Menu`, `Select` and `Popover` need the `popover` attribute (Safari 17, Firefox 125)
10
10
  - Interactive island primitives: `ControlledDialog`, `ControlledDrawer`, `Tabs`, `Menu`, `Select`, `CommandPalette`, `DataTable`, `Toaster`
11
11
  - Headless signal behaviors & helpers: `createDialog`, `createTabs`, `createDataTable`, `toast`, `handleListKeyDown`, `findFirstEnabledIndex`, `findLastEnabledIndex`, `findNextEnabledIndex`, `isDialogBackdropClick`, `syncDialogOpen`, `nextUiId`
12
12
  - `@prunellejs/ui/plugin`: `ui(options?)`, `GRAMMAR_NAMES`, `UI_COMPONENT_PARTS`, `UI_EXPORT_TO_PARTS`, `grammarCssPath`, `renderGrammarCss`, `renderGrammarBaseCss`, `renderGrammarPartsCss`, `ejectGrammar`
@@ -25,6 +25,7 @@ export default defineConfig({
25
25
 
26
26
  - `grammar`: `'editorial'` (default) | `'workshop'` | `'console'` | `'soft'` | `'orbit'` | `'prunelle'` (prunelle's own: eye radios, switches and progress; titles in Fraunces, which the app loads) | `'bare'` | `false` (skip injecting CSS when importing your own).
27
27
  - `emitGrammars`: `boolean | GrammarName[] | { dir?: string, grammars?: GrammarName[] }` — emits standalone CSS files to `/<dir>/<name>.css` (default `grammars/<name>.css`) for runtime theme switching.
28
+ - Labels: built-in labels (Dialog's close button, Toaster's dismiss, Select's placeholder, CommandPalette and DataTable texts) follow `lang` from `prunelle.config.ts`: French for `'fr'` or `'fr-*'`, English otherwise. Each label prop overrides them; an app with several locales passes them for the locales other than `lang`.
28
29
  - CLI: `prunelle ui-eject <grammar> [dest]` copies a self-contained CSS grammar (with `base.css` and component sheets inlined) into your app (default `editorial` → `src/styles/ui.css`).
29
30
 
30
31
  ## Tokenized Grammar Architecture & Per-Component CSS
@@ -32,24 +33,25 @@ export default defineConfig({
32
33
  - All styles live inside `@layer kui`, layered as `base.css` (box-sizing, `.kui-sr-only`, single `:focus-visible` indicator, reduced motion, `[hidden]`) → per-component structural sheets (`components/<part>.css`) → shared tokenized sheets (`themed/<part>.css`) → thin grammar token files (`grammars/<name>.css`).
33
34
  - Focus visibility (RGAA 10.7) is defined once in `base.css` via `--ui-focus-color` (falling back to `--ui-accent`); grammars never suppress focus outlines with `outline: none`.
34
35
  - Per-component assembly: `renderGrammarBaseCss(grammar)` returns the base floor + grammar tokens; `renderGrammarPartsCss(grammar, parts)` returns only the requested `UiComponentPart` stylesheets in deterministic cascade order; `UI_EXPORT_TO_PARTS` maps every component export to its required parts (including transitive dependencies).
36
+ - prunelle's `<ConsentBanner>` and `<ConsentPreferences>` are styled by the `consent` part, shipped to the pages that import them: the banner sits fixed at the bottom of the viewport, Refuse all and Accept all at one width.
35
37
 
36
38
  ## Key Props & Types
37
39
 
38
40
  - Shared tokens: `Tone = 'neutral' | 'accent' | 'success' | 'warning' | 'danger'`, `ButtonVariant = 'solid' | 'outline' | 'ghost'`, `Size = 'sm' | 'md' | 'lg'`, `SpaceToken = 'none' | '2xs' | 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl'`, `TrackSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl'`.
39
41
  - Layout: `<Stack gap="md">`, `<Cluster gap="sm">`, `<Grid min="md" gap="md">`, `<Sidebar side="sm" gap="lg">`, `<Split gap="md">`.
40
- - `Button`: `{ variant?, tone?, size?, href?, type?, disabled?, class?, children? }` (renders `<a>` when `href` is set, else `<button>`).
41
- - `Field`: `{ id, label, hint?, error?, required?, class?, children? }` — auto-wires `for`, `id`, `aria-describedby`, `aria-invalid`, `required` onto its child control (and provides `FieldContext`).
42
- - `Checkbox` / `Switch`: `{ id?, name?, value?, label, checked?, disabled? }`; `RadioGroup`: `{ name, legend?, options: RadioOption[], defaultValue? }`.
42
+ - `Button`: `{ variant?, tone?, size?, href?, type?, disabled?, class?, children? }` (renders `<a>` when `href` is set, else `<button>`; a disabled link drops its `href` and takes `aria-disabled="true"`).
43
+ - `Field`: `{ id, label, hint?, error?, required?, class?, children? }` — auto-wires `for`, `id`, `aria-describedby`, `aria-invalid`, `required` onto its child control (and provides `FieldContext`). A hint stays shown under an error, and `aria-describedby` names both, the error first.
44
+ - `Checkbox` / `Switch`: `{ id?, name?, value?, label, checked?, disabled? }`; `RadioGroup`: `{ name, legend?, options: RadioOption[], defaultValue? }`. A `label` (here, in a `RadioOption` and in `Field`) is text or markup, so a consent checkbox can link to the privacy policy: `label={<>I accept the <a href="/privacy">privacy policy</a></>}`. `Progress.label` stays text.
43
45
  - `Progress`: `{ label, value?, max? (100) }`, a native `<progress>`: indeterminate (a loader) without `value`.
44
46
  - `Accordion` + `AccordionItem`: `{ title, group?, open?, children? }` (native `<details name={group}>`).
45
47
  - `Popover`: `{ id, triggerLabel, triggerVariant?, children? }` (native Popover API). `Popover`, `Menu` and `Select` open in the top layer (never clipped by an `overflow` parent), anchored below their trigger and flipped when the viewport has no room.
46
48
  - `Dialog` / `Drawer`: `{ id?, title?, ariaLabel?, description?, triggerLabel?, triggerVariant?, closeLabel?, side?: 'right' | 'left' | 'bottom', children? }`; another button opens one with `commandfor={id} command="show-modal"`. `ControlledDialog` / `ControlledDrawer` take the same props plus `open: Signal<boolean>`, which the browser closing it sets back to `false`.
47
- - `Tabs`: `{ id?, items: Array<{ id, label, content }>, defaultValue?, label? }`.
49
+ - `Tabs`: `{ id?, items: Array<{ id, label, content }>, defaultValue?, label? }` (the tablist is named only when `label` is given; each panel takes `tabindex="0"` so Tab reaches a panel of plain text).
48
50
  - `Menu`: `{ id?, label, items: Array<{ id, label, href?, disabled?, onSelect? }>, variant?, onSelect? }`.
49
- - `Select`: `{ id?, options: Array<{ value, label, disabled? }>, value?: Signal<string>, defaultValue?, name?, placeholder?, ariaLabel?, onChange? }`.
51
+ - `Select`: `{ id?, options: Array<{ value, label, disabled? }>, value?: Signal<string>, defaultValue?, name?, placeholder?, ariaLabel?, onChange? }`. With no `value` or `defaultValue` it shows `placeholder` and submits `""` until the user picks. Outside a `Field` or `<label for>` it needs `ariaLabel`, or `prunelle check` warns `rgaa/form-label`.
50
52
  - `CommandPalette`: `{ id?, items?: CommandItem[], source?: CommandSource, shortcutKey? ('k'), open?: Signal<boolean>, onSelect?, ...labels }` (`source` is a lazy search function or `{ search(query) }`, e.g. `createSearchSource()` from `@prunellejs/search/client`, invoked only once opened).
51
- - `DataTable`: `{ rows, columns: Array<{ key, label, sortable? }>, rowKey? ('id'), pageSize? (10), searchable? (true), selectable? (false), ...labels }`.
52
- - `Toaster` + `toast`: mount `<Toaster dismissLabel? />` once in `_layout.tsx`; call `toast.show|info|success|warning|danger|error(title, description?, durationMs?)`, `toast.dismiss(id)`, `toast.clear()`.
53
+ - `DataTable`: `{ rows, columns: Array<{ key, label, sortable? }>, rowKey? ('id'; every row needs a unique key, or the table throws), locale? (sort order; `<html lang>`), onSelect?(keys) (the selected keys, each time they change), rowLabelKey? (first column: names each row's checkbox), pageSize? (10), searchable? (true), selectable? (false), ...labels }`. With `selectable`, the header checkbox selects or clears every row the filter shows. A sort is announced (`ascendingLabel`, `descendingLabel`), and so is the page. `Sort is numeric and accent-aware (`Intl.Collator`), search and `CommandPalette` ignore case and accents, and the selection drops rows that leave `rows`. `createDataTable()` also has `setSelected(keys, on)` and `onSelect`.
54
+ - `Toaster` + `toast`: mount `<Toaster dismissLabel? />` once in `_layout.tsx`; call `toast.show|info|success|warning|danger|error(title, description?, durationMs?)`, `toast.dismiss(id)`, `toast.clear()`. A `danger`/`error` toast stays until dismissed and the others stay 4.5 to 15 s by text length, unless `durationMs` is given (`0` keeps it). Hovering or focusing the stack pauses every timer, which then resumes with the time it had left; Escape closes the focused toast, and focus moves to the next toast, else back where it was.
53
55
 
54
56
  ## Example
55
57
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/ui",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Platform-first headless UI primitives and pure CSS @layer kui Style Grammars for Prunelle",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -29,6 +29,6 @@
29
29
  "directory": "packages/ui"
30
30
  },
31
31
  "peerDependencies": {
32
- "prunelle": "^0.6.0"
32
+ "prunelle": "^0.7.0"
33
33
  }
34
34
  }
@@ -4,6 +4,8 @@
4
4
  import type { Signal } from 'prunelle'
5
5
  import { computed, effect, onMount, signal } from 'prunelle'
6
6
  import { findFirstEnabledIndex, handleListKeyDown, isDialogBackdropClick, navigateSafeHref, nextUiId, syncDialogOpen } from './behaviors'
7
+ import { foldText } from './fold'
8
+ import * as PALETTE_LABELS from './labels/palette'
7
9
 
8
10
  export interface CommandItem {
9
11
  id: string
@@ -41,13 +43,13 @@ export interface CommandPaletteProps {
41
43
  const isItemDisabled = (it: CommandItem) => Boolean(it.disabled)
42
44
 
43
45
  function filterStaticItems(items: CommandItem[], rawQuery: string): CommandItem[] {
44
- const q = rawQuery.trim().toLowerCase()
46
+ const q = foldText(rawQuery.trim())
45
47
  if (!q)
46
48
  return items
47
49
  return items.filter(it =>
48
- it.label.toLowerCase().includes(q)
49
- || (it.group?.toLowerCase().includes(q) ?? false)
50
- || (it.description?.toLowerCase().includes(q) ?? false),
50
+ foldText(it.label).includes(q)
51
+ || (it.group !== undefined && foldText(it.group).includes(q))
52
+ || (it.description !== undefined && foldText(it.description).includes(q)),
51
53
  )
52
54
  }
53
55
 
@@ -104,14 +106,14 @@ export function CommandPalette(props: CommandPaletteProps) {
104
106
  const baseId = props.id ?? nextUiId('kui-cmd')
105
107
  const listId = `${baseId}-list`
106
108
  const optionId = (idx: number) => `${baseId}-opt-${idx}`
107
- const placeholder = props.placeholder ?? 'Type a command or search...'
108
- const inputLabel = props.inputLabel ?? 'Search commands'
109
- const ariaLabel = props.ariaLabel ?? 'Command palette'
110
- const triggerLabel = props.triggerLabel ?? 'Search (⌘K)'
111
- const emptyLabel = props.emptyLabel ?? 'No matching commands.'
112
- const noResultsLabel = props.noResultsLabel ?? 'No results'
113
- const resultLabel = props.resultLabel ?? 'result'
114
- const resultsLabel = props.resultsLabel ?? 'results'
109
+ const placeholder = props.placeholder ?? PALETTE_LABELS.placeholder
110
+ const inputLabel = props.inputLabel ?? PALETTE_LABELS.input
111
+ const ariaLabel = props.ariaLabel ?? PALETTE_LABELS.palette
112
+ const triggerLabel = props.triggerLabel ?? PALETTE_LABELS.trigger
113
+ const emptyLabel = props.emptyLabel ?? PALETTE_LABELS.empty
114
+ const noResultsLabel = props.noResultsLabel ?? PALETTE_LABELS.noResults
115
+ const resultLabel = props.resultLabel ?? PALETTE_LABELS.result
116
+ const resultsLabel = props.resultsLabel ?? PALETTE_LABELS.results
115
117
  const staticItems = props.items ?? []
116
118
 
117
119
  const isOpen = props.open ?? signal(false)
package/src/DataTable.tsx CHANGED
@@ -1,6 +1,9 @@
1
1
  /** @jsxImportSource prunelle */
2
2
  // Interactive DataTable island powered by headless `createDataTable()` signals (sort, filter, select, paginate).
3
3
 
4
+ import type { DataTableState } from './table-state'
5
+ import { effect, signal } from 'prunelle'
6
+ import * as TABLE_LABELS from './labels/table'
4
7
  import { createDataTable } from './table-state'
5
8
 
6
9
  export interface DataTableColumn {
@@ -13,7 +16,13 @@ export interface DataTableProps {
13
16
  rows: Array<Record<string, string | number>>
14
17
  columns: DataTableColumn[]
15
18
  rowKey?: string | undefined
19
+ /** Column whose value names a row's checkbox; the first column by default. */
20
+ rowLabelKey?: string | undefined
16
21
  pageSize?: number | undefined
22
+ /** Language of the sort order; `<html lang>` by default. */
23
+ locale?: string | undefined
24
+ /** Called with the selected row keys each time the selection changes. */
25
+ onSelect?: ((keys: Array<string | number>) => void) | undefined
17
26
  searchable?: boolean | undefined
18
27
  selectable?: boolean | undefined
19
28
  caption?: string | undefined
@@ -22,6 +31,9 @@ export interface DataTableProps {
22
31
  searchLabel?: string | undefined
23
32
  selectColumnLabel?: string | undefined
24
33
  selectRowLabel?: string | undefined
34
+ selectAllLabel?: string | undefined
35
+ ascendingLabel?: string | undefined
36
+ descendingLabel?: string | undefined
25
37
  rowsLabel?: string | undefined
26
38
  selectedLabel?: string | undefined
27
39
  pageLabel?: string | undefined
@@ -30,32 +42,100 @@ export interface DataTableProps {
30
42
  emptyLabel?: string | undefined
31
43
  }
32
44
 
45
+ type Row = Record<string, string | number>
46
+
47
+ // Rows without a key, or sharing one, would select together: refuse them with the fix.
48
+ function checkedRows(rows: Row[], rowKey: string): Row[] {
49
+ const seen = new Map<string, number>()
50
+ for (const [i, row] of rows.entries()) {
51
+ const key = row[rowKey]
52
+ if (key === undefined || key === null || key === '')
53
+ throw new Error(`prunelle: DataTable row ${i} has no "${rowKey}" value: give every row a unique "${rowKey}", or pass rowKey="<column>" naming a column that is unique.`)
54
+ const first = seen.get(String(key))
55
+ if (first !== undefined)
56
+ throw new Error(`prunelle: DataTable rows ${first} and ${i} share the key "${String(key)}": pass rowKey="<column>" naming a column that is unique.`)
57
+ seen.set(String(key), i)
58
+ }
59
+ return rows
60
+ }
61
+
62
+ // When a pager button disables itself, focus moves to the other one instead of falling to <body>.
63
+ function Pager({ table, pageLabel, prevLabel, nextLabel }: { table: DataTableState<Row>, pageLabel: string, prevLabel: string, nextLabel: string }) {
64
+ const turn = (by: number, other: Element | null) => {
65
+ table.page.value += by
66
+ const atEnd = by < 0 ? table.page.peek() <= 1 : table.page.peek() >= table.totalPages.peek()
67
+ if (atEnd && other instanceof HTMLElement)
68
+ other.focus()
69
+ }
70
+ return (
71
+ <div data-part="pagination" data-layout="split">
72
+ <span data-part="meta" role="status">
73
+ {`${pageLabel} ${table.page.value} / ${table.totalPages.value}`}
74
+ </span>
75
+ <div data-layout="cluster">
76
+ <button
77
+ data-ui="button"
78
+ data-variant="outline"
79
+ data-size="sm"
80
+ type="button"
81
+ disabled={table.page.value <= 1}
82
+ onClick={e => turn(-1, e.currentTarget.nextElementSibling)}
83
+ >
84
+ {prevLabel}
85
+ </button>
86
+ <button
87
+ data-ui="button"
88
+ data-variant="outline"
89
+ data-size="sm"
90
+ type="button"
91
+ disabled={table.page.value >= table.totalPages.value}
92
+ onClick={e => turn(1, e.currentTarget.previousElementSibling)}
93
+ >
94
+ {nextLabel}
95
+ </button>
96
+ </div>
97
+ </div>
98
+ )
99
+ }
100
+
33
101
  export function DataTable(props: DataTableProps) {
34
102
  const rowKey = props.rowKey ?? 'id'
35
103
  const searchable = props.searchable ?? true
36
104
  const selectable = props.selectable ?? false
37
105
  const caption = props.caption
38
106
  const ariaLabel = props.ariaLabel
39
- const placeholder = props.placeholder ?? 'Filter rows...'
40
- const searchLabel = props.searchLabel ?? 'Search'
41
- const selectColumnLabel = props.selectColumnLabel ?? 'Select'
42
- const selectRowLabel = props.selectRowLabel ?? 'Select row'
43
- const rowsLabel = props.rowsLabel ?? 'rows'
44
- const selectedLabel = props.selectedLabel ?? 'selected'
45
- const pageLabel = props.pageLabel ?? 'Page'
46
- const prevLabel = props.prevLabel ?? 'Prev'
47
- const nextLabel = props.nextLabel ?? 'Next'
48
- const emptyLabel = props.emptyLabel ?? 'No matching rows.'
107
+ const placeholder = props.placeholder ?? TABLE_LABELS.placeholder
108
+ const searchLabel = props.searchLabel ?? TABLE_LABELS.search
109
+ const selectColumnLabel = props.selectColumnLabel ?? TABLE_LABELS.selectColumn
110
+ const selectRowLabel = props.selectRowLabel ?? TABLE_LABELS.selectRow
111
+ const selectAllLabel = props.selectAllLabel ?? TABLE_LABELS.selectAll
112
+ const ascendingLabel = props.ascendingLabel ?? TABLE_LABELS.ascending
113
+ const descendingLabel = props.descendingLabel ?? TABLE_LABELS.descending
114
+ const rowsLabel = props.rowsLabel ?? TABLE_LABELS.rows
115
+ const selectedLabel = props.selectedLabel ?? TABLE_LABELS.selected
116
+ const pageLabel = props.pageLabel ?? TABLE_LABELS.page
117
+ const prevLabel = props.prevLabel ?? TABLE_LABELS.prev
118
+ const nextLabel = props.nextLabel ?? TABLE_LABELS.next
119
+ const emptyLabel = props.emptyLabel ?? TABLE_LABELS.empty
49
120
  const columns = props.columns
50
- const keyOf = (r: Record<string, string | number>) => String(r[rowKey] ?? '')
121
+ const keyOf = (r: Row) => String(r[rowKey] ?? '')
122
+ const labelKey = props.rowLabelKey ?? columns[0]?.key ?? rowKey
51
123
  const sortOf = (k: string) => (table.sortBy.value === k ? table.sortDir.value : undefined)
124
+ // What a sort just changed, for screen readers: aria-sort alone changes silently.
125
+ const said = signal('')
52
126
 
53
127
  const table = createDataTable({
54
- rows: () => props.rows,
128
+ rows: () => checkedRows(props.rows, rowKey),
55
129
  getKey: keyOf,
130
+ locale: props.locale,
131
+ onSelect: props.onSelect,
56
132
  pageSize: props.pageSize ?? 10,
57
133
  searchText: r => columns.map(c => String(r[c.key] ?? '')).join(' '),
58
134
  })
135
+ // The header checkbox covers the rows the filter shows.
136
+ const shownKeys = () => table.filtered.value.map(keyOf)
137
+ const allShownSelected = () => shownKeys().length > 0 && shownKeys().every(k => table.selected.value.has(k))
138
+ const someShownSelected = () => shownKeys().some(k => table.selected.value.has(k))
59
139
 
60
140
  return (
61
141
  <div data-ui="datatable">
@@ -86,6 +166,13 @@ export function DataTable(props: DataTableProps) {
86
166
  {selectable && (
87
167
  <th scope="col" data-part="select-col">
88
168
  <span class="kui-sr-only">{selectColumnLabel}</span>
169
+ <input
170
+ type="checkbox"
171
+ aria-label={selectAllLabel}
172
+ checked={allShownSelected()}
173
+ ref={(el: HTMLInputElement) => effect(() => { el.indeterminate = someShownSelected() && !allShownSelected() })}
174
+ onChange={() => table.setSelected(shownKeys(), !allShownSelected())}
175
+ />
89
176
  </th>
90
177
  )}
91
178
  {columns.map(col => (
@@ -100,7 +187,10 @@ export function DataTable(props: DataTableProps) {
100
187
  type="button"
101
188
  data-part="sort"
102
189
  data-active={sortOf(col.key) ? 'true' : undefined}
103
- onClick={() => table.toggleSort(col.key)}
190
+ onClick={() => {
191
+ table.toggleSort(col.key)
192
+ said.value = `${col.label}, ${table.sortDir.peek() === 'asc' ? ascendingLabel : descendingLabel}`
193
+ }}
104
194
  >
105
195
  {col.label}
106
196
  <span aria-hidden="true">{sortOf(col.key) === 'asc' ? ' ↑' : sortOf(col.key) === 'desc' ? ' ↓' : ''}</span>
@@ -127,7 +217,7 @@ export function DataTable(props: DataTableProps) {
127
217
  <input
128
218
  type="checkbox"
129
219
  checked={table.isSelected(keyOf(row))}
130
- aria-label={`${selectRowLabel} ${keyOf(row)}`}
220
+ aria-label={`${selectRowLabel} ${String(row[labelKey] ?? keyOf(row))}`}
131
221
  onChange={() => table.toggleSelect(keyOf(row))}
132
222
  />
133
223
  </td>
@@ -141,35 +231,8 @@ export function DataTable(props: DataTableProps) {
141
231
  </table>
142
232
  </div>
143
233
 
144
- {table.totalPages.value > 1 && (
145
- <div data-part="pagination" data-layout="split">
146
- <span data-part="meta">
147
- {`${pageLabel} ${table.page.value} / ${table.totalPages.value}`}
148
- </span>
149
- <div data-layout="cluster">
150
- <button
151
- data-ui="button"
152
- data-variant="outline"
153
- data-size="sm"
154
- type="button"
155
- disabled={table.page.value <= 1}
156
- onClick={() => { table.page.value-- }}
157
- >
158
- {prevLabel}
159
- </button>
160
- <button
161
- data-ui="button"
162
- data-variant="outline"
163
- data-size="sm"
164
- type="button"
165
- disabled={table.page.value >= table.totalPages.value}
166
- onClick={() => { table.page.value++ }}
167
- >
168
- {nextLabel}
169
- </button>
170
- </div>
171
- </div>
172
- )}
234
+ {table.totalPages.value > 1 && <Pager table={table} pageLabel={pageLabel} prevLabel={prevLabel} nextLabel={nextLabel} />}
235
+ <span data-part="announce" class="kui-sr-only" role="status">{said.value}</span>
173
236
  </div>
174
237
  )
175
238
  }
package/src/Dialog.tsx CHANGED
@@ -6,6 +6,7 @@ import type { PrunelleChild, Signal } from 'prunelle'
6
6
  import type { ButtonVariant } from './static'
7
7
  import { effect } from 'prunelle'
8
8
  import { nextUiId, syncDialogOpen } from './behaviors'
9
+ import * as DIALOG_LABELS from './labels/dialog'
9
10
 
10
11
  export interface DialogProps {
11
12
  id?: string | undefined
@@ -55,7 +56,7 @@ function dialogAttrs(props: Shared, kind: Kind, ids: DialogIds) {
55
56
  'data-side': kind === 'drawer' ? (props.side ?? 'right') : undefined,
56
57
  'data-part': 'content',
57
58
  'aria-labelledby': props.title ? ids.titleId : undefined,
58
- 'aria-label': !props.title ? (props.ariaLabel ?? (kind === 'drawer' ? 'Drawer' : 'Dialog')) : undefined,
59
+ 'aria-label': !props.title ? (props.ariaLabel ?? (kind === 'drawer' ? DIALOG_LABELS.drawer : DIALOG_LABELS.dialog)) : undefined,
59
60
  'aria-describedby': props.description ? ids.descId : undefined,
60
61
  }
61
62
  }
@@ -69,7 +70,7 @@ function closeButtonAttrs(dialog: Shared, ids: DialogIds) {
69
70
  'type': 'button' as const,
70
71
  'commandfor': ids.baseId,
71
72
  'command': 'close' as const,
72
- 'aria-label': dialog.closeLabel ?? 'Close',
73
+ 'aria-label': dialog.closeLabel ?? DIALOG_LABELS.close,
73
74
  }
74
75
  }
75
76
 
@@ -88,8 +89,7 @@ function DialogPanel(props: { dialog: Shared, ids: DialogIds }) {
88
89
  )
89
90
  }
90
91
 
91
- function ControlledDialogPanel(props: { dialog: Shared, ids: DialogIds, onClose: () => void }) {
92
- const { dialog, ids, onClose } = props
92
+ function ControlledDialogPanel({ dialog, ids, onClose }: { dialog: Shared, ids: DialogIds, onClose: () => void }) {
93
93
  return (
94
94
  <div data-part="panel">
95
95
  <header data-part="header" data-layout="split">
package/src/Select.tsx CHANGED
@@ -4,6 +4,7 @@
4
4
  import type { Signal } from 'prunelle'
5
5
  import { onMount, signal } from 'prunelle'
6
6
  import { createListPopup, nextUiId, useFieldContext } from './behaviors'
7
+ import * as SELECT_LABELS from './labels/select'
7
8
 
8
9
  export interface SelectOption {
9
10
  value: string
@@ -29,10 +30,10 @@ export function Select(props: SelectProps) {
29
30
  const listboxId = `${baseId}-listbox`
30
31
  const optionId = (idx: number) => `${baseId}-opt-${idx}`
31
32
  const name = props.name
32
- const placeholder = props.placeholder ?? 'Select…'
33
+ const placeholder = props.placeholder ?? SELECT_LABELS.placeholder
33
34
  const ariaLabel = props.ariaLabel
34
35
 
35
- const selected = props.value ?? signal(props.defaultValue ?? props.options[0]?.value ?? '')
36
+ const selected = props.value ?? signal(props.defaultValue ?? '')
36
37
  const currentLabel = () => props.options.find(o => o.value === selected.value)?.label ?? placeholder
37
38
 
38
39
  const pick = (opt: SelectOption) => {
package/src/Tabs.tsx CHANGED
@@ -19,7 +19,7 @@ export interface TabsProps {
19
19
  class?: string | undefined
20
20
  }
21
21
 
22
- export function Tabs({ id, items, defaultValue, label = 'Tabs', class: cls }: TabsProps) {
22
+ export function Tabs({ id, items, defaultValue, label, class: cls }: TabsProps) {
23
23
  const baseId = id ?? nextUiId('kui-tabs')
24
24
  const ids = items.map(i => i.id)
25
25
  const tabs = createTabs(defaultValue ?? items[0]?.id ?? '')
@@ -53,6 +53,7 @@ export function Tabs({ id, items, defaultValue, label = 'Tabs', class: cls }: Ta
53
53
  data-state={tabs.isActive(item.id) ? 'active' : 'inactive'}
54
54
  role="tabpanel"
55
55
  aria-labelledby={`${baseId}-tab-${item.id}`}
56
+ tabIndex={0}
56
57
  hidden={!tabs.isActive(item.id)}
57
58
  >
58
59
  {item.content}
package/src/Toaster.tsx CHANGED
@@ -1,107 +1,73 @@
1
1
  /** @jsxImportSource prunelle */
2
2
  // Live-region Toast stack driven by the reactive `toast` store.
3
3
 
4
- import { effect, onCleanup } from 'prunelle'
5
- import { toast } from './toast'
4
+ import { effect } from 'prunelle'
5
+ import { dismiss } from './labels/toaster'
6
+ import { pauseToasts, resumeToasts, toast } from './toast'
6
7
 
7
8
  export interface ToasterProps {
8
9
  dismissLabel?: string | undefined
9
10
  }
10
11
 
11
- const TOAST_STORE_KEY = Symbol.for('pru.ui.toasts')
12
- const RESUME_DURATION_MS = 4500
12
+ export function Toaster({ dismissLabel = dismiss }: ToasterProps = {}) {
13
+ let hovered = false
14
+ let focused = false
15
+ // Where focus was before it entered the toaster, given back when the last toast closes.
16
+ let returnTo: HTMLElement | null = null
13
17
 
14
- interface SharedToastTimers {
15
- t: Map<string, ReturnType<typeof setTimeout>>
16
- }
17
-
18
- function getTimerMap(): Map<string, ReturnType<typeof setTimeout>> | undefined {
19
- if (typeof document === 'undefined')
20
- return undefined
21
- return (document as unknown as Record<symbol, SharedToastTimers | undefined>)[TOAST_STORE_KEY]?.t
22
- }
23
-
24
- export function Toaster({ dismissLabel = 'Dismiss' }: ToasterProps = {}) {
25
- let hoveredToaster = false
26
- let focusedToaster = false
27
- const hoveredToasts = new Set<string>()
28
- const pausedIds = new Set<string>()
29
-
30
- const isPaused = () => hoveredToaster || focusedToaster || hoveredToasts.size > 0
31
-
32
- const pauseTimers = () => {
33
- const timers = getTimerMap()
34
- if (timers === undefined)
35
- return
36
- for (const item of toast.items.peek()) {
37
- const handle = timers.get(item.id)
38
- if (handle !== undefined) {
39
- clearTimeout(handle)
40
- timers.delete(item.id)
41
- pausedIds.add(item.id)
42
- }
43
- }
44
- }
45
-
46
- const resumeTimers = () => {
47
- if (isPaused())
48
- return
49
- const timers = getTimerMap()
50
- if (timers === undefined) {
51
- pausedIds.clear()
52
- return
53
- }
54
- const active = new Set(toast.items.peek().map(x => x.id))
55
- for (const id of pausedIds) {
56
- if (active.has(id) && !timers.has(id))
57
- timers.set(id, setTimeout(() => toast.dismiss(id), RESUME_DURATION_MS))
58
- }
59
- pausedIds.clear()
18
+ const resume = () => {
19
+ if (!hovered && !focused)
20
+ resumeToasts()
60
21
  }
61
22
 
23
+ // A toast pushed while the stack is hovered or focused waits too.
62
24
  effect(() => {
63
- const items = toast.items.value
64
- if (items.length === 0)
25
+ if (toast.items.value.length > 0 && (hovered || focused))
26
+ pauseToasts()
27
+ })
28
+
29
+ // Closing the focused toast moves focus to the next one, else the previous one, else back where it came from.
30
+ const close = (item: HTMLElement) => {
31
+ const root = item.closest<HTMLElement>('[data-ui="toaster"]')
32
+ const hadFocus = item.contains(document.activeElement)
33
+ const sibling = (item.nextElementSibling ?? item.previousElementSibling)?.querySelector<HTMLElement>('[data-part="close"]')
34
+ toast.dismiss(item.getAttribute('data-toast-id') ?? '')
35
+ if (!hadFocus)
65
36
  return
66
- if (isPaused())
67
- pauseTimers()
68
- const onKeyDown = (e: KeyboardEvent) => {
69
- if (e.key !== 'Escape' || e.defaultPrevented)
70
- return
71
- const current = toast.items.peek()
72
- if (current.length === 0)
73
- return
74
- const activeEl = typeof document !== 'undefined' ? document.activeElement : null
75
- const focusedId = activeEl?.closest?.('[data-ui="toast"]')?.getAttribute('data-toast-id')
76
- const targetId = focusedId && current.some(x => x.id === focusedId)
77
- ? focusedId
78
- : current[current.length - 1]!.id
79
- toast.dismiss(targetId)
37
+ const target = sibling ?? returnTo
38
+ if (target?.isConnected)
39
+ target.focus()
40
+ if (root !== null && !root.contains(document.activeElement)) {
41
+ focused = false
42
+ returnTo = null
43
+ resume()
80
44
  }
81
- document.addEventListener('keydown', onKeyDown)
82
- onCleanup(() => document.removeEventListener('keydown', onKeyDown))
83
- })
45
+ }
84
46
 
85
47
  return (
86
48
  <div
87
49
  data-ui="toaster"
88
50
  onMouseEnter={() => {
89
- hoveredToaster = true
90
- pauseTimers()
51
+ hovered = true
52
+ pauseToasts()
91
53
  }}
92
54
  onMouseLeave={() => {
93
- hoveredToaster = false
94
- resumeTimers()
55
+ hovered = false
56
+ resume()
95
57
  }}
96
- onFocusIn={() => {
97
- focusedToaster = true
98
- pauseTimers()
58
+ onFocusIn={(e) => {
59
+ const from = e.relatedTarget
60
+ if (from instanceof HTMLElement && !e.currentTarget.contains(from))
61
+ returnTo = from
62
+ focused = true
63
+ pauseToasts()
99
64
  }}
100
65
  onFocusOut={(e) => {
101
66
  const next = e.relatedTarget as Node | null
102
67
  if (next === null || !e.currentTarget.contains(next)) {
103
- focusedToaster = false
104
- resumeTimers()
68
+ focused = false
69
+ returnTo = null
70
+ resume()
105
71
  }
106
72
  }}
107
73
  >
@@ -113,13 +79,11 @@ export function Toaster({ dismissLabel = 'Dismiss' }: ToasterProps = {}) {
113
79
  data-tone={item.tone}
114
80
  role={item.tone === 'danger' ? 'alert' : 'status'}
115
81
  aria-atomic="true"
116
- onMouseEnter={() => {
117
- hoveredToasts.add(item.id)
118
- pauseTimers()
119
- }}
120
- onMouseLeave={() => {
121
- hoveredToasts.delete(item.id)
122
- resumeTimers()
82
+ onKeyDown={(e) => {
83
+ if (e.key !== 'Escape' || e.defaultPrevented)
84
+ return
85
+ e.preventDefault()
86
+ close(e.currentTarget)
123
87
  }}
124
88
  >
125
89
  <div>
@@ -130,7 +94,7 @@ export function Toaster({ dismissLabel = 'Dismiss' }: ToasterProps = {}) {
130
94
  data-part="close"
131
95
  type="button"
132
96
  aria-label={dismissLabel}
133
- onClick={() => toast.dismiss(item.id)}
97
+ onClick={e => close(e.currentTarget.closest<HTMLElement>('[data-ui="toast"]')!)}
134
98
  >
135
99
  ✕
136
100
  </button>
package/src/behaviors.ts CHANGED
@@ -33,7 +33,7 @@ export function safeHref(href: string | undefined): string | undefined {
33
33
  return UNSAFE_HREF_RE.test(cleaned) ? undefined : trimmed
34
34
  }
35
35
 
36
- /** Navigates to a safe href via a synthetic anchor click so `@prunellejs/spa` can intercept same-origin links, falling back to `location.assign`. */
36
+ /** Navigates to a safe href with one synthetic anchor click, which `@prunellejs/spa` can intercept and the browser follows otherwise; `location.assign` only when there is no body to hold the anchor. */
37
37
  export function navigateSafeHref(href: string | undefined): boolean {
38
38
  const safe = safeHref(href)
39
39
  if (safe === undefined)
@@ -43,17 +43,13 @@ export function navigateSafeHref(href: string | undefined): boolean {
43
43
  a.href = safe
44
44
  a.hidden = true
45
45
  document.body.appendChild(a)
46
- let prevented = false
47
46
  try {
48
- const ev = new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 })
49
- a.dispatchEvent(ev)
50
- prevented = ev.defaultPrevented
47
+ a.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 }))
51
48
  }
52
49
  finally {
53
50
  a.remove()
54
51
  }
55
- if (prevented)
56
- return true
52
+ return true
57
53
  }
58
54
  if (typeof location !== 'undefined')
59
55
  location.assign(safe)