@adea-ai/ui 0.154.1 → 0.155.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/dist/components/composites/appearance-editor/appearance-editor.d.ts.map +1 -1
- package/dist/components/composites/appearance-editor/appearance-editor.js +23 -1
- package/dist/components/composites/appearance-editor/appearance-editor.js.map +1 -1
- package/dist/components/composites/appearance-editor/appearance-rows.d.ts +10 -2
- package/dist/components/composites/appearance-editor/appearance-rows.d.ts.map +1 -1
- package/dist/components/composites/appearance-editor/appearance-rows.js +35 -7
- package/dist/components/composites/appearance-editor/appearance-rows.js.map +1 -1
- package/dist/components/composites/appearance-editor/appearance-types.d.ts +6 -0
- package/dist/components/composites/appearance-editor/appearance-types.d.ts.map +1 -1
- package/dist/components/composites/tree/index.d.ts +1 -1
- package/dist/components/composites/tree/index.d.ts.map +1 -1
- package/dist/components/composites/tree/index.js +1 -1
- package/dist/components/composites/tree/tree.d.ts +31 -1
- package/dist/components/composites/tree/tree.d.ts.map +1 -1
- package/dist/components/composites/tree/tree.js +76 -1
- package/dist/components/composites/tree/tree.js.map +1 -1
- package/dist/components/theme/theme-document.d.ts +14 -1
- package/dist/components/theme/theme-document.d.ts.map +1 -1
- package/dist/components/theme/theme-document.js +19 -2
- package/dist/components/theme/theme-document.js.map +1 -1
- package/dist/components/theme/theme-persistence.d.ts.map +1 -1
- package/dist/components/theme/theme-persistence.js +1 -0
- package/dist/components/theme/theme-persistence.js.map +1 -1
- package/dist/components/theme/theme-provider-value.d.ts.map +1 -1
- package/dist/components/theme/theme-provider-value.js +2 -1
- package/dist/components/theme/theme-provider-value.js.map +1 -1
- package/dist/components/theme/theme-state.d.ts +20 -0
- package/dist/components/theme/theme-state.d.ts.map +1 -1
- package/dist/components/theme/theme-state.js +9 -1
- package/dist/components/theme/theme-state.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/lib/theme-engine.d.ts +2 -1
- package/dist/lib/theme-engine.d.ts.map +1 -1
- package/dist/lib/theme-engine.js +2 -1
- package/dist/lib/theme-engine.js.map +1 -1
- package/dist/r/src/components/composites/appearance-editor/appearance-editor.tsx +11 -1
- package/dist/r/src/components/composites/appearance-editor/appearance-rows.tsx +27 -6
- package/dist/r/src/components/composites/appearance-editor/appearance-types.ts +6 -0
- package/dist/r/src/components/composites/tree/index.ts +3 -0
- package/dist/r/src/components/composites/tree/tree.tsx +82 -0
- package/dist/r/src/components/theme/theme-document.ts +36 -1
- package/dist/r/src/components/theme/theme-persistence.ts +4 -0
- package/dist/r/src/components/theme/theme-provider-value.ts +2 -0
- package/dist/r/src/components/theme/theme-state.ts +26 -0
- package/dist/r/src/lib/theme-engine.ts +3 -2
- package/package.json +1 -1
- package/src/components/composites/appearance-editor/appearance-editor.tsx +11 -1
- package/src/components/composites/appearance-editor/appearance-rows.tsx +27 -6
- package/src/components/composites/appearance-editor/appearance-types.ts +6 -0
- package/src/components/composites/tree/index.ts +3 -0
- package/src/components/composites/tree/tree.tsx +82 -0
- package/src/components/theme/theme-document.ts +36 -1
- package/src/components/theme/theme-persistence.ts +4 -0
- package/src/components/theme/theme-provider-value.ts +2 -0
- package/src/components/theme/theme-state.ts +26 -0
- package/src/lib/theme-engine.ts +3 -2
|
@@ -11,6 +11,9 @@ var _tmpl$3 = /*#__PURE__*/ template(`<span aria-hidden=true data-slot=tree-row-
|
|
|
11
11
|
var _tmpl$4 = /*#__PURE__*/ template(`<span class="flex size-4 shrink-0 items-center justify-center [&_svg]:size-4">`);
|
|
12
12
|
var _tmpl$5 = /*#__PURE__*/ template(`<span class="ms-auto flex shrink-0 items-center gap-1 text-muted-foreground">`);
|
|
13
13
|
var _tmpl$6 = /*#__PURE__*/ template(`<span data-slot=tree-row-actions>`);
|
|
14
|
+
var _tmpl$7 = /*#__PURE__*/ template(`<div aria-hidden=true class="border-b border-border bg-background">`);
|
|
15
|
+
var _tmpl$8 = /*#__PURE__*/ template(`<div data-slot=tree-sticky-header>`);
|
|
16
|
+
var _tmpl$9 = /*#__PURE__*/ template(`<button type=button tabindex=-1 class="flex min-h-row-sm w-full min-w-0 items-center gap-1.5 pe-1.5 text-left text-sm outline-none hover:bg-surface-hover"><span class="flex size-3.5 shrink-0 items-center justify-center text-muted-foreground">`);
|
|
14
17
|
var ChevronRight$1 = fastIcon(ChevronRight);
|
|
15
18
|
var TreeContext = createContext();
|
|
16
19
|
function useTreeContext() {
|
|
@@ -467,6 +470,77 @@ function TreeRowActions(props) {
|
|
|
467
470
|
return _el$8;
|
|
468
471
|
})();
|
|
469
472
|
}
|
|
473
|
+
/**
|
|
474
|
+
* TreeStickyHeader.
|
|
475
|
+
*
|
|
476
|
+
* Pins the folders above the first row in view to the top of a scrolling tree, so a reader deep
|
|
477
|
+
* in a long folder still sees where they are (Zed's sticky scroll, VS Code's sticky tree). Put it
|
|
478
|
+
* first inside `Tree`, whose root is the scroll container. It takes no layout space: the pinned
|
|
479
|
+
* rows float over the rows beneath, so the host's row window math is unchanged.
|
|
480
|
+
*
|
|
481
|
+
* The pinned rows repeat rows the tree already exposes, so they are hidden from assistive
|
|
482
|
+
* technology and kept out of the tab order; they are a pointer shortcut only. The host decides
|
|
483
|
+
* which row is first in view (it owns the row window), and should pass the row under the pinned
|
|
484
|
+
* stack rather than the one at the very top, see `treeStickyAncestors`.
|
|
485
|
+
*/
|
|
486
|
+
function TreeStickyHeader(props) {
|
|
487
|
+
const tree = useTreeContext();
|
|
488
|
+
const ancestors = createMemo(() => treeStickyAncestors(tree.index(), props.topId).slice(-(props.maxRows ?? 5)));
|
|
489
|
+
return (() => {
|
|
490
|
+
var _el$9 = _tmpl$8();
|
|
491
|
+
insert(_el$9, createComponent(Show, {
|
|
492
|
+
get when() {
|
|
493
|
+
return ancestors().length > 0;
|
|
494
|
+
},
|
|
495
|
+
get children() {
|
|
496
|
+
var _el$0 = _tmpl$7();
|
|
497
|
+
insert(_el$0, createComponent(For, {
|
|
498
|
+
get each() {
|
|
499
|
+
return ancestors();
|
|
500
|
+
},
|
|
501
|
+
children: (item) => (() => {
|
|
502
|
+
var _el$1 = _tmpl$9(), _el$10 = _el$1.firstChild;
|
|
503
|
+
_el$1.$$click = () => props.onSelect?.(item.id);
|
|
504
|
+
_el$1.$$mousedown = handleMarkerMouseDown;
|
|
505
|
+
insert(_el$10, createComponent(ChevronRight$1, {
|
|
506
|
+
"aria-hidden": "true",
|
|
507
|
+
"class": "size-3.5 rotate-90"
|
|
508
|
+
}));
|
|
509
|
+
insert(_el$1, () => props.label(item.id), null);
|
|
510
|
+
effect((_p$) => {
|
|
511
|
+
var _v$3 = item.id, _v$4 = `${rowInset(item.level)}px`;
|
|
512
|
+
_v$3 !== _p$.e && setAttribute(_el$1, "data-tree-sticky-id", _p$.e = _v$3);
|
|
513
|
+
_v$4 !== _p$.t && setStyleProperty(_el$1, "padding-inline-start", _p$.t = _v$4);
|
|
514
|
+
return _p$;
|
|
515
|
+
}, {
|
|
516
|
+
e: void 0,
|
|
517
|
+
t: void 0
|
|
518
|
+
});
|
|
519
|
+
return _el$1;
|
|
520
|
+
})()
|
|
521
|
+
}));
|
|
522
|
+
return _el$0;
|
|
523
|
+
}
|
|
524
|
+
}));
|
|
525
|
+
effect(() => className(_el$9, cn("sticky top-0 z-10 h-0", props.class)));
|
|
526
|
+
return _el$9;
|
|
527
|
+
})();
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* The expanded folders above `id`, outermost first. A host finds the row under the pinned stack
|
|
531
|
+
* by asking again for the row at `scrollTop + ancestors × rowHeight` until the answer settles.
|
|
532
|
+
*/
|
|
533
|
+
function treeStickyAncestors(index, id) {
|
|
534
|
+
const chain = [];
|
|
535
|
+
let parentId = id === null ? null : index.byId.get(id)?.parentId ?? null;
|
|
536
|
+
while (parentId !== null) {
|
|
537
|
+
const parent = index.byId.get(parentId);
|
|
538
|
+
if (!parent) break;
|
|
539
|
+
chain.push(parent);
|
|
540
|
+
parentId = parent.parentId;
|
|
541
|
+
}
|
|
542
|
+
return chain.toReversed();
|
|
543
|
+
}
|
|
470
544
|
var handleMarkerMouseDown = (event) => event.preventDefault();
|
|
471
545
|
var handleMarkerDoubleClick = (event) => event.stopPropagation();
|
|
472
546
|
/** The inline-start padding of a row at a one-based `level`, in px. */
|
|
@@ -477,6 +551,7 @@ function rowInset(level) {
|
|
|
477
551
|
var GUIDE_CENTER = 7;
|
|
478
552
|
function isActionTarget(target, currentTarget) {
|
|
479
553
|
if (!(target instanceof Element) || target === currentTarget) return false;
|
|
554
|
+
if (!currentTarget.contains(target)) return true;
|
|
480
555
|
return Boolean(target.closest("a, button, input, textarea, select, [contenteditable=\"true\"], [role=\"button\"], [data-tree-keyboard-stop]"));
|
|
481
556
|
}
|
|
482
557
|
function composeRefs(internal, external) {
|
|
@@ -491,6 +566,6 @@ delegateEvents([
|
|
|
491
566
|
"click",
|
|
492
567
|
"dblclick"
|
|
493
568
|
]);
|
|
494
|
-
export { Tree, TreeRow, TreeRowActions };
|
|
569
|
+
export { Tree, TreeRow, TreeRowActions, TreeStickyHeader, treeStickyAncestors };
|
|
495
570
|
|
|
496
571
|
//# sourceMappingURL=tree.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tree.js","names":["ChevronRight","LucideChevronRight","createContext","createEffect","createMemo","createSelector","createUniqueId","For","onCleanup","Show","splitProps","useContext","cn","indexTreeItems","treeNavigationAction","typeaheadIndex","fastIcon","idPrefix","activeId","isActive","id","index","register","element","HTMLDivElement","unregister","focusItem","noteFocus","noteBlur","next","activate","event","expand","expanded","disclosure","guides","onActiveIdChange","TreeContext","useTreeContext","tree","Error","visibleItems","onExpand","onActivate","onSelectItem","onRequestReveal","onRowSizeChange","blockSize","selectionMode","typeaheadLabel","children","Element","Tree","props","local","rest","effectiveActiveId","candidate","visible","byId","has","ids","rows","Map","rowIdsByElement","WeakMap","pendingFocusId","pendingFocusGuard","requestedRevealId","focusedId","disposed","isInsideTreeRow","row","closest","focusIsOutsideTree","document","active","activeElement","body","documentElement","rowSizeObserver","ResizeObserver","undefined","entries","entry","get","target","borderBoxSize","offsetHeight","Number","isFinite","setPendingFocus","removeEventListener","cancelPendingFocus","addEventListener","typed","typedTimer","setTimeout","disconnect","clearTimeout","requestReveal","focusWhenMounted","queueMicrotask","focus","context","set","observe","focusWasInside","Boolean","contains","delete","unobserve","fallbackId","typeahead","label","ctrlKey","metaKey","altKey","key","length","indexById","map","preventDefault","handleKeyDown","defaultPrevented","isActionTarget","currentTarget","action","type","_$createComponent","Provider","value","_el$","_tmpl$","_$spread","_$mergeProps","class","_$insert","item","selected","leading","trailing","onDoubleClick","TreeRow","registeredId","handleFocusOut","relatedTarget","setRef","nextId","handleFocus","handleClick","handleDoubleClick","position","positionById","markerTarget","expandable","handleMarkerClick","stopPropagation","_el$2","_tmpl$2","_el$3","firstChild","_el$4","nextSibling","_ref$","composeRefs","ref","_$use","encodeURIComponent","level","_$memo","setSize","tabIndex","String","relative","style","rowInset","when","each","Array","from","_","_el$5","_tmpl$3","_$effect","_$p","_$setStyleProperty","GUIDE_CENTER","_$addEventListener","handleMarkerDoubleClick","handleMarkerMouseDown","_c$","slot","_el$6","_tmpl$4","_el$7","_tmpl$5","_p$","_v$","_v$2","e","_$setAttribute","t","_$className","TreeRowActions","pinned","_el$8","_tmpl$6","Math","max","internal","external","_$delegateEvents"],"sources":["../../../../src/components/composites/tree/tree.tsx"],"sourcesContent":["import type { ComponentProps, JSX } from 'solid-js'\nimport { ChevronRight as LucideChevronRight } from 'lucide-solid'\nimport {\n createContext,\n createEffect,\n createMemo,\n createSelector,\n createUniqueId,\n For,\n onCleanup,\n Show,\n splitProps,\n useContext,\n} from 'solid-js'\nimport { cn } from '#lib/utils'\nimport {\n indexTreeItems,\n treeNavigationAction,\n typeaheadIndex,\n type TreeItemDescriptor,\n type TreeNavigationIndex,\n} from './tree-navigation'\nimport { fastIcon } from '#lib/fast-icon'\n\n// lucide icons drawn from a cloned template (see fastIcon).\nconst ChevronRight = fastIcon(LucideChevronRight)\n\ntype TreeContextValue = {\n idPrefix: string\n activeId: () => string | null\n /** O(1) per change: only the rows whose answer flips re-run, not every row. */\n isActive: (id: string) => boolean\n index: () => TreeNavigationIndex\n register: (id: string, element: HTMLDivElement) => void\n unregister: (id: string, element: HTMLDivElement | undefined) => void\n focusItem: (id: string) => void\n noteFocus: (id: string) => void\n noteBlur: (next: EventTarget | null) => void\n activate: (id: string, event: Event) => void\n expand: (id: string, expanded: boolean) => void\n disclosure: () => TreeDisclosure\n guides: () => boolean\n onActiveIdChange: (id: string) => void\n}\n\nconst TreeContext = createContext<TreeContextValue>()\n\nfunction useTreeContext() {\n const tree = useContext(TreeContext)\n if (!tree) throw new Error('[adea-ui]: TreeRow must be used inside Tree.')\n return tree\n}\n\n/**\n * Who owns the pointer on a row's disclosure chevron.\n *\n * - `row` (default): the chevron is decoration; a click anywhere on the row,\n * chevron included, is a row activation. This is the file-explorer\n * convention, where the host's `onActivate` toggles a folder.\n * - `marker`: the chevron of an expandable row is its own pointer target. It\n * calls `onExpand(id, !expanded)` and nothing else; the rest of the row still\n * activates. For trees where expanding and selecting are independent (a\n * source list that selects a source and separately reveals its details).\n */\nexport type TreeDisclosure = 'row' | 'marker'\n\ntype TreeAccessibleName =\n | { 'aria-label': string; 'aria-labelledby'?: string }\n | { 'aria-label'?: string; 'aria-labelledby': string }\n\nexport type TreeProps = Omit<\n ComponentProps<'div'>,\n 'children' | 'role' | 'tabIndex' | 'onKeyDown' | 'aria-label' | 'aria-labelledby'\n> &\n TreeAccessibleName & {\n /** Complete, ordered projection of currently visible (expanded) items. */\n visibleItems: readonly TreeItemDescriptor[]\n /** The host-owned identity of the row that currently owns roving focus. */\n activeId: string | null\n /**\n * Called when keyboard or pointer navigation changes the active row, and when\n * the active row leaves `visibleItems` (collapsed away, filtered out) and the\n * first visible row takes over as the roving stop.\n */\n onActiveIdChange: (id: string) => void\n /** Called for Left/Right expand and collapse requests. */\n onExpand?: (id: string, expanded: boolean) => void\n /**\n * Opt-in pointer behaviour of the disclosure chevron; see {@link TreeDisclosure}.\n * Keyboard behaviour is identical in both modes: Left/Right expand and collapse.\n */\n disclosure?: TreeDisclosure\n /**\n * Draw a vertical guide line down each ancestor level of a nested row, so a\n * group of children reads as belonging to its parent. Off by default: a flat\n * list or a dense file explorer carries its own rhythm.\n */\n guides?: boolean\n /** Called for Enter or pointer activation. Domain action stays host-owned. */\n onActivate?: (id: string, event: Event) => void\n /** Called for Space selection. Selection state stays host-owned. */\n onSelectItem?: (id: string, event: Event) => void\n /** Ask the host window to mount/reveal an item before focus moves to it. */\n onRequestReveal?: (id: string) => void\n /** Report a mounted row's border-box block size in CSS pixels for host range math. */\n onRowSizeChange?: (id: string, blockSize: number) => void\n /** Declares a multi-select tree to assistive technology. */\n selectionMode?: 'single' | 'multiple'\n /**\n * The text a row is found by when the reader types its first letters. Supply\n * it to turn on typeahead: a typed prefix moves focus to the next visible row\n * whose label starts with it, revealing an unmounted row first.\n */\n typeaheadLabel?: (id: string) => string\n children?: JSX.Element\n }\n\n/**\n * Tree.\n *\n * Supplies semantic and keyboard behavior for a tree whose host owns the\n * visible projection, filesystem state, row window and domain actions. The\n * mounted children can be a small virtualized window; `visibleItems` remains\n * the complete ordered projection so keyboard movement and sibling positions\n * do not depend on which rows currently exist in the DOM.\n *\n * Kobalte 0.13.14 has no Tree primitive, so this component implements the\n * WAI-ARIA tree row navigation contract and leaves product state to callbacks.\n *\n * By default the disclosure chevron is decoration and a click anywhere on a\n * row activates it, so a file explorer can toggle a folder from `onActivate`.\n * Reach for `disclosure=\"marker\"` when expanding and selecting are separate\n * decisions: the chevron then calls only `onExpand`, and the rest of the row\n * calls only `onActivate`. The chevron stays `aria-hidden` and out of the tab\n * order in both modes; keyboard expansion is Left/Right either way.\n *\n * Collapsing is the one thing that can move focus without a key or a click on\n * the target row: when the active row leaves `visibleItems`, the first visible\n * row becomes the roving stop and `onActiveIdChange` is called with it. If the\n * removed row held focus, or was the last row the tree saw focused, focus moves\n * to that same row; if it had no focus, only the roving stop moves. Focus that\n * has already gone to a control outside the tree is never pulled back: the tree\n * forgets its last focused row when focus moves to an element outside it, and\n * the roving stop alone moves if that control still has focus when the row is\n * hidden. Focus the tree has asked for but not yet moved (a queued recovery, or a\n * keyboard move to a row the host has not mounted) is withdrawn when focus lands\n * outside the tree, and is checked again when a row mounts. This is the same in\n * both `disclosure` modes and for every way a host collapses a row.\n */\nexport function Tree(props: TreeProps) {\n const [local, rest] = splitProps(props, [\n 'class',\n 'visibleItems',\n 'activeId',\n 'onActiveIdChange',\n 'onExpand',\n 'disclosure',\n 'guides',\n 'onActivate',\n 'onSelectItem',\n 'onRequestReveal',\n 'onRowSizeChange',\n 'selectionMode',\n 'typeaheadLabel',\n 'children',\n ])\n\n const index = createMemo(() => indexTreeItems(local.visibleItems))\n const effectiveActiveId = createMemo(() => {\n const candidate = local.activeId\n const visible = index()\n return candidate !== null && visible.byId.has(candidate) ? candidate : (visible.ids[0] ?? null)\n })\n const idPrefix = `tree-${createUniqueId()}`\n const rows = new Map<string, HTMLDivElement>()\n const rowIdsByElement = new WeakMap<HTMLDivElement, string>()\n let pendingFocusId: string | null = null\n let pendingFocusGuard: ((event: FocusEvent) => void) | undefined\n let requestedRevealId: string | null = null\n let focusedId: string | null = null\n let disposed = false\n const isInsideTreeRow = (element: Element) => {\n const row = element.closest('[role=\"treeitem\"]')\n return row instanceof HTMLDivElement && rowIdsByElement.has(row)\n }\n // True when a focusable control outside this tree owns focus. Nothing focused\n // (`body`) is not outside: that is where focus falls when a focused row is removed.\n const focusIsOutsideTree = () => {\n if (typeof document === 'undefined') return false\n const active = document.activeElement\n return (\n active instanceof Element &&\n active !== document.body &&\n active !== document.documentElement &&\n !isInsideTreeRow(active)\n )\n }\n // Rows are only observed for a host that reads their sizes (a virtualiser); an\n // observer per tree otherwise measures every row on every mount for nothing.\n const rowSizeObserver =\n typeof ResizeObserver === 'undefined' || !local.onRowSizeChange\n ? undefined\n : new ResizeObserver((entries) => {\n if (disposed) return\n for (const entry of entries) {\n const id = rowIdsByElement.get(entry.target as HTMLDivElement)\n const blockSize =\n entry.borderBoxSize[0]?.blockSize ?? (entry.target as HTMLElement).offsetHeight\n if (id !== undefined && Number.isFinite(blockSize) && blockSize > 0)\n local.onRowSizeChange?.(id, blockSize)\n }\n })\n\n // Focus the tree has asked for but not yet moved (a microtask away, or waiting for a\n // virtualised row to mount) is only a request. While one is pending, focus arriving\n // on a control outside the tree withdraws it, so a row mounting later cannot take\n // focus back from a control the user, or the host, has since chosen.\n const setPendingFocus = (id: string | null) => {\n pendingFocusId = id\n if (typeof document === 'undefined') return\n if (id === null) {\n if (pendingFocusGuard) document.removeEventListener('focusin', pendingFocusGuard, true)\n pendingFocusGuard = undefined\n } else if (!pendingFocusGuard) {\n pendingFocusGuard = (event) => {\n if (event.target instanceof Element && !isInsideTreeRow(event.target)) cancelPendingFocus()\n }\n document.addEventListener('focusin', pendingFocusGuard, true)\n }\n }\n // Withdrawing a request also drops the memory of the row it was recovering for:\n // nothing is left to recover.\n const cancelPendingFocus = () => {\n setPendingFocus(null)\n focusedId = null\n }\n\n let typed = ''\n let typedTimer: ReturnType<typeof setTimeout> | undefined\n\n onCleanup(() => {\n disposed = true\n setPendingFocus(null)\n rowSizeObserver?.disconnect()\n clearTimeout(typedTimer)\n })\n\n const requestReveal = (id: string) => {\n if (requestedRevealId === id) return\n requestedRevealId = id\n local.onRequestReveal?.(id)\n }\n\n const focusWhenMounted = (id: string) => {\n queueMicrotask(() => {\n if (pendingFocusId !== id || effectiveActiveId() !== id) return\n const row = rows.get(id)\n if (!row || typeof document === 'undefined') return\n // Ownership is checked when focus would move, not when it was requested: a\n // control outside the tree may have taken focus since, and keeps it.\n if (focusIsOutsideTree()) {\n cancelPendingFocus()\n return\n }\n row.focus()\n if (document.activeElement === row) setPendingFocus(null)\n })\n }\n\n const focusItem = (id: string) => {\n setPendingFocus(id)\n local.onActiveIdChange(id)\n if (rows.has(id)) requestedRevealId = null\n else requestReveal(id)\n focusWhenMounted(id)\n }\n\n const context: TreeContextValue = {\n idPrefix,\n activeId: effectiveActiveId,\n isActive: createSelector(effectiveActiveId),\n index,\n register: (id, element) => {\n rows.set(id, element)\n rowIdsByElement.set(element, id)\n rowSizeObserver?.observe(element)\n if (requestedRevealId === id) requestedRevealId = null\n if (pendingFocusId === id) focusWhenMounted(id)\n },\n unregister: (id, element) => {\n if (rows.get(id) !== element) return\n const focusWasInside =\n !disposed &&\n Boolean(\n element && typeof document !== 'undefined' && element.contains(document.activeElement)\n )\n rows.delete(id)\n if (element) {\n rowIdsByElement.delete(element)\n rowSizeObserver?.unobserve(element)\n }\n if (requestedRevealId === id) requestedRevealId = null\n if (focusWasInside) {\n queueMicrotask(() => {\n const fallbackId = effectiveActiveId()\n if (disposed || fallbackId === null || pendingFocusId === fallbackId) return\n // Focus fell out of the removed row, but it may have been given to a control\n // outside the tree before this ran. Only nothing-focused (body) recovers.\n if (focusIsOutsideTree()) {\n focusedId = null\n return\n }\n focusItem(fallbackId)\n })\n }\n },\n focusItem,\n noteFocus: (id) => {\n focusedId = id\n },\n noteBlur: (next) => {\n // Focus moving to an element outside this tree ends the memory of the last\n // focused row and withdraws any focus the tree was still waiting to give a\n // row. A null target (focus to nothing, or the window losing focus) is\n // ambiguous, so both stay for the recovery below.\n if (next instanceof Element && !isInsideTreeRow(next)) cancelPendingFocus()\n },\n activate: (id, event) => local.onActivate?.(id, event),\n expand: (id, expanded) => local.onExpand?.(id, expanded),\n disclosure: () => local.disclosure ?? 'row',\n guides: () => local.guides ?? false,\n onActiveIdChange: (id) => local.onActiveIdChange(id),\n }\n\n // A filtered, collapsed-away or removed active ID falls back to the first\n // visible item. This keeps one treeitem in the sequential tab order while\n // notifying the host.\n createEffect(() => {\n const activeId = effectiveActiveId()\n if (activeId === null) return\n // If the projection removes the last row that took focus (a host filter, or\n // an ancestor collapsing), move focus to the same fallback that now owns the\n // roving tab stop, unless a control outside the tree has focus: that control\n // keeps it, and only the roving stop moves.\n if (focusedId !== null && !index().byId.has(focusedId) && pendingFocusId !== activeId) {\n if (focusIsOutsideTree()) {\n focusedId = null\n if (local.activeId !== activeId) local.onActiveIdChange(activeId)\n } else {\n focusItem(activeId)\n }\n } else if (local.activeId !== activeId) {\n local.onActiveIdChange(activeId)\n }\n // Preserve the active row in a caller-owned virtual window, including when\n // the pane mounts with its saved active row outside the initial render range.\n if (!rows.has(activeId)) requestReveal(activeId)\n if (pendingFocusId === activeId) focusWhenMounted(activeId)\n })\n\n const typeahead = (event: KeyboardEvent) => {\n const label = local.typeaheadLabel\n if (\n !label ||\n event.ctrlKey ||\n event.metaKey ||\n event.altKey ||\n event.key.length !== 1 ||\n event.key === ' '\n )\n return\n typed += event.key\n clearTimeout(typedTimer)\n typedTimer = setTimeout(() => (typed = ''), 700)\n const { ids, indexById } = index()\n const active = local.activeId === null ? -1 : (indexById.get(local.activeId) ?? -1)\n const target = ids[typeaheadIndex(ids.map(label), active, typed)]\n if (target === undefined) return\n event.preventDefault()\n focusItem(target)\n }\n\n const handleKeyDown: JSX.EventHandler<HTMLDivElement, KeyboardEvent> = (event) => {\n if (event.defaultPrevented || isActionTarget(event.target, event.currentTarget)) return\n\n const action = treeNavigationAction(index(), effectiveActiveId(), event.key)\n if (!action) {\n typeahead(event)\n return\n }\n event.preventDefault()\n\n switch (action.type) {\n case 'focus':\n focusItem(action.id)\n break\n case 'expand':\n local.onExpand?.(action.id, action.expanded)\n break\n case 'activate':\n local.onActivate?.(action.id, event)\n break\n case 'select':\n local.onSelectItem?.(action.id, event)\n break\n }\n }\n\n return (\n <TreeContext.Provider value={context}>\n <div\n {...rest}\n role=\"tree\"\n aria-multiselectable={local.selectionMode === 'multiple' ? 'true' : undefined}\n data-slot=\"tree\"\n class={cn(\n /* A virtualized host remounts rows as it scrolls; scroll anchoring\n would latch onto the focused row and fight the scrollbar. */\n 'flex min-w-0 flex-col [overflow-anchor:none]',\n local.class\n )}\n onKeyDown={handleKeyDown}\n >\n {local.children}\n </div>\n </TreeContext.Provider>\n )\n}\n\nexport type TreeRowProps = Omit<\n ComponentProps<'div'>,\n | 'children'\n | 'role'\n | 'tabIndex'\n | 'onClick'\n | 'onFocus'\n | 'onDoubleClick'\n | 'style'\n | 'aria-level'\n | 'aria-expanded'\n | 'aria-selected'\n | 'aria-posinset'\n | 'aria-setsize'\n> & {\n item: TreeItemDescriptor\n /** Host-owned selection state; omitted for non-selectable trees. */\n selected?: boolean\n leading?: JSX.Element\n trailing?: JSX.Element\n children: JSX.Element\n onDoubleClick?: (id: string, event: MouseEvent & { currentTarget: HTMLDivElement }) => void\n}\n\n/**\n * TreeRow.\n *\n * Keeps the donor's disclosure marker, leading file/folder affordance, primary\n * label and trailing-action hierarchy while replacing the donor's button and\n * runtime callbacks with a shared treeitem and host-owned slots/actions.\n *\n * With `Tree`'s `disclosure=\"marker\"` the chevron of an expandable row is a\n * separate pointer target (`data-slot=\"tree-row-disclosure\"`) that only calls\n * `onExpand`. It is not focusable and has no role: the row remains the single\n * focus stop, Enter and Space still activate and select, and Left/Right still\n * expand and collapse, so the marker adds a pointer path and nothing else.\n * Pressing it does not move focus or the roving stop to its row; if the toggle\n * hides the focused row, `Tree` recovers focus as it does for any collapse (see\n * the `Tree` comment).\n */\nexport function TreeRow(props: TreeRowProps) {\n const tree = useTreeContext()\n const [local, rest] = splitProps(props, [\n 'class',\n 'item',\n 'selected',\n 'leading',\n 'trailing',\n 'children',\n 'onDoubleClick',\n 'ref',\n ])\n\n let row: HTMLDivElement | undefined\n let registeredId: string | undefined\n const id = () => local.item.id\n // Each slot is a JSX getter that builds its subtree per read, so it is read once\n // into a memo. The memo holds the slot as given (not resolved), so the wrapper\n // span renders exactly when it did before: whenever a slot is passed, even one\n // whose content is currently empty, which keeps the row's spacing stable.\n const leading = createMemo(() => local.leading)\n const trailing = createMemo(() => local.trailing)\n\n const handleFocusOut = (event: FocusEvent) => tree.noteBlur(event.relatedTarget)\n\n onCleanup(() => {\n row?.removeEventListener('focusout', handleFocusOut)\n tree.unregister(registeredId ?? id(), row)\n })\n\n const setRef = (element: HTMLDivElement) => {\n row = element\n registeredId = id()\n tree.register(registeredId, element)\n // A listener, not an `onFocusOut` prop, so a host's own handler is untouched.\n element.addEventListener('focusout', handleFocusOut)\n }\n\n createEffect(() => {\n const nextId = id()\n if (!row || registeredId === nextId) return\n if (registeredId !== undefined) tree.unregister(registeredId, row)\n registeredId = nextId\n tree.register(nextId, row)\n })\n\n const handleFocus = () => {\n tree.noteFocus(id())\n if (tree.activeId() !== id()) tree.onActiveIdChange(id())\n }\n\n const handleClick: JSX.EventHandler<HTMLDivElement, MouseEvent> = (event) => {\n if (isActionTarget(event.target, event.currentTarget)) return\n tree.focusItem(id())\n tree.activate(id(), event)\n }\n\n const handleDoubleClick: JSX.EventHandler<HTMLDivElement, MouseEvent> = (event) => {\n if (isActionTarget(event.target, event.currentTarget)) return\n local.onDoubleClick?.(id(), event)\n }\n\n const position = () => tree.index().positionById.get(id())\n // Only an expandable row has a chevron to press; a leaf's marker slot stays\n // part of the row so a click there is an ordinary row click.\n const markerTarget = () => tree.disclosure() === 'marker' && local.item.expandable\n\n const handleMarkerClick: JSX.EventHandler<HTMLSpanElement, MouseEvent> = (event) => {\n // The row's own handler would focus and activate the row.\n event.stopPropagation()\n tree.expand(id(), !local.item.expanded)\n }\n return (\n <div\n {...rest}\n ref={composeRefs(setRef, () => local.ref)}\n id={rest.id ?? `${tree.idPrefix}-item-${encodeURIComponent(id())}`}\n role=\"treeitem\"\n aria-level={local.item.level}\n aria-expanded={local.item.expandable ? (local.item.expanded ? 'true' : 'false') : undefined}\n aria-selected={local.selected === undefined ? undefined : local.selected ? 'true' : 'false'}\n aria-posinset={position()?.position}\n aria-setsize={position()?.setSize}\n tabIndex={tree.isActive(id()) ? 0 : -1}\n data-tree-id={id()}\n data-active={tree.isActive(id()) ? '' : undefined}\n data-selected={local.selected ? '' : undefined}\n data-expanded={local.item.expandable ? String(local.item.expanded) : undefined}\n class={cn(\n 'group/tree-row flex min-h-row-sm w-full min-w-0 items-center gap-1.5 rounded-md pe-1.5 text-left text-sm outline-none transition-colors',\n 'focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-primary-subtle',\n {\n // Guide lines are positioned against the row; without them it keeps its original classes.\n relative: tree.guides(),\n 'bg-primary-subtle text-foreground': local.selected,\n 'hover:bg-surface-hover': !local.selected,\n },\n local.class\n )}\n style={{ 'padding-inline-start': `${rowInset(local.item.level)}px` }}\n onFocus={handleFocus}\n onClick={handleClick}\n onDblClick={handleDoubleClick}\n >\n <Show when={tree.guides() && local.item.level > 1}>\n <For each={Array.from({ length: local.item.level - 1 }, (_, index) => index)}>\n {(index) => (\n <span\n aria-hidden=\"true\"\n data-slot=\"tree-row-guide\"\n class=\"pointer-events-none absolute inset-y-0 w-px bg-border\"\n style={{ 'inset-inline-start': `${rowInset(index + 1) + GUIDE_CENTER}px` }}\n />\n )}\n </For>\n </Show>\n <span\n data-slot={markerTarget() ? 'tree-row-disclosure' : undefined}\n class={cn(\n 'flex',\n !markerTarget() && 'size-3.5',\n 'shrink-0 items-center justify-center text-muted-foreground',\n /* The glyph stays 14px wide but the target is not: it takes the row's full\n height (a flex child's `self-stretch`, so it follows row density and a\n tall trailing control) and the pseudo-element widens it to 26px, which\n stops at the row's own padding and gap, never over the icon or label. */\n markerTarget() &&\n 'relative w-3.5 cursor-pointer self-stretch hover:text-foreground after:absolute after:inset-y-0 after:-inset-x-1.5'\n )}\n onMouseDown={markerTarget() ? handleMarkerMouseDown : undefined}\n onClick={markerTarget() ? handleMarkerClick : undefined}\n onDblClick={markerTarget() ? handleMarkerDoubleClick : undefined}\n >\n {local.item.expandable ? (\n <ChevronRight\n aria-hidden=\"true\"\n class={cn('size-3.5 transition-transform', local.item.expanded && 'rotate-90')}\n />\n ) : null}\n </span>\n <Show when={leading()}>\n {(slot) => (\n <span class=\"flex size-4 shrink-0 items-center justify-center [&_svg]:size-4\">\n {slot()}\n </span>\n )}\n </Show>\n <span class=\"min-w-0 flex-1 truncate\">{local.children}</span>\n <Show when={trailing()}>\n {(slot) => (\n <span class=\"ms-auto flex shrink-0 items-center gap-1 text-muted-foreground\">\n {slot()}\n </span>\n )}\n </Show>\n </div>\n )\n}\n\n/**\n * TreeRowActions.\n *\n * Row-level commands (rename, copy, delete) that stay out of the way until the\n * row is hovered or holds focus, so a long tree reads as names rather than a\n * wall of buttons. Put it in `TreeRow`'s `trailing` slot beside any status that\n * must stay visible. `pinned` keeps the actions shown, e.g. while a destructive\n * action waits for its confirming second press.\n */\nexport function TreeRowActions(props: ComponentProps<'span'> & { pinned?: boolean }) {\n const [local, rest] = splitProps(props, ['class', 'pinned'])\n return (\n <span\n data-slot=\"tree-row-actions\"\n data-pinned={local.pinned ? '' : undefined}\n class={cn(\n 'flex shrink-0 items-center gap-1 opacity-0 transition-opacity ease-out',\n 'group-hover/tree-row:opacity-100 group-focus-within/tree-row:opacity-100 data-pinned:opacity-100',\n local.class\n )}\n {...rest}\n />\n )\n}\n\n// Pressing the chevron must not move focus to its row: a mousedown on a\n// non-focusable child would otherwise focus the row, making it the roving stop\n// (and notifying `onActiveIdChange`) for what is a disclosure toggle, not a\n// selection. The press itself leaves focus where it was, so Left/Right keep\n// acting on the row the keyboard user left off at. It cannot stop the toggle\n// from hiding that row; `Tree` then recovers focus onto the first visible row.\nconst handleMarkerMouseDown: JSX.EventHandler<HTMLSpanElement, MouseEvent> = (event) =>\n event.preventDefault()\n// A double-click is two toggles; it must not also reach `onDoubleClick`\n// (rename, open) as though the row itself had been double-clicked.\nconst handleMarkerDoubleClick: JSX.EventHandler<HTMLSpanElement, MouseEvent> = (event) =>\n event.stopPropagation()\n\n/** The inline-start padding of a row at a one-based `level`, in px. */\nfunction rowInset(level: number): number {\n return 6 + Math.max(0, level - 1) * 12\n}\n/** Half the 14px chevron: a level's guide line runs down the middle of its parent's chevron. */\nconst GUIDE_CENTER = 7\n\nfunction isActionTarget(target: EventTarget | null, currentTarget: HTMLElement): boolean {\n if (!(target instanceof Element) || target === currentTarget) return false\n return Boolean(\n target.closest(\n 'a, button, input, textarea, select, [contenteditable=\"true\"], [role=\"button\"], [data-tree-keyboard-stop]'\n )\n )\n}\n\nfunction composeRefs(\n internal: (element: HTMLDivElement) => void,\n external: () => ComponentProps<'div'>['ref']\n): (element: HTMLDivElement) => void {\n return (element) => {\n internal(element)\n const ref = external()\n if (typeof ref === 'function') ref(element)\n }\n}\n\nexport type { TreeItemDescriptor } from './tree-navigation'\n"],"mappings":";;;;;;;;;;;;;AAyBA,IAAMA,iBAAegB,SAASf,YAAkB;AAoBhD,IAAMoC,cAAcnC,cAAgC;AAEpD,SAASoC,iBAAiB;CACxB,MAAMC,OAAO5B,WAAW0B,WAAW;CACnC,IAAI,CAACE,MAAM,MAAM,IAAIC,MAAM,8CAA8C;CACzE,OAAOD;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkGA,SAAgBa,KAAKC,OAAkB;CACrC,MAAM,CAACC,OAAOC,QAAQ7C,WAAW2C,OAAO;EACtC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CAAU,CACX;CAED,MAAMhC,QAAQjB,iBAAiBS,eAAeyC,MAAMb,YAAY,CAAC;CACjE,MAAMe,oBAAoBpD,iBAAiB;EACzC,MAAMqD,YAAYH,MAAMpC;EACxB,MAAMwC,UAAUrC,MAAM;EACtB,OAAOoC,cAAc,QAAQC,QAAQC,KAAKC,IAAIH,SAAS,IAAIA,YAAaC,QAAQG,IAAI,MAAM;CAC5F,CAAC;CACD,MAAM5C,WAAW,QAAQX,eAAe;CACxC,MAAMwD,uBAAO,IAAIC,IAA4B;CAC7C,MAAMC,kCAAkB,IAAIC,QAAgC;CAC5D,IAAIC,iBAAgC;CACpC,IAAIC;CACJ,IAAIC,oBAAmC;CACvC,IAAIC,YAA2B;CAC/B,IAAIC,WAAW;CACf,MAAMC,mBAAmBhD,YAAqB;EAC5C,MAAMiD,MAAMjD,QAAQkD,QAAQ,qBAAmB;EAC/C,OAAOD,eAAehD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C,kBAAkBnC,YAAYmC,WAAWwC,eAAe,OAAO;CACrE,OAAOlB,QACLtB,OAAOb,QACL,8GACF,CACF;AACF;AAEA,SAAS4F,YACP6C,UACAC,UACmC;CACnC,QAAQ5L,YAAY;EAClB2L,SAAS3L,OAAO;EAChB,MAAM+I,MAAM6C,SAAS;EACrB,IAAI,OAAO7C,QAAQ,YAAYA,IAAI/I,OAAO;CAC5C;AACF;AAE2D6L,eAAA;CAAA;CAAA;CAAA;AAAA,CAAA"}
|
|
1
|
+
{"version":3,"file":"tree.js","names":["ChevronRight","LucideChevronRight","createContext","createEffect","createMemo","createSelector","createUniqueId","For","onCleanup","Show","splitProps","useContext","cn","indexTreeItems","treeNavigationAction","typeaheadIndex","fastIcon","idPrefix","activeId","isActive","id","index","register","element","HTMLDivElement","unregister","focusItem","noteFocus","noteBlur","next","activate","event","expand","expanded","disclosure","guides","onActiveIdChange","TreeContext","useTreeContext","tree","Error","visibleItems","onExpand","onActivate","onSelectItem","onRequestReveal","onRowSizeChange","blockSize","selectionMode","typeaheadLabel","children","Element","Tree","props","local","rest","effectiveActiveId","candidate","visible","byId","has","ids","rows","Map","rowIdsByElement","WeakMap","pendingFocusId","pendingFocusGuard","requestedRevealId","focusedId","disposed","isInsideTreeRow","row","closest","focusIsOutsideTree","document","active","activeElement","body","documentElement","rowSizeObserver","ResizeObserver","undefined","entries","entry","get","target","borderBoxSize","offsetHeight","Number","isFinite","setPendingFocus","removeEventListener","cancelPendingFocus","addEventListener","typed","typedTimer","setTimeout","disconnect","clearTimeout","requestReveal","focusWhenMounted","queueMicrotask","focus","context","set","observe","focusWasInside","Boolean","contains","delete","unobserve","fallbackId","typeahead","label","ctrlKey","metaKey","altKey","key","length","indexById","map","preventDefault","handleKeyDown","defaultPrevented","isActionTarget","currentTarget","action","type","_$createComponent","Provider","value","_el$","_tmpl$","_$spread","_$mergeProps","class","_$insert","item","selected","leading","trailing","onDoubleClick","TreeRow","registeredId","handleFocusOut","relatedTarget","setRef","nextId","handleFocus","handleClick","handleDoubleClick","position","positionById","markerTarget","expandable","handleMarkerClick","stopPropagation","_el$2","_tmpl$2","_el$3","firstChild","_el$4","nextSibling","_ref$","composeRefs","ref","_$use","encodeURIComponent","level","_$memo","setSize","tabIndex","String","relative","style","rowInset","when","each","Array","from","_","_el$5","_tmpl$3","_$effect","_$p","_$setStyleProperty","GUIDE_CENTER","_$addEventListener","handleMarkerDoubleClick","handleMarkerMouseDown","_c$","slot","_el$6","_tmpl$4","_el$7","_tmpl$5","_p$","_v$","_v$2","e","_$setAttribute","t","_$className","TreeRowActions","pinned","_el$8","_tmpl$6","topId","onSelect","maxRows","TreeStickyHeader","ancestors","treeStickyAncestors","slice","_el$9","_tmpl$8","_el$0","_tmpl$7","_el$1","_tmpl$9","_el$10","$$click","$$mousedown","_v$3","_v$4","chain","parentId","parent","push","toReversed","Math","max","internal","external","_$delegateEvents"],"sources":["../../../../src/components/composites/tree/tree.tsx"],"sourcesContent":["import type { ComponentProps, JSX } from 'solid-js'\nimport { ChevronRight as LucideChevronRight } from 'lucide-solid'\nimport {\n createContext,\n createEffect,\n createMemo,\n createSelector,\n createUniqueId,\n For,\n onCleanup,\n Show,\n splitProps,\n useContext,\n} from 'solid-js'\nimport { cn } from '#lib/utils'\nimport {\n indexTreeItems,\n treeNavigationAction,\n typeaheadIndex,\n type TreeItemDescriptor,\n type TreeNavigationIndex,\n} from './tree-navigation'\nimport { fastIcon } from '#lib/fast-icon'\n\n// lucide icons drawn from a cloned template (see fastIcon).\nconst ChevronRight = fastIcon(LucideChevronRight)\n\ntype TreeContextValue = {\n idPrefix: string\n activeId: () => string | null\n /** O(1) per change: only the rows whose answer flips re-run, not every row. */\n isActive: (id: string) => boolean\n index: () => TreeNavigationIndex\n register: (id: string, element: HTMLDivElement) => void\n unregister: (id: string, element: HTMLDivElement | undefined) => void\n focusItem: (id: string) => void\n noteFocus: (id: string) => void\n noteBlur: (next: EventTarget | null) => void\n activate: (id: string, event: Event) => void\n expand: (id: string, expanded: boolean) => void\n disclosure: () => TreeDisclosure\n guides: () => boolean\n onActiveIdChange: (id: string) => void\n}\n\nconst TreeContext = createContext<TreeContextValue>()\n\nfunction useTreeContext() {\n const tree = useContext(TreeContext)\n if (!tree) throw new Error('[adea-ui]: TreeRow must be used inside Tree.')\n return tree\n}\n\n/**\n * Who owns the pointer on a row's disclosure chevron.\n *\n * - `row` (default): the chevron is decoration; a click anywhere on the row,\n * chevron included, is a row activation. This is the file-explorer\n * convention, where the host's `onActivate` toggles a folder.\n * - `marker`: the chevron of an expandable row is its own pointer target. It\n * calls `onExpand(id, !expanded)` and nothing else; the rest of the row still\n * activates. For trees where expanding and selecting are independent (a\n * source list that selects a source and separately reveals its details).\n */\nexport type TreeDisclosure = 'row' | 'marker'\n\ntype TreeAccessibleName =\n | { 'aria-label': string; 'aria-labelledby'?: string }\n | { 'aria-label'?: string; 'aria-labelledby': string }\n\nexport type TreeProps = Omit<\n ComponentProps<'div'>,\n 'children' | 'role' | 'tabIndex' | 'onKeyDown' | 'aria-label' | 'aria-labelledby'\n> &\n TreeAccessibleName & {\n /** Complete, ordered projection of currently visible (expanded) items. */\n visibleItems: readonly TreeItemDescriptor[]\n /** The host-owned identity of the row that currently owns roving focus. */\n activeId: string | null\n /**\n * Called when keyboard or pointer navigation changes the active row, and when\n * the active row leaves `visibleItems` (collapsed away, filtered out) and the\n * first visible row takes over as the roving stop.\n */\n onActiveIdChange: (id: string) => void\n /** Called for Left/Right expand and collapse requests. */\n onExpand?: (id: string, expanded: boolean) => void\n /**\n * Opt-in pointer behaviour of the disclosure chevron; see {@link TreeDisclosure}.\n * Keyboard behaviour is identical in both modes: Left/Right expand and collapse.\n */\n disclosure?: TreeDisclosure\n /**\n * Draw a vertical guide line down each ancestor level of a nested row, so a\n * group of children reads as belonging to its parent. Off by default: a flat\n * list or a dense file explorer carries its own rhythm.\n */\n guides?: boolean\n /** Called for Enter or pointer activation. Domain action stays host-owned. */\n onActivate?: (id: string, event: Event) => void\n /** Called for Space selection. Selection state stays host-owned. */\n onSelectItem?: (id: string, event: Event) => void\n /** Ask the host window to mount/reveal an item before focus moves to it. */\n onRequestReveal?: (id: string) => void\n /** Report a mounted row's border-box block size in CSS pixels for host range math. */\n onRowSizeChange?: (id: string, blockSize: number) => void\n /** Declares a multi-select tree to assistive technology. */\n selectionMode?: 'single' | 'multiple'\n /**\n * The text a row is found by when the reader types its first letters. Supply\n * it to turn on typeahead: a typed prefix moves focus to the next visible row\n * whose label starts with it, revealing an unmounted row first.\n */\n typeaheadLabel?: (id: string) => string\n children?: JSX.Element\n }\n\n/**\n * Tree.\n *\n * Supplies semantic and keyboard behavior for a tree whose host owns the\n * visible projection, filesystem state, row window and domain actions. The\n * mounted children can be a small virtualized window; `visibleItems` remains\n * the complete ordered projection so keyboard movement and sibling positions\n * do not depend on which rows currently exist in the DOM.\n *\n * Kobalte 0.13.14 has no Tree primitive, so this component implements the\n * WAI-ARIA tree row navigation contract and leaves product state to callbacks.\n *\n * By default the disclosure chevron is decoration and a click anywhere on a\n * row activates it, so a file explorer can toggle a folder from `onActivate`.\n * Reach for `disclosure=\"marker\"` when expanding and selecting are separate\n * decisions: the chevron then calls only `onExpand`, and the rest of the row\n * calls only `onActivate`. The chevron stays `aria-hidden` and out of the tab\n * order in both modes; keyboard expansion is Left/Right either way.\n *\n * Collapsing is the one thing that can move focus without a key or a click on\n * the target row: when the active row leaves `visibleItems`, the first visible\n * row becomes the roving stop and `onActiveIdChange` is called with it. If the\n * removed row held focus, or was the last row the tree saw focused, focus moves\n * to that same row; if it had no focus, only the roving stop moves. Focus that\n * has already gone to a control outside the tree is never pulled back: the tree\n * forgets its last focused row when focus moves to an element outside it, and\n * the roving stop alone moves if that control still has focus when the row is\n * hidden. Focus the tree has asked for but not yet moved (a queued recovery, or a\n * keyboard move to a row the host has not mounted) is withdrawn when focus lands\n * outside the tree, and is checked again when a row mounts. This is the same in\n * both `disclosure` modes and for every way a host collapses a row.\n */\nexport function Tree(props: TreeProps) {\n const [local, rest] = splitProps(props, [\n 'class',\n 'visibleItems',\n 'activeId',\n 'onActiveIdChange',\n 'onExpand',\n 'disclosure',\n 'guides',\n 'onActivate',\n 'onSelectItem',\n 'onRequestReveal',\n 'onRowSizeChange',\n 'selectionMode',\n 'typeaheadLabel',\n 'children',\n ])\n\n const index = createMemo(() => indexTreeItems(local.visibleItems))\n const effectiveActiveId = createMemo(() => {\n const candidate = local.activeId\n const visible = index()\n return candidate !== null && visible.byId.has(candidate) ? candidate : (visible.ids[0] ?? null)\n })\n const idPrefix = `tree-${createUniqueId()}`\n const rows = new Map<string, HTMLDivElement>()\n const rowIdsByElement = new WeakMap<HTMLDivElement, string>()\n let pendingFocusId: string | null = null\n let pendingFocusGuard: ((event: FocusEvent) => void) | undefined\n let requestedRevealId: string | null = null\n let focusedId: string | null = null\n let disposed = false\n const isInsideTreeRow = (element: Element) => {\n const row = element.closest('[role=\"treeitem\"]')\n return row instanceof HTMLDivElement && rowIdsByElement.has(row)\n }\n // True when a focusable control outside this tree owns focus. Nothing focused\n // (`body`) is not outside: that is where focus falls when a focused row is removed.\n const focusIsOutsideTree = () => {\n if (typeof document === 'undefined') return false\n const active = document.activeElement\n return (\n active instanceof Element &&\n active !== document.body &&\n active !== document.documentElement &&\n !isInsideTreeRow(active)\n )\n }\n // Rows are only observed for a host that reads their sizes (a virtualiser); an\n // observer per tree otherwise measures every row on every mount for nothing.\n const rowSizeObserver =\n typeof ResizeObserver === 'undefined' || !local.onRowSizeChange\n ? undefined\n : new ResizeObserver((entries) => {\n if (disposed) return\n for (const entry of entries) {\n const id = rowIdsByElement.get(entry.target as HTMLDivElement)\n const blockSize =\n entry.borderBoxSize[0]?.blockSize ?? (entry.target as HTMLElement).offsetHeight\n if (id !== undefined && Number.isFinite(blockSize) && blockSize > 0)\n local.onRowSizeChange?.(id, blockSize)\n }\n })\n\n // Focus the tree has asked for but not yet moved (a microtask away, or waiting for a\n // virtualised row to mount) is only a request. While one is pending, focus arriving\n // on a control outside the tree withdraws it, so a row mounting later cannot take\n // focus back from a control the user, or the host, has since chosen.\n const setPendingFocus = (id: string | null) => {\n pendingFocusId = id\n if (typeof document === 'undefined') return\n if (id === null) {\n if (pendingFocusGuard) document.removeEventListener('focusin', pendingFocusGuard, true)\n pendingFocusGuard = undefined\n } else if (!pendingFocusGuard) {\n pendingFocusGuard = (event) => {\n if (event.target instanceof Element && !isInsideTreeRow(event.target)) cancelPendingFocus()\n }\n document.addEventListener('focusin', pendingFocusGuard, true)\n }\n }\n // Withdrawing a request also drops the memory of the row it was recovering for:\n // nothing is left to recover.\n const cancelPendingFocus = () => {\n setPendingFocus(null)\n focusedId = null\n }\n\n let typed = ''\n let typedTimer: ReturnType<typeof setTimeout> | undefined\n\n onCleanup(() => {\n disposed = true\n setPendingFocus(null)\n rowSizeObserver?.disconnect()\n clearTimeout(typedTimer)\n })\n\n const requestReveal = (id: string) => {\n if (requestedRevealId === id) return\n requestedRevealId = id\n local.onRequestReveal?.(id)\n }\n\n const focusWhenMounted = (id: string) => {\n queueMicrotask(() => {\n if (pendingFocusId !== id || effectiveActiveId() !== id) return\n const row = rows.get(id)\n if (!row || typeof document === 'undefined') return\n // Ownership is checked when focus would move, not when it was requested: a\n // control outside the tree may have taken focus since, and keeps it.\n if (focusIsOutsideTree()) {\n cancelPendingFocus()\n return\n }\n row.focus()\n if (document.activeElement === row) setPendingFocus(null)\n })\n }\n\n const focusItem = (id: string) => {\n setPendingFocus(id)\n local.onActiveIdChange(id)\n if (rows.has(id)) requestedRevealId = null\n else requestReveal(id)\n focusWhenMounted(id)\n }\n\n const context: TreeContextValue = {\n idPrefix,\n activeId: effectiveActiveId,\n isActive: createSelector(effectiveActiveId),\n index,\n register: (id, element) => {\n rows.set(id, element)\n rowIdsByElement.set(element, id)\n rowSizeObserver?.observe(element)\n if (requestedRevealId === id) requestedRevealId = null\n if (pendingFocusId === id) focusWhenMounted(id)\n },\n unregister: (id, element) => {\n if (rows.get(id) !== element) return\n const focusWasInside =\n !disposed &&\n Boolean(\n element && typeof document !== 'undefined' && element.contains(document.activeElement)\n )\n rows.delete(id)\n if (element) {\n rowIdsByElement.delete(element)\n rowSizeObserver?.unobserve(element)\n }\n if (requestedRevealId === id) requestedRevealId = null\n if (focusWasInside) {\n queueMicrotask(() => {\n const fallbackId = effectiveActiveId()\n if (disposed || fallbackId === null || pendingFocusId === fallbackId) return\n // Focus fell out of the removed row, but it may have been given to a control\n // outside the tree before this ran. Only nothing-focused (body) recovers.\n if (focusIsOutsideTree()) {\n focusedId = null\n return\n }\n focusItem(fallbackId)\n })\n }\n },\n focusItem,\n noteFocus: (id) => {\n focusedId = id\n },\n noteBlur: (next) => {\n // Focus moving to an element outside this tree ends the memory of the last\n // focused row and withdraws any focus the tree was still waiting to give a\n // row. A null target (focus to nothing, or the window losing focus) is\n // ambiguous, so both stay for the recovery below.\n if (next instanceof Element && !isInsideTreeRow(next)) cancelPendingFocus()\n },\n activate: (id, event) => local.onActivate?.(id, event),\n expand: (id, expanded) => local.onExpand?.(id, expanded),\n disclosure: () => local.disclosure ?? 'row',\n guides: () => local.guides ?? false,\n onActiveIdChange: (id) => local.onActiveIdChange(id),\n }\n\n // A filtered, collapsed-away or removed active ID falls back to the first\n // visible item. This keeps one treeitem in the sequential tab order while\n // notifying the host.\n createEffect(() => {\n const activeId = effectiveActiveId()\n if (activeId === null) return\n // If the projection removes the last row that took focus (a host filter, or\n // an ancestor collapsing), move focus to the same fallback that now owns the\n // roving tab stop, unless a control outside the tree has focus: that control\n // keeps it, and only the roving stop moves.\n if (focusedId !== null && !index().byId.has(focusedId) && pendingFocusId !== activeId) {\n if (focusIsOutsideTree()) {\n focusedId = null\n if (local.activeId !== activeId) local.onActiveIdChange(activeId)\n } else {\n focusItem(activeId)\n }\n } else if (local.activeId !== activeId) {\n local.onActiveIdChange(activeId)\n }\n // Preserve the active row in a caller-owned virtual window, including when\n // the pane mounts with its saved active row outside the initial render range.\n if (!rows.has(activeId)) requestReveal(activeId)\n if (pendingFocusId === activeId) focusWhenMounted(activeId)\n })\n\n const typeahead = (event: KeyboardEvent) => {\n const label = local.typeaheadLabel\n if (\n !label ||\n event.ctrlKey ||\n event.metaKey ||\n event.altKey ||\n event.key.length !== 1 ||\n event.key === ' '\n )\n return\n typed += event.key\n clearTimeout(typedTimer)\n typedTimer = setTimeout(() => (typed = ''), 700)\n const { ids, indexById } = index()\n const active = local.activeId === null ? -1 : (indexById.get(local.activeId) ?? -1)\n const target = ids[typeaheadIndex(ids.map(label), active, typed)]\n if (target === undefined) return\n event.preventDefault()\n focusItem(target)\n }\n\n const handleKeyDown: JSX.EventHandler<HTMLDivElement, KeyboardEvent> = (event) => {\n if (event.defaultPrevented || isActionTarget(event.target, event.currentTarget)) return\n\n const action = treeNavigationAction(index(), effectiveActiveId(), event.key)\n if (!action) {\n typeahead(event)\n return\n }\n event.preventDefault()\n\n switch (action.type) {\n case 'focus':\n focusItem(action.id)\n break\n case 'expand':\n local.onExpand?.(action.id, action.expanded)\n break\n case 'activate':\n local.onActivate?.(action.id, event)\n break\n case 'select':\n local.onSelectItem?.(action.id, event)\n break\n }\n }\n\n return (\n <TreeContext.Provider value={context}>\n <div\n {...rest}\n role=\"tree\"\n aria-multiselectable={local.selectionMode === 'multiple' ? 'true' : undefined}\n data-slot=\"tree\"\n class={cn(\n /* A virtualized host remounts rows as it scrolls; scroll anchoring\n would latch onto the focused row and fight the scrollbar. */\n 'flex min-w-0 flex-col [overflow-anchor:none]',\n local.class\n )}\n onKeyDown={handleKeyDown}\n >\n {local.children}\n </div>\n </TreeContext.Provider>\n )\n}\n\nexport type TreeRowProps = Omit<\n ComponentProps<'div'>,\n | 'children'\n | 'role'\n | 'tabIndex'\n | 'onClick'\n | 'onFocus'\n | 'onDoubleClick'\n | 'style'\n | 'aria-level'\n | 'aria-expanded'\n | 'aria-selected'\n | 'aria-posinset'\n | 'aria-setsize'\n> & {\n item: TreeItemDescriptor\n /** Host-owned selection state; omitted for non-selectable trees. */\n selected?: boolean\n leading?: JSX.Element\n trailing?: JSX.Element\n children: JSX.Element\n onDoubleClick?: (id: string, event: MouseEvent & { currentTarget: HTMLDivElement }) => void\n}\n\n/**\n * TreeRow.\n *\n * Keeps the donor's disclosure marker, leading file/folder affordance, primary\n * label and trailing-action hierarchy while replacing the donor's button and\n * runtime callbacks with a shared treeitem and host-owned slots/actions.\n *\n * With `Tree`'s `disclosure=\"marker\"` the chevron of an expandable row is a\n * separate pointer target (`data-slot=\"tree-row-disclosure\"`) that only calls\n * `onExpand`. It is not focusable and has no role: the row remains the single\n * focus stop, Enter and Space still activate and select, and Left/Right still\n * expand and collapse, so the marker adds a pointer path and nothing else.\n * Pressing it does not move focus or the roving stop to its row; if the toggle\n * hides the focused row, `Tree` recovers focus as it does for any collapse (see\n * the `Tree` comment).\n */\nexport function TreeRow(props: TreeRowProps) {\n const tree = useTreeContext()\n const [local, rest] = splitProps(props, [\n 'class',\n 'item',\n 'selected',\n 'leading',\n 'trailing',\n 'children',\n 'onDoubleClick',\n 'ref',\n ])\n\n let row: HTMLDivElement | undefined\n let registeredId: string | undefined\n const id = () => local.item.id\n // Each slot is a JSX getter that builds its subtree per read, so it is read once\n // into a memo. The memo holds the slot as given (not resolved), so the wrapper\n // span renders exactly when it did before: whenever a slot is passed, even one\n // whose content is currently empty, which keeps the row's spacing stable.\n const leading = createMemo(() => local.leading)\n const trailing = createMemo(() => local.trailing)\n\n const handleFocusOut = (event: FocusEvent) => tree.noteBlur(event.relatedTarget)\n\n onCleanup(() => {\n row?.removeEventListener('focusout', handleFocusOut)\n tree.unregister(registeredId ?? id(), row)\n })\n\n const setRef = (element: HTMLDivElement) => {\n row = element\n registeredId = id()\n tree.register(registeredId, element)\n // A listener, not an `onFocusOut` prop, so a host's own handler is untouched.\n element.addEventListener('focusout', handleFocusOut)\n }\n\n createEffect(() => {\n const nextId = id()\n if (!row || registeredId === nextId) return\n if (registeredId !== undefined) tree.unregister(registeredId, row)\n registeredId = nextId\n tree.register(nextId, row)\n })\n\n const handleFocus = () => {\n tree.noteFocus(id())\n if (tree.activeId() !== id()) tree.onActiveIdChange(id())\n }\n\n const handleClick: JSX.EventHandler<HTMLDivElement, MouseEvent> = (event) => {\n if (isActionTarget(event.target, event.currentTarget)) return\n tree.focusItem(id())\n tree.activate(id(), event)\n }\n\n const handleDoubleClick: JSX.EventHandler<HTMLDivElement, MouseEvent> = (event) => {\n if (isActionTarget(event.target, event.currentTarget)) return\n local.onDoubleClick?.(id(), event)\n }\n\n const position = () => tree.index().positionById.get(id())\n // Only an expandable row has a chevron to press; a leaf's marker slot stays\n // part of the row so a click there is an ordinary row click.\n const markerTarget = () => tree.disclosure() === 'marker' && local.item.expandable\n\n const handleMarkerClick: JSX.EventHandler<HTMLSpanElement, MouseEvent> = (event) => {\n // The row's own handler would focus and activate the row.\n event.stopPropagation()\n tree.expand(id(), !local.item.expanded)\n }\n return (\n <div\n {...rest}\n ref={composeRefs(setRef, () => local.ref)}\n id={rest.id ?? `${tree.idPrefix}-item-${encodeURIComponent(id())}`}\n role=\"treeitem\"\n aria-level={local.item.level}\n aria-expanded={local.item.expandable ? (local.item.expanded ? 'true' : 'false') : undefined}\n aria-selected={local.selected === undefined ? undefined : local.selected ? 'true' : 'false'}\n aria-posinset={position()?.position}\n aria-setsize={position()?.setSize}\n tabIndex={tree.isActive(id()) ? 0 : -1}\n data-tree-id={id()}\n data-active={tree.isActive(id()) ? '' : undefined}\n data-selected={local.selected ? '' : undefined}\n data-expanded={local.item.expandable ? String(local.item.expanded) : undefined}\n class={cn(\n 'group/tree-row flex min-h-row-sm w-full min-w-0 items-center gap-1.5 rounded-md pe-1.5 text-left text-sm outline-none transition-colors',\n 'focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-primary-subtle',\n {\n // Guide lines are positioned against the row; without them it keeps its original classes.\n relative: tree.guides(),\n 'bg-primary-subtle text-foreground': local.selected,\n 'hover:bg-surface-hover': !local.selected,\n },\n local.class\n )}\n style={{ 'padding-inline-start': `${rowInset(local.item.level)}px` }}\n onFocus={handleFocus}\n onClick={handleClick}\n onDblClick={handleDoubleClick}\n >\n <Show when={tree.guides() && local.item.level > 1}>\n <For each={Array.from({ length: local.item.level - 1 }, (_, index) => index)}>\n {(index) => (\n <span\n aria-hidden=\"true\"\n data-slot=\"tree-row-guide\"\n class=\"pointer-events-none absolute inset-y-0 w-px bg-border\"\n style={{ 'inset-inline-start': `${rowInset(index + 1) + GUIDE_CENTER}px` }}\n />\n )}\n </For>\n </Show>\n <span\n data-slot={markerTarget() ? 'tree-row-disclosure' : undefined}\n class={cn(\n 'flex',\n !markerTarget() && 'size-3.5',\n 'shrink-0 items-center justify-center text-muted-foreground',\n /* The glyph stays 14px wide but the target is not: it takes the row's full\n height (a flex child's `self-stretch`, so it follows row density and a\n tall trailing control) and the pseudo-element widens it to 26px, which\n stops at the row's own padding and gap, never over the icon or label. */\n markerTarget() &&\n 'relative w-3.5 cursor-pointer self-stretch hover:text-foreground after:absolute after:inset-y-0 after:-inset-x-1.5'\n )}\n onMouseDown={markerTarget() ? handleMarkerMouseDown : undefined}\n onClick={markerTarget() ? handleMarkerClick : undefined}\n onDblClick={markerTarget() ? handleMarkerDoubleClick : undefined}\n >\n {local.item.expandable ? (\n <ChevronRight\n aria-hidden=\"true\"\n class={cn('size-3.5 transition-transform', local.item.expanded && 'rotate-90')}\n />\n ) : null}\n </span>\n <Show when={leading()}>\n {(slot) => (\n <span class=\"flex size-4 shrink-0 items-center justify-center [&_svg]:size-4\">\n {slot()}\n </span>\n )}\n </Show>\n <span class=\"min-w-0 flex-1 truncate\">{local.children}</span>\n <Show when={trailing()}>\n {(slot) => (\n <span class=\"ms-auto flex shrink-0 items-center gap-1 text-muted-foreground\">\n {slot()}\n </span>\n )}\n </Show>\n </div>\n )\n}\n\n/**\n * TreeRowActions.\n *\n * Row-level commands (rename, copy, delete) that stay out of the way until the\n * row is hovered or holds focus, so a long tree reads as names rather than a\n * wall of buttons. Put it in `TreeRow`'s `trailing` slot beside any status that\n * must stay visible. `pinned` keeps the actions shown, e.g. while a destructive\n * action waits for its confirming second press.\n */\nexport function TreeRowActions(props: ComponentProps<'span'> & { pinned?: boolean }) {\n const [local, rest] = splitProps(props, ['class', 'pinned'])\n return (\n <span\n data-slot=\"tree-row-actions\"\n data-pinned={local.pinned ? '' : undefined}\n class={cn(\n 'flex shrink-0 items-center gap-1 opacity-0 transition-opacity ease-out',\n 'group-hover/tree-row:opacity-100 group-focus-within/tree-row:opacity-100 data-pinned:opacity-100',\n local.class\n )}\n {...rest}\n />\n )\n}\n\nexport type TreeStickyHeaderProps = {\n /** The first row in view; its expanded ancestors pin above it. Null pins nothing. */\n topId: string | null\n /** A pinned folder's content: the same icon and name its row shows. */\n label: (id: string) => JSX.Element\n /** A pinned folder was pressed; a file explorer scrolls its row into view. */\n onSelect?: (id: string) => void\n /** The most ancestors pinned at once; the deepest ones win. Defaults to 5. */\n maxRows?: number\n class?: string\n}\n\n/**\n * TreeStickyHeader.\n *\n * Pins the folders above the first row in view to the top of a scrolling tree, so a reader deep\n * in a long folder still sees where they are (Zed's sticky scroll, VS Code's sticky tree). Put it\n * first inside `Tree`, whose root is the scroll container. It takes no layout space: the pinned\n * rows float over the rows beneath, so the host's row window math is unchanged.\n *\n * The pinned rows repeat rows the tree already exposes, so they are hidden from assistive\n * technology and kept out of the tab order; they are a pointer shortcut only. The host decides\n * which row is first in view (it owns the row window), and should pass the row under the pinned\n * stack rather than the one at the very top, see `treeStickyAncestors`.\n */\nexport function TreeStickyHeader(props: TreeStickyHeaderProps) {\n const tree = useTreeContext()\n const ancestors = createMemo(() =>\n treeStickyAncestors(tree.index(), props.topId).slice(-(props.maxRows ?? 5))\n )\n return (\n <div data-slot=\"tree-sticky-header\" class={cn('sticky top-0 z-10 h-0', props.class)}>\n <Show when={ancestors().length > 0}>\n <div aria-hidden=\"true\" class=\"border-b border-border bg-background\">\n <For each={ancestors()}>\n {(item) => (\n <button\n type=\"button\"\n tabIndex={-1}\n data-tree-sticky-id={item.id}\n class=\"flex min-h-row-sm w-full min-w-0 items-center gap-1.5 pe-1.5 text-left text-sm outline-none hover:bg-surface-hover\"\n style={{ 'padding-inline-start': `${rowInset(item.level)}px` }}\n // A press must not focus this aria-hidden shortcut: focus would leave the\n // tree, its recovery state would clear and Arrow keys would stop working.\n onMouseDown={handleMarkerMouseDown}\n onClick={() => props.onSelect?.(item.id)}\n >\n <span class=\"flex size-3.5 shrink-0 items-center justify-center text-muted-foreground\">\n <ChevronRight aria-hidden=\"true\" class=\"size-3.5 rotate-90\" />\n </span>\n {props.label(item.id)}\n </button>\n )}\n </For>\n </div>\n </Show>\n </div>\n )\n}\n\n/**\n * The expanded folders above `id`, outermost first. A host finds the row under the pinned stack\n * by asking again for the row at `scrollTop + ancestors × rowHeight` until the answer settles.\n */\nexport function treeStickyAncestors(\n index: Pick<TreeNavigationIndex, 'byId'>,\n id: string | null\n): TreeItemDescriptor[] {\n const chain: TreeItemDescriptor[] = []\n let parentId = id === null ? null : (index.byId.get(id)?.parentId ?? null)\n while (parentId !== null) {\n const parent = index.byId.get(parentId)\n if (!parent) break\n chain.push(parent)\n parentId = parent.parentId\n }\n return chain.toReversed()\n}\n\n// Pressing the chevron must not move focus to its row: a mousedown on a\n// non-focusable child would otherwise focus the row, making it the roving stop\n// (and notifying `onActiveIdChange`) for what is a disclosure toggle, not a\n// selection. The press itself leaves focus where it was, so Left/Right keep\n// acting on the row the keyboard user left off at. It cannot stop the toggle\n// from hiding that row; `Tree` then recovers focus onto the first visible row.\nconst handleMarkerMouseDown: JSX.EventHandler<HTMLSpanElement, MouseEvent> = (event) =>\n event.preventDefault()\n// A double-click is two toggles; it must not also reach `onDoubleClick`\n// (rename, open) as though the row itself had been double-clicked.\nconst handleMarkerDoubleClick: JSX.EventHandler<HTMLSpanElement, MouseEvent> = (event) =>\n event.stopPropagation()\n\n/** The inline-start padding of a row at a one-based `level`, in px. */\nfunction rowInset(level: number): number {\n return 6 + Math.max(0, level - 1) * 12\n}\n/** Half the 14px chevron: a level's guide line runs down the middle of its parent's chevron. */\nconst GUIDE_CENTER = 7\n\nfunction isActionTarget(target: EventTarget | null, currentTarget: HTMLElement): boolean {\n if (!(target instanceof Element) || target === currentTarget) return false\n // Solid delivers an event from a portalled child (a row's menu) to the component that hosts\n // the portal, so a click on a menu item would otherwise also activate the row behind it.\n if (!currentTarget.contains(target)) return true\n return Boolean(\n target.closest(\n 'a, button, input, textarea, select, [contenteditable=\"true\"], [role=\"button\"], [data-tree-keyboard-stop]'\n )\n )\n}\n\nfunction composeRefs(\n internal: (element: HTMLDivElement) => void,\n external: () => ComponentProps<'div'>['ref']\n): (element: HTMLDivElement) => void {\n return (element) => {\n internal(element)\n const ref = external()\n if (typeof ref === 'function') ref(element)\n }\n}\n\nexport type { TreeItemDescriptor } from './tree-navigation'\n"],"mappings":";;;;;;;;;;;;;;;;AAyBA,IAAMA,iBAAegB,SAASf,YAAkB;AAoBhD,IAAMoC,cAAcnC,cAAgC;AAEpD,SAASoC,iBAAiB;CACxB,MAAMC,OAAO5B,WAAW0B,WAAW;CACnC,IAAI,CAACE,MAAM,MAAM,IAAIC,MAAM,8CAA8C;CACzE,OAAOD;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkGA,SAAgBa,KAAKC,OAAkB;CACrC,MAAM,CAACC,OAAOC,QAAQ7C,WAAW2C,OAAO;EACtC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CAAU,CACX;CAED,MAAMhC,QAAQjB,iBAAiBS,eAAeyC,MAAMb,YAAY,CAAC;CACjE,MAAMe,oBAAoBpD,iBAAiB;EACzC,MAAMqD,YAAYH,MAAMpC;EACxB,MAAMwC,UAAUrC,MAAM;EACtB,OAAOoC,cAAc,QAAQC,QAAQC,KAAKC,IAAIH,SAAS,IAAIA,YAAaC,QAAQG,IAAI,MAAM;CAC5F,CAAC;CACD,MAAM5C,WAAW,QAAQX,eAAe;CACxC,MAAMwD,uBAAO,IAAIC,IAA4B;CAC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,yBAAyByC,MAAMmF,KAAK,CAAC,CAAA;EAAA,OAAA+E;CAAA,EAAA,CAAA;AA2BvF;;;;;AAMA,SAAgBF,oBACdhM,OACAD,IACsB;CACtB,MAAM8M,QAA8B,CAAA;CACpC,IAAIC,WAAW/M,OAAO,OAAO,OAAQC,MAAMsC,KAAK0B,IAAIjE,EAAE,CAAC,EAAE+M,YAAY;CACrE,OAAOA,aAAa,MAAM;EACxB,MAAMC,SAAS/M,MAAMsC,KAAK0B,IAAI8I,QAAQ;EACtC,IAAI,CAACC,QAAQ;EACbF,MAAMG,KAAKD,MAAM;EACjBD,WAAWC,OAAOD;CACpB;CACA,OAAOD,MAAMI,WAAW;AAC1B;AAQA,IAAMxC,yBAAwE/J,UAC5EA,MAAM2F,eAAe;AAGvB,IAAMmE,2BAA0E9J,UAC9EA,MAAM8H,gBAAgB;;AAGxB,SAASmB,SAASP,OAAuB;CACvC,OAAO,IAAI8D,KAAKC,IAAI,GAAG/D,QAAQ,CAAC,IAAI;AACtC;;AAEA,IAAMkB,eAAe;AAErB,SAAS9D,eAAevC,QAA4BwC,eAAqC;CACvF,IAAI,EAAExC,kBAAkBnC,YAAYmC,WAAWwC,eAAe,OAAO;CAGrE,IAAI,CAACA,cAAcjB,SAASvB,MAAM,GAAG,OAAO;CAC5C,OAAOsB,QACLtB,OAAOb,QACL,8GACF,CACF;AACF;AAEA,SAAS4F,YACPoE,UACAC,UACmC;CACnC,QAAQnN,YAAY;EAClBkN,SAASlN,OAAO;EAChB,MAAM+I,MAAMoE,SAAS;EACrB,IAAI,OAAOpE,QAAQ,YAAYA,IAAI/I,OAAO;CAC5C;AACF;AAE2DoN,eAAA;CAAA;CAAA;CAAA;AAAA,CAAA"}
|
|
@@ -21,6 +21,12 @@ export type ThemeDocumentState = {
|
|
|
21
21
|
* Absent, the terminal follows the interface theme.
|
|
22
22
|
*/
|
|
23
23
|
terminalVariant?: ThemeVariant;
|
|
24
|
+
/**
|
|
25
|
+
* The variant whose syntax palette, and the canvas it was measured on, is pinned
|
|
26
|
+
* over the interface variant's `--editor-*` ramp. Absent, code follows the
|
|
27
|
+
* interface theme and no `--editor-background` family is written.
|
|
28
|
+
*/
|
|
29
|
+
codeVariant?: ThemeVariant;
|
|
24
30
|
/**
|
|
25
31
|
* The resolved surface axis. Absent, the axis is off: no attribute and no
|
|
26
32
|
* `--surface-alpha` is written, and any this writer wrote before is removed.
|
|
@@ -64,9 +70,16 @@ export type ThemeDocumentOptions = {
|
|
|
64
70
|
*/
|
|
65
71
|
editorRoles?: EditorRolesMode;
|
|
66
72
|
} & ThemeTokenProjectionOptions;
|
|
73
|
+
/**
|
|
74
|
+
* The properties a pinned code theme writes: its `--editor-*` syntax ramp under the
|
|
75
|
+
* host's projection, and the four canvas roles that ramp was measured against. Code
|
|
76
|
+
* surfaces read the canvas as `var(--editor-background, var(--background))`, so the
|
|
77
|
+
* interface canvas is the fallback whenever nothing is pinned.
|
|
78
|
+
*/
|
|
79
|
+
export declare function codeCssVariables(engine: ThemeEngine, variant: ThemeVariant, editorRoles?: EditorRolesMode): Record<string, string>;
|
|
67
80
|
/**
|
|
68
81
|
* The custom properties a state paints: the variant's roles, an optional projection
|
|
69
|
-
* from the raw host map, the accent, the pinned terminal
|
|
82
|
+
* from the raw host map, the accent, the pinned terminal and code palettes, the surface alpha,
|
|
70
83
|
* then `transformTokens`.
|
|
71
84
|
*
|
|
72
85
|
* The accent is applied *here* rather than left to the `[data-accent]` blocks in
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"theme-document.d.ts","sourceRoot":"","sources":["../../../src/components/theme/theme-document.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAA;AAErE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AACpD,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAA;AAEtF,OAAO,EAAgB,KAA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E,MAAM,CAAC,CAYxB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,WAAW,EACnB,KAAK,EAAE,kBAAkB,EACzB,OAAO,GAAE,oBAAyB,GACjC;IAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,QAAQ,EAAE,OAAO,CAAA;CAAE,CAsCvD;AAED;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,WAAW,EACnB,IAAI,EAAE,SAAS,EACf,KAAK,EAAE,kBAAkB,EACzB,OAAO,GAAE,oBAAyB,EAClC,QAAQ,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,GAC7B,WAAW,CAAC,MAAM,CAAC,CAmDrB;AAOD,gEAAgE;AAChE,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,EAAE;QAAE,WAAW,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAAA;KAAE,CAAA;IAC7C,aAAa,CAAC,GAAG,EAAE,OAAO,GAAG;QAC3B,WAAW,EAAE,MAAM,GAAG,IAAI,CAAA;QAC1B,YAAY,CAAC,EAAE,MAAM,CAAA;QACrB,MAAM,IAAI,IAAI,CAAA;KACf,CAAA;CACF,CAAA;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,uBAAuB,CACrC,GAAG,EAAE,kBAAkB,EACvB,KAAK,EAAE,MAAM,IAAI,EACjB,QAAQ,GAAE,CAAC,QAAQ,EAAE,MAAM,IAAI,KAAK,IAAsB,GACzD,MAAM,IAAI,CAqBZ"}
|
|
@@ -15,8 +15,24 @@ function stylesheetOverrides(engine, variant, editorRoles) {
|
|
|
15
15
|
return Object.fromEntries(Object.entries(engine.themeCssVariables(variant, { editor: "floor" })).filter(([name]) => name.startsWith("--editor-")));
|
|
16
16
|
}
|
|
17
17
|
/**
|
|
18
|
+
* The properties a pinned code theme writes: its `--editor-*` syntax ramp under the
|
|
19
|
+
* host's projection, and the four canvas roles that ramp was measured against. Code
|
|
20
|
+
* surfaces read the canvas as `var(--editor-background, var(--background))`, so the
|
|
21
|
+
* interface canvas is the fallback whenever nothing is pinned.
|
|
22
|
+
*/
|
|
23
|
+
function codeCssVariables(engine, variant, editorRoles) {
|
|
24
|
+
const all = engine.themeCssVariables(variant, { editor: editorRoles });
|
|
25
|
+
const properties = {};
|
|
26
|
+
for (const [name, value] of Object.entries(all)) if (name.startsWith("--editor-")) properties[name] = value;
|
|
27
|
+
properties["--editor-background"] = all["--background"] ?? variant.colors.background;
|
|
28
|
+
properties["--editor-foreground"] = all["--foreground"] ?? variant.colors.foreground;
|
|
29
|
+
properties["--editor-muted-foreground"] = all["--muted-foreground"] ?? variant.colors.mutedForeground;
|
|
30
|
+
properties["--editor-border"] = all["--border"] ?? variant.colors.border;
|
|
31
|
+
return properties;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
18
34
|
* The custom properties a state paints: the variant's roles, an optional projection
|
|
19
|
-
* from the raw host map, the accent, the pinned terminal
|
|
35
|
+
* from the raw host map, the accent, the pinned terminal and code palettes, the surface alpha,
|
|
20
36
|
* then `transformTokens`.
|
|
21
37
|
*
|
|
22
38
|
* The accent is applied *here* rather than left to the `[data-accent]` blocks in
|
|
@@ -44,6 +60,7 @@ function themeDocumentTokens(engine, state, options = {}) {
|
|
|
44
60
|
});
|
|
45
61
|
if (accent) Object.assign(properties, accent);
|
|
46
62
|
if (state.terminalVariant) Object.assign(properties, terminalCssVariables(state.terminalVariant));
|
|
63
|
+
if (state.codeVariant) Object.assign(properties, codeCssVariables(engine, state.codeVariant, options.editorRoles));
|
|
47
64
|
if (state.surface) properties["--surface-alpha"] = surfaceAlpha[state.surface.surface];
|
|
48
65
|
return {
|
|
49
66
|
tokens: options.transformTokens ? options.transformTokens(properties) : properties,
|
|
@@ -127,6 +144,6 @@ function defaultSchedule(callback) {
|
|
|
127
144
|
if (typeof requestAnimationFrame === "function") requestAnimationFrame(callback);
|
|
128
145
|
else callback();
|
|
129
146
|
}
|
|
130
|
-
export { applyThemeToRoot, applyWithoutTransitions, themeDocumentTokens };
|
|
147
|
+
export { applyThemeToRoot, applyWithoutTransitions, codeCssVariables, themeDocumentTokens };
|
|
131
148
|
|
|
132
149
|
//# sourceMappingURL=theme-document.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"theme-document.js","names":[],"sources":["../../../src/components/theme/theme-document.ts"],"sourcesContent":["import {\n applyAppearanceFontSettings,\n normalizeAppearanceEditorFontSettings,\n} from '#lib/appearance-font-settings'\nimport { terminalCssVariables } from '#lib/theme-css'\nimport type { ThemeTokenProjectionOptions } from './token-projection'\nimport { assertThemeTokenProjectionConfig } from './token-projection-options'\nimport type { ThemeEngine } from '#lib/theme-engine'\nimport type { EditorRolesMode, ThemeAppearance, ThemeVariant } from '#lib/theme-types'\nimport { isCustomAccent } from '#lib/accent-roles'\nimport { surfaceAlpha, type SurfaceState } from '#lib/theme-surface'\nimport { resolvedDensity, type ThemeSelection } from './theme-state'\n\n/**\n * The document half of the theme provider: the single writer of `<html>`.\n *\n * Written against the few members of an element it uses, so the rules can be tested\n * on a stand-in. Every question the catalogue answers goes through the\n * {@link ThemeEngine} it is given, so it imports no catalogue code or data.\n */\nexport type ThemeRoot = Pick<\n HTMLElement,\n 'classList' | 'dataset' | 'style' | 'removeAttribute' | 'setAttribute'\n>\n\nexport type ThemeDocumentState = {\n /** What the document shows: the committed selection, or a preview laid over it. */\n selection: ThemeSelection\n appearance: ThemeAppearance\n variant: ThemeVariant\n /**\n * The variant whose terminal palette is pinned over the interface variant's.\n * Absent, the terminal follows the interface theme.\n */\n terminalVariant?: ThemeVariant\n /**\n * The resolved surface axis. Absent, the axis is off: no attribute and no\n * `--surface-alpha` is written, and any this writer wrote before is removed.\n */\n surface?: SurfaceState\n}\n\nexport type ThemeDocumentOptions = {\n /**\n * Rewrites the custom properties just before they are written: the variant's\n * roles with the accent laid over them. It sees every property of the pass and\n * must return the full map; a name it drops is not written.\n */\n transformTokens?: (tokens: Record<string, string>) => Record<string, string>\n /**\n * The contrast an accent is held to against the variant's background. Absent, a\n * preset is painted verbatim (the catalogue measured it for its own themes) and\n * only a custom `#rrggbb` is held to the default floor of 3:1.\n */\n accentContrastFloor?: number\n /**\n * Where a catalogue variant's palette comes from. `inline` (the default) writes\n * every role onto the root. `stylesheet` writes none for a catalogue variant,\n * because the host loads a stylesheet that carries a `[data-theme]` block for it;\n * a variant the catalogue does not hold (a host's imported theme) is still written\n * inline, since no stylesheet can know it. The accent, the terminal pin, the\n * surface alpha and the fonts are written the same in both.\n *\n * Switching from an imported variant back to a catalogue one removes what the\n * imported one wrote, so nothing inline outlives it to beat the stylesheet.\n */\n palette?: 'inline' | 'stylesheet'\n /**\n * The `--editor-*` projection. `syntax` (the default) is the catalogue's quiet\n * syntax roles, which is what `theme-variants.css` carries; `floor` holds every\n * editor role to 4.5:1 on the canvas, as hex.\n *\n * With `palette: 'stylesheet'`, `floor` is the one palette write a catalogue\n * variant still gets: the stylesheet is generated for the default projection, so\n * the sixteen `--editor-*` properties are written inline over it. The rest of the\n * palette stays in the stylesheet.\n */\n editorRoles?: EditorRolesMode\n} & ThemeTokenProjectionOptions\n\n/**\n * What a catalogue variant still writes inline when its palette is the stylesheet's:\n * nothing, unless the editor projection is not the one the stylesheet was generated\n * for.\n */\nfunction stylesheetOverrides(\n engine: ThemeEngine,\n variant: ThemeVariant,\n editorRoles: EditorRolesMode | undefined\n): Record<string, string> {\n if (editorRoles !== 'floor') return {}\n return Object.fromEntries(\n Object.entries(engine.themeCssVariables(variant, { editor: 'floor' })).filter(([name]) =>\n name.startsWith('--editor-')\n )\n )\n}\n\n/**\n * The custom properties a state paints: the variant's roles, an optional projection\n * from the raw host map, the accent, the pinned terminal palette, the surface alpha,\n * then `transformTokens`.\n *\n * The accent is applied *here* rather than left to the `[data-accent]` blocks in\n * `theme.css`, because the properties are written inline and an inline declaration\n * outranks every stylesheet selector however specific it is. The blocks still exist\n * and are still correct — they are what styles the window before this runs — but\n * they cannot win from here, so leaving the accent to them meant the attribute was\n * set, the rules were present, and nothing changed on screen.\n */\nexport function themeDocumentTokens(\n engine: ThemeEngine,\n state: ThemeDocumentState,\n options: ThemeDocumentOptions = {}\n): { tokens: Record<string, string>; accented: boolean } {\n assertThemeTokenProjectionConfig(options.tokenProjection)\n const fromStylesheet =\n options.palette === 'stylesheet' && engine.isCatalogueVariant(state.variant)\n const properties = fromStylesheet\n ? stylesheetOverrides(engine, state.variant, options.editorRoles)\n : { ...engine.themeCssVariables(state.variant, { editor: options.editorRoles }) }\n if (options.tokenProjection && !engine.isCatalogueVariant(state.variant)) {\n const rawTokens = state.variant.tokens ?? {}\n const projected = options.tokenProjection.project(rawTokens, options.tokenProjection.rules)\n for (const rule of options.tokenProjection.rules) {\n if (!rule || typeof rule.target !== 'string') continue\n if (Object.hasOwn(projected, rule.target)) {\n properties[rule.target] = projected[rule.target]!\n }\n }\n }\n const accent = engine.accentVariables(state.selection.accent, state.appearance, state.selection, {\n background: state.variant.colors.background,\n floor: options.accentContrastFloor,\n variantId: state.variant.id,\n })\n if (accent) Object.assign(properties, accent)\n // Written after the variant and the accent, so it wins over the interface\n // variant's own terminal ramp (and over the stylesheet's, which it outranks as an\n // inline declaration). Dropping the pin needs no removal of its own: the ramp is\n // then rewritten by the variant, or swept back to the stylesheet.\n if (state.terminalVariant) Object.assign(properties, terminalCssVariables(state.terminalVariant))\n if (state.surface) properties['--surface-alpha'] = surfaceAlpha[state.surface.surface]\n return {\n tokens: options.transformTokens ? options.transformTokens(properties) : properties,\n accented: accent !== undefined,\n }\n}\n\n/**\n * Write a state onto a root and report which custom properties it owns.\n *\n * Pass the previous call's return as `previous` and any palette property that pass\n * wrote and this one does not is removed. For the catalogue the two sets are the\n * same, so nothing is ever removed; it matters for a host variant that carries\n * `tokens` the catalogue does not, which would otherwise stay inline, beating the\n * stylesheet, after the user switched away from it.\n */\nexport function applyThemeToRoot(\n engine: ThemeEngine,\n root: ThemeRoot,\n state: ThemeDocumentState,\n options: ThemeDocumentOptions = {},\n previous?: ReadonlySet<string>\n): ReadonlySet<string> {\n const { tokens, accented } = themeDocumentTokens(engine, state, options)\n\n // Every pass recomputes the whole token set (an accent or font step included);\n // only the values that changed are written, so an unchanged palette does not\n // dirty the document's style. Custom property values read back as written.\n for (const [name, value] of Object.entries(tokens)) {\n if (root.style.getPropertyValue(name) !== value) root.style.setProperty(name, value)\n }\n if (previous) {\n for (const name of previous) {\n if (!(name in tokens)) root.style.removeProperty(name)\n }\n }\n\n root.classList.toggle('dark', state.appearance === 'dark')\n setData(root, 'theme', state.variant.id)\n setData(root, 'appearance', state.appearance)\n if (root.style.colorScheme !== state.appearance) root.style.colorScheme = state.appearance\n\n // A custom colour has no stylesheet block to select, and its value is the\n // attribute's worst possible content, so it is reported as `custom`.\n if (!accented) root.removeAttribute('data-accent')\n else\n setData(\n root,\n 'accent',\n isCustomAccent(state.selection.accent) ? 'custom' : state.selection.accent\n )\n\n // The surface axis is opt-in, so its absence removes rather than defaults: a host\n // that never enables it keeps an `<html>` with neither attribute, and one that\n // turns it off leaves nothing behind. (`--surface-alpha` is swept with the tokens.)\n if (state.surface) {\n setData(root, 'surface', state.surface.surface)\n setData(root, 'reduceTransparency', state.surface.reduceTransparencyActive ? 'true' : 'false')\n } else {\n root.removeAttribute('data-surface')\n root.removeAttribute('data-reduce-transparency')\n }\n\n applyAppearanceFontSettings(\n root,\n normalizeAppearanceEditorFontSettings(state.selection.fonts, state.selection.font).settings\n )\n\n const density = resolvedDensity(state.selection)\n if (density === 'comfortable') root.removeAttribute('data-density')\n else setData(root, 'density', density)\n\n return new Set(Object.keys(tokens))\n}\n\n/** Rewriting an attribute with its own value still queues a mutation and a style check. */\nfunction setData(root: ThemeRoot, key: string, value: string) {\n if (root.dataset[key] !== value) root.dataset[key] = value\n}\n\n/** What {@link applyWithoutTransitions} needs of a document. */\nexport type TransitionDocument = {\n head: { appendChild(node: unknown): unknown }\n createElement(tag: 'style'): {\n textContent: string | null\n offsetHeight?: number\n remove(): void\n }\n}\n\n/**\n * Run `apply` with every CSS transition switched off for the frame that carries\n * it, so a theme switch cannot animate page-wide.\n *\n * Without this, flipping the custom properties on `<html>` starts a transition on\n * every element that declares one, and each fades from the old palette to the new\n * over its own duration: a theme change that looks like a rendering fault. The\n * rule is removed two frames later, after the browser has committed the new styles\n * with transitions off, and `restore` runs it early (the provider calls it when it\n * is disposed mid-switch).\n *\n * `schedule` is the frame source; it defaults to `requestAnimationFrame` and falls\n * back to running at once where there is none, which leaves transitions on rather\n * than off.\n */\nexport function applyWithoutTransitions(\n doc: TransitionDocument,\n apply: () => void,\n schedule: (callback: () => void) => void = defaultSchedule\n): () => void {\n const style = doc.createElement('style')\n style.textContent = '*{transition:none !important}'\n doc.head.appendChild(style)\n // Reading a layout property forces the browser to commit the rule before the\n // properties change; without it the two can be batched into one style recalc.\n void style.offsetHeight\n let removed = false\n const restore = () => {\n if (removed) return\n removed = true\n style.remove()\n }\n try {\n apply()\n } catch (error) {\n restore()\n throw error\n }\n schedule(() => schedule(restore))\n return restore\n}\n\nfunction defaultSchedule(callback: () => void): void {\n if (typeof requestAnimationFrame === 'function') requestAnimationFrame(callback)\n else callback()\n}\n"],"mappings":";;;;;;;;;;;;AAqFA,SAAS,oBACP,QACA,SACA,aACwB;CACxB,IAAI,gBAAgB,SAAS,OAAO,CAAC;CACrC,OAAO,OAAO,YACZ,OAAO,QAAQ,OAAO,kBAAkB,SAAS,EAAE,QAAQ,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,UAC9E,KAAK,WAAW,WAAW,CAC7B,CACF;AACF;;;;;;;;;;;;;AAcA,SAAgB,oBACd,QACA,OACA,UAAgC,CAAC,GACsB;CACvD,iCAAiC,QAAQ,eAAe;CAGxD,MAAM,aADJ,QAAQ,YAAY,gBAAgB,OAAO,mBAAmB,MAAM,OAAO,IAEzE,oBAAoB,QAAQ,MAAM,SAAS,QAAQ,WAAW,IAC9D,EAAE,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AAC;CAChC,OAAO;AACT;AAEA,SAAS,gBAAgB,UAA4B;CACnD,IAAI,OAAO,0BAA0B,YAAY,sBAAsB,QAAQ;MAC1E,SAAS;AAChB"}
|
|
1
|
+
{"version":3,"file":"theme-document.js","names":[],"sources":["../../../src/components/theme/theme-document.ts"],"sourcesContent":["import {\n applyAppearanceFontSettings,\n normalizeAppearanceEditorFontSettings,\n} from '#lib/appearance-font-settings'\nimport { terminalCssVariables } from '#lib/theme-css'\nimport type { ThemeTokenProjectionOptions } from './token-projection'\nimport { assertThemeTokenProjectionConfig } from './token-projection-options'\nimport type { ThemeEngine } from '#lib/theme-engine'\nimport type { EditorRolesMode, ThemeAppearance, ThemeVariant } from '#lib/theme-types'\nimport { isCustomAccent } from '#lib/accent-roles'\nimport { surfaceAlpha, type SurfaceState } from '#lib/theme-surface'\nimport { resolvedDensity, type ThemeSelection } from './theme-state'\n\n/**\n * The document half of the theme provider: the single writer of `<html>`.\n *\n * Written against the few members of an element it uses, so the rules can be tested\n * on a stand-in. Every question the catalogue answers goes through the\n * {@link ThemeEngine} it is given, so it imports no catalogue code or data.\n */\nexport type ThemeRoot = Pick<\n HTMLElement,\n 'classList' | 'dataset' | 'style' | 'removeAttribute' | 'setAttribute'\n>\n\nexport type ThemeDocumentState = {\n /** What the document shows: the committed selection, or a preview laid over it. */\n selection: ThemeSelection\n appearance: ThemeAppearance\n variant: ThemeVariant\n /**\n * The variant whose terminal palette is pinned over the interface variant's.\n * Absent, the terminal follows the interface theme.\n */\n terminalVariant?: ThemeVariant\n /**\n * The variant whose syntax palette, and the canvas it was measured on, is pinned\n * over the interface variant's `--editor-*` ramp. Absent, code follows the\n * interface theme and no `--editor-background` family is written.\n */\n codeVariant?: ThemeVariant\n /**\n * The resolved surface axis. Absent, the axis is off: no attribute and no\n * `--surface-alpha` is written, and any this writer wrote before is removed.\n */\n surface?: SurfaceState\n}\n\nexport type ThemeDocumentOptions = {\n /**\n * Rewrites the custom properties just before they are written: the variant's\n * roles with the accent laid over them. It sees every property of the pass and\n * must return the full map; a name it drops is not written.\n */\n transformTokens?: (tokens: Record<string, string>) => Record<string, string>\n /**\n * The contrast an accent is held to against the variant's background. Absent, a\n * preset is painted verbatim (the catalogue measured it for its own themes) and\n * only a custom `#rrggbb` is held to the default floor of 3:1.\n */\n accentContrastFloor?: number\n /**\n * Where a catalogue variant's palette comes from. `inline` (the default) writes\n * every role onto the root. `stylesheet` writes none for a catalogue variant,\n * because the host loads a stylesheet that carries a `[data-theme]` block for it;\n * a variant the catalogue does not hold (a host's imported theme) is still written\n * inline, since no stylesheet can know it. The accent, the terminal pin, the\n * surface alpha and the fonts are written the same in both.\n *\n * Switching from an imported variant back to a catalogue one removes what the\n * imported one wrote, so nothing inline outlives it to beat the stylesheet.\n */\n palette?: 'inline' | 'stylesheet'\n /**\n * The `--editor-*` projection. `syntax` (the default) is the catalogue's quiet\n * syntax roles, which is what `theme-variants.css` carries; `floor` holds every\n * editor role to 4.5:1 on the canvas, as hex.\n *\n * With `palette: 'stylesheet'`, `floor` is the one palette write a catalogue\n * variant still gets: the stylesheet is generated for the default projection, so\n * the sixteen `--editor-*` properties are written inline over it. The rest of the\n * palette stays in the stylesheet.\n */\n editorRoles?: EditorRolesMode\n} & ThemeTokenProjectionOptions\n\n/**\n * What a catalogue variant still writes inline when its palette is the stylesheet's:\n * nothing, unless the editor projection is not the one the stylesheet was generated\n * for.\n */\nfunction stylesheetOverrides(\n engine: ThemeEngine,\n variant: ThemeVariant,\n editorRoles: EditorRolesMode | undefined\n): Record<string, string> {\n if (editorRoles !== 'floor') return {}\n return Object.fromEntries(\n Object.entries(engine.themeCssVariables(variant, { editor: 'floor' })).filter(([name]) =>\n name.startsWith('--editor-')\n )\n )\n}\n\n/**\n * The properties a pinned code theme writes: its `--editor-*` syntax ramp under the\n * host's projection, and the four canvas roles that ramp was measured against. Code\n * surfaces read the canvas as `var(--editor-background, var(--background))`, so the\n * interface canvas is the fallback whenever nothing is pinned.\n */\nexport function codeCssVariables(\n engine: ThemeEngine,\n variant: ThemeVariant,\n editorRoles?: EditorRolesMode\n): Record<string, string> {\n const all = engine.themeCssVariables(variant, { editor: editorRoles })\n const properties: Record<string, string> = {}\n for (const [name, value] of Object.entries(all)) {\n if (name.startsWith('--editor-')) properties[name] = value\n }\n properties['--editor-background'] = all['--background'] ?? variant.colors.background\n properties['--editor-foreground'] = all['--foreground'] ?? variant.colors.foreground\n properties['--editor-muted-foreground'] =\n all['--muted-foreground'] ?? variant.colors.mutedForeground\n properties['--editor-border'] = all['--border'] ?? variant.colors.border\n return properties\n}\n\n/**\n * The custom properties a state paints: the variant's roles, an optional projection\n * from the raw host map, the accent, the pinned terminal and code palettes, the surface alpha,\n * then `transformTokens`.\n *\n * The accent is applied *here* rather than left to the `[data-accent]` blocks in\n * `theme.css`, because the properties are written inline and an inline declaration\n * outranks every stylesheet selector however specific it is. The blocks still exist\n * and are still correct — they are what styles the window before this runs — but\n * they cannot win from here, so leaving the accent to them meant the attribute was\n * set, the rules were present, and nothing changed on screen.\n */\nexport function themeDocumentTokens(\n engine: ThemeEngine,\n state: ThemeDocumentState,\n options: ThemeDocumentOptions = {}\n): { tokens: Record<string, string>; accented: boolean } {\n assertThemeTokenProjectionConfig(options.tokenProjection)\n const fromStylesheet =\n options.palette === 'stylesheet' && engine.isCatalogueVariant(state.variant)\n const properties = fromStylesheet\n ? stylesheetOverrides(engine, state.variant, options.editorRoles)\n : { ...engine.themeCssVariables(state.variant, { editor: options.editorRoles }) }\n if (options.tokenProjection && !engine.isCatalogueVariant(state.variant)) {\n const rawTokens = state.variant.tokens ?? {}\n const projected = options.tokenProjection.project(rawTokens, options.tokenProjection.rules)\n for (const rule of options.tokenProjection.rules) {\n if (!rule || typeof rule.target !== 'string') continue\n if (Object.hasOwn(projected, rule.target)) {\n properties[rule.target] = projected[rule.target]!\n }\n }\n }\n const accent = engine.accentVariables(state.selection.accent, state.appearance, state.selection, {\n background: state.variant.colors.background,\n floor: options.accentContrastFloor,\n variantId: state.variant.id,\n })\n if (accent) Object.assign(properties, accent)\n // Written after the variant and the accent, so it wins over the interface\n // variant's own terminal ramp (and over the stylesheet's, which it outranks as an\n // inline declaration). Dropping the pin needs no removal of its own: the ramp is\n // then rewritten by the variant, or swept back to the stylesheet.\n if (state.terminalVariant) Object.assign(properties, terminalCssVariables(state.terminalVariant))\n // The same rule for code: the pinned ramp wins over the interface variant's, and its\n // canvas comes with it. Unpinning drops the canvas properties from this pass, so the\n // previous-set sweep removes them and code falls back to the interface canvas.\n if (state.codeVariant)\n Object.assign(properties, codeCssVariables(engine, state.codeVariant, options.editorRoles))\n if (state.surface) properties['--surface-alpha'] = surfaceAlpha[state.surface.surface]\n return {\n tokens: options.transformTokens ? options.transformTokens(properties) : properties,\n accented: accent !== undefined,\n }\n}\n\n/**\n * Write a state onto a root and report which custom properties it owns.\n *\n * Pass the previous call's return as `previous` and any palette property that pass\n * wrote and this one does not is removed. For the catalogue the two sets are the\n * same, so nothing is ever removed; it matters for a host variant that carries\n * `tokens` the catalogue does not, which would otherwise stay inline, beating the\n * stylesheet, after the user switched away from it.\n */\nexport function applyThemeToRoot(\n engine: ThemeEngine,\n root: ThemeRoot,\n state: ThemeDocumentState,\n options: ThemeDocumentOptions = {},\n previous?: ReadonlySet<string>\n): ReadonlySet<string> {\n const { tokens, accented } = themeDocumentTokens(engine, state, options)\n\n // Every pass recomputes the whole token set (an accent or font step included);\n // only the values that changed are written, so an unchanged palette does not\n // dirty the document's style. Custom property values read back as written.\n for (const [name, value] of Object.entries(tokens)) {\n if (root.style.getPropertyValue(name) !== value) root.style.setProperty(name, value)\n }\n if (previous) {\n for (const name of previous) {\n if (!(name in tokens)) root.style.removeProperty(name)\n }\n }\n\n root.classList.toggle('dark', state.appearance === 'dark')\n setData(root, 'theme', state.variant.id)\n setData(root, 'appearance', state.appearance)\n if (root.style.colorScheme !== state.appearance) root.style.colorScheme = state.appearance\n\n // A custom colour has no stylesheet block to select, and its value is the\n // attribute's worst possible content, so it is reported as `custom`.\n if (!accented) root.removeAttribute('data-accent')\n else\n setData(\n root,\n 'accent',\n isCustomAccent(state.selection.accent) ? 'custom' : state.selection.accent\n )\n\n // The surface axis is opt-in, so its absence removes rather than defaults: a host\n // that never enables it keeps an `<html>` with neither attribute, and one that\n // turns it off leaves nothing behind. (`--surface-alpha` is swept with the tokens.)\n if (state.surface) {\n setData(root, 'surface', state.surface.surface)\n setData(root, 'reduceTransparency', state.surface.reduceTransparencyActive ? 'true' : 'false')\n } else {\n root.removeAttribute('data-surface')\n root.removeAttribute('data-reduce-transparency')\n }\n\n applyAppearanceFontSettings(\n root,\n normalizeAppearanceEditorFontSettings(state.selection.fonts, state.selection.font).settings\n )\n\n const density = resolvedDensity(state.selection)\n if (density === 'comfortable') root.removeAttribute('data-density')\n else setData(root, 'density', density)\n\n return new Set(Object.keys(tokens))\n}\n\n/** Rewriting an attribute with its own value still queues a mutation and a style check. */\nfunction setData(root: ThemeRoot, key: string, value: string) {\n if (root.dataset[key] !== value) root.dataset[key] = value\n}\n\n/** What {@link applyWithoutTransitions} needs of a document. */\nexport type TransitionDocument = {\n head: { appendChild(node: unknown): unknown }\n createElement(tag: 'style'): {\n textContent: string | null\n offsetHeight?: number\n remove(): void\n }\n}\n\n/**\n * Run `apply` with every CSS transition switched off for the frame that carries\n * it, so a theme switch cannot animate page-wide.\n *\n * Without this, flipping the custom properties on `<html>` starts a transition on\n * every element that declares one, and each fades from the old palette to the new\n * over its own duration: a theme change that looks like a rendering fault. The\n * rule is removed two frames later, after the browser has committed the new styles\n * with transitions off, and `restore` runs it early (the provider calls it when it\n * is disposed mid-switch).\n *\n * `schedule` is the frame source; it defaults to `requestAnimationFrame` and falls\n * back to running at once where there is none, which leaves transitions on rather\n * than off.\n */\nexport function applyWithoutTransitions(\n doc: TransitionDocument,\n apply: () => void,\n schedule: (callback: () => void) => void = defaultSchedule\n): () => void {\n const style = doc.createElement('style')\n style.textContent = '*{transition:none !important}'\n doc.head.appendChild(style)\n // Reading a layout property forces the browser to commit the rule before the\n // properties change; without it the two can be batched into one style recalc.\n void style.offsetHeight\n let removed = false\n const restore = () => {\n if (removed) return\n removed = true\n style.remove()\n }\n try {\n apply()\n } catch (error) {\n restore()\n throw error\n }\n schedule(() => schedule(restore))\n return restore\n}\n\nfunction defaultSchedule(callback: () => void): void {\n if (typeof requestAnimationFrame === 'function') requestAnimationFrame(callback)\n else callback()\n}\n"],"mappings":";;;;;;;;;;;;AA2FA,SAAS,oBACP,QACA,SACA,aACwB;CACxB,IAAI,gBAAgB,SAAS,OAAO,CAAC;CACrC,OAAO,OAAO,YACZ,OAAO,QAAQ,OAAO,kBAAkB,SAAS,EAAE,QAAQ,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,UAC9E,KAAK,WAAW,WAAW,CAC7B,CACF;AACF;;;;;;;AAQA,SAAgB,iBACd,QACA,SACA,aACwB;CACxB,MAAM,MAAM,OAAO,kBAAkB,SAAS,EAAE,QAAQ,YAAY,CAAC;CACrE,MAAM,aAAqC,CAAC;CAC5C,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,GAAG,GAC5C,IAAI,KAAK,WAAW,WAAW,GAAG,WAAW,QAAQ;CAEvD,WAAW,yBAAyB,IAAI,mBAAmB,QAAQ,OAAO;CAC1E,WAAW,yBAAyB,IAAI,mBAAmB,QAAQ,OAAO;CAC1E,WAAW,+BACT,IAAI,yBAAyB,QAAQ,OAAO;CAC9C,WAAW,qBAAqB,IAAI,eAAe,QAAQ,OAAO;CAClE,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAgB,oBACd,QACA,OACA,UAAgC,CAAC,GACsB;CACvD,iCAAiC,QAAQ,eAAe;CAGxD,MAAM,aADJ,QAAQ,YAAY,gBAAgB,OAAO,mBAAmB,MAAM,OAAO,IAEzE,oBAAoB,QAAQ,MAAM,SAAS,QAAQ,WAAW,IAC9D,EAAE,GAAG,OAAO,kBAAkB,MAAM,SAAS,EAAE,QAAQ,QAAQ,YAAY,CAA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ACR;CACA,eAAe,SAAS,OAAO,CAAC;CAChC,OAAO;AACT;AAEA,SAAS,gBAAgB,UAA4B;CACnD,IAAI,OAAO,0BAA0B,YAAY,sBAAsB,QAAQ;MAC1E,SAAS;AAChB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"theme-persistence.d.ts","sourceRoot":"","sources":["../../../src/components/theme/theme-persistence.ts"],"names":[],"mappings":"AAIA,OAAO,EAOL,KAAK,iBAAiB,EACvB,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAA0C,KAAK,cAAc,EAAE,MAAM,eAAe,CAAA;AAE3F;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,IAAI,IAAI,OAAO,CAAC,cAAc,CAAC,GAAG,SAAS,CAAA;IAC3C,KAAK,CAAC,IAAI,EAAE,cAAc,GAAG,IAAI,CAAA;CAClC,CAAA;
|
|
1
|
+
{"version":3,"file":"theme-persistence.d.ts","sourceRoot":"","sources":["../../../src/components/theme/theme-persistence.ts"],"names":[],"mappings":"AAIA,OAAO,EAOL,KAAK,iBAAiB,EACvB,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAA0C,KAAK,cAAc,EAAE,MAAM,eAAe,CAAA;AAE3F;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,IAAI,IAAI,OAAO,CAAC,cAAc,CAAC,GAAG,SAAS,CAAA;IAC3C,KAAK,CAAC,IAAI,EAAE,cAAc,GAAG,IAAI,CAAA;CAClC,CAAA;AAmDD;;;;;;;;;;;;GAYG;AACH,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,MAAM,MAAM,CAAC,GAAG,gBAAgB,CAStF;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,WAAW,EAAE,gBAAgB,GAAG,OAAO,CAAC,cAAc,CAAC,GAAG,SAAS,CAEhG;AAED,+FAA+F;AAC/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CAAC,GAAG,EAC5C,MAAM,EAAE,kBAAkB,EAC1B,KAAK,EAAE,cAAc,CAAC,GAAG,CAAC,EAC1B,OAAO,GAAE,2BAAgC,GACxC,gBAAgB,CA2ClB"}
|
|
@@ -26,6 +26,7 @@ function readSelection(storageKey) {
|
|
|
26
26
|
fonts,
|
|
27
27
|
density: resolvedDensity(stored),
|
|
28
28
|
terminalThemeId: typeof stored.terminalThemeId === "string" && stored.terminalThemeId.trim() !== "" ? stored.terminalThemeId : void 0,
|
|
29
|
+
codeThemeId: typeof stored.codeThemeId === "string" && stored.codeThemeId.trim() !== "" ? stored.codeThemeId : void 0,
|
|
29
30
|
surface: normalizeSurface(stored.surface),
|
|
30
31
|
reduceTransparency: typeof stored.reduceTransparency === "boolean" ? stored.reduceTransparency : void 0
|
|
31
32
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"theme-persistence.js","names":[],"sources":["../../../src/components/theme/theme-persistence.ts"],"sourcesContent":["import { normalizeAccentSelection } from '#lib/accent-roles'\nimport { normalizeAppearanceEditorFontSettings } from '#lib/appearance-font-settings'\nimport { defaultDarkThemeId, defaultLightThemeId, storedThemeId } from '#lib/theme-defaults'\nimport { normalizeSurface } from '#lib/theme-surface'\nimport {\n attemptStorage,\n defaultPreferenceStorage,\n readLegacyValue,\n readVersionedRecord,\n recoveryKeyFor,\n writeVersionedRecord,\n type PreferenceStorage,\n} from '#lib/preference-store'\nimport { defaultThemeSelection, resolvedDensity, type ThemeSelection } from './theme-state'\n\n/**\n * Where a selection is kept between sessions.\n *\n * The provider never touches storage itself; it asks a `ThemePersistence`. The\n * default is {@link localStoragePersistence}, which is what the provider always did.\n * A host that stores the preference in a different shape, under a versioned\n * envelope, or somewhere that is not `localStorage` supplies its own and the\n * resolution and application rules stay the shared ones.\n *\n * The contract is deliberately narrow, so that an implementation cannot make the\n * provider less safe than it was:\n *\n * - `read` is synchronous and runs once, when the provider is created. It may\n * repair or quarantine what it finds, and it must not throw: the provider\n * treats a throw as \"nothing stored\" and starts from the defaults.\n * - `write` runs only from `setSelection`. Never on mount, never from `preview`,\n * never as a side effect of reading, so the first write to a store is always a\n * user's decision. A throw is swallowed, because a full or blocked store must\n * not break the switch.\n */\nexport type ThemePersistence = {\n read(): Partial<ThemeSelection> | undefined\n write(next: ThemeSelection): void\n}\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * The stored preference, validated against the policy in `lib/theme-defaults` and\n * `lib/accent-roles`, so reading it never loads the catalogue.\n */\nfunction readSelection(storageKey: string): ThemeSelection {\n const parsed = attemptStorage<unknown>(\n () => JSON.parse(defaultPreferenceStorage()?.getItem(storageKey) ?? 'null'),\n null\n )\n if (!isRecord(parsed)) return defaultThemeSelection\n const stored = parsed as Partial<Record<keyof ThemeSelection, unknown>>\n const fonts = normalizeAppearanceEditorFontSettings(stored.fonts, stored.font).settings\n return {\n appearance:\n stored.appearance === 'light' ||\n stored.appearance === 'dark' ||\n stored.appearance === 'system'\n ? stored.appearance\n : defaultThemeSelection.appearance,\n lightThemeId: storedThemeId(stored.lightThemeId, 'light') ?? defaultLightThemeId,\n darkThemeId: storedThemeId(stored.darkThemeId, 'dark') ?? defaultDarkThemeId,\n accent: normalizeAccentSelection(stored.accent) ?? defaultThemeSelection.accent,\n font: fonts.ui.family,\n fonts,\n // Every axis has to be read back here, or it is lost twice: the provider's\n // document effect removes the `data-density` that `themeScript` set for the first\n // paint, and the next `setSelection` rewrites the store without it.\n density: resolvedDensity(stored as ThemeSelection),\n // The newer axes are read back only when the store holds a usable value and are\n // otherwise left `undefined`, never defaulted: `JSON.stringify` drops them, so a\n // consumer that never sets one writes the bytes it always did.\n terminalThemeId:\n typeof stored.terminalThemeId === 'string' && stored.terminalThemeId.trim() !== ''\n ? stored.terminalThemeId\n : undefined,\n surface: normalizeSurface(stored.surface),\n reduceTransparency:\n typeof stored.reduceTransparency === 'boolean' ? stored.reduceTransparency : undefined,\n }\n}\n\n/**\n * The default persistence: one JSON document in `localStorage` under `key`.\n *\n * Every stored id is validated, and an id is kept even when nothing holds it today\n * (a host's imported theme), exactly as {@link createVersionedPersistence} keeps what\n * its codec decodes: the provider resolves an unknown id, it never rewrites one.\n * `key` may be a function so a provider whose `storageKey` prop changes writes to the\n * key it is now given.\n *\n * Blocked, full or absent storage is survivable in both directions: a read answers\n * with the defaults and a write is dropped, so the preference simply lasts the\n * session.\n */\nexport function localStoragePersistence(key: string | (() => string)): ThemePersistence {\n const keyOf = () => (typeof key === 'function' ? key() : key)\n return {\n read: () => readSelection(keyOf()),\n write(next) {\n const storage = defaultPreferenceStorage()\n if (storage) writeVersionedRecord(storage, keyOf(), next)\n },\n }\n}\n\n/**\n * What a persistence knows, or nothing.\n *\n * The seam's `read` must not throw, and the provider does not rely on that: a host\n * persistence is code the design system has not seen, and a theme provider that\n * fails to mount because a store misbehaved has turned a lost preference into a\n * blank application.\n */\nexport function readPersisted(persistence: ThemePersistence): Partial<ThemeSelection> | undefined {\n return attemptStorage(() => persistence.read(), undefined)\n}\n\n/** Hand a selection to the store; a store that throws loses the preference, not the switch. */\nexport function writePersisted(persistence: ThemePersistence, next: ThemeSelection): void {\n attemptStorage(() => persistence.write(next), undefined)\n}\n\n/**\n * Where a host's versioned preference document lives. One schema describes the\n * document to both halves of the system: {@link createVersionedPersistence} reads and\n * writes it, and `themeScript(options)` reads it before first paint, so the two\n * cannot disagree about a key or a version.\n */\nexport type ThemeStorageSchema = {\n /** The storage key of the document. */\n key: string\n /**\n * The only top-level `version` read. Absent, the document is unversioned. A record\n * of any other version is quarantined (see `recoveryKey`), not interpreted.\n */\n version?: number\n /**\n * The document field that holds the appearance preference (`system`, `light`,\n * `dark`). Read by `themeScript`; the persistence leaves field names to the codec.\n * Default `appearance`.\n */\n appearanceField?: 'appearance' | 'mode'\n /**\n * An older single-value key (`light` | `dark` | `system`) read only while `key` is\n * absent, and never deleted. The persistence hands it to the codec's `fromLegacy`.\n */\n legacyAppearanceKey?: string\n /**\n * The stored library of imported themes, for `themeScript` only: an imported\n * theme's id and verbatim tokens, so the first paint can use the right variant. The\n * persistence neither reads nor writes it.\n */\n libraryKey?: string\n /** Where an unreadable document is kept. Default `${key}.recovery`. */\n recoveryKey?: string\n}\n\n/**\n * How a host's document maps to and from the shared {@link ThemeSelection}.\n *\n * The codec is the product schema: it decides which fields a document has, how an\n * unknown value is corrected, and what a fresh install looks like. The engine decides\n * everything about *storage*: what is quarantined, when the legacy key is read, and\n * that nothing is written until `setSelection` asks.\n */\nexport type VersionedCodec<Doc> = {\n /**\n * A readable record (the right JSON shape and version) as a selection patch. Fields\n * it leaves `undefined` fall back to the provider's defaults. It may keep an id the\n * catalogue lacks; the provider resolves it, it does not rewrite it.\n */\n decode(record: Readonly<Record<string, unknown>>): Partial<ThemeSelection>\n /**\n * The legacy key's value (never `null`) as a selection patch, or `undefined` for a\n * value it does not recognise. Called only when the main key is absent.\n */\n fromLegacy?(value: string): Partial<ThemeSelection> | undefined\n /**\n * What a store with nothing readable answers: a fresh install, an unreadable\n * document, a blocked store. Absent, the provider's own defaults apply.\n */\n defaults?(): Partial<ThemeSelection> | undefined\n /**\n * The document to store for a selection. `previous` is the record last read or\n * written, so a codec can carry a field the selection does not model.\n */\n encode(next: ThemeSelection, previous?: Readonly<Record<string, unknown>>): Doc\n}\n\n/** Seams for the storage and the clock; both default to the real ones. */\nexport type VersionedPersistenceOptions = {\n /** The store, or nothing. Called per access; default is `localStorage` (blocked-safe). */\n storage?: () => PreferenceStorage | undefined\n /** The clock for the recovery envelope's `capturedAt`. */\n now?: () => Date\n}\n\n/**\n * A {@link ThemePersistence} over a versioned document and a host codec.\n *\n * `read` follows the engine's rules (`lib/preference-store.ts`): the main key first;\n * an unreadable or unsupported document is quarantined byte for byte into the\n * recovery key and the codec's `defaults` answer; the legacy key only when the main\n * key is absent. It never writes the main key, so the first write is a user's\n * decision. `write` stores `codec.encode(next, previous)` as JSON and swallows a\n * failure.\n *\n * Neither method throws. The stored bytes are exactly what the codec encodes, so a\n * host keeps its keys, field names and bytes by keeping its codec.\n */\nexport function createVersionedPersistence<Doc>(\n schema: ThemeStorageSchema,\n codec: VersionedCodec<Doc>,\n options: VersionedPersistenceOptions = {}\n): ThemePersistence {\n const storageOf = options.storage ?? defaultPreferenceStorage\n const recordSchema = {\n key: schema.key,\n version: schema.version,\n recoveryKey: recoveryKeyFor(schema),\n }\n let previous: Readonly<Record<string, unknown>> | undefined\n\n const readDocument = (storage: PreferenceStorage): Partial<ThemeSelection> | undefined => {\n const found = readVersionedRecord(storage, recordSchema, options.now)\n if (found.status === 'record') {\n previous = found.record\n return codec.decode(found.record)\n }\n if (found.status !== 'absent' || !schema.legacyAppearanceKey || !codec.fromLegacy) return\n const legacy = readLegacyValue(storage, schema.legacyAppearanceKey)\n return legacy === null ? undefined : codec.fromLegacy(legacy)\n }\n\n return {\n read() {\n const storage = attemptStorage(storageOf, undefined)\n // A codec that throws on a record it cannot read is an unreadable store.\n const found = storage ? attemptStorage(() => readDocument(storage), undefined) : undefined\n return found ?? attemptStorage(() => codec.defaults?.(), undefined)\n },\n write(next) {\n const storage = attemptStorage(storageOf, undefined)\n if (!storage) return\n const unencodable = Symbol()\n const document = attemptStorage<Doc | typeof unencodable>(\n () => codec.encode(next, previous),\n unencodable\n )\n if (document !== unencodable && writeVersionedRecord(storage, schema.key, document)) {\n previous =\n typeof document === 'object' && document !== null\n ? (document as Readonly<Record<string, unknown>>)\n : undefined\n }\n },\n }\n}\n"],"mappings":";;;;;;;AAwCA,SAAS,SAAS,OAA4D;CAC5E,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;;;AAMA,SAAS,cAAc,YAAoC;CACzD,MAAM,SAAS,qBACP,KAAK,MAAM,yBAAyB,CAAC,EAAE,QAAQ,UAAU,KAAK,MAAM,GAC1E,IACF;CACA,IAAI,CAAC,SAAS,MAAM,GAAG,OAAO;CAC9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B,SAAS,cAAc,QAAQ,GAAG;EACpE,IAAI,MAAM,WAAW,UAAU;GAC7B,WAAW,MAAM;GACjB,OAAO,MAAM,OAAO,MAAM,MAAM;EAClC;EACA,IAAI,MAAM,WAAW,YAAY,CAAC,OAAO,uBAAuB,CAAC,MAAM,YAAY;EACnF,MAAM,SAAS,gBAAgB,SAAS,OAAO,mBAAmB;EAClE,OAAO,WAAW,OAAO,KAAA,IAAY,MAAM,WAAW,MAAM;CAC9D;CAEA,OAAO;EACL,OAAO;GACL,MAAM,UAAU,eAAe,WAAW,KAAA,CAAS;GAGnD,QADc,UAAU,qBAAqB,aAAa,OAAO,GAAG,KAAA,CAAS,IAAI,KAAA,MACjE,qBAAqB,MAAM,WAAW,GAAG,KAAA,CAAS;EACpE;EACA,MAAM,MAAM;GACV,MAAM,UAAU,eAAe,WAAW,KAAA,CAAS;GACnD,IAAI,CAAC,SAAS;GACd,MAAM,cAAc,OAAO;GAC3B,MAAM,WAAW,qBACT,MAAM,OAAO,MAAM,QAAQ,GACjC,WACF;GACA,IAAI,aAAa,eAAe,qBAAqB,SAAS,OAAO,KAAK,QAAQ,GAChF,WACE,OAAO,aAAa,YAAY,aAAa,OACxC,WACD,KAAA;EAEV;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"theme-persistence.js","names":[],"sources":["../../../src/components/theme/theme-persistence.ts"],"sourcesContent":["import { normalizeAccentSelection } from '#lib/accent-roles'\nimport { normalizeAppearanceEditorFontSettings } from '#lib/appearance-font-settings'\nimport { defaultDarkThemeId, defaultLightThemeId, storedThemeId } from '#lib/theme-defaults'\nimport { normalizeSurface } from '#lib/theme-surface'\nimport {\n attemptStorage,\n defaultPreferenceStorage,\n readLegacyValue,\n readVersionedRecord,\n recoveryKeyFor,\n writeVersionedRecord,\n type PreferenceStorage,\n} from '#lib/preference-store'\nimport { defaultThemeSelection, resolvedDensity, type ThemeSelection } from './theme-state'\n\n/**\n * Where a selection is kept between sessions.\n *\n * The provider never touches storage itself; it asks a `ThemePersistence`. The\n * default is {@link localStoragePersistence}, which is what the provider always did.\n * A host that stores the preference in a different shape, under a versioned\n * envelope, or somewhere that is not `localStorage` supplies its own and the\n * resolution and application rules stay the shared ones.\n *\n * The contract is deliberately narrow, so that an implementation cannot make the\n * provider less safe than it was:\n *\n * - `read` is synchronous and runs once, when the provider is created. It may\n * repair or quarantine what it finds, and it must not throw: the provider\n * treats a throw as \"nothing stored\" and starts from the defaults.\n * - `write` runs only from `setSelection`. Never on mount, never from `preview`,\n * never as a side effect of reading, so the first write to a store is always a\n * user's decision. A throw is swallowed, because a full or blocked store must\n * not break the switch.\n */\nexport type ThemePersistence = {\n read(): Partial<ThemeSelection> | undefined\n write(next: ThemeSelection): void\n}\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * The stored preference, validated against the policy in `lib/theme-defaults` and\n * `lib/accent-roles`, so reading it never loads the catalogue.\n */\nfunction readSelection(storageKey: string): ThemeSelection {\n const parsed = attemptStorage<unknown>(\n () => JSON.parse(defaultPreferenceStorage()?.getItem(storageKey) ?? 'null'),\n null\n )\n if (!isRecord(parsed)) return defaultThemeSelection\n const stored = parsed as Partial<Record<keyof ThemeSelection, unknown>>\n const fonts = normalizeAppearanceEditorFontSettings(stored.fonts, stored.font).settings\n return {\n appearance:\n stored.appearance === 'light' ||\n stored.appearance === 'dark' ||\n stored.appearance === 'system'\n ? stored.appearance\n : defaultThemeSelection.appearance,\n lightThemeId: storedThemeId(stored.lightThemeId, 'light') ?? defaultLightThemeId,\n darkThemeId: storedThemeId(stored.darkThemeId, 'dark') ?? defaultDarkThemeId,\n accent: normalizeAccentSelection(stored.accent) ?? defaultThemeSelection.accent,\n font: fonts.ui.family,\n fonts,\n // Every axis has to be read back here, or it is lost twice: the provider's\n // document effect removes the `data-density` that `themeScript` set for the first\n // paint, and the next `setSelection` rewrites the store without it.\n density: resolvedDensity(stored as ThemeSelection),\n // The newer axes are read back only when the store holds a usable value and are\n // otherwise left `undefined`, never defaulted: `JSON.stringify` drops them, so a\n // consumer that never sets one writes the bytes it always did.\n terminalThemeId:\n typeof stored.terminalThemeId === 'string' && stored.terminalThemeId.trim() !== ''\n ? stored.terminalThemeId\n : undefined,\n codeThemeId:\n typeof stored.codeThemeId === 'string' && stored.codeThemeId.trim() !== ''\n ? stored.codeThemeId\n : undefined,\n surface: normalizeSurface(stored.surface),\n reduceTransparency:\n typeof stored.reduceTransparency === 'boolean' ? stored.reduceTransparency : undefined,\n }\n}\n\n/**\n * The default persistence: one JSON document in `localStorage` under `key`.\n *\n * Every stored id is validated, and an id is kept even when nothing holds it today\n * (a host's imported theme), exactly as {@link createVersionedPersistence} keeps what\n * its codec decodes: the provider resolves an unknown id, it never rewrites one.\n * `key` may be a function so a provider whose `storageKey` prop changes writes to the\n * key it is now given.\n *\n * Blocked, full or absent storage is survivable in both directions: a read answers\n * with the defaults and a write is dropped, so the preference simply lasts the\n * session.\n */\nexport function localStoragePersistence(key: string | (() => string)): ThemePersistence {\n const keyOf = () => (typeof key === 'function' ? key() : key)\n return {\n read: () => readSelection(keyOf()),\n write(next) {\n const storage = defaultPreferenceStorage()\n if (storage) writeVersionedRecord(storage, keyOf(), next)\n },\n }\n}\n\n/**\n * What a persistence knows, or nothing.\n *\n * The seam's `read` must not throw, and the provider does not rely on that: a host\n * persistence is code the design system has not seen, and a theme provider that\n * fails to mount because a store misbehaved has turned a lost preference into a\n * blank application.\n */\nexport function readPersisted(persistence: ThemePersistence): Partial<ThemeSelection> | undefined {\n return attemptStorage(() => persistence.read(), undefined)\n}\n\n/** Hand a selection to the store; a store that throws loses the preference, not the switch. */\nexport function writePersisted(persistence: ThemePersistence, next: ThemeSelection): void {\n attemptStorage(() => persistence.write(next), undefined)\n}\n\n/**\n * Where a host's versioned preference document lives. One schema describes the\n * document to both halves of the system: {@link createVersionedPersistence} reads and\n * writes it, and `themeScript(options)` reads it before first paint, so the two\n * cannot disagree about a key or a version.\n */\nexport type ThemeStorageSchema = {\n /** The storage key of the document. */\n key: string\n /**\n * The only top-level `version` read. Absent, the document is unversioned. A record\n * of any other version is quarantined (see `recoveryKey`), not interpreted.\n */\n version?: number\n /**\n * The document field that holds the appearance preference (`system`, `light`,\n * `dark`). Read by `themeScript`; the persistence leaves field names to the codec.\n * Default `appearance`.\n */\n appearanceField?: 'appearance' | 'mode'\n /**\n * An older single-value key (`light` | `dark` | `system`) read only while `key` is\n * absent, and never deleted. The persistence hands it to the codec's `fromLegacy`.\n */\n legacyAppearanceKey?: string\n /**\n * The stored library of imported themes, for `themeScript` only: an imported\n * theme's id and verbatim tokens, so the first paint can use the right variant. The\n * persistence neither reads nor writes it.\n */\n libraryKey?: string\n /** Where an unreadable document is kept. Default `${key}.recovery`. */\n recoveryKey?: string\n}\n\n/**\n * How a host's document maps to and from the shared {@link ThemeSelection}.\n *\n * The codec is the product schema: it decides which fields a document has, how an\n * unknown value is corrected, and what a fresh install looks like. The engine decides\n * everything about *storage*: what is quarantined, when the legacy key is read, and\n * that nothing is written until `setSelection` asks.\n */\nexport type VersionedCodec<Doc> = {\n /**\n * A readable record (the right JSON shape and version) as a selection patch. Fields\n * it leaves `undefined` fall back to the provider's defaults. It may keep an id the\n * catalogue lacks; the provider resolves it, it does not rewrite it.\n */\n decode(record: Readonly<Record<string, unknown>>): Partial<ThemeSelection>\n /**\n * The legacy key's value (never `null`) as a selection patch, or `undefined` for a\n * value it does not recognise. Called only when the main key is absent.\n */\n fromLegacy?(value: string): Partial<ThemeSelection> | undefined\n /**\n * What a store with nothing readable answers: a fresh install, an unreadable\n * document, a blocked store. Absent, the provider's own defaults apply.\n */\n defaults?(): Partial<ThemeSelection> | undefined\n /**\n * The document to store for a selection. `previous` is the record last read or\n * written, so a codec can carry a field the selection does not model.\n */\n encode(next: ThemeSelection, previous?: Readonly<Record<string, unknown>>): Doc\n}\n\n/** Seams for the storage and the clock; both default to the real ones. */\nexport type VersionedPersistenceOptions = {\n /** The store, or nothing. Called per access; default is `localStorage` (blocked-safe). */\n storage?: () => PreferenceStorage | undefined\n /** The clock for the recovery envelope's `capturedAt`. */\n now?: () => Date\n}\n\n/**\n * A {@link ThemePersistence} over a versioned document and a host codec.\n *\n * `read` follows the engine's rules (`lib/preference-store.ts`): the main key first;\n * an unreadable or unsupported document is quarantined byte for byte into the\n * recovery key and the codec's `defaults` answer; the legacy key only when the main\n * key is absent. It never writes the main key, so the first write is a user's\n * decision. `write` stores `codec.encode(next, previous)` as JSON and swallows a\n * failure.\n *\n * Neither method throws. The stored bytes are exactly what the codec encodes, so a\n * host keeps its keys, field names and bytes by keeping its codec.\n */\nexport function createVersionedPersistence<Doc>(\n schema: ThemeStorageSchema,\n codec: VersionedCodec<Doc>,\n options: VersionedPersistenceOptions = {}\n): ThemePersistence {\n const storageOf = options.storage ?? defaultPreferenceStorage\n const recordSchema = {\n key: schema.key,\n version: schema.version,\n recoveryKey: recoveryKeyFor(schema),\n }\n let previous: Readonly<Record<string, unknown>> | undefined\n\n const readDocument = (storage: PreferenceStorage): Partial<ThemeSelection> | undefined => {\n const found = readVersionedRecord(storage, recordSchema, options.now)\n if (found.status === 'record') {\n previous = found.record\n return codec.decode(found.record)\n }\n if (found.status !== 'absent' || !schema.legacyAppearanceKey || !codec.fromLegacy) return\n const legacy = readLegacyValue(storage, schema.legacyAppearanceKey)\n return legacy === null ? undefined : codec.fromLegacy(legacy)\n }\n\n return {\n read() {\n const storage = attemptStorage(storageOf, undefined)\n // A codec that throws on a record it cannot read is an unreadable store.\n const found = storage ? attemptStorage(() => readDocument(storage), undefined) : undefined\n return found ?? attemptStorage(() => codec.defaults?.(), undefined)\n },\n write(next) {\n const storage = attemptStorage(storageOf, undefined)\n if (!storage) return\n const unencodable = Symbol()\n const document = attemptStorage<Doc | typeof unencodable>(\n () => codec.encode(next, previous),\n unencodable\n )\n if (document !== unencodable && writeVersionedRecord(storage, schema.key, document)) {\n previous =\n typeof document === 'object' && document !== null\n ? (document as Readonly<Record<string,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ts","sourceRoot":"","sources":["../../../src/components/theme/theme-provider-value.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAUnC,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAA;AAKrE,OAAO,EAAiC,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAA;AACnF,OAAO,KAAK,EAAE,eAAe,EAAmB,YAAY,EAAE,MAAM,kBAAkB,CAAA;AAGtF,OAAO,EAIL,KAAK,gBAAgB,EACtB,MAAM,qBAAqB,CAAA;AAC5B,OAAO,
|
|
1
|
+
{"version":3,"file":"theme-provider-value.d.ts","sourceRoot":"","sources":["../../../src/components/theme/theme-provider-value.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAUnC,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAA;AAKrE,OAAO,EAAiC,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAA;AACnF,OAAO,KAAK,EAAE,eAAe,EAAmB,YAAY,EAAE,MAAM,kBAAkB,CAAA;AAGtF,OAAO,EAIL,KAAK,gBAAgB,EACtB,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EASL,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACpB,MAAM,eAAe,CAAA;AAEtB;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,QAAQ,CAAC,EAAE,GAAG,CAAC,OAAO,CAAA;IACtB,mEAAmE;IACnE,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,wDAAwD;IACxD,OAAO,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,CAAA;IACjC;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,CAAA;IACnC;;;;;OAKG;IACH,WAAW,CAAC,EAAE,gBAAgB,CAAA;IAC9B;;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