@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.
- package/llms.txt +76 -0
- package/package.json +32 -4
- package/src/CommandPalette.tsx +257 -0
- package/src/DataTable.tsx +165 -0
- package/src/Dialog.tsx +165 -0
- package/src/Drawer.tsx +4 -0
- package/src/Menu.tsx +115 -0
- package/src/Select.tsx +114 -0
- package/src/Tabs.tsx +63 -0
- package/src/Toaster.tsx +31 -0
- package/src/behaviors.ts +287 -0
- package/src/field-context.ts +21 -0
- package/src/index.ts +72 -0
- package/src/platform-fallback.ts +36 -0
- package/src/plugin.ts +169 -0
- package/src/primitives.tsx +237 -0
- package/src/static.tsx +319 -0
- package/src/styles/bare.css +24 -0
- package/src/styles/base.css +55 -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/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 +178 -0
- package/src/styles/grammars/editorial.css +163 -0
- package/src/styles/grammars/orbit.css +268 -0
- package/src/styles/grammars/prunelle.css +449 -0
- package/src/styles/grammars/soft.css +160 -0
- package/src/styles/grammars/workshop.css +171 -0
- package/src/styles/scan.ts +137 -0
- package/src/styles/split.ts +381 -0
- package/src/styles/theme.css +21 -0
- package/src/styles/themed/accordion.css +20 -0
- package/src/styles/themed/badge.css +20 -0
- package/src/styles/themed/button.css +21 -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/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 +18 -0
- package/src/styles/themed/tabs.css +17 -0
- package/src/styles/themed/toast.css +18 -0
- package/src/table-state.ts +126 -0
- package/src/tabs-state.ts +39 -0
- package/src/toast.ts +68 -0
- package/README.md +0 -3
package/src/behaviors.ts
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
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
|
+
// ---- Stable hydration-safe unique IDs for ARIA wiring ----
|
|
17
|
+
|
|
18
|
+
export function nextUiId(prefix: string): string {
|
|
19
|
+
return useId(prefix)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// ---- Shared listbox / menu keyboard navigation ----
|
|
23
|
+
|
|
24
|
+
export function findFirstEnabledIndex<T>(items: readonly T[], isDisabled?: (item: T) => boolean): number {
|
|
25
|
+
return findNextEnabledIndex(items, -1, 1, isDisabled)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function findLastEnabledIndex<T>(items: readonly T[], isDisabled?: (item: T) => boolean): number {
|
|
29
|
+
return findNextEnabledIndex(items, items.length, -1, isDisabled)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function findNextEnabledIndex<T>(
|
|
33
|
+
items: readonly T[],
|
|
34
|
+
current: number,
|
|
35
|
+
delta: 1 | -1,
|
|
36
|
+
isDisabled?: (item: T) => boolean,
|
|
37
|
+
): number {
|
|
38
|
+
const len = items.length
|
|
39
|
+
if (len === 0)
|
|
40
|
+
return -1
|
|
41
|
+
let idx = current < 0 || current >= len ? (delta === 1 ? -1 : len) : current
|
|
42
|
+
for (let step = 0; step < len; step++) {
|
|
43
|
+
idx = (idx + delta + len) % len
|
|
44
|
+
if (!isDisabled?.(items[idx]!))
|
|
45
|
+
return idx
|
|
46
|
+
}
|
|
47
|
+
return -1
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface ListNavigationOptions<T> {
|
|
51
|
+
items: () => readonly T[]
|
|
52
|
+
activeIndex: Signal<number>
|
|
53
|
+
isDisabled?: ((item: T) => boolean) | undefined
|
|
54
|
+
onSelect: (item: T, index: number) => void
|
|
55
|
+
onClose: (returnFocus?: boolean) => void
|
|
56
|
+
selectOnSpace?: boolean | undefined
|
|
57
|
+
homeEnd?: boolean | undefined
|
|
58
|
+
closeOnTab?: boolean | undefined
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Shared keyboard handler for ARIA menu / listbox / combobox popups (ArrowUp/Down, Home/End, Enter/Space, Escape, Tab). */
|
|
62
|
+
export function handleListKeyDown<T>(e: KeyboardEvent, opts: ListNavigationOptions<T>): boolean {
|
|
63
|
+
const list = opts.items()
|
|
64
|
+
if (e.key === 'Escape') {
|
|
65
|
+
opts.onClose(true)
|
|
66
|
+
return true
|
|
67
|
+
}
|
|
68
|
+
if (e.key === 'Tab') {
|
|
69
|
+
if (opts.closeOnTab === false)
|
|
70
|
+
return false
|
|
71
|
+
opts.onClose(false)
|
|
72
|
+
return true
|
|
73
|
+
}
|
|
74
|
+
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
|
75
|
+
e.preventDefault()
|
|
76
|
+
opts.activeIndex.value = findNextEnabledIndex(list, opts.activeIndex.value, e.key === 'ArrowDown' ? 1 : -1, opts.isDisabled)
|
|
77
|
+
return true
|
|
78
|
+
}
|
|
79
|
+
if (opts.homeEnd !== false && (e.key === 'Home' || e.key === 'End')) {
|
|
80
|
+
e.preventDefault()
|
|
81
|
+
opts.activeIndex.value = (e.key === 'Home' ? findFirstEnabledIndex : findLastEnabledIndex)(list, opts.isDisabled)
|
|
82
|
+
return true
|
|
83
|
+
}
|
|
84
|
+
if (e.key === 'Enter' || (opts.selectOnSpace !== false && e.key === ' ')) {
|
|
85
|
+
const idx = opts.activeIndex.value
|
|
86
|
+
const active = idx >= 0 && idx < list.length ? list[idx] : undefined
|
|
87
|
+
if (active !== undefined && !opts.isDisabled?.(active)) {
|
|
88
|
+
e.preventDefault()
|
|
89
|
+
opts.onSelect(active, idx)
|
|
90
|
+
return true
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return false
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface ListPopupOptions<T> {
|
|
97
|
+
items: () => readonly T[]
|
|
98
|
+
itemId: (idx: number) => string
|
|
99
|
+
isDisabled: (item: T) => boolean
|
|
100
|
+
onSelect: (item: T, idx: number) => void
|
|
101
|
+
initialIndex?: () => number
|
|
102
|
+
focusActive?: boolean | undefined
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface ListPopupState {
|
|
106
|
+
readonly open: Signal<boolean>
|
|
107
|
+
readonly highlighted: Signal<number>
|
|
108
|
+
setRoot(el: HTMLElement | undefined): void
|
|
109
|
+
close(returnFocus?: boolean): void
|
|
110
|
+
toggle(e: MouseEvent): void
|
|
111
|
+
onTriggerKeyDown(e: KeyboardEvent): void
|
|
112
|
+
focusActive(): void
|
|
113
|
+
activeDescendantId(): string | undefined
|
|
114
|
+
/** The popup's `ref`: shows it in the top layer, anchored to the trigger. */
|
|
115
|
+
mountPopup(el: HTMLElement | undefined): void
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// 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.
|
|
119
|
+
function showAnchored(el: HTMLElement, trigger: HTMLElement): void {
|
|
120
|
+
if (el.isConnected && !el.matches(':popover-open'))
|
|
121
|
+
el.showPopover({ source: trigger })
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Shared popup open/close and keyboard list navigation for Menu and Select; the browser dismisses the popup on an outside click. */
|
|
125
|
+
export function createListPopup<T>(opts: ListPopupOptions<T>): ListPopupState {
|
|
126
|
+
const open = signal(false)
|
|
127
|
+
const highlighted = signal(findFirstEnabledIndex(opts.items(), opts.isDisabled))
|
|
128
|
+
let rootEl: HTMLElement | undefined
|
|
129
|
+
let lastOpenEvent: Event | undefined
|
|
130
|
+
|
|
131
|
+
const activeDescendantId = (): string | undefined => {
|
|
132
|
+
const idx = highlighted.value
|
|
133
|
+
const list = opts.items()
|
|
134
|
+
return !open.value || idx < 0 || idx >= list.length || opts.isDisabled(list[idx]!) ? undefined : opts.itemId(idx)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const focusActive = () => {
|
|
138
|
+
const id = opts.focusActive ? activeDescendantId() : undefined
|
|
139
|
+
if (!id)
|
|
140
|
+
return
|
|
141
|
+
const el = document.getElementById(id)
|
|
142
|
+
if (el)
|
|
143
|
+
el.focus()
|
|
144
|
+
else
|
|
145
|
+
queueMicrotask(() => document.getElementById(id)?.focus())
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const openWith = (last: boolean) => {
|
|
149
|
+
open.value = true
|
|
150
|
+
const init = opts.initialIndex?.()
|
|
151
|
+
highlighted.value = init !== undefined && init >= 0
|
|
152
|
+
? init
|
|
153
|
+
: (last ? findLastEnabledIndex : findFirstEnabledIndex)(opts.items(), opts.isDisabled)
|
|
154
|
+
focusActive()
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const close = (returnFocus = false) => {
|
|
158
|
+
open.value = false
|
|
159
|
+
if (returnFocus)
|
|
160
|
+
rootEl?.querySelector<HTMLElement>('[data-part="trigger"]')?.focus()
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
effect(() => {
|
|
164
|
+
if (!open.value)
|
|
165
|
+
return
|
|
166
|
+
const onKey = (e: KeyboardEvent) => {
|
|
167
|
+
if (e === lastOpenEvent)
|
|
168
|
+
return
|
|
169
|
+
const prev = highlighted.peek()
|
|
170
|
+
handleListKeyDown(e, {
|
|
171
|
+
items: opts.items,
|
|
172
|
+
activeIndex: highlighted,
|
|
173
|
+
isDisabled: opts.isDisabled,
|
|
174
|
+
onSelect: opts.onSelect,
|
|
175
|
+
onClose: close,
|
|
176
|
+
selectOnSpace: true,
|
|
177
|
+
})
|
|
178
|
+
if (open.peek() && highlighted.peek() !== prev)
|
|
179
|
+
focusActive()
|
|
180
|
+
}
|
|
181
|
+
document.addEventListener('keydown', onKey)
|
|
182
|
+
onCleanup(() => document.removeEventListener('keydown', onKey))
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
return {
|
|
186
|
+
open,
|
|
187
|
+
highlighted,
|
|
188
|
+
setRoot(el) { rootEl = el },
|
|
189
|
+
close,
|
|
190
|
+
toggle(e) {
|
|
191
|
+
e.stopPropagation()
|
|
192
|
+
if (open.value)
|
|
193
|
+
close()
|
|
194
|
+
else
|
|
195
|
+
openWith(false)
|
|
196
|
+
},
|
|
197
|
+
onTriggerKeyDown(e) {
|
|
198
|
+
if (!open.value && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
|
|
199
|
+
e.preventDefault()
|
|
200
|
+
e.stopPropagation()
|
|
201
|
+
lastOpenEvent = e
|
|
202
|
+
openWith(e.key === 'ArrowUp')
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
focusActive,
|
|
206
|
+
activeDescendantId,
|
|
207
|
+
mountPopup(el) {
|
|
208
|
+
if (el === undefined)
|
|
209
|
+
return
|
|
210
|
+
el.addEventListener('toggle', e => (e as ToggleEvent).newState === 'closed' && close())
|
|
211
|
+
queueMicrotask(() => {
|
|
212
|
+
showAnchored(el, rootEl!.querySelector<HTMLElement>('[data-part="trigger"]')!)
|
|
213
|
+
focusActive()
|
|
214
|
+
})
|
|
215
|
+
},
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ---- Shared native <dialog> sync & backdrop click helpers ----
|
|
220
|
+
|
|
221
|
+
/** Syncs a native `<dialog>` element's modal state, handling initial `open={signal(true)}` on mount/hydration. */
|
|
222
|
+
export function syncDialogOpen(
|
|
223
|
+
el: HTMLDialogElement | undefined,
|
|
224
|
+
isOpen: Signal<boolean>,
|
|
225
|
+
wantOpen: boolean,
|
|
226
|
+
onOpened?: () => void,
|
|
227
|
+
): void {
|
|
228
|
+
if (el === undefined)
|
|
229
|
+
return
|
|
230
|
+
if (wantOpen) {
|
|
231
|
+
if (!el.open) {
|
|
232
|
+
try {
|
|
233
|
+
el.showModal()
|
|
234
|
+
onOpened?.()
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
queueMicrotask(() => {
|
|
238
|
+
if (isOpen.peek() && !el.open && el.isConnected) {
|
|
239
|
+
el.showModal()
|
|
240
|
+
onOpened?.()
|
|
241
|
+
}
|
|
242
|
+
})
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
else if (el.open) {
|
|
247
|
+
el.close()
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Returns true only when a click on `<dialog>` targeted the backdrop outside its inner panel. */
|
|
252
|
+
export function isDialogBackdropClick(e: MouseEvent, dialogEl: HTMLDialogElement | undefined): boolean {
|
|
253
|
+
if (dialogEl === undefined || e.target !== dialogEl)
|
|
254
|
+
return false
|
|
255
|
+
const rect = dialogEl.getBoundingClientRect()
|
|
256
|
+
if (rect.width === 0 && rect.height === 0)
|
|
257
|
+
return true
|
|
258
|
+
return e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// ---- Dialog behavior ----
|
|
262
|
+
|
|
263
|
+
export interface DialogBehavior {
|
|
264
|
+
readonly open: Signal<boolean>
|
|
265
|
+
show(): void
|
|
266
|
+
close(): void
|
|
267
|
+
toggle(): void
|
|
268
|
+
readonly triggerProps: Record<string, unknown>
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export function createDialog(initial = false): DialogBehavior {
|
|
272
|
+
const open = signal(initial)
|
|
273
|
+
return {
|
|
274
|
+
open,
|
|
275
|
+
show: () => { open.value = true },
|
|
276
|
+
close: () => { open.value = false },
|
|
277
|
+
toggle: () => { open.value = !open.value },
|
|
278
|
+
get triggerProps() {
|
|
279
|
+
return {
|
|
280
|
+
'type': 'button',
|
|
281
|
+
'aria-haspopup': 'dialog',
|
|
282
|
+
'aria-expanded': open.value ? 'true' : 'false',
|
|
283
|
+
'onClick': () => { open.value = true },
|
|
284
|
+
}
|
|
285
|
+
},
|
|
286
|
+
}
|
|
287
|
+
}
|
|
@@ -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
|
+
}
|