@prunellejs/ui 0.1.1 → 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 (79) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +19 -11
  3. package/package.json +2 -2
  4. package/src/CommandPalette.tsx +130 -75
  5. package/src/DataTable.tsx +131 -58
  6. package/src/Dialog.tsx +30 -14
  7. package/src/Menu.tsx +10 -8
  8. package/src/Select.tsx +19 -8
  9. package/src/Tabs.tsx +2 -1
  10. package/src/Toaster.tsx +79 -5
  11. package/src/behaviors.ts +104 -6
  12. package/src/fold.ts +7 -0
  13. package/src/index.ts +1 -1
  14. package/src/labels/dialog.ts +3 -0
  15. package/src/labels/fr/dialog.ts +3 -0
  16. package/src/labels/fr/palette.ts +8 -0
  17. package/src/labels/fr/select.ts +1 -0
  18. package/src/labels/fr/table.ts +13 -0
  19. package/src/labels/fr/toaster.ts +1 -0
  20. package/src/labels/palette.ts +8 -0
  21. package/src/labels/select.ts +1 -0
  22. package/src/labels/table.ts +13 -0
  23. package/src/labels/toaster.ts +1 -0
  24. package/src/plugin.ts +114 -31
  25. package/src/primitives.tsx +3 -2
  26. package/src/static.tsx +11 -6
  27. package/src/styles/bare.css +22 -312
  28. package/src/styles/base.css +61 -0
  29. package/src/styles/components/accordion.css +10 -0
  30. package/src/styles/components/badge.css +6 -0
  31. package/src/styles/components/button.css +11 -0
  32. package/src/styles/components/card.css +5 -0
  33. package/src/styles/components/checkbox.css +11 -0
  34. package/src/styles/components/command.css +25 -0
  35. package/src/styles/components/consent.css +38 -0
  36. package/src/styles/components/datatable.css +9 -0
  37. package/src/styles/components/dialog.css +16 -0
  38. package/src/styles/components/drawer.css +29 -0
  39. package/src/styles/components/field.css +8 -0
  40. package/src/styles/components/layout.css +69 -0
  41. package/src/styles/components/menu.css +21 -0
  42. package/src/styles/components/notice.css +5 -0
  43. package/src/styles/components/popover.css +8 -0
  44. package/src/styles/components/progress.css +14 -0
  45. package/src/styles/components/radio-group.css +11 -0
  46. package/src/styles/components/select.css +25 -0
  47. package/src/styles/components/switch.css +42 -0
  48. package/src/styles/components/tabs.css +4 -0
  49. package/src/styles/components/toast.css +28 -0
  50. package/src/styles/grammars/console.css +114 -256
  51. package/src/styles/grammars/editorial.css +101 -271
  52. package/src/styles/grammars/orbit.css +121 -390
  53. package/src/styles/grammars/prunelle.css +157 -360
  54. package/src/styles/grammars/soft.css +106 -240
  55. package/src/styles/grammars/workshop.css +110 -251
  56. package/src/styles/scan.ts +144 -0
  57. package/src/styles/split.ts +429 -0
  58. package/src/styles/theme.css +22 -0
  59. package/src/styles/themed/accordion.css +20 -0
  60. package/src/styles/themed/badge.css +20 -0
  61. package/src/styles/themed/button.css +24 -0
  62. package/src/styles/themed/card.css +23 -0
  63. package/src/styles/themed/checkbox.css +4 -0
  64. package/src/styles/themed/command.css +33 -0
  65. package/src/styles/themed/consent.css +33 -0
  66. package/src/styles/themed/datatable.css +28 -0
  67. package/src/styles/themed/dialog.css +13 -0
  68. package/src/styles/themed/drawer.css +13 -0
  69. package/src/styles/themed/field.css +22 -0
  70. package/src/styles/themed/menu.css +21 -0
  71. package/src/styles/themed/notice.css +17 -0
  72. package/src/styles/themed/popover.css +11 -0
  73. package/src/styles/themed/radio-group.css +12 -0
  74. package/src/styles/themed/select.css +32 -0
  75. package/src/styles/themed/switch.css +23 -0
  76. package/src/styles/themed/tabs.css +20 -0
  77. package/src/styles/themed/toast.css +18 -0
  78. package/src/table-state.ts +53 -16
  79. 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,10 +6,10 @@
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
- - `@prunellejs/ui/plugin`: `ui(options?)`, `GRAMMAR_NAMES`, `grammarCssPath`, `renderGrammarCss`, `ejectGrammar`
12
+ - `@prunellejs/ui/plugin`: `ui(options?)`, `GRAMMAR_NAMES`, `UI_COMPONENT_PARTS`, `UI_EXPORT_TO_PARTS`, `grammarCssPath`, `renderGrammarCss`, `renderGrammarBaseCss`, `renderGrammarPartsCss`, `ejectGrammar`
13
13
  - CSS subpaths: `@prunellejs/ui/bare.css`, `@prunellejs/ui/grammars/{editorial,workshop,console,soft,orbit,prunelle}.css`
14
14
 
15
15
  ## Plugin Setup (`prunelle.config.ts`)
@@ -25,25 +25,33 @@ 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
- - CLI: `prunelle ui-eject <grammar> [dest]` copies a self-contained CSS grammar (with `bare.css` inlined) into your app (default `editorial` → `src/styles/ui.css`).
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`.
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`).
30
+
31
+ ## Tokenized Grammar Architecture & Per-Component CSS
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`).
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`.
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.
29
37
 
30
38
  ## Key Props & Types
31
39
 
32
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'`.
33
41
  - Layout: `<Stack gap="md">`, `<Cluster gap="sm">`, `<Grid min="md" gap="md">`, `<Sidebar side="sm" gap="lg">`, `<Split gap="md">`.
34
- - `Button`: `{ variant?, tone?, size?, href?, type?, disabled?, class?, children? }` (renders `<a>` when `href` is set, else `<button>`).
35
- - `Field`: `{ id, label, hint?, error?, required?, class?, children? }` — auto-wires `for`, `id`, `aria-describedby`, `aria-invalid`, `required` onto its child control (and provides `FieldContext`).
36
- - `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.
37
45
  - `Progress`: `{ label, value?, max? (100) }`, a native `<progress>`: indeterminate (a loader) without `value`.
38
46
  - `Accordion` + `AccordionItem`: `{ title, group?, open?, children? }` (native `<details name={group}>`).
39
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.
40
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`.
41
- - `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).
42
50
  - `Menu`: `{ id?, label, items: Array<{ id, label, href?, disabled?, onSelect? }>, variant?, onSelect? }`.
43
- - `Select`: `{ id?, options: Array<{ value, label, disabled? }>, value?: Signal<string>, defaultValue?, name?, placeholder?, ariaLabel?, onChange? }`.
44
- - `CommandPalette`: `{ id?, items: CommandItem[], shortcutKey? ('k'), open?: Signal<boolean>, onSelect?, ...labels }`.
45
- - `DataTable`: `{ rows, columns: Array<{ key, label, sortable? }>, rowKey? ('id'), pageSize? (10), searchable? (true), selectable? (false), ...labels }`.
46
- - `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()`.
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`.
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).
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.
47
55
 
48
56
  ## Example
49
57
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/ui",
3
- "version": "0.1.1",
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.1.1"
32
+ "prunelle": "^0.7.0"
33
33
  }
34
34
  }
@@ -3,11 +3,14 @@
3
3
 
4
4
  import type { Signal } from 'prunelle'
5
5
  import { computed, effect, onMount, signal } from 'prunelle'
6
- import { findFirstEnabledIndex, handleListKeyDown, isDialogBackdropClick, nextUiId, syncDialogOpen } from './behaviors'
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
10
12
  label: string
13
+ description?: string | undefined
11
14
  group?: string | undefined
12
15
  shortcut?: string | undefined
13
16
  href?: string | undefined
@@ -15,9 +18,15 @@ export interface CommandItem {
15
18
  onSelect?: (() => void) | undefined
16
19
  }
17
20
 
21
+ export type CommandSource =
22
+ | ((query: string) => CommandItem[] | Promise<CommandItem[]>)
23
+ | { search: (query: string) => CommandItem[] | Promise<CommandItem[]> }
24
+
18
25
  export interface CommandPaletteProps {
19
26
  id?: string | undefined
20
- items: CommandItem[]
27
+ items?: CommandItem[] | undefined
28
+ /** Dynamic or lazy search source (invoked only once the palette opens, e.g. `createSearchSource()` from `@prunellejs/search/client`). */
29
+ source?: CommandSource | undefined
21
30
  placeholder?: string | undefined
22
31
  inputLabel?: string | undefined
23
32
  ariaLabel?: string | undefined
@@ -33,34 +42,95 @@ export interface CommandPaletteProps {
33
42
 
34
43
  const isItemDisabled = (it: CommandItem) => Boolean(it.disabled)
35
44
 
45
+ function filterStaticItems(items: CommandItem[], rawQuery: string): CommandItem[] {
46
+ const q = foldText(rawQuery.trim())
47
+ if (!q)
48
+ return items
49
+ return items.filter(it =>
50
+ foldText(it.label).includes(q)
51
+ || (it.group !== undefined && foldText(it.group).includes(q))
52
+ || (it.description !== undefined && foldText(it.description).includes(q)),
53
+ )
54
+ }
55
+
56
+ function createSourceLoader(
57
+ source: CommandSource | undefined,
58
+ sourceItems: Signal<CommandItem[]>,
59
+ onLoaded: () => void,
60
+ ): (q: string) => void {
61
+ if (!source)
62
+ return () => {}
63
+ let seq = 0
64
+ return (q: string) => {
65
+ const id = ++seq
66
+ const out = typeof source === 'function' ? source(q) : source.search(q)
67
+ Promise.resolve(out).then(
68
+ (results) => {
69
+ if (id === seq) {
70
+ sourceItems.value = results
71
+ onLoaded()
72
+ }
73
+ },
74
+ () => {
75
+ if (id === seq)
76
+ sourceItems.value = []
77
+ },
78
+ )
79
+ }
80
+ }
81
+
82
+ function bindPaletteShortcut(shortcutKey: string, isOpen: Signal<boolean>): void {
83
+ onMount(() => {
84
+ const onKeyDown = (e: KeyboardEvent) => {
85
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === shortcutKey) {
86
+ e.preventDefault()
87
+ isOpen.value = !isOpen.value
88
+ }
89
+ }
90
+ window.addEventListener('keydown', onKeyDown)
91
+ return () => window.removeEventListener('keydown', onKeyDown)
92
+ })
93
+ }
94
+
95
+ function selectCommandItem(item: CommandItem, isOpen: Signal<boolean>, onSelect?: (id: string) => void): void {
96
+ if (item.disabled)
97
+ return
98
+ isOpen.value = false
99
+ item.onSelect?.()
100
+ onSelect?.(item.id)
101
+ if (item.href)
102
+ navigateSafeHref(item.href)
103
+ }
104
+
36
105
  export function CommandPalette(props: CommandPaletteProps) {
37
106
  const baseId = props.id ?? nextUiId('kui-cmd')
38
107
  const listId = `${baseId}-list`
39
108
  const optionId = (idx: number) => `${baseId}-opt-${idx}`
40
- const placeholder = props.placeholder ?? 'Type a command or search...'
41
- const inputLabel = props.inputLabel ?? 'Search commands'
42
- const ariaLabel = props.ariaLabel ?? 'Command palette'
43
- const triggerLabel = props.triggerLabel ?? 'Search (⌘K)'
44
- const emptyLabel = props.emptyLabel ?? 'No matching commands.'
45
- const noResultsLabel = props.noResultsLabel ?? 'No results'
46
- const resultLabel = props.resultLabel ?? 'result'
47
- const resultsLabel = props.resultsLabel ?? 'results'
48
- const shortcutKey = (props.shortcutKey ?? 'k').toLowerCase()
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
117
+ const staticItems = props.items ?? []
49
118
 
50
119
  const isOpen = props.open ?? signal(false)
51
120
  const query = signal('')
52
- const activeIdx = signal(findFirstEnabledIndex(props.items, isItemDisabled))
121
+ const sourceItems = signal<CommandItem[]>([])
122
+ const activeIdx = signal(findFirstEnabledIndex(staticItems, isItemDisabled))
53
123
  let dialogEl: HTMLDialogElement | undefined
54
124
  let inputEl: HTMLInputElement | undefined
55
125
 
56
126
  const filtered = computed(() => {
57
- const q = query.value.trim().toLowerCase()
58
- const items = props.items
59
- if (!q)
60
- return items
61
- return items.filter(it =>
62
- it.label.toLowerCase().includes(q) || (it.group?.toLowerCase().includes(q) ?? false),
63
- )
127
+ const base = filterStaticItems(staticItems, query.value)
128
+ const remote = sourceItems.value
129
+ return remote.length ? (base.length ? [...base, ...remote] : remote) : base
130
+ })
131
+
132
+ const refreshSource = createSourceLoader(props.source, sourceItems, () => {
133
+ activeIdx.value = findFirstEnabledIndex(filtered.value, isItemDisabled)
64
134
  })
65
135
 
66
136
  const activeOptionId = () => {
@@ -73,41 +143,20 @@ export function CommandPalette(props: CommandPaletteProps) {
73
143
  if (!isOpen.value)
74
144
  return ''
75
145
  const n = filtered.value.length
76
- if (n === 0)
77
- return noResultsLabel
78
- return n === 1 ? `1 ${resultLabel}` : `${n} ${resultsLabel}`
146
+ return n === 0 ? noResultsLabel : n === 1 ? `1 ${resultLabel}` : `${n} ${resultsLabel}`
79
147
  }
80
148
 
81
149
  const onOpened = () => {
82
150
  query.value = ''
83
- activeIdx.value = findFirstEnabledIndex(props.items, isItemDisabled)
151
+ activeIdx.value = findFirstEnabledIndex(staticItems, isItemDisabled)
152
+ refreshSource('')
84
153
  queueMicrotask(() => inputEl?.focus())
85
154
  }
86
155
 
87
- onMount(() => {
88
- const onKeyDown = (e: KeyboardEvent) => {
89
- if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === shortcutKey) {
90
- e.preventDefault()
91
- isOpen.value = !isOpen.value
92
- }
93
- }
94
- window.addEventListener('keydown', onKeyDown)
95
- return () => window.removeEventListener('keydown', onKeyDown)
96
- })
156
+ bindPaletteShortcut((props.shortcutKey ?? 'k').toLowerCase(), isOpen)
157
+ effect(() => { syncDialogOpen(dialogEl, isOpen, isOpen.value, onOpened) })
97
158
 
98
- effect(() => {
99
- syncDialogOpen(dialogEl, isOpen, isOpen.value, onOpened)
100
- })
101
-
102
- const runItem = (item: CommandItem) => {
103
- if (item.disabled)
104
- return
105
- isOpen.value = false
106
- item.onSelect?.()
107
- props.onSelect?.(item.id)
108
- if (item.href)
109
- window.location.assign(item.href)
110
- }
159
+ const runItem = (item: CommandItem) => selectCommandItem(item, isOpen, props.onSelect)
111
160
 
112
161
  return (
113
162
  <div data-ui="command-root" data-state={isOpen.value ? 'open' : 'closed'}>
@@ -148,13 +197,15 @@ export function CommandPalette(props: CommandPaletteProps) {
148
197
  aria-label={inputLabel}
149
198
  aria-expanded={isOpen.value ? 'true' : 'false'}
150
199
  aria-autocomplete="list"
151
- aria-controls={listId}
200
+ aria-controls={filtered.value.length > 0 ? listId : undefined}
152
201
  aria-activedescendant={activeOptionId()}
153
202
  placeholder={placeholder}
154
203
  value={query.value}
155
204
  onInput={(e) => {
156
- query.value = e.currentTarget.value
205
+ const val = e.currentTarget.value
206
+ query.value = val
157
207
  activeIdx.value = findFirstEnabledIndex(filtered.value, isItemDisabled)
208
+ refreshSource(val)
158
209
  }}
159
210
  onKeyDown={(e) => {
160
211
  handleListKeyDown(e, {
@@ -170,33 +221,37 @@ export function CommandPalette(props: CommandPaletteProps) {
170
221
  }}
171
222
  />
172
223
  </div>
173
- <div id={listId} data-part="list" role="listbox" aria-label={inputLabel}>
174
- {filtered.value.map((item, idx) => (
175
- <button
176
- key={item.id}
177
- id={optionId(idx)}
178
- type="button"
179
- role="option"
180
- tabindex={-1}
181
- disabled={item.disabled}
182
- aria-disabled={item.disabled ? 'true' : undefined}
183
- data-part="item"
184
- data-highlighted={activeIdx.value === idx ? 'true' : undefined}
185
- aria-selected={activeIdx.value === idx ? 'true' : 'false'}
186
- onMouseEnter={() => {
187
- if (!item.disabled)
188
- activeIdx.value = idx
189
- }}
190
- onClick={() => runItem(item)}
191
- >
192
- <span data-part="item-label">{item.label}</span>
193
- {item.shortcut && <kbd data-part="kbd">{item.shortcut}</kbd>}
194
- </button>
195
- ))}
196
- </div>
197
- {filtered.value.length === 0 && (
198
- <p data-part="empty">{emptyLabel}</p>
199
- )}
224
+ {filtered.value.length > 0
225
+ ? (
226
+ <div id={listId} data-part="list" role="listbox" aria-label={inputLabel}>
227
+ {filtered.value.map((item, idx) => (
228
+ <button
229
+ key={item.id}
230
+ id={optionId(idx)}
231
+ type="button"
232
+ role="option"
233
+ tabindex={-1}
234
+ disabled={item.disabled}
235
+ aria-disabled={item.disabled ? 'true' : undefined}
236
+ data-part="item"
237
+ data-highlighted={activeIdx.value === idx ? 'true' : undefined}
238
+ aria-selected={activeIdx.value === idx ? 'true' : 'false'}
239
+ onMouseEnter={() => {
240
+ if (!item.disabled)
241
+ activeIdx.value = idx
242
+ }}
243
+ onClick={() => runItem(item)}
244
+ >
245
+ <span data-part="item-label">{item.label}</span>
246
+ {item.description && <span data-part="item-description">{item.description}</span>}
247
+ {item.shortcut && <kbd data-part="kbd">{item.shortcut}</kbd>}
248
+ </button>
249
+ ))}
250
+ </div>
251
+ )
252
+ : (
253
+ <p data-part="empty">{emptyLabel}</p>
254
+ )}
200
255
  <div class="kui-sr-only" role="status" aria-live="polite" aria-atomic="true">
201
256
  {statusText()}
202
257
  </div>
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,11 +31,71 @@ 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
28
40
  prevLabel?: string | undefined
29
41
  nextLabel?: string | undefined
42
+ emptyLabel?: string | undefined
43
+ }
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
+ )
30
99
  }
31
100
 
32
101
  export function DataTable(props: DataTableProps) {
@@ -35,25 +104,38 @@ export function DataTable(props: DataTableProps) {
35
104
  const selectable = props.selectable ?? false
36
105
  const caption = props.caption
37
106
  const ariaLabel = props.ariaLabel
38
- const placeholder = props.placeholder ?? 'Filter rows...'
39
- const searchLabel = props.searchLabel ?? 'Search'
40
- const selectColumnLabel = props.selectColumnLabel ?? 'Select'
41
- const selectRowLabel = props.selectRowLabel ?? 'Select row'
42
- const rowsLabel = props.rowsLabel ?? 'rows'
43
- const selectedLabel = props.selectedLabel ?? 'selected'
44
- const pageLabel = props.pageLabel ?? 'Page'
45
- const prevLabel = props.prevLabel ?? 'Prev'
46
- const nextLabel = props.nextLabel ?? 'Next'
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
47
120
  const columns = props.columns
48
- 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
49
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('')
50
126
 
51
127
  const table = createDataTable({
52
- rows: () => props.rows,
128
+ rows: () => checkedRows(props.rows, rowKey),
53
129
  getKey: keyOf,
130
+ locale: props.locale,
131
+ onSelect: props.onSelect,
54
132
  pageSize: props.pageSize ?? 10,
55
133
  searchText: r => columns.map(c => String(r[c.key] ?? '')).join(' '),
56
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))
57
139
 
58
140
  return (
59
141
  <div data-ui="datatable">
@@ -70,7 +152,7 @@ export function DataTable(props: DataTableProps) {
70
152
  table.page.value = 1
71
153
  }}
72
154
  />
73
- <span data-part="meta">
155
+ <span data-part="meta" role="status" aria-live="polite">
74
156
  {`${table.filtered.value.length} ${rowsLabel}${selectable && table.selected.value.size > 0 ? ` · ${table.selected.value.size} ${selectedLabel}` : ''}`}
75
157
  </span>
76
158
  </div>
@@ -84,6 +166,13 @@ export function DataTable(props: DataTableProps) {
84
166
  {selectable && (
85
167
  <th scope="col" data-part="select-col">
86
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
+ />
87
176
  </th>
88
177
  )}
89
178
  {columns.map(col => (
@@ -98,7 +187,10 @@ export function DataTable(props: DataTableProps) {
98
187
  type="button"
99
188
  data-part="sort"
100
189
  data-active={sortOf(col.key) ? 'true' : undefined}
101
- onClick={() => table.toggleSort(col.key)}
190
+ onClick={() => {
191
+ table.toggleSort(col.key)
192
+ said.value = `${col.label}, ${table.sortDir.peek() === 'asc' ? ascendingLabel : descendingLabel}`
193
+ }}
102
194
  >
103
195
  {col.label}
104
196
  <span aria-hidden="true">{sortOf(col.key) === 'asc' ? ' ↑' : sortOf(col.key) === 'desc' ? ' ↓' : ''}</span>
@@ -110,56 +202,37 @@ export function DataTable(props: DataTableProps) {
110
202
  </tr>
111
203
  </thead>
112
204
  <tbody>
113
- {table.visible.value.map(row => (
114
- <tr key={keyOf(row)} data-selected={table.isSelected(keyOf(row)) ? 'true' : undefined}>
115
- {selectable && (
116
- <td data-part="select-col">
117
- <input
118
- type="checkbox"
119
- checked={table.isSelected(keyOf(row))}
120
- aria-label={`${selectRowLabel} ${keyOf(row)}`}
121
- onChange={() => table.toggleSelect(keyOf(row))}
122
- />
123
- </td>
124
- )}
125
- {columns.map(col => (
126
- <td key={col.key}>{String(row[col.key] ?? '')}</td>
205
+ {table.visible.value.length === 0
206
+ ? (
207
+ <tr data-part="empty">
208
+ <td colspan={Math.max(1, columns.length + (selectable ? 1 : 0))}>
209
+ {emptyLabel}
210
+ </td>
211
+ </tr>
212
+ )
213
+ : table.visible.value.map(row => (
214
+ <tr key={keyOf(row)} data-selected={table.isSelected(keyOf(row)) ? 'true' : undefined}>
215
+ {selectable && (
216
+ <td data-part="select-col">
217
+ <input
218
+ type="checkbox"
219
+ checked={table.isSelected(keyOf(row))}
220
+ aria-label={`${selectRowLabel} ${String(row[labelKey] ?? keyOf(row))}`}
221
+ onChange={() => table.toggleSelect(keyOf(row))}
222
+ />
223
+ </td>
224
+ )}
225
+ {columns.map(col => (
226
+ <td key={col.key}>{String(row[col.key] ?? '')}</td>
227
+ ))}
228
+ </tr>
127
229
  ))}
128
- </tr>
129
- ))}
130
230
  </tbody>
131
231
  </table>
132
232
  </div>
133
233
 
134
- {table.totalPages.value > 1 && (
135
- <div data-part="pagination" data-layout="split">
136
- <span data-part="meta">
137
- {`${pageLabel} ${table.page.value} / ${table.totalPages.value}`}
138
- </span>
139
- <div data-layout="cluster">
140
- <button
141
- data-ui="button"
142
- data-variant="outline"
143
- data-size="sm"
144
- type="button"
145
- disabled={table.page.value <= 1}
146
- onClick={() => { table.page.value-- }}
147
- >
148
- {prevLabel}
149
- </button>
150
- <button
151
- data-ui="button"
152
- data-variant="outline"
153
- data-size="sm"
154
- type="button"
155
- disabled={table.page.value >= table.totalPages.value}
156
- onClick={() => { table.page.value++ }}
157
- >
158
- {nextLabel}
159
- </button>
160
- </div>
161
- </div>
162
- )}
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>
163
236
  </div>
164
237
  )
165
238
  }