@prunellejs/ui 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,72 @@
1
+ // @prunellejs/ui — Platform-first headless primitives + pure CSS Style Grammars.
2
+ // Zero JS recipes, zero Tailwind lock-in, zero custom compiler syntax.
3
+
4
+ export {
5
+ createDataTable,
6
+ createDialog,
7
+ createTabs,
8
+ findFirstEnabledIndex,
9
+ findLastEnabledIndex,
10
+ findNextEnabledIndex,
11
+ handleListKeyDown,
12
+ isDialogBackdropClick,
13
+ nextUiId,
14
+ syncDialogOpen,
15
+ } from './behaviors'
16
+ export type { DataTableOptions, DataTableState, DialogBehavior, ListNavigationOptions, TabsBehavior } from './behaviors'
17
+ export { toast } from './toast'
18
+ export type { ToastItem } from './toast'
19
+ export { CommandPalette } from './CommandPalette'
20
+ export type { CommandItem, CommandPaletteProps } from './CommandPalette'
21
+ export { DataTable } from './DataTable'
22
+ export type { DataTableColumn, DataTableProps } from './DataTable'
23
+ export { ControlledDialog, Dialog } from './Dialog'
24
+ export type { ControlledDialogProps, DialogProps } from './Dialog'
25
+ export { ControlledDrawer, Drawer } from './Drawer'
26
+ export type { ControlledDrawerProps, DrawerProps } from './Drawer'
27
+ export { Menu } from './Menu'
28
+ export type { MenuItemDef, MenuProps } from './Menu'
29
+ export {
30
+ Accordion,
31
+ AccordionItem,
32
+ Badge,
33
+ Card,
34
+ CardBody,
35
+ CardFooter,
36
+ CardHeader,
37
+ Checkbox,
38
+ Grid,
39
+ Popover,
40
+ Progress,
41
+ RadioGroup,
42
+ Sidebar,
43
+ Split,
44
+ Switch,
45
+ } from './primitives'
46
+ export type { CheckControlProps, PopoverProps, ProgressProps, RadioGroupProps, RadioOption } from './primitives'
47
+ export { Select } from './Select'
48
+ export type { SelectOption, SelectProps } from './Select'
49
+ export {
50
+ Button,
51
+ Cluster,
52
+ Field,
53
+ Notice,
54
+ Stack,
55
+ } from './static'
56
+ export type {
57
+ ButtonProps,
58
+ ButtonVariant,
59
+ FieldControlWiring,
60
+ FieldProps,
61
+ Size,
62
+ SpaceToken,
63
+ SpaceValue,
64
+ Tone,
65
+ TrackSize,
66
+ TrackValue,
67
+ } from './static'
68
+ export { FieldContext, useFieldContext } from './static'
69
+ export { Tabs } from './Tabs'
70
+ export type { TabDef, TabsProps } from './Tabs'
71
+ export { Toaster } from './Toaster'
72
+ export type { ToasterProps } from './Toaster'
@@ -0,0 +1,36 @@
1
+ // What a browser lacking invoker commands (Safari before 26.2), `closedby` (Safari before 27.3) or anchor positioning (Safari before 26, Firefox before 147) needs for the static Dialog and Drawer, `commandfor` buttons and the Menu, Select and Popover popups: only that browser loads it.
2
+
3
+ // Below the trigger, or above it and right-aligned where the viewport has no room, as `position-try-fallbacks` would; again on scroll, as an anchor would follow.
4
+ const PLACE_POPUP = 'const S=["[data-ui=menu] [role=menu]","[data-ui=select] [role=listbox]","[data-ui=popover][popover]"],'
5
+ + 'P=t=>{const b=t.closest("[data-ui=menu],[data-ui=select]")?.querySelector("[data-part=trigger]")??document.querySelector(`[popovertarget="${t.id}"]`);if(!b)return;'
6
+ + 'const r=b.getBoundingClientRect(),h=t.offsetHeight,w=t.offsetWidth,y=r.bottom+4+h>innerHeight&&r.top-4-h>=0?r.top-4-h:r.bottom+4,x=r.left+w>innerWidth?Math.max(0,r.right-w):r.left;'
7
+ + 'Object.assign(t.style,{positionArea:"none",positionTryFallbacks:"none",margin:"0",inset:`${y}px auto auto ${x}px`,minWidth:t.matches("[data-ui=popover]")?"":`${r.width}px`})};'
8
+ + 'A&&(document.addEventListener("toggle",e=>e.newState==="open"&&e.target.matches(S.join())&&P(e.target),true),'
9
+ + 'addEventListener("scroll",()=>document.querySelectorAll(S.map(s=>`${s}:popover-open`).join()).forEach(P),{capture:true,passive:true}));'
10
+
11
+ /** Opens and closes what a `commandfor` button names, closes a `closedby="any"` dialog on a click pressed and released on its backdrop, and places the popups against their trigger. */
12
+ export const FALLBACK_JS = 'const C=!("command"in HTMLButtonElement.prototype),B=!("closedBy"in HTMLDialogElement.prototype),A=!CSS.supports("position-area:block-end");let D;'
13
+ + PLACE_POPUP
14
+ + 'document.addEventListener("pointerdown",e=>D=e.target,true);'
15
+ + 'document.addEventListener("click",e=>{const t=e.target;'
16
+ + 'if(C){const b=t.closest&&t.closest("button[commandfor]"),d=b&&document.getElementById(b.getAttribute("commandfor"));'
17
+ + 'if(d){const c=b.getAttribute("command");c==="show-modal"?d.open||d.showModal():c==="close"||c==="request-close"?d.close():c==="toggle-popover"?d.togglePopover():c==="show-popover"?d.showPopover():c==="hide-popover"&&d.hidePopover();return}}'
18
+ + 'if(B&&t===D&&t instanceof HTMLDialogElement&&t.open&&t.getAttribute("closedby")==="any"){const r=t.getBoundingClientRect();'
19
+ + '(e.clientX<r.left||e.clientX>r.right||e.clientY<r.top||e.clientY>r.bottom)&&t.close()}})'
20
+
21
+ /** The fallback's file under the asset prefix, named by its content so a browser keeps it for good. */
22
+ export const FALLBACK_FILE = `kui-fallback-${new Bun.CryptoHasher('sha256').update(FALLBACK_JS).digest('hex').slice(0, 8)}.js`
23
+
24
+ /** Inline on a page with a `commandfor` button or a popup: imports the fallback only where a feature is missing, so other browsers fetch nothing. */
25
+ export const FALLBACK_GUARD = 'if(!("command"in HTMLButtonElement.prototype&&"closedBy"in HTMLDialogElement.prototype&&CSS.supports("position-area:block-end")))import(document.querySelector("script[data-kui-fallback]").dataset.kuiFallback)'
26
+
27
+ const NEEDS_FALLBACK_RE = /<button\b[^>]*\scommandfor=|\sdata-ui="(?:menu|select|popover)"/
28
+
29
+ /** `html` with the guard before `</head>` when a button in it carries `commandfor` or it holds a Menu, Select or Popover, pointing at the fallback under `assetPrefix`. */
30
+ export function withPlatformFallback(html: string, assetPrefix: string): string {
31
+ if (!NEEDS_FALLBACK_RE.test(html) || html.includes('data-kui-fallback'))
32
+ return html
33
+ const tag = `<script type="module" data-kui-fallback="${assetPrefix.replace(/\/$/, '')}/${FALLBACK_FILE}">${FALLBACK_GUARD}</script>`
34
+ const head = html.indexOf('</head>')
35
+ return head === -1 ? `${tag}${html}` : `${html.slice(0, head)}${tag}${html.slice(head)}`
36
+ }
package/src/plugin.ts ADDED
@@ -0,0 +1,105 @@
1
+ // @prunellejs/ui PrunellePlugin — wires a pure CSS Grammar (`editorial | workshop | console | soft | orbit | prunelle | bare`)
2
+ // and adds `prunelle ui-eject <grammar> [dest]` so apps can copy & own the entire look in ONE ~200-line CSS file.
3
+
4
+ import type { PrunellePlugin } from 'prunelle/config'
5
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
6
+ import { dirname, join, resolve } from 'node:path'
7
+ import { definePlugin, serviceKey } from 'prunelle/config'
8
+ import { FALLBACK_FILE, FALLBACK_GUARD, FALLBACK_JS, withPlatformFallback } from './platform-fallback'
9
+
10
+ const UI_KUI_LAYER_SERVICE = serviceKey<boolean>('prunelle.ui.kuiLayer')
11
+
12
+ export type GrammarName = 'bare' | 'editorial' | 'workshop' | 'console' | 'soft' | 'orbit' | 'prunelle'
13
+
14
+ export const GRAMMAR_NAMES: readonly GrammarName[] = ['bare', 'editorial', 'workshop', 'console', 'soft', 'orbit', 'prunelle']
15
+
16
+ const STYLES_DIR = join(import.meta.dir, 'styles')
17
+ const BARE_IMPORT_RE = /^@import\s+['"]\.\.\/bare\.css['"];?\s*/gm
18
+
19
+ export function grammarCssPath(grammar: GrammarName): string {
20
+ return grammar === 'bare'
21
+ ? join(STYLES_DIR, 'bare.css')
22
+ : join(STYLES_DIR, 'grammars', `${grammar}.css`)
23
+ }
24
+
25
+ /** Returns the self-contained CSS source for a grammar (with `bare.css` inlined). */
26
+ export function renderGrammarCss(grammar: GrammarName, bareCss?: string): string {
27
+ const bare = bareCss ?? readFileSync(join(STYLES_DIR, 'bare.css'), 'utf8')
28
+ if (grammar === 'bare')
29
+ return bare
30
+ const rawGrammar = readFileSync(grammarCssPath(grammar), 'utf8')
31
+ const withoutImport = rawGrammar.replace(BARE_IMPORT_RE, '')
32
+ return `${bare}\n${withoutImport}`
33
+ }
34
+
35
+ /** Ejects a complete, self-contained CSS Grammar file (with bare.css inlined) into the app! */
36
+ export function ejectGrammar(root: string, grammar: GrammarName = 'editorial', destRel = 'src/styles/ui.css'): string {
37
+ const outPath = resolve(root, destRel)
38
+ mkdirSync(dirname(outPath), { recursive: true })
39
+ writeFileSync(outPath, renderGrammarCss(grammar))
40
+ return outPath
41
+ }
42
+
43
+ export interface EmitGrammarsOptions {
44
+ /** Public directory relative to `dist/public` (default: `'grammars'`). */
45
+ dir?: string | undefined
46
+ /** Subset of grammars to emit (default: all grammars). */
47
+ grammars?: readonly GrammarName[] | undefined
48
+ }
49
+
50
+ export interface UiPluginOptions {
51
+ /** Which pure CSS Grammar to include (default: 'editorial'). Pass `false` if importing your own CSS. */
52
+ grammar?: GrammarName | false | undefined
53
+ /** Emit standalone self-contained grammar CSS files into `public/grammars/<name>.css` for runtime switching. */
54
+ emitGrammars?: boolean | readonly GrammarName[] | EmitGrammarsOptions | undefined
55
+ }
56
+
57
+ function resolveEmitGrammars(opt: UiPluginOptions['emitGrammars']): { dir: string, grammars: readonly GrammarName[] } | undefined {
58
+ if (!opt)
59
+ return undefined
60
+ if (opt === true)
61
+ return { dir: 'grammars', grammars: GRAMMAR_NAMES }
62
+ if (Array.isArray(opt))
63
+ return { dir: 'grammars', grammars: opt }
64
+ const opts = opt as EmitGrammarsOptions
65
+ const dir = (opts.dir ?? 'grammars').replace(/^\/+|\/+$/g, '')
66
+ return { dir, grammars: opts.grammars ?? GRAMMAR_NAMES }
67
+ }
68
+
69
+ export function ui(options: UiPluginOptions = {}): PrunellePlugin {
70
+ const grammar = options.grammar === undefined ? 'editorial' : options.grammar
71
+ const emit = resolveEmitGrammars(options.emitGrammars)
72
+ let assetPrefix = '/_pru'
73
+ return definePlugin({
74
+ name: '@prunellejs/ui',
75
+ css: grammar === false ? undefined : [grammarCssPath(grammar)],
76
+ inlineScripts: [FALLBACK_GUARD],
77
+ build(ctx) {
78
+ ctx.emitAsset(FALLBACK_FILE, FALLBACK_JS)
79
+ if (grammar !== false)
80
+ ctx.provide?.(UI_KUI_LAYER_SERVICE, true)
81
+ if (emit !== undefined) {
82
+ const bare = readFileSync(join(STYLES_DIR, 'bare.css'), 'utf8')
83
+ const prefix = emit.dir ? `${emit.dir}/` : ''
84
+ for (const g of emit.grammars)
85
+ ctx.emitPublic(`${prefix}${g}.css`, renderGrammarCss(g, bare))
86
+ }
87
+ },
88
+ server(api) {
89
+ assetPrefix = api.assetPrefix
90
+ },
91
+ transformHtml: html => withPlatformFallback(html, assetPrefix),
92
+ commands: {
93
+ 'ui-eject': (args, root) => {
94
+ const name = (args[0] ?? 'editorial') as GrammarName
95
+ if (!GRAMMAR_NAMES.includes(name)) {
96
+ console.error(`Unknown grammar "${name}". Choose one of: ${GRAMMAR_NAMES.join(', ')}`)
97
+ process.exit(1)
98
+ }
99
+ const dest = args[1] ?? 'src/styles/ui.css'
100
+ const outPath = ejectGrammar(root, name, dest)
101
+ console.log(`Ejected @prunellejs/ui "${name}" grammar to ${outPath}`)
102
+ },
103
+ },
104
+ })
105
+ }
@@ -0,0 +1,237 @@
1
+ /** @jsxImportSource prunelle */
2
+ // Zero-JS static & native-platform primitives (`0 KB` client JS!) split from static.tsx so islands using only Field/Button/Notice don't bundle unused templates.
3
+
4
+ import type { PrunelleChild } from 'prunelle'
5
+ import type { ButtonVariant, SpaceValue, Tone, TrackValue } from './static'
6
+
7
+ const SPACE_TOKENS = new Set<string>(['none', '2xs', 'xs', 'sm', 'md', 'lg', 'xl', '2xl'])
8
+ const TRACK_TOKENS = new Set<string>(['xs', 'sm', 'md', 'lg', 'xl'])
9
+ const isSpaceToken = (v: string | undefined): boolean => v !== undefined && SPACE_TOKENS.has(v)
10
+ const isTrackToken = (v: string | undefined): boolean => v !== undefined && TRACK_TOKENS.has(v)
11
+
12
+ export function Badge(props: BoxProps & { tone?: Tone | undefined }) {
13
+ const rest = restProps(props, ['tone', 'class'])
14
+ return <span data-ui="badge" data-tone={props.tone} class={props.class} {...rest}>{props.children}</span>
15
+ }
16
+
17
+ export function Grid(props: BoxProps & { min?: TrackValue | undefined, gap?: SpaceValue | undefined }) {
18
+ const rest = restProps(props, ['min', 'gap', 'class'])
19
+ return (
20
+ <div
21
+ data-layout="grid"
22
+ data-min={isTrackToken(props.min) ? props.min : undefined}
23
+ data-min-value={props.min && !isTrackToken(props.min) ? props.min : undefined}
24
+ data-gap={isSpaceToken(props.gap) ? props.gap : undefined}
25
+ data-gap-value={props.gap && !isSpaceToken(props.gap) ? props.gap : undefined}
26
+ class={props.class}
27
+ {...rest}
28
+ >
29
+ {props.children}
30
+ </div>
31
+ )
32
+ }
33
+
34
+ export function Sidebar(props: BoxProps & { side?: TrackValue | undefined, gap?: SpaceValue | undefined }) {
35
+ const rest = restProps(props, ['side', 'gap', 'class'])
36
+ return (
37
+ <div
38
+ data-layout="sidebar"
39
+ data-side={isTrackToken(props.side) ? props.side : undefined}
40
+ data-side-value={props.side && !isTrackToken(props.side) ? props.side : undefined}
41
+ data-gap={isSpaceToken(props.gap) ? props.gap : undefined}
42
+ data-gap-value={props.gap && !isSpaceToken(props.gap) ? props.gap : undefined}
43
+ class={props.class}
44
+ {...rest}
45
+ >
46
+ {props.children}
47
+ </div>
48
+ )
49
+ }
50
+
51
+ export function Split(props: BoxProps & { gap?: SpaceValue | undefined }) {
52
+ const rest = restProps(props, ['gap', 'class'])
53
+ return (
54
+ <div
55
+ data-layout="split"
56
+ data-gap={isSpaceToken(props.gap) ? props.gap : undefined}
57
+ data-gap-value={props.gap && !isSpaceToken(props.gap) ? props.gap : undefined}
58
+ class={props.class}
59
+ {...rest}
60
+ >
61
+ {props.children}
62
+ </div>
63
+ )
64
+ }
65
+
66
+ interface BoxProps {
67
+ class?: string | undefined
68
+ children?: PrunelleChild | undefined
69
+ [attr: string]: unknown
70
+ }
71
+
72
+ function restProps(props: Record<string, unknown>, skip: readonly string[]): Record<string, unknown> {
73
+ const out: Record<string, unknown> = {}
74
+ for (const k of Object.keys(props)) {
75
+ if (k !== 'children' && !skip.includes(k))
76
+ out[k] = props[k]
77
+ }
78
+ return out
79
+ }
80
+
81
+ export function Card(props: BoxProps) {
82
+ const rest = restProps(props, ['class'])
83
+ return <section data-ui="card" class={props.class} {...rest}>{props.children}</section>
84
+ }
85
+
86
+ export function CardHeader(props: BoxProps) {
87
+ const rest = restProps(props, ['class'])
88
+ return <header data-part="header" class={props.class} {...rest}>{props.children}</header>
89
+ }
90
+
91
+ export function CardBody(props: BoxProps) {
92
+ const rest = restProps(props, ['class'])
93
+ return <div data-part="body" class={props.class} {...rest}>{props.children}</div>
94
+ }
95
+
96
+ export function CardFooter(props: BoxProps) {
97
+ const rest = restProps(props, ['class'])
98
+ return <footer data-part="footer" class={props.class} {...rest}>{props.children}</footer>
99
+ }
100
+
101
+ /** Zero-JS native `<details>` accordion (`name` enables exclusive mode natively in the browser). */
102
+ export function Accordion(props: BoxProps) {
103
+ const rest = restProps(props, ['class'])
104
+ return <div data-ui="accordion" class={props.class} {...rest}>{props.children}</div>
105
+ }
106
+
107
+ export function AccordionItem(props: { title: string, group?: string | undefined, open?: boolean | undefined, children?: PrunelleChild | undefined, [attr: string]: unknown }) {
108
+ const rest = restProps(props, ['title', 'group', 'open'])
109
+ return (
110
+ <details name={props.group} open={props.open} {...rest}>
111
+ <summary data-part="trigger">{props.title}</summary>
112
+ <div data-part="content">{props.children}</div>
113
+ </details>
114
+ )
115
+ }
116
+
117
+ /** Zero-JS native Popover API trigger + anchored popover panel (`0 KB` client JS!). */
118
+ export interface PopoverProps {
119
+ id: string
120
+ triggerLabel: string
121
+ triggerVariant?: ButtonVariant | undefined
122
+ children?: PrunelleChild | undefined
123
+ }
124
+
125
+ export function Popover({ id, triggerLabel, triggerVariant = 'outline', children }: PopoverProps) {
126
+ return (
127
+ <>
128
+ <button
129
+ data-ui="button"
130
+ data-variant={triggerVariant}
131
+ type="button"
132
+ popovertarget={id}
133
+ >
134
+ {triggerLabel}
135
+ </button>
136
+ <div
137
+ id={id}
138
+ data-ui="popover"
139
+ popover="auto"
140
+ >
141
+ {children}
142
+ </div>
143
+ </>
144
+ )
145
+ }
146
+
147
+ // ---- Zero-JS native form controls (`0 KB` client JS!) ----
148
+
149
+ export interface CheckControlProps {
150
+ id?: string | undefined
151
+ name?: string | undefined
152
+ value?: string | undefined
153
+ label: string
154
+ checked?: boolean | undefined
155
+ disabled?: boolean | undefined
156
+ class?: string | undefined
157
+ [attr: string]: unknown
158
+ }
159
+
160
+ export function Checkbox({ id, name, value, label, checked, disabled, class: cls, ...rest }: CheckControlProps) {
161
+ return (
162
+ <label data-ui="checkbox" data-disabled={disabled ? 'true' : undefined} class={cls}>
163
+ <input id={id} type="checkbox" name={name} value={value} checked={checked} disabled={disabled} {...rest} />
164
+ <span data-part="label">{label}</span>
165
+ </label>
166
+ )
167
+ }
168
+
169
+ export function Switch({ id, name, value, label, checked, disabled, class: cls, ...rest }: CheckControlProps) {
170
+ return (
171
+ <label data-ui="switch" data-disabled={disabled ? 'true' : undefined} class={cls}>
172
+ <input id={id} type="checkbox" role="switch" name={name} value={value} checked={checked} disabled={disabled} {...rest} />
173
+ <span data-part="track" aria-hidden="true" />
174
+ <span data-part="label">{label}</span>
175
+ </label>
176
+ )
177
+ }
178
+
179
+ export interface RadioOption {
180
+ value: string
181
+ label: string
182
+ hint?: string | undefined
183
+ disabled?: boolean | undefined
184
+ }
185
+
186
+ export interface RadioGroupProps {
187
+ name: string
188
+ legend?: string | undefined
189
+ options: RadioOption[]
190
+ defaultValue?: string | undefined
191
+ class?: string | undefined
192
+ }
193
+
194
+ export function RadioGroup({ name, legend, options, defaultValue, class: cls }: RadioGroupProps) {
195
+ return (
196
+ <fieldset data-ui="radio-group" class={cls}>
197
+ {legend && <legend data-part="legend">{legend}</legend>}
198
+ <div data-part="options">
199
+ {options.map(opt => (
200
+ <label key={opt.value} data-part="option" data-disabled={opt.disabled ? 'true' : undefined}>
201
+ <input
202
+ type="radio"
203
+ name={name}
204
+ value={opt.value}
205
+ checked={defaultValue === opt.value ? true : undefined}
206
+ disabled={opt.disabled}
207
+ />
208
+ <span data-part="label">{opt.label}</span>
209
+ {opt.hint && <span data-part="hint">{opt.hint}</span>}
210
+ </label>
211
+ ))}
212
+ </div>
213
+ </fieldset>
214
+ )
215
+ }
216
+
217
+ export interface ProgressProps {
218
+ label: string
219
+ /** Without one the bar is indeterminate: a loader. */
220
+ value?: number | undefined
221
+ max?: number | undefined
222
+ class?: string | undefined
223
+ [attr: string]: unknown
224
+ }
225
+
226
+ // The share done, rounded to the 5% step a grammar styles: a style attribute would break a CSP without 'unsafe-inline'.
227
+ const progressStep = (value: number, max: number): string => String(Math.round(Math.min(Math.max(value / max, 0), 1) * 20) * 5)
228
+
229
+ export function Progress({ label, value, max = 100, class: cls, ...rest }: ProgressProps) {
230
+ return (
231
+ <span data-ui="progress" data-value={value === undefined ? undefined : progressStep(value, max)} class={cls} {...rest}>
232
+ <span data-part="eye" aria-hidden="true" />
233
+ <progress value={value} max={value === undefined ? undefined : max} aria-label={label} />
234
+ <span data-part="label" aria-hidden="true">{label}</span>
235
+ </span>
236
+ )
237
+ }