@prunellejs/ui 0.0.0-stage → 0.7.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.
- package/LICENSE +21 -0
- package/llms.txt +78 -0
- package/package.json +32 -4
- package/src/CommandPalette.tsx +262 -0
- package/src/DataTable.tsx +244 -0
- package/src/Dialog.tsx +181 -0
- package/src/Drawer.tsx +4 -0
- package/src/Menu.tsx +117 -0
- package/src/Select.tsx +125 -0
- package/src/Tabs.tsx +64 -0
- package/src/Toaster.tsx +105 -0
- package/src/behaviors.ts +385 -0
- package/src/field-context.ts +21 -0
- package/src/fold.ts +7 -0
- package/src/index.ts +72 -0
- package/src/labels/dialog.ts +3 -0
- package/src/labels/fr/dialog.ts +3 -0
- package/src/labels/fr/palette.ts +8 -0
- package/src/labels/fr/select.ts +1 -0
- package/src/labels/fr/table.ts +13 -0
- package/src/labels/fr/toaster.ts +1 -0
- package/src/labels/palette.ts +8 -0
- package/src/labels/select.ts +1 -0
- package/src/labels/table.ts +13 -0
- package/src/labels/toaster.ts +1 -0
- package/src/platform-fallback.ts +36 -0
- package/src/plugin.ts +188 -0
- package/src/primitives.tsx +238 -0
- package/src/static.tsx +324 -0
- package/src/styles/bare.css +25 -0
- package/src/styles/base.css +61 -0
- package/src/styles/components/accordion.css +10 -0
- package/src/styles/components/badge.css +6 -0
- package/src/styles/components/button.css +11 -0
- package/src/styles/components/card.css +5 -0
- package/src/styles/components/checkbox.css +11 -0
- package/src/styles/components/command.css +25 -0
- package/src/styles/components/consent.css +38 -0
- package/src/styles/components/datatable.css +9 -0
- package/src/styles/components/dialog.css +16 -0
- package/src/styles/components/drawer.css +29 -0
- package/src/styles/components/field.css +8 -0
- package/src/styles/components/layout.css +69 -0
- package/src/styles/components/menu.css +21 -0
- package/src/styles/components/notice.css +5 -0
- package/src/styles/components/popover.css +8 -0
- package/src/styles/components/progress.css +14 -0
- package/src/styles/components/radio-group.css +11 -0
- package/src/styles/components/select.css +25 -0
- package/src/styles/components/switch.css +42 -0
- package/src/styles/components/tabs.css +4 -0
- package/src/styles/components/toast.css +28 -0
- package/src/styles/grammars/console.css +179 -0
- package/src/styles/grammars/editorial.css +164 -0
- package/src/styles/grammars/orbit.css +269 -0
- package/src/styles/grammars/prunelle.css +504 -0
- package/src/styles/grammars/soft.css +160 -0
- package/src/styles/grammars/workshop.css +172 -0
- package/src/styles/scan.ts +144 -0
- package/src/styles/split.ts +429 -0
- package/src/styles/theme.css +22 -0
- package/src/styles/themed/accordion.css +20 -0
- package/src/styles/themed/badge.css +20 -0
- package/src/styles/themed/button.css +24 -0
- package/src/styles/themed/card.css +23 -0
- package/src/styles/themed/checkbox.css +4 -0
- package/src/styles/themed/command.css +33 -0
- package/src/styles/themed/consent.css +33 -0
- package/src/styles/themed/datatable.css +28 -0
- package/src/styles/themed/dialog.css +13 -0
- package/src/styles/themed/drawer.css +13 -0
- package/src/styles/themed/field.css +22 -0
- package/src/styles/themed/menu.css +21 -0
- package/src/styles/themed/notice.css +17 -0
- package/src/styles/themed/popover.css +11 -0
- package/src/styles/themed/radio-group.css +12 -0
- package/src/styles/themed/select.css +32 -0
- package/src/styles/themed/switch.css +23 -0
- package/src/styles/themed/tabs.css +20 -0
- package/src/styles/themed/toast.css +18 -0
- package/src/table-state.ts +163 -0
- package/src/tabs-state.ts +39 -0
- package/src/toast.ts +110 -0
- package/README.md +0 -3
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
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
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). 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
|
+
- 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
|
+
- 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.
|
|
37
|
+
|
|
38
|
+
## Key Props & Types
|
|
39
|
+
|
|
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'`.
|
|
41
|
+
- Layout: `<Stack gap="md">`, `<Cluster gap="sm">`, `<Grid min="md" gap="md">`, `<Sidebar side="sm" gap="lg">`, `<Split gap="md">`.
|
|
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.
|
|
45
|
+
- `Progress`: `{ label, value?, max? (100) }`, a native `<progress>`: indeterminate (a loader) without `value`.
|
|
46
|
+
- `Accordion` + `AccordionItem`: `{ title, group?, open?, children? }` (native `<details name={group}>`).
|
|
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.
|
|
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`.
|
|
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).
|
|
50
|
+
- `Menu`: `{ id?, label, items: Array<{ id, label, href?, disabled?, onSelect? }>, variant?, onSelect? }`.
|
|
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.
|
|
55
|
+
|
|
56
|
+
## Example
|
|
57
|
+
|
|
58
|
+
```tsx
|
|
59
|
+
import { Button, Card, CardBody, Field, Stack } from '@prunellejs/ui'
|
|
60
|
+
import { createPost } from '../actions/posts'
|
|
61
|
+
|
|
62
|
+
export default function NewPostForm({ error }: { error?: string }) {
|
|
63
|
+
return (
|
|
64
|
+
<Card>
|
|
65
|
+
<CardBody>
|
|
66
|
+
<form action={createPost} method="post">
|
|
67
|
+
<Stack gap="md">
|
|
68
|
+
<Field id="title" label="Title" error={error} required>
|
|
69
|
+
<input name="title" type="text" />
|
|
70
|
+
</Field>
|
|
71
|
+
<Button type="submit" tone="accent">Publish</Button>
|
|
72
|
+
</Stack>
|
|
73
|
+
</form>
|
|
74
|
+
</CardBody>
|
|
75
|
+
</Card>
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/ui",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.7.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.7.2"
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,262 @@
|
|
|
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, navigateSafeHref, nextUiId, syncDialogOpen } from './behaviors'
|
|
7
|
+
import { foldText } from './fold'
|
|
8
|
+
import * as PALETTE_LABELS from './labels/palette'
|
|
9
|
+
|
|
10
|
+
export interface CommandItem {
|
|
11
|
+
id: string
|
|
12
|
+
label: string
|
|
13
|
+
description?: string | undefined
|
|
14
|
+
group?: string | undefined
|
|
15
|
+
shortcut?: string | undefined
|
|
16
|
+
href?: string | undefined
|
|
17
|
+
disabled?: boolean | undefined
|
|
18
|
+
onSelect?: (() => void) | undefined
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type CommandSource =
|
|
22
|
+
| ((query: string) => CommandItem[] | Promise<CommandItem[]>)
|
|
23
|
+
| { search: (query: string) => CommandItem[] | Promise<CommandItem[]> }
|
|
24
|
+
|
|
25
|
+
export interface CommandPaletteProps {
|
|
26
|
+
id?: string | undefined
|
|
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
|
|
30
|
+
placeholder?: string | undefined
|
|
31
|
+
inputLabel?: string | undefined
|
|
32
|
+
ariaLabel?: string | undefined
|
|
33
|
+
triggerLabel?: string | undefined
|
|
34
|
+
emptyLabel?: string | undefined
|
|
35
|
+
noResultsLabel?: string | undefined
|
|
36
|
+
resultLabel?: string | undefined
|
|
37
|
+
resultsLabel?: string | undefined
|
|
38
|
+
shortcutKey?: string | undefined
|
|
39
|
+
open?: Signal<boolean> | undefined
|
|
40
|
+
onSelect?: ((id: string) => void) | undefined
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const isItemDisabled = (it: CommandItem) => Boolean(it.disabled)
|
|
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
|
+
|
|
105
|
+
export function CommandPalette(props: CommandPaletteProps) {
|
|
106
|
+
const baseId = props.id ?? nextUiId('kui-cmd')
|
|
107
|
+
const listId = `${baseId}-list`
|
|
108
|
+
const optionId = (idx: number) => `${baseId}-opt-${idx}`
|
|
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 ?? []
|
|
118
|
+
|
|
119
|
+
const isOpen = props.open ?? signal(false)
|
|
120
|
+
const query = signal('')
|
|
121
|
+
const sourceItems = signal<CommandItem[]>([])
|
|
122
|
+
const activeIdx = signal(findFirstEnabledIndex(staticItems, isItemDisabled))
|
|
123
|
+
let dialogEl: HTMLDialogElement | undefined
|
|
124
|
+
let inputEl: HTMLInputElement | undefined
|
|
125
|
+
|
|
126
|
+
const filtered = computed(() => {
|
|
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)
|
|
134
|
+
})
|
|
135
|
+
|
|
136
|
+
const activeOptionId = () => {
|
|
137
|
+
const list = filtered.value
|
|
138
|
+
const idx = activeIdx.value
|
|
139
|
+
return !isOpen.value || idx < 0 || idx >= list.length || list[idx]?.disabled ? undefined : optionId(idx)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const statusText = () => {
|
|
143
|
+
if (!isOpen.value)
|
|
144
|
+
return ''
|
|
145
|
+
const n = filtered.value.length
|
|
146
|
+
return n === 0 ? noResultsLabel : n === 1 ? `1 ${resultLabel}` : `${n} ${resultsLabel}`
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const onOpened = () => {
|
|
150
|
+
query.value = ''
|
|
151
|
+
activeIdx.value = findFirstEnabledIndex(staticItems, isItemDisabled)
|
|
152
|
+
refreshSource('')
|
|
153
|
+
queueMicrotask(() => inputEl?.focus())
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
bindPaletteShortcut((props.shortcutKey ?? 'k').toLowerCase(), isOpen)
|
|
157
|
+
effect(() => { syncDialogOpen(dialogEl, isOpen, isOpen.value, onOpened) })
|
|
158
|
+
|
|
159
|
+
const runItem = (item: CommandItem) => selectCommandItem(item, isOpen, props.onSelect)
|
|
160
|
+
|
|
161
|
+
return (
|
|
162
|
+
<div data-ui="command-root" data-state={isOpen.value ? 'open' : 'closed'}>
|
|
163
|
+
{triggerLabel && (
|
|
164
|
+
<button
|
|
165
|
+
data-ui="button"
|
|
166
|
+
data-variant="outline"
|
|
167
|
+
data-part="trigger"
|
|
168
|
+
type="button"
|
|
169
|
+
aria-haspopup="dialog"
|
|
170
|
+
aria-expanded={isOpen.value ? 'true' : 'false'}
|
|
171
|
+
onClick={() => { isOpen.value = true }}
|
|
172
|
+
>
|
|
173
|
+
{triggerLabel}
|
|
174
|
+
</button>
|
|
175
|
+
)}
|
|
176
|
+
<dialog
|
|
177
|
+
data-ui="command"
|
|
178
|
+
data-part="content"
|
|
179
|
+
aria-label={ariaLabel}
|
|
180
|
+
ref={(el) => {
|
|
181
|
+
dialogEl = el
|
|
182
|
+
syncDialogOpen(dialogEl, isOpen, isOpen.peek(), onOpened)
|
|
183
|
+
}}
|
|
184
|
+
onClose={() => { isOpen.value = false }}
|
|
185
|
+
onClick={(e) => {
|
|
186
|
+
if (isDialogBackdropClick(e, dialogEl))
|
|
187
|
+
isOpen.value = false
|
|
188
|
+
}}
|
|
189
|
+
>
|
|
190
|
+
<div data-part="panel">
|
|
191
|
+
<div data-part="input-wrap">
|
|
192
|
+
<input
|
|
193
|
+
ref={(el) => { inputEl = el }}
|
|
194
|
+
data-part="input"
|
|
195
|
+
type="search"
|
|
196
|
+
role="combobox"
|
|
197
|
+
aria-label={inputLabel}
|
|
198
|
+
aria-expanded={isOpen.value ? 'true' : 'false'}
|
|
199
|
+
aria-autocomplete="list"
|
|
200
|
+
aria-controls={filtered.value.length > 0 ? listId : undefined}
|
|
201
|
+
aria-activedescendant={activeOptionId()}
|
|
202
|
+
placeholder={placeholder}
|
|
203
|
+
value={query.value}
|
|
204
|
+
onInput={(e) => {
|
|
205
|
+
const val = e.currentTarget.value
|
|
206
|
+
query.value = val
|
|
207
|
+
activeIdx.value = findFirstEnabledIndex(filtered.value, isItemDisabled)
|
|
208
|
+
refreshSource(val)
|
|
209
|
+
}}
|
|
210
|
+
onKeyDown={(e) => {
|
|
211
|
+
handleListKeyDown(e, {
|
|
212
|
+
items: () => filtered.value,
|
|
213
|
+
activeIndex: activeIdx,
|
|
214
|
+
isDisabled: isItemDisabled,
|
|
215
|
+
onSelect: runItem,
|
|
216
|
+
onClose: () => { isOpen.value = false },
|
|
217
|
+
selectOnSpace: false,
|
|
218
|
+
homeEnd: false,
|
|
219
|
+
closeOnTab: false,
|
|
220
|
+
})
|
|
221
|
+
}}
|
|
222
|
+
/>
|
|
223
|
+
</div>
|
|
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
|
+
)}
|
|
255
|
+
<div class="kui-sr-only" role="status" aria-live="polite" aria-atomic="true">
|
|
256
|
+
{statusText()}
|
|
257
|
+
</div>
|
|
258
|
+
</div>
|
|
259
|
+
</dialog>
|
|
260
|
+
</div>
|
|
261
|
+
)
|
|
262
|
+
}
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
/** @jsxImportSource prunelle */
|
|
2
|
+
// Interactive DataTable island powered by headless `createDataTable()` signals (sort, filter, select, paginate).
|
|
3
|
+
|
|
4
|
+
import type { DataTableState } from './table-state'
|
|
5
|
+
import { effect, signal } from 'prunelle'
|
|
6
|
+
import * as TABLE_LABELS from './labels/table'
|
|
7
|
+
import { createDataTable } from './table-state'
|
|
8
|
+
|
|
9
|
+
export interface DataTableColumn {
|
|
10
|
+
key: string
|
|
11
|
+
label: string
|
|
12
|
+
sortable?: boolean | undefined
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface DataTableProps {
|
|
16
|
+
rows: Array<Record<string, string | number>>
|
|
17
|
+
columns: DataTableColumn[]
|
|
18
|
+
rowKey?: string | undefined
|
|
19
|
+
/** Column whose value names a row's checkbox; the first column by default. */
|
|
20
|
+
rowLabelKey?: string | undefined
|
|
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
|
|
26
|
+
searchable?: boolean | undefined
|
|
27
|
+
selectable?: boolean | undefined
|
|
28
|
+
caption?: string | undefined
|
|
29
|
+
ariaLabel?: string | undefined
|
|
30
|
+
placeholder?: string | undefined
|
|
31
|
+
searchLabel?: string | undefined
|
|
32
|
+
selectColumnLabel?: string | undefined
|
|
33
|
+
selectRowLabel?: string | undefined
|
|
34
|
+
selectAllLabel?: string | undefined
|
|
35
|
+
ascendingLabel?: string | undefined
|
|
36
|
+
descendingLabel?: string | undefined
|
|
37
|
+
rowsLabel?: string | undefined
|
|
38
|
+
selectedLabel?: string | undefined
|
|
39
|
+
pageLabel?: string | undefined
|
|
40
|
+
prevLabel?: string | undefined
|
|
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 page = table.page.peek()
|
|
67
|
+
const total = table.totalPages.peek()
|
|
68
|
+
const atEnd = by < 0 ? page <= 1 : page >= total
|
|
69
|
+
const otherEnabled = by < 0 ? page < total : page > 1
|
|
70
|
+
if (atEnd && otherEnabled && other instanceof HTMLButtonElement) {
|
|
71
|
+
// Enable before focusing: delegated onClick runs inside batch(), so reactive `disabled` updates flush after turn() returns.
|
|
72
|
+
other.disabled = false
|
|
73
|
+
other.focus()
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return (
|
|
77
|
+
<div data-part="pagination" data-layout="split">
|
|
78
|
+
<span data-part="meta" role="status">
|
|
79
|
+
{`${pageLabel} ${table.page.value} / ${table.totalPages.value}`}
|
|
80
|
+
</span>
|
|
81
|
+
<div data-layout="cluster">
|
|
82
|
+
<button
|
|
83
|
+
data-ui="button"
|
|
84
|
+
data-variant="outline"
|
|
85
|
+
data-size="sm"
|
|
86
|
+
type="button"
|
|
87
|
+
disabled={table.page.value <= 1}
|
|
88
|
+
onClick={e => turn(-1, e.currentTarget.nextElementSibling)}
|
|
89
|
+
>
|
|
90
|
+
{prevLabel}
|
|
91
|
+
</button>
|
|
92
|
+
<button
|
|
93
|
+
data-ui="button"
|
|
94
|
+
data-variant="outline"
|
|
95
|
+
data-size="sm"
|
|
96
|
+
type="button"
|
|
97
|
+
disabled={table.page.value >= table.totalPages.value}
|
|
98
|
+
onClick={e => turn(1, e.currentTarget.previousElementSibling)}
|
|
99
|
+
>
|
|
100
|
+
{nextLabel}
|
|
101
|
+
</button>
|
|
102
|
+
</div>
|
|
103
|
+
</div>
|
|
104
|
+
)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function DataTable(props: DataTableProps) {
|
|
108
|
+
const rowKey = props.rowKey ?? 'id'
|
|
109
|
+
const searchable = props.searchable ?? true
|
|
110
|
+
const selectable = props.selectable ?? false
|
|
111
|
+
const caption = props.caption
|
|
112
|
+
const ariaLabel = props.ariaLabel
|
|
113
|
+
const placeholder = props.placeholder ?? TABLE_LABELS.placeholder
|
|
114
|
+
const searchLabel = props.searchLabel ?? TABLE_LABELS.search
|
|
115
|
+
const selectColumnLabel = props.selectColumnLabel ?? TABLE_LABELS.selectColumn
|
|
116
|
+
const selectRowLabel = props.selectRowLabel ?? TABLE_LABELS.selectRow
|
|
117
|
+
const selectAllLabel = props.selectAllLabel ?? TABLE_LABELS.selectAll
|
|
118
|
+
const ascendingLabel = props.ascendingLabel ?? TABLE_LABELS.ascending
|
|
119
|
+
const descendingLabel = props.descendingLabel ?? TABLE_LABELS.descending
|
|
120
|
+
const rowsLabel = props.rowsLabel ?? TABLE_LABELS.rows
|
|
121
|
+
const selectedLabel = props.selectedLabel ?? TABLE_LABELS.selected
|
|
122
|
+
const pageLabel = props.pageLabel ?? TABLE_LABELS.page
|
|
123
|
+
const prevLabel = props.prevLabel ?? TABLE_LABELS.prev
|
|
124
|
+
const nextLabel = props.nextLabel ?? TABLE_LABELS.next
|
|
125
|
+
const emptyLabel = props.emptyLabel ?? TABLE_LABELS.empty
|
|
126
|
+
const columns = props.columns
|
|
127
|
+
const keyOf = (r: Row) => String(r[rowKey] ?? '')
|
|
128
|
+
const labelKey = props.rowLabelKey ?? columns[0]?.key ?? rowKey
|
|
129
|
+
const sortOf = (k: string) => (table.sortBy.value === k ? table.sortDir.value : undefined)
|
|
130
|
+
// What a sort just changed, for screen readers: aria-sort alone changes silently.
|
|
131
|
+
const said = signal('')
|
|
132
|
+
|
|
133
|
+
const table = createDataTable({
|
|
134
|
+
rows: () => checkedRows(props.rows, rowKey),
|
|
135
|
+
getKey: keyOf,
|
|
136
|
+
locale: props.locale,
|
|
137
|
+
onSelect: props.onSelect,
|
|
138
|
+
pageSize: props.pageSize ?? 10,
|
|
139
|
+
searchText: r => columns.map(c => String(r[c.key] ?? '')).join(' '),
|
|
140
|
+
})
|
|
141
|
+
// The header checkbox covers the rows the filter shows.
|
|
142
|
+
const shownKeys = () => table.filtered.value.map(keyOf)
|
|
143
|
+
const allShownSelected = () => shownKeys().length > 0 && shownKeys().every(k => table.selected.value.has(k))
|
|
144
|
+
const someShownSelected = () => shownKeys().some(k => table.selected.value.has(k))
|
|
145
|
+
|
|
146
|
+
return (
|
|
147
|
+
<div data-ui="datatable">
|
|
148
|
+
{searchable && (
|
|
149
|
+
<div data-part="toolbar" data-layout="split">
|
|
150
|
+
<input
|
|
151
|
+
data-part="search"
|
|
152
|
+
type="search"
|
|
153
|
+
aria-label={searchLabel}
|
|
154
|
+
placeholder={placeholder}
|
|
155
|
+
value={table.query.value}
|
|
156
|
+
onInput={(e) => {
|
|
157
|
+
table.query.value = e.currentTarget.value
|
|
158
|
+
table.page.value = 1
|
|
159
|
+
}}
|
|
160
|
+
/>
|
|
161
|
+
<span data-part="meta" role="status" aria-live="polite">
|
|
162
|
+
{`${table.filtered.value.length} ${rowsLabel}${selectable && table.selected.value.size > 0 ? ` · ${table.selected.value.size} ${selectedLabel}` : ''}`}
|
|
163
|
+
</span>
|
|
164
|
+
</div>
|
|
165
|
+
)}
|
|
166
|
+
|
|
167
|
+
<div data-part="scroll">
|
|
168
|
+
<table data-ui="table" aria-label={caption ? undefined : ariaLabel}>
|
|
169
|
+
{caption && <caption data-part="caption">{caption}</caption>}
|
|
170
|
+
<thead>
|
|
171
|
+
<tr>
|
|
172
|
+
{selectable && (
|
|
173
|
+
<th scope="col" data-part="select-col">
|
|
174
|
+
<span class="kui-sr-only">{selectColumnLabel}</span>
|
|
175
|
+
<input
|
|
176
|
+
type="checkbox"
|
|
177
|
+
aria-label={selectAllLabel}
|
|
178
|
+
checked={allShownSelected()}
|
|
179
|
+
ref={(el: HTMLInputElement) => effect(() => { el.indeterminate = someShownSelected() && !allShownSelected() })}
|
|
180
|
+
onChange={() => table.setSelected(shownKeys(), !allShownSelected())}
|
|
181
|
+
/>
|
|
182
|
+
</th>
|
|
183
|
+
)}
|
|
184
|
+
{columns.map(col => (
|
|
185
|
+
<th
|
|
186
|
+
key={col.key}
|
|
187
|
+
scope="col"
|
|
188
|
+
aria-sort={col.sortable === false ? undefined : sortOf(col.key) === 'asc' ? 'ascending' : sortOf(col.key) === 'desc' ? 'descending' : 'none'}
|
|
189
|
+
>
|
|
190
|
+
{col.sortable !== false
|
|
191
|
+
? (
|
|
192
|
+
<button
|
|
193
|
+
type="button"
|
|
194
|
+
data-part="sort"
|
|
195
|
+
data-active={sortOf(col.key) ? 'true' : undefined}
|
|
196
|
+
onClick={() => {
|
|
197
|
+
table.toggleSort(col.key)
|
|
198
|
+
said.value = `${col.label}, ${table.sortDir.peek() === 'asc' ? ascendingLabel : descendingLabel}`
|
|
199
|
+
}}
|
|
200
|
+
>
|
|
201
|
+
{col.label}
|
|
202
|
+
<span aria-hidden="true">{sortOf(col.key) === 'asc' ? ' ↑' : sortOf(col.key) === 'desc' ? ' ↓' : ''}</span>
|
|
203
|
+
</button>
|
|
204
|
+
)
|
|
205
|
+
: col.label}
|
|
206
|
+
</th>
|
|
207
|
+
))}
|
|
208
|
+
</tr>
|
|
209
|
+
</thead>
|
|
210
|
+
<tbody>
|
|
211
|
+
{table.visible.value.length === 0
|
|
212
|
+
? (
|
|
213
|
+
<tr data-part="empty">
|
|
214
|
+
<td colspan={Math.max(1, columns.length + (selectable ? 1 : 0))}>
|
|
215
|
+
{emptyLabel}
|
|
216
|
+
</td>
|
|
217
|
+
</tr>
|
|
218
|
+
)
|
|
219
|
+
: table.visible.value.map(row => (
|
|
220
|
+
<tr key={keyOf(row)} data-selected={table.isSelected(keyOf(row)) ? 'true' : undefined}>
|
|
221
|
+
{selectable && (
|
|
222
|
+
<td data-part="select-col">
|
|
223
|
+
<input
|
|
224
|
+
type="checkbox"
|
|
225
|
+
checked={table.isSelected(keyOf(row))}
|
|
226
|
+
aria-label={`${selectRowLabel} ${String(row[labelKey] ?? keyOf(row))}`}
|
|
227
|
+
onChange={() => table.toggleSelect(keyOf(row))}
|
|
228
|
+
/>
|
|
229
|
+
</td>
|
|
230
|
+
)}
|
|
231
|
+
{columns.map(col => (
|
|
232
|
+
<td key={col.key}>{String(row[col.key] ?? '')}</td>
|
|
233
|
+
))}
|
|
234
|
+
</tr>
|
|
235
|
+
))}
|
|
236
|
+
</tbody>
|
|
237
|
+
</table>
|
|
238
|
+
</div>
|
|
239
|
+
|
|
240
|
+
{table.totalPages.value > 1 && <Pager table={table} pageLabel={pageLabel} prevLabel={prevLabel} nextLabel={nextLabel} />}
|
|
241
|
+
<span data-part="announce" class="kui-sr-only" role="status">{said.value}</span>
|
|
242
|
+
</div>
|
|
243
|
+
)
|
|
244
|
+
}
|