@prunellejs/ui 0.0.0-stage → 0.5.2

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 (70) hide show
  1. package/llms.txt +76 -0
  2. package/package.json +32 -4
  3. package/src/CommandPalette.tsx +257 -0
  4. package/src/DataTable.tsx +165 -0
  5. package/src/Dialog.tsx +165 -0
  6. package/src/Drawer.tsx +4 -0
  7. package/src/Menu.tsx +115 -0
  8. package/src/Select.tsx +114 -0
  9. package/src/Tabs.tsx +63 -0
  10. package/src/Toaster.tsx +31 -0
  11. package/src/behaviors.ts +287 -0
  12. package/src/field-context.ts +21 -0
  13. package/src/index.ts +72 -0
  14. package/src/platform-fallback.ts +36 -0
  15. package/src/plugin.ts +169 -0
  16. package/src/primitives.tsx +237 -0
  17. package/src/static.tsx +319 -0
  18. package/src/styles/bare.css +24 -0
  19. package/src/styles/base.css +55 -0
  20. package/src/styles/components/accordion.css +10 -0
  21. package/src/styles/components/badge.css +6 -0
  22. package/src/styles/components/button.css +11 -0
  23. package/src/styles/components/card.css +5 -0
  24. package/src/styles/components/checkbox.css +11 -0
  25. package/src/styles/components/command.css +25 -0
  26. package/src/styles/components/datatable.css +9 -0
  27. package/src/styles/components/dialog.css +16 -0
  28. package/src/styles/components/drawer.css +29 -0
  29. package/src/styles/components/field.css +8 -0
  30. package/src/styles/components/layout.css +69 -0
  31. package/src/styles/components/menu.css +21 -0
  32. package/src/styles/components/notice.css +5 -0
  33. package/src/styles/components/popover.css +8 -0
  34. package/src/styles/components/progress.css +14 -0
  35. package/src/styles/components/radio-group.css +11 -0
  36. package/src/styles/components/select.css +25 -0
  37. package/src/styles/components/switch.css +42 -0
  38. package/src/styles/components/tabs.css +4 -0
  39. package/src/styles/components/toast.css +28 -0
  40. package/src/styles/grammars/console.css +178 -0
  41. package/src/styles/grammars/editorial.css +163 -0
  42. package/src/styles/grammars/orbit.css +268 -0
  43. package/src/styles/grammars/prunelle.css +449 -0
  44. package/src/styles/grammars/soft.css +160 -0
  45. package/src/styles/grammars/workshop.css +171 -0
  46. package/src/styles/scan.ts +137 -0
  47. package/src/styles/split.ts +381 -0
  48. package/src/styles/theme.css +21 -0
  49. package/src/styles/themed/accordion.css +20 -0
  50. package/src/styles/themed/badge.css +20 -0
  51. package/src/styles/themed/button.css +21 -0
  52. package/src/styles/themed/card.css +23 -0
  53. package/src/styles/themed/checkbox.css +4 -0
  54. package/src/styles/themed/command.css +33 -0
  55. package/src/styles/themed/datatable.css +28 -0
  56. package/src/styles/themed/dialog.css +13 -0
  57. package/src/styles/themed/drawer.css +13 -0
  58. package/src/styles/themed/field.css +22 -0
  59. package/src/styles/themed/menu.css +21 -0
  60. package/src/styles/themed/notice.css +17 -0
  61. package/src/styles/themed/popover.css +11 -0
  62. package/src/styles/themed/radio-group.css +12 -0
  63. package/src/styles/themed/select.css +32 -0
  64. package/src/styles/themed/switch.css +18 -0
  65. package/src/styles/themed/tabs.css +17 -0
  66. package/src/styles/themed/toast.css +18 -0
  67. package/src/table-state.ts +126 -0
  68. package/src/tabs-state.ts +39 -0
  69. package/src/toast.ts +68 -0
  70. package/README.md +0 -3
package/llms.txt ADDED
@@ -0,0 +1,76 @@
1
+ # @prunellejs/ui Reference
2
+
3
+ > Platform-first headless UI primitives and pure CSS `@layer kui` Style Grammars (`0 KB` JS for static primitives; islands only for interactive widgets).
4
+
5
+ ## Imports
6
+
7
+ - `@prunellejs/ui`:
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)
10
+ - Interactive island primitives: `ControlledDialog`, `ControlledDrawer`, `Tabs`, `Menu`, `Select`, `CommandPalette`, `DataTable`, `Toaster`
11
+ - Headless signal behaviors & helpers: `createDialog`, `createTabs`, `createDataTable`, `toast`, `handleListKeyDown`, `findFirstEnabledIndex`, `findLastEnabledIndex`, `findNextEnabledIndex`, `isDialogBackdropClick`, `syncDialogOpen`, `nextUiId`
12
+ - `@prunellejs/ui/plugin`: `ui(options?)`, `GRAMMAR_NAMES`, `UI_COMPONENT_PARTS`, `UI_EXPORT_TO_PARTS`, `grammarCssPath`, `renderGrammarCss`, `renderGrammarBaseCss`, `renderGrammarPartsCss`, `ejectGrammar`
13
+ - CSS subpaths: `@prunellejs/ui/bare.css`, `@prunellejs/ui/grammars/{editorial,workshop,console,soft,orbit,prunelle}.css`
14
+
15
+ ## Plugin Setup (`prunelle.config.ts`)
16
+
17
+ ```ts
18
+ import { defineConfig } from 'prunelle/config'
19
+ import { ui } from '@prunellejs/ui/plugin'
20
+
21
+ export default defineConfig({
22
+ plugins: [ui({ grammar: 'editorial' })],
23
+ })
24
+ ```
25
+
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
+ - `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 `base.css` and component sheets inlined) into your app (default `editorial` → `src/styles/ui.css`).
29
+
30
+ ## Tokenized Grammar Architecture & Per-Component CSS
31
+
32
+ - 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
+ - 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
+ - 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).
35
+
36
+ ## Key Props & Types
37
+
38
+ - 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
+ - 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? }`.
43
+ - `Progress`: `{ label, value?, max? (100) }`, a native `<progress>`: indeterminate (a loader) without `value`.
44
+ - `Accordion` + `AccordionItem`: `{ title, group?, open?, children? }` (native `<details name={group}>`).
45
+ - `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
+ - `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? }`.
48
+ - `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? }`.
50
+ - `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
+
54
+ ## Example
55
+
56
+ ```tsx
57
+ import { Button, Card, CardBody, Field, Stack } from '@prunellejs/ui'
58
+ import { createPost } from '../actions/posts'
59
+
60
+ export default function NewPostForm({ error }: { error?: string }) {
61
+ return (
62
+ <Card>
63
+ <CardBody>
64
+ <form action={createPost} method="post">
65
+ <Stack gap="md">
66
+ <Field id="title" label="Title" error={error} required>
67
+ <input name="title" type="text" />
68
+ </Field>
69
+ <Button type="submit" tone="accent">Publish</Button>
70
+ </Stack>
71
+ </form>
72
+ </CardBody>
73
+ </Card>
74
+ )
75
+ }
76
+ ```
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@prunellejs/ui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.2",
4
+ "description": "Platform-first headless UI primitives and pure CSS @layer kui Style Grammars for Prunelle",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "files": [
9
+ "src",
10
+ "llms.txt"
11
+ ],
12
+ "exports": {
13
+ ".": "./src/index.ts",
14
+ "./plugin": "./src/plugin.ts",
15
+ "./bare.css": "./src/styles/bare.css",
16
+ "./grammars/editorial.css": "./src/styles/grammars/editorial.css",
17
+ "./grammars/workshop.css": "./src/styles/grammars/workshop.css",
18
+ "./grammars/console.css": "./src/styles/grammars/console.css",
19
+ "./grammars/soft.css": "./src/styles/grammars/soft.css",
20
+ "./grammars/orbit.css": "./src/styles/grammars/orbit.css",
21
+ "./grammars/prunelle.css": "./src/styles/grammars/prunelle.css"
22
+ },
23
+ "engines": {
24
+ "bun": ">=1.4.0"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/Kayno0o/prunelle",
29
+ "directory": "packages/ui"
30
+ },
31
+ "peerDependencies": {
32
+ "prunelle": "^0.5.2"
33
+ }
34
+ }
@@ -0,0 +1,257 @@
1
+ /** @jsxImportSource prunelle */
2
+ // Accessible Cmd+K / Ctrl+K CommandPalette built on native `<dialog>` + fine-grained signals.
3
+
4
+ import type { Signal } from 'prunelle'
5
+ import { computed, effect, onMount, signal } from 'prunelle'
6
+ import { findFirstEnabledIndex, handleListKeyDown, isDialogBackdropClick, nextUiId, syncDialogOpen } from './behaviors'
7
+
8
+ export interface CommandItem {
9
+ id: string
10
+ label: string
11
+ description?: string | undefined
12
+ group?: string | undefined
13
+ shortcut?: string | undefined
14
+ href?: string | undefined
15
+ disabled?: boolean | undefined
16
+ onSelect?: (() => void) | undefined
17
+ }
18
+
19
+ export type CommandSource =
20
+ | ((query: string) => CommandItem[] | Promise<CommandItem[]>)
21
+ | { search: (query: string) => CommandItem[] | Promise<CommandItem[]> }
22
+
23
+ export interface CommandPaletteProps {
24
+ id?: string | undefined
25
+ items?: CommandItem[] | undefined
26
+ /** Dynamic or lazy search source (invoked only once the palette opens, e.g. `createSearchSource()` from `@prunellejs/search/client`). */
27
+ source?: CommandSource | undefined
28
+ placeholder?: string | undefined
29
+ inputLabel?: string | undefined
30
+ ariaLabel?: string | undefined
31
+ triggerLabel?: string | undefined
32
+ emptyLabel?: string | undefined
33
+ noResultsLabel?: string | undefined
34
+ resultLabel?: string | undefined
35
+ resultsLabel?: string | undefined
36
+ shortcutKey?: string | undefined
37
+ open?: Signal<boolean> | undefined
38
+ onSelect?: ((id: string) => void) | undefined
39
+ }
40
+
41
+ const isItemDisabled = (it: CommandItem) => Boolean(it.disabled)
42
+
43
+ function filterStaticItems(items: CommandItem[], rawQuery: string): CommandItem[] {
44
+ const q = rawQuery.trim().toLowerCase()
45
+ if (!q)
46
+ return items
47
+ return items.filter(it =>
48
+ it.label.toLowerCase().includes(q)
49
+ || (it.group?.toLowerCase().includes(q) ?? false)
50
+ || (it.description?.toLowerCase().includes(q) ?? false),
51
+ )
52
+ }
53
+
54
+ function createSourceLoader(
55
+ source: CommandSource | undefined,
56
+ sourceItems: Signal<CommandItem[]>,
57
+ onLoaded: () => void,
58
+ ): (q: string) => void {
59
+ if (!source)
60
+ return () => {}
61
+ let seq = 0
62
+ return (q: string) => {
63
+ const id = ++seq
64
+ const out = typeof source === 'function' ? source(q) : source.search(q)
65
+ Promise.resolve(out).then(
66
+ (results) => {
67
+ if (id === seq) {
68
+ sourceItems.value = results
69
+ onLoaded()
70
+ }
71
+ },
72
+ () => {
73
+ if (id === seq)
74
+ sourceItems.value = []
75
+ },
76
+ )
77
+ }
78
+ }
79
+
80
+ function bindPaletteShortcut(shortcutKey: string, isOpen: Signal<boolean>): void {
81
+ onMount(() => {
82
+ const onKeyDown = (e: KeyboardEvent) => {
83
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === shortcutKey) {
84
+ e.preventDefault()
85
+ isOpen.value = !isOpen.value
86
+ }
87
+ }
88
+ window.addEventListener('keydown', onKeyDown)
89
+ return () => window.removeEventListener('keydown', onKeyDown)
90
+ })
91
+ }
92
+
93
+ function selectCommandItem(item: CommandItem, isOpen: Signal<boolean>, onSelect?: (id: string) => void): void {
94
+ if (item.disabled)
95
+ return
96
+ isOpen.value = false
97
+ item.onSelect?.()
98
+ onSelect?.(item.id)
99
+ if (item.href)
100
+ window.location.assign(item.href)
101
+ }
102
+
103
+ export function CommandPalette(props: CommandPaletteProps) {
104
+ const baseId = props.id ?? nextUiId('kui-cmd')
105
+ const listId = `${baseId}-list`
106
+ 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'
115
+ const staticItems = props.items ?? []
116
+
117
+ const isOpen = props.open ?? signal(false)
118
+ const query = signal('')
119
+ const sourceItems = signal<CommandItem[]>([])
120
+ const activeIdx = signal(findFirstEnabledIndex(staticItems, isItemDisabled))
121
+ let dialogEl: HTMLDialogElement | undefined
122
+ let inputEl: HTMLInputElement | undefined
123
+
124
+ const filtered = computed(() => {
125
+ const base = filterStaticItems(staticItems, query.value)
126
+ const remote = sourceItems.value
127
+ return remote.length ? (base.length ? [...base, ...remote] : remote) : base
128
+ })
129
+
130
+ const refreshSource = createSourceLoader(props.source, sourceItems, () => {
131
+ activeIdx.value = findFirstEnabledIndex(filtered.value, isItemDisabled)
132
+ })
133
+
134
+ const activeOptionId = () => {
135
+ const list = filtered.value
136
+ const idx = activeIdx.value
137
+ return !isOpen.value || idx < 0 || idx >= list.length || list[idx]?.disabled ? undefined : optionId(idx)
138
+ }
139
+
140
+ const statusText = () => {
141
+ if (!isOpen.value)
142
+ return ''
143
+ const n = filtered.value.length
144
+ return n === 0 ? noResultsLabel : n === 1 ? `1 ${resultLabel}` : `${n} ${resultsLabel}`
145
+ }
146
+
147
+ const onOpened = () => {
148
+ query.value = ''
149
+ activeIdx.value = findFirstEnabledIndex(staticItems, isItemDisabled)
150
+ refreshSource('')
151
+ queueMicrotask(() => inputEl?.focus())
152
+ }
153
+
154
+ bindPaletteShortcut((props.shortcutKey ?? 'k').toLowerCase(), isOpen)
155
+ effect(() => { syncDialogOpen(dialogEl, isOpen, isOpen.value, onOpened) })
156
+
157
+ const runItem = (item: CommandItem) => selectCommandItem(item, isOpen, props.onSelect)
158
+
159
+ return (
160
+ <div data-ui="command-root" data-state={isOpen.value ? 'open' : 'closed'}>
161
+ {triggerLabel && (
162
+ <button
163
+ data-ui="button"
164
+ data-variant="outline"
165
+ data-part="trigger"
166
+ type="button"
167
+ aria-haspopup="dialog"
168
+ aria-expanded={isOpen.value ? 'true' : 'false'}
169
+ onClick={() => { isOpen.value = true }}
170
+ >
171
+ {triggerLabel}
172
+ </button>
173
+ )}
174
+ <dialog
175
+ data-ui="command"
176
+ data-part="content"
177
+ aria-label={ariaLabel}
178
+ ref={(el) => {
179
+ dialogEl = el
180
+ syncDialogOpen(dialogEl, isOpen, isOpen.peek(), onOpened)
181
+ }}
182
+ onClose={() => { isOpen.value = false }}
183
+ onClick={(e) => {
184
+ if (isDialogBackdropClick(e, dialogEl))
185
+ isOpen.value = false
186
+ }}
187
+ >
188
+ <div data-part="panel">
189
+ <div data-part="input-wrap">
190
+ <input
191
+ ref={(el) => { inputEl = el }}
192
+ data-part="input"
193
+ type="search"
194
+ role="combobox"
195
+ aria-label={inputLabel}
196
+ aria-expanded={isOpen.value ? 'true' : 'false'}
197
+ aria-autocomplete="list"
198
+ aria-controls={listId}
199
+ aria-activedescendant={activeOptionId()}
200
+ placeholder={placeholder}
201
+ value={query.value}
202
+ onInput={(e) => {
203
+ const val = e.currentTarget.value
204
+ query.value = val
205
+ activeIdx.value = findFirstEnabledIndex(filtered.value, isItemDisabled)
206
+ refreshSource(val)
207
+ }}
208
+ onKeyDown={(e) => {
209
+ handleListKeyDown(e, {
210
+ items: () => filtered.value,
211
+ activeIndex: activeIdx,
212
+ isDisabled: isItemDisabled,
213
+ onSelect: runItem,
214
+ onClose: () => { isOpen.value = false },
215
+ selectOnSpace: false,
216
+ homeEnd: false,
217
+ closeOnTab: false,
218
+ })
219
+ }}
220
+ />
221
+ </div>
222
+ <div id={listId} data-part="list" role="listbox" aria-label={inputLabel}>
223
+ {filtered.value.map((item, idx) => (
224
+ <button
225
+ key={item.id}
226
+ id={optionId(idx)}
227
+ type="button"
228
+ role="option"
229
+ tabindex={-1}
230
+ disabled={item.disabled}
231
+ aria-disabled={item.disabled ? 'true' : undefined}
232
+ data-part="item"
233
+ data-highlighted={activeIdx.value === idx ? 'true' : undefined}
234
+ aria-selected={activeIdx.value === idx ? 'true' : 'false'}
235
+ onMouseEnter={() => {
236
+ if (!item.disabled)
237
+ activeIdx.value = idx
238
+ }}
239
+ onClick={() => runItem(item)}
240
+ >
241
+ <span data-part="item-label">{item.label}</span>
242
+ {item.description && <span data-part="item-description">{item.description}</span>}
243
+ {item.shortcut && <kbd data-part="kbd">{item.shortcut}</kbd>}
244
+ </button>
245
+ ))}
246
+ </div>
247
+ {filtered.value.length === 0 && (
248
+ <p data-part="empty">{emptyLabel}</p>
249
+ )}
250
+ <div class="kui-sr-only" role="status" aria-live="polite" aria-atomic="true">
251
+ {statusText()}
252
+ </div>
253
+ </div>
254
+ </dialog>
255
+ </div>
256
+ )
257
+ }
@@ -0,0 +1,165 @@
1
+ /** @jsxImportSource prunelle */
2
+ // Interactive DataTable island powered by headless `createDataTable()` signals (sort, filter, select, paginate).
3
+
4
+ import { createDataTable } from './table-state'
5
+
6
+ export interface DataTableColumn {
7
+ key: string
8
+ label: string
9
+ sortable?: boolean | undefined
10
+ }
11
+
12
+ export interface DataTableProps {
13
+ rows: Array<Record<string, string | number>>
14
+ columns: DataTableColumn[]
15
+ rowKey?: string | undefined
16
+ pageSize?: number | undefined
17
+ searchable?: boolean | undefined
18
+ selectable?: boolean | undefined
19
+ caption?: string | undefined
20
+ ariaLabel?: string | undefined
21
+ placeholder?: string | undefined
22
+ searchLabel?: string | undefined
23
+ selectColumnLabel?: string | undefined
24
+ selectRowLabel?: string | undefined
25
+ rowsLabel?: string | undefined
26
+ selectedLabel?: string | undefined
27
+ pageLabel?: string | undefined
28
+ prevLabel?: string | undefined
29
+ nextLabel?: string | undefined
30
+ }
31
+
32
+ export function DataTable(props: DataTableProps) {
33
+ const rowKey = props.rowKey ?? 'id'
34
+ const searchable = props.searchable ?? true
35
+ const selectable = props.selectable ?? false
36
+ const caption = props.caption
37
+ 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'
47
+ const columns = props.columns
48
+ const keyOf = (r: Record<string, string | number>) => String(r[rowKey] ?? '')
49
+ const sortOf = (k: string) => (table.sortBy.value === k ? table.sortDir.value : undefined)
50
+
51
+ const table = createDataTable({
52
+ rows: () => props.rows,
53
+ getKey: keyOf,
54
+ pageSize: props.pageSize ?? 10,
55
+ searchText: r => columns.map(c => String(r[c.key] ?? '')).join(' '),
56
+ })
57
+
58
+ return (
59
+ <div data-ui="datatable">
60
+ {searchable && (
61
+ <div data-part="toolbar" data-layout="split">
62
+ <input
63
+ data-part="search"
64
+ type="search"
65
+ aria-label={searchLabel}
66
+ placeholder={placeholder}
67
+ value={table.query.value}
68
+ onInput={(e) => {
69
+ table.query.value = e.currentTarget.value
70
+ table.page.value = 1
71
+ }}
72
+ />
73
+ <span data-part="meta">
74
+ {`${table.filtered.value.length} ${rowsLabel}${selectable && table.selected.value.size > 0 ? ` · ${table.selected.value.size} ${selectedLabel}` : ''}`}
75
+ </span>
76
+ </div>
77
+ )}
78
+
79
+ <div data-part="scroll">
80
+ <table data-ui="table" aria-label={caption ? undefined : ariaLabel}>
81
+ {caption && <caption data-part="caption">{caption}</caption>}
82
+ <thead>
83
+ <tr>
84
+ {selectable && (
85
+ <th scope="col" data-part="select-col">
86
+ <span class="kui-sr-only">{selectColumnLabel}</span>
87
+ </th>
88
+ )}
89
+ {columns.map(col => (
90
+ <th
91
+ key={col.key}
92
+ scope="col"
93
+ aria-sort={col.sortable === false ? undefined : sortOf(col.key) === 'asc' ? 'ascending' : sortOf(col.key) === 'desc' ? 'descending' : 'none'}
94
+ >
95
+ {col.sortable !== false
96
+ ? (
97
+ <button
98
+ type="button"
99
+ data-part="sort"
100
+ data-active={sortOf(col.key) ? 'true' : undefined}
101
+ onClick={() => table.toggleSort(col.key)}
102
+ >
103
+ {col.label}
104
+ <span aria-hidden="true">{sortOf(col.key) === 'asc' ? ' ↑' : sortOf(col.key) === 'desc' ? ' ↓' : ''}</span>
105
+ </button>
106
+ )
107
+ : col.label}
108
+ </th>
109
+ ))}
110
+ </tr>
111
+ </thead>
112
+ <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>
127
+ ))}
128
+ </tr>
129
+ ))}
130
+ </tbody>
131
+ </table>
132
+ </div>
133
+
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
+ )}
163
+ </div>
164
+ )
165
+ }