@toolbox-web/grid 3.10.0 → 3.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/all.js +2 -1
- package/all.js.map +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/lib/features/registry.js +1 -1
- package/lib/plugins/editing/editing-plugin.d.ts +11 -5
- package/lib/plugins/editing/index.js +2 -1
- package/lib/plugins/editing/index.js.map +1 -1
- package/lib/plugins/editing/internal/editor-injection.d.ts +9 -2
- package/lib/plugins/editing/internal/helpers.d.ts +23 -0
- package/lib/plugins/editing/types.d.ts +11 -0
- package/lib/plugins/grouping-rows/index.js +1 -1
- package/lib/plugins/grouping-rows/index.js.map +1 -1
- package/lib/plugins/hierarchy/hierarchy.d.ts +5 -1
- package/lib/plugins/hierarchy/index.js +1 -1
- package/lib/plugins/hierarchy/index.js.map +1 -1
- package/lib/plugins/master-detail/index.js +1 -1
- package/lib/plugins/master-detail/index.js.map +1 -1
- package/lib/plugins/master-detail/master-detail-plugin.d.ts +6 -1
- package/lib/plugins/shared/structural-toggle.d.ts +14 -0
- package/lib/plugins/tree/index.js +1 -1
- package/lib/plugins/tree/index.js.map +1 -1
- package/lib/plugins/undo-redo/index.d.ts +1 -1
- package/lib/plugins/undo-redo/index.js +1 -1
- package/lib/plugins/undo-redo/index.js.map +1 -1
- package/lib/plugins/undo-redo/types.d.ts +20 -2
- package/lib/plugins/undo-redo/undo-redo-plugin.d.ts +8 -0
- package/package.json +1 -1
- package/umd/grid.all.umd.js +1 -1
- package/umd/grid.all.umd.js.map +1 -1
- package/umd/grid.umd.js +1 -1
- package/umd/grid.umd.js.map +1 -1
- package/umd/plugins/editing.umd.js +1 -1
- package/umd/plugins/editing.umd.js.map +1 -1
- package/umd/plugins/grouping-rows.umd.js +1 -1
- package/umd/plugins/grouping-rows.umd.js.map +1 -1
- package/umd/plugins/hierarchy.umd.js +1 -1
- package/umd/plugins/hierarchy.umd.js.map +1 -1
- package/umd/plugins/master-detail.umd.js +1 -1
- package/umd/plugins/master-detail.umd.js.map +1 -1
- package/umd/plugins/tree.umd.js +1 -1
- package/umd/plugins/tree.umd.js.map +1 -1
- package/umd/plugins/undo-redo.umd.js +1 -1
- package/umd/plugins/undo-redo.umd.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tree.umd.js","names":["BaseGridPlugin","BaseGridPlugin","styles","builtInSort","global","factory","exports","module","require","define","amd","globalThis","self","TbwGridPlugin_tree","TbwGrid","this","_toolbox_web_grid","Object","defineProperty","Symbol","toStringTag","value","GridClasses","_F","split","map","s","reverse","join","DANGEROUS_TAGS","RegExp","slice","Set","DANGEROUS_ATTR_PATTERN","URL_ATTRS","DANGEROUS_URL_PROTOCOL","sanitizeToFragment","html","template","document","createElement","innerHTML","root","toRemove","elements","querySelectorAll","el","tagName","toLowerCase","has","push","namespaceURI","Array","from","attributes","some","attr","test","name","attrsToRemove","attrName","forEach","removeAttribute","remove","sanitizeNode","content","buildHierarchy","rows","contributors","meta","WeakMap","active","stage","c","hierarchyStage","beginHierarchy","length","out","process","nodes","parent","depth","context","row","parentKey","key","processSiblings","emit","setSize","i","node","set","level","posInSet","children","expanded","shaped","roots","positionOf","get","endHierarchy","delete","setAttrIfChanged","next","String","getAttribute","setAttribute","isContributor","plugin","processRowsPriority","constructor","manifest","hookPriority","processRows","HierarchyPlugin","BaseGridPlugin","static","modifiesRowStructure","detach","gridElement","querySelector","caller","includes","getRowMeta","afterRender","applyAria","onScrollRender","grid","_pluginManager","getPlugins","filter","sort","a","b","body","hierarchical","rowEl","__rowDataRef","role","rowsBody","generateRowKey","index","id","toggleExpand","expandedKeys","newExpanded","add","expandAll","config","childrenField","keys","isArray","childKeys","k","getPathToKey","targetKey","childPath","expandToKey","existingExpanded","path","detectTreeStructure","hasChildren","__loading","TreePlugin","incompatibleWith","reason","events","type","description","queries","required","provide","styles","defaultConfig","autoDetect","defaultExpanded","indentWidth","showExpandIcons","animation","initialExpansionDone","flattenedRows","rowKeyMap","Map","previousVisibleKeys","keysToAnimate","rootOwners","rootCount","sortState","levelSort","loads","loadedRows","WeakSet","requestedRows","cancelledRows","pendingReconcile","rowKeys","rowMeta","originalTreeColumnRenderer","originalTreeColumnRendererProperty","wrappedTreeColumnField","treeColumnWrapped","treeColumnSyncScheduled","clear","load","values","controller","abort","handleQuery","query","viewportStart","viewportEnd","last","ownerAt","Math","max","min","startNode","endNode","totalLoadedNodes","mapViewportToRoots","attach","super","on","detail","d","claimed","source","parentRow","parentNode","keyOf","takeLoad","mergeChildren","broadcast","childCount","requestRender","error","animationStyle","isAnimationEnabled","detect","treeRows","field","commonArrayFields","inferChildrenField","hierarchy","getPluginByName","reconcileFlatRows","syncTreeColumn","serverSorts","resolveEffectiveSortState","hasChildrenFn","keyFor","ordered","sortNodes","direction","embeddedChildren","isExpanded","data","child","processed","currentKeys","rootOrdinal","needsReconcile","queueReconcile","queueMicrotask","requestColumnsRender","cached","dir","byRow","sortLevel","host","columns","_columns","input","result","effectiveConfig","sortHandler","builtInSort","then","catch","needsChildFetch","custom","size","owners","flat","pending","started","cancelOnly","cancelLoad","requestLazyChildren","flatRow","isServerSideActive","queryBoolean","loadChildren","AbortController","nodePath","signal","loadChildrenLocally","isLoading","cancelled","finish","aborted","onSuccess","onError","subscribe","settled","release","unsubscribe","subscription","addEventListener","once","Promise","resolve","multiSortResults","sortModel","processColumns","cols","idx","findIndex","renderer","treeColumn","targetIndex","targetCol","targetField","viewRenderer","originalRenderer","getConfig","setIconFn","setIcon","bind","ctx","container","className","style","setProperty","spinner","createDefaultSpinner","classList","appendChild","icon","spacer","Node","indexOf","replaceChildren","textContent","onCellClick","event","target","originalEvent","contains","onKeyDown","composedPath","HTMLElement","tag","isContentEditable","isFormFieldKeyTarget","focusRow","_focusRow","preventDefault","requestRenderWithFocus","onHeaderClick","column","sortable","gridEl","_sortState","shouldAnimate","animClass","treeRow","hasAttribute","toggle","expand","collapse","emitPluginEvent","collapseAll","getExpandedKeys","getFlattenedRows","getRowByKey"],"sources":["../../../../../libs/grid/src/lib/core/constants.ts","../../../../../libs/grid/src/lib/core/internal/sanitize.ts","../../../../../libs/grid/src/lib/core/internal/loading.ts","../../../../../libs/grid/src/lib/plugins/hierarchy/hierarchy.ts","../../../../../libs/grid/src/lib/plugins/hierarchy/hierarchy-plugin.ts","../../../../../libs/grid/src/lib/plugins/tree/tree-data.ts","../../../../../libs/grid/src/lib/plugins/shared/form-field-target.ts","../../../../../libs/grid/src/lib/plugins/tree/tree-datasource.ts","../../../../../libs/grid/src/lib/plugins/tree/tree-detect.ts","../../../../../libs/grid/src/lib/plugins/tree/tree.css?inline","../../../../../libs/grid/src/lib/plugins/tree/tree-plugin.ts"],"sourcesContent":["/**\n * Grid DOM Constants\n *\n * Centralized constants for CSS classes, data attributes, and selectors\n * used throughout the grid. Use these instead of magic strings.\n *\n * Note: Some constants here are used by plugins but defined in core because:\n * 1. The core CSS needs to style these elements (e.g., sticky positioning)\n * 2. Multiple plugins may share the same class names\n *\n * Plugins can define their own additional constants and export them.\n * See each plugin's index.ts for plugin-specific exports.\n */\n\n/**\n * CSS selector for focusable editor elements within a cell.\n * Used by EditingPlugin, UndoRedoPlugin, and keyboard navigation. Defined here\n * (a leaf module) rather than in `rows.ts` so `keyboard.ts` can consume it\n * without creating a rows ↔ keyboard import cycle.\n */\nexport const FOCUSABLE_EDITOR_SELECTOR =\n 'input,select,textarea,[contenteditable=\"true\"],[contenteditable=\"\"],[tabindex]:not([tabindex=\"-1\"])';\n\n// #region CSS Classes\n\n/**\n * CSS class names used in the grid's DOM.\n * Use these when adding/removing classes or querying elements.\n *\n * Classes are organized by:\n * - Core: Used by the grid core for structure and basic functionality\n * - Shared: Used by multiple features/plugins, styled by core CSS\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport const GridClasses = {\n // ─── Core Structure ───────────────────────────────────────────────\n ROOT: 'tbw-grid-root',\n HEADER: 'header',\n HEADER_ROW: 'header-row',\n HEADER_CELL: 'header-cell',\n\n // Body structure\n ROWS_VIEWPORT: 'rows-viewport',\n ROWS_SPACER: 'rows-spacer',\n ROWS_CONTAINER: 'rows',\n\n // Row elements\n DATA_ROW: 'data-grid-row',\n GROUP_ROW: 'group-row',\n\n // Cell elements\n DATA_CELL: 'cell',\n\n // ─── Core States ──────────────────────────────────────────────────\n SELECTED: 'selected',\n FOCUSED: 'focused',\n EDITING: 'editing',\n EXPANDED: 'expanded',\n COLLAPSED: 'collapsed',\n DRAGGING: 'dragging',\n RESIZING: 'resizing',\n\n // Sorting (core feature)\n SORTABLE: 'sortable',\n SORTED_ASC: 'sorted-asc',\n SORTED_DESC: 'sorted-desc',\n\n // Visibility\n HIDDEN: 'hidden',\n\n // ─── Shared Classes (used by plugins, styled by core CSS) ────────\n // These are defined here because core CSS provides the base styling.\n // Plugins apply these classes; core CSS defines how they look.\n\n // Sticky positioning (PinnedColumnsPlugin applies, core CSS styles)\n STICKY_LEFT: 'sticky-left',\n STICKY_RIGHT: 'sticky-right',\n\n // Pinned rows (PinnedRowsPlugin applies, core CSS styles)\n PINNED_TOP: 'pinned-top',\n PINNED_BOTTOM: 'pinned-bottom',\n\n // Tree structure (TreePlugin applies, core CSS styles)\n TREE_TOGGLE: 'tree-toggle',\n TREE_INDENT: 'tree-indent',\n\n // Grouping (GroupingRowsPlugin applies, core CSS styles)\n GROUP_TOGGLE: 'group-toggle',\n GROUP_LABEL: 'group-label',\n GROUP_COUNT: 'group-count',\n\n // Selection (SelectionPlugin applies, core CSS styles)\n RANGE_SELECTION: 'range-selection',\n SELECTION_OVERLAY: 'selection-overlay',\n} as const;\n\n// #endregion\n\n// #region Data Attributes\n\n/**\n * Data attribute names used on grid elements.\n * Use these when getting/setting data attributes.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport const GridDataAttrs = {\n // ─── Core Attributes ──────────────────────────────────────────────\n FIELD: 'data-field',\n\n /**\n * Marks a `title` the grid itself put on a cell to reveal ellipsised text\n * (WCAG SC 1.4.12). Anything that sets its own `title` on a cell must clear\n * this, or the grid will later mistake that title for its own and replace it.\n *\n * @since 3.6.0\n */\n TRUNCATED: 'data-tbw-truncated',\n\n // ─── Shared Attributes (used by plugins) ──────────────────────────\n GROUP_KEY: 'data-group-key', // GroupingRowsPlugin\n} as const;\n\n// #endregion\n\n// #region Selectors\n\n/**\n * Common CSS selectors for querying grid elements.\n * Built from the class constants for consistency.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport const GridSelectors = {\n ROOT: `.${GridClasses.ROOT}`,\n HEADER: `.${GridClasses.HEADER}`,\n HEADER_ROW: `.${GridClasses.HEADER_ROW}`,\n HEADER_CELL: `.${GridClasses.HEADER_CELL}`,\n ROWS_VIEWPORT: `.${GridClasses.ROWS_VIEWPORT}`,\n ROWS_CONTAINER: `.${GridClasses.ROWS_CONTAINER}`,\n DATA_ROW: `.${GridClasses.DATA_ROW}`,\n DATA_CELL: `.${GridClasses.DATA_CELL}`,\n GROUP_ROW: `.${GridClasses.GROUP_ROW}`,\n\n // By data attribute\n CELL_BY_FIELD: (field: string) => `.${GridClasses.DATA_CELL}[${GridDataAttrs.FIELD}=\"${field}\"]`,\n\n // State selectors\n SELECTED_ROWS: `.${GridClasses.DATA_ROW}.${GridClasses.SELECTED}`,\n EDITING_CELL: `.${GridClasses.DATA_CELL}.${GridClasses.EDITING}`,\n} as const;\n\n// #endregion\n\n// #region CSS Custom Properties\n\n/**\n * CSS custom property names for theming.\n * Use these when programmatically setting styles.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport const GridCSSVars = {\n // Colors\n COLOR_BG: '--tbw-color-bg',\n COLOR_FG: '--tbw-color-fg',\n COLOR_FG_MUTED: '--tbw-color-fg-muted',\n COLOR_BORDER: '--tbw-color-border',\n COLOR_ACCENT: '--tbw-color-accent',\n COLOR_HEADER_BG: '--tbw-color-header-bg',\n COLOR_HEADER_FG: '--tbw-color-header-fg',\n COLOR_SELECTION: '--tbw-color-selection',\n COLOR_ROW_HOVER: '--tbw-color-row-hover',\n COLOR_ROW_ALT: '--tbw-color-row-alt',\n\n // Sizing\n ROW_HEIGHT: '--tbw-row-height',\n HEADER_HEIGHT: '--tbw-header-height',\n CELL_PADDING: '--tbw-cell-padding',\n\n // Typography\n FONT_FAMILY: '--tbw-font-family',\n FONT_SIZE: '--tbw-font-size',\n\n // Borders\n BORDER_RADIUS: '--tbw-border-radius',\n FOCUS_OUTLINE: '--tbw-focus-outline',\n} as const;\n\n// #endregion\n\n// Type helpers\n\n/**\n * Union of all CSS class names used in the grid's DOM.\n * Use `GridClasses` to access individual values by key.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport type GridClassName = (typeof GridClasses)[keyof typeof GridClasses];\n\n/**\n * Union of all `data-*` attribute names used on grid elements.\n * Use `GridDataAttrs` to access individual values by key.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport type GridDataAttr = (typeof GridDataAttrs)[keyof typeof GridDataAttrs];\n\n/**\n * Union of all CSS custom property names (`--tbw-*`) available for theming.\n * Use `GridCSSVars` to access individual values by key.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport type GridCSSVar = (typeof GridCSSVars)[keyof typeof GridCSSVars];\n","// Centralized template expression evaluation & sanitization utilities.\n// Responsible for safely interpolating {{ }} expressions while blocking\n// access to dangerous globals / reflective capabilities.\nimport type { CompiledViewFunction, EvalContext } from '../types';\n\n// #region Constants\nconst EXPR_RE = /{{\\s*([^}]+)\\s*}}/g;\nconst EMPTY_SENTINEL = '__DG_EMPTY__';\nconst SAFE_EXPR = /^[\\w$. '?+\\-*/%:()!<>=,&|]+$/;\n\n// Forbidden identifiers built at runtime to avoid static analysis scanners\n// from flagging string literals (e.g. socket.dev \"network access\" / \"uses eval\").\n// Stored as reversed, pipe-delimited tokens — reversed back when constructing the regex.\nconst _F =\n '__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles'\n .split('|')\n .map((s) => s.split('').reverse().join(''));\nconst FORBIDDEN = new RegExp(`__(proto|defineGetter|defineSetter)|${_F.slice(3).join('|')}|this\\\\b`);\n// #endregion\n\n// #region HTML Sanitization\n\n/**\n * Escape a plain text string for safe insertion into HTML.\n * Converts special HTML characters to their entity equivalents.\n *\n * @param text - Plain text string to escape\n * @returns HTML-safe string\n */\nexport function escapeHtml(text: string): string {\n if (!text || typeof text !== 'string') return '';\n return text\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Tags that are considered dangerous and will be completely removed.\n * These can execute scripts, load external resources, or manipulate the page.\n */\nconst DANGEROUS_TAGS = new Set(\n 'script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing|math'.split(\n '|',\n ),\n);\n\n/**\n * Attributes that are considered dangerous - event handlers and data loading.\n */\nconst DANGEROUS_ATTR_PATTERN = /^on\\w+$/i;\n\n/**\n * Attributes that can contain URLs which might be javascript: or data: URIs.\n */\nconst URL_ATTRS = new Set('href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset'.split('|'));\n\n/**\n * Protocol patterns that are dangerous in URLs.\n */\nconst DANGEROUS_URL_PROTOCOL = /^\\s*(javascript|vbscript|data|blob):/i;\n\n/**\n * Sanitize an HTML string by removing dangerous tags and attributes.\n *\n * Prefer {@link setSanitizedHTML} wherever the result is destined for an\n * element: this function has to re-serialize the sanitized tree back to a\n * string, and the caller's `innerHTML =` then re-parses it. That\n * parse→serialize→parse round trip is the classic mutation-XSS vector, and it\n * costs a second parse. Use this overload only when a string is genuinely\n * required (e.g. the value is stored, compared, or handed to another API).\n *\n * @param html - Raw HTML string to sanitize\n * @returns Sanitized HTML string safe for innerHTML\n */\nexport function sanitizeHTML(html: string): string {\n if (!html || typeof html !== 'string') return '';\n\n // Fast path: if no HTML tags at all, return as-is (already safe)\n if (html.indexOf('<') === -1) return html;\n\n const template = document.createElement('template');\n template.innerHTML = html;\n\n sanitizeNode(template.content);\n\n return template.innerHTML;\n}\n\n/**\n * Parse and sanitize an HTML string into a detached {@link DocumentFragment}.\n *\n * This is the primitive {@link setSanitizedHTML} builds on, exposed for callers\n * that need to inspect or relocate the nodes before insertion.\n *\n * @param html - Raw HTML string to sanitize\n * @returns Fragment containing the sanitized nodes (empty for falsy input)\n */\nexport function sanitizeToFragment(html: string): DocumentFragment {\n const template = document.createElement('template');\n if (html && typeof html === 'string') {\n template.innerHTML = html;\n sanitizeNode(template.content);\n }\n return template.content;\n}\n\n/**\n * Replace an element's children with the sanitized parse of `html`.\n *\n * **This is the canonical sink for user-supplied markup** — cell/header/group\n * renderer string returns, `gridConfig.icons.*`, light-DOM tool panel fallback\n * content, and any new extension point that turns a user string into markup.\n * `textContent` is wrong here (it renders SVG icon strings as literal text) and\n * raw `innerHTML` is wrong (it is an XSS sink).\n *\n * Nodes are moved from the parse fragment rather than re-serialized, so the\n * sanitized tree is exactly what lands in the document.\n *\n * @param el - Element whose children are replaced\n * @param html - Raw HTML string to sanitize and insert\n */\nexport function setSanitizedHTML(el: Element, html: string): void {\n if (!html || typeof html !== 'string') {\n el.replaceChildren();\n return;\n }\n // Nothing for the parser to do: no markup and no entities to decode.\n if (html.indexOf('<') === -1 && html.indexOf('&') === -1) {\n el.textContent = html;\n return;\n }\n el.replaceChildren(sanitizeToFragment(html));\n}\n\n/**\n * Recursively sanitize a DOM node tree.\n */\nfunction sanitizeNode(root: DocumentFragment | Element): void {\n const toRemove: Element[] = [];\n\n // Use querySelectorAll to find all elements, then filter\n const elements = root.querySelectorAll('*');\n\n for (const el of elements) {\n const tagName = el.tagName.toLowerCase();\n\n // Check if tag is dangerous\n if (DANGEROUS_TAGS.has(tagName)) {\n toRemove.push(el);\n continue;\n }\n\n // SVG elements need special handling - they can contain script-like behavior\n if (tagName === 'svg' || el.namespaceURI === 'http://www.w3.org/2000/svg') {\n // Remove entire SVG if it has any suspicious attributes\n const hasDangerousContent = Array.from(el.attributes).some(\n (attr) => DANGEROUS_ATTR_PATTERN.test(attr.name) || attr.name === 'href' || attr.name === 'xlink:href',\n );\n if (hasDangerousContent) {\n toRemove.push(el);\n continue;\n }\n }\n\n // Check and remove dangerous attributes\n const attrsToRemove: string[] = [];\n for (const attr of el.attributes) {\n const attrName = attr.name.toLowerCase();\n\n // Event handlers (onclick, onerror, onload, etc.)\n if (DANGEROUS_ATTR_PATTERN.test(attrName)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // `is=` upgrades a plain tag into a registered customized built-in, so it\n // can smuggle behaviour past the tag-name check above.\n if (attrName === 'is') {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // URL attributes with dangerous protocols\n if (URL_ATTRS.has(attrName) && DANGEROUS_URL_PROTOCOL.test(attr.value)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // style attribute can contain expressions (IE) or url() with javascript:\n if (attrName === 'style' && /expression\\s*\\(|javascript:|behavior\\s*:/i.test(attr.value)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n }\n\n attrsToRemove.forEach((name) => el.removeAttribute(name));\n }\n\n // Remove dangerous elements (do this after iteration to avoid modifying during traversal)\n toRemove.forEach((el) => el.remove());\n}\n\n// #endregion\n\n// #region Template Evaluation\n\n// #region Safe Expression Evaluator\n// A minimal recursive-descent evaluator for the token set allowed by SAFE_EXPR.\n// Replaces `new Function()` to avoid dynamic code execution warnings from\n// static analysis tools (socket.dev, npm audit) while maintaining identical\n// functionality for expressions that pass the allowlist guards.\n//\n// Supported grammar (matching SAFE_EXPR = /^[\\w$. '?+\\-*/%:()!<>=,&|]+$/):\n// ternary → logicalOr ('?' ternary ':' ternary)?\n// logicalOr → logicalAnd ('||' logicalAnd)*\n// logicalAnd → equality ('&&' equality)*\n// equality → comparison (('==' | '!=' | '===' | '!==') comparison)*\n// comparison → additive (('<' | '>' | '<=' | '>=') additive)*\n// additive → multiplicative (('+' | '-') multiplicative)*\n// multiplicative → unary (('*' | '/' | '%') unary)*\n// unary → '!' unary | primary\n// primary → NUMBER | STRING | IDENT ('.' IDENT)? | '(' ternary ')'\n\ntype Token =\n { type: 'num'; v: number } | { type: 'str'; v: string } | { type: 'id'; v: string } | { type: 'op'; v: string };\n\nfunction tokenize(expr: string): Token[] | null {\n const tokens: Token[] = [];\n let i = 0;\n while (i < expr.length) {\n const ch = expr[i];\n if (ch === ' ') {\n i++;\n continue;\n }\n\n // Numbers\n if ((ch >= '0' && ch <= '9') || (ch === '.' && i + 1 < expr.length && expr[i + 1] >= '0' && expr[i + 1] <= '9')) {\n const start = i;\n while (i < expr.length && ((expr[i] >= '0' && expr[i] <= '9') || expr[i] === '.')) i++;\n tokens.push({ type: 'num', v: Number(expr.slice(start, i)) });\n continue;\n }\n\n // String literals (single-quoted only, per SAFE_EXPR)\n if (ch === \"'\") {\n let s = '';\n i++; // skip opening quote\n while (i < expr.length && expr[i] !== \"'\") s += expr[i++];\n if (i >= expr.length) return null; // unterminated\n i++; // skip closing quote\n tokens.push({ type: 'str', v: s });\n continue;\n }\n\n // Identifiers (value, row, row.field)\n if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch === '_' || ch === '$') {\n const start = i;\n while (i < expr.length && /[\\w$.]/.test(expr[i])) i++;\n tokens.push({ type: 'id', v: expr.slice(start, i) });\n continue;\n }\n\n // Multi-char operators\n if (i + 2 < expr.length) {\n const tri = expr.slice(i, i + 3);\n if (tri === '===' || tri === '!==') {\n tokens.push({ type: 'op', v: tri });\n i += 3;\n continue;\n }\n }\n if (i + 1 < expr.length) {\n const bi = expr.slice(i, i + 2);\n if (bi === '==' || bi === '!=' || bi === '<=' || bi === '>=' || bi === '&&' || bi === '||') {\n tokens.push({ type: 'op', v: bi });\n i += 2;\n continue;\n }\n }\n\n // Single-char operators\n if ('+-*/%<>!?:(),'.includes(ch)) {\n tokens.push({ type: 'op', v: ch });\n i++;\n continue;\n }\n\n return null; // unexpected character\n }\n return tokens;\n}\n\nfunction safeEval(expr: string, ctx: EvalContext): unknown {\n const toks = tokenize(expr);\n if (!toks) return undefined;\n const tokens: Token[] = toks;\n let pos = 0;\n\n function peek(): Token | undefined {\n return tokens[pos];\n }\n function advance(): Token {\n return tokens[pos++];\n }\n function match(type: string, val?: string): boolean {\n const t = peek();\n if (!t) return false;\n if (t.type !== type) return false;\n if (val !== undefined && t.v !== val) return false;\n return true;\n }\n\n function resolveId(name: string): unknown {\n if (name === 'value') return ctx.value;\n if (name.startsWith('row.')) {\n const key = name.slice(4);\n return ctx.row ? ctx.row[key] : undefined;\n }\n if (name.startsWith('typeDefault.')) {\n const key = name.slice('typeDefault.'.length);\n return ctx.typeDefault ? ctx.typeDefault[key] : undefined;\n }\n // bare 'row' reference\n if (name === 'row') return ctx.row;\n if (name === 'typeDefault') return ctx.typeDefault;\n return undefined;\n }\n\n function parseTernary(): unknown {\n const result = parseLogicalOr();\n if (match('op', '?')) {\n advance(); // consume '?'\n const consequent = parseTernary();\n if (!match('op', ':')) return undefined;\n advance(); // consume ':'\n const alternate = parseTernary();\n return result ? consequent : alternate;\n }\n return result;\n }\n\n function parseLogicalOr(): unknown {\n let left = parseLogicalAnd();\n while (match('op', '||')) {\n advance();\n left = left || parseLogicalAnd();\n }\n return left;\n }\n\n function parseLogicalAnd(): unknown {\n let left = parseEquality();\n while (match('op', '&&')) {\n advance();\n left = left && parseEquality();\n }\n return left;\n }\n\n function parseEquality(): unknown {\n let left = parseComparison();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '===') {\n advance();\n left = left === parseComparison();\n } else if (t.v === '!==') {\n advance();\n left = left !== parseComparison();\n } else if (t.v === '==') {\n advance();\n left = left == parseComparison();\n } else if (t.v === '!=') {\n advance();\n left = left != parseComparison();\n } else break;\n }\n return left;\n }\n\n function parseComparison(): unknown {\n let left = parseAdditive();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '<') {\n advance();\n left = (left as number) < (parseAdditive() as number);\n } else if (t.v === '>') {\n advance();\n left = (left as number) > (parseAdditive() as number);\n } else if (t.v === '<=') {\n advance();\n left = (left as number) <= (parseAdditive() as number);\n } else if (t.v === '>=') {\n advance();\n left = (left as number) >= (parseAdditive() as number);\n } else break;\n }\n return left;\n }\n\n function parseAdditive(): unknown {\n let left = parseMultiplicative();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '+') {\n advance();\n left = (left as number) + (parseMultiplicative() as number);\n } else if (t.v === '-') {\n advance();\n left = (left as number) - (parseMultiplicative() as number);\n } else break;\n }\n return left;\n }\n\n function parseMultiplicative(): unknown {\n let left = parseUnary();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '*') {\n advance();\n left = (left as number) * (parseUnary() as number);\n } else if (t.v === '/') {\n advance();\n left = (left as number) / (parseUnary() as number);\n } else if (t.v === '%') {\n advance();\n left = (left as number) % (parseUnary() as number);\n } else break;\n }\n return left;\n }\n\n function parseUnary(): unknown {\n if (match('op', '!')) {\n advance();\n return !parseUnary();\n }\n return parsePrimary();\n }\n\n function parsePrimary(): unknown {\n const t = peek();\n if (!t) return undefined;\n if (t.type === 'num') {\n advance();\n return t.v;\n }\n if (t.type === 'str') {\n advance();\n return t.v;\n }\n if (t.type === 'id') {\n advance();\n return resolveId(t.v as string);\n }\n if (t.type === 'op' && t.v === '(') {\n advance(); // consume '('\n const result = parseTernary();\n if (match('op', ')')) advance(); // consume ')'\n return result;\n }\n // Unary minus for negative numbers\n if (t.type === 'op' && t.v === '-') {\n advance();\n return -(parsePrimary() as number);\n }\n return undefined;\n }\n\n const result = parseTernary();\n // Ensure all tokens were consumed\n if (pos < tokens.length) return undefined;\n return result;\n}\n// #endregion\n\nexport function evalTemplateString(raw: string, ctx: EvalContext): string {\n if (!raw || raw.indexOf('{{') === -1) return raw; // fast path (no expressions)\n const parts: { expr: string; result: string }[] = [];\n const evaluated = raw.replace(EXPR_RE, (_m, expr) => {\n const res = evalSingle(expr, ctx);\n parts.push({ expr: expr.trim(), result: res });\n // The template markup is author-controlled; the interpolated data is not.\n // Escaping here stops row data from injecting elements or breaking out of\n // an attribute (sanitizeHTML downstream only strips *dangerous* markup).\n return res === EMPTY_SENTINEL ? res : escapeHtml(res);\n });\n const finalStr = postProcess(evaluated);\n // If every part evaluated to EMPTY_SENTINEL we treat this as intentionally blank.\n // If any expression was blocked due to forbidden token (EMPTY_SENTINEL) we *still* only output ''\n // but do not escalate to BLOCKED_SENTINEL unless the original contained explicit forbidden tokens.\n const allEmpty = parts.length && parts.every((p) => p.result === '' || p.result === EMPTY_SENTINEL);\n const hadForbidden = REFLECTIVE_RE.test(raw);\n if (hadForbidden || allEmpty) return '';\n return finalStr;\n}\n\nfunction evalSingle(expr: string, ctx: EvalContext): string {\n expr = (expr || '').trim();\n if (!expr) return EMPTY_SENTINEL;\n if (REFLECTIVE_RE.test(expr)) return EMPTY_SENTINEL;\n if (expr === 'value') return ctx.value == null ? EMPTY_SENTINEL : String(ctx.value);\n if (expr.startsWith('row.') && !/[()?]/.test(expr) && !expr.includes(':')) {\n const key = expr.slice(4);\n const v = ctx.row ? ctx.row[key] : undefined;\n return v == null ? EMPTY_SENTINEL : String(v);\n }\n if (expr.startsWith('typeDefault.') && !/[()?]/.test(expr) && !expr.includes(':')) {\n const key = expr.slice('typeDefault.'.length);\n const v = ctx.typeDefault ? ctx.typeDefault[key] : undefined;\n return v == null ? EMPTY_SENTINEL : String(v);\n }\n if (expr.length > 80) return EMPTY_SENTINEL;\n if (!SAFE_EXPR.test(expr) || FORBIDDEN.test(expr)) return EMPTY_SENTINEL;\n const dotChain = expr.match(/\\./g);\n if (dotChain && dotChain.length > 1) return EMPTY_SENTINEL;\n try {\n const out = safeEval(expr, ctx);\n const str = out == null ? '' : String(out);\n if (REFLECTIVE_RE.test(str)) return EMPTY_SENTINEL;\n return str || EMPTY_SENTINEL;\n } catch {\n return EMPTY_SENTINEL;\n }\n}\n// #endregion\n\n// #region Cell Scrubbing\n/** Pattern matching reflective/introspective APIs that must be stripped from output. */\nconst REFLECTIVE_RE = /Reflect|Proxy|ownKeys/;\n\nfunction postProcess(s: string): string {\n if (!s) return s;\n return s.replace(new RegExp(EMPTY_SENTINEL, 'g'), '').replace(/Reflect\\.[^<>{}\\s]+|\\bProxy\\b|ownKeys\\([^)]*\\)/g, '');\n}\n\nexport function finalCellScrub(cell: HTMLElement): void {\n if (!REFLECTIVE_RE.test(cell.textContent || '')) return;\n // First pass: clear only text nodes containing forbidden tokens\n for (const n of cell.childNodes) {\n if (n.nodeType === Node.TEXT_NODE && REFLECTIVE_RE.test(n.textContent || '')) n.textContent = '';\n }\n // If forbidden tokens persist in element nodes, nuke everything\n if (REFLECTIVE_RE.test(cell.textContent || '')) {\n cell.textContent = '';\n }\n}\n// #endregion\n\n// #region Template Compilation\nexport function compileTemplate(raw: string) {\n if (REFLECTIVE_RE.test(raw)) {\n const fn = (() => '') as CompiledViewFunction;\n fn.__blocked = true;\n return fn;\n }\n const fn = ((ctx: EvalContext) => evalTemplateString(raw, ctx)) as CompiledViewFunction;\n fn.__blocked = false;\n return fn;\n}\n// #endregion\n","/**\n * Loading State Module\n *\n * Handles loading overlays, row loading, and cell loading states.\n * Provides DOM manipulation helpers for loading indicators.\n *\n * @module internal/loading\n */\n\nimport type { FrameworkAdapter, GridConfig, LoadingContext, RowElementInternal } from '../types';\nimport { setSanitizedHTML } from './sanitize';\n\n/**\n * Create the default spinner element.\n * @param size - 'large' for grid overlay, 'small' for row/cell\n */\nexport function createDefaultSpinner(size: 'large' | 'small'): HTMLElement {\n const spinner = document.createElement('div');\n spinner.className = `tbw-spinner tbw-spinner--${size}`;\n spinner.setAttribute('role', 'progressbar');\n spinner.setAttribute('aria-label', 'Loading');\n return spinner;\n}\n\n/**\n * Create loading content using custom renderer or default spinner.\n *\n * Strings returned by a custom renderer are passed through `setSanitizedHTML()`\n * — mirroring the cell, header and empty-state render paths — so a message\n * interpolating server data (e.g. `Loading ${dataset.name}…`) is not an XSS\n * sink.\n *\n * @param size - 'large' for grid overlay, 'small' for row/cell\n * @param renderer - Optional custom loading renderer from config\n */\nexport function createLoadingContent(size: 'large' | 'small', renderer?: GridConfig['loadingRenderer']): HTMLElement {\n if (renderer) {\n const context: LoadingContext = { size };\n const result = renderer(context);\n if (typeof result === 'string') {\n const wrapper = document.createElement('div');\n setSanitizedHTML(wrapper, result);\n return wrapper;\n }\n return result;\n }\n\n return createDefaultSpinner(size);\n}\n\n/**\n * Create or update the loading overlay element.\n * @param renderer - Optional custom loading renderer from config\n */\nexport function createLoadingOverlay(renderer?: GridConfig['loadingRenderer']): HTMLElement {\n const overlay = document.createElement('div');\n overlay.className = 'tbw-loading-overlay';\n overlay.setAttribute('role', 'status');\n overlay.setAttribute('aria-live', 'polite');\n overlay.appendChild(createLoadingContent('large', renderer));\n return overlay;\n}\n\n/**\n * Show the loading overlay on the grid root element.\n * @param gridRoot - The .tbw-grid-root element\n * @param overlayEl - The overlay element (will be cached by caller)\n */\nexport function showLoadingOverlay(gridRoot: Element, overlayEl: HTMLElement): void {\n gridRoot.appendChild(overlayEl);\n}\n\n/**\n * Hide the loading overlay.\n * @param overlayEl - The overlay element to remove\n */\nexport function hideLoadingOverlay(overlayEl: HTMLElement | undefined): void {\n overlayEl?.remove();\n}\n\n/** Remove a cell's owned loading overlay and release adapter-managed content. */\nexport function removeCellLoadingOverlay(cellEl: HTMLElement, adapter?: Pick<FrameworkAdapter, 'unmount'>): void {\n if (!cellEl.firstElementChild) return;\n const overlay = cellEl.querySelector<HTMLElement>(':scope > .tbw-cell-loading-overlay');\n if (!overlay) return;\n adapter?.unmount?.(overlay);\n overlay.remove();\n}\n\n/**\n * Move a cell's owned loading overlay in front of the cell while its content is rewritten,\n * so the still-active loader survives adapter release and content replacement. The caller\n * appends it back. The overlay stays connected because React prunes detached portal containers.\n */\nexport function parkCellLoadingOverlay(cellEl: HTMLElement): HTMLElement | null {\n if (!cellEl.firstElementChild) return null;\n const overlay = cellEl.querySelector<HTMLElement>(':scope > .tbw-cell-loading-overlay');\n if (!overlay) return null;\n const parent = cellEl.parentElement;\n if (parent) parent.insertBefore(overlay, cellEl);\n else overlay.remove();\n return overlay;\n}\n\n/** Remove a row's owned loading overlay and release adapter-managed content. */\nexport function removeRowLoadingOverlay(rowEl: HTMLElement, adapter?: Pick<FrameworkAdapter, 'unmount'>): void {\n if (!rowEl.firstElementChild) return;\n const overlay = rowEl.querySelector<HTMLElement>(':scope > .tbw-row-loading-overlay');\n if (!overlay) return;\n adapter?.unmount?.(overlay);\n overlay.remove();\n}\n\n/**\n * Update a row element's loading state.\n * Uses real DOM elements instead of ::before/::after pseudo-elements\n * because the selection plugin already uses ::after on rows for border styling.\n * @param rowEl - The row element\n * @param loading - Whether the row is loading\n * @param renderer - Optional `gridConfig.loadingRenderer`; called with `{ size: 'small' }`\n * in place of the default spinner. Only invoked when the overlay is created.\n * @param adapter - Framework adapter used to release renderer-owned content on removal.\n */\nexport function setRowLoadingState(\n rowEl: HTMLElement,\n loading: boolean,\n renderer?: GridConfig['loadingRenderer'],\n adapter?: Pick<FrameworkAdapter, 'unmount'>,\n): void {\n if (loading) {\n rowEl.classList.add('tbw-row-loading');\n rowEl.setAttribute('aria-busy', 'true');\n\n // Create overlay + spinner DOM elements if not already present.\n // Direct children only — a nested grid's row overlay must not be mistaken for this row's.\n if (!rowEl.querySelector(':scope > .tbw-row-loading-overlay')) {\n const overlay = document.createElement('div');\n overlay.className = 'tbw-row-loading-overlay';\n overlay.setAttribute('aria-hidden', 'true');\n\n if (renderer) {\n overlay.appendChild(createLoadingContent('small', renderer));\n } else {\n const spinner = document.createElement('div');\n spinner.className = 'tbw-row-loading-spinner';\n overlay.appendChild(spinner);\n }\n\n rowEl.appendChild(overlay);\n }\n } else {\n rowEl.classList.remove('tbw-row-loading');\n rowEl.removeAttribute('aria-busy');\n\n // Remove overlay + spinner DOM elements\n removeRowLoadingOverlay(rowEl, adapter);\n }\n}\n\n/**\n * Update a cell element's loading state.\n * @param cellEl - The cell element\n * @param loading - Whether the cell is loading\n * @param renderer - Optional `gridConfig.loadingRenderer`; called with `{ size: 'small' }`\n * @param adapter - Framework adapter used to release renderer-owned content on removal.\n */\nexport function setCellLoadingState(\n cellEl: HTMLElement,\n loading: boolean,\n renderer?: GridConfig['loadingRenderer'],\n adapter?: Pick<FrameworkAdapter, 'unmount'>,\n): void {\n if (loading) {\n cellEl.classList.add('tbw-cell-loading');\n cellEl.setAttribute('aria-busy', 'true');\n\n // Breadcrumb so the render hot path can skip the per-cell scan on the\n // overwhelming majority of rows. Conservative: only ever set here, so it can\n // read stale-true after the last loading cell clears (costs one extra scan).\n const rowEl = cellEl.parentElement as RowElementInternal | null;\n if (rowEl) rowEl.__hasCellLoading = true;\n\n if (renderer) {\n cellEl.classList.add('tbw-cell-loading-custom');\n if (!cellEl.querySelector(':scope > .tbw-cell-loading-overlay')) {\n const overlay = document.createElement('div');\n overlay.className = 'tbw-cell-loading-overlay';\n overlay.setAttribute('aria-hidden', 'true');\n overlay.appendChild(createLoadingContent('small', renderer));\n cellEl.appendChild(overlay);\n }\n } else {\n cellEl.classList.remove('tbw-cell-loading-custom');\n removeCellLoadingOverlay(cellEl, adapter);\n }\n } else {\n cellEl.classList.remove('tbw-cell-loading');\n cellEl.classList.remove('tbw-cell-loading-custom');\n cellEl.removeAttribute('aria-busy');\n removeCellLoadingOverlay(cellEl, adapter);\n }\n}\n","/**\n * Hierarchy Engine\n *\n * Pure row-model builder shared by the HierarchyPlugin and its contributors.\n */\n\nimport type { HierarchyContributor, HierarchyNode, HierarchyRowMeta } from './types';\n\n/**\n * Build the flat row list for `rows` from every contributor's sibling-list\n * transforms, recording each emitted row's ARIA position in `meta`.\n *\n * Contributors whose `beginHierarchy` returns `false` sit out the rebuild.\n * With no active contributor the rows pass through unchanged. When every\n * active contributor's `endHierarchy` returns `false`, no position is kept in `meta`.\n *\n * This is what `HierarchyPlugin.process()` runs for all attached contributors.\n * Call it directly to run a contributor without a grid — e.g. as the\n * `processRows` fallback when no HierarchyPlugin is attached, or in unit tests.\n *\n * @example\n * ```ts\n * override processRows(rows: readonly unknown[]): unknown[] {\n * const hierarchy = this.grid?.getPluginByName('hierarchy');\n * return hierarchy ? hierarchy.process(rows, this) : buildHierarchy(rows, [this]);\n * }\n * ```\n *\n * @param rows - The root rows.\n * @param contributors - Contributors to run, in `processRows` hook order.\n * @param meta - Receives each emitted row's position. Pass a fresh map per rebuild.\n * @returns The flattened rows, in render order.\n * @since 3.9.0\n */\nexport function buildHierarchy(\n rows: readonly unknown[],\n contributors: readonly HierarchyContributor[],\n meta: WeakMap<object, HierarchyRowMeta> = new WeakMap(),\n): unknown[] {\n const active: HierarchyContributor[] = [];\n for (const stage of ['structure', 'transform'] as const) {\n for (const c of contributors) {\n if (c.hierarchyStage === stage && c.beginHierarchy(rows)) active.push(c);\n }\n }\n if (active.length === 0) return [...rows];\n\n const out: unknown[] = [];\n const process = (nodes: HierarchyNode[], parent: HierarchyNode | null, depth: number): HierarchyNode[] => {\n const context = { parent: parent ? parent.row : null, parentKey: parent?.key ?? null, depth };\n for (const c of active) nodes = c.processSiblings(nodes, context);\n return nodes;\n };\n const emit = (nodes: HierarchyNode[], depth: number): void => {\n const setSize = nodes.length;\n for (let i = 0; i < setSize; i++) {\n const node = nodes[i];\n out.push(node.row);\n if (typeof node.row === 'object' && node.row !== null) {\n meta.set(node.row, { level: depth + 1, setSize, posInSet: i + 1 });\n }\n const children = node.children;\n if (node.expanded && children) {\n emit(node.shaped ? children : process(children, node, depth + 1), depth + 1);\n }\n }\n };\n\n const roots: HierarchyNode[] = new Array(rows.length);\n for (let i = 0; i < rows.length; i++) roots[i] = { row: rows[i] };\n emit(process(roots, null, 0), 0);\n\n const positionOf = (row: unknown) => (typeof row === 'object' && row !== null ? meta.get(row) : undefined);\n let shaped = false;\n for (const c of active) if (c.endHierarchy(out, positionOf)) shaped = true;\n if (!shaped) {\n for (const row of out) if (typeof row === 'object' && row !== null) meta.delete(row);\n }\n return out;\n}\n","/**\n * Hierarchy Plugin\n *\n * Owns the hierarchical row model shared by structure-contributing plugins.\n */\n\nimport type { PluginManifest } from '../../core/plugin/base-plugin';\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { RowElementInternal } from '../../core/types';\nimport { buildHierarchy } from './hierarchy';\nimport type { HierarchyContributor, HierarchyRowMeta } from './types';\n\n/** Attribute write that skips the DOM mutation when the value is unchanged (per-frame hot path). */\nfunction setAttrIfChanged(el: Element, name: string, value: number): void {\n const next = String(value);\n if (el.getAttribute(name) !== next) el.setAttribute(name, next);\n}\n\nfunction isContributor(plugin: unknown): plugin is HierarchyContributor & BaseGridPlugin {\n return typeof (plugin as Partial<HierarchyContributor>).processSiblings === 'function';\n}\n\nfunction processRowsPriority(plugin: BaseGridPlugin): number {\n return (plugin.constructor as typeof BaseGridPlugin).manifest?.hookPriority?.processRows ?? 0;\n}\n\n/**\n * Hierarchy Plugin for tbw-grid\n *\n * Builds one hierarchical row model from every attached structure contributor\n * — {@link https://toolboxjs.com/grid/plugins/tree/ | TreePlugin} discovers\n * child rows, {@link https://toolboxjs.com/grid/plugins/grouping-rows/ | GroupingRowsPlugin}\n * groups sibling lists — and announces each row's position with the WAI-ARIA\n * treegrid pattern (`aria-level` / `aria-setsize` / `aria-posinset`).\n *\n * Contributors know nothing about each other, so they compose: a grid with\n * both Tree and GroupingRows groups the children of every tree level.\n *\n * You never need to add this plugin yourself — TreePlugin and\n * GroupingRowsPlugin declare it as a dependency and the grid attaches it\n * automatically. It has no configuration.\n *\n * @example Group the children of every tree node\n * ```ts\n * import { TreePlugin } from '@toolbox-web/grid/plugins/tree';\n * import { GroupingRowsPlugin } from '@toolbox-web/grid/plugins/grouping-rows';\n *\n * grid.gridConfig = {\n * plugins: [\n * new TreePlugin({ childrenField: 'children' }),\n * new GroupingRowsPlugin({\n * // Leave the root level ungrouped, group every child level by kind\n * groupOn: (row, { depth }) => (depth > 0 ? row.kind : null),\n * }),\n * ],\n * };\n * ```\n *\n * @since 3.9.0\n */\nexport class HierarchyPlugin extends BaseGridPlugin {\n /** @internal */\n static override readonly manifest: PluginManifest = {\n modifiesRowStructure: true,\n };\n\n /** @internal */\n readonly name = 'hierarchy';\n\n #meta = new WeakMap<object, HierarchyRowMeta>();\n\n /** @internal */\n override detach(): void {\n // Restore the default `role=\"grid\"` (template default in `core/internal/dom-builder.ts`).\n this.gridElement?.querySelector('.rows-body')?.setAttribute('role', 'grid');\n this.#meta = new WeakMap();\n }\n\n /**\n * Build the row model for a contributor's `processRows` hook.\n *\n * Every contributor forwards its hook here; only the one that runs last in\n * the `processRows` pipeline builds the model (for all contributors at\n * once) — the earlier ones pass their rows through untouched.\n *\n * @example\n * ```ts\n * override processRows(rows: readonly unknown[]): unknown[] {\n * return this.grid.getPluginByName('hierarchy')?.process(rows, this) ?? [...rows];\n * }\n * ```\n *\n * @since 3.9.0\n */\n process(rows: readonly unknown[], caller: HierarchyContributor): unknown[] {\n const contributors = this.#contributors();\n if (!contributors.includes(caller as HierarchyContributor & BaseGridPlugin)) {\n this.#meta = new WeakMap();\n return buildHierarchy(rows, [caller], this.#meta);\n }\n if (contributors[contributors.length - 1] !== caller) return rows as unknown[];\n this.#meta = new WeakMap();\n return buildHierarchy(rows, contributors, this.#meta);\n }\n\n /**\n * Hierarchy position of a row in the current row model, or `undefined` when\n * the row is not rendered (e.g. collapsed under a parent).\n *\n * @example\n * ```ts\n * const meta = grid.getPluginByName('hierarchy')?.getRowMeta(grid.rows[0]);\n * console.log(meta?.level, meta?.posInSet, meta?.setSize);\n * ```\n *\n * @since 3.9.0\n */\n getRowMeta(row: unknown): HierarchyRowMeta | undefined {\n return typeof row === 'object' && row !== null ? this.#meta.get(row) : undefined;\n }\n\n /** @internal */\n override afterRender(): void {\n this.#applyAria();\n }\n\n /** @internal */\n override onScrollRender(): void {\n this.#applyAria();\n }\n\n /** Attached contributors, in `processRows` hook order. */\n #contributors(): Array<HierarchyContributor & BaseGridPlugin> {\n const plugins = (this.grid?._pluginManager?.getPlugins?.() ?? []) as readonly BaseGridPlugin[];\n return plugins.filter(isContributor).sort((a, b) => processRowsPriority(a) - processRowsPriority(b));\n }\n\n #applyAria(): void {\n if (this.#contributors().length === 0) return;\n const body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n let hierarchical = false;\n for (const rowEl of body.querySelectorAll('.data-grid-row')) {\n const meta = this.getRowMeta((rowEl as RowElementInternal).__rowDataRef);\n if (!meta) {\n // Pooled row elements may carry a position from a previous row model.\n rowEl.removeAttribute('aria-level');\n rowEl.removeAttribute('aria-setsize');\n rowEl.removeAttribute('aria-posinset');\n continue;\n }\n hierarchical = true;\n setAttrIfChanged(rowEl, 'aria-level', meta.level);\n setAttrIfChanged(rowEl, 'aria-setsize', meta.setSize);\n setAttrIfChanged(rowEl, 'aria-posinset', meta.posInSet);\n }\n\n // `treegrid` only while the model has hierarchy, so per-row level/setsize/posinset are valid in context.\n const role = hierarchical ? 'treegrid' : 'grid';\n const rowsBody = this.gridElement?.querySelector('.rows-body');\n if (rowsBody && rowsBody.getAttribute('role') !== role) rowsBody.setAttribute('role', role);\n }\n}\n","/**\n * Core Tree Data Logic\n *\n * Pure functions for tree flattening, expansion, and traversal.\n */\n\nimport type { FlattenedTreeRow, TreeConfig, TreeRow } from './types';\n\n/**\n * Generates a unique key for a row.\n * Uses row.id if available, otherwise generates from path.\n */\nexport function generateRowKey(row: TreeRow, index: number, parentKey: string | null): string {\n if (row.id !== undefined) return String(row.id);\n return parentKey ? `${parentKey}-${index}` : String(index);\n}\n\n/**\n * Flattens a hierarchical tree into a flat array of rows with metadata.\n * Only includes children of expanded nodes.\n */\nexport function flattenTree(\n rows: readonly TreeRow[],\n config: TreeConfig,\n expandedKeys: Set<string>,\n parentKey: string | null = null,\n depth = 0,\n): FlattenedTreeRow[] {\n const childrenField = config.childrenField ?? 'children';\n const result: FlattenedTreeRow[] = [];\n appendFlattenedRows(rows, childrenField, expandedKeys, parentKey, depth, result);\n return result;\n}\n\nfunction appendFlattenedRows(\n rows: readonly TreeRow[],\n childrenField: string,\n expandedKeys: Set<string>,\n parentKey: string | null,\n depth: number,\n result: FlattenedTreeRow[],\n): void {\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const key = generateRowKey(row, i, parentKey);\n const children = row[childrenField];\n const hasChildren = Array.isArray(children) && children.length > 0;\n const isExpanded = expandedKeys.has(key);\n\n result.push({\n key,\n data: row,\n depth,\n hasChildren,\n isExpanded,\n parentKey,\n posInSet: i + 1,\n setSize: rows.length,\n });\n\n // Recursively add children if expanded\n if (hasChildren && isExpanded) {\n appendFlattenedRows(children as TreeRow[], childrenField, expandedKeys, key, depth + 1, result);\n }\n }\n}\n\n/**\n * Toggles the expansion state of a row.\n * Returns a new Set with the toggled state.\n */\nexport function toggleExpand(expandedKeys: Set<string>, key: string): Set<string> {\n const newExpanded = new Set(expandedKeys);\n if (newExpanded.has(key)) {\n newExpanded.delete(key);\n } else {\n newExpanded.add(key);\n }\n return newExpanded;\n}\n\n/**\n * Expands all nodes in the tree.\n * Returns a Set of all parent row keys.\n */\nexport function expandAll(\n rows: readonly TreeRow[],\n config: TreeConfig,\n parentKey: string | null = null,\n depth = 0,\n): Set<string> {\n const childrenField = config.childrenField ?? 'children';\n const keys = new Set<string>();\n\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const key = generateRowKey(row, i, parentKey);\n const children = row[childrenField];\n\n if (Array.isArray(children) && children.length > 0) {\n keys.add(key);\n const childKeys = expandAll(children as TreeRow[], config, key, depth + 1);\n for (const k of childKeys) keys.add(k);\n }\n }\n\n return keys;\n}\n\n/**\n * Collapses all nodes.\n * Returns an empty Set.\n */\nexport function collapseAll(): Set<string> {\n return new Set();\n}\n\n/**\n * Gets all descendants of a node from the flattened row list.\n * Useful for operations that need to affect an entire subtree.\n */\nexport function getDescendants(flattenedRows: FlattenedTreeRow[], parentKey: string): FlattenedTreeRow[] {\n const descendants: FlattenedTreeRow[] = [];\n let collecting = false;\n let parentDepth = -1;\n\n for (const row of flattenedRows) {\n if (row.key === parentKey) {\n collecting = true;\n parentDepth = row.depth;\n continue;\n }\n\n if (collecting) {\n if (row.depth > parentDepth) {\n descendants.push(row);\n } else {\n break; // No longer a descendant\n }\n }\n }\n\n return descendants;\n}\n\n/**\n * Finds the path from root to a specific row key.\n * Returns an array of keys from root to the target (inclusive).\n */\nexport function getPathToKey(\n rows: readonly TreeRow[],\n targetKey: string,\n config: TreeConfig,\n parentKey: string | null = null,\n depth = 0,\n): string[] | null {\n const childrenField = config.childrenField ?? 'children';\n\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const key = generateRowKey(row, i, parentKey);\n\n if (key === targetKey) {\n return [key];\n }\n\n const children = row[childrenField];\n if (Array.isArray(children) && children.length > 0) {\n const childPath = getPathToKey(children as TreeRow[], targetKey, config, key, depth + 1);\n if (childPath) {\n return [key, ...childPath];\n }\n }\n }\n\n return null;\n}\n\n/**\n * Expands all ancestors of a specific row to make it visible.\n * Returns a new Set with the required keys added.\n */\nexport function expandToKey(\n rows: readonly TreeRow[],\n targetKey: string,\n config: TreeConfig,\n existingExpanded: Set<string>,\n): Set<string> {\n const path = getPathToKey(rows, targetKey, config);\n if (!path) return existingExpanded;\n\n const newExpanded = new Set(existingExpanded);\n // Add all keys except the last one (the target itself)\n for (let i = 0; i < path.length - 1; i++) {\n newExpanded.add(path[i]);\n }\n return newExpanded;\n}\n","/**\n * True when a keyboard event originates in a text-entry control — `<input>`, `<select>`,\n * `<textarea>` or a contenteditable element. Plugin key handlers (e.g. Space to toggle a tree\n * row) must defer to the control so the keystroke is typed rather than swallowed.\n *\n * Reads `composedPath()[0]` so controls inside an editor's open shadow root are recognised;\n * `event.target` is retargeted to the shadow host by the time the grid sees the event.\n * @internal\n */\nexport function isFormFieldKeyTarget(event: Event): boolean {\n const path = event.composedPath?.() ?? [];\n const target = path.length ? path[0] : event.target;\n if (!(target instanceof HTMLElement)) return false;\n const tag = target.tagName;\n return tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA' || target.isContentEditable;\n}\n","/**\n * Tree Viewport Mapping Utilities\n *\n * Pure functions for translating between flat viewport row indices and\n * top-level tree node indices. Used by the Tree plugin's\n * `datasource:viewport-mapping` query handler.\n */\n\nimport type { ViewportMappingResponse } from '../server-side/datasource-types';\n\n/**\n * Translate a range of rendered row indices to the range of root nodes that own them.\n *\n * @param rootOwners - Index-aligned with the grid's final row list (including rows other\n * contributors inserted, e.g. group headers): the 0-based ordinal of the root node each row\n * belongs to, or `-1` for rows rendered before the first root.\n * @param rootCount - Number of root nodes in the rendered rows.\n */\nexport function mapViewportToRoots(\n rootOwners: readonly number[],\n rootCount: number,\n viewportStart: number,\n viewportEnd: number,\n): ViewportMappingResponse {\n const last = rootOwners.length - 1;\n const ownerAt = (index: number) => Math.max(0, rootOwners[Math.max(0, Math.min(index, last))] ?? 0);\n return {\n startNode: ownerAt(viewportStart),\n endNode: ownerAt(viewportEnd) + 1, // exclusive\n totalLoadedNodes: rootCount,\n };\n}\n","/**\n * Tree Structure Auto-Detection\n *\n * Utilities for detecting hierarchical tree data structures.\n */\n\nimport type { TreeRow } from './types';\n\n/**\n * Detects if the data has a tree structure by checking for children arrays.\n *\n * @param rows - The candidate root rows\n * @param childrenField - Field holding the children array / lazy indicator\n * @param hasChildren - Optional {@link TreeConfig.hasChildren} predicate. When\n * supplied, a row it reports as a parent marks the data as a tree even if it\n * carries no `childrenField` at all — the purely lazy case where children are\n * only ever fetched through `loadChildren`.\n */\nexport function detectTreeStructure(\n rows: readonly TreeRow[],\n childrenField = 'children',\n hasChildren?: (row: TreeRow) => boolean,\n): boolean {\n if (!Array.isArray(rows) || rows.length === 0) return false;\n\n // Check if any row has children (embedded array or lazy indicator)\n for (const row of rows) {\n // Loading placeholders (ServerSide) hold no data; never pass them to `hasChildren`.\n if (!row || row.__loading === true) continue;\n const children = row[childrenField];\n // Embedded children: non-empty array\n if (Array.isArray(children) && children.length > 0) return true;\n // Lazy children: truthy non-array value (e.g. `true`, number > 0)\n if (children != null && !Array.isArray(children) && !!children) return true;\n // Predicate-only lazy children: no `childrenField` on the row at all.\n if (hasChildren?.(row)) return true;\n }\n\n return false;\n}\n\n/**\n * Attempts to infer the children field name from common patterns.\n * Returns the first field that contains an array with items.\n */\nexport function inferChildrenField(rows: readonly TreeRow[]): string | null {\n if (!Array.isArray(rows) || rows.length === 0) return null;\n\n const commonArrayFields = ['children', 'items', 'nodes', 'subRows', 'nested'];\n\n for (const row of rows) {\n if (!row || typeof row !== 'object') continue;\n\n for (const field of commonArrayFields) {\n const value = row[field];\n if (Array.isArray(value) && value.length > 0) {\n return field;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Calculates the maximum depth of the tree.\n * Useful for layout calculations and virtualization.\n */\nexport function getMaxDepth(rows: readonly TreeRow[], childrenField = 'children', currentDepth = 0): number {\n if (!Array.isArray(rows) || rows.length === 0) return currentDepth;\n\n let maxDepth = currentDepth;\n\n for (const row of rows) {\n if (!row) continue;\n const children = row[childrenField];\n if (Array.isArray(children) && children.length > 0) {\n const childDepth = getMaxDepth(children as TreeRow[], childrenField, currentDepth + 1);\n if (childDepth > maxDepth) {\n maxDepth = childDepth;\n }\n }\n }\n\n return maxDepth;\n}\n\n/**\n * Counts total nodes in the tree (including all descendants).\n */\nexport function countNodes(rows: readonly TreeRow[], childrenField = 'children'): number {\n if (!Array.isArray(rows)) return 0;\n\n let count = 0;\n for (const row of rows) {\n if (!row) continue;\n count++;\n const children = row[childrenField];\n if (Array.isArray(children)) {\n count += countNodes(children as TreeRow[], childrenField);\n }\n }\n\n return count;\n}\n","/**\n * Tree Plugin Styles\n *\n * Scoped to tbw-grid using CSS nesting for light DOM compatibility.\n */\n@layer tbw-plugins {\n tbw-grid {\n /* Expander column data cells - always first, borderless end edge */\n .cell[data-field='__tbw_expander'] {\n border-inline-end: none !important;\n padding: 0;\n display: flex;\n align-items: center;\n justify-content: flex-start;\n }\n\n /* Expander column header - completely hidden, next column spans both */\n .header-row .cell[data-field='__tbw_expander'] {\n display: none;\n }\n\n .header-row .cell[data-field='__tbw_expander'] + .cell {\n grid-column: 1 / 3;\n }\n\n /* Tree cell wrapper with depth-based indentation */\n .tree-cell-wrapper {\n display: inline-flex;\n align-items: center;\n /* Prevent baseline differences between tree-toggle (inline-flex) and\n tree-spacer (inline-block) from causing inconsistent row heights,\n which would trigger a rowHeight oscillation loop in virtualization. */\n vertical-align: middle;\n /* Override cell > * { overflow: hidden } which clips indented tree content */\n overflow: visible;\n /* Indent must be >= toggle icon width to keep leaf nodes aligned */\n padding-inline-start: calc(\n var(--tbw-tree-depth, 0) * var(--tbw-tree-indent-width, var(--tbw-tree-toggle-size, 1.25em))\n );\n }\n\n /* Tree expander cell with indentation */\n .tree-expander {\n display: flex;\n align-items: center;\n justify-content: flex-start;\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n }\n\n .tree-toggle {\n cursor: pointer;\n user-select: none;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n /* Explicit size ensures consistent spacing with tree-spacer */\n width: var(--tbw-tree-toggle-size, 1.25em);\n height: var(--tbw-tree-toggle-size, 1.25em);\n flex-shrink: 0;\n }\n\n .tree-toggle:hover {\n color: var(--tbw-tree-accent, var(--tbw-color-accent));\n }\n\n /* SC 2.5.8 Target Size (Minimum) applies to every pointer type, but a 24px\n box would widen every indentation level. The overlay grows the target\n instead of the box, so density is untouched. */\n .tree-toggle {\n position: relative;\n\n &::after {\n content: '';\n position: absolute;\n inset-block-start: 50%;\n inset-inline-start: 50%;\n translate: -50% -50%;\n inline-size: var(--tbw-touch-target-min, 24px);\n block-size: var(--tbw-touch-target-min, 24px);\n }\n }\n\n .tree-spacer {\n /* Must match tree-toggle width and height for alignment */\n width: var(--tbw-tree-toggle-size, 1.25em);\n height: var(--tbw-tree-toggle-size, 1.25em);\n display: inline-block;\n flex-shrink: 0;\n }\n\n /* The spacer occupies the toggle slot on leaf rows, so it must grow with the\n toggle — otherwise leaf rows sit narrower than expandable ones on touch. */\n @media (pointer: coarse) {\n .tree-toggle,\n .tree-spacer {\n min-width: var(--tbw-touch-target-min, 24px);\n min-height: var(--tbw-touch-target-min, 24px);\n }\n }\n\n /* Lazy-loading indicator — core's small spinner (`.tbw-spinner--small`)\n resized to the toggle slot so swapping toggle ↔ spinner doesn't reflow\n the row. Only the size token is overridden; all other spinner theming\n (`--tbw-spinner-color`, `--tbw-spinner-track-color`) still applies. */\n .tree-loading {\n --tbw-spinner-size: var(--tbw-tree-toggle-size, 1.25em);\n flex-shrink: 0;\n }\n\n /* Slide animation for child rows appearing */\n .data-grid-row.tbw-tree-slide-in {\n animation: tbw-tree-slide-in var(--tbw-animation-duration, 200ms) var(--tbw-animation-easing, ease-out) forwards;\n }\n\n /* Fade animation for child rows appearing */\n .data-grid-row.tbw-tree-fade-in {\n animation: tbw-tree-fade-in var(--tbw-animation-duration, 200ms) var(--tbw-animation-easing, ease-out) forwards;\n }\n }\n\n @keyframes tbw-tree-slide-in {\n from {\n opacity: 0;\n transform: translateX(-8px);\n }\n to {\n opacity: 1;\n transform: translateX(0);\n }\n }\n\n @keyframes tbw-tree-fade-in {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n }\n} /* End @layer tbw-plugins */\n","/**\n * Tree Data Plugin\n *\n * Enables hierarchical tree data with expand/collapse, sorting, and auto-detection.\n */\n\nimport { GridClasses } from '../../core/constants';\nimport { createDefaultSpinner } from '../../core/internal/loading';\nimport { setSanitizedHTML } from '../../core/internal/sanitize';\nimport { builtInSort } from '../../core/internal/sorting';\nimport type { GridElement } from '../../core/plugin/base-plugin';\nimport {\n BaseGridPlugin,\n CellClickEvent,\n HeaderClickEvent,\n type PluginManifest,\n type PluginQuery,\n} from '../../core/plugin/base-plugin';\nimport type { ColumnConfig, ColumnViewRenderer, RowElementInternal, SortHandler } from '../../core/types';\nimport type { HierarchyContributor, HierarchyNode, HierarchyRowMeta, HierarchySiblingContext } from '../hierarchy';\nimport { buildHierarchy, HierarchyPlugin } from '../hierarchy';\nimport type {\n DataSourceChildrenDetail,\n DataSourceDataDetail,\n DataSourceErrorDetail,\n FetchChildrenQuery,\n Subscribable,\n ViewportMappingQuery,\n} from '../server-side/datasource-types';\nimport { collapseAll, expandAll, expandToKey, toggleExpand } from './tree-data';\nimport { isFormFieldKeyTarget } from '../shared/form-field-target';\nimport { mapViewportToRoots } from './tree-datasource';\nimport { detectTreeStructure, inferChildrenField } from './tree-detect';\nimport styles from './tree.css?inline';\nimport type {\n ExpandCollapseAnimation,\n FlattenedTreeRow,\n TreeConfig,\n TreeExpandDetail,\n TreeLoadEndDetail,\n TreeLoadErrorDetail,\n TreeLoadStartDetail,\n TreeRow,\n} from './types';\n\n/** Narrow a `loadChildren` result to the Subscribable branch. */\nfunction isSubscribable<T>(value: Promise<T> | Subscribable<T>): value is Subscribable<T> {\n return typeof (value as Subscribable<T>).subscribe === 'function';\n}\n\n/**\n * Tree Data Plugin for tbw-grid\n *\n * Transforms your flat grid into a hierarchical tree view with expandable parent-child\n * relationships. Ideal for file explorers, organizational charts, nested categories,\n * or any data with a natural hierarchy.\n *\n * ## Installation\n *\n * ```ts\n * import { TreePlugin } from '@toolbox-web/grid/plugins/tree';\n * ```\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-tree-toggle-size` | `1.25em` | Toggle icon width |\n * | `--tbw-tree-indent-width` | `var(--tbw-tree-toggle-size)` | Indentation per level |\n * | `--tbw-tree-accent` | `var(--tbw-color-accent)` | Toggle icon hover color |\n * | `--tbw-animation-duration` | `200ms` | Expand/collapse animation duration |\n * | `--tbw-animation-easing` | `ease-out` | Animation curve |\n *\n * @example Basic Tree with Nested Children\n * ```ts\n * import { queryGrid } from '@toolbox-web/grid';\n * import { TreePlugin } from '@toolbox-web/grid/plugins/tree';\n *\n * const grid = queryGrid('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'type', header: 'Type' },\n * { field: 'size', header: 'Size' },\n * ],\n * plugins: [new TreePlugin({ childrenField: 'children', indentWidth: 24 })],\n * };\n * grid.rows = [\n * {\n * id: 1,\n * name: 'Documents',\n * type: 'folder',\n * children: [\n * { id: 2, name: 'Report.docx', type: 'file', size: '24 KB' },\n * ],\n * },\n * ];\n * ```\n *\n * @example Expanded by Default with Custom Animation\n * ```ts\n * new TreePlugin({\n * defaultExpanded: true,\n * animation: 'fade', // 'slide' | 'fade' | false\n * indentWidth: 32,\n * })\n * ```\n *\n * @see {@link TreeConfig} for all configuration options\n * @see {@link FlattenedTreeRow} for the flattened row structure\n *\n * @internal Extends BaseGridPlugin\n * @since 0.1.1\n */\nexport class TreePlugin extends BaseGridPlugin<TreeConfig> implements HierarchyContributor {\n static override readonly manifest: PluginManifest = {\n modifiesRowStructure: true,\n hookPriority: {\n processRows: 10, // Run after ServerSide (-10) so we receive managedNodes[]\n },\n incompatibleWith: [\n {\n name: 'pivot',\n reason:\n 'PivotPlugin replaces the entire row and column structure with aggregated pivot data. ' +\n 'Tree hierarchy cannot coexist with pivot aggregation.',\n },\n ],\n events: [\n {\n type: 'tree-expand',\n description:\n 'Emitted when tree expansion state changes (toggle, expand all, collapse all). Broadcast to both DOM consumers and plugin bus.',\n },\n {\n type: 'tree-load-start',\n description: 'Emitted when lazy child loading starts for a node whose children are not yet loaded.',\n },\n {\n type: 'tree-load-end',\n description: 'Emitted when lazy child loading completes and children have been merged into the parent row.',\n },\n {\n type: 'tree-load-error',\n description: 'Emitted when lazy child loading fails. The node leaves its loading state and can be retried.',\n },\n ],\n queries: [\n {\n type: 'canMoveRow',\n description: 'Returns false for rows with children (parent nodes cannot be reordered)',\n },\n {\n type: 'datasource:viewport-mapping',\n description: 'Translates flat viewport row indices to top-level node indices for ServerSide pagination.',\n },\n ],\n };\n\n /**\n * Optional dependency on MultiSort for coordinated sorting.\n * When MultiSort is loaded, Tree defers header click sorting to it and queries the\n * sort model in processRows. When MultiSort is absent, Tree uses its own sort state.\n */\n static override readonly dependencies = [\n {\n name: 'hierarchy',\n required: true,\n reason: 'Builds the hierarchical row model',\n provide: () => new HierarchyPlugin(),\n },\n { name: 'multiSort', required: false, reason: 'Queries sort model for coordinated tree sorting' },\n { name: 'serverSide', required: false, reason: 'Consumes datasource events for lazy-loaded tree data' },\n ];\n\n /** @internal */\n readonly name = 'tree';\n /** @internal */\n readonly hierarchyStage = 'structure';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<TreeConfig> {\n return {\n childrenField: 'children',\n autoDetect: true,\n defaultExpanded: false,\n indentWidth: 20,\n showExpandIcons: true,\n animation: 'slide',\n };\n }\n\n // #region State\n\n private expandedKeys = new Set<string>();\n private initialExpansionDone = false;\n private flattenedRows: FlattenedTreeRow[] = [];\n private rowKeyMap = new Map<string, FlattenedTreeRow>();\n private previousVisibleKeys = new Set<string>();\n private keysToAnimate = new Set<string>();\n /** Root-node ordinal per row of the FINAL row list — group rows interleave with tree rows when composed. */\n #rootOwners: number[] = [];\n #rootCount = 0;\n private sortState: { field: string; direction: 1 | -1 } | null = null;\n /** Sort applied to every sibling list during the current rebuild. */\n #levelSort: { field: string; direction: 1 | -1 } | null = null;\n /**\n * In-flight lazy child loads, keyed by node key. `row` is the row OBJECT the\n * request is for — a ServerSide refetch can hand a new object for the same key\n * while the old request is still pending (#527). Both routes carry a\n * `controller`: local `loadChildren` gets its `signal`, ServerSide receives it\n * as `FetchChildrenQuery.signal` and links it to `getChildRows({ signal })`.\n */\n #loads = new Map<string, { row: TreeRow; depth: number; controller: AbortController }>();\n /**\n * Row objects whose children have already been fetched. Prevents a re-fetch on\n * collapse → re-expand, and prevents an infinite retry loop when a node\n * legitimately resolves to zero children but a custom `hasChildren`\n * predicate keeps reporting `true`.\n *\n * Keyed by row IDENTITY, not by node key: a ServerSide refetch (server\n * sort/filter change, `refresh()`) or a `grid.rows` reassignment delivers a\n * NEW object for the same key whose children are lazy again (#527).\n */\n #loadedRows = new WeakSet<object>();\n /**\n * Row objects with a child fetch that was started and NOT cancelled (in\n * flight, loaded, or failed). Limits the automatic re-request of\n * still-expanded lazy nodes (see {@link endHierarchy}) to one attempt per row\n * object, so a failing fetch can't retry on every render.\n */\n #requestedRows = new WeakSet<object>();\n /**\n * Row objects whose load was cancelled because a same-key row superseded it.\n * Kept apart from {@link #requestedRows} so a restored row (A → B → A) loads\n * again automatically, while a late response for the cancelled request is\n * still dropped.\n */\n #cancelledRows = new WeakSet<object>();\n /** Rendered nodes queued for load reconciliation (cancel / auto-request), flushed in one microtask. */\n #pendingReconcile: Array<{ meta: FlattenedTreeRow; flat: boolean }> = [];\n\n /**\n * Stable key cache keyed by row identity.\n * Persists across sort operations (object identity is preserved by sort);\n * replaces the previous `__stableKey` field-mutation approach so that\n * `_rows[i]` remains the user's original row reference and `updateRow(s)`\n * mutations survive the next `processRows` rebuild.\n *\n * INVARIANT: never mutate row objects to attach tree metadata — keep all\n * tree-specific state in this map and `#rowMeta` (see plugin-author rule\n * in `.github/knowledge/grid-plugins.md`).\n */\n #rowKeys = new WeakMap<object, string>();\n\n /**\n * Per-row tree metadata (depth, hasChildren, isExpanded, key) keyed by\n * row identity. Looked up by the column renderer via {@link getRowMeta}.\n * Reassigned to a fresh `WeakMap` at the start of each `processRows` call so\n * collapsed/hidden rows don't return stale metadata from a prior pass.\n */\n #rowMeta = new WeakMap<object, FlattenedTreeRow>();\n\n /** Cached original (unwrapped) renderer to prevent re-wrapping on repeated processColumns calls. */\n private originalTreeColumnRenderer: ColumnViewRenderer | undefined;\n /** Property used by the original renderer, matching core's renderer precedence. */\n private originalTreeColumnRendererProperty: 'renderer' | 'viewRenderer' = 'viewRenderer';\n /** Field name of the column currently wrapped with tree decorations. */\n private wrappedTreeColumnField: string | undefined;\n /** True while `processColumns` has the tree renderer installed on the tree column. */\n #treeColumnWrapped = false;\n /** Guards `#syncTreeColumn` against queueing more than one microtask. */\n #treeColumnSyncScheduled = false;\n\n /** @internal */\n override detach(): void {\n this.expandedKeys.clear();\n this.initialExpansionDone = false;\n this.flattenedRows = [];\n this.#rootOwners = [];\n this.#rootCount = 0;\n this.rowKeyMap.clear();\n this.previousVisibleKeys.clear();\n this.keysToAnimate.clear();\n this.sortState = null;\n this.#levelSort = null;\n this.#loadedRows = new WeakSet();\n this.#requestedRows = new WeakSet();\n this.#cancelledRows = new WeakSet();\n this.#pendingReconcile = [];\n // Silent on teardown — no `tree-load-end` for loads the detach aborts.\n for (const load of this.#loads.values()) load.controller.abort();\n this.#loads.clear();\n this.originalTreeColumnRenderer = undefined;\n this.originalTreeColumnRendererProperty = 'viewRenderer';\n this.wrappedTreeColumnField = undefined;\n this.#treeColumnWrapped = false;\n // WeakMaps GC themselves once row references are dropped — nothing to clear.\n }\n\n /**\n * Handle plugin queries.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'canMoveRow') {\n // Tree rows with children cannot be reordered\n const row = query.context as { [key: string]: unknown } | null | undefined;\n const childrenField = this.config.childrenField ?? 'children';\n const children = row?.[childrenField];\n if (Array.isArray(children) && children.length > 0) {\n return false;\n }\n }\n\n if (query.type === 'datasource:viewport-mapping') {\n // Translate visible flat row indices → top-level node indices for ServerSide pagination\n const { viewportStart, viewportEnd } = query.context as ViewportMappingQuery;\n if (this.flattenedRows.length === 0) return undefined;\n return mapViewportToRoots(this.#rootOwners, this.#rootCount, viewportStart, viewportEnd);\n }\n\n return undefined;\n }\n\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Listen for datasource:data from ServerSidePlugin — claim data for tree processing\n this.on('datasource:data', (detail: unknown) => {\n const d = detail as DataSourceDataDetail;\n if (!d.claimed) {\n d.claimed = true;\n }\n // Data flows through processRows pipeline — Tree receives it via the rows parameter\n // since ServerSide's processRows (hookPriority -10) runs first and returns managedNodes[]\n });\n\n // Listen for datasource:children — consume child rows from ServerSide\n this.on('datasource:children', (detail: unknown) => {\n const d = detail as DataSourceChildrenDetail;\n if (d.context?.source !== 'tree') return;\n d.claimed = true;\n\n // Merge children into the parent node\n const parentRow = d.context.parentNode as TreeRow | undefined;\n if (parentRow) {\n const key = this.#keyOf(parentRow);\n const load = this.#takeLoad(key, parentRow);\n // Requested by Tree but no longer active: superseded and already reported\n // as cancelled — never merge stale children into the replaced row.\n if (!load && (this.#requestedRows.has(parentRow as object) || this.#cancelledRows.has(parentRow as object))) {\n return;\n }\n this.#mergeChildren(parentRow, (d.rows ?? []) as TreeRow[]);\n this.broadcast<TreeLoadEndDetail>('tree-load-end', {\n key,\n row: parentRow,\n depth: load?.depth ?? this.rowKeyMap.get(key)?.depth ?? 0,\n childCount: d.rows?.length ?? 0,\n });\n this.requestRender();\n }\n });\n\n // Listen for datasource:error — release the node's loading state so the\n // user can retry by collapsing and re-expanding. Without this the load\n // stays in `#loads` forever and `requestLazyChildren` short-circuits.\n this.on('datasource:error', (detail: unknown) => {\n const d = detail as DataSourceErrorDetail;\n if (d.context?.source !== 'tree') return;\n const parentRow = d.context.parentNode as TreeRow | undefined;\n if (!parentRow) return;\n const key = this.#keyOf(parentRow);\n const load = this.#takeLoad(key, parentRow);\n if (!load) return;\n this.broadcast<TreeLoadErrorDetail>('tree-load-error', {\n key,\n row: parentRow,\n depth: load.depth,\n error: d.error,\n });\n this.requestRender();\n });\n }\n\n // #endregion\n\n // #region Animation\n\n /**\n * Get expand/collapse animation style from plugin config.\n * Uses base class isAnimationEnabled to respect grid-level settings.\n */\n private get animationStyle(): ExpandCollapseAnimation {\n if (!this.isAnimationEnabled) return false;\n return this.config.animation ?? 'slide';\n }\n\n // #endregion\n\n // #region Auto-Detection\n\n detect(rows: readonly unknown[]): boolean {\n if (!this.config.autoDetect) return false;\n const treeRows = rows as readonly TreeRow[];\n const field = this.config.childrenField ?? inferChildrenField(treeRows) ?? 'children';\n return detectTreeStructure(treeRows, field);\n }\n\n // #endregion\n\n // #region Data Processing\n\n /** @internal */\n override processRows(rows: readonly unknown[]): TreeRow[] {\n const hierarchy = this.grid?.getPluginByName?.('hierarchy');\n return (hierarchy ? hierarchy.process(rows, this) : buildHierarchy(rows, [this])) as TreeRow[];\n }\n\n /** @internal Hierarchy contributor hook */\n beginHierarchy(rows: readonly unknown[]): boolean {\n const treeRows = rows as readonly TreeRow[];\n if (\n treeRows.length === 0 ||\n !detectTreeStructure(treeRows, this.config.childrenField ?? 'children', this.config.hasChildren)\n ) {\n this.flattenedRows = [];\n this.#rootOwners = [];\n this.#rootCount = 0;\n this.rowKeyMap.clear();\n this.previousVisibleKeys.clear();\n this.#reconcileFlatRows(treeRows);\n this.#syncTreeColumn();\n return false;\n }\n\n // A ServerSide data source in `sortMode: 'server'` already ordered the roots\n // (`getRows({ sortModel })`) and lazy children (`getChildRows({ sortModel })`)\n // — keep its order (#524). Otherwise prefer MultiSort's model over local sort\n // state so Tree and MultiSort don't fight over sort ownership.\n const serverSorts = this.grid?.query?.<'server' | 'local'>('datasource:sort-mode', null)?.[0] === 'server';\n this.#levelSort = serverSorts ? null : this.resolveEffectiveSortState();\n\n if (this.config.defaultExpanded && !this.initialExpansionDone) {\n this.expandedKeys = expandAll(treeRows, this.config);\n this.initialExpansionDone = true;\n }\n this.#rowMeta = new WeakMap();\n return true;\n }\n\n /**\n * Sort one sibling list and attach each expanded node's children, never\n * cloning row objects — `data` on each FlattenedTreeRow stays `===` the\n * user's source row.\n * @internal Hierarchy contributor hook\n */\n processSiblings(nodes: HierarchyNode[], context: HierarchySiblingContext): HierarchyNode[] {\n const { parentKey, depth } = context;\n const childrenField = this.config.childrenField ?? 'children';\n const hasChildrenFn = this.config.hasChildren;\n // Assign stable keys using the ORIGINAL (unsorted) index so that\n // path-based keys match those produced by `expandAll` (which walks the\n // tree in source order). `#keyFor` caches by row identity, so the\n // subsequent lookup in the post-sort loop returns the same key.\n for (let i = 0; i < nodes.length; i++) {\n this.#keyFor(nodes[i].row as TreeRow, i, parentKey);\n }\n const sort = this.#levelSort;\n const ordered = sort ? this.#sortNodes(nodes, sort.field, sort.direction) : nodes;\n\n for (let i = 0; i < ordered.length; i++) {\n const node = ordered[i];\n const row = node.row as TreeRow;\n const key = this.#keyFor(row, i, parentKey);\n const children = row[childrenField];\n const embeddedChildren = Array.isArray(children) && children.length > 0;\n // Lazy children: either a custom `hasChildren` predicate reports the node\n // has children, or (default heuristic) a truthy non-array value such as\n // `children: true` signals children exist but haven't been fetched yet.\n // A loading placeholder (ServerSide) is a leaf and never reaches `hasChildren`.\n const hasChildren =\n embeddedChildren ||\n (row.__loading !== true &&\n (hasChildrenFn ? hasChildrenFn(row) : children != null && !Array.isArray(children) && !!children));\n const isExpanded = this.expandedKeys.has(key);\n\n this.#rowMeta.set(row as object, {\n key,\n data: row,\n depth,\n hasChildren,\n isExpanded,\n parentKey,\n posInSet: i + 1,\n setSize: ordered.length,\n });\n\n node.key = key;\n if (embeddedChildren && isExpanded) {\n node.expanded = true;\n node.children = (children as TreeRow[]).map((child) => ({ row: child }));\n }\n }\n return ordered;\n }\n\n /** @internal Hierarchy contributor hook */\n endHierarchy(rows: readonly unknown[], positionOf: (row: unknown) => HierarchyRowMeta | undefined): boolean {\n // Keep metadata for rendered rows only, so rows hidden by a collapsed\n // ancestor don't return stale entries via getRowMeta().\n const processed = this.#rowMeta;\n this.#rowMeta = new WeakMap();\n this.flattenedRows = [];\n this.rowKeyMap.clear();\n this.keysToAnimate.clear();\n const currentKeys = new Set<string>();\n const rootOwners = new Array<number>(rows.length);\n let rootOrdinal = -1;\n\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const meta = processed.get(row as object);\n if (meta?.parentKey === null) rootOrdinal++;\n rootOwners[i] = rootOrdinal;\n if (!meta) continue;\n // Indent below any levels another contributor (e.g. grouping) inserted above this row.\n const level = positionOf(row)?.level;\n if (level !== undefined) meta.depth = level - 1;\n this.flattenedRows.push(meta);\n this.rowKeyMap.set(meta.key, meta);\n this.#rowMeta.set(row as object, meta);\n currentKeys.add(meta.key);\n if (!this.previousVisibleKeys.has(meta.key) && meta.depth > 0) {\n this.keysToAnimate.add(meta.key);\n }\n if (this.#needsReconcile(meta)) {\n this.#queueReconcile(meta);\n }\n }\n this.previousVisibleKeys = currentKeys;\n this.#rootOwners = rootOwners;\n this.#rootCount = rootOrdinal + 1;\n\n this.#syncTreeColumn();\n return true;\n }\n\n /**\n * Keep the tree column decoration in sync with whether the current data is a\n * tree.\n *\n * `processColumns` bails out while `flattenedRows` is empty, and a ROWS-only\n * render (async `grid.rows` assignment, a ServerSide block landing) never\n * re-runs the COLUMNS phase — so without this the toggle/indent renderer is\n * never installed for data that arrives after the first render.\n *\n * The comparison is deferred to a microtask so that a COLUMNS-phase render —\n * whose `processColumns` runs later in the same synchronous scheduler flush —\n * settles the flag first and costs no extra frame.\n */\n #syncTreeColumn(): void {\n if (this.#treeColumnSyncScheduled) return;\n this.#treeColumnSyncScheduled = true;\n queueMicrotask(() => {\n this.#treeColumnSyncScheduled = false;\n if (!this.grid) return;\n if (this.#treeColumnWrapped !== this.flattenedRows.length > 0) {\n this.requestColumnsRender();\n }\n });\n }\n\n /**\n * Resolve the stable key for a row, caching by identity in {@link #rowKeys}.\n * Prefers `row.id` (already stable across sort), then any previously cached\n * key for this row reference, then falls back to a path-based key.\n */\n #keyFor(row: TreeRow, index: number, parentKey: string | null): string {\n if (row.id !== undefined) {\n const key = String(row.id);\n this.#rowKeys.set(row as object, key);\n return key;\n }\n const cached = this.#rowKeys.get(row as object);\n if (cached !== undefined) return cached;\n const key = parentKey ? `${parentKey}-${index}` : String(index);\n this.#rowKeys.set(row as object, key);\n return key;\n }\n\n /** Order a sibling list's nodes by their rows via {@link #sortLevel}. */\n #sortNodes(nodes: HierarchyNode[], field: string, dir: 1 | -1): HierarchyNode[] {\n const byRow = new Map<unknown, HierarchyNode>();\n for (const node of nodes) byRow.set(node.row, node);\n const sorted = this.#sortLevel(\n nodes.map((node) => node.row as TreeRow),\n field,\n dir,\n );\n return sorted.map((row) => byRow.get(row) ?? { row });\n }\n\n /**\n * Sort rows at a single level, returning a new array of the SAME row references\n * in sorted order. Never clones row objects, and never mutates the input array\n * (children arrays are user-owned for tree rows — we always pass a shallow copy\n * to the handler so a custom in-place sortHandler can't corrupt user data).\n *\n * Delegates to the same handler chain core uses: `gridConfig.sortHandler` when\n * provided, otherwise `builtInSort` (which honors per-column `sortComparator`\n * and `valueAccessor`). Async handlers cannot be awaited inside the synchronous\n * tree flatten — fall back to `builtInSort` when one is detected, and swallow\n * any rejection so it doesn't surface as an unhandled promise rejection.\n */\n #sortLevel(rows: readonly TreeRow[], field: string, dir: 1 | -1): TreeRow[] {\n const host = this.grid;\n const columns = (host?._columns ?? []) as ColumnConfig<TreeRow>[];\n const handler: SortHandler<TreeRow> = host?.effectiveConfig?.sortHandler ?? builtInSort;\n const sortState = { field, direction: dir };\n // Always pass a shallow copy: `rows` may be a user-owned `row.children`\n // array, and a non-defensive sortHandler could otherwise mutate it.\n const input = [...rows] as TreeRow[];\n const result = handler(input, sortState, columns);\n if (result && typeof (result as Promise<unknown[]>).then === 'function') {\n void (result as Promise<unknown[]>).catch(() => undefined);\n return builtInSort(input, sortState, columns);\n }\n return result as TreeRow[];\n }\n\n /**\n * Look up the stable key by row identity (was stored on the row as\n * `__stableKey` historically; now lives in a parallel WeakMap to keep row\n * identity intact).\n */\n #keyOf(row: TreeRow): string {\n return this.#rowKeys.get(row as object) ?? String(row.id ?? '?');\n }\n\n /** Write fetched children onto the parent row and mark the node as loaded. */\n #mergeChildren(row: TreeRow, children: TreeRow[]): void {\n (row as Record<string, unknown>)[this.config.childrenField ?? 'children'] = children;\n this.#loadedRows.add(row as object);\n }\n\n /**\n * Whether a node's children still need to be fetched — it reports having\n * children (via the lazy indicator or a custom `hasChildren` predicate) but\n * none are embedded yet, and no previous fetch for this row object has resolved.\n */\n #needsChildFetch(row: TreeRow): boolean {\n if (this.#loadedRows.has(row as object)) return false;\n const children = row[this.config.childrenField ?? 'children'];\n if (Array.isArray(children) && children.length > 0) return false;\n const custom = this.config.hasChildren;\n return custom ? custom(row) : children != null && !Array.isArray(children) && !!children;\n }\n\n /**\n * Whether a rendered node needs reconciling with `#loads`:\n * - a pending load belongs to a DIFFERENT row object under this key — the row\n * was replaced, so that load is obsolete whether or not the replacement needs\n * a fetch (it may embed its children, or the node may be collapsed);\n * - or the node is expanded with lazy children its row object never requested\n * — e.g. a root replaced by a ServerSide refetch (#527), or a node passed to\n * {@link expand} before its row existed.\n *\n * ServerSide placeholders never supersede a load: their path key can collide\n * with a real row's id.\n */\n #needsReconcile(meta: FlattenedTreeRow): boolean {\n if (meta.data.__loading === true) return false;\n const load = this.#loads.get(meta.key);\n if (load) return load.row !== meta.data;\n return (\n meta.isExpanded &&\n meta.hasChildren &&\n !this.#requestedRows.has(meta.data as object) &&\n this.#needsChildFetch(meta.data)\n );\n }\n\n /**\n * Cancel pending loads whose key now belongs to a different row object in data\n * that is no longer a tree (e.g. the only lazy root replaced by a same-key row\n * with `children: []`). `endHierarchy` never runs for flat data, so the\n * {@link #needsReconcile} pass doesn't see these replacements. Cancel-only:\n * flat data never requests children. Placeholders are skipped as in\n * `#needsReconcile`; on duplicate keys the last row owns the key, as in `rowKeyMap`.\n */\n #reconcileFlatRows(rows: readonly TreeRow[]): void {\n if (this.#loads.size === 0) return;\n const owners = new Map<string, TreeRow>();\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n if (row.__loading === true) continue;\n // Read-only key lookup — matches `#keyFor` without caching keys for flat rows.\n const key = row.id !== undefined ? String(row.id) : (this.#rowKeys.get(row as object) ?? String(i));\n if (this.#loads.has(key)) owners.set(key, row);\n }\n for (const [key, row] of owners) {\n if (this.#loads.get(key)?.row === row) continue;\n this.#queueReconcile(\n { key, data: row, depth: 0, hasChildren: false, isExpanded: false, parentKey: null, posInSet: 0, setSize: 0 },\n true,\n );\n }\n }\n\n /**\n * Queue a node for {@link #needsReconcile} handling. Deferred to ONE microtask:\n * `endHierarchy` runs inside the render pipeline, and cancelling / requesting\n * broadcasts `tree-load-end` / `tree-load-start` and queries ServerSide\n * synchronously. Loads of nodes that are not rendered (hidden under a\n * collapsed ancestor, or gone from the data) are left to settle.\n *\n * @param flat - Entry from {@link #reconcileFlatRows}: cancel only. `rowKeyMap`\n * is empty for flat data, so the owner check was already applied by the caller.\n */\n #queueReconcile(meta: FlattenedTreeRow, flat = false): void {\n if (this.#pendingReconcile.push({ meta, flat }) > 1) return;\n queueMicrotask(() => {\n const pending = this.#pendingReconcile;\n this.#pendingReconcile = [];\n if (!this.grid) return;\n let started = false;\n for (const { meta: node, flat: cancelOnly } of pending) {\n // Only the key's current owner acts — skips rows replaced again by a later\n // rebuild, and keeps duplicate keys from cancelling each other in a loop.\n if (!cancelOnly && this.rowKeyMap.get(node.key)?.data !== node.data) continue;\n const load = this.#loads.get(node.key);\n if (load && load.row !== node.data) this.#cancelLoad(node.key);\n if (cancelOnly || !this.expandedKeys.has(node.key) || this.#requestedRows.has(node.data as object)) continue;\n // One automatic attempt per row object, even when no loader is configured.\n this.#requestedRows.add(node.data as object);\n started = this.requestLazyChildren(node) || started;\n }\n if (started) this.requestRender();\n });\n }\n\n /**\n * Request lazy children for a node that is being expanded.\n *\n * Two routes, in precedence order:\n * 1. **ServerSide** — when `ServerSidePlugin` is active, dispatch the\n * `datasource:fetch-children` query; the result arrives asynchronously as\n * a `datasource:children` (or `datasource:error`) broadcast.\n * 2. **Local `loadChildren`** — invoke the config callback directly. Works\n * without `ServerSidePlugin` for grids that only need lazy tree children\n * and not server-side root pagination/sorting/filtering.\n *\n * No-op when neither route is configured, this row is already loading, or\n * its children are already embedded. A pending load for a DIFFERENT row\n * object under the same key (replaced by a refetch) is cancelled first.\n *\n * @returns `true` when a fetch was started.\n */\n private requestLazyChildren(flatRow: FlattenedTreeRow): boolean {\n const { key, depth, data: row } = flatRow;\n const active = this.#loads.get(key);\n if (active?.row === row) return false;\n if (!this.#needsChildFetch(row)) return false;\n\n const isServerSideActive = this.queryBoolean('datasource:is-active');\n const { loadChildren } = this.config;\n if (!isServerSideActive && !loadChildren) return false;\n\n if (active) this.#cancelLoad(key);\n const controller = new AbortController();\n this.#loads.set(key, { row, depth, controller });\n this.#requestedRows.add(row as object);\n this.#cancelledRows.delete(row as object);\n this.broadcast<TreeLoadStartDetail>('tree-load-start', { key, row, depth });\n\n if (isServerSideActive) {\n this.grid.query('datasource:fetch-children', {\n context: { source: 'tree', parentNode: row, nodePath: [key] },\n signal: controller.signal,\n } satisfies FetchChildrenQuery);\n return true;\n }\n\n this.#loadChildrenLocally(key, row, depth, controller);\n return true;\n }\n\n /** Whether `meta`'s row object (not just its key) has a child load in flight. */\n #isLoading(meta: FlattenedTreeRow): boolean {\n return this.#loads.get(meta.key)?.row === meta.data;\n }\n\n /** Remove and return the in-flight load for `key` when it belongs to `row`. */\n #takeLoad(key: string, row: TreeRow): { row: TreeRow; depth: number; controller: AbortController } | undefined {\n const load = this.#loads.get(key);\n if (load?.row !== row) return undefined;\n this.#loads.delete(key);\n return load;\n }\n\n /**\n * Abort a superseded load and close its event pair with a cancelled\n * `tree-load-end`, so every `tree-load-start` gets exactly one end or error.\n */\n #cancelLoad(key: string): void {\n const load = this.#loads.get(key);\n if (!load) return;\n this.#loads.delete(key);\n // Not a settled attempt: a restored row must be able to load again automatically.\n this.#requestedRows.delete(load.row as object);\n this.#cancelledRows.add(load.row as object);\n load.controller.abort();\n this.broadcast<TreeLoadEndDetail>('tree-load-end', {\n key,\n row: load.row,\n depth: load.depth,\n childCount: 0,\n cancelled: true,\n });\n }\n\n /**\n * Drive the local `loadChildren` callback. Supports both `Promise` and\n * `Subscribable` results; the subscription is torn down on abort so an\n * Angular `HttpClient` request is cancelled natively.\n */\n #loadChildrenLocally(key: string, row: TreeRow, depth: number, controller: AbortController): void {\n // A callback is guaranteed by the caller's guard.\n const loadChildren = this.config.loadChildren as NonNullable<TreeConfig['loadChildren']>;\n\n const finish = (): boolean => {\n // Superseded (already reported as cancelled) or detached — drop the result.\n if (controller.signal.aborted) return false;\n this.#loads.delete(key);\n return true;\n };\n\n const onSuccess = (rows: TreeRow[] | null | undefined) => {\n if (!finish()) return;\n const children = rows ?? [];\n this.#mergeChildren(row, children);\n this.broadcast<TreeLoadEndDetail>('tree-load-end', { key, row, depth, childCount: children.length });\n this.requestRender();\n };\n\n const onError = (error: unknown) => {\n if (!finish()) return;\n this.broadcast<TreeLoadErrorDetail>('tree-load-error', { key, row, depth, error });\n this.requestRender();\n };\n\n let result: Promise<TreeRow[]> | Subscribable<TreeRow[]>;\n try {\n result = loadChildren({ row, key, depth, signal: controller.signal });\n } catch (error) {\n onError(error);\n return;\n }\n\n if (result && isSubscribable(result)) {\n // Take-one semantics: `onSuccess`/`onError` are single-shot (guarded by\n // `finish()`), so hold the subscription only until the first emission.\n // Without this, a source that never completes (a subject-like stream)\n // stays subscribed forever once its value has been consumed, because\n // `finish()` has already removed the load whose controller `detach()` aborts.\n let settled = false;\n let active: { unsubscribe(): void } | null = null;\n const release = (): void => {\n settled = true;\n active?.unsubscribe();\n active = null;\n };\n const subscription = result.subscribe({\n next: (rows) => {\n onSuccess(rows);\n release();\n },\n error: (error) => {\n onError(error);\n release();\n },\n });\n // A synchronous emission ran `release()` before `subscription` was bound.\n if (settled) {\n subscription.unsubscribe();\n return;\n }\n active = subscription;\n controller.signal.addEventListener('abort', release, { once: true });\n return;\n }\n Promise.resolve(result).then(onSuccess, onError);\n }\n\n /**\n * Resolve the effective sort state: prefer MultiSort's model when available,\n * fall back to local tree sort state.\n * This follows the same pattern as GroupingRowsPlugin.resolveGroupSortDirections.\n */\n private resolveEffectiveSortState(): { field: string; direction: 1 | -1 } | null {\n // When MultiSort is loaded, prefer its model for consistency\n const multiSortResults = this.grid?.query?.('sort:get-model', null);\n if (Array.isArray(multiSortResults) && multiSortResults.length > 0) {\n const sortModel = multiSortResults[0] as Array<{ field: string; direction: 'asc' | 'desc' }>;\n if (Array.isArray(sortModel) && sortModel.length > 0) {\n // Use the primary sort column from MultiSort\n return {\n field: sortModel[0].field,\n direction: sortModel[0].direction === 'desc' ? -1 : 1,\n };\n }\n }\n // Fallback: local sort state (when MultiSort is not loaded)\n return this.sortState;\n }\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n if (this.flattenedRows.length === 0) {\n const cols = [...columns] as ColumnConfig[];\n // The wrapper cannot simply be dropped: `_schedulerMergeConfig` reseeds\n // `#baseColumns` from `_columns`, so a previously wrapped renderer is\n // already baked into the columns handed to us. Put the original back.\n if (this.#treeColumnWrapped) {\n const idx = cols.findIndex((c) => c.field === this.wrappedTreeColumnField);\n if (idx >= 0) {\n cols[idx] = {\n ...cols[idx],\n renderer:\n this.originalTreeColumnRendererProperty === 'renderer' ? this.originalTreeColumnRenderer : undefined,\n };\n }\n }\n this.#treeColumnWrapped = false;\n this.originalTreeColumnRenderer = undefined;\n this.originalTreeColumnRendererProperty = 'viewRenderer';\n this.wrappedTreeColumnField = undefined;\n return cols;\n }\n\n const cols = [...columns] as ColumnConfig[];\n if (cols.length === 0) return cols;\n\n // Determine which column gets the tree toggle and indentation.\n // If treeColumn is configured, find it by field name; otherwise use the first column.\n const { treeColumn } = this.config;\n let targetIndex = 0;\n if (treeColumn) {\n const idx = cols.findIndex((c) => c.field === treeColumn);\n if (idx >= 0) targetIndex = idx;\n }\n const targetCol = cols[targetIndex];\n const targetField = targetCol.field;\n\n // Capture the original (unwrapped) renderer only once per target column.\n // On subsequent processColumns calls, reuse the cached original so we\n // don't nest tree-cell-wrappers.\n if (this.wrappedTreeColumnField !== targetField) {\n this.originalTreeColumnRenderer = targetCol.renderer || targetCol.viewRenderer;\n this.originalTreeColumnRendererProperty = targetCol.renderer ? 'renderer' : 'viewRenderer';\n this.wrappedTreeColumnField = targetField;\n }\n const originalRenderer = this.originalTreeColumnRenderer;\n const getConfig = () => this.config;\n const setIconFn = this.setIcon.bind(this);\n\n const wrappedRenderer: ColumnViewRenderer = (ctx) => {\n const { row, value } = ctx;\n const { showExpandIcons = true, indentWidth } = getConfig();\n const meta = this.#rowMeta.get(row as object);\n const depth = meta?.depth ?? 0;\n\n const container = document.createElement('span');\n container.className = 'tree-cell-wrapper';\n container.style.setProperty('--tbw-tree-depth', String(depth));\n // Allow config-based indentWidth to override CSS default\n if (indentWidth !== undefined) {\n container.style.setProperty('--tbw-tree-indent-width', `${indentWidth}px`);\n }\n\n // Add expand/collapse icon, loading spinner, or spacer\n if (showExpandIcons) {\n if (meta && this.#isLoading(meta)) {\n // Reuse the core loading UI (`.tbw-spinner--small`) instead of a\n // tree-specific indicator so custom spinner theming applies here too.\n const spinner = createDefaultSpinner('small');\n spinner.classList.add('tree-loading');\n container.appendChild(spinner);\n } else if (meta && meta.hasChildren) {\n const icon = document.createElement('span');\n icon.className = `${GridClasses.TREE_TOGGLE}${meta.isExpanded ? ` ${GridClasses.EXPANDED}` : ''}`;\n setIconFn(icon, meta.isExpanded ? 'collapse' : 'expand');\n icon.setAttribute('data-tree-key', meta.key);\n container.appendChild(icon);\n } else {\n const spacer = document.createElement('span');\n spacer.className = 'tree-spacer';\n container.appendChild(spacer);\n }\n }\n\n // Add the original content\n const content = document.createElement('span');\n content.className = 'tree-content';\n if (originalRenderer) {\n const result = originalRenderer(ctx);\n if (result instanceof Node) {\n content.appendChild(result);\n } else if (typeof result === 'string') {\n setSanitizedHTML(content, result);\n }\n } else {\n content.textContent = value != null ? String(value) : '';\n }\n container.appendChild(content);\n\n return container;\n };\n\n cols[targetIndex] = { ...targetCol, renderer: wrappedRenderer };\n this.#treeColumnWrapped = true;\n return cols;\n }\n\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onCellClick(event: CellClickEvent): boolean {\n const target = event.originalEvent?.target as HTMLElement;\n if (!target?.classList.contains(GridClasses.TREE_TOGGLE)) return false;\n\n const key = target.getAttribute('data-tree-key');\n if (!key) return false;\n\n const flatRow = this.rowKeyMap.get(key);\n if (!flatRow) return false;\n\n this.expandedKeys = toggleExpand(this.expandedKeys, key);\n\n // Request lazy children when expanding a node without embedded children\n if (this.expandedKeys.has(key)) {\n this.requestLazyChildren(flatRow);\n }\n\n this.broadcast<TreeExpandDetail>('tree-expand', {\n key,\n row: flatRow.data,\n expanded: this.expandedKeys.has(key),\n depth: flatRow.depth,\n expandedKeys: [...this.expandedKeys],\n });\n this.requestRender();\n return true;\n }\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n // SPACE toggles expansion when on a row with children\n if (event.key !== ' ') return;\n // An open editor (or any input in the row) owns Space — let it type (#546).\n if (isFormFieldKeyTarget(event)) return;\n\n const focusRow = this.grid._focusRow;\n const flatRow = this.#rowMeta.get(this.rows[focusRow] as object);\n if (!flatRow?.hasChildren) return;\n\n event.preventDefault();\n this.expandedKeys = toggleExpand(this.expandedKeys, flatRow.key);\n\n // Request lazy children when expanding a node without embedded children\n if (this.expandedKeys.has(flatRow.key)) {\n this.requestLazyChildren(flatRow);\n }\n\n this.broadcast<TreeExpandDetail>('tree-expand', {\n key: flatRow.key,\n row: flatRow.data,\n expanded: this.expandedKeys.has(flatRow.key),\n depth: flatRow.depth,\n expandedKeys: [...this.expandedKeys],\n });\n this.requestRenderWithFocus();\n return true;\n }\n\n /** @internal */\n override onHeaderClick(event: HeaderClickEvent): boolean {\n if (this.flattenedRows.length === 0 || !event.column.sortable) return false;\n\n // When MultiSort is active, let it handle header clicks entirely.\n // Tree will pick up the sort model in processRows via resolveEffectiveSortState().\n const multiSortResults = this.grid?.query?.('sort:get-model', null);\n if (Array.isArray(multiSortResults) && multiSortResults.length > 0) {\n // MultiSort is loaded — don't consume the event, let MultiSort handle it\n return false;\n }\n\n // Fallback: manage own sort state when MultiSort is not loaded\n const { field } = event.column;\n if (!this.sortState || this.sortState.field !== field) {\n this.sortState = { field, direction: 1 };\n } else if (this.sortState.direction === 1) {\n this.sortState = { field, direction: -1 };\n } else {\n this.sortState = null;\n }\n\n // Sync grid sort indicator\n const gridEl = this.grid;\n if (gridEl._sortState !== undefined) {\n gridEl._sortState = this.sortState ? { ...this.sortState } : null;\n }\n\n this.broadcast('sort-change', { field, direction: this.sortState?.direction ?? 0 });\n this.requestRender();\n return true;\n }\n\n /** @internal */\n override afterRender(): void {\n const body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n const style = this.animationStyle;\n const shouldAnimate = style !== false && this.keysToAnimate.size > 0;\n const animClass = style === 'fade' ? 'tbw-tree-fade-in' : 'tbw-tree-slide-in';\n\n for (const rowEl of body.querySelectorAll('.data-grid-row')) {\n // Look up by row identity: other hierarchy contributors (group rows)\n // may be interleaved with tree rows in the rendered list.\n const treeRow = this.#rowMeta.get((rowEl as RowElementInternal).__rowDataRef as object);\n if (!treeRow) continue;\n\n // Set aria-expanded on parent rows for screen readers. MUST clear it\n // on leaf rows: virtualization recycles row DOM elements, so a leaf\n // row reusing a previously-expanded parent's element would otherwise\n // inherit a stale `aria-expanded=\"true\"` (issue #282). The matching\n // `.tbw-row-expanded` class is the public hook for theming expanded\n // rows — devs should style against the class, not the ARIA attribute.\n if (treeRow.hasChildren) {\n rowEl.setAttribute('aria-expanded', String(treeRow.isExpanded));\n } else if (rowEl.hasAttribute('aria-expanded')) {\n rowEl.removeAttribute('aria-expanded');\n }\n rowEl.classList.toggle('tbw-row-expanded', treeRow.hasChildren && treeRow.isExpanded);\n\n // Announce in-flight lazy child loading. MUST clear on the negative\n // branch — virtualization recycles row elements, so a row reusing a\n // previously-loading element would inherit a stale `aria-busy`. A row in\n // the CORE row-loading state (`.tbw-row-loading`: a ServerSide placeholder,\n // or `grid.setRowLoading()`) owns its own `aria-busy` — leave it alone.\n if (this.#isLoading(treeRow)) {\n rowEl.setAttribute('aria-busy', 'true');\n } else if (rowEl.hasAttribute('aria-busy') && !rowEl.classList.contains('tbw-row-loading')) {\n rowEl.removeAttribute('aria-busy');\n }\n\n if (shouldAnimate && treeRow.key && this.keysToAnimate.has(treeRow.key)) {\n rowEl.classList.add(animClass);\n rowEl.addEventListener('animationend', () => rowEl.classList.remove(animClass), { once: true });\n }\n }\n this.keysToAnimate.clear();\n }\n\n // #endregion\n\n // #region Public API\n\n /**\n * Expand a specific tree node, revealing its children.\n *\n * If the node is already expanded, this is a no-op.\n * Does **not** emit a `tree-expand` event (use {@link toggle} for event emission).\n *\n * @param key - The unique key of the node to expand (from {@link FlattenedTreeRow.key})\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * tree.expand('documents'); // Expand a root node\n * tree.expand('documents||reports'); // Expand a nested node\n * ```\n */\n expand(key: string): void {\n this.expandedKeys.add(key);\n const flatRow = this.rowKeyMap.get(key);\n if (flatRow) {\n this.requestLazyChildren(flatRow);\n }\n this.requestRender();\n }\n\n /**\n * Collapse a specific tree node, hiding its children.\n *\n * If the node is already collapsed, this is a no-op.\n * Does **not** emit a `tree-expand` event (use {@link toggle} for event emission).\n *\n * @param key - The unique key of the node to collapse (from {@link FlattenedTreeRow.key})\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * tree.collapse('documents');\n * ```\n */\n collapse(key: string): void {\n this.expandedKeys.delete(key);\n this.requestRender();\n }\n\n /**\n * Toggle the expanded state of a tree node.\n *\n * If the node is expanded it will be collapsed, and vice versa.\n * Emits a `tree-expand` event (broadcast to both DOM consumers and plugin bus).\n *\n * @param key - The unique key of the node to toggle (from {@link FlattenedTreeRow.key})\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * tree.toggle('documents'); // Expand if collapsed, collapse if expanded\n * ```\n */\n toggle(key: string): void {\n this.expandedKeys = toggleExpand(this.expandedKeys, key);\n const flatRow = this.rowKeyMap.get(key);\n if (flatRow) {\n // Request lazy children when expanding a node without embedded children\n if (this.expandedKeys.has(key)) {\n this.requestLazyChildren(flatRow);\n }\n this.broadcast<TreeExpandDetail>('tree-expand', {\n key,\n row: flatRow.data,\n expanded: this.expandedKeys.has(key),\n depth: flatRow.depth,\n expandedKeys: [...this.expandedKeys],\n });\n } else {\n this.emitPluginEvent('tree-expand', { expandedKeys: [...this.expandedKeys] });\n }\n this.requestRender();\n }\n\n /**\n * Expand all tree nodes recursively.\n *\n * Every node with children will be expanded, revealing the full tree hierarchy.\n * Emits a `tree-expand` plugin event.\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * tree.expandAll();\n * ```\n */\n expandAll(): void {\n this.expandedKeys = expandAll(this.rows as TreeRow[], this.config);\n this.emitPluginEvent('tree-expand', { expandedKeys: [...this.expandedKeys] });\n this.requestRender();\n }\n\n /**\n * Collapse all tree nodes.\n *\n * Every node will be collapsed, showing only root-level rows.\n * Emits a `tree-expand` plugin event.\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * tree.collapseAll();\n * ```\n */\n collapseAll(): void {\n this.expandedKeys = collapseAll();\n this.emitPluginEvent('tree-expand', { expandedKeys: [...this.expandedKeys] });\n this.requestRender();\n }\n\n /**\n * Check whether a specific tree node is currently expanded.\n *\n * @param key - The unique key of the node to check\n * @returns `true` if the node is expanded, `false` otherwise\n */\n isExpanded(key: string): boolean {\n return this.expandedKeys.has(key);\n }\n\n /**\n * Get the keys of all currently expanded nodes.\n *\n * Returns a snapshot copy — mutating the returned array does not affect the tree state.\n *\n * @returns Array of expanded node keys\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * const keys = tree.getExpandedKeys();\n * localStorage.setItem('treeState', JSON.stringify(keys));\n * ```\n */\n getExpandedKeys(): string[] {\n return [...this.expandedKeys];\n }\n\n /**\n * Get the flattened row model used for rendering.\n *\n * Returns a snapshot copy of the internal flattened tree rows, including\n * hierarchy metadata (depth, hasChildren, isExpanded, parentKey).\n *\n * @returns Array of {@link FlattenedTreeRow} objects\n */\n getFlattenedRows(): FlattenedTreeRow[] {\n return [...this.flattenedRows];\n }\n\n /**\n * Get tree metadata (depth, key, hasChildren, isExpanded, parentKey) for a\n * specific row reference. Returns `undefined` if the row is not part of the\n * currently-flattened tree (e.g. collapsed under a parent or never processed).\n *\n * Tree metadata lives in a parallel WeakMap keyed by row identity \\u2014 it is\n * NOT stored on the row object itself. This preserves the invariant that\n * `_rows[i]` IS the user's source row reference, so `grid.updateRow(s)`\n * mutations survive the next ROWS-phase rebuild.\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * const meta = tree.getRowMeta(grid.rows[0]);\n * console.log(meta?.depth, meta?.hasChildren);\n * ```\n */\n getRowMeta(row: TreeRow): FlattenedTreeRow | undefined {\n return this.#rowMeta.get(row as object);\n }\n\n /**\n * Look up an original row data object by its tree key.\n *\n * @param key - The unique key of the node\n * @returns The original row data, or `undefined` if not found\n */\n getRowByKey(key: string): TreeRow | undefined {\n return this.rowKeyMap.get(key)?.data;\n }\n\n /**\n * Expand all ancestor nodes of the target key, revealing it in the tree.\n *\n * Useful for \"scroll to node\" or search-and-reveal scenarios where a deeply\n * nested node needs to be made visible.\n *\n * @param key - The unique key of the node to reveal\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * // Reveal a deeply nested node by expanding all its parents\n * tree.expandToKey('root||child||grandchild');\n * ```\n */\n expandToKey(key: string): void {\n this.expandedKeys = expandToKey(this.rows as TreeRow[], key, this.config, this.expandedKeys);\n this.requestRender();\n }\n\n // #endregion\n}\n"],"mappings":"C,qWAoCA,IAAasB,EAuBD,WAvBCA,EAiDE,cCxETC,EACJ,4SACGC,MAAM,KACNC,IAAKC,GAAMA,EAAEF,MAAM,IAAIG,UAAUC,KAAK,KA2BrCC,GA1BY,IAAIC,OAAO,uCAAuCP,EAAGQ,MAAM,GAAGH,KAAK,gBA0B9D,IAAII,IACzB,2KAA2KR,MACzK,OAOES,EAAyB,WAKzBC,EAAY,IAAIF,IAAI,kEAAkER,MAAM,MAK5FW,EAAyB,wCAsC/B,SAAgBC,EAAmBC,GACjC,MAAMC,EAAWC,SAASC,cAAc,YAKxC,OAJIH,G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AAKtE,KAAKqI,OAAQrI,KAAKiI,cAC/EjI,KAAK2N,eACP,G"}
|
|
1
|
+
{"version":3,"file":"tree.umd.js","names":["BaseGridPlugin","BaseGridPlugin","styles","builtInSort","global","factory","exports","module","require","define","amd","globalThis","self","TbwGridPlugin_tree","TbwGrid","this","_toolbox_web_grid","Object","defineProperty","Symbol","toStringTag","value","GridClasses","_F","split","map","s","reverse","join","DANGEROUS_TAGS","RegExp","slice","Set","DANGEROUS_ATTR_PATTERN","URL_ATTRS","DANGEROUS_URL_PROTOCOL","sanitizeToFragment","html","template","document","createElement","innerHTML","root","toRemove","elements","querySelectorAll","el","tagName","toLowerCase","has","push","namespaceURI","Array","from","attributes","some","attr","test","name","attrsToRemove","attrName","forEach","removeAttribute","remove","sanitizeNode","content","buildHierarchy","rows","contributors","meta","WeakMap","substitute","roots","out","i","length","row","substituteValues","active","stage","c","hierarchyStage","beginHierarchy","process","nodes","parent","depth","substituteRows","context","parentKey","key","processSiblings","emit","setSize","node","set","level","posInSet","children","expanded","shaped","rootNodes","positionOf","get","endHierarchy","delete","setAttrIfChanged","next","String","getAttribute","setAttribute","isContributor","plugin","processRowsPriority","constructor","manifest","hookPriority","processRows","HierarchyPlugin","BaseGridPlugin","static","modifiesRowStructure","detach","gridElement","querySelector","caller","includes","rowSubstitute","responses","grid","query","pinned","size","Map","id","getRowId","getRowMeta","afterRender","applyAria","onScrollRender","_pluginManager","getPlugins","filter","sort","a","b","body","hierarchical","rowEl","__rowDataRef","role","rowsBody","generateRowKey","index","toggleExpand","expandedKeys","newExpanded","add","expandAll","config","childrenField","keys","isArray","childKeys","k","getPathToKey","targetKey","childPath","expandToKey","existingExpanded","path","detectTreeStructure","hasChildren","__loading","TreePlugin","onCellClick","incompatibleWith","reason","events","type","description","queries","required","provide","styles","defaultConfig","autoDetect","defaultExpanded","indentWidth","showExpandIcons","animation","initialExpansionDone","flattenedRows","rowKeyMap","previousVisibleKeys","keysToAnimate","rootOwners","rootCount","sortState","levelSort","loads","loadedRows","WeakSet","requestedRows","cancelledRows","pendingReconcile","rowKeys","rowMeta","originalTreeColumnRenderer","originalTreeColumnRendererProperty","wrappedTreeColumnField","treeColumnWrapped","treeColumnSyncScheduled","clear","load","values","controller","abort","handleQuery","viewportStart","viewportEnd","last","ownerAt","Math","max","min","startNode","endNode","totalLoadedNodes","mapViewportToRoots","attach","super","on","detail","d","claimed","source","parentRow","parentNode","keyOf","takeLoad","mergeChildren","broadcast","childCount","requestRender","error","animationStyle","isAnimationEnabled","detect","treeRows","field","commonArrayFields","inferChildrenField","hierarchy","getPluginByName","reconcileFlatRows","syncTreeColumn","serverSorts","resolveEffectiveSortState","hasChildrenFn","keyFor","ordered","sortNodes","direction","embeddedChildren","isExpanded","data","child","processed","currentKeys","rootOrdinal","needsReconcile","queueReconcile","queueMicrotask","requestColumnsRender","cached","dir","byRow","sortLevel","host","columns","_columns","input","result","effectiveConfig","sortHandler","builtInSort","then","catch","needsChildFetch","custom","owners","flat","pending","started","cancelOnly","cancelLoad","requestLazyChildren","flatRow","isServerSideActive","queryBoolean","loadChildren","AbortController","nodePath","signal","loadChildrenLocally","isLoading","cancelled","finish","aborted","onSuccess","onError","subscribe","settled","release","unsubscribe","subscription","addEventListener","once","Promise","resolve","multiSortResults","sortModel","processColumns","cols","idx","findIndex","renderer","treeColumn","targetIndex","targetCol","targetField","viewRenderer","originalRenderer","getConfig","setIconFn","setIcon","bind","ctx","container","className","style","setProperty","spinner","createDefaultSpinner","classList","appendChild","icon","spacer","Node","indexOf","replaceChildren","textContent","event","toggle","originalEvent","target","closest","onKeyDown","composedPath","HTMLElement","tag","isContentEditable","isFormFieldKeyTarget","focusRow","_focusRow","preventDefault","requestRenderWithFocus","onHeaderClick","column","sortable","gridEl","_sortState","shouldAnimate","animClass","treeRow","hasAttribute","contains","expand","collapse","emitPluginEvent","collapseAll","getExpandedKeys","getFlattenedRows","getRowByKey"],"sources":["../../../../../libs/grid/src/lib/core/constants.ts","../../../../../libs/grid/src/lib/core/internal/sanitize.ts","../../../../../libs/grid/src/lib/core/internal/loading.ts","../../../../../libs/grid/src/lib/plugins/hierarchy/hierarchy.ts","../../../../../libs/grid/src/lib/plugins/hierarchy/hierarchy-plugin.ts","../../../../../libs/grid/src/lib/plugins/tree/tree-data.ts","../../../../../libs/grid/src/lib/plugins/shared/form-field-target.ts","../../../../../libs/grid/src/lib/plugins/tree/tree-datasource.ts","../../../../../libs/grid/src/lib/plugins/tree/tree-detect.ts","../../../../../libs/grid/src/lib/plugins/tree/tree.css?inline","../../../../../libs/grid/src/lib/plugins/tree/tree-plugin.ts"],"sourcesContent":["/**\n * Grid DOM Constants\n *\n * Centralized constants for CSS classes, data attributes, and selectors\n * used throughout the grid. Use these instead of magic strings.\n *\n * Note: Some constants here are used by plugins but defined in core because:\n * 1. The core CSS needs to style these elements (e.g., sticky positioning)\n * 2. Multiple plugins may share the same class names\n *\n * Plugins can define their own additional constants and export them.\n * See each plugin's index.ts for plugin-specific exports.\n */\n\n/**\n * CSS selector for focusable editor elements within a cell.\n * Used by EditingPlugin, UndoRedoPlugin, and keyboard navigation. Defined here\n * (a leaf module) rather than in `rows.ts` so `keyboard.ts` can consume it\n * without creating a rows ↔ keyboard import cycle.\n */\nexport const FOCUSABLE_EDITOR_SELECTOR =\n 'input,select,textarea,[contenteditable=\"true\"],[contenteditable=\"\"],[tabindex]:not([tabindex=\"-1\"])';\n\n// #region CSS Classes\n\n/**\n * CSS class names used in the grid's DOM.\n * Use these when adding/removing classes or querying elements.\n *\n * Classes are organized by:\n * - Core: Used by the grid core for structure and basic functionality\n * - Shared: Used by multiple features/plugins, styled by core CSS\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport const GridClasses = {\n // ─── Core Structure ───────────────────────────────────────────────\n ROOT: 'tbw-grid-root',\n HEADER: 'header',\n HEADER_ROW: 'header-row',\n HEADER_CELL: 'header-cell',\n\n // Body structure\n ROWS_VIEWPORT: 'rows-viewport',\n ROWS_SPACER: 'rows-spacer',\n ROWS_CONTAINER: 'rows',\n\n // Row elements\n DATA_ROW: 'data-grid-row',\n GROUP_ROW: 'group-row',\n\n // Cell elements\n DATA_CELL: 'cell',\n\n // ─── Core States ──────────────────────────────────────────────────\n SELECTED: 'selected',\n FOCUSED: 'focused',\n EDITING: 'editing',\n EXPANDED: 'expanded',\n COLLAPSED: 'collapsed',\n DRAGGING: 'dragging',\n RESIZING: 'resizing',\n\n // Sorting (core feature)\n SORTABLE: 'sortable',\n SORTED_ASC: 'sorted-asc',\n SORTED_DESC: 'sorted-desc',\n\n // Visibility\n HIDDEN: 'hidden',\n\n // ─── Shared Classes (used by plugins, styled by core CSS) ────────\n // These are defined here because core CSS provides the base styling.\n // Plugins apply these classes; core CSS defines how they look.\n\n // Sticky positioning (PinnedColumnsPlugin applies, core CSS styles)\n STICKY_LEFT: 'sticky-left',\n STICKY_RIGHT: 'sticky-right',\n\n // Pinned rows (PinnedRowsPlugin applies, core CSS styles)\n PINNED_TOP: 'pinned-top',\n PINNED_BOTTOM: 'pinned-bottom',\n\n // Tree structure (TreePlugin applies, core CSS styles)\n TREE_TOGGLE: 'tree-toggle',\n TREE_INDENT: 'tree-indent',\n\n // Grouping (GroupingRowsPlugin applies, core CSS styles)\n GROUP_TOGGLE: 'group-toggle',\n GROUP_LABEL: 'group-label',\n GROUP_COUNT: 'group-count',\n\n // Selection (SelectionPlugin applies, core CSS styles)\n RANGE_SELECTION: 'range-selection',\n SELECTION_OVERLAY: 'selection-overlay',\n} as const;\n\n// #endregion\n\n// #region Data Attributes\n\n/**\n * Data attribute names used on grid elements.\n * Use these when getting/setting data attributes.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport const GridDataAttrs = {\n // ─── Core Attributes ──────────────────────────────────────────────\n FIELD: 'data-field',\n\n /**\n * Marks a `title` the grid itself put on a cell to reveal ellipsised text\n * (WCAG SC 1.4.12). Anything that sets its own `title` on a cell must clear\n * this, or the grid will later mistake that title for its own and replace it.\n *\n * @since 3.6.0\n */\n TRUNCATED: 'data-tbw-truncated',\n\n // ─── Shared Attributes (used by plugins) ──────────────────────────\n GROUP_KEY: 'data-group-key', // GroupingRowsPlugin\n} as const;\n\n// #endregion\n\n// #region Selectors\n\n/**\n * Common CSS selectors for querying grid elements.\n * Built from the class constants for consistency.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport const GridSelectors = {\n ROOT: `.${GridClasses.ROOT}`,\n HEADER: `.${GridClasses.HEADER}`,\n HEADER_ROW: `.${GridClasses.HEADER_ROW}`,\n HEADER_CELL: `.${GridClasses.HEADER_CELL}`,\n ROWS_VIEWPORT: `.${GridClasses.ROWS_VIEWPORT}`,\n ROWS_CONTAINER: `.${GridClasses.ROWS_CONTAINER}`,\n DATA_ROW: `.${GridClasses.DATA_ROW}`,\n DATA_CELL: `.${GridClasses.DATA_CELL}`,\n GROUP_ROW: `.${GridClasses.GROUP_ROW}`,\n\n // By data attribute\n CELL_BY_FIELD: (field: string) => `.${GridClasses.DATA_CELL}[${GridDataAttrs.FIELD}=\"${field}\"]`,\n\n // State selectors\n SELECTED_ROWS: `.${GridClasses.DATA_ROW}.${GridClasses.SELECTED}`,\n EDITING_CELL: `.${GridClasses.DATA_CELL}.${GridClasses.EDITING}`,\n} as const;\n\n// #endregion\n\n// #region CSS Custom Properties\n\n/**\n * CSS custom property names for theming.\n * Use these when programmatically setting styles.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport const GridCSSVars = {\n // Colors\n COLOR_BG: '--tbw-color-bg',\n COLOR_FG: '--tbw-color-fg',\n COLOR_FG_MUTED: '--tbw-color-fg-muted',\n COLOR_BORDER: '--tbw-color-border',\n COLOR_ACCENT: '--tbw-color-accent',\n COLOR_HEADER_BG: '--tbw-color-header-bg',\n COLOR_HEADER_FG: '--tbw-color-header-fg',\n COLOR_SELECTION: '--tbw-color-selection',\n COLOR_ROW_HOVER: '--tbw-color-row-hover',\n COLOR_ROW_ALT: '--tbw-color-row-alt',\n\n // Sizing\n ROW_HEIGHT: '--tbw-row-height',\n HEADER_HEIGHT: '--tbw-header-height',\n CELL_PADDING: '--tbw-cell-padding',\n\n // Typography\n FONT_FAMILY: '--tbw-font-family',\n FONT_SIZE: '--tbw-font-size',\n\n // Borders\n BORDER_RADIUS: '--tbw-border-radius',\n FOCUS_OUTLINE: '--tbw-focus-outline',\n} as const;\n\n// #endregion\n\n// Type helpers\n\n/**\n * Union of all CSS class names used in the grid's DOM.\n * Use `GridClasses` to access individual values by key.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport type GridClassName = (typeof GridClasses)[keyof typeof GridClasses];\n\n/**\n * Union of all `data-*` attribute names used on grid elements.\n * Use `GridDataAttrs` to access individual values by key.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport type GridDataAttr = (typeof GridDataAttrs)[keyof typeof GridDataAttrs];\n\n/**\n * Union of all CSS custom property names (`--tbw-*`) available for theming.\n * Use `GridCSSVars` to access individual values by key.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport type GridCSSVar = (typeof GridCSSVars)[keyof typeof GridCSSVars];\n","// Centralized template expression evaluation & sanitization utilities.\n// Responsible for safely interpolating {{ }} expressions while blocking\n// access to dangerous globals / reflective capabilities.\nimport type { CompiledViewFunction, EvalContext } from '../types';\n\n// #region Constants\nconst EXPR_RE = /{{\\s*([^}]+)\\s*}}/g;\nconst EMPTY_SENTINEL = '__DG_EMPTY__';\nconst SAFE_EXPR = /^[\\w$. '?+\\-*/%:()!<>=,&|]+$/;\n\n// Forbidden identifiers built at runtime to avoid static analysis scanners\n// from flagging string literals (e.g. socket.dev \"network access\" / \"uses eval\").\n// Stored as reversed, pipe-delimited tokens — reversed back when constructing the regex.\nconst _F =\n '__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles'\n .split('|')\n .map((s) => s.split('').reverse().join(''));\nconst FORBIDDEN = new RegExp(`__(proto|defineGetter|defineSetter)|${_F.slice(3).join('|')}|this\\\\b`);\n// #endregion\n\n// #region HTML Sanitization\n\n/**\n * Escape a plain text string for safe insertion into HTML.\n * Converts special HTML characters to their entity equivalents.\n *\n * @param text - Plain text string to escape\n * @returns HTML-safe string\n */\nexport function escapeHtml(text: string): string {\n if (!text || typeof text !== 'string') return '';\n return text\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Tags that are considered dangerous and will be completely removed.\n * These can execute scripts, load external resources, or manipulate the page.\n */\nconst DANGEROUS_TAGS = new Set(\n 'script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing|math'.split(\n '|',\n ),\n);\n\n/**\n * Attributes that are considered dangerous - event handlers and data loading.\n */\nconst DANGEROUS_ATTR_PATTERN = /^on\\w+$/i;\n\n/**\n * Attributes that can contain URLs which might be javascript: or data: URIs.\n */\nconst URL_ATTRS = new Set('href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset'.split('|'));\n\n/**\n * Protocol patterns that are dangerous in URLs.\n */\nconst DANGEROUS_URL_PROTOCOL = /^\\s*(javascript|vbscript|data|blob):/i;\n\n/**\n * Sanitize an HTML string by removing dangerous tags and attributes.\n *\n * Prefer {@link setSanitizedHTML} wherever the result is destined for an\n * element: this function has to re-serialize the sanitized tree back to a\n * string, and the caller's `innerHTML =` then re-parses it. That\n * parse→serialize→parse round trip is the classic mutation-XSS vector, and it\n * costs a second parse. Use this overload only when a string is genuinely\n * required (e.g. the value is stored, compared, or handed to another API).\n *\n * @param html - Raw HTML string to sanitize\n * @returns Sanitized HTML string safe for innerHTML\n */\nexport function sanitizeHTML(html: string): string {\n if (!html || typeof html !== 'string') return '';\n\n // Fast path: if no HTML tags at all, return as-is (already safe)\n if (html.indexOf('<') === -1) return html;\n\n const template = document.createElement('template');\n template.innerHTML = html;\n\n sanitizeNode(template.content);\n\n return template.innerHTML;\n}\n\n/**\n * Parse and sanitize an HTML string into a detached {@link DocumentFragment}.\n *\n * This is the primitive {@link setSanitizedHTML} builds on, exposed for callers\n * that need to inspect or relocate the nodes before insertion.\n *\n * @param html - Raw HTML string to sanitize\n * @returns Fragment containing the sanitized nodes (empty for falsy input)\n */\nexport function sanitizeToFragment(html: string): DocumentFragment {\n const template = document.createElement('template');\n if (html && typeof html === 'string') {\n template.innerHTML = html;\n sanitizeNode(template.content);\n }\n return template.content;\n}\n\n/**\n * Replace an element's children with the sanitized parse of `html`.\n *\n * **This is the canonical sink for user-supplied markup** — cell/header/group\n * renderer string returns, `gridConfig.icons.*`, light-DOM tool panel fallback\n * content, and any new extension point that turns a user string into markup.\n * `textContent` is wrong here (it renders SVG icon strings as literal text) and\n * raw `innerHTML` is wrong (it is an XSS sink).\n *\n * Nodes are moved from the parse fragment rather than re-serialized, so the\n * sanitized tree is exactly what lands in the document.\n *\n * @param el - Element whose children are replaced\n * @param html - Raw HTML string to sanitize and insert\n */\nexport function setSanitizedHTML(el: Element, html: string): void {\n if (!html || typeof html !== 'string') {\n el.replaceChildren();\n return;\n }\n // Nothing for the parser to do: no markup and no entities to decode.\n if (html.indexOf('<') === -1 && html.indexOf('&') === -1) {\n el.textContent = html;\n return;\n }\n el.replaceChildren(sanitizeToFragment(html));\n}\n\n/**\n * Recursively sanitize a DOM node tree.\n */\nfunction sanitizeNode(root: DocumentFragment | Element): void {\n const toRemove: Element[] = [];\n\n // Use querySelectorAll to find all elements, then filter\n const elements = root.querySelectorAll('*');\n\n for (const el of elements) {\n const tagName = el.tagName.toLowerCase();\n\n // Check if tag is dangerous\n if (DANGEROUS_TAGS.has(tagName)) {\n toRemove.push(el);\n continue;\n }\n\n // SVG elements need special handling - they can contain script-like behavior\n if (tagName === 'svg' || el.namespaceURI === 'http://www.w3.org/2000/svg') {\n // Remove entire SVG if it has any suspicious attributes\n const hasDangerousContent = Array.from(el.attributes).some(\n (attr) => DANGEROUS_ATTR_PATTERN.test(attr.name) || attr.name === 'href' || attr.name === 'xlink:href',\n );\n if (hasDangerousContent) {\n toRemove.push(el);\n continue;\n }\n }\n\n // Check and remove dangerous attributes\n const attrsToRemove: string[] = [];\n for (const attr of el.attributes) {\n const attrName = attr.name.toLowerCase();\n\n // Event handlers (onclick, onerror, onload, etc.)\n if (DANGEROUS_ATTR_PATTERN.test(attrName)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // `is=` upgrades a plain tag into a registered customized built-in, so it\n // can smuggle behaviour past the tag-name check above.\n if (attrName === 'is') {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // URL attributes with dangerous protocols\n if (URL_ATTRS.has(attrName) && DANGEROUS_URL_PROTOCOL.test(attr.value)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // style attribute can contain expressions (IE) or url() with javascript:\n if (attrName === 'style' && /expression\\s*\\(|javascript:|behavior\\s*:/i.test(attr.value)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n }\n\n attrsToRemove.forEach((name) => el.removeAttribute(name));\n }\n\n // Remove dangerous elements (do this after iteration to avoid modifying during traversal)\n toRemove.forEach((el) => el.remove());\n}\n\n// #endregion\n\n// #region Template Evaluation\n\n// #region Safe Expression Evaluator\n// A minimal recursive-descent evaluator for the token set allowed by SAFE_EXPR.\n// Replaces `new Function()` to avoid dynamic code execution warnings from\n// static analysis tools (socket.dev, npm audit) while maintaining identical\n// functionality for expressions that pass the allowlist guards.\n//\n// Supported grammar (matching SAFE_EXPR = /^[\\w$. '?+\\-*/%:()!<>=,&|]+$/):\n// ternary → logicalOr ('?' ternary ':' ternary)?\n// logicalOr → logicalAnd ('||' logicalAnd)*\n// logicalAnd → equality ('&&' equality)*\n// equality → comparison (('==' | '!=' | '===' | '!==') comparison)*\n// comparison → additive (('<' | '>' | '<=' | '>=') additive)*\n// additive → multiplicative (('+' | '-') multiplicative)*\n// multiplicative → unary (('*' | '/' | '%') unary)*\n// unary → '!' unary | primary\n// primary → NUMBER | STRING | IDENT ('.' IDENT)? | '(' ternary ')'\n\ntype Token =\n { type: 'num'; v: number } | { type: 'str'; v: string } | { type: 'id'; v: string } | { type: 'op'; v: string };\n\nfunction tokenize(expr: string): Token[] | null {\n const tokens: Token[] = [];\n let i = 0;\n while (i < expr.length) {\n const ch = expr[i];\n if (ch === ' ') {\n i++;\n continue;\n }\n\n // Numbers\n if ((ch >= '0' && ch <= '9') || (ch === '.' && i + 1 < expr.length && expr[i + 1] >= '0' && expr[i + 1] <= '9')) {\n const start = i;\n while (i < expr.length && ((expr[i] >= '0' && expr[i] <= '9') || expr[i] === '.')) i++;\n tokens.push({ type: 'num', v: Number(expr.slice(start, i)) });\n continue;\n }\n\n // String literals (single-quoted only, per SAFE_EXPR)\n if (ch === \"'\") {\n let s = '';\n i++; // skip opening quote\n while (i < expr.length && expr[i] !== \"'\") s += expr[i++];\n if (i >= expr.length) return null; // unterminated\n i++; // skip closing quote\n tokens.push({ type: 'str', v: s });\n continue;\n }\n\n // Identifiers (value, row, row.field)\n if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch === '_' || ch === '$') {\n const start = i;\n while (i < expr.length && /[\\w$.]/.test(expr[i])) i++;\n tokens.push({ type: 'id', v: expr.slice(start, i) });\n continue;\n }\n\n // Multi-char operators\n if (i + 2 < expr.length) {\n const tri = expr.slice(i, i + 3);\n if (tri === '===' || tri === '!==') {\n tokens.push({ type: 'op', v: tri });\n i += 3;\n continue;\n }\n }\n if (i + 1 < expr.length) {\n const bi = expr.slice(i, i + 2);\n if (bi === '==' || bi === '!=' || bi === '<=' || bi === '>=' || bi === '&&' || bi === '||') {\n tokens.push({ type: 'op', v: bi });\n i += 2;\n continue;\n }\n }\n\n // Single-char operators\n if ('+-*/%<>!?:(),'.includes(ch)) {\n tokens.push({ type: 'op', v: ch });\n i++;\n continue;\n }\n\n return null; // unexpected character\n }\n return tokens;\n}\n\nfunction safeEval(expr: string, ctx: EvalContext): unknown {\n const toks = tokenize(expr);\n if (!toks) return undefined;\n const tokens: Token[] = toks;\n let pos = 0;\n\n function peek(): Token | undefined {\n return tokens[pos];\n }\n function advance(): Token {\n return tokens[pos++];\n }\n function match(type: string, val?: string): boolean {\n const t = peek();\n if (!t) return false;\n if (t.type !== type) return false;\n if (val !== undefined && t.v !== val) return false;\n return true;\n }\n\n function resolveId(name: string): unknown {\n if (name === 'value') return ctx.value;\n if (name.startsWith('row.')) {\n const key = name.slice(4);\n return ctx.row ? ctx.row[key] : undefined;\n }\n if (name.startsWith('typeDefault.')) {\n const key = name.slice('typeDefault.'.length);\n return ctx.typeDefault ? ctx.typeDefault[key] : undefined;\n }\n // bare 'row' reference\n if (name === 'row') return ctx.row;\n if (name === 'typeDefault') return ctx.typeDefault;\n return undefined;\n }\n\n function parseTernary(): unknown {\n const result = parseLogicalOr();\n if (match('op', '?')) {\n advance(); // consume '?'\n const consequent = parseTernary();\n if (!match('op', ':')) return undefined;\n advance(); // consume ':'\n const alternate = parseTernary();\n return result ? consequent : alternate;\n }\n return result;\n }\n\n function parseLogicalOr(): unknown {\n let left = parseLogicalAnd();\n while (match('op', '||')) {\n advance();\n left = left || parseLogicalAnd();\n }\n return left;\n }\n\n function parseLogicalAnd(): unknown {\n let left = parseEquality();\n while (match('op', '&&')) {\n advance();\n left = left && parseEquality();\n }\n return left;\n }\n\n function parseEquality(): unknown {\n let left = parseComparison();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '===') {\n advance();\n left = left === parseComparison();\n } else if (t.v === '!==') {\n advance();\n left = left !== parseComparison();\n } else if (t.v === '==') {\n advance();\n left = left == parseComparison();\n } else if (t.v === '!=') {\n advance();\n left = left != parseComparison();\n } else break;\n }\n return left;\n }\n\n function parseComparison(): unknown {\n let left = parseAdditive();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '<') {\n advance();\n left = (left as number) < (parseAdditive() as number);\n } else if (t.v === '>') {\n advance();\n left = (left as number) > (parseAdditive() as number);\n } else if (t.v === '<=') {\n advance();\n left = (left as number) <= (parseAdditive() as number);\n } else if (t.v === '>=') {\n advance();\n left = (left as number) >= (parseAdditive() as number);\n } else break;\n }\n return left;\n }\n\n function parseAdditive(): unknown {\n let left = parseMultiplicative();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '+') {\n advance();\n left = (left as number) + (parseMultiplicative() as number);\n } else if (t.v === '-') {\n advance();\n left = (left as number) - (parseMultiplicative() as number);\n } else break;\n }\n return left;\n }\n\n function parseMultiplicative(): unknown {\n let left = parseUnary();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '*') {\n advance();\n left = (left as number) * (parseUnary() as number);\n } else if (t.v === '/') {\n advance();\n left = (left as number) / (parseUnary() as number);\n } else if (t.v === '%') {\n advance();\n left = (left as number) % (parseUnary() as number);\n } else break;\n }\n return left;\n }\n\n function parseUnary(): unknown {\n if (match('op', '!')) {\n advance();\n return !parseUnary();\n }\n return parsePrimary();\n }\n\n function parsePrimary(): unknown {\n const t = peek();\n if (!t) return undefined;\n if (t.type === 'num') {\n advance();\n return t.v;\n }\n if (t.type === 'str') {\n advance();\n return t.v;\n }\n if (t.type === 'id') {\n advance();\n return resolveId(t.v as string);\n }\n if (t.type === 'op' && t.v === '(') {\n advance(); // consume '('\n const result = parseTernary();\n if (match('op', ')')) advance(); // consume ')'\n return result;\n }\n // Unary minus for negative numbers\n if (t.type === 'op' && t.v === '-') {\n advance();\n return -(parsePrimary() as number);\n }\n return undefined;\n }\n\n const result = parseTernary();\n // Ensure all tokens were consumed\n if (pos < tokens.length) return undefined;\n return result;\n}\n// #endregion\n\nexport function evalTemplateString(raw: string, ctx: EvalContext): string {\n if (!raw || raw.indexOf('{{') === -1) return raw; // fast path (no expressions)\n const parts: { expr: string; result: string }[] = [];\n const evaluated = raw.replace(EXPR_RE, (_m, expr) => {\n const res = evalSingle(expr, ctx);\n parts.push({ expr: expr.trim(), result: res });\n // The template markup is author-controlled; the interpolated data is not.\n // Escaping here stops row data from injecting elements or breaking out of\n // an attribute (sanitizeHTML downstream only strips *dangerous* markup).\n return res === EMPTY_SENTINEL ? res : escapeHtml(res);\n });\n const finalStr = postProcess(evaluated);\n // If every part evaluated to EMPTY_SENTINEL we treat this as intentionally blank.\n // If any expression was blocked due to forbidden token (EMPTY_SENTINEL) we *still* only output ''\n // but do not escalate to BLOCKED_SENTINEL unless the original contained explicit forbidden tokens.\n const allEmpty = parts.length && parts.every((p) => p.result === '' || p.result === EMPTY_SENTINEL);\n const hadForbidden = REFLECTIVE_RE.test(raw);\n if (hadForbidden || allEmpty) return '';\n return finalStr;\n}\n\nfunction evalSingle(expr: string, ctx: EvalContext): string {\n expr = (expr || '').trim();\n if (!expr) return EMPTY_SENTINEL;\n if (REFLECTIVE_RE.test(expr)) return EMPTY_SENTINEL;\n if (expr === 'value') return ctx.value == null ? EMPTY_SENTINEL : String(ctx.value);\n if (expr.startsWith('row.') && !/[()?]/.test(expr) && !expr.includes(':')) {\n const key = expr.slice(4);\n const v = ctx.row ? ctx.row[key] : undefined;\n return v == null ? EMPTY_SENTINEL : String(v);\n }\n if (expr.startsWith('typeDefault.') && !/[()?]/.test(expr) && !expr.includes(':')) {\n const key = expr.slice('typeDefault.'.length);\n const v = ctx.typeDefault ? ctx.typeDefault[key] : undefined;\n return v == null ? EMPTY_SENTINEL : String(v);\n }\n if (expr.length > 80) return EMPTY_SENTINEL;\n if (!SAFE_EXPR.test(expr) || FORBIDDEN.test(expr)) return EMPTY_SENTINEL;\n const dotChain = expr.match(/\\./g);\n if (dotChain && dotChain.length > 1) return EMPTY_SENTINEL;\n try {\n const out = safeEval(expr, ctx);\n const str = out == null ? '' : String(out);\n if (REFLECTIVE_RE.test(str)) return EMPTY_SENTINEL;\n return str || EMPTY_SENTINEL;\n } catch {\n return EMPTY_SENTINEL;\n }\n}\n// #endregion\n\n// #region Cell Scrubbing\n/** Pattern matching reflective/introspective APIs that must be stripped from output. */\nconst REFLECTIVE_RE = /Reflect|Proxy|ownKeys/;\n\nfunction postProcess(s: string): string {\n if (!s) return s;\n return s.replace(new RegExp(EMPTY_SENTINEL, 'g'), '').replace(/Reflect\\.[^<>{}\\s]+|\\bProxy\\b|ownKeys\\([^)]*\\)/g, '');\n}\n\nexport function finalCellScrub(cell: HTMLElement): void {\n if (!REFLECTIVE_RE.test(cell.textContent || '')) return;\n // First pass: clear only text nodes containing forbidden tokens\n for (const n of cell.childNodes) {\n if (n.nodeType === Node.TEXT_NODE && REFLECTIVE_RE.test(n.textContent || '')) n.textContent = '';\n }\n // If forbidden tokens persist in element nodes, nuke everything\n if (REFLECTIVE_RE.test(cell.textContent || '')) {\n cell.textContent = '';\n }\n}\n// #endregion\n\n// #region Template Compilation\nexport function compileTemplate(raw: string) {\n if (REFLECTIVE_RE.test(raw)) {\n const fn = (() => '') as CompiledViewFunction;\n fn.__blocked = true;\n return fn;\n }\n const fn = ((ctx: EvalContext) => evalTemplateString(raw, ctx)) as CompiledViewFunction;\n fn.__blocked = false;\n return fn;\n}\n// #endregion\n","/**\n * Loading State Module\n *\n * Handles loading overlays, row loading, and cell loading states.\n * Provides DOM manipulation helpers for loading indicators.\n *\n * @module internal/loading\n */\n\nimport type { FrameworkAdapter, GridConfig, LoadingContext, RowElementInternal } from '../types';\nimport { setSanitizedHTML } from './sanitize';\n\n/**\n * Create the default spinner element.\n * @param size - 'large' for grid overlay, 'small' for row/cell\n */\nexport function createDefaultSpinner(size: 'large' | 'small'): HTMLElement {\n const spinner = document.createElement('div');\n spinner.className = `tbw-spinner tbw-spinner--${size}`;\n spinner.setAttribute('role', 'progressbar');\n spinner.setAttribute('aria-label', 'Loading');\n return spinner;\n}\n\n/**\n * Create loading content using custom renderer or default spinner.\n *\n * Strings returned by a custom renderer are passed through `setSanitizedHTML()`\n * — mirroring the cell, header and empty-state render paths — so a message\n * interpolating server data (e.g. `Loading ${dataset.name}…`) is not an XSS\n * sink.\n *\n * @param size - 'large' for grid overlay, 'small' for row/cell\n * @param renderer - Optional custom loading renderer from config\n */\nexport function createLoadingContent(size: 'large' | 'small', renderer?: GridConfig['loadingRenderer']): HTMLElement {\n if (renderer) {\n const context: LoadingContext = { size };\n const result = renderer(context);\n if (typeof result === 'string') {\n const wrapper = document.createElement('div');\n setSanitizedHTML(wrapper, result);\n return wrapper;\n }\n return result;\n }\n\n return createDefaultSpinner(size);\n}\n\n/**\n * Create or update the loading overlay element.\n * @param renderer - Optional custom loading renderer from config\n */\nexport function createLoadingOverlay(renderer?: GridConfig['loadingRenderer']): HTMLElement {\n const overlay = document.createElement('div');\n overlay.className = 'tbw-loading-overlay';\n overlay.setAttribute('role', 'status');\n overlay.setAttribute('aria-live', 'polite');\n overlay.appendChild(createLoadingContent('large', renderer));\n return overlay;\n}\n\n/**\n * Show the loading overlay on the grid root element.\n * @param gridRoot - The .tbw-grid-root element\n * @param overlayEl - The overlay element (will be cached by caller)\n */\nexport function showLoadingOverlay(gridRoot: Element, overlayEl: HTMLElement): void {\n gridRoot.appendChild(overlayEl);\n}\n\n/**\n * Hide the loading overlay.\n * @param overlayEl - The overlay element to remove\n */\nexport function hideLoadingOverlay(overlayEl: HTMLElement | undefined): void {\n overlayEl?.remove();\n}\n\n/** Remove a cell's owned loading overlay and release adapter-managed content. */\nexport function removeCellLoadingOverlay(cellEl: HTMLElement, adapter?: Pick<FrameworkAdapter, 'unmount'>): void {\n if (!cellEl.firstElementChild) return;\n const overlay = cellEl.querySelector<HTMLElement>(':scope > .tbw-cell-loading-overlay');\n if (!overlay) return;\n adapter?.unmount?.(overlay);\n overlay.remove();\n}\n\n/**\n * Move a cell's owned loading overlay in front of the cell while its content is rewritten,\n * so the still-active loader survives adapter release and content replacement. The caller\n * appends it back. The overlay stays connected because React prunes detached portal containers.\n */\nexport function parkCellLoadingOverlay(cellEl: HTMLElement): HTMLElement | null {\n if (!cellEl.firstElementChild) return null;\n const overlay = cellEl.querySelector<HTMLElement>(':scope > .tbw-cell-loading-overlay');\n if (!overlay) return null;\n const parent = cellEl.parentElement;\n if (parent) parent.insertBefore(overlay, cellEl);\n else overlay.remove();\n return overlay;\n}\n\n/** Remove a row's owned loading overlay and release adapter-managed content. */\nexport function removeRowLoadingOverlay(rowEl: HTMLElement, adapter?: Pick<FrameworkAdapter, 'unmount'>): void {\n if (!rowEl.firstElementChild) return;\n const overlay = rowEl.querySelector<HTMLElement>(':scope > .tbw-row-loading-overlay');\n if (!overlay) return;\n adapter?.unmount?.(overlay);\n overlay.remove();\n}\n\n/**\n * Update a row element's loading state.\n * Uses real DOM elements instead of ::before/::after pseudo-elements\n * because the selection plugin already uses ::after on rows for border styling.\n * @param rowEl - The row element\n * @param loading - Whether the row is loading\n * @param renderer - Optional `gridConfig.loadingRenderer`; called with `{ size: 'small' }`\n * in place of the default spinner. Only invoked when the overlay is created.\n * @param adapter - Framework adapter used to release renderer-owned content on removal.\n */\nexport function setRowLoadingState(\n rowEl: HTMLElement,\n loading: boolean,\n renderer?: GridConfig['loadingRenderer'],\n adapter?: Pick<FrameworkAdapter, 'unmount'>,\n): void {\n if (loading) {\n rowEl.classList.add('tbw-row-loading');\n rowEl.setAttribute('aria-busy', 'true');\n\n // Create overlay + spinner DOM elements if not already present.\n // Direct children only — a nested grid's row overlay must not be mistaken for this row's.\n if (!rowEl.querySelector(':scope > .tbw-row-loading-overlay')) {\n const overlay = document.createElement('div');\n overlay.className = 'tbw-row-loading-overlay';\n overlay.setAttribute('aria-hidden', 'true');\n\n if (renderer) {\n overlay.appendChild(createLoadingContent('small', renderer));\n } else {\n const spinner = document.createElement('div');\n spinner.className = 'tbw-row-loading-spinner';\n overlay.appendChild(spinner);\n }\n\n rowEl.appendChild(overlay);\n }\n } else {\n rowEl.classList.remove('tbw-row-loading');\n rowEl.removeAttribute('aria-busy');\n\n // Remove overlay + spinner DOM elements\n removeRowLoadingOverlay(rowEl, adapter);\n }\n}\n\n/**\n * Update a cell element's loading state.\n * @param cellEl - The cell element\n * @param loading - Whether the cell is loading\n * @param renderer - Optional `gridConfig.loadingRenderer`; called with `{ size: 'small' }`\n * @param adapter - Framework adapter used to release renderer-owned content on removal.\n */\nexport function setCellLoadingState(\n cellEl: HTMLElement,\n loading: boolean,\n renderer?: GridConfig['loadingRenderer'],\n adapter?: Pick<FrameworkAdapter, 'unmount'>,\n): void {\n if (loading) {\n cellEl.classList.add('tbw-cell-loading');\n cellEl.setAttribute('aria-busy', 'true');\n\n // Breadcrumb so the render hot path can skip the per-cell scan on the\n // overwhelming majority of rows. Conservative: only ever set here, so it can\n // read stale-true after the last loading cell clears (costs one extra scan).\n const rowEl = cellEl.parentElement as RowElementInternal | null;\n if (rowEl) rowEl.__hasCellLoading = true;\n\n if (renderer) {\n cellEl.classList.add('tbw-cell-loading-custom');\n if (!cellEl.querySelector(':scope > .tbw-cell-loading-overlay')) {\n const overlay = document.createElement('div');\n overlay.className = 'tbw-cell-loading-overlay';\n overlay.setAttribute('aria-hidden', 'true');\n overlay.appendChild(createLoadingContent('small', renderer));\n cellEl.appendChild(overlay);\n }\n } else {\n cellEl.classList.remove('tbw-cell-loading-custom');\n removeCellLoadingOverlay(cellEl, adapter);\n }\n } else {\n cellEl.classList.remove('tbw-cell-loading');\n cellEl.classList.remove('tbw-cell-loading-custom');\n cellEl.removeAttribute('aria-busy');\n removeCellLoadingOverlay(cellEl, adapter);\n }\n}\n","/**\n * Hierarchy Engine\n *\n * Pure row-model builder shared by the HierarchyPlugin and its contributors.\n */\n\nimport type { HierarchyContributor, HierarchyNode, HierarchyRowMeta } from './types';\n\n/** Copy-on-write: contributors may hold on to node objects, so a substituted node is a new object. */\nfunction substituteRows(nodes: HierarchyNode[], substitute: (row: unknown) => unknown): HierarchyNode[] {\n let out: HierarchyNode[] | undefined;\n for (let i = 0; i < nodes.length; i++) {\n const row = substitute(nodes[i].row);\n if (row === nodes[i].row) continue;\n out ??= nodes.slice();\n out[i] = { ...nodes[i], row };\n }\n return out ?? nodes;\n}\n\n/** Copy-on-write substitution of a plain row list (the roots, before any node exists). */\nfunction substituteValues(rows: readonly unknown[], substitute: (row: unknown) => unknown): readonly unknown[] {\n let out: unknown[] | undefined;\n for (let i = 0; i < rows.length; i++) {\n const row = substitute(rows[i]);\n if (row === rows[i]) continue;\n out ??= rows.slice();\n out[i] = row;\n }\n return out ?? rows;\n}\n\n/**\n * Build the flat row list for `rows` from every contributor's sibling-list\n * transforms, recording each emitted row's ARIA position in `meta`.\n *\n * Contributors whose `beginHierarchy` returns `false` sit out the rebuild.\n * With no active contributor the rows pass through unchanged. When every\n * active contributor's `endHierarchy` returns `false`, no position is kept in `meta`.\n *\n * This is what `HierarchyPlugin.process()` runs for all attached contributors.\n * Call it directly to run a contributor without a grid — e.g. as the\n * `processRows` fallback when no HierarchyPlugin is attached, or in unit tests.\n *\n * @example\n * ```ts\n * override processRows(rows: readonly unknown[]): unknown[] {\n * const hierarchy = this.grid?.getPluginByName('hierarchy');\n * return hierarchy ? hierarchy.process(rows, this) : buildHierarchy(rows, [this]);\n * }\n * ```\n *\n * @param rows - The root rows.\n * @param contributors - Contributors to run, in `processRows` hook order.\n * @param meta - Receives each emitted row's position. Pass a fresh map per rebuild.\n * @param substitute - Optional. Maps a row to the object to use in its place, at\n * every nesting level, before any contributor sees it. Return the row itself to\n * keep it. `HierarchyPlugin` uses this to keep a row being edited when the data\n * is replaced with new objects. Added in 3.10.2.\n * @returns The flattened rows, in render order.\n * @since 3.9.0\n */\nexport function buildHierarchy(\n rows: readonly unknown[],\n contributors: readonly HierarchyContributor[],\n meta: WeakMap<object, HierarchyRowMeta> = new WeakMap(),\n substitute?: (row: unknown) => unknown,\n): unknown[] {\n // Roots are substituted BEFORE activation: `beginHierarchy` decides from them whether\n // there is any structure (a pinned parent may be the only row with children).\n const roots = substitute ? substituteValues(rows, substitute) : rows;\n const active: HierarchyContributor[] = [];\n for (const stage of ['structure', 'transform'] as const) {\n for (const c of contributors) {\n if (c.hierarchyStage === stage && c.beginHierarchy(roots)) active.push(c);\n }\n }\n if (active.length === 0) return [...roots];\n\n const out: unknown[] = [];\n const process = (nodes: HierarchyNode[], parent: HierarchyNode | null, depth: number): HierarchyNode[] => {\n if (substitute && parent) nodes = substituteRows(nodes, substitute);\n const context = { parent: parent ? parent.row : null, parentKey: parent?.key ?? null, depth };\n for (const c of active) nodes = c.processSiblings(nodes, context);\n return nodes;\n };\n const emit = (nodes: HierarchyNode[], depth: number): void => {\n const setSize = nodes.length;\n for (let i = 0; i < setSize; i++) {\n const node = nodes[i];\n out.push(node.row);\n if (typeof node.row === 'object' && node.row !== null) {\n meta.set(node.row, { level: depth + 1, setSize, posInSet: i + 1 });\n }\n const children = node.children;\n if (node.expanded && children) {\n emit(node.shaped ? children : process(children, node, depth + 1), depth + 1);\n }\n }\n };\n\n const rootNodes: HierarchyNode[] = new Array(roots.length);\n for (let i = 0; i < roots.length; i++) rootNodes[i] = { row: roots[i] };\n emit(process(rootNodes, null, 0), 0);\n\n const positionOf = (row: unknown) => (typeof row === 'object' && row !== null ? meta.get(row) : undefined);\n let shaped = false;\n for (const c of active) if (c.endHierarchy(out, positionOf)) shaped = true;\n if (!shaped) {\n for (const row of out) if (typeof row === 'object' && row !== null) meta.delete(row);\n }\n return out;\n}\n","/**\n * Hierarchy Plugin\n *\n * Owns the hierarchical row model shared by structure-contributing plugins.\n */\n\nimport type { PluginManifest } from '../../core/plugin/base-plugin';\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { RowElementInternal } from '../../core/types';\nimport { buildHierarchy } from './hierarchy';\nimport type { HierarchyContributor, HierarchyRowMeta } from './types';\n\n/** Attribute write that skips the DOM mutation when the value is unchanged (per-frame hot path). */\nfunction setAttrIfChanged(el: Element, name: string, value: number): void {\n const next = String(value);\n if (el.getAttribute(name) !== next) el.setAttribute(name, next);\n}\n\nfunction isContributor(plugin: unknown): plugin is HierarchyContributor & BaseGridPlugin {\n return typeof (plugin as Partial<HierarchyContributor>).processSiblings === 'function';\n}\n\nfunction processRowsPriority(plugin: BaseGridPlugin): number {\n return (plugin.constructor as typeof BaseGridPlugin).manifest?.hookPriority?.processRows ?? 0;\n}\n\n/**\n * Hierarchy Plugin for tbw-grid\n *\n * Builds one hierarchical row model from every attached structure contributor\n * — {@link https://toolboxjs.com/grid/plugins/tree/ | TreePlugin} discovers\n * child rows, {@link https://toolboxjs.com/grid/plugins/grouping-rows/ | GroupingRowsPlugin}\n * groups sibling lists — and announces each row's position with the WAI-ARIA\n * treegrid pattern (`aria-level` / `aria-setsize` / `aria-posinset`).\n *\n * Contributors know nothing about each other, so they compose: a grid with\n * both Tree and GroupingRows groups the children of every tree level.\n *\n * You never need to add this plugin yourself — TreePlugin and\n * GroupingRowsPlugin declare it as a dependency and the grid attaches it\n * automatically. It has no configuration.\n *\n * @example Group the children of every tree node\n * ```ts\n * import { TreePlugin } from '@toolbox-web/grid/plugins/tree';\n * import { GroupingRowsPlugin } from '@toolbox-web/grid/plugins/grouping-rows';\n *\n * grid.gridConfig = {\n * plugins: [\n * new TreePlugin({ childrenField: 'children' }),\n * new GroupingRowsPlugin({\n * // Leave the root level ungrouped, group every child level by kind\n * groupOn: (row, { depth }) => (depth > 0 ? row.kind : null),\n * }),\n * ],\n * };\n * ```\n *\n * @since 3.9.0\n */\nexport class HierarchyPlugin extends BaseGridPlugin {\n /** @internal */\n static override readonly manifest: PluginManifest = {\n modifiesRowStructure: true,\n };\n\n /** @internal */\n readonly name = 'hierarchy';\n\n #meta = new WeakMap<object, HierarchyRowMeta>();\n\n /** @internal */\n override detach(): void {\n // Restore the default `role=\"grid\"` (template default in `core/internal/dom-builder.ts`).\n this.gridElement?.querySelector('.rows-body')?.setAttribute('role', 'grid');\n this.#meta = new WeakMap();\n }\n\n /**\n * Build the row model for a contributor's `processRows` hook.\n *\n * Every contributor forwards its hook here; only the one that runs last in\n * the `processRows` pipeline builds the model (for all contributors at\n * once) — the earlier ones pass their rows through untouched.\n *\n * @example\n * ```ts\n * override processRows(rows: readonly unknown[]): unknown[] {\n * return this.grid.getPluginByName('hierarchy')?.process(rows, this) ?? [...rows];\n * }\n * ```\n *\n * @since 3.9.0\n */\n process(rows: readonly unknown[], caller: HierarchyContributor): unknown[] {\n const contributors = this.#contributors();\n if (!contributors.includes(caller as HierarchyContributor & BaseGridPlugin)) {\n this.#meta = new WeakMap();\n return buildHierarchy(rows, [caller], this.#meta, this.#rowSubstitute());\n }\n if (contributors[contributors.length - 1] !== caller) return rows as unknown[];\n this.#meta = new WeakMap();\n return buildHierarchy(rows, contributors, this.#meta, this.#rowSubstitute());\n }\n\n /**\n * Rows other plugins pin by ID for this rebuild (`getRowSubstitutes` query) — e.g.\n * EditingPlugin's in-progress row, so an edit survives `rows` being replaced with\n * new objects even when the row is nested (#570). `undefined` when nothing is pinned.\n */\n #rowSubstitute(): ((row: unknown) => unknown) | undefined {\n const responses = this.grid?.query?.<ReadonlyMap<string, unknown> | undefined>('getRowSubstitutes', null) ?? [];\n let pinned: Map<string, unknown> | undefined;\n for (const map of responses) {\n if (!map?.size) continue;\n pinned ??= new Map();\n for (const [id, row] of map) pinned.set(id, row);\n }\n if (!pinned) return undefined;\n const grid = this.grid;\n return (row) => {\n if (typeof row !== 'object' || row === null) return row;\n let id: string | undefined;\n try {\n id = grid.getRowId(row);\n } catch {\n return row;\n }\n return pinned.has(id) ? pinned.get(id) : row;\n };\n }\n\n /**\n * Hierarchy position of a row in the current row model, or `undefined` when\n * the row is not rendered (e.g. collapsed under a parent).\n *\n * @example\n * ```ts\n * const meta = grid.getPluginByName('hierarchy')?.getRowMeta(grid.rows[0]);\n * console.log(meta?.level, meta?.posInSet, meta?.setSize);\n * ```\n *\n * @since 3.9.0\n */\n getRowMeta(row: unknown): HierarchyRowMeta | undefined {\n return typeof row === 'object' && row !== null ? this.#meta.get(row) : undefined;\n }\n\n /** @internal */\n override afterRender(): void {\n this.#applyAria();\n }\n\n /** @internal */\n override onScrollRender(): void {\n this.#applyAria();\n }\n\n /** Attached contributors, in `processRows` hook order. */\n #contributors(): Array<HierarchyContributor & BaseGridPlugin> {\n const plugins = (this.grid?._pluginManager?.getPlugins?.() ?? []) as readonly BaseGridPlugin[];\n return plugins.filter(isContributor).sort((a, b) => processRowsPriority(a) - processRowsPriority(b));\n }\n\n #applyAria(): void {\n if (this.#contributors().length === 0) return;\n const body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n let hierarchical = false;\n for (const rowEl of body.querySelectorAll('.data-grid-row')) {\n const meta = this.getRowMeta((rowEl as RowElementInternal).__rowDataRef);\n if (!meta) {\n // Pooled row elements may carry a position from a previous row model.\n rowEl.removeAttribute('aria-level');\n rowEl.removeAttribute('aria-setsize');\n rowEl.removeAttribute('aria-posinset');\n continue;\n }\n hierarchical = true;\n setAttrIfChanged(rowEl, 'aria-level', meta.level);\n setAttrIfChanged(rowEl, 'aria-setsize', meta.setSize);\n setAttrIfChanged(rowEl, 'aria-posinset', meta.posInSet);\n }\n\n // `treegrid` only while the model has hierarchy, so per-row level/setsize/posinset are valid in context.\n const role = hierarchical ? 'treegrid' : 'grid';\n const rowsBody = this.gridElement?.querySelector('.rows-body');\n if (rowsBody && rowsBody.getAttribute('role') !== role) rowsBody.setAttribute('role', role);\n }\n}\n","/**\n * Core Tree Data Logic\n *\n * Pure functions for tree flattening, expansion, and traversal.\n */\n\nimport type { FlattenedTreeRow, TreeConfig, TreeRow } from './types';\n\n/**\n * Generates a unique key for a row.\n * Uses row.id if available, otherwise generates from path.\n */\nexport function generateRowKey(row: TreeRow, index: number, parentKey: string | null): string {\n if (row.id !== undefined) return String(row.id);\n return parentKey ? `${parentKey}-${index}` : String(index);\n}\n\n/**\n * Flattens a hierarchical tree into a flat array of rows with metadata.\n * Only includes children of expanded nodes.\n */\nexport function flattenTree(\n rows: readonly TreeRow[],\n config: TreeConfig,\n expandedKeys: Set<string>,\n parentKey: string | null = null,\n depth = 0,\n): FlattenedTreeRow[] {\n const childrenField = config.childrenField ?? 'children';\n const result: FlattenedTreeRow[] = [];\n appendFlattenedRows(rows, childrenField, expandedKeys, parentKey, depth, result);\n return result;\n}\n\nfunction appendFlattenedRows(\n rows: readonly TreeRow[],\n childrenField: string,\n expandedKeys: Set<string>,\n parentKey: string | null,\n depth: number,\n result: FlattenedTreeRow[],\n): void {\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const key = generateRowKey(row, i, parentKey);\n const children = row[childrenField];\n const hasChildren = Array.isArray(children) && children.length > 0;\n const isExpanded = expandedKeys.has(key);\n\n result.push({\n key,\n data: row,\n depth,\n hasChildren,\n isExpanded,\n parentKey,\n posInSet: i + 1,\n setSize: rows.length,\n });\n\n // Recursively add children if expanded\n if (hasChildren && isExpanded) {\n appendFlattenedRows(children as TreeRow[], childrenField, expandedKeys, key, depth + 1, result);\n }\n }\n}\n\n/**\n * Toggles the expansion state of a row.\n * Returns a new Set with the toggled state.\n */\nexport function toggleExpand(expandedKeys: Set<string>, key: string): Set<string> {\n const newExpanded = new Set(expandedKeys);\n if (newExpanded.has(key)) {\n newExpanded.delete(key);\n } else {\n newExpanded.add(key);\n }\n return newExpanded;\n}\n\n/**\n * Expands all nodes in the tree.\n * Returns a Set of all parent row keys.\n */\nexport function expandAll(\n rows: readonly TreeRow[],\n config: TreeConfig,\n parentKey: string | null = null,\n depth = 0,\n): Set<string> {\n const childrenField = config.childrenField ?? 'children';\n const keys = new Set<string>();\n\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const key = generateRowKey(row, i, parentKey);\n const children = row[childrenField];\n\n if (Array.isArray(children) && children.length > 0) {\n keys.add(key);\n const childKeys = expandAll(children as TreeRow[], config, key, depth + 1);\n for (const k of childKeys) keys.add(k);\n }\n }\n\n return keys;\n}\n\n/**\n * Collapses all nodes.\n * Returns an empty Set.\n */\nexport function collapseAll(): Set<string> {\n return new Set();\n}\n\n/**\n * Gets all descendants of a node from the flattened row list.\n * Useful for operations that need to affect an entire subtree.\n */\nexport function getDescendants(flattenedRows: FlattenedTreeRow[], parentKey: string): FlattenedTreeRow[] {\n const descendants: FlattenedTreeRow[] = [];\n let collecting = false;\n let parentDepth = -1;\n\n for (const row of flattenedRows) {\n if (row.key === parentKey) {\n collecting = true;\n parentDepth = row.depth;\n continue;\n }\n\n if (collecting) {\n if (row.depth > parentDepth) {\n descendants.push(row);\n } else {\n break; // No longer a descendant\n }\n }\n }\n\n return descendants;\n}\n\n/**\n * Finds the path from root to a specific row key.\n * Returns an array of keys from root to the target (inclusive).\n */\nexport function getPathToKey(\n rows: readonly TreeRow[],\n targetKey: string,\n config: TreeConfig,\n parentKey: string | null = null,\n depth = 0,\n): string[] | null {\n const childrenField = config.childrenField ?? 'children';\n\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const key = generateRowKey(row, i, parentKey);\n\n if (key === targetKey) {\n return [key];\n }\n\n const children = row[childrenField];\n if (Array.isArray(children) && children.length > 0) {\n const childPath = getPathToKey(children as TreeRow[], targetKey, config, key, depth + 1);\n if (childPath) {\n return [key, ...childPath];\n }\n }\n }\n\n return null;\n}\n\n/**\n * Expands all ancestors of a specific row to make it visible.\n * Returns a new Set with the required keys added.\n */\nexport function expandToKey(\n rows: readonly TreeRow[],\n targetKey: string,\n config: TreeConfig,\n existingExpanded: Set<string>,\n): Set<string> {\n const path = getPathToKey(rows, targetKey, config);\n if (!path) return existingExpanded;\n\n const newExpanded = new Set(existingExpanded);\n // Add all keys except the last one (the target itself)\n for (let i = 0; i < path.length - 1; i++) {\n newExpanded.add(path[i]);\n }\n return newExpanded;\n}\n","/**\n * True when a keyboard event originates in a text-entry control — `<input>`, `<select>`,\n * `<textarea>` or a contenteditable element. Plugin key handlers (e.g. Space to toggle a tree\n * row) must defer to the control so the keystroke is typed rather than swallowed.\n *\n * Reads `composedPath()[0]` so controls inside an editor's open shadow root are recognised;\n * `event.target` is retargeted to the shadow host by the time the grid sees the event.\n * @internal\n */\nexport function isFormFieldKeyTarget(event: Event): boolean {\n const path = event.composedPath?.() ?? [];\n const target = path.length ? path[0] : event.target;\n if (!(target instanceof HTMLElement)) return false;\n const tag = target.tagName;\n return tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA' || target.isContentEditable;\n}\n","/**\n * Tree Viewport Mapping Utilities\n *\n * Pure functions for translating between flat viewport row indices and\n * top-level tree node indices. Used by the Tree plugin's\n * `datasource:viewport-mapping` query handler.\n */\n\nimport type { ViewportMappingResponse } from '../server-side/datasource-types';\n\n/**\n * Translate a range of rendered row indices to the range of root nodes that own them.\n *\n * @param rootOwners - Index-aligned with the grid's final row list (including rows other\n * contributors inserted, e.g. group headers): the 0-based ordinal of the root node each row\n * belongs to, or `-1` for rows rendered before the first root.\n * @param rootCount - Number of root nodes in the rendered rows.\n */\nexport function mapViewportToRoots(\n rootOwners: readonly number[],\n rootCount: number,\n viewportStart: number,\n viewportEnd: number,\n): ViewportMappingResponse {\n const last = rootOwners.length - 1;\n const ownerAt = (index: number) => Math.max(0, rootOwners[Math.max(0, Math.min(index, last))] ?? 0);\n return {\n startNode: ownerAt(viewportStart),\n endNode: ownerAt(viewportEnd) + 1, // exclusive\n totalLoadedNodes: rootCount,\n };\n}\n","/**\n * Tree Structure Auto-Detection\n *\n * Utilities for detecting hierarchical tree data structures.\n */\n\nimport type { TreeRow } from './types';\n\n/**\n * Detects if the data has a tree structure by checking for children arrays.\n *\n * @param rows - The candidate root rows\n * @param childrenField - Field holding the children array / lazy indicator\n * @param hasChildren - Optional {@link TreeConfig.hasChildren} predicate. When\n * supplied, a row it reports as a parent marks the data as a tree even if it\n * carries no `childrenField` at all — the purely lazy case where children are\n * only ever fetched through `loadChildren`.\n */\nexport function detectTreeStructure(\n rows: readonly TreeRow[],\n childrenField = 'children',\n hasChildren?: (row: TreeRow) => boolean,\n): boolean {\n if (!Array.isArray(rows) || rows.length === 0) return false;\n\n // Check if any row has children (embedded array or lazy indicator)\n for (const row of rows) {\n // Loading placeholders (ServerSide) hold no data; never pass them to `hasChildren`.\n if (!row || row.__loading === true) continue;\n const children = row[childrenField];\n // Embedded children: non-empty array\n if (Array.isArray(children) && children.length > 0) return true;\n // Lazy children: truthy non-array value (e.g. `true`, number > 0)\n if (children != null && !Array.isArray(children) && !!children) return true;\n // Predicate-only lazy children: no `childrenField` on the row at all.\n if (hasChildren?.(row)) return true;\n }\n\n return false;\n}\n\n/**\n * Attempts to infer the children field name from common patterns.\n * Returns the first field that contains an array with items.\n */\nexport function inferChildrenField(rows: readonly TreeRow[]): string | null {\n if (!Array.isArray(rows) || rows.length === 0) return null;\n\n const commonArrayFields = ['children', 'items', 'nodes', 'subRows', 'nested'];\n\n for (const row of rows) {\n if (!row || typeof row !== 'object') continue;\n\n for (const field of commonArrayFields) {\n const value = row[field];\n if (Array.isArray(value) && value.length > 0) {\n return field;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Calculates the maximum depth of the tree.\n * Useful for layout calculations and virtualization.\n */\nexport function getMaxDepth(rows: readonly TreeRow[], childrenField = 'children', currentDepth = 0): number {\n if (!Array.isArray(rows) || rows.length === 0) return currentDepth;\n\n let maxDepth = currentDepth;\n\n for (const row of rows) {\n if (!row) continue;\n const children = row[childrenField];\n if (Array.isArray(children) && children.length > 0) {\n const childDepth = getMaxDepth(children as TreeRow[], childrenField, currentDepth + 1);\n if (childDepth > maxDepth) {\n maxDepth = childDepth;\n }\n }\n }\n\n return maxDepth;\n}\n\n/**\n * Counts total nodes in the tree (including all descendants).\n */\nexport function countNodes(rows: readonly TreeRow[], childrenField = 'children'): number {\n if (!Array.isArray(rows)) return 0;\n\n let count = 0;\n for (const row of rows) {\n if (!row) continue;\n count++;\n const children = row[childrenField];\n if (Array.isArray(children)) {\n count += countNodes(children as TreeRow[], childrenField);\n }\n }\n\n return count;\n}\n","/**\n * Tree Plugin Styles\n *\n * Scoped to tbw-grid using CSS nesting for light DOM compatibility.\n */\n@layer tbw-plugins {\n tbw-grid {\n /* Expander column data cells - always first, borderless end edge */\n .cell[data-field='__tbw_expander'] {\n border-inline-end: none !important;\n padding: 0;\n display: flex;\n align-items: center;\n justify-content: flex-start;\n }\n\n /* Expander column header - completely hidden, next column spans both */\n .header-row .cell[data-field='__tbw_expander'] {\n display: none;\n }\n\n .header-row .cell[data-field='__tbw_expander'] + .cell {\n grid-column: 1 / 3;\n }\n\n /* Tree cell wrapper with depth-based indentation */\n .tree-cell-wrapper {\n display: inline-flex;\n align-items: center;\n /* Prevent baseline differences between tree-toggle (inline-flex) and\n tree-spacer (inline-block) from causing inconsistent row heights,\n which would trigger a rowHeight oscillation loop in virtualization. */\n vertical-align: middle;\n /* Override cell > * { overflow: hidden } which clips indented tree content */\n overflow: visible;\n /* Indent must be >= toggle icon width to keep leaf nodes aligned */\n padding-inline-start: calc(\n var(--tbw-tree-depth, 0) * var(--tbw-tree-indent-width, var(--tbw-tree-toggle-size, 1.25em))\n );\n }\n\n /* Tree expander cell with indentation */\n .tree-expander {\n display: flex;\n align-items: center;\n justify-content: flex-start;\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n }\n\n .tree-toggle {\n cursor: pointer;\n user-select: none;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n /* Explicit size ensures consistent spacing with tree-spacer */\n width: var(--tbw-tree-toggle-size, 1.25em);\n height: var(--tbw-tree-toggle-size, 1.25em);\n flex-shrink: 0;\n }\n\n .tree-toggle:hover {\n color: var(--tbw-tree-accent, var(--tbw-color-accent));\n }\n\n /* SC 2.5.8 Target Size (Minimum) applies to every pointer type, but a 24px\n box would widen every indentation level. The overlay grows the target\n instead of the box, so density is untouched. */\n .tree-toggle {\n position: relative;\n\n &::after {\n content: '';\n position: absolute;\n inset-block-start: 50%;\n inset-inline-start: 50%;\n translate: -50% -50%;\n inline-size: var(--tbw-touch-target-min, 24px);\n block-size: var(--tbw-touch-target-min, 24px);\n }\n }\n\n .tree-spacer {\n /* Must match tree-toggle width and height for alignment */\n width: var(--tbw-tree-toggle-size, 1.25em);\n height: var(--tbw-tree-toggle-size, 1.25em);\n display: inline-block;\n flex-shrink: 0;\n }\n\n /* The spacer occupies the toggle slot on leaf rows, so it must grow with the\n toggle — otherwise leaf rows sit narrower than expandable ones on touch. */\n @media (pointer: coarse) {\n .tree-toggle,\n .tree-spacer {\n min-width: var(--tbw-touch-target-min, 24px);\n min-height: var(--tbw-touch-target-min, 24px);\n }\n }\n\n /* Lazy-loading indicator — core's small spinner (`.tbw-spinner--small`)\n resized to the toggle slot so swapping toggle ↔ spinner doesn't reflow\n the row. Only the size token is overridden; all other spinner theming\n (`--tbw-spinner-color`, `--tbw-spinner-track-color`) still applies. */\n .tree-loading {\n --tbw-spinner-size: var(--tbw-tree-toggle-size, 1.25em);\n flex-shrink: 0;\n }\n\n /* Slide animation for child rows appearing */\n .data-grid-row.tbw-tree-slide-in {\n animation: tbw-tree-slide-in var(--tbw-animation-duration, 200ms) var(--tbw-animation-easing, ease-out) forwards;\n }\n\n /* Fade animation for child rows appearing */\n .data-grid-row.tbw-tree-fade-in {\n animation: tbw-tree-fade-in var(--tbw-animation-duration, 200ms) var(--tbw-animation-easing, ease-out) forwards;\n }\n }\n\n @keyframes tbw-tree-slide-in {\n from {\n opacity: 0;\n transform: translateX(-8px);\n }\n to {\n opacity: 1;\n transform: translateX(0);\n }\n }\n\n @keyframes tbw-tree-fade-in {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n }\n} /* End @layer tbw-plugins */\n","/**\n * Tree Data Plugin\n *\n * Enables hierarchical tree data with expand/collapse, sorting, and auto-detection.\n */\n\nimport { GridClasses } from '../../core/constants';\nimport { createDefaultSpinner } from '../../core/internal/loading';\nimport { setSanitizedHTML } from '../../core/internal/sanitize';\nimport { builtInSort } from '../../core/internal/sorting';\nimport type { GridElement } from '../../core/plugin/base-plugin';\nimport {\n BaseGridPlugin,\n CellClickEvent,\n HeaderClickEvent,\n type PluginManifest,\n type PluginQuery,\n} from '../../core/plugin/base-plugin';\nimport type { ColumnConfig, ColumnViewRenderer, RowElementInternal, SortHandler } from '../../core/types';\nimport type { HierarchyContributor, HierarchyNode, HierarchyRowMeta, HierarchySiblingContext } from '../hierarchy';\nimport { buildHierarchy, HierarchyPlugin } from '../hierarchy';\nimport type {\n DataSourceChildrenDetail,\n DataSourceDataDetail,\n DataSourceErrorDetail,\n FetchChildrenQuery,\n Subscribable,\n ViewportMappingQuery,\n} from '../server-side/datasource-types';\nimport { collapseAll, expandAll, expandToKey, toggleExpand } from './tree-data';\nimport { isFormFieldKeyTarget } from '../shared/form-field-target';\nimport { mapViewportToRoots } from './tree-datasource';\nimport { detectTreeStructure, inferChildrenField } from './tree-detect';\nimport styles from './tree.css?inline';\nimport type {\n ExpandCollapseAnimation,\n FlattenedTreeRow,\n TreeConfig,\n TreeExpandDetail,\n TreeLoadEndDetail,\n TreeLoadErrorDetail,\n TreeLoadStartDetail,\n TreeRow,\n} from './types';\n\n/** Narrow a `loadChildren` result to the Subscribable branch. */\nfunction isSubscribable<T>(value: Promise<T> | Subscribable<T>): value is Subscribable<T> {\n return typeof (value as Subscribable<T>).subscribe === 'function';\n}\n\n/**\n * Tree Data Plugin for tbw-grid\n *\n * Transforms your flat grid into a hierarchical tree view with expandable parent-child\n * relationships. Ideal for file explorers, organizational charts, nested categories,\n * or any data with a natural hierarchy.\n *\n * ## Installation\n *\n * ```ts\n * import { TreePlugin } from '@toolbox-web/grid/plugins/tree';\n * ```\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-tree-toggle-size` | `1.25em` | Toggle icon width |\n * | `--tbw-tree-indent-width` | `var(--tbw-tree-toggle-size)` | Indentation per level |\n * | `--tbw-tree-accent` | `var(--tbw-color-accent)` | Toggle icon hover color |\n * | `--tbw-animation-duration` | `200ms` | Expand/collapse animation duration |\n * | `--tbw-animation-easing` | `ease-out` | Animation curve |\n *\n * @example Basic Tree with Nested Children\n * ```ts\n * import { queryGrid } from '@toolbox-web/grid';\n * import { TreePlugin } from '@toolbox-web/grid/plugins/tree';\n *\n * const grid = queryGrid('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'type', header: 'Type' },\n * { field: 'size', header: 'Size' },\n * ],\n * plugins: [new TreePlugin({ childrenField: 'children', indentWidth: 24 })],\n * };\n * grid.rows = [\n * {\n * id: 1,\n * name: 'Documents',\n * type: 'folder',\n * children: [\n * { id: 2, name: 'Report.docx', type: 'file', size: '24 KB' },\n * ],\n * },\n * ];\n * ```\n *\n * @example Expanded by Default with Custom Animation\n * ```ts\n * new TreePlugin({\n * defaultExpanded: true,\n * animation: 'fade', // 'slide' | 'fade' | false\n * indentWidth: 32,\n * })\n * ```\n *\n * @see {@link TreeConfig} for all configuration options\n * @see {@link FlattenedTreeRow} for the flattened row structure\n *\n * @internal Extends BaseGridPlugin\n * @since 0.1.1\n */\nexport class TreePlugin extends BaseGridPlugin<TreeConfig> implements HierarchyContributor {\n static override readonly manifest: PluginManifest = {\n modifiesRowStructure: true,\n hookPriority: {\n processRows: 10, // Run after ServerSide (-10) so we receive managedNodes[]\n // Claim toggle clicks before Editing/Selection, whatever the registration order (#565)\n onCellClick: -10,\n },\n incompatibleWith: [\n {\n name: 'pivot',\n reason:\n 'PivotPlugin replaces the entire row and column structure with aggregated pivot data. ' +\n 'Tree hierarchy cannot coexist with pivot aggregation.',\n },\n ],\n events: [\n {\n type: 'tree-expand',\n description:\n 'Emitted when tree expansion state changes (toggle, expand all, collapse all). Broadcast to both DOM consumers and plugin bus.',\n },\n {\n type: 'tree-load-start',\n description: 'Emitted when lazy child loading starts for a node whose children are not yet loaded.',\n },\n {\n type: 'tree-load-end',\n description: 'Emitted when lazy child loading completes and children have been merged into the parent row.',\n },\n {\n type: 'tree-load-error',\n description: 'Emitted when lazy child loading fails. The node leaves its loading state and can be retried.',\n },\n ],\n queries: [\n {\n type: 'canMoveRow',\n description: 'Returns false for rows with children (parent nodes cannot be reordered)',\n },\n {\n type: 'datasource:viewport-mapping',\n description: 'Translates flat viewport row indices to top-level node indices for ServerSide pagination.',\n },\n ],\n };\n\n /**\n * Optional dependency on MultiSort for coordinated sorting.\n * When MultiSort is loaded, Tree defers header click sorting to it and queries the\n * sort model in processRows. When MultiSort is absent, Tree uses its own sort state.\n */\n static override readonly dependencies = [\n {\n name: 'hierarchy',\n required: true,\n reason: 'Builds the hierarchical row model',\n provide: () => new HierarchyPlugin(),\n },\n { name: 'multiSort', required: false, reason: 'Queries sort model for coordinated tree sorting' },\n { name: 'serverSide', required: false, reason: 'Consumes datasource events for lazy-loaded tree data' },\n ];\n\n /** @internal */\n readonly name = 'tree';\n /** @internal */\n readonly hierarchyStage = 'structure';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<TreeConfig> {\n return {\n childrenField: 'children',\n autoDetect: true,\n defaultExpanded: false,\n indentWidth: 20,\n showExpandIcons: true,\n animation: 'slide',\n };\n }\n\n // #region State\n\n private expandedKeys = new Set<string>();\n private initialExpansionDone = false;\n private flattenedRows: FlattenedTreeRow[] = [];\n private rowKeyMap = new Map<string, FlattenedTreeRow>();\n private previousVisibleKeys = new Set<string>();\n private keysToAnimate = new Set<string>();\n /** Root-node ordinal per row of the FINAL row list — group rows interleave with tree rows when composed. */\n #rootOwners: number[] = [];\n #rootCount = 0;\n private sortState: { field: string; direction: 1 | -1 } | null = null;\n /** Sort applied to every sibling list during the current rebuild. */\n #levelSort: { field: string; direction: 1 | -1 } | null = null;\n /**\n * In-flight lazy child loads, keyed by node key. `row` is the row OBJECT the\n * request is for — a ServerSide refetch can hand a new object for the same key\n * while the old request is still pending (#527). Both routes carry a\n * `controller`: local `loadChildren` gets its `signal`, ServerSide receives it\n * as `FetchChildrenQuery.signal` and links it to `getChildRows({ signal })`.\n */\n #loads = new Map<string, { row: TreeRow; depth: number; controller: AbortController }>();\n /**\n * Row objects whose children have already been fetched. Prevents a re-fetch on\n * collapse → re-expand, and prevents an infinite retry loop when a node\n * legitimately resolves to zero children but a custom `hasChildren`\n * predicate keeps reporting `true`.\n *\n * Keyed by row IDENTITY, not by node key: a ServerSide refetch (server\n * sort/filter change, `refresh()`) or a `grid.rows` reassignment delivers a\n * NEW object for the same key whose children are lazy again (#527).\n */\n #loadedRows = new WeakSet<object>();\n /**\n * Row objects with a child fetch that was started and NOT cancelled (in\n * flight, loaded, or failed). Limits the automatic re-request of\n * still-expanded lazy nodes (see {@link endHierarchy}) to one attempt per row\n * object, so a failing fetch can't retry on every render.\n */\n #requestedRows = new WeakSet<object>();\n /**\n * Row objects whose load was cancelled because a same-key row superseded it.\n * Kept apart from {@link #requestedRows} so a restored row (A → B → A) loads\n * again automatically, while a late response for the cancelled request is\n * still dropped.\n */\n #cancelledRows = new WeakSet<object>();\n /** Rendered nodes queued for load reconciliation (cancel / auto-request), flushed in one microtask. */\n #pendingReconcile: Array<{ meta: FlattenedTreeRow; flat: boolean }> = [];\n\n /**\n * Stable key cache keyed by row identity.\n * Persists across sort operations (object identity is preserved by sort);\n * replaces the previous `__stableKey` field-mutation approach so that\n * `_rows[i]` remains the user's original row reference and `updateRow(s)`\n * mutations survive the next `processRows` rebuild.\n *\n * INVARIANT: never mutate row objects to attach tree metadata — keep all\n * tree-specific state in this map and `#rowMeta` (see plugin-author rule\n * in `.github/knowledge/grid-plugins.md`).\n */\n #rowKeys = new WeakMap<object, string>();\n\n /**\n * Per-row tree metadata (depth, hasChildren, isExpanded, key) keyed by\n * row identity. Looked up by the column renderer via {@link getRowMeta}.\n * Reassigned to a fresh `WeakMap` at the start of each `processRows` call so\n * collapsed/hidden rows don't return stale metadata from a prior pass.\n */\n #rowMeta = new WeakMap<object, FlattenedTreeRow>();\n\n /** Cached original (unwrapped) renderer to prevent re-wrapping on repeated processColumns calls. */\n private originalTreeColumnRenderer: ColumnViewRenderer | undefined;\n /** Property used by the original renderer, matching core's renderer precedence. */\n private originalTreeColumnRendererProperty: 'renderer' | 'viewRenderer' = 'viewRenderer';\n /** Field name of the column currently wrapped with tree decorations. */\n private wrappedTreeColumnField: string | undefined;\n /** True while `processColumns` has the tree renderer installed on the tree column. */\n #treeColumnWrapped = false;\n /** Guards `#syncTreeColumn` against queueing more than one microtask. */\n #treeColumnSyncScheduled = false;\n\n /** @internal */\n override detach(): void {\n this.expandedKeys.clear();\n this.initialExpansionDone = false;\n this.flattenedRows = [];\n this.#rootOwners = [];\n this.#rootCount = 0;\n this.rowKeyMap.clear();\n this.previousVisibleKeys.clear();\n this.keysToAnimate.clear();\n this.sortState = null;\n this.#levelSort = null;\n this.#loadedRows = new WeakSet();\n this.#requestedRows = new WeakSet();\n this.#cancelledRows = new WeakSet();\n this.#pendingReconcile = [];\n // Silent on teardown — no `tree-load-end` for loads the detach aborts.\n for (const load of this.#loads.values()) load.controller.abort();\n this.#loads.clear();\n this.originalTreeColumnRenderer = undefined;\n this.originalTreeColumnRendererProperty = 'viewRenderer';\n this.wrappedTreeColumnField = undefined;\n this.#treeColumnWrapped = false;\n // WeakMaps GC themselves once row references are dropped — nothing to clear.\n }\n\n /**\n * Handle plugin queries.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'canMoveRow') {\n // Tree rows with children cannot be reordered\n const row = query.context as { [key: string]: unknown } | null | undefined;\n const childrenField = this.config.childrenField ?? 'children';\n const children = row?.[childrenField];\n if (Array.isArray(children) && children.length > 0) {\n return false;\n }\n }\n\n if (query.type === 'datasource:viewport-mapping') {\n // Translate visible flat row indices → top-level node indices for ServerSide pagination\n const { viewportStart, viewportEnd } = query.context as ViewportMappingQuery;\n if (this.flattenedRows.length === 0) return undefined;\n return mapViewportToRoots(this.#rootOwners, this.#rootCount, viewportStart, viewportEnd);\n }\n\n return undefined;\n }\n\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Listen for datasource:data from ServerSidePlugin — claim data for tree processing\n this.on('datasource:data', (detail: unknown) => {\n const d = detail as DataSourceDataDetail;\n if (!d.claimed) {\n d.claimed = true;\n }\n // Data flows through processRows pipeline — Tree receives it via the rows parameter\n // since ServerSide's processRows (hookPriority -10) runs first and returns managedNodes[]\n });\n\n // Listen for datasource:children — consume child rows from ServerSide\n this.on('datasource:children', (detail: unknown) => {\n const d = detail as DataSourceChildrenDetail;\n if (d.context?.source !== 'tree') return;\n d.claimed = true;\n\n // Merge children into the parent node\n const parentRow = d.context.parentNode as TreeRow | undefined;\n if (parentRow) {\n const key = this.#keyOf(parentRow);\n const load = this.#takeLoad(key, parentRow);\n // Requested by Tree but no longer active: superseded and already reported\n // as cancelled — never merge stale children into the replaced row.\n if (!load && (this.#requestedRows.has(parentRow as object) || this.#cancelledRows.has(parentRow as object))) {\n return;\n }\n this.#mergeChildren(parentRow, (d.rows ?? []) as TreeRow[]);\n this.broadcast<TreeLoadEndDetail>('tree-load-end', {\n key,\n row: parentRow,\n depth: load?.depth ?? this.rowKeyMap.get(key)?.depth ?? 0,\n childCount: d.rows?.length ?? 0,\n });\n this.requestRender();\n }\n });\n\n // Listen for datasource:error — release the node's loading state so the\n // user can retry by collapsing and re-expanding. Without this the load\n // stays in `#loads` forever and `requestLazyChildren` short-circuits.\n this.on('datasource:error', (detail: unknown) => {\n const d = detail as DataSourceErrorDetail;\n if (d.context?.source !== 'tree') return;\n const parentRow = d.context.parentNode as TreeRow | undefined;\n if (!parentRow) return;\n const key = this.#keyOf(parentRow);\n const load = this.#takeLoad(key, parentRow);\n if (!load) return;\n this.broadcast<TreeLoadErrorDetail>('tree-load-error', {\n key,\n row: parentRow,\n depth: load.depth,\n error: d.error,\n });\n this.requestRender();\n });\n }\n\n // #endregion\n\n // #region Animation\n\n /**\n * Get expand/collapse animation style from plugin config.\n * Uses base class isAnimationEnabled to respect grid-level settings.\n */\n private get animationStyle(): ExpandCollapseAnimation {\n if (!this.isAnimationEnabled) return false;\n return this.config.animation ?? 'slide';\n }\n\n // #endregion\n\n // #region Auto-Detection\n\n detect(rows: readonly unknown[]): boolean {\n if (!this.config.autoDetect) return false;\n const treeRows = rows as readonly TreeRow[];\n const field = this.config.childrenField ?? inferChildrenField(treeRows) ?? 'children';\n return detectTreeStructure(treeRows, field);\n }\n\n // #endregion\n\n // #region Data Processing\n\n /** @internal */\n override processRows(rows: readonly unknown[]): TreeRow[] {\n const hierarchy = this.grid?.getPluginByName?.('hierarchy');\n return (hierarchy ? hierarchy.process(rows, this) : buildHierarchy(rows, [this])) as TreeRow[];\n }\n\n /** @internal Hierarchy contributor hook */\n beginHierarchy(rows: readonly unknown[]): boolean {\n const treeRows = rows as readonly TreeRow[];\n if (\n treeRows.length === 0 ||\n !detectTreeStructure(treeRows, this.config.childrenField ?? 'children', this.config.hasChildren)\n ) {\n this.flattenedRows = [];\n this.#rootOwners = [];\n this.#rootCount = 0;\n this.rowKeyMap.clear();\n this.previousVisibleKeys.clear();\n this.#reconcileFlatRows(treeRows);\n this.#syncTreeColumn();\n return false;\n }\n\n // A ServerSide data source in `sortMode: 'server'` already ordered the roots\n // (`getRows({ sortModel })`) and lazy children (`getChildRows({ sortModel })`)\n // — keep its order (#524). Otherwise prefer MultiSort's model over local sort\n // state so Tree and MultiSort don't fight over sort ownership.\n const serverSorts = this.grid?.query?.<'server' | 'local'>('datasource:sort-mode', null)?.[0] === 'server';\n this.#levelSort = serverSorts ? null : this.resolveEffectiveSortState();\n\n if (this.config.defaultExpanded && !this.initialExpansionDone) {\n this.expandedKeys = expandAll(treeRows, this.config);\n this.initialExpansionDone = true;\n }\n this.#rowMeta = new WeakMap();\n return true;\n }\n\n /**\n * Sort one sibling list and attach each expanded node's children, never\n * cloning row objects — `data` on each FlattenedTreeRow stays `===` the\n * user's source row.\n * @internal Hierarchy contributor hook\n */\n processSiblings(nodes: HierarchyNode[], context: HierarchySiblingContext): HierarchyNode[] {\n const { parentKey, depth } = context;\n const childrenField = this.config.childrenField ?? 'children';\n const hasChildrenFn = this.config.hasChildren;\n // Assign stable keys using the ORIGINAL (unsorted) index so that\n // path-based keys match those produced by `expandAll` (which walks the\n // tree in source order). `#keyFor` caches by row identity, so the\n // subsequent lookup in the post-sort loop returns the same key.\n for (let i = 0; i < nodes.length; i++) {\n this.#keyFor(nodes[i].row as TreeRow, i, parentKey);\n }\n const sort = this.#levelSort;\n const ordered = sort ? this.#sortNodes(nodes, sort.field, sort.direction) : nodes;\n\n for (let i = 0; i < ordered.length; i++) {\n const node = ordered[i];\n const row = node.row as TreeRow;\n const key = this.#keyFor(row, i, parentKey);\n const children = row[childrenField];\n const embeddedChildren = Array.isArray(children) && children.length > 0;\n // Lazy children: either a custom `hasChildren` predicate reports the node\n // has children, or (default heuristic) a truthy non-array value such as\n // `children: true` signals children exist but haven't been fetched yet.\n // A loading placeholder (ServerSide) is a leaf and never reaches `hasChildren`.\n const hasChildren =\n embeddedChildren ||\n (row.__loading !== true &&\n (hasChildrenFn ? hasChildrenFn(row) : children != null && !Array.isArray(children) && !!children));\n const isExpanded = this.expandedKeys.has(key);\n\n this.#rowMeta.set(row as object, {\n key,\n data: row,\n depth,\n hasChildren,\n isExpanded,\n parentKey,\n posInSet: i + 1,\n setSize: ordered.length,\n });\n\n node.key = key;\n if (embeddedChildren && isExpanded) {\n node.expanded = true;\n node.children = (children as TreeRow[]).map((child) => ({ row: child }));\n }\n }\n return ordered;\n }\n\n /** @internal Hierarchy contributor hook */\n endHierarchy(rows: readonly unknown[], positionOf: (row: unknown) => HierarchyRowMeta | undefined): boolean {\n // Keep metadata for rendered rows only, so rows hidden by a collapsed\n // ancestor don't return stale entries via getRowMeta().\n const processed = this.#rowMeta;\n this.#rowMeta = new WeakMap();\n this.flattenedRows = [];\n this.rowKeyMap.clear();\n this.keysToAnimate.clear();\n const currentKeys = new Set<string>();\n const rootOwners = new Array<number>(rows.length);\n let rootOrdinal = -1;\n\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const meta = processed.get(row as object);\n if (meta?.parentKey === null) rootOrdinal++;\n rootOwners[i] = rootOrdinal;\n if (!meta) continue;\n // Indent below any levels another contributor (e.g. grouping) inserted above this row.\n const level = positionOf(row)?.level;\n if (level !== undefined) meta.depth = level - 1;\n this.flattenedRows.push(meta);\n this.rowKeyMap.set(meta.key, meta);\n this.#rowMeta.set(row as object, meta);\n currentKeys.add(meta.key);\n if (!this.previousVisibleKeys.has(meta.key) && meta.depth > 0) {\n this.keysToAnimate.add(meta.key);\n }\n if (this.#needsReconcile(meta)) {\n this.#queueReconcile(meta);\n }\n }\n this.previousVisibleKeys = currentKeys;\n this.#rootOwners = rootOwners;\n this.#rootCount = rootOrdinal + 1;\n\n this.#syncTreeColumn();\n return true;\n }\n\n /**\n * Keep the tree column decoration in sync with whether the current data is a\n * tree.\n *\n * `processColumns` bails out while `flattenedRows` is empty, and a ROWS-only\n * render (async `grid.rows` assignment, a ServerSide block landing) never\n * re-runs the COLUMNS phase — so without this the toggle/indent renderer is\n * never installed for data that arrives after the first render.\n *\n * The comparison is deferred to a microtask so that a COLUMNS-phase render —\n * whose `processColumns` runs later in the same synchronous scheduler flush —\n * settles the flag first and costs no extra frame.\n */\n #syncTreeColumn(): void {\n if (this.#treeColumnSyncScheduled) return;\n this.#treeColumnSyncScheduled = true;\n queueMicrotask(() => {\n this.#treeColumnSyncScheduled = false;\n if (!this.grid) return;\n if (this.#treeColumnWrapped !== this.flattenedRows.length > 0) {\n this.requestColumnsRender();\n }\n });\n }\n\n /**\n * Resolve the stable key for a row, caching by identity in {@link #rowKeys}.\n * Prefers `row.id` (already stable across sort), then any previously cached\n * key for this row reference, then falls back to a path-based key.\n */\n #keyFor(row: TreeRow, index: number, parentKey: string | null): string {\n if (row.id !== undefined) {\n const key = String(row.id);\n this.#rowKeys.set(row as object, key);\n return key;\n }\n const cached = this.#rowKeys.get(row as object);\n if (cached !== undefined) return cached;\n const key = parentKey ? `${parentKey}-${index}` : String(index);\n this.#rowKeys.set(row as object, key);\n return key;\n }\n\n /** Order a sibling list's nodes by their rows via {@link #sortLevel}. */\n #sortNodes(nodes: HierarchyNode[], field: string, dir: 1 | -1): HierarchyNode[] {\n const byRow = new Map<unknown, HierarchyNode>();\n for (const node of nodes) byRow.set(node.row, node);\n const sorted = this.#sortLevel(\n nodes.map((node) => node.row as TreeRow),\n field,\n dir,\n );\n return sorted.map((row) => byRow.get(row) ?? { row });\n }\n\n /**\n * Sort rows at a single level, returning a new array of the SAME row references\n * in sorted order. Never clones row objects, and never mutates the input array\n * (children arrays are user-owned for tree rows — we always pass a shallow copy\n * to the handler so a custom in-place sortHandler can't corrupt user data).\n *\n * Delegates to the same handler chain core uses: `gridConfig.sortHandler` when\n * provided, otherwise `builtInSort` (which honors per-column `sortComparator`\n * and `valueAccessor`). Async handlers cannot be awaited inside the synchronous\n * tree flatten — fall back to `builtInSort` when one is detected, and swallow\n * any rejection so it doesn't surface as an unhandled promise rejection.\n */\n #sortLevel(rows: readonly TreeRow[], field: string, dir: 1 | -1): TreeRow[] {\n const host = this.grid;\n const columns = (host?._columns ?? []) as ColumnConfig<TreeRow>[];\n const handler: SortHandler<TreeRow> = host?.effectiveConfig?.sortHandler ?? builtInSort;\n const sortState = { field, direction: dir };\n // Always pass a shallow copy: `rows` may be a user-owned `row.children`\n // array, and a non-defensive sortHandler could otherwise mutate it.\n const input = [...rows] as TreeRow[];\n const result = handler(input, sortState, columns);\n if (result && typeof (result as Promise<unknown[]>).then === 'function') {\n void (result as Promise<unknown[]>).catch(() => undefined);\n return builtInSort(input, sortState, columns);\n }\n return result as TreeRow[];\n }\n\n /**\n * Look up the stable key by row identity (was stored on the row as\n * `__stableKey` historically; now lives in a parallel WeakMap to keep row\n * identity intact).\n */\n #keyOf(row: TreeRow): string {\n return this.#rowKeys.get(row as object) ?? String(row.id ?? '?');\n }\n\n /** Write fetched children onto the parent row and mark the node as loaded. */\n #mergeChildren(row: TreeRow, children: TreeRow[]): void {\n (row as Record<string, unknown>)[this.config.childrenField ?? 'children'] = children;\n this.#loadedRows.add(row as object);\n }\n\n /**\n * Whether a node's children still need to be fetched — it reports having\n * children (via the lazy indicator or a custom `hasChildren` predicate) but\n * none are embedded yet, and no previous fetch for this row object has resolved.\n */\n #needsChildFetch(row: TreeRow): boolean {\n if (this.#loadedRows.has(row as object)) return false;\n const children = row[this.config.childrenField ?? 'children'];\n if (Array.isArray(children) && children.length > 0) return false;\n const custom = this.config.hasChildren;\n return custom ? custom(row) : children != null && !Array.isArray(children) && !!children;\n }\n\n /**\n * Whether a rendered node needs reconciling with `#loads`:\n * - a pending load belongs to a DIFFERENT row object under this key — the row\n * was replaced, so that load is obsolete whether or not the replacement needs\n * a fetch (it may embed its children, or the node may be collapsed);\n * - or the node is expanded with lazy children its row object never requested\n * — e.g. a root replaced by a ServerSide refetch (#527), or a node passed to\n * {@link expand} before its row existed.\n *\n * ServerSide placeholders never supersede a load: their path key can collide\n * with a real row's id.\n */\n #needsReconcile(meta: FlattenedTreeRow): boolean {\n if (meta.data.__loading === true) return false;\n const load = this.#loads.get(meta.key);\n if (load) return load.row !== meta.data;\n return (\n meta.isExpanded &&\n meta.hasChildren &&\n !this.#requestedRows.has(meta.data as object) &&\n this.#needsChildFetch(meta.data)\n );\n }\n\n /**\n * Cancel pending loads whose key now belongs to a different row object in data\n * that is no longer a tree (e.g. the only lazy root replaced by a same-key row\n * with `children: []`). `endHierarchy` never runs for flat data, so the\n * {@link #needsReconcile} pass doesn't see these replacements. Cancel-only:\n * flat data never requests children. Placeholders are skipped as in\n * `#needsReconcile`; on duplicate keys the last row owns the key, as in `rowKeyMap`.\n */\n #reconcileFlatRows(rows: readonly TreeRow[]): void {\n if (this.#loads.size === 0) return;\n const owners = new Map<string, TreeRow>();\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n if (row.__loading === true) continue;\n // Read-only key lookup — matches `#keyFor` without caching keys for flat rows.\n const key = row.id !== undefined ? String(row.id) : (this.#rowKeys.get(row as object) ?? String(i));\n if (this.#loads.has(key)) owners.set(key, row);\n }\n for (const [key, row] of owners) {\n if (this.#loads.get(key)?.row === row) continue;\n this.#queueReconcile(\n { key, data: row, depth: 0, hasChildren: false, isExpanded: false, parentKey: null, posInSet: 0, setSize: 0 },\n true,\n );\n }\n }\n\n /**\n * Queue a node for {@link #needsReconcile} handling. Deferred to ONE microtask:\n * `endHierarchy` runs inside the render pipeline, and cancelling / requesting\n * broadcasts `tree-load-end` / `tree-load-start` and queries ServerSide\n * synchronously. Loads of nodes that are not rendered (hidden under a\n * collapsed ancestor, or gone from the data) are left to settle.\n *\n * @param flat - Entry from {@link #reconcileFlatRows}: cancel only. `rowKeyMap`\n * is empty for flat data, so the owner check was already applied by the caller.\n */\n #queueReconcile(meta: FlattenedTreeRow, flat = false): void {\n if (this.#pendingReconcile.push({ meta, flat }) > 1) return;\n queueMicrotask(() => {\n const pending = this.#pendingReconcile;\n this.#pendingReconcile = [];\n if (!this.grid) return;\n let started = false;\n for (const { meta: node, flat: cancelOnly } of pending) {\n // Only the key's current owner acts — skips rows replaced again by a later\n // rebuild, and keeps duplicate keys from cancelling each other in a loop.\n if (!cancelOnly && this.rowKeyMap.get(node.key)?.data !== node.data) continue;\n const load = this.#loads.get(node.key);\n if (load && load.row !== node.data) this.#cancelLoad(node.key);\n if (cancelOnly || !this.expandedKeys.has(node.key) || this.#requestedRows.has(node.data as object)) continue;\n // One automatic attempt per row object, even when no loader is configured.\n this.#requestedRows.add(node.data as object);\n started = this.requestLazyChildren(node) || started;\n }\n if (started) this.requestRender();\n });\n }\n\n /**\n * Request lazy children for a node that is being expanded.\n *\n * Two routes, in precedence order:\n * 1. **ServerSide** — when `ServerSidePlugin` is active, dispatch the\n * `datasource:fetch-children` query; the result arrives asynchronously as\n * a `datasource:children` (or `datasource:error`) broadcast.\n * 2. **Local `loadChildren`** — invoke the config callback directly. Works\n * without `ServerSidePlugin` for grids that only need lazy tree children\n * and not server-side root pagination/sorting/filtering.\n *\n * No-op when neither route is configured, this row is already loading, or\n * its children are already embedded. A pending load for a DIFFERENT row\n * object under the same key (replaced by a refetch) is cancelled first.\n *\n * @returns `true` when a fetch was started.\n */\n private requestLazyChildren(flatRow: FlattenedTreeRow): boolean {\n const { key, depth, data: row } = flatRow;\n const active = this.#loads.get(key);\n if (active?.row === row) return false;\n if (!this.#needsChildFetch(row)) return false;\n\n const isServerSideActive = this.queryBoolean('datasource:is-active');\n const { loadChildren } = this.config;\n if (!isServerSideActive && !loadChildren) return false;\n\n if (active) this.#cancelLoad(key);\n const controller = new AbortController();\n this.#loads.set(key, { row, depth, controller });\n this.#requestedRows.add(row as object);\n this.#cancelledRows.delete(row as object);\n this.broadcast<TreeLoadStartDetail>('tree-load-start', { key, row, depth });\n\n if (isServerSideActive) {\n this.grid.query('datasource:fetch-children', {\n context: { source: 'tree', parentNode: row, nodePath: [key] },\n signal: controller.signal,\n } satisfies FetchChildrenQuery);\n return true;\n }\n\n this.#loadChildrenLocally(key, row, depth, controller);\n return true;\n }\n\n /** Whether `meta`'s row object (not just its key) has a child load in flight. */\n #isLoading(meta: FlattenedTreeRow): boolean {\n return this.#loads.get(meta.key)?.row === meta.data;\n }\n\n /** Remove and return the in-flight load for `key` when it belongs to `row`. */\n #takeLoad(key: string, row: TreeRow): { row: TreeRow; depth: number; controller: AbortController } | undefined {\n const load = this.#loads.get(key);\n if (load?.row !== row) return undefined;\n this.#loads.delete(key);\n return load;\n }\n\n /**\n * Abort a superseded load and close its event pair with a cancelled\n * `tree-load-end`, so every `tree-load-start` gets exactly one end or error.\n */\n #cancelLoad(key: string): void {\n const load = this.#loads.get(key);\n if (!load) return;\n this.#loads.delete(key);\n // Not a settled attempt: a restored row must be able to load again automatically.\n this.#requestedRows.delete(load.row as object);\n this.#cancelledRows.add(load.row as object);\n load.controller.abort();\n this.broadcast<TreeLoadEndDetail>('tree-load-end', {\n key,\n row: load.row,\n depth: load.depth,\n childCount: 0,\n cancelled: true,\n });\n }\n\n /**\n * Drive the local `loadChildren` callback. Supports both `Promise` and\n * `Subscribable` results; the subscription is torn down on abort so an\n * Angular `HttpClient` request is cancelled natively.\n */\n #loadChildrenLocally(key: string, row: TreeRow, depth: number, controller: AbortController): void {\n // A callback is guaranteed by the caller's guard.\n const loadChildren = this.config.loadChildren as NonNullable<TreeConfig['loadChildren']>;\n\n const finish = (): boolean => {\n // Superseded (already reported as cancelled) or detached — drop the result.\n if (controller.signal.aborted) return false;\n this.#loads.delete(key);\n return true;\n };\n\n const onSuccess = (rows: TreeRow[] | null | undefined) => {\n if (!finish()) return;\n const children = rows ?? [];\n this.#mergeChildren(row, children);\n this.broadcast<TreeLoadEndDetail>('tree-load-end', { key, row, depth, childCount: children.length });\n this.requestRender();\n };\n\n const onError = (error: unknown) => {\n if (!finish()) return;\n this.broadcast<TreeLoadErrorDetail>('tree-load-error', { key, row, depth, error });\n this.requestRender();\n };\n\n let result: Promise<TreeRow[]> | Subscribable<TreeRow[]>;\n try {\n result = loadChildren({ row, key, depth, signal: controller.signal });\n } catch (error) {\n onError(error);\n return;\n }\n\n if (result && isSubscribable(result)) {\n // Take-one semantics: `onSuccess`/`onError` are single-shot (guarded by\n // `finish()`), so hold the subscription only until the first emission.\n // Without this, a source that never completes (a subject-like stream)\n // stays subscribed forever once its value has been consumed, because\n // `finish()` has already removed the load whose controller `detach()` aborts.\n let settled = false;\n let active: { unsubscribe(): void } | null = null;\n const release = (): void => {\n settled = true;\n active?.unsubscribe();\n active = null;\n };\n const subscription = result.subscribe({\n next: (rows) => {\n onSuccess(rows);\n release();\n },\n error: (error) => {\n onError(error);\n release();\n },\n });\n // A synchronous emission ran `release()` before `subscription` was bound.\n if (settled) {\n subscription.unsubscribe();\n return;\n }\n active = subscription;\n controller.signal.addEventListener('abort', release, { once: true });\n return;\n }\n Promise.resolve(result).then(onSuccess, onError);\n }\n\n /**\n * Resolve the effective sort state: prefer MultiSort's model when available,\n * fall back to local tree sort state.\n * This follows the same pattern as GroupingRowsPlugin.resolveGroupSortDirections.\n */\n private resolveEffectiveSortState(): { field: string; direction: 1 | -1 } | null {\n // When MultiSort is loaded, prefer its model for consistency\n const multiSortResults = this.grid?.query?.('sort:get-model', null);\n if (Array.isArray(multiSortResults) && multiSortResults.length > 0) {\n const sortModel = multiSortResults[0] as Array<{ field: string; direction: 'asc' | 'desc' }>;\n if (Array.isArray(sortModel) && sortModel.length > 0) {\n // Use the primary sort column from MultiSort\n return {\n field: sortModel[0].field,\n direction: sortModel[0].direction === 'desc' ? -1 : 1,\n };\n }\n }\n // Fallback: local sort state (when MultiSort is not loaded)\n return this.sortState;\n }\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n if (this.flattenedRows.length === 0) {\n const cols = [...columns] as ColumnConfig[];\n // The wrapper cannot simply be dropped: `_schedulerMergeConfig` reseeds\n // `#baseColumns` from `_columns`, so a previously wrapped renderer is\n // already baked into the columns handed to us. Put the original back.\n if (this.#treeColumnWrapped) {\n const idx = cols.findIndex((c) => c.field === this.wrappedTreeColumnField);\n if (idx >= 0) {\n cols[idx] = {\n ...cols[idx],\n renderer:\n this.originalTreeColumnRendererProperty === 'renderer' ? this.originalTreeColumnRenderer : undefined,\n };\n }\n }\n this.#treeColumnWrapped = false;\n this.originalTreeColumnRenderer = undefined;\n this.originalTreeColumnRendererProperty = 'viewRenderer';\n this.wrappedTreeColumnField = undefined;\n return cols;\n }\n\n const cols = [...columns] as ColumnConfig[];\n if (cols.length === 0) return cols;\n\n // Determine which column gets the tree toggle and indentation.\n // If treeColumn is configured, find it by field name; otherwise use the first column.\n const { treeColumn } = this.config;\n let targetIndex = 0;\n if (treeColumn) {\n const idx = cols.findIndex((c) => c.field === treeColumn);\n if (idx >= 0) targetIndex = idx;\n }\n const targetCol = cols[targetIndex];\n const targetField = targetCol.field;\n\n // Capture the original (unwrapped) renderer only once per target column.\n // On subsequent processColumns calls, reuse the cached original so we\n // don't nest tree-cell-wrappers.\n if (this.wrappedTreeColumnField !== targetField) {\n this.originalTreeColumnRenderer = targetCol.renderer || targetCol.viewRenderer;\n this.originalTreeColumnRendererProperty = targetCol.renderer ? 'renderer' : 'viewRenderer';\n this.wrappedTreeColumnField = targetField;\n }\n const originalRenderer = this.originalTreeColumnRenderer;\n const getConfig = () => this.config;\n const setIconFn = this.setIcon.bind(this);\n\n const wrappedRenderer: ColumnViewRenderer = (ctx) => {\n const { row, value } = ctx;\n const { showExpandIcons = true, indentWidth } = getConfig();\n const meta = this.#rowMeta.get(row as object);\n const depth = meta?.depth ?? 0;\n\n const container = document.createElement('span');\n container.className = 'tree-cell-wrapper';\n container.style.setProperty('--tbw-tree-depth', String(depth));\n // Allow config-based indentWidth to override CSS default\n if (indentWidth !== undefined) {\n container.style.setProperty('--tbw-tree-indent-width', `${indentWidth}px`);\n }\n\n // Add expand/collapse icon, loading spinner, or spacer\n if (showExpandIcons) {\n if (meta && this.#isLoading(meta)) {\n // Reuse the core loading UI (`.tbw-spinner--small`) instead of a\n // tree-specific indicator so custom spinner theming applies here too.\n const spinner = createDefaultSpinner('small');\n spinner.classList.add('tree-loading');\n container.appendChild(spinner);\n } else if (meta && meta.hasChildren) {\n const icon = document.createElement('span');\n icon.className = `${GridClasses.TREE_TOGGLE}${meta.isExpanded ? ` ${GridClasses.EXPANDED}` : ''}`;\n setIconFn(icon, meta.isExpanded ? 'collapse' : 'expand');\n icon.setAttribute('data-tree-key', meta.key);\n container.appendChild(icon);\n } else {\n const spacer = document.createElement('span');\n spacer.className = 'tree-spacer';\n container.appendChild(spacer);\n }\n }\n\n // Add the original content\n const content = document.createElement('span');\n content.className = 'tree-content';\n if (originalRenderer) {\n const result = originalRenderer(ctx);\n if (result instanceof Node) {\n content.appendChild(result);\n } else if (typeof result === 'string') {\n setSanitizedHTML(content, result);\n }\n } else {\n content.textContent = value != null ? String(value) : '';\n }\n container.appendChild(content);\n\n return container;\n };\n\n cols[targetIndex] = { ...targetCol, renderer: wrappedRenderer };\n this.#treeColumnWrapped = true;\n return cols;\n }\n\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onCellClick(event: CellClickEvent): boolean {\n // closest(): a custom icon (setIcon HTML/element) puts the click target inside the toggle\n const toggle = (event.originalEvent?.target as Element | null)?.closest?.(`.${GridClasses.TREE_TOGGLE}`);\n if (!toggle) return false;\n // #568: core also routes `dblclick` here; toggle only on clicks so a double-click\n // toggles twice (click, click), not three times. Still claim it — the toggle owns it.\n if (event.originalEvent.type === 'dblclick') return true;\n\n const key = toggle.getAttribute('data-tree-key');\n if (!key) return false;\n\n const flatRow = this.rowKeyMap.get(key);\n if (!flatRow) return false;\n\n this.expandedKeys = toggleExpand(this.expandedKeys, key);\n\n // Request lazy children when expanding a node without embedded children\n if (this.expandedKeys.has(key)) {\n this.requestLazyChildren(flatRow);\n }\n\n this.broadcast<TreeExpandDetail>('tree-expand', {\n key,\n row: flatRow.data,\n expanded: this.expandedKeys.has(key),\n depth: flatRow.depth,\n expandedKeys: [...this.expandedKeys],\n });\n this.requestRender();\n return true;\n }\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n // SPACE toggles expansion when on a row with children\n if (event.key !== ' ') return;\n // An open editor (or any input in the row) owns Space — let it type (#546).\n if (isFormFieldKeyTarget(event)) return;\n\n const focusRow = this.grid._focusRow;\n const flatRow = this.#rowMeta.get(this.rows[focusRow] as object);\n if (!flatRow?.hasChildren) return;\n\n event.preventDefault();\n this.expandedKeys = toggleExpand(this.expandedKeys, flatRow.key);\n\n // Request lazy children when expanding a node without embedded children\n if (this.expandedKeys.has(flatRow.key)) {\n this.requestLazyChildren(flatRow);\n }\n\n this.broadcast<TreeExpandDetail>('tree-expand', {\n key: flatRow.key,\n row: flatRow.data,\n expanded: this.expandedKeys.has(flatRow.key),\n depth: flatRow.depth,\n expandedKeys: [...this.expandedKeys],\n });\n this.requestRenderWithFocus();\n return true;\n }\n\n /** @internal */\n override onHeaderClick(event: HeaderClickEvent): boolean {\n if (this.flattenedRows.length === 0 || !event.column.sortable) return false;\n\n // When MultiSort is active, let it handle header clicks entirely.\n // Tree will pick up the sort model in processRows via resolveEffectiveSortState().\n const multiSortResults = this.grid?.query?.('sort:get-model', null);\n if (Array.isArray(multiSortResults) && multiSortResults.length > 0) {\n // MultiSort is loaded — don't consume the event, let MultiSort handle it\n return false;\n }\n\n // Fallback: manage own sort state when MultiSort is not loaded\n const { field } = event.column;\n if (!this.sortState || this.sortState.field !== field) {\n this.sortState = { field, direction: 1 };\n } else if (this.sortState.direction === 1) {\n this.sortState = { field, direction: -1 };\n } else {\n this.sortState = null;\n }\n\n // Sync grid sort indicator\n const gridEl = this.grid;\n if (gridEl._sortState !== undefined) {\n gridEl._sortState = this.sortState ? { ...this.sortState } : null;\n }\n\n this.broadcast('sort-change', { field, direction: this.sortState?.direction ?? 0 });\n this.requestRender();\n return true;\n }\n\n /** @internal */\n override afterRender(): void {\n const body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n const style = this.animationStyle;\n const shouldAnimate = style !== false && this.keysToAnimate.size > 0;\n const animClass = style === 'fade' ? 'tbw-tree-fade-in' : 'tbw-tree-slide-in';\n\n for (const rowEl of body.querySelectorAll('.data-grid-row')) {\n // Look up by row identity: other hierarchy contributors (group rows)\n // may be interleaved with tree rows in the rendered list.\n const treeRow = this.#rowMeta.get((rowEl as RowElementInternal).__rowDataRef as object);\n if (!treeRow) continue;\n\n // Set aria-expanded on parent rows for screen readers. MUST clear it\n // on leaf rows: virtualization recycles row DOM elements, so a leaf\n // row reusing a previously-expanded parent's element would otherwise\n // inherit a stale `aria-expanded=\"true\"` (issue #282). The matching\n // `.tbw-row-expanded` class is the public hook for theming expanded\n // rows — devs should style against the class, not the ARIA attribute.\n if (treeRow.hasChildren) {\n rowEl.setAttribute('aria-expanded', String(treeRow.isExpanded));\n } else if (rowEl.hasAttribute('aria-expanded')) {\n rowEl.removeAttribute('aria-expanded');\n }\n rowEl.classList.toggle('tbw-row-expanded', treeRow.hasChildren && treeRow.isExpanded);\n\n // Announce in-flight lazy child loading. MUST clear on the negative\n // branch — virtualization recycles row elements, so a row reusing a\n // previously-loading element would inherit a stale `aria-busy`. A row in\n // the CORE row-loading state (`.tbw-row-loading`: a ServerSide placeholder,\n // or `grid.setRowLoading()`) owns its own `aria-busy` — leave it alone.\n if (this.#isLoading(treeRow)) {\n rowEl.setAttribute('aria-busy', 'true');\n } else if (rowEl.hasAttribute('aria-busy') && !rowEl.classList.contains('tbw-row-loading')) {\n rowEl.removeAttribute('aria-busy');\n }\n\n if (shouldAnimate && treeRow.key && this.keysToAnimate.has(treeRow.key)) {\n rowEl.classList.add(animClass);\n rowEl.addEventListener('animationend', () => rowEl.classList.remove(animClass), { once: true });\n }\n }\n this.keysToAnimate.clear();\n }\n\n // #endregion\n\n // #region Public API\n\n /**\n * Expand a specific tree node, revealing its children.\n *\n * If the node is already expanded, this is a no-op.\n * Does **not** emit a `tree-expand` event (use {@link toggle} for event emission).\n *\n * @param key - The unique key of the node to expand (from {@link FlattenedTreeRow.key})\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * tree.expand('documents'); // Expand a root node\n * tree.expand('documents||reports'); // Expand a nested node\n * ```\n */\n expand(key: string): void {\n this.expandedKeys.add(key);\n const flatRow = this.rowKeyMap.get(key);\n if (flatRow) {\n this.requestLazyChildren(flatRow);\n }\n this.requestRender();\n }\n\n /**\n * Collapse a specific tree node, hiding its children.\n *\n * If the node is already collapsed, this is a no-op.\n * Does **not** emit a `tree-expand` event (use {@link toggle} for event emission).\n *\n * @param key - The unique key of the node to collapse (from {@link FlattenedTreeRow.key})\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * tree.collapse('documents');\n * ```\n */\n collapse(key: string): void {\n this.expandedKeys.delete(key);\n this.requestRender();\n }\n\n /**\n * Toggle the expanded state of a tree node.\n *\n * If the node is expanded it will be collapsed, and vice versa.\n * Emits a `tree-expand` event (broadcast to both DOM consumers and plugin bus).\n *\n * @param key - The unique key of the node to toggle (from {@link FlattenedTreeRow.key})\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * tree.toggle('documents'); // Expand if collapsed, collapse if expanded\n * ```\n */\n toggle(key: string): void {\n this.expandedKeys = toggleExpand(this.expandedKeys, key);\n const flatRow = this.rowKeyMap.get(key);\n if (flatRow) {\n // Request lazy children when expanding a node without embedded children\n if (this.expandedKeys.has(key)) {\n this.requestLazyChildren(flatRow);\n }\n this.broadcast<TreeExpandDetail>('tree-expand', {\n key,\n row: flatRow.data,\n expanded: this.expandedKeys.has(key),\n depth: flatRow.depth,\n expandedKeys: [...this.expandedKeys],\n });\n } else {\n this.emitPluginEvent('tree-expand', { expandedKeys: [...this.expandedKeys] });\n }\n this.requestRender();\n }\n\n /**\n * Expand all tree nodes recursively.\n *\n * Every node with children will be expanded, revealing the full tree hierarchy.\n * Emits a `tree-expand` plugin event.\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * tree.expandAll();\n * ```\n */\n expandAll(): void {\n this.expandedKeys = expandAll(this.rows as TreeRow[], this.config);\n this.emitPluginEvent('tree-expand', { expandedKeys: [...this.expandedKeys] });\n this.requestRender();\n }\n\n /**\n * Collapse all tree nodes.\n *\n * Every node will be collapsed, showing only root-level rows.\n * Emits a `tree-expand` plugin event.\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * tree.collapseAll();\n * ```\n */\n collapseAll(): void {\n this.expandedKeys = collapseAll();\n this.emitPluginEvent('tree-expand', { expandedKeys: [...this.expandedKeys] });\n this.requestRender();\n }\n\n /**\n * Check whether a specific tree node is currently expanded.\n *\n * @param key - The unique key of the node to check\n * @returns `true` if the node is expanded, `false` otherwise\n */\n isExpanded(key: string): boolean {\n return this.expandedKeys.has(key);\n }\n\n /**\n * Get the keys of all currently expanded nodes.\n *\n * Returns a snapshot copy — mutating the returned array does not affect the tree state.\n *\n * @returns Array of expanded node keys\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * const keys = tree.getExpandedKeys();\n * localStorage.setItem('treeState', JSON.stringify(keys));\n * ```\n */\n getExpandedKeys(): string[] {\n return [...this.expandedKeys];\n }\n\n /**\n * Get the flattened row model used for rendering.\n *\n * Returns a snapshot copy of the internal flattened tree rows, including\n * hierarchy metadata (depth, hasChildren, isExpanded, parentKey).\n *\n * @returns Array of {@link FlattenedTreeRow} objects\n */\n getFlattenedRows(): FlattenedTreeRow[] {\n return [...this.flattenedRows];\n }\n\n /**\n * Get tree metadata (depth, key, hasChildren, isExpanded, parentKey) for a\n * specific row reference. Returns `undefined` if the row is not part of the\n * currently-flattened tree (e.g. collapsed under a parent or never processed).\n *\n * Tree metadata lives in a parallel WeakMap keyed by row identity \\u2014 it is\n * NOT stored on the row object itself. This preserves the invariant that\n * `_rows[i]` IS the user's source row reference, so `grid.updateRow(s)`\n * mutations survive the next ROWS-phase rebuild.\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * const meta = tree.getRowMeta(grid.rows[0]);\n * console.log(meta?.depth, meta?.hasChildren);\n * ```\n */\n getRowMeta(row: TreeRow): FlattenedTreeRow | undefined {\n return this.#rowMeta.get(row as object);\n }\n\n /**\n * Look up an original row data object by its tree key.\n *\n * @param key - The unique key of the node\n * @returns The original row data, or `undefined` if not found\n */\n getRowByKey(key: string): TreeRow | undefined {\n return this.rowKeyMap.get(key)?.data;\n }\n\n /**\n * Expand all ancestor nodes of the target key, revealing it in the tree.\n *\n * Useful for \"scroll to node\" or search-and-reveal scenarios where a deeply\n * nested node needs to be made visible.\n *\n * @param key - The unique key of the node to reveal\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * // Reveal a deeply nested node by expanding all its parents\n * tree.expandToKey('root||child||grandchild');\n * ```\n */\n expandToKey(key: string): void {\n this.expandedKeys = expandToKey(this.rows as TreeRow[], key, this.config, this.expandedKeys);\n this.requestRender();\n }\n\n // #endregion\n}\n"],"mappings":"C,qWAoCA,IAAasB,EAuBD,WAvBCA,EAiDE,cCxETC,EACJ,4SACGC,MAAM,KACNC,IAAKC,GAAMA,EAAEF,MAAM,IAAIG,UAAUC,KAAK,KA2BrCC,GA1BY,IAAIC,OAAO,uCAAuCP,EAAGQ,MAAM,GAAGH,KAAK,gBA0B9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