@prunellejs/ui 0.0.0-stage → 0.6.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 (70) hide show
  1. package/llms.txt +76 -0
  2. package/package.json +32 -4
  3. package/src/CommandPalette.tsx +260 -0
  4. package/src/DataTable.tsx +175 -0
  5. package/src/Dialog.tsx +181 -0
  6. package/src/Drawer.tsx +4 -0
  7. package/src/Menu.tsx +117 -0
  8. package/src/Select.tsx +124 -0
  9. package/src/Tabs.tsx +63 -0
  10. package/src/Toaster.tsx +141 -0
  11. package/src/behaviors.ts +389 -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
@@ -0,0 +1,389 @@
1
+ // Headless signal behavior hooks (zero CSS, zero DOM lock-in — standard TSX `{...spread}`).
2
+ // DataTable and Tabs state live in ./table-state.ts and ./tabs-state.ts so lightweight pages don't download them.
3
+
4
+ import type { Signal } from 'prunelle'
5
+ import { effect, onCleanup, signal, useId } from 'prunelle'
6
+ import { useFieldContext } from './field-context'
7
+
8
+ export { createDataTable } from './table-state'
9
+ export type { DataTableOptions, DataTableState } from './table-state'
10
+ export { createTabs } from './tabs-state'
11
+ export type { TabsBehavior } from './tabs-state'
12
+ export { toast } from './toast'
13
+ export type { ToastItem } from './toast'
14
+ export { useFieldContext }
15
+
16
+ // ---- Safe href validation & SPA-friendly navigation ----
17
+
18
+ const UNSAFE_HREF_RE = /^(?:javascript|vbscript|data):/i
19
+
20
+ /** Returns a safe navigable URL (rejecting `javascript:`, `vbscript:`, and `data:` schemes even with control-char obfuscation), or `undefined`. */
21
+ export function safeHref(href: string | undefined): string | undefined {
22
+ if (href === undefined)
23
+ return undefined
24
+ const trimmed = href.trim()
25
+ if (trimmed.length === 0)
26
+ return undefined
27
+ let cleaned = ''
28
+ for (let i = 0; i < trimmed.length; i++) {
29
+ const code = trimmed.charCodeAt(i)
30
+ if (code > 0x20 && code !== 0x7F)
31
+ cleaned += trimmed[i]
32
+ }
33
+ return UNSAFE_HREF_RE.test(cleaned) ? undefined : trimmed
34
+ }
35
+
36
+ /** Navigates to a safe href via a synthetic anchor click so `@prunellejs/spa` can intercept same-origin links, falling back to `location.assign`. */
37
+ export function navigateSafeHref(href: string | undefined): boolean {
38
+ const safe = safeHref(href)
39
+ if (safe === undefined)
40
+ return false
41
+ if (typeof document !== 'undefined' && document.body !== null) {
42
+ const a = document.createElement('a')
43
+ a.href = safe
44
+ a.hidden = true
45
+ document.body.appendChild(a)
46
+ let prevented = false
47
+ try {
48
+ const ev = new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 })
49
+ a.dispatchEvent(ev)
50
+ prevented = ev.defaultPrevented
51
+ }
52
+ finally {
53
+ a.remove()
54
+ }
55
+ if (prevented)
56
+ return true
57
+ }
58
+ if (typeof location !== 'undefined')
59
+ location.assign(safe)
60
+ return true
61
+ }
62
+
63
+ // ---- Stable hydration-safe unique IDs for ARIA wiring ----
64
+
65
+ export function nextUiId(prefix: string): string {
66
+ return useId(prefix)
67
+ }
68
+
69
+ // ---- Shared listbox / menu keyboard navigation ----
70
+
71
+ export function findFirstEnabledIndex<T>(items: readonly T[], isDisabled?: (item: T) => boolean): number {
72
+ return findNextEnabledIndex(items, -1, 1, isDisabled)
73
+ }
74
+
75
+ export function findLastEnabledIndex<T>(items: readonly T[], isDisabled?: (item: T) => boolean): number {
76
+ return findNextEnabledIndex(items, items.length, -1, isDisabled)
77
+ }
78
+
79
+ export function findNextEnabledIndex<T>(
80
+ items: readonly T[],
81
+ current: number,
82
+ delta: 1 | -1,
83
+ isDisabled?: (item: T) => boolean,
84
+ ): number {
85
+ const len = items.length
86
+ if (len === 0)
87
+ return -1
88
+ let idx = current < 0 || current >= len ? (delta === 1 ? -1 : len) : current
89
+ for (let step = 0; step < len; step++) {
90
+ idx = (idx + delta + len) % len
91
+ if (!isDisabled?.(items[idx]!))
92
+ return idx
93
+ }
94
+ return -1
95
+ }
96
+
97
+ export interface ListNavigationOptions<T> {
98
+ items: () => readonly T[]
99
+ activeIndex: Signal<number>
100
+ isDisabled?: ((item: T) => boolean) | undefined
101
+ onSelect: (item: T, index: number) => void
102
+ onClose: (returnFocus?: boolean) => void
103
+ selectOnSpace?: boolean | undefined
104
+ homeEnd?: boolean | undefined
105
+ closeOnTab?: boolean | undefined
106
+ }
107
+
108
+ /** Shared keyboard handler for ARIA menu / listbox / combobox popups (ArrowUp/Down, Home/End, Enter/Space, Escape, Tab). */
109
+ export function handleListKeyDown<T>(e: KeyboardEvent, opts: ListNavigationOptions<T>): boolean {
110
+ const list = opts.items()
111
+ if (e.key === 'Escape') {
112
+ opts.onClose(true)
113
+ return true
114
+ }
115
+ if (e.key === 'Tab') {
116
+ if (opts.closeOnTab === false)
117
+ return false
118
+ opts.onClose(false)
119
+ return true
120
+ }
121
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
122
+ e.preventDefault()
123
+ opts.activeIndex.value = findNextEnabledIndex(list, opts.activeIndex.value, e.key === 'ArrowDown' ? 1 : -1, opts.isDisabled)
124
+ return true
125
+ }
126
+ if (opts.homeEnd !== false && (e.key === 'Home' || e.key === 'End')) {
127
+ e.preventDefault()
128
+ opts.activeIndex.value = (e.key === 'Home' ? findFirstEnabledIndex : findLastEnabledIndex)(list, opts.isDisabled)
129
+ return true
130
+ }
131
+ if (e.key === 'Enter' || (opts.selectOnSpace !== false && e.key === ' ')) {
132
+ const idx = opts.activeIndex.value
133
+ const active = idx >= 0 && idx < list.length ? list[idx] : undefined
134
+ if (active !== undefined && !opts.isDisabled?.(active)) {
135
+ e.preventDefault()
136
+ opts.onSelect(active, idx)
137
+ return true
138
+ }
139
+ }
140
+ return false
141
+ }
142
+
143
+ export interface ListPopupOptions<T> {
144
+ items: () => readonly T[]
145
+ itemId: (idx: number) => string
146
+ isDisabled: (item: T) => boolean
147
+ onSelect: (item: T, idx: number) => void
148
+ initialIndex?: () => number
149
+ focusActive?: boolean | undefined
150
+ }
151
+
152
+ export interface ListPopupState {
153
+ readonly open: Signal<boolean>
154
+ readonly highlighted: Signal<number>
155
+ setRoot(el: HTMLElement | undefined): void
156
+ close(returnFocus?: boolean): void
157
+ toggle(e: MouseEvent): void
158
+ onTriggerKeyDown(e: KeyboardEvent): void
159
+ focusActive(): void
160
+ activeDescendantId(): string | undefined
161
+ /** The popup's `ref`: shows it in the top layer, anchored to the trigger. */
162
+ mountPopup(el: HTMLElement | undefined): void
163
+ }
164
+
165
+ // In the top layer no overflow ancestor clips the popup, and the trigger as its `source` is the anchor CSS places it against and a click the browser does not count as outside.
166
+ function showAnchored(el: HTMLElement, trigger: HTMLElement): void {
167
+ if (el.isConnected && !el.matches(':popover-open')) {
168
+ try {
169
+ el.showPopover({ source: trigger })
170
+ }
171
+ catch {
172
+ el.showPopover()
173
+ }
174
+ }
175
+ }
176
+
177
+ /** Shared popup open/close and keyboard list navigation for Menu and Select; the browser dismisses the popup on an outside click. */
178
+ export function createListPopup<T>(opts: ListPopupOptions<T>): ListPopupState {
179
+ const open = signal(false)
180
+ const highlighted = signal(findFirstEnabledIndex(opts.items(), opts.isDisabled))
181
+ let rootEl: HTMLElement | undefined
182
+ let lastOpenEvent: Event | undefined
183
+ // On browsers without `showPopover({ source })`, clicking the trigger light-dismisses the popover before `click` fires; suppress that click so it stays closed.
184
+ let pointerDownOnTrigger = false
185
+ let pointerDown = false
186
+ let suppressNextClick = false
187
+ let clearSuppressTimer: ReturnType<typeof setTimeout> | undefined
188
+
189
+ const scheduleSuppressReset = () => {
190
+ clearTimeout(clearSuppressTimer)
191
+ clearSuppressTimer = setTimeout(() => {
192
+ clearSuppressTimer = undefined
193
+ pointerDownOnTrigger = false
194
+ suppressNextClick = false
195
+ }, 50)
196
+ }
197
+
198
+ const activeDescendantId = (): string | undefined => {
199
+ const idx = highlighted.value
200
+ const list = opts.items()
201
+ return !open.value || idx < 0 || idx >= list.length || opts.isDisabled(list[idx]!) ? undefined : opts.itemId(idx)
202
+ }
203
+
204
+ const focusActive = () => {
205
+ const id = opts.focusActive ? activeDescendantId() : undefined
206
+ if (!id)
207
+ return
208
+ const el = document.getElementById(id)
209
+ if (el)
210
+ el.focus()
211
+ else
212
+ queueMicrotask(() => document.getElementById(id)?.focus())
213
+ }
214
+
215
+ const openWith = (last: boolean) => {
216
+ open.value = true
217
+ const init = opts.initialIndex?.()
218
+ highlighted.value = init !== undefined && init >= 0
219
+ ? init
220
+ : (last ? findLastEnabledIndex : findFirstEnabledIndex)(opts.items(), opts.isDisabled)
221
+ focusActive()
222
+ }
223
+
224
+ const close = (returnFocus = false) => {
225
+ open.value = false
226
+ if (returnFocus)
227
+ rootEl?.querySelector<HTMLElement>('[data-part="trigger"]')?.focus()
228
+ }
229
+
230
+ effect(() => {
231
+ if (!open.value)
232
+ return
233
+ const onPointerDown = (e: Event) => {
234
+ const trigger = rootEl?.querySelector('[data-part="trigger"]')
235
+ pointerDownOnTrigger = trigger !== null && trigger !== undefined && trigger.contains(e.target as Node)
236
+ if (!pointerDownOnTrigger)
237
+ return
238
+ pointerDown = true
239
+ suppressNextClick = false
240
+ const onUp = () => {
241
+ pointerDown = false
242
+ document.removeEventListener('pointerup', onUp, true)
243
+ document.removeEventListener('pointercancel', onUp, true)
244
+ scheduleSuppressReset()
245
+ }
246
+ document.addEventListener('pointerup', onUp, true)
247
+ document.addEventListener('pointercancel', onUp, true)
248
+ }
249
+ const onKey = (e: KeyboardEvent) => {
250
+ if (e === lastOpenEvent)
251
+ return
252
+ const prev = highlighted.peek()
253
+ handleListKeyDown(e, {
254
+ items: opts.items,
255
+ activeIndex: highlighted,
256
+ isDisabled: opts.isDisabled,
257
+ onSelect: opts.onSelect,
258
+ onClose: close,
259
+ selectOnSpace: true,
260
+ })
261
+ if (open.peek() && highlighted.peek() !== prev)
262
+ focusActive()
263
+ }
264
+ document.addEventListener('pointerdown', onPointerDown, true)
265
+ document.addEventListener('keydown', onKey)
266
+ onCleanup(() => {
267
+ document.removeEventListener('pointerdown', onPointerDown, true)
268
+ document.removeEventListener('keydown', onKey)
269
+ })
270
+ })
271
+
272
+ return {
273
+ open,
274
+ highlighted,
275
+ setRoot(el) { rootEl = el },
276
+ close,
277
+ toggle(e) {
278
+ e.stopPropagation()
279
+ if (open.value) {
280
+ close()
281
+ }
282
+ else if (suppressNextClick) {
283
+ suppressNextClick = false
284
+ pointerDownOnTrigger = false
285
+ }
286
+ else {
287
+ openWith(false)
288
+ }
289
+ },
290
+ onTriggerKeyDown(e) {
291
+ if (!open.value && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
292
+ e.preventDefault()
293
+ e.stopPropagation()
294
+ lastOpenEvent = e
295
+ openWith(e.key === 'ArrowUp')
296
+ }
297
+ },
298
+ focusActive,
299
+ activeDescendantId,
300
+ mountPopup(el) {
301
+ if (el === undefined)
302
+ return
303
+ el.addEventListener('toggle', (e) => {
304
+ if ((e as ToggleEvent).newState !== 'closed')
305
+ return
306
+ if (open.peek() && pointerDownOnTrigger) {
307
+ suppressNextClick = true
308
+ if (!pointerDown)
309
+ scheduleSuppressReset()
310
+ }
311
+ close()
312
+ })
313
+ queueMicrotask(() => {
314
+ showAnchored(el, rootEl!.querySelector<HTMLElement>('[data-part="trigger"]')!)
315
+ focusActive()
316
+ })
317
+ },
318
+ }
319
+ }
320
+
321
+ // ---- Shared native <dialog> sync & backdrop click helpers ----
322
+
323
+ /** Syncs a native `<dialog>` element's modal state, handling initial `open={signal(true)}` on mount/hydration. */
324
+ export function syncDialogOpen(
325
+ el: HTMLDialogElement | undefined,
326
+ isOpen: Signal<boolean>,
327
+ wantOpen: boolean,
328
+ onOpened?: () => void,
329
+ ): void {
330
+ if (el === undefined)
331
+ return
332
+ if (wantOpen) {
333
+ if (!el.open) {
334
+ try {
335
+ el.showModal()
336
+ onOpened?.()
337
+ }
338
+ catch {
339
+ queueMicrotask(() => {
340
+ if (isOpen.peek() && !el.open && el.isConnected) {
341
+ el.showModal()
342
+ onOpened?.()
343
+ }
344
+ })
345
+ }
346
+ }
347
+ }
348
+ else if (el.open) {
349
+ el.close()
350
+ }
351
+ }
352
+
353
+ /** Returns true only when a click on `<dialog>` targeted the backdrop outside its inner panel. */
354
+ export function isDialogBackdropClick(e: MouseEvent, dialogEl: HTMLDialogElement | undefined): boolean {
355
+ if (dialogEl === undefined || e.target !== dialogEl)
356
+ return false
357
+ const rect = dialogEl.getBoundingClientRect()
358
+ if (rect.width === 0 && rect.height === 0)
359
+ return true
360
+ return e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom
361
+ }
362
+
363
+ // ---- Dialog behavior ----
364
+
365
+ export interface DialogBehavior {
366
+ readonly open: Signal<boolean>
367
+ show(): void
368
+ close(): void
369
+ toggle(): void
370
+ readonly triggerProps: Record<string, unknown>
371
+ }
372
+
373
+ export function createDialog(initial = false): DialogBehavior {
374
+ const open = signal(initial)
375
+ return {
376
+ open,
377
+ show: () => { open.value = true },
378
+ close: () => { open.value = false },
379
+ toggle: () => { open.value = !open.value },
380
+ get triggerProps() {
381
+ return {
382
+ 'type': 'button',
383
+ 'aria-haspopup': 'dialog',
384
+ 'aria-expanded': open.value ? 'true' : 'false',
385
+ 'onClick': () => { open.value = true },
386
+ }
387
+ },
388
+ }
389
+ }
@@ -0,0 +1,21 @@
1
+ import type { Context } from 'prunelle'
2
+ import { useContext } from 'prunelle'
3
+
4
+ export interface FieldControlWiring {
5
+ id: string
6
+ describedBy: string | undefined
7
+ invalid: boolean
8
+ required: boolean
9
+ }
10
+
11
+ export const FIELD_CONTEXT_ID = Symbol.for('pru.ui.field')
12
+ const FIELD_CONTEXT_REF = { id: FIELD_CONTEXT_ID, defaultValue: undefined } as Context<FieldControlWiring | undefined>
13
+
14
+ export function useFieldContext(): FieldControlWiring | undefined {
15
+ try {
16
+ return useContext(FIELD_CONTEXT_REF)
17
+ }
18
+ catch {
19
+ return undefined
20
+ }
21
+ }
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, CommandSource } 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,169 @@
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 CSS file.
3
+
4
+ import type { BuildPluginContext, PrunellePlugin } from 'prunelle/config'
5
+ import type { GrammarName, UiComponentPart } from './styles/split'
6
+ import { createHash } from 'node:crypto'
7
+ import { mkdirSync, writeFileSync } from 'node:fs'
8
+ import { dirname, resolve } from 'node:path'
9
+ import { definePlugin, minifyCss, serviceKey } from 'prunelle/config'
10
+ import { FALLBACK_FILE, FALLBACK_GUARD, FALLBACK_JS, withPlatformFallback } from './platform-fallback'
11
+ import { createUiPartScanner } from './styles/scan'
12
+ import {
13
+ GRAMMAR_NAMES,
14
+ grammarCssPath,
15
+ renderGrammarBaseCss,
16
+ renderGrammarCss as renderFullGrammarCss,
17
+ renderGrammarPartsCss,
18
+ UI_COMPONENT_PARTS,
19
+ UI_EXPORT_TO_PARTS,
20
+ } from './styles/split'
21
+
22
+ export {
23
+ GRAMMAR_NAMES,
24
+ grammarCssPath,
25
+ renderGrammarBaseCss,
26
+ renderGrammarPartsCss,
27
+ UI_COMPONENT_PARTS,
28
+ UI_EXPORT_TO_PARTS,
29
+ }
30
+ export type { GrammarName, UiComponentPart }
31
+
32
+ const UI_KUI_LAYER_SERVICE = serviceKey<boolean>('prunelle.ui.kuiLayer')
33
+
34
+ /** Returns the self-contained CSS source for a grammar (with `base.css` and component sheets inlined). */
35
+ export function renderGrammarCss(grammar: GrammarName, _bareCss?: string): string {
36
+ return renderFullGrammarCss(grammar)
37
+ }
38
+
39
+ /** Ejects a complete, self-contained CSS Grammar file into the app. */
40
+ export function ejectGrammar(root: string, grammar: GrammarName = 'editorial', destRel = 'src/styles/ui.css'): string {
41
+ const outPath = resolve(root, destRel)
42
+ mkdirSync(dirname(outPath), { recursive: true })
43
+ writeFileSync(outPath, renderGrammarCss(grammar))
44
+ return outPath
45
+ }
46
+
47
+ export interface EmitGrammarsOptions {
48
+ /** Public directory relative to `dist/public` (default: `'grammars'`). */
49
+ dir?: string | undefined
50
+ /** Subset of grammars to emit (default: all grammars). */
51
+ grammars?: readonly GrammarName[] | undefined
52
+ }
53
+
54
+ export interface UiPluginOptions {
55
+ /** Which pure CSS Grammar to include (default: 'editorial'). Pass `false` if importing your own CSS. */
56
+ grammar?: GrammarName | false | undefined
57
+ /** Emit standalone self-contained grammar CSS files into `public/grammars/<name>.css` for runtime switching. */
58
+ emitGrammars?: boolean | readonly GrammarName[] | EmitGrammarsOptions | undefined
59
+ }
60
+
61
+ function resolveEmitGrammars(opt: UiPluginOptions['emitGrammars']): { dir: string, grammars: readonly GrammarName[] } | undefined {
62
+ if (!opt)
63
+ return undefined
64
+ if (opt === true)
65
+ return { dir: 'grammars', grammars: GRAMMAR_NAMES }
66
+ if (Array.isArray(opt))
67
+ return { dir: 'grammars', grammars: opt }
68
+ const opts = opt as EmitGrammarsOptions
69
+ const dir = (opts.dir ?? 'grammars').replace(/^\/+|\/+$/g, '')
70
+ return { dir, grammars: opts.grammars ?? GRAMMAR_NAMES }
71
+ }
72
+
73
+ function cssHash(css: string): string {
74
+ return createHash('sha256').update(css).digest('hex').slice(0, 8)
75
+ }
76
+
77
+ function emitGrammarStyles(ctx: BuildPluginContext, grammar: GrammarName): void {
78
+ const prepGlobal = ctx.prependStyle ?? ctx.addStyle
79
+ const prepRoute = ctx.prependRouteStyle ?? ctx.addRouteStyle
80
+ if (prepGlobal === undefined)
81
+ return
82
+ const format = (css: string): string => ctx.minify ? minifyCss(css) : css
83
+
84
+ if (ctx.routeSourceFiles === undefined) {
85
+ const full = format(renderGrammarCss(grammar))
86
+ prepGlobal(ctx.emitAsset(`${grammar}-${cssHash(full)}.css`, full))
87
+ return
88
+ }
89
+
90
+ const scan = createUiPartScanner()
91
+ const globalParts = scan(ctx.globalSourceFiles ?? [])
92
+ const routes = ctx.routes ?? []
93
+ const perRoute = new Map<string, Set<UiComponentPart>>()
94
+ for (const route of routes)
95
+ perRoute.set(route.path, scan(ctx.routeSourceFiles.get(route.path) ?? []))
96
+
97
+ // Any UI component part rendered on every route belongs in the site-wide sheet so it is cached across navigations.
98
+ if (routes.length > 0) {
99
+ const firstParts = perRoute.get(routes[0]!.path)!
100
+ for (const part of firstParts) {
101
+ if (routes.every(r => perRoute.get(r.path)!.has(part)))
102
+ globalParts.add(part)
103
+ }
104
+ }
105
+
106
+ const baseSource = globalParts.size > 0
107
+ ? `${renderGrammarBaseCss(grammar)}\n${renderGrammarPartsCss(grammar, globalParts)}`
108
+ : renderGrammarBaseCss(grammar)
109
+ const baseCss = format(baseSource)
110
+ prepGlobal(ctx.emitAsset(`${grammar}-${cssHash(baseCss)}.css`, baseCss))
111
+
112
+ if (prepRoute === undefined)
113
+ return
114
+ const routeCache = new Map<string, string>()
115
+ for (const route of routes) {
116
+ const routeParts = perRoute.get(route.path)!
117
+ const extra = UI_COMPONENT_PARTS.filter(p => routeParts.has(p) && !globalParts.has(p))
118
+ if (extra.length === 0)
119
+ continue
120
+ const key = extra.join(',')
121
+ let href = routeCache.get(key)
122
+ if (href === undefined) {
123
+ const partsCss = format(renderGrammarPartsCss(grammar, extra))
124
+ href = ctx.emitAsset(`${grammar}-parts-${cssHash(partsCss)}.css`, partsCss)
125
+ routeCache.set(key, href)
126
+ }
127
+ prepRoute(route.path, href)
128
+ }
129
+ }
130
+
131
+ export function ui(options: UiPluginOptions = {}): PrunellePlugin {
132
+ const grammar = options.grammar === undefined ? 'editorial' : options.grammar
133
+ const emit = resolveEmitGrammars(options.emitGrammars)
134
+ let assetPrefix = '/_pru'
135
+ return definePlugin({
136
+ name: '@prunellejs/ui',
137
+ inlineScripts: [FALLBACK_GUARD],
138
+ build(ctx) {
139
+ ctx.emitAsset(FALLBACK_FILE, FALLBACK_JS)
140
+ if (grammar !== false) {
141
+ ctx.provide?.(UI_KUI_LAYER_SERVICE, true)
142
+ emitGrammarStyles(ctx, grammar)
143
+ }
144
+ if (emit !== undefined) {
145
+ const prefix = emit.dir ? `${emit.dir}/` : ''
146
+ for (const g of emit.grammars) {
147
+ const css = renderGrammarCss(g)
148
+ ctx.emitPublic(`${prefix}${g}.css`, ctx.minify ? minifyCss(css) : css)
149
+ }
150
+ }
151
+ },
152
+ server(api) {
153
+ assetPrefix = api.assetPrefix
154
+ },
155
+ transformHtml: html => withPlatformFallback(html, assetPrefix),
156
+ commands: {
157
+ 'ui-eject': (args, root) => {
158
+ const name = (args[0] ?? 'editorial') as GrammarName
159
+ if (!GRAMMAR_NAMES.includes(name)) {
160
+ console.error(`Unknown grammar "${name}". Choose one of: ${GRAMMAR_NAMES.join(', ')}`)
161
+ process.exit(1)
162
+ }
163
+ const dest = args[1] ?? 'src/styles/ui.css'
164
+ const outPath = ejectGrammar(root, name, dest)
165
+ console.log(`Ejected @prunellejs/ui "${name}" grammar to ${outPath}`)
166
+ },
167
+ },
168
+ })
169
+ }