@toolbox-web/grid 3.8.2 → 3.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/all.d.ts +1 -0
- package/all.js +1 -1
- package/all.js.map +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/lib/core/defaults.d.ts +1 -1
- package/lib/core/internal/aria.d.ts +1 -1
- package/lib/core/internal/config-manager.d.ts +0 -4
- package/lib/core/plugin/base-plugin.d.ts +14 -0
- package/lib/core/plugin/plugin-manager.d.ts +5 -1
- package/lib/core/plugin/types.d.ts +2 -0
- package/lib/core/types.d.ts +6 -0
- package/lib/features/registry.js +1 -1
- package/lib/plugins/clipboard/clipboard-plugin.d.ts +2 -3
- package/lib/plugins/clipboard/index.js +1 -1
- package/lib/plugins/clipboard/index.js.map +1 -1
- package/lib/plugins/column-virtualization/index.js +1 -1
- package/lib/plugins/column-virtualization/index.js.map +1 -1
- package/lib/plugins/context-menu/index.js +1 -1
- package/lib/plugins/context-menu/index.js.map +1 -1
- package/lib/plugins/editing/index.js +1 -1
- package/lib/plugins/editing/index.js.map +1 -1
- package/lib/plugins/export/index.js +1 -1
- package/lib/plugins/export/index.js.map +1 -1
- package/lib/plugins/filtering/index.js +1 -1
- package/lib/plugins/filtering/index.js.map +1 -1
- package/lib/plugins/grouping-columns/index.js +1 -1
- package/lib/plugins/grouping-columns/index.js.map +1 -1
- package/lib/plugins/grouping-rows/grouping-rows-plugin.d.ts +20 -24
- package/lib/plugins/grouping-rows/grouping-rows.d.ts +9 -4
- package/lib/plugins/grouping-rows/index.d.ts +1 -1
- package/lib/plugins/grouping-rows/index.js +1 -1
- package/lib/plugins/grouping-rows/index.js.map +1 -1
- package/lib/plugins/grouping-rows/types.d.ts +32 -4
- package/lib/plugins/hierarchy/hierarchy-plugin.d.ts +79 -0
- package/lib/plugins/hierarchy/hierarchy.d.ts +28 -0
- package/lib/plugins/hierarchy/index.d.ts +9 -0
- package/lib/plugins/hierarchy/index.js +2 -0
- package/lib/plugins/hierarchy/index.js.map +1 -0
- package/lib/plugins/hierarchy/types.d.ts +92 -0
- package/lib/plugins/master-detail/index.js +1 -1
- package/lib/plugins/master-detail/index.js.map +1 -1
- package/lib/plugins/multi-sort/index.js +1 -1
- package/lib/plugins/multi-sort/index.js.map +1 -1
- package/lib/plugins/pinned-columns/index.js +1 -1
- package/lib/plugins/pinned-columns/index.js.map +1 -1
- package/lib/plugins/pinned-rows/index.js +1 -1
- package/lib/plugins/pinned-rows/index.js.map +1 -1
- package/lib/plugins/pivot/index.js +1 -1
- package/lib/plugins/pivot/index.js.map +1 -1
- package/lib/plugins/print/index.js +1 -1
- package/lib/plugins/print/index.js.map +1 -1
- package/lib/plugins/reorder-columns/index.js +1 -1
- package/lib/plugins/reorder-columns/index.js.map +1 -1
- package/lib/plugins/responsive/index.js +1 -1
- package/lib/plugins/responsive/index.js.map +1 -1
- package/lib/plugins/row-drag-drop/index.js +1 -1
- package/lib/plugins/row-drag-drop/index.js.map +1 -1
- package/lib/plugins/row-drag-drop/row-drag-drop-plugin.d.ts +1 -0
- package/lib/plugins/row-drag-drop/types.d.ts +3 -2
- package/lib/plugins/selection/index.js +1 -1
- package/lib/plugins/selection/index.js.map +1 -1
- package/lib/plugins/selection/selection-plugin.d.ts +2 -2
- package/lib/plugins/server-side/index.js +1 -1
- package/lib/plugins/server-side/index.js.map +1 -1
- package/lib/plugins/shell/index.js +1 -1
- package/lib/plugins/shell/index.js.map +1 -1
- package/lib/plugins/sticky-rows/index.js +1 -1
- package/lib/plugins/sticky-rows/index.js.map +1 -1
- package/lib/plugins/tooltip/index.js +1 -1
- package/lib/plugins/tooltip/index.js.map +1 -1
- package/lib/plugins/tree/index.js +1 -1
- package/lib/plugins/tree/index.js.map +1 -1
- package/lib/plugins/tree/tree-datasource.d.ts +7 -10
- package/lib/plugins/tree/tree-plugin.d.ts +23 -3
- package/lib/plugins/undo-redo/index.js +1 -1
- package/lib/plugins/undo-redo/index.js.map +1 -1
- package/lib/plugins/visibility/index.js +1 -1
- package/lib/plugins/visibility/index.js.map +1 -1
- 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/clipboard.umd.js +1 -1
- package/umd/plugins/clipboard.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 +2 -0
- package/umd/plugins/hierarchy.umd.js.map +1 -0
- package/umd/plugins/row-drag-drop.umd.js +1 -1
- package/umd/plugins/row-drag-drop.umd.js.map +1 -1
- package/umd/plugins/selection.umd.js +1 -1
- package/umd/plugins/selection.umd.js.map +1 -1
- package/umd/plugins/tooltip.umd.js +1 -1
- package/umd/plugins/tooltip.umd.js.map +1 -1
- package/umd/plugins/tree.umd.js +1 -1
- package/umd/plugins/tree.umd.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"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/core/defaults.ts","../../../../../../libs/grid/src/lib/core/internal/value-accessor.ts","../../../../../../libs/grid/src/lib/core/internal/sorting.ts","../../../../../../libs/grid/src/lib/core/internal/diagnostics.ts","../../../../../../libs/grid/src/lib/core/plugin/base-plugin.ts","../../../../../../libs/grid/src/lib/plugins/tree/tree-data.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 { GridConfig, LoadingContext } 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/**\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 */\nexport function setRowLoadingState(rowEl: HTMLElement, loading: boolean): 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 if (!rowEl.querySelector('.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 const spinner = document.createElement('div');\n spinner.className = 'tbw-row-loading-spinner';\n overlay.appendChild(spinner);\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 rowEl.querySelector('.tbw-row-loading-overlay')?.remove();\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 */\nexport function setCellLoadingState(cellEl: HTMLElement, loading: boolean): void {\n if (loading) {\n cellEl.classList.add('tbw-cell-loading');\n cellEl.setAttribute('aria-busy', 'true');\n } else {\n cellEl.classList.remove('tbw-cell-loading');\n cellEl.removeAttribute('aria-busy');\n }\n}\n","/**\n * Runtime default values for grid configuration.\n *\n * Kept out of `core/types.ts` so that file stays type-only apart from the two\n * enum-like consts whose `type` aliases are derived from them via `typeof`.\n * Import types from `./types`; import the values that back them from here.\n */\n\nimport type { A11yMessages, AnimationConfig, GridIcons } from './types';\n\n/**\n * Default English announcement messages.\n * Used when no custom messages are provided via {@link A11yConfig.messages}.\n * @since 2.0.0\n */\nexport const DEFAULT_A11Y_MESSAGES: A11yMessages = {\n sortApplied: (column, direction) => `Sorted by ${column}, ${direction}`,\n sortCleared: () => 'Sort cleared',\n filterApplied: (column) => `Filter applied on ${column}`,\n filterCleared: (column) => `Filter cleared from ${column}`,\n allFiltersCleared: () => 'All filters cleared',\n groupExpanded: (name, count) => `Group ${name} expanded, ${count} rows`,\n groupCollapsed: (name) => `Group ${name} collapsed`,\n selectionChanged: (count) => `${count} rows selected`,\n selectAllRows: () => 'Select all rows',\n selectRow: (rowIndex) => `Select row ${rowIndex + 1}`,\n columnSelected: (label) => `Column ${label} selected`,\n columnSelectionChanged: (count) => `${count} columns selected`,\n columnSelectionCleared: () => 'Column selection cleared',\n selectionAxisChanged: (toAxis) =>\n toAxis === 'column'\n ? 'Row selection cleared, column selection active'\n : 'Column selection cleared, row selection active',\n editingStarted: (rowIndex) => `Editing row ${rowIndex + 1}`,\n editingCommitted: (rowIndex) => `Row ${rowIndex + 1} saved`,\n dataLoaded: (count) => `${count} rows loaded`,\n};\n\n/**\n * Default animation configuration\n * @since 0.2.7\n */\nexport const DEFAULT_ANIMATION_CONFIG: Required<Omit<AnimationConfig, 'sort'>> = {\n mode: 'reduced-motion',\n duration: 200,\n easing: 'ease-out',\n};\n\n/**\n * Default icons used when not overridden. Most entries are short text/emoji;\n * `filter` and `filterActive` are empty strings because the actual rendering\n * is driven by the `--tbw-icon-filter[-active]-mask` CSS custom properties\n * (see `core/styles/variables.css`). Userland that wants an HTML/SVG fallback\n * via `gridConfig.icons.filter = '<svg…>'` is unaffected — that path overrides this default.\n * @since 0.1.1\n */\nexport const DEFAULT_GRID_ICONS: Required<GridIcons> = {\n expand: '▶',\n collapse: '▼',\n sortAsc: '▲',\n sortDesc: '▼',\n sortNone: '⇅',\n submenuArrow: '▶',\n dragHandle: '⋮⋮',\n toolPanel: '☰',\n filter: '',\n filterActive: '',\n print: '🖨️',\n};\n","/**\n * Value Accessor Module\n *\n * Single source of truth for resolving a column's value from a row.\n *\n * Resolution precedence:\n * 1. `column.valueAccessor({ row, column, rowIndex })` — when defined\n * 2. `row[column.field]` — direct field read (default)\n *\n * Per-column escape hatches (`sortComparator`, `filterValue`) still take\n * precedence over the accessor — the accessor is the *default* value source,\n * never an override. See {@link BaseColumnConfig.valueAccessor}.\n *\n * Performance: results are memoized per (row identity, column field) using a\n * `WeakMap`. Row identity changes (immutable updates) invalidate naturally;\n * in-place mutations must call {@link invalidateAccessorCache} on the row.\n */\n\nimport type { ColumnConfig } from '../types';\n\n// Box-wrapped values let the cache-hit path do a SINGLE `Map.get` instead of\n// `has()` + `get()`. A truthy box means cache hit (even when the cached value\n// itself is `undefined` / `null` / `0` / `''`).\ninterface CacheBox {\n v: unknown;\n}\nconst accessorCache = new WeakMap<object, Map<string, CacheBox>>();\n\n// #region Nested dotted-path field access (issue #438)\n\n// Prototype-pollution guard applied to every path segment on read AND write.\n// Uses explicit `===` comparisons (not a Set lookup) so static analyzers\n// recognize the barrier guarding the assignments in `setByPath`/`writeCellField`.\nfunction isUnsafeKey(key: string): boolean {\n return key === '__proto__' || key === 'constructor' || key === 'prototype';\n}\n\n// Parsed dotted-path cache: field string → segments. Only **dotted** fields are\n// cached; a plain key is recognised by a single `indexOf` scan, which is cheaper\n// than hashing the string for a Map probe and — critically — keeps the cache\n// from growing without bound when a plugin mints synthetic field names at\n// runtime (PivotPlugin derives one column per distinct pivot value).\nconst fieldPathCache = new Map<string, readonly string[]>();\n\n/**\n * Parse a column `field` into path segments, or `null` when it is a plain\n * top-level key (contains no `.`). Dotted results are memoized.\n *\n * @param field - The column field key (may be a dotted path like `a.b.c`).\n * @returns Frozen segment array for dotted paths, else `null`.\n * @since 3.3.0\n */\nexport function parseFieldPath(field: string): readonly string[] | null {\n if (field.indexOf('.') === -1) return null;\n let segments = fieldPathCache.get(field);\n if (segments === undefined) {\n segments = Object.freeze(field.split('.'));\n fieldPathCache.set(field, segments);\n }\n return segments;\n}\n\n/**\n * Read a nested value from `row` by pre-parsed path segments. Returns\n * `undefined` on any nullish/non-object hop. Prototype-pollution safe.\n *\n * @since 3.3.0\n */\nexport function getByPath(row: unknown, path: readonly string[]): unknown {\n let cur = row as Record<string, unknown> | null | undefined;\n for (let i = 0; i < path.length; i++) {\n if (cur == null || typeof cur !== 'object') return undefined;\n const seg = path[i];\n if (isUnsafeKey(seg)) return undefined;\n cur = cur[seg] as Record<string, unknown>;\n }\n return cur;\n}\n\n/**\n * Write `value` into `row` at the location described by pre-parsed path\n * segments. Walks **existing** objects only — it does NOT fabricate missing\n * intermediates — and returns `true` only when the write happened.\n * Prototype-pollution safe (every segment is guarded).\n *\n * @since 3.3.0\n */\nexport function setByPath(row: unknown, path: readonly string[], value: unknown): boolean {\n if (row == null || typeof row !== 'object') return false;\n let cur = row as Record<string, unknown>;\n for (let i = 0; i < path.length - 1; i++) {\n const seg = path[i];\n if (isUnsafeKey(seg)) return false;\n const next = cur[seg];\n if (next == null || typeof next !== 'object') return false;\n cur = next as Record<string, unknown>;\n }\n const last = path[path.length - 1];\n if (isUnsafeKey(last)) return false;\n cur[last] = value;\n return true;\n}\n\n/**\n * Read the raw stored value for `field` from `row`, honoring nested dotted\n * paths — the non-accessor counterpart to {@link resolveCellValue}.\n *\n * Resolution rules (back-compat critical, see `grid-core.md` DECIDED #438):\n * 1. Plain field (no `.`) → direct `row[field]` (identical to legacy path),\n * except prototype-polluting keys (`__proto__`/`constructor`/`prototype`)\n * which return `undefined` — symmetric with {@link writeCellField}.\n * 2. Dotted field whose literal key is an **own property** of `row` → that\n * flat value wins (preserves synthetic-key rows that really store `'a.b'`).\n * 3. Otherwise → nested traversal via {@link getByPath}.\n *\n * @since 3.3.0\n */\nexport function readCellField(row: unknown, field: string): unknown {\n if (row == null) return undefined;\n const path = parseFieldPath(field);\n const r = row as Record<string, unknown>;\n if (path === null) return isUnsafeKey(field) ? undefined : r[field];\n if (Object.prototype.hasOwnProperty.call(r, field)) return r[field];\n return getByPath(r, path);\n}\n\n/**\n * A precompiled reader that extracts one column's raw value from a row.\n *\n * @since 3.4.0\n */\nexport type FieldReader = (row: unknown) => unknown;\n\n/**\n * Build a {@link FieldReader} for `field`, resolving the plain / unsafe /\n * dotted decision **once** instead of on every cell read.\n *\n * Hoist the reader out of any per-row loop (sort comparators, compiled filter\n * predicates, aggregators, export writers). Semantics are identical to\n * {@link readCellField}; only the dispatch is paid up front.\n *\n * @param field - The column field key (may be a dotted path like `a.b.c`).\n * @returns A single-argument reader closure.\n *\n * @example\n * ```typescript\n * const read = createFieldReader(column.field);\n * rows.sort((a, b) => compare(read(a), read(b)));\n * ```\n * @since 3.4.0\n */\nexport function createFieldReader(field: string): FieldReader {\n const path = parseFieldPath(field);\n if (path === null) {\n if (isUnsafeKey(field)) return () => undefined;\n return (row) => (row == null ? undefined : (row as Record<string, unknown>)[field]);\n }\n return (row) => {\n if (row == null) return undefined;\n const r = row as Record<string, unknown>;\n // A literal own key containing a dot wins over traversal (see readCellField).\n if (Object.prototype.hasOwnProperty.call(r, field)) return r[field];\n return getByPath(r, path);\n };\n}\n\n/**\n * Whether `field` is a plain, safe top-level key — i.e. `row[field]` is exactly\n * equivalent to {@link readCellField} and callers may inline the property read.\n *\n * Used by benchmarked hot loops (compiled filter predicates) that keep a\n * hand-inlined fast path and only fall back to a {@link FieldReader} for the\n * dotted/unsafe minority.\n *\n * @since 3.4.0\n */\nexport function isPlainField(field: string): boolean {\n return field.indexOf('.') === -1 && !isUnsafeKey(field);\n}\n\n/**\n * Write `value` into `row` for `field`, honoring nested dotted paths and the\n * same back-compat precedence as {@link readCellField}. Returns `true` when a\n * write occurred. Prototype-pollution safe.\n *\n * @since 3.3.0\n */\nexport function writeCellField(row: unknown, field: string, value: unknown): boolean {\n if (row == null || typeof row !== 'object') return false;\n const path = parseFieldPath(field);\n const r = row as Record<string, unknown>;\n if (path === null) {\n if (isUnsafeKey(field)) return false;\n r[field] = value;\n return true;\n }\n // A literal own key containing a dot wins over traversal (symmetric with\n // readCellField). Such a key always contains `.`, so it can never be an\n // unsafe prototype key.\n if (Object.prototype.hasOwnProperty.call(r, field)) {\n r[field] = value;\n return true;\n }\n return setByPath(r, path, value);\n}\n\n// #endregion\n\n/**\n * Resolve the cell value for a column, honoring `valueAccessor` if defined,\n * otherwise reading `row[column.field]` (with nested dotted-path support).\n *\n * @param row - The row object\n * @param column - The column definition\n * @param rowIndex - The visible row index (passed to accessor; defaults to -1)\n * @returns The resolved cell value\n *\n * @example\n * ```typescript\n * const value = resolveCellValue(row, column);\n * ```\n * @since 2.2.0\n */\nexport function resolveCellValue<TRow>(row: TRow, column: ColumnConfig<TRow>, rowIndex = -1): unknown {\n if (!column.valueAccessor) {\n return readCellField(row, column.field);\n }\n // Non-object rows (primitives, null) bypass the cache.\n if (typeof row !== 'object' || row === null) {\n return column.valueAccessor({ row, column, rowIndex });\n }\n // After the guard above, `row` is provably a non-null object. Single\n // assertion (no `as unknown as`) bridges the generic `TRow` to the WeakMap\n // key type; see `.github/instructions/typescript-conventions.instructions.md`.\n const rowKey = row as object;\n const key = column.field;\n let cellMap = accessorCache.get(rowKey);\n if (cellMap) {\n const box = cellMap.get(key);\n if (box !== undefined) return box.v;\n } else {\n cellMap = new Map();\n accessorCache.set(rowKey, cellMap);\n }\n const value = column.valueAccessor({ row, column, rowIndex });\n cellMap.set(key, { v: value });\n return value;\n}\n\n/**\n * Invalidate cached accessor values for a row (after in-place mutation),\n * a single (row, field) pair, or — when called with no argument — clear\n * the entire cache. Immutable updates auto-invalidate via row identity.\n *\n * Edit/transaction paths that mutate row objects in-place must call this.\n * @since 2.2.0\n */\nexport function invalidateAccessorCache(row?: object, field?: string): void {\n if (!row) {\n // WeakMap can't be cleared in O(1); the GC handles unreferenced rows.\n // For an explicit full reset, callers should mutate row identities instead.\n return;\n }\n if (!field) {\n accessorCache.delete(row);\n return;\n }\n accessorCache.get(row)?.delete(field);\n}\n\n/**\n * Build a `(value, row) => unknown` extractor compatible with\n * `filterValue`-style APIs from a column's `valueAccessor`. Returns `undefined`\n * when the column has no accessor.\n *\n * Used by FilteringPlugin to bridge the two API shapes without duplicating\n * cache lookups.\n */\nexport function accessorAsFilterValue<TRow>(\n column: ColumnConfig<TRow>,\n): ((value: unknown, row: TRow) => unknown) | undefined {\n if (!column.valueAccessor) return undefined;\n return (_value, row) => resolveCellValue(row, column);\n}\n","/**\n * Sorting Module\n *\n * Handles column sorting state transitions and row ordering.\n */\n\nimport type { ColumnConfig, GridHost, InternalGrid, SortHandler, SortState } from '../types';\nimport { announce, getA11yMessage } from './aria';\nimport { createFieldReader, isPlainField, resolveCellValue } from './value-accessor';\n\n/**\n * Default comparator used when no column-level `sortComparator` is configured.\n * Pushes `null`/`undefined` to the end and compares remaining values via `>` / `<`\n * operators, which works correctly for numbers and falls back to lexicographic\n * comparison for strings.\n *\n * Use this as a fallback inside a custom `sortComparator` when you only need\n * special handling for certain values:\n *\n * @example\n * ```typescript\n * import { defaultComparator } from '@toolbox-web/grid';\n *\n * const column = {\n * field: 'priority',\n * sortComparator: (a, b, rowA, rowB) => {\n * // Pin \"urgent\" to the top, then fall back to default ordering\n * if (a === 'urgent') return -1;\n * if (b === 'urgent') return 1;\n * return defaultComparator(a, b);\n * },\n * };\n * ```\n *\n * @see {@link BaseColumnConfig.sortComparator} for column-level comparators\n * @see {@link builtInSort} for the full sort handler that uses this comparator\n * @category Factory Functions\n * @since 0.2.7\n */\nexport function defaultComparator(a: unknown, b: unknown): number {\n if (a == null && b == null) return 0;\n if (a == null) return -1;\n if (b == null) return 1;\n return a > b ? 1 : a < b ? -1 : 0;\n}\n\n/**\n * The default `sortHandler` used when none is provided in {@link GridConfig.sortHandler}.\n * Reads each column's `sortComparator` (falling back to {@link defaultComparator})\n * and returns a sorted copy of the rows array.\n *\n * **Contract:** This function is non-mutating — it copies the input array\n * (`[...rows].sort()`) before sorting and returns the new array. Public callers\n * may pass any array safely; internal callers that already own a mutable copy\n * should bypass this function and sort in place to avoid the extra allocation.\n * The non-mutation guarantee is part of the public API and must be preserved.\n *\n * Use this as a fallback inside a custom `sortHandler` when you only need to\n * intercept sorting for specific columns or add pre/post-processing:\n *\n * @example\n * ```typescript\n * import { builtInSort } from '@toolbox-web/grid';\n * import type { SortHandler } from '@toolbox-web/grid';\n *\n * const customSort: SortHandler<Employee> = (rows, state, columns) => {\n * // Server-side sort for the \"salary\" column, client-side for everything else\n * if (state.field === 'salary') {\n * return fetch(`/api/employees?sort=${state.field}&dir=${state.direction}`)\n * .then(res => res.json());\n * }\n * return builtInSort(rows, state, columns);\n * };\n *\n * grid.gridConfig = { sortHandler: customSort };\n * ```\n *\n * @see {@link GridConfig.sortHandler} for configuring the handler\n * @see {@link defaultComparator} for the comparator used per column\n * @category Factory Functions\n * @since 0.2.7\n */\nexport function builtInSort<T>(rows: T[], sortState: SortState, columns: ColumnConfig<T>[]): T[] {\n const sorted = [...rows];\n executeBuiltInSortInPlace(sorted, sortState.field, sortState.direction, columns as ColumnConfig<any>[]);\n return sorted;\n}\n\n/**\n * Sort an array in-place using the default comparator with direction folded in.\n * Shared between the public `builtInSort` (which copies first) and the internal\n * fast paths in `applySort` / `reapplyCoreSort` (which skip the copy).\n *\n * Pins `__loading` placeholder rows (e.g. ServerSidePlugin under `sortMode: 'local'`)\n * to the end regardless of direction.\n */\nfunction sortInPlace(rows: any[], field: string, direction: 1 | -1): void {\n // A plain top-level key is a monomorphic inline property load — cheaper read\n // than any indirection we could add. This comparator MUST stay fully inlined\n // (no shared helper call): it runs ~2·N·log N times, so even one extra call\n // per compare is measurable. See the INVARIANT in `.github/knowledge/grid-core.md`.\n if (isPlainField(field)) {\n rows.sort((rA: any, rB: any) => {\n const pinned = pinLoadingRows(rA, rB);\n if (pinned !== 0) return pinned;\n const a = rA[field];\n const b = rB[field];\n if (a == null && b == null) return 0;\n if (a == null) return -direction;\n if (b == null) return direction;\n return a > b ? direction : a < b ? -direction : 0;\n });\n return;\n }\n // Nested dotted path: each read walks the path, so hoist the extraction out\n // of the comparator (decorate-sort-undecorate). Touches every row once\n // instead of ~2·N·log N times.\n sortByExtractedKeys(rows, createFieldReader(field), direction);\n}\n\n/**\n * Decorate-sort-undecorate: extract every row's sort key once, sort an index\n * array, then permute the rows in place.\n *\n * Used when the key extraction is more than a single property load (nested\n * dotted paths, `valueAccessor`). Sorting indices keeps the sort **stable**,\n * because `Array.prototype.sort` is stable and equal keys fall back to\n * ascending index order — i.e. the original row order.\n */\nfunction sortByExtractedKeys(rows: any[], read: (row: unknown) => unknown, direction: 1 | -1): void {\n const n = rows.length;\n if (n < 2) return;\n\n const keys = new Array<unknown>(n);\n // `Uint8Array` keeps the placeholder flags off the JS heap's boxed path.\n const loading = new Uint8Array(n);\n const order = new Array<number>(n);\n for (let i = 0; i < n; i++) {\n const row = rows[i];\n order[i] = i;\n keys[i] = read(row);\n // Same test as `pinLoadingRows`, applied once per row instead of per compare.\n loading[i] = (row as { __loading?: unknown } | null)?.__loading === true ? 1 : 0;\n }\n\n // Inlined for the same reason as `sortInPlace` — this runs ~2·N·log N times.\n order.sort((ia, ib) => {\n const la = loading[ia];\n const lb = loading[ib];\n if (la !== lb) return la ? 1 : -1;\n const a = keys[ia];\n const b = keys[ib];\n if (a == null && b == null) return 0;\n if (a == null) return -direction;\n if (b == null) return direction;\n return (a as number) > (b as number) ? direction : (a as number) < (b as number) ? -direction : 0;\n });\n\n const sorted = new Array<unknown>(n);\n for (let i = 0; i < n; i++) sorted[i] = rows[order[i]];\n for (let i = 0; i < n; i++) rows[i] = sorted[i];\n}\n\n/**\n * Sort an array in-place using `column.valueAccessor` to extract each cell value.\n * Mirrors {@link sortInPlace} but routes value reads through the accessor +\n * shared per-row cache. Used when no `sortComparator` is configured.\n *\n * Pins `__loading` placeholder rows to the end regardless of direction.\n */\nfunction sortInPlaceWithAccessor(rows: any[], column: ColumnConfig<any>, direction: 1 | -1): void {\n sortByExtractedKeys(rows, (row) => resolveCellValue(row, column), direction);\n}\n\n/**\n * Pin `__loading` placeholder rows to the end of the sorted array regardless\n * of sort direction. Returns 0 when neither row is a placeholder.\n *\n * Applied only on the built-in default-comparator paths. Custom column\n * `sortComparator` callbacks receive the row pair and own placeholder handling.\n *\n * @internal\n */\nfunction pinLoadingRows(a: unknown, b: unknown): number {\n const aLoading = (a as { __loading?: unknown } | null)?.__loading === true;\n const bLoading = (b as { __loading?: unknown } | null)?.__loading === true;\n if (aLoading === bLoading) return 0;\n return aLoading ? 1 : -1;\n}\n\n/**\n * Execute the built-in sort on rows in-place, using a column-level custom\n * comparator when present, otherwise the default comparator.\n *\n * Shared by the public {@link builtInSort} (which copies first) and the internal\n * fast paths in `applySort` / `reapplyCoreSort` (which sort the live array).\n */\nfunction executeBuiltInSortInPlace(rows: any[], field: string, direction: 1 | -1, columns: ColumnConfig<any>[]): void {\n const col = columns.find((c) => c.field === field);\n const customComparator = col?.sortComparator;\n if (customComparator) {\n // Custom comparator path — keep the indirect call.\n // sortComparator wins over valueAccessor (per-column override).\n if (col?.valueAccessor) {\n rows.sort(\n (rA: any, rB: any) =>\n customComparator(resolveCellValue(rA, col), resolveCellValue(rB, col), rA, rB) * direction,\n );\n } else {\n const read = createFieldReader(field);\n rows.sort((rA: any, rB: any) => customComparator(read(rA), read(rB), rA, rB) * direction);\n }\n } else if (col?.valueAccessor) {\n // valueAccessor path — extract values via the accessor.\n sortInPlaceWithAccessor(rows, col, direction);\n } else {\n // Fast path — inline default comparator and fold direction to avoid\n // ~20M indirect function calls + multiplications at 1M rows.\n sortInPlace(rows, field, direction);\n }\n}\n\n/**\n * Apply sort result to grid and update UI.\n * Called after sync or async sort completes.\n */\nfunction finalizeSortResult<T>(grid: GridHost<T>, sortedRows: T[], col: ColumnConfig<T>, dir: 1 | -1): void {\n grid._rows = sortedRows;\n // Bump epoch so renderVisibleRows triggers full inline rebuild\n grid.__rowRenderEpoch++;\n // Invalidate pooled rows to guarantee rebuild\n for (let i = 0; i < grid._rowPool.length; i++) {\n grid._rowPool[i].__epoch = -1;\n }\n grid._schedulerRenderHeader();\n grid.refreshVirtualWindow(true);\n emitSortChange(grid, col, dir);\n}\n\n/**\n * Emit sort-change event, aria announcement, and state change request.\n * Shared by both the direct sort path and the scheduler-delegated path.\n *\n * Emits to BOTH channels:\n * - DOM CustomEvent — for external consumers (`grid.addEventListener('sort-change', …)`).\n * - Plugin event bus — for plugins that subscribe via `this.on('sort-change', …)`\n * (e.g. ServerSidePlugin purges its block cache on sort change). Without the\n * plugin-bus emit, the core sort path silently bypasses every plugin listener\n * while MultiSortPlugin (which uses `broadcast()`) works correctly.\n */\nfunction emitSortChange<T>(grid: GridHost<T>, col: ColumnConfig<T>, dir: 1 | -1 | 0): void {\n const detail = { field: col.field, direction: dir };\n grid.dispatchEvent(new CustomEvent('sort-change', { detail }));\n grid._pluginManager?.emitPluginEvent?.('sort-change', detail);\n announce(\n grid,\n getA11yMessage(\n grid,\n dir === 0 ? 'sortCleared' : 'sortApplied',\n col.header ?? col.field,\n dir === 1 ? 'ascending' : 'descending',\n ),\n );\n // Trigger state change after sort applied\n grid.requestStateChange?.();\n}\n\n/**\n * Check whether the grid has plugins that inject synthetic rows into `_rows`\n * (group headers, tree nodes, pivot aggregates, etc.).\n * When true, sorting must go through the render scheduler so the full row-model\n * pipeline (reapplyCoreSort → processRows) runs on the base rows instead of\n * directly mutating _rows which would corrupt plugin-generated row structures.\n *\n * This intentionally ignores plugins that only filter or reorder rows (Filtering,\n * MultiSort) — direct in-place sorting is safe for those.\n */\nfunction hasRowStructurePlugins(grid: GridHost): boolean {\n return grid._pluginManager?._hasRowStructurePlugins ?? false;\n}\n\n/**\n * Cycle sort state for a column: none -> ascending -> descending -> none.\n * Restores original row order when clearing sort.\n */\nexport function toggleSort(grid: GridHost, col: ColumnConfig<any>): void {\n if (!grid._sortState || grid._sortState.field !== col.field) {\n if (!grid._sortState) grid.__originalOrder = grid._rows.slice();\n applySort(grid, col, 1);\n } else if (grid._sortState.direction === 1) {\n applySort(grid, col, -1);\n } else {\n grid._sortState = null;\n\n // When row-model plugins are active (grouping, tree, etc.), delegate to the\n // render scheduler so #rebuildRowModel runs the full pipeline on base rows.\n if (hasRowStructurePlugins(grid)) {\n // RenderPhase.ROWS = 4 — triggers rebuildRowModel which skips reapplyCoreSort\n // when _sortState is null, then runs processRows to rebuild groups.\n grid._requestSchedulerPhase(4, 'sort-clear');\n emitSortChange(grid, col, 0);\n return;\n }\n\n // Fast path: no row-model plugins — direct _rows manipulation is safe.\n // Force full row rebuild after clearing sort so templated cells reflect original order\n grid.__rowRenderEpoch++;\n // Invalidate existing pooled row epochs so virtualization triggers a full inline rebuild\n for (let i = 0; i < grid._rowPool.length; i++) {\n grid._rowPool[i].__epoch = -1;\n }\n grid._rows = grid.__originalOrder.slice();\n grid.__originalOrder = [];\n grid._schedulerRenderHeader();\n // After re-render ensure cleared column shows aria-sort=\"none\" baseline.\n const headers = grid._headerRowEl?.querySelectorAll('[role=\"columnheader\"].sortable');\n if (headers) {\n for (let i = 0; i < headers.length; i++) {\n const h = headers[i];\n if (!h.getAttribute('aria-sort')) h.setAttribute('aria-sort', 'none');\n else if (h.getAttribute('aria-sort') === 'ascending' || h.getAttribute('aria-sort') === 'descending') {\n // The active column was re-rendered already, but normalize any missing ones.\n if (!grid._sortState) h.setAttribute('aria-sort', 'none');\n }\n }\n }\n grid.refreshVirtualWindow(true);\n emitSortChange(grid, col, 0);\n }\n}\n\n/**\n * Re-apply the current core sort to rows during #rebuildRowModel.\n * Updates __originalOrder so \"clear sort\" restores the current dataset.\n * Returns rows unchanged if no core sort is active or handler is async.\n *\n * @param skipOriginalOrderSave - When true, caller already saved __originalOrder.\n * Avoids an O(n) `rows.slice()` in the hot path.\n */\nexport function reapplyCoreSort<T>(grid: InternalGrid<T>, rows: T[], skipOriginalOrderSave = false): T[] {\n if (!grid._sortState) return rows;\n\n const handler: SortHandler<any> = grid.effectiveConfig?.sortHandler ?? builtInSort;\n\n // Reference equality gate: builtInSort is public API and must not mutate its input,\n // but internally we can bypass the copy when we know the caller already made one.\n // Do NOT replace with duck-typing or string comparison — the identity check is intentional.\n if (handler === builtInSort) {\n // Fast path: caller (#rebuildRowModel) already passed a copy of #rows.\n // Save a snapshot for \"clear sort\" unless the caller already did.\n if (!skipOriginalOrderSave) {\n grid.__originalOrder = rows.slice();\n }\n executeBuiltInSortInPlace(\n rows,\n grid._sortState!.field,\n grid._sortState!.direction,\n grid._columns as ColumnConfig<any>[],\n );\n return rows;\n }\n\n // Custom handler: preserve current behavior\n if (!skipOriginalOrderSave) {\n grid.__originalOrder = rows;\n }\n const result = handler(rows, grid._sortState, grid._columns as ColumnConfig<any>[]);\n if (result && typeof (result as Promise<unknown[]>).then === 'function') return rows;\n return result as T[];\n}\n\n/**\n * Apply a concrete sort direction to rows.\n *\n * Uses custom sortHandler from gridConfig if provided, otherwise uses built-in sorting.\n * Supports both sync and async handlers (for server-side sorting).\n *\n * When row-model plugins are active (grouping, tree, pivot), delegates to the render\n * scheduler so the full pipeline (reapplyCoreSort → processRows) runs on base rows.\n * This prevents sorting from corrupting plugin-generated row structures.\n */\nexport function applySort(grid: GridHost, col: ColumnConfig<any>, dir: 1 | -1): void {\n grid._sortState = { field: col.field, direction: dir };\n\n // When row-model plugins are active, delegate to the render scheduler.\n // #rebuildRowModel will call reapplyCoreSort on the base rows, then processRows\n // rebuilds groups/trees on the sorted data.\n if (hasRowStructurePlugins(grid)) {\n // RenderPhase.ROWS = 4\n grid._requestSchedulerPhase(4, 'sort-apply');\n emitSortChange(grid, col, dir);\n return;\n }\n\n // Fast path: no row-model plugins — sort _rows directly.\n const sortState: SortState = { field: col.field, direction: dir };\n const columns = grid._columns as ColumnConfig<any>[];\n\n // Get custom handler from effectiveConfig, or use built-in\n const handler: SortHandler<any> = grid.effectiveConfig?.sortHandler ?? builtInSort;\n\n // Reference equality gate — see comment in reapplyCoreSort above.\n if (handler === builtInSort) {\n // Fast path: sort grid._rows in-place — avoids allocating a 1M-element copy.\n // __originalOrder was already saved by toggleSort before calling applySort.\n executeBuiltInSortInPlace(grid._rows as any[], sortState.field, dir, columns);\n finalizeSortResult(grid, grid._rows, col, dir);\n return;\n }\n\n const result = handler(grid._rows, sortState, columns);\n\n // Handle async (Promise) or sync result\n if (result && typeof (result as Promise<unknown[]>).then === 'function') {\n // Async handler - wait for result\n (result as Promise<unknown[]>).then((sortedRows) => {\n finalizeSortResult(grid, sortedRows, col, dir);\n });\n } else {\n // Sync handler - apply immediately\n finalizeSortResult(grid, result as unknown[], col, dir);\n }\n}\n","/**\n * Centralized diagnostic messages for @toolbox-web/grid.\n *\n * Every user-facing warning, error, or info message in the grid has a unique\n * diagnostic code (e.g. `TBW001`). Each code maps to a section on the online\n * troubleshooting page, giving developers a direct link to resolution steps.\n *\n * ## Usage\n *\n * ```ts\n * import { MISSING_BREAKPOINT, warnDiagnostic, throwDiagnostic } from './diagnostics';\n *\n * // Warn with a code\n * warnDiagnostic(MISSING_BREAKPOINT, 'Set a breakpoint...', gridId);\n *\n * // Throw with a code\n * throwDiagnostic(MISSING_ROW_ID, 'Configure getRowId...', gridId);\n * ```\n *\n * Plugins should prefer `this.warn(MISSING_BREAKPOINT, message)` via BaseGridPlugin\n * instead of importing this module directly.\n *\n * @internal\n */\n\n// #region Grid Prefix\n\n/**\n * Build the `[tbw-grid]` or `[tbw-grid#my-id]` log prefix.\n * Pass `pluginName` for a scoped prefix like `[tbw-grid:SelectionPlugin]`.\n */\nexport function gridPrefix(gridId?: string, pluginName?: string): string {\n const id = gridId ? `#${gridId}` : '';\n const plugin = pluginName ? `:${pluginName}` : '';\n return `[tbw-grid${id}${plugin}]`;\n}\n\n// #endregion\n\n// #region Diagnostic Codes\n\n/**\n * Diagnostic codes used across the grid library.\n *\n * Each code is an individual export so that unused codes are tree-shaken\n * from bundles that don't reference them (esbuild can't tree-shake\n * properties from a single object).\n *\n * Naming: TBW + 3-digit number.\n * Ranges:\n * 001–019 Configuration validation (missing plugins, bad config)\n * 020–029 Plugin lifecycle (dependencies, incompatibilities, alias collapse)\n * 030–039 Feature registry\n * 040–049 Row operations (row ID, row mutations)\n * 050–059 Column operations (width, template)\n * 060–069 Rendering (callbacks, formatters, external views)\n * 070–079 Shell (tool panels, header/toolbar content)\n * 080–089 Editing & editors\n * 090–099 Print\n * 100–109 Clipboard\n * 110–119 Plugin-specific (responsive, undo-redo, grouping-columns)\n * 120–129 Style injection\n * 130–139 Attribute parsing\n * 140–149 DataSource / ServerSide\n */\n\n// --- Config validation (001–019) ---\n/** Column uses a plugin-owned property but the plugin is not loaded. */\nexport const MISSING_PLUGIN = 'TBW001' as const;\n/** Grid config uses a plugin-owned property but the plugin is not loaded. */\nexport const MISSING_PLUGIN_CONFIG = 'TBW002' as const;\n/** Plugin config rule violation (error severity). */\nexport const CONFIG_RULE_ERROR = 'TBW003' as const;\n/** Plugin config rule violation (warning severity). */\nexport const CONFIG_RULE_WARN = 'TBW004' as const;\n\n// --- Plugin lifecycle (020–029) ---\n/** Required plugin dependency is missing. */\nexport const MISSING_DEPENDENCY = 'TBW020' as const;\n/** Optional plugin dependency is missing. */\nexport const OPTIONAL_DEPENDENCY = 'TBW021' as const;\n/** Two loaded plugins are incompatible. */\nexport const INCOMPATIBLE_PLUGINS = 'TBW022' as const;\n/** Two plugin instances resolve to the same canonical name (alias collapse). */\nexport const PLUGIN_ALIAS_COLLAPSE = 'TBW023' as const;\n/** Error thrown inside a plugin event handler. */\nexport const PLUGIN_EVENT_ERROR = 'TBW024' as const;\n/** Conflicting config values found while merging alias-collapsed plugin instances. */\nexport const PLUGIN_ALIAS_CONFIG_CONFLICT = 'TBW025' as const;\n\n// --- Feature registry (030–039) ---\n/** Feature was re-registered (overwritten). */\nexport const FEATURE_REREGISTERED = 'TBW030' as const;\n/** Feature configured but not imported. */\nexport const FEATURE_NOT_IMPORTED = 'TBW031' as const;\n/** Feature depends on another feature that is not enabled. */\nexport const FEATURE_MISSING_DEP = 'TBW032' as const;\n\n// --- Row operations (040–049) ---\n/** Cannot determine row ID (no getRowId and no id property). */\nexport const MISSING_ROW_ID = 'TBW040' as const;\n/** Row with given ID not found. */\nexport const ROW_NOT_FOUND = 'TBW041' as const;\n\n// --- Column operations (050–059) ---\n/** Column has an invalid CSS width value. */\nexport const INVALID_COLUMN_WIDTH = 'TBW050' as const;\n\n// --- Rendering callbacks (060–069) ---\n/** rowClass callback threw an error. */\nexport const ROW_CLASS_ERROR = 'TBW060' as const;\n/** cellClass callback threw an error. */\nexport const CELL_CLASS_ERROR = 'TBW061' as const;\n/** Column format function threw an error. */\nexport const FORMAT_ERROR = 'TBW062' as const;\n/** External view mount() threw an error. */\nexport const VIEW_MOUNT_ERROR = 'TBW063' as const;\n/** External view event dispatch error. */\nexport const VIEW_DISPATCH_ERROR = 'TBW064' as const;\n\n// --- Shell (070–079) ---\n/** Tool panel missing required id. */\nexport const TOOL_PANEL_MISSING_ATTR = 'TBW070' as const;\n/** No tool panels registered. */\nexport const NO_TOOL_PANELS = 'TBW071' as const;\n/** Tool panel section not found. */\nexport const TOOL_PANEL_NOT_FOUND = 'TBW072' as const;\n/** Tool panel already registered. */\nexport const TOOL_PANEL_DUPLICATE = 'TBW073' as const;\n/** Header content already registered. */\nexport const HEADER_CONTENT_DUPLICATE = 'TBW074' as const;\n/** Toolbar content already registered. */\nexport const TOOLBAR_CONTENT_DUPLICATE = 'TBW075' as const;\n\n// --- Editing & editors (080–089) ---\n/** External editor mount() threw an error. */\nexport const EDITOR_MOUNT_ERROR = 'TBW080' as const;\n\n// --- Print (090–099) ---\n/** Print already in progress. */\nexport const PRINT_IN_PROGRESS = 'TBW090' as const;\n/** Grid not available for printing. */\nexport const PRINT_NO_GRID = 'TBW091' as const;\n/** Print operation failed. */\nexport const PRINT_FAILED = 'TBW092' as const;\n/** Multiple elements share the same grid ID (print isolation issue). */\nexport const PRINT_DUPLICATE_ID = 'TBW093' as const;\n\n// --- Clipboard (100–109) ---\n/** Clipboard API write failed. */\nexport const CLIPBOARD_FAILED = 'TBW100' as const;\n\n// --- Plugin-specific (110–119) ---\n/** ResponsivePlugin: no breakpoint configured. */\nexport const MISSING_BREAKPOINT = 'TBW110' as const;\n/** UndoRedoPlugin: transaction already in progress. */\nexport const TRANSACTION_IN_PROGRESS = 'TBW111' as const;\n/** UndoRedoPlugin: no transaction in progress. */\nexport const NO_TRANSACTION = 'TBW112' as const;\n/** GroupingColumnsPlugin: missing id or header on column group definition. */\nexport const COLUMN_GROUP_NO_ID = 'TBW113' as const;\n/** GroupingColumnsPlugin: conflicting columnGroups sources. */\nexport const COLUMN_GROUPS_CONFLICT = 'TBW114' as const;\n\n// --- Style injection (120–129) ---\n/** Failed to extract grid.css from document stylesheets. */\nexport const STYLE_EXTRACT_FAILED = 'TBW120' as const;\n/** Could not find grid.css in document.styleSheets. */\nexport const STYLE_NOT_FOUND = 'TBW121' as const;\n\n// --- Attribute parsing (130–139) ---\n/** Invalid JSON in an HTML attribute. */\nexport const INVALID_ATTRIBUTE_JSON = 'TBW130' as const;\n\n// --- DataSource / ServerSide (140–149) ---\n/** ServerSidePlugin: getRows() rejected. */\nexport const DATASOURCE_FETCH_ERROR = 'TBW140' as const;\n/** ServerSidePlugin: getChildRows() rejected. */\nexport const DATASOURCE_CHILD_FETCH_ERROR = 'TBW141' as const;\n/** ServerSidePlugin: getChildRows() not implemented but a plugin queried for children. */\nexport const DATASOURCE_NO_CHILD_HANDLER = 'TBW142' as const;\n/** ServerSidePlugin: concurrent request limit reached, request deferred. */\nexport const DATASOURCE_THROTTLED = 'TBW143' as const;\n\nexport type DiagnosticCode =\n | typeof MISSING_PLUGIN\n | typeof MISSING_PLUGIN_CONFIG\n | typeof CONFIG_RULE_ERROR\n | typeof CONFIG_RULE_WARN\n | typeof MISSING_DEPENDENCY\n | typeof OPTIONAL_DEPENDENCY\n | typeof INCOMPATIBLE_PLUGINS\n | typeof PLUGIN_ALIAS_COLLAPSE\n | typeof PLUGIN_EVENT_ERROR\n | typeof PLUGIN_ALIAS_CONFIG_CONFLICT\n | typeof FEATURE_REREGISTERED\n | typeof FEATURE_NOT_IMPORTED\n | typeof FEATURE_MISSING_DEP\n | typeof MISSING_ROW_ID\n | typeof ROW_NOT_FOUND\n | typeof INVALID_COLUMN_WIDTH\n | typeof ROW_CLASS_ERROR\n | typeof CELL_CLASS_ERROR\n | typeof FORMAT_ERROR\n | typeof VIEW_MOUNT_ERROR\n | typeof VIEW_DISPATCH_ERROR\n | typeof TOOL_PANEL_MISSING_ATTR\n | typeof NO_TOOL_PANELS\n | typeof TOOL_PANEL_NOT_FOUND\n | typeof TOOL_PANEL_DUPLICATE\n | typeof HEADER_CONTENT_DUPLICATE\n | typeof TOOLBAR_CONTENT_DUPLICATE\n | typeof EDITOR_MOUNT_ERROR\n | typeof PRINT_IN_PROGRESS\n | typeof PRINT_NO_GRID\n | typeof PRINT_FAILED\n | typeof PRINT_DUPLICATE_ID\n | typeof CLIPBOARD_FAILED\n | typeof MISSING_BREAKPOINT\n | typeof TRANSACTION_IN_PROGRESS\n | typeof NO_TRANSACTION\n | typeof COLUMN_GROUP_NO_ID\n | typeof COLUMN_GROUPS_CONFLICT\n | typeof STYLE_EXTRACT_FAILED\n | typeof STYLE_NOT_FOUND\n | typeof INVALID_ATTRIBUTE_JSON\n | typeof DATASOURCE_FETCH_ERROR\n | typeof DATASOURCE_CHILD_FETCH_ERROR\n | typeof DATASOURCE_NO_CHILD_HANDLER\n | typeof DATASOURCE_THROTTLED;\n\n// #endregion\n\n// #region Docs URL\n\nconst DOCS_BASE = 'https://toolboxjs.com/grid/errors';\n\n/** Build a direct link to the troubleshooting section for a code. */\nfunction docsUrl(code: DiagnosticCode): string {\n return `${DOCS_BASE}#${code.toLowerCase()}`;\n}\n\n// #endregion\n\n// #region Formatting\n\n/**\n * Format a diagnostic message with prefix, code, and docs link.\n *\n * Output format:\n * ```\n * [tbw-grid#my-id] TBW001: Your message here.\n *\n * → More info: https://toolboxjs.com/grid/errors#tbw001\n * ```\n */\nexport function formatDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): string {\n const prefix = gridPrefix(gridId, pluginName);\n return `${prefix} ${code}: ${message}\\n\\n → More info: ${docsUrl(code)}`;\n}\n\n// #endregion\n\n// #region Public API\n\n/**\n * Throw an error with a diagnostic code and docs link.\n * Use for configuration errors and API misuse that should halt execution.\n */\nexport function throwDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): never {\n throw new Error(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log a warning with a diagnostic code and docs link.\n * Use for recoverable issues the developer should fix.\n */\nexport function warnDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.warn(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log a debug message with a diagnostic code and docs link.\n * Use for optional/soft dependency notifications — visible only when\n * the browser DevTools \"Verbose\" log level is enabled.\n */\nexport function debugDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.debug(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log an error with a diagnostic code and docs link.\n * Use for non-throwing errors (e.g., failed async operations).\n */\nexport function errorDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.error(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n// #endregion\n","/**\n * Base Grid Plugin Class\n *\n * All plugins extend this abstract class.\n * Plugins are instantiated per-grid and manage their own state.\n */\n\n// Injected by Vite at build time from package.json (same as grid.ts)\ndeclare const __GRID_VERSION__: string;\n\nimport type { HeaderContentDefinition, ToolPanelDefinition } from '../../plugins/shell/types';\nimport { DEFAULT_GRID_ICONS } from '../defaults';\nimport {\n type DiagnosticCode,\n PLUGIN_ALIAS_CONFIG_CONFLICT,\n formatDiagnostic,\n gridPrefix,\n} from '../internal/diagnostics';\nimport { setSanitizedHTML } from '../internal/sanitize';\nimport type {\n ColumnConfig,\n ColumnState,\n GridConfig,\n GridIcons,\n GridPlugin,\n IconValue,\n PluginNameMap,\n Translate,\n} from '../types';\n\n// Re-export shared plugin types for convenience\nexport type {\n AfterCellRenderContext,\n AfterRowRenderContext,\n CellClickEvent,\n CellCoords,\n CellEditor,\n CellMouseEvent,\n CellRenderer,\n ContextMenuItem,\n ContextMenuParams,\n GridElementRef,\n HeaderClickEvent,\n HeaderRenderer,\n KeyboardModifiers,\n PluginCellRenderContext,\n PluginQuery,\n RowClickEvent,\n ScrollEvent,\n} from './types';\n\nimport type {\n AfterCellRenderContext,\n AfterRowRenderContext,\n CellClickEvent,\n CellEditor,\n CellMouseEvent,\n CellRenderer,\n GridElementRef,\n HeaderClickEvent,\n HeaderRenderer,\n PluginQuery,\n RowClickEvent,\n ScrollEvent,\n} from './types';\n\n/**\n * Grid element interface for plugins.\n * Extends GridElementRef with plugin-specific methods.\n * Note: effectiveConfig is already available from GridElementRef.\n */\nexport interface GridElement extends GridElementRef {\n getPlugin<T extends GridPlugin>(PluginClass: new (...args: any[]) => T): T | undefined;\n getPluginByName<K extends string>(\n name: K,\n ): (K extends keyof PluginNameMap ? PluginNameMap[K] : BaseGridPlugin) | undefined;\n /**\n * Get a plugin's state by plugin name.\n * This is a loose-coupling method for plugins to access other plugins' state\n * without importing the plugin class directly.\n * @internal Plugin API\n */\n getPluginState?(name: string): unknown;\n\n // Focus Management\n /** Register an external DOM element as a logical focus container. @internal Plugin API */\n registerExternalFocusContainer?(el: Element): void;\n /** Unregister a previously registered external focus container. @internal Plugin API */\n unregisterExternalFocusContainer?(el: Element): void;\n /** Check whether focus is logically inside this grid (own DOM + external containers). @internal Plugin API */\n containsFocus?(node?: Node | null): boolean;\n}\n\n/**\n * Header render context for plugin header renderers.\n */\nexport interface PluginHeaderRenderContext {\n /** Column configuration */\n column: ColumnConfig;\n /** Column index */\n colIndex: number;\n}\n\n// ============================================================================\n// Plugin Dependency Types\n// ============================================================================\n\n/**\n * Declares a dependency on another plugin.\n *\n * @category Plugin Development\n * @example\n * ```typescript\n * export class UndoRedoPlugin extends BaseGridPlugin {\n * static readonly dependencies: PluginDependency[] = [\n * { name: 'editing', required: true },\n * ];\n * }\n * ```\n * @since 0.4.1\n */\nexport interface PluginDependency {\n /**\n * The name of the required plugin (matches the plugin's `name` property).\n * Use string names for loose coupling - avoids static imports.\n */\n name: string;\n\n /**\n * Whether this dependency is required (hard) or optional (soft).\n * - `true`: Plugin cannot function without it. Throws error if missing.\n * - `false`: Plugin works with reduced functionality. Silent if missing\n * (set {@link severity} to `'warn'` or `'info'` to opt into a message).\n * @default true\n */\n required?: boolean;\n\n /**\n * Explicit severity when this dependency is missing. Overrides the default\n * derived from {@link required}.\n * - `'error'`: throw (halts grid setup). Default when `required` is not `false`.\n * - `'warn'`: log a console warning and continue (development only).\n * - `'info'`: log a verbose console.debug message and continue (development only).\n *\n * When omitted, a missing hard dependency throws and a missing soft\n * dependency is silent — preserving backward-compatible behavior.\n * @since 2.16.0\n */\n severity?: 'error' | 'warn' | 'info';\n\n /**\n * Optional predicate that gates whether this dependency applies, evaluated\n * against the depending plugin's own resolved configuration (defaults merged\n * with user config). Return `false` to skip the dependency entirely.\n *\n * Lets a plugin require/recommend another plugin only under certain config\n * — e.g. a plugin that needs a tool-panel host only when its tool panel is\n * enabled. When omitted, the dependency always applies.\n * @example when: (cfg: PivotConfig) => cfg.showToolPanel === true\n * @since 2.16.0\n */\n when?: (pluginConfig: unknown) => boolean;\n\n /**\n * Human-readable reason for this dependency.\n * Shown in error/info messages to help users understand why.\n * @example \"UndoRedoPlugin needs EditingPlugin to track cell edits\"\n */\n reason?: string;\n}\n\n/**\n * Declares an incompatibility between plugins.\n * When both plugins are loaded, a warning is logged to help users understand the conflict.\n *\n * @category Plugin Development\n */\nexport interface PluginIncompatibility {\n /**\n * The name of the incompatible plugin (matches the plugin's `name` property).\n */\n name: string;\n\n /**\n * Human-readable reason for the incompatibility.\n * Should explain why the plugins conflict and any workarounds.\n * @example \"Both transform the entire row model in different ways\"\n */\n reason: string;\n}\n\n// ============================================================================\n// Plugin Query & Event Definitions\n// ============================================================================\n\n/**\n * Defines a query that a plugin can handle.\n * Other plugins or the grid can send this query type to retrieve data.\n *\n * @category Plugin Development\n *\n * @example\n * ```typescript\n * // In manifest\n * queries: [\n * {\n * type: 'canMoveColumn',\n * description: 'Check if a column can be moved/reordered',\n * },\n * ]\n *\n * // In plugin class\n * handleQuery(query: PluginQuery): unknown {\n * if (query.type === 'canMoveColumn') {\n * return this.canMoveColumn(query.context);\n * }\n * }\n * ```\n * @since 1.8.0\n */\nexport interface QueryDefinition {\n /**\n * The query type identifier (e.g., 'canMoveColumn', 'getContextMenuItems').\n * Should be unique across all plugins.\n */\n type: string;\n\n /**\n * Human-readable description of what the query does.\n */\n description?: string;\n}\n\n/**\n * Defines an event that a plugin can emit.\n * Other plugins can subscribe to these events via the Event Bus.\n *\n * @category Plugin Development\n *\n * @example\n * ```typescript\n * // In manifest\n * events: [\n * {\n * type: 'filter-change',\n * description: 'Emitted when filter criteria change',\n * },\n * ]\n *\n * // In plugin class - emit\n * this.emitPluginEvent('filter-change', { field: 'name', value: 'Alice' });\n *\n * // In another plugin - subscribe\n * this.on('filter-change', (detail) => console.log('Filter changed:', detail));\n * ```\n * @since 1.8.0\n */\nexport interface EventDefinition {\n /**\n * The event type identifier (e.g., 'filter-change', 'selection-change').\n * Used when emitting and subscribing to events.\n */\n type: string;\n\n /**\n * Human-readable description of what the event represents.\n */\n description?: string;\n\n /**\n * Whether this event is cancelable via `event.preventDefault()`.\n * @default false\n */\n cancelable?: boolean;\n}\n\n// ============================================================================\n// Plugin Manifest Types\n// ============================================================================\n\n/**\n * Defines a property that a plugin \"owns\" - used for configuration validation.\n * When this property is used without the owning plugin loaded, an error is thrown.\n *\n * @category Plugin Development\n */\nexport interface PluginPropertyDefinition {\n /** The property name on column or grid config */\n property: string;\n /** Whether this is a column-level or config-level property */\n level: 'column' | 'config';\n /** Human-readable description for error messages (e.g., 'the \"editable\" column property') */\n description: string;\n /** Import path hint for error messages (e.g., \"import { EditingPlugin } from '@toolbox-web/grid/plugins/editing';\") */\n importHint?: string;\n /** Custom check for whether property is considered \"used\" (default: truthy value check) */\n isUsed?: (value: unknown) => boolean;\n}\n\n/**\n * A configuration validation rule for detecting invalid/conflicting settings.\n * Plugins declare rules in their manifest; the validator executes them during grid initialization.\n *\n * @category Plugin Development\n * @template TConfig - The plugin's configuration type\n */\nexport interface PluginConfigRule<TConfig = unknown> {\n /** Rule identifier for debugging (e.g., 'selection/range-dblclick') */\n id: string;\n /** Severity: 'error' throws, 'warn' logs warning */\n severity: 'error' | 'warn';\n /** Human-readable message shown when rule is violated */\n message: string;\n /** Predicate returning true if the rule is VIOLATED (i.e., config is invalid) */\n check: (pluginConfig: TConfig) => boolean;\n}\n\n/**\n * Hook names that can have execution priority configured.\n *\n * @category Plugin Development\n */\nexport type HookName =\n | 'processColumns'\n | 'processConfig'\n | 'processRows'\n | 'afterStructuralRender'\n | 'afterRender'\n | 'afterCellRender'\n | 'afterRowRender'\n | 'onCellClick'\n | 'onCellMouseDown'\n | 'onCellMouseMove'\n | 'onCellMouseUp'\n | 'onHeaderClick'\n | 'onKeyDown'\n | 'onRowClick'\n | 'onScroll'\n | 'onScrollRender';\n\n/**\n * Static metadata about a plugin's capabilities and requirements.\n * Declared as a static property on plugin classes.\n *\n * @category Plugin Development\n * @template TConfig - The plugin's configuration type\n *\n * @example\n * ```typescript\n * export class MyPlugin extends BaseGridPlugin<MyConfig> {\n * static override readonly manifest: PluginManifest<MyConfig> = {\n * ownedProperties: [\n * { property: 'myProp', level: 'column', description: 'the \"myProp\" column property' },\n * ],\n * configRules: [\n * { id: 'my-plugin/invalid-combo', severity: 'warn', message: '...', check: (c) => c.a && c.b },\n * ],\n * };\n * readonly name = 'myPlugin';\n * }\n * ```\n * @since 1.1.0\n */\nexport interface PluginManifest<TConfig = unknown> {\n /**\n * Properties this plugin owns - validated by validate-config.ts.\n * If a user uses one of these properties without loading the plugin, an error is thrown.\n */\n ownedProperties?: PluginPropertyDefinition[];\n\n /**\n * Hook execution priority (higher = later, default 0).\n * Use negative values to run earlier, positive to run later.\n */\n hookPriority?: Partial<Record<HookName, number>>;\n\n /**\n * Configuration validation rules - checked during grid initialization.\n * Rules with severity 'error' throw, 'warn' logs to console.\n */\n configRules?: PluginConfigRule<TConfig>[];\n\n /**\n * Plugins that are incompatible with this plugin.\n * When both plugins are loaded together, a warning is shown.\n *\n * @example\n * ```typescript\n * incompatibleWith: [\n * { name: 'tree', reason: 'Both transform the entire row model in different ways' },\n * ],\n * ```\n */\n incompatibleWith?: PluginIncompatibility[];\n\n /**\n * Queries this plugin can handle.\n * Declares what query types this plugin responds to via `handleQuery()`.\n * This replaces the centralized PLUGIN_QUERIES approach with manifest-declared queries.\n *\n * @example\n * ```typescript\n * queries: [\n * { type: 'canMoveColumn', description: 'Check if a column can be moved' },\n * ],\n * ```\n */\n queries?: QueryDefinition[];\n\n /**\n * Events this plugin can emit.\n * Declares what event types other plugins can subscribe to via `on()`.\n *\n * @example\n * ```typescript\n * events: [\n * { type: 'filter-change', description: 'Emitted when filter criteria change' },\n * ],\n * ```\n */\n events?: EventDefinition[];\n\n /**\n * Whether this plugin's `processRows` hook injects or removes rows\n * (group headers, tree nodes, pivot aggregates, placeholders, etc.).\n *\n * When true, the core sorting module delegates to the render scheduler\n * instead of sorting `_rows` in-place, because `_rows` may contain\n * plugin-generated marker objects that would be corrupted by a direct sort.\n *\n * Plugins that only **filter** or **reorder** existing rows (e.g. Filtering,\n * MultiSort) should leave this unset or set it to `false`.\n */\n modifiesRowStructure?: boolean;\n}\n\n/** Convert camelCase icon key to kebab-case data-icon attribute value. */\nexport function toIconAttr(key: string): string {\n return key.replace(/([A-Z])/g, '-$1').toLowerCase();\n}\n\n/**\n * Abstract base class for all grid plugins.\n *\n * @category Plugin Development\n * @template TConfig - Configuration type for the plugin\n * @since 0.1.1\n */\nexport abstract class BaseGridPlugin<TConfig = unknown> implements GridPlugin {\n /**\n * Plugin dependencies - declare other plugins this one requires.\n *\n * Dependencies are validated when the plugin is attached.\n * Required dependencies throw an error if missing. Optional dependencies are\n * silent by default; set a {@link PluginDependency.severity} of `'warn'` or\n * `'info'` to opt into a development-only log.\n *\n * @example\n * ```typescript\n * static readonly dependencies: PluginDependency[] = [\n * { name: 'editing', required: true, reason: 'Tracks cell edits for undo/redo' },\n * { name: 'selection', required: false, reason: 'Enables selection-based undo' },\n * ];\n * ```\n */\n static readonly dependencies?: PluginDependency[];\n\n /**\n * Plugin manifest - declares owned properties, config rules, and hook priorities.\n *\n * This is read by the configuration validator to:\n * - Validate that required plugins are loaded when their properties are used\n * - Execute configRules to detect invalid/conflicting settings\n * - Order hook execution based on priority\n *\n * @example\n * ```typescript\n * static override readonly manifest: PluginManifest<MyConfig> = {\n * ownedProperties: [\n * { property: 'myProp', level: 'column', description: 'the \"myProp\" column property' },\n * ],\n * configRules: [\n * { id: 'myPlugin/conflict', severity: 'warn', message: '...', check: (c) => c.a && c.b },\n * ],\n * };\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static readonly manifest?: PluginManifest<any>;\n\n /** Unique plugin identifier (derived from class name by default) */\n abstract readonly name: string;\n\n /**\n * Alternative names for backward compatibility.\n * `getPluginByName()` matches against both `name` and `aliases`.\n * @internal\n */\n readonly aliases?: readonly string[];\n\n /**\n * Plugin version - defaults to grid version for built-in plugins.\n * Third-party plugins can override with their own semver.\n */\n readonly version: string = typeof __GRID_VERSION__ !== 'undefined' ? __GRID_VERSION__ : 'dev';\n\n /** CSS styles to inject via `document.adoptedStyleSheets` */\n readonly styles?: string;\n\n /** Custom cell renderers keyed by type name */\n readonly cellRenderers?: Record<string, CellRenderer>;\n\n /** Custom header renderers keyed by type name */\n readonly headerRenderers?: Record<string, HeaderRenderer>;\n\n /** Custom cell editors keyed by type name */\n readonly cellEditors?: Record<string, CellEditor>;\n\n /** The grid instance this plugin is attached to */\n protected grid!: GridElement;\n\n /** Plugin configuration - merged with defaults in attach() */\n protected config!: TConfig;\n\n /** User-provided configuration from constructor */\n protected readonly userConfig: Partial<TConfig>;\n\n /**\n * Plugin-level AbortController for event listener cleanup.\n * Created fresh in attach(), aborted in detach().\n * This ensures event listeners are properly cleaned up when plugins are re-attached.\n */\n #abortController?: AbortController;\n\n /**\n * Default configuration - subclasses should override this getter.\n * Note: This must be a getter (not property initializer) for proper inheritance\n * since property initializers run after parent constructor.\n */\n protected get defaultConfig(): Partial<TConfig> {\n return {};\n }\n\n constructor(config: Partial<TConfig> = {}) {\n this.userConfig = config;\n }\n\n /**\n * Effective configuration (defaults merged with user config), resolved\n * eagerly so it is available **before** {@link attach} runs. Dependency\n * validation happens before `attach()` merges {@link config}, so config\n * -conditional dependency `when` predicates evaluate against this getter.\n *\n * While attached, returns the already-merged {@link config}; otherwise\n * recomputes `defaultConfig` + `userConfig` fresh. `config` is intentionally\n * **not** trusted when detached because {@link detach} does not clear it — a\n * re-validated plugin would otherwise see stale config from a prior\n * attachment. The {@link attach}-managed abort controller is the\n * attached/detached signal.\n * @internal Plugin infrastructure (used by `validatePluginDependencies`).\n */\n get resolvedConfig(): TConfig {\n return (this.#abortController ? this.config : { ...this.defaultConfig, ...this.userConfig }) as TConfig;\n }\n\n /**\n * Merge user-supplied configuration from other plugin instances into this\n * plugin's `userConfig`. Used by `PluginManager.attachAll()`'s alias-collapse\n * pre-pass: when a consumer instantiates the same plugin more than once (or\n * under an alias name), only one instance is attached, and the other\n * instances' configs are folded in via this method.\n *\n * Merge rules (shallow):\n *\n * - Same key, **same value** → silent.\n * - Same key, **different values** (incl. function vs function) → throws\n * a diagnostic naming the conflicting key. Conflicting callbacks\n * (`canDrag`, `canDrop`, etc.) cannot be reconciled automatically.\n * - **Disjoint keys** → merged cleanly.\n *\n * Subclasses may override to implement custom deep-merge logic, but should\n * call `super.mergeConfigsFrom(others)` to inherit the conflict-detection.\n *\n * @internal Plugin infrastructure (used by `PluginManager.attachAll`).\n * @throws Error with diagnostic code `TBW025` when configs conflict.\n */\n mergeConfigsFrom(others: readonly BaseGridPlugin<TConfig>[]): void {\n if (others.length === 0) return;\n const merged = { ...this.userConfig } as Record<string, unknown>;\n const sources: Record<string, BaseGridPlugin<TConfig>> = {};\n for (const key of Object.keys(merged)) sources[key] = this;\n for (const other of others) {\n const otherConfig = other.userConfig as Record<string, unknown>;\n for (const [key, value] of Object.entries(otherConfig)) {\n if (value === undefined) continue;\n if (!(key in merged)) {\n merged[key] = value;\n sources[key] = other;\n continue;\n }\n if (merged[key] === value) continue;\n // Conflict\n const ownerA = sources[key]?.constructor.name ?? this.constructor.name;\n const ownerB = other.constructor.name;\n const code = formatDiagnostic(\n PLUGIN_ALIAS_CONFIG_CONFLICT,\n `Cannot merge plugin configs for \"${this.name}\": conflicting value for \"${key}\" supplied by both ${ownerA} and ${ownerB}. Pass the option on a single instance, or remove the duplicate.`,\n undefined,\n this.name,\n );\n throw new Error(code);\n }\n }\n // Mutate userConfig in place so re-attach picks it up via attach().\n // `userConfig` is declared `readonly` to prevent reassigning the binding,\n // but the object's own properties are intentionally mutable for this\n // alias-collapse pre-pass. A single cast to a record is enough — no\n // `as unknown as` double-cast needed.\n Object.assign(this.userConfig as Record<string, unknown>, merged);\n }\n\n /**\n * Replace this plugin's `userConfig` with a freshly-resolved sibling\n * instance's config. Used by the grid's per-grid feature-instance gate\n * (`#initializePlugins`): when a feature is re-resolved across a config\n * change, the **existing** instance is reused — so its accumulated state\n * survives — but it must adopt the latest `gridConfig.features.<name>`\n * value. Unlike {@link mergeConfigsFrom}, this is last-write-wins with no\n * conflict detection: the re-resolved instance is authoritative.\n *\n * `attach()` recomputes {@link config} from `userConfig`, so updating\n * `userConfig` here is enough for the reused instance to pick up the new\n * config on its next attach during the same `#initializePlugins` pass.\n *\n * @internal Plugin infrastructure (used by the grid feature gate).\n */\n refreshUserConfigFrom(other: BaseGridPlugin<TConfig>): void {\n const target = this.userConfig as Record<string, unknown>;\n // Snapshot the source BEFORE clearing `target`. A feature factory may\n // store the consumer's config object by reference (e.g. `new\n // ContextMenuPlugin(config)`), and a consumer that passes the *same* config\n // object across re-resolutions (common when `gridConfig` is a recomputed\n // Angular `computed()`) makes `this.userConfig === other.userConfig`.\n // Without this snapshot, the `delete` loop below would empty that shared\n // object first, then `Object.assign` would copy back nothing — silently\n // wiping the config and falling back to plugin defaults. (#contextMenu)\n const source = { ...(other.userConfig as Record<string, unknown>) };\n for (const key of Object.keys(target)) delete target[key];\n Object.assign(target, source);\n }\n\n /**\n * Called when the plugin is attached to a grid.\n * Override to set up event listeners, initialize state, etc.\n *\n * @example\n * ```ts\n * attach(grid: GridElement): void {\n * super.attach(grid);\n * // Set up document-level listeners with auto-cleanup\n * document.addEventListener('keydown', this.handleEscape, {\n * signal: this.disconnectSignal\n * });\n * }\n * ```\n */\n attach(grid: GridElement): void {\n // Abort any previous abort controller (in case of re-attach without detach)\n this.#abortController?.abort();\n // Create fresh abort controller for this attachment\n this.#abortController = new AbortController();\n\n this.grid = grid;\n // Merge config here (after subclass construction is complete)\n this.config = { ...this.defaultConfig, ...this.userConfig } as TConfig;\n }\n\n /**\n * Called when the plugin is detached from a grid.\n * Override to clean up event listeners, timers, etc.\n *\n * @example\n * ```ts\n * detach(): void {\n * // Clean up any state not handled by disconnectSignal\n * this.selectedRows.clear();\n * this.cache = null;\n * }\n * ```\n */\n detach(): void {\n // Abort the plugin's abort controller to clean up all event listeners\n // registered with { signal: this.disconnectSignal }\n this.#abortController?.abort();\n this.#abortController = undefined;\n // Override in subclass for additional cleanup\n }\n\n /**\n * Called when another plugin is attached to the same grid.\n * Use for inter-plugin coordination, e.g., to integrate with new plugins.\n *\n * @param name - The name of the plugin that was attached\n * @param plugin - The plugin instance (for direct access if needed)\n *\n * @example\n * ```ts\n * onPluginAttached(name: string, plugin: BaseGridPlugin): void {\n * if (name === 'selection') {\n * // Integrate with selection plugin\n * this.selectionPlugin = plugin as SelectionPlugin;\n * }\n * }\n * ```\n */\n onPluginAttached?(name: string, plugin: BaseGridPlugin): void;\n\n /**\n * Called when another plugin is detached from the same grid.\n * Use to clean up inter-plugin references.\n *\n * @param name - The name of the plugin that was detached\n *\n * @example\n * ```ts\n * onPluginDetached(name: string): void {\n * if (name === 'selection') {\n * this.selectionPlugin = undefined;\n * }\n * }\n * ```\n */\n onPluginDetached?(name: string): void;\n\n /**\n * Get another plugin instance from the same grid.\n * Use for inter-plugin communication.\n *\n * **Prefer {@link BaseGridPlugin.grid grid.getPluginByName()}** when you don't need the class import.\n *\n * @example\n * ```ts\n * // Preferred: by name\n * const selection = this.grid?.getPluginByName('selection');\n *\n * // Alternative: by class\n * const selection = this.getPlugin(SelectionPlugin);\n * if (selection) {\n * const selectedRows = selection.getSelectedRows();\n * }\n * ```\n */\n protected getPlugin<T extends BaseGridPlugin>(PluginClass: new (...args: any[]) => T): T | undefined {\n return this.grid?.getPlugin(PluginClass);\n }\n\n /**\n * Emit a custom event from the grid.\n */\n protected emit<T>(eventName: string, detail: T): void {\n this.grid?.dispatchEvent?.(new CustomEvent(eventName, { detail, bubbles: true }));\n }\n\n /**\n * Emit a cancelable custom event from the grid.\n * @returns `true` if the event was cancelled (preventDefault called), `false` otherwise\n */\n protected emitCancelable<T>(eventName: string, detail: T): boolean {\n const event = new CustomEvent(eventName, { detail, bubbles: true, cancelable: true });\n this.grid?.dispatchEvent?.(event);\n return event.defaultPrevented;\n }\n\n // =========================================================================\n // Event Bus - Plugin-to-Plugin Communication\n // =========================================================================\n\n /**\n * Subscribe to an event from another plugin.\n * The subscription is automatically cleaned up when this plugin is detached.\n *\n * @category Plugin Development\n * @param eventType - The event type to listen for (e.g., 'filter-change')\n * @param callback - The callback to invoke when the event is emitted\n *\n * @example\n * ```typescript\n * // In attach() or other initialization\n * this.on('filter-change', (detail) => {\n * console.log('Filter changed:', detail);\n * });\n * ```\n */\n protected on<T = unknown>(eventType: string, callback: (detail: T) => void): void {\n this.grid?._pluginManager?.subscribe(this, eventType, callback as (detail: unknown) => void);\n }\n\n /**\n * Unsubscribe from a plugin event.\n *\n * @category Plugin Development\n * @param eventType - The event type to stop listening for\n *\n * @example\n * ```typescript\n * this.off('filter-change');\n * ```\n */\n protected off(eventType: string): void {\n this.grid?._pluginManager?.unsubscribe(this, eventType);\n }\n\n /**\n * Emit an event to other plugins via the Event Bus.\n * This is for inter-plugin communication only; it does NOT dispatch DOM events.\n * Use `emit()` to dispatch DOM events that external consumers can listen to.\n *\n * @category Plugin Development\n * @param eventType - The event type to emit (should be declared in manifest.events)\n * @param detail - The event payload\n *\n * @example\n * ```typescript\n * // Emit to other plugins (not DOM)\n * this.emitPluginEvent('filter-change', { field: 'name', value: 'Alice' });\n *\n * // For DOM events that consumers can addEventListener to:\n * this.emit('filter-change', { field: 'name', value: 'Alice' });\n * ```\n */\n protected emitPluginEvent<T>(eventType: string, detail: T): void {\n this.grid?._pluginManager?.emitPluginEvent(eventType, detail);\n }\n\n /**\n * Emit an event to **both** the plugin Event Bus (for inter-plugin communication)\n * **and** the DOM (for external consumers via `addEventListener`).\n *\n * Use this when a state change is relevant to both other plugins and external\n * consumers. For example, `sort-change` needs to invalidate Selection (plugin bus)\n * and notify the host application (DOM event).\n *\n * @category Plugin Development\n * @param eventType - The event type to broadcast\n * @param detail - The event payload\n *\n * @example\n * ```typescript\n * // Notify both plugins and consumers of a sort change\n * this.broadcast('sort-change', { sortModel: [...this.sortModel] });\n * ```\n */\n protected broadcast<T>(eventType: string, detail: T): void {\n this.emitPluginEvent(eventType, detail);\n this.emit(eventType, detail);\n }\n\n /**\n * Run a yes/no plugin query and reduce the responses to a single boolean.\n *\n * `grid.query()` always returns an **array** of responses (empty when no\n * plugin handles the query), and `[]` is truthy in JavaScript — so testing\n * the raw result directly (`if (grid.query(...))`) is always `true` and\n * silently takes the \"some plugin said yes\" branch even when nothing\n * answered. Always route boolean queries through this helper.\n *\n * @category Plugin Development\n * @param type - The query type to dispatch\n * @param context - Optional query context passed to the handlers\n * @returns `true` only when at least one plugin answered truthily\n *\n * @example\n * ```typescript\n * if (this.queryBoolean('datasource:is-active')) {\n * // A ServerSide data source really is installed\n * }\n * ```\n * @since 3.4.0\n */\n protected queryBoolean(type: string, context: unknown = null): boolean {\n const responses = this.grid?.query?.(type, context);\n // Tolerate hosts/tests that hand back a bare value instead of the array.\n return Array.isArray(responses) ? responses.some(Boolean) : !!responses;\n }\n\n /**\n * Request a re-render of the grid.\n * Uses ROWS phase - does NOT trigger processColumns hooks.\n */\n protected requestRender(): void {\n this.grid?.requestRender?.();\n }\n\n /**\n * Request a columns re-render of the grid.\n * Uses COLUMNS phase - triggers processColumns hooks.\n * Use this when your plugin needs to reprocess column configuration.\n */\n protected requestColumnsRender(): void {\n (this.grid as { requestColumnsRender?: () => void })?.requestColumnsRender?.();\n }\n\n /**\n * Request a re-render and restore focus styling afterward.\n * Use this when a plugin action (like expand/collapse) triggers a render\n * but needs to maintain keyboard navigation focus.\n */\n protected requestRenderWithFocus(): void {\n this.grid?.requestRenderWithFocus?.();\n }\n\n /**\n * Request a lightweight style update without rebuilding DOM.\n * Use this instead of requestRender() when only CSS classes need updating.\n */\n protected requestAfterRender(): void {\n this.grid?.requestAfterRender?.();\n }\n\n /**\n * Re-render visible rows without rebuilding the row model or recalculating geometry.\n * Use this when row data has been updated in-place (e.g., server-side block loads)\n * and only the visible viewport needs to re-render.\n */\n protected requestVirtualRefresh(): void {\n this.grid?.requestVirtualRefresh?.();\n }\n\n /**\n * Get the current rows from the grid.\n */\n protected get rows(): any[] {\n return this.grid?.rows ?? [];\n }\n\n /**\n * Get the original unfiltered/unprocessed rows from the grid.\n * Use this when you need all source data regardless of active filters.\n */\n protected get sourceRows(): any[] {\n return this.grid?.sourceRows ?? [];\n }\n\n /**\n * Get the current columns from the grid.\n */\n protected get columns(): ColumnConfig[] {\n return this.grid?.columns ?? [];\n }\n\n /**\n * Get only visible columns from the grid (excludes hidden).\n * Use this for rendering that needs to match the grid template.\n */\n protected get visibleColumns(): ColumnConfig[] {\n return this.grid?._visibleColumns ?? [];\n }\n\n /**\n * Get the grid as an HTMLElement for direct DOM operations.\n * Use sparingly - prefer the typed GridElementRef API when possible.\n *\n * @example\n * ```ts\n * const width = this.gridElement.clientWidth;\n * this.gridElement.classList.add('my-plugin-active');\n * ```\n */\n protected get gridElement(): HTMLElement {\n return this.grid?._hostElement;\n }\n\n /**\n * Get the disconnect signal for event listener cleanup.\n * This signal is aborted when the grid disconnects from the DOM.\n * Use this when adding event listeners that should be cleaned up automatically.\n *\n * Best for:\n * - Document/window-level listeners added in attach()\n * - Listeners on the grid element itself\n * - Any listener that should persist across renders\n *\n * Not needed for:\n * - Listeners on elements created in afterRender() (removed with element)\n *\n * @example\n * element.addEventListener('click', handler, { signal: this.disconnectSignal });\n * document.addEventListener('keydown', handler, { signal: this.disconnectSignal });\n */\n protected get disconnectSignal(): AbortSignal {\n // Return the plugin's own abort signal for proper cleanup on detach/re-attach\n // Falls back to grid's signal if plugin's controller not yet created\n return this.#abortController?.signal ?? this.grid?.disconnectSignal;\n }\n\n /**\n * Get the grid-level icons configuration.\n * Returns merged icons (user config + defaults).\n */\n protected get gridIcons(): Required<GridIcons> {\n const userIcons = this.grid?.gridConfig?.icons ?? {};\n return { ...DEFAULT_GRID_ICONS, ...userIcons };\n }\n\n /**\n * Resolve a user-visible string from {@link GridConfig.locale}, falling back to\n * the English default supplied at the call site.\n *\n * The fallback is passed inline rather than read from a shipped default map so\n * that a plugin's strings live in the plugin's own chunk.\n *\n * @param key - Namespaced message id, e.g. `'filter.apply'`.\n * @param fallback - English text used when the key is not overridden.\n * @since 3.5.0\n *\n * @example\n * ```ts\n * applyBtn.textContent = this.t('filter.apply', 'Apply');\n * ```\n */\n protected t(key: string, fallback: string): string {\n return this.grid?.effectiveConfig?.locale?.[key] ?? fallback;\n }\n\n /**\n * A bound `t()` suitable for handing to standalone renderer\n * helpers and public renderer callbacks.\n * @since 3.5.0\n */\n protected get translate(): Translate {\n return (key, fallback) => this.t(key, fallback);\n }\n\n // #region Animation Helpers\n\n /**\n * Check if animations are enabled at the grid level.\n * Respects gridConfig.animation.mode and the CSS variable set by the grid.\n *\n * Plugins should use this to skip animations when:\n * - Animation mode is 'off' or `false`\n * - User prefers reduced motion and mode is 'reduced-motion' (default)\n *\n * @example\n * ```ts\n * private get animationStyle(): 'slide' | 'fade' | false {\n * if (!this.isAnimationEnabled) return false;\n * return this.config.animation ?? 'slide';\n * }\n * ```\n */\n protected get isAnimationEnabled(): boolean {\n const mode = this.grid?.effectiveConfig?.animation?.mode ?? 'reduced-motion';\n\n // Explicit off = disabled\n if (mode === false || mode === 'off') return false;\n\n // Explicit on = always enabled\n if (mode === true || mode === 'on') return true;\n\n // reduced-motion: check CSS variable (set by grid based on media query)\n const host = this.gridElement;\n if (host) {\n const enabled = getComputedStyle(host).getPropertyValue('--tbw-animation-enabled').trim();\n return enabled !== '0';\n }\n\n return true; // Default to enabled\n }\n\n /**\n * Get the animation duration in milliseconds from CSS variable.\n * Falls back to 200ms if not set.\n *\n * Plugins can use this for their animation timing to stay consistent\n * with the grid-level animation.duration setting.\n *\n * @example\n * ```ts\n * element.animate(keyframes, { duration: this.animationDuration });\n * ```\n */\n protected get animationDuration(): number {\n const host = this.gridElement;\n if (host) {\n const durationStr = getComputedStyle(host).getPropertyValue('--tbw-animation-duration').trim();\n const parsed = parseInt(durationStr, 10);\n if (!isNaN(parsed)) return parsed;\n }\n return 200; // Default\n }\n\n // #endregion\n\n /**\n * Set an icon on an element using the CSS-first hybrid approach.\n *\n * Sets `data-icon` for CSS pseudo-element rendering and `data-expanded` for\n * expand/collapse toggle elements. Only injects DOM content when a JS override\n * is present (via `gridConfig.icons` or `pluginOverride`), which naturally\n * suppresses the CSS `::before` via the `:empty` selector.\n *\n * @param element - The element to set the icon on\n * @param iconKey - The icon key in GridIcons (e.g., 'expand', 'collapse')\n * @param pluginOverride - Optional plugin-level override (string or HTMLElement)\n */\n protected setIcon(element: HTMLElement, iconKey: keyof GridIcons, pluginOverride?: IconValue): void {\n // Set data-icon attribute for CSS targeting (always)\n element.dataset.icon = toIconAttr(iconKey);\n\n // Set data-expanded for toggle elements (tree, group, master-detail)\n if (iconKey === 'collapse') {\n element.dataset.expanded = '';\n } else if (iconKey === 'expand') {\n delete element.dataset.expanded;\n }\n\n // Resolve JS-only icon (returns undefined when CSS default should be used)\n const jsIcon = this.#resolveJsIcon(iconKey, pluginOverride);\n\n if (jsIcon !== undefined) {\n // JS override: inject content (suppresses CSS ::before via :empty)\n if (typeof jsIcon === 'string') {\n setSanitizedHTML(element, jsIcon);\n } else if (jsIcon instanceof HTMLElement) {\n element.replaceChildren(jsIcon.cloneNode(true));\n }\n } else {\n // CSS path: ensure element is empty so ::before renders\n element.innerHTML = '';\n }\n }\n\n /**\n * Resolve JS-only icon override. Returns undefined if CSS default should render.\n * Only returns a value when the user explicitly set gridConfig.icons[key] or\n * the plugin passed an override.\n */\n #resolveJsIcon(iconKey: keyof GridIcons, pluginOverride?: IconValue): IconValue | undefined {\n if (pluginOverride !== undefined) return pluginOverride;\n return this.grid?.gridConfig?.icons?.[iconKey];\n }\n\n /**\n * Create or replace a sort indicator on a header cell.\n *\n * Handles the full lifecycle: removes any existing indicator, creates a new\n * `<span part=\"sort-indicator\" class=\"sort-indicator\">` with the appropriate\n * icon, sets `aria-sort` / `data-sort` attributes, and inserts it before the\n * filter button or resize handle.\n *\n * Plugins decide **which** cells and **when** — this method handles **how**.\n *\n * @param cell - The header cell element\n * @param direction - `'asc'` | `'desc'` for sorted, `null` for unsorted idle state\n * @returns The created indicator element (useful for appending badges, etc.)\n */\n protected updateSortIndicator(cell: Element, direction: 'asc' | 'desc' | null): HTMLElement {\n // Remove any existing indicator (core uses part, plugins use class)\n cell.querySelector('[part~=\"sort-indicator\"], .sort-indicator')?.remove();\n\n const indicator = document.createElement('span');\n indicator.setAttribute('part', 'sort-indicator');\n indicator.className = 'sort-indicator';\n\n if (direction) {\n cell.setAttribute('aria-sort', direction === 'asc' ? 'ascending' : 'descending');\n cell.setAttribute('data-sort', direction);\n this.setIcon(indicator, direction === 'asc' ? 'sortAsc' : 'sortDesc');\n } else {\n cell.setAttribute('aria-sort', 'none');\n cell.removeAttribute('data-sort');\n this.setIcon(indicator, 'sortNone');\n }\n\n // Insert before filter button or resize handle to maintain DOM order\n const insertBefore = cell.querySelector('.tbw-filter-btn') ?? cell.querySelector('.resize-handle');\n if (insertBefore) {\n cell.insertBefore(indicator, insertBefore);\n } else {\n cell.appendChild(indicator);\n }\n\n return indicator;\n }\n\n /**\n * Log a warning with an optional diagnostic code.\n *\n * When a diagnostic code is provided, the message is formatted with the code\n * and a link to the troubleshooting docs.\n *\n * @example\n * ```ts\n * this.warn('Something went wrong'); // plain\n * this.warn(MISSING_BREAKPOINT, 'Set a breakpoint'); // with code + docs link\n * ```\n */\n protected warn(message: string): void;\n protected warn(code: DiagnosticCode, message: string): void;\n protected warn(codeOrMessage: DiagnosticCode | string, message?: string): void {\n if (message !== undefined) {\n // Called with (code, message)\n console.warn(formatDiagnostic(codeOrMessage as DiagnosticCode, message, this.gridElement.id, this.name));\n } else {\n // Called with (message) — plain warning, no diagnostic code\n console.warn(`${gridPrefix(this.gridElement.id, this.name)} ${codeOrMessage}`);\n }\n }\n\n /**\n * Throw an error with a diagnostic code and docs link.\n * Use for configuration errors and API misuse that should halt execution.\n */\n protected throwDiagnostic(code: DiagnosticCode, message: string): never {\n throw new Error(formatDiagnostic(code, message, this.gridElement.id, this.name));\n }\n\n // #region Lifecycle Hooks\n\n /**\n * Transform rows before rendering.\n * Called during each render cycle before rows are rendered to the DOM.\n * Use this to filter, sort, or add computed properties to rows.\n *\n * @param rows - The current rows array (readonly to encourage returning a new array)\n * @returns The modified rows array to render\n *\n * @example\n * ```ts\n * processRows(rows: readonly any[]): any[] {\n * // Filter out hidden rows\n * return rows.filter(row => !row._hidden);\n * }\n * ```\n *\n * @example\n * ```ts\n * processRows(rows: readonly any[]): any[] {\n * // Add computed properties\n * return rows.map(row => ({\n * ...row,\n * _fullName: `${row.firstName} ${row.lastName}`\n * }));\n * }\n * ```\n */\n processRows?(rows: readonly any[]): any[];\n\n /**\n * Contribute to the grid's effective configuration during each config merge.\n * Called by {@link ConfigManager.merge} after the base config is assembled,\n * before it becomes `effectiveConfig`. Mutate `config` in place to inject\n * plugin-derived settings (e.g. the shell plugin folds its light-DOM /\n * API-registered state into `config.shell`).\n *\n * This is the config-pipeline counterpart to {@link processColumns} /\n * {@link processRows}: it keeps the core config merge free of any plugin\n * knowledge — each plugin owns the shape it contributes.\n *\n * @param config - The mutable base config being assembled into effectiveConfig.\n *\n * @example\n * ```ts\n * processConfig(config: GridConfig): void {\n * config.shell = { ...config.shell, header: { title: this.#title } };\n * }\n * ```\n */\n processConfig?(config: GridConfig): void;\n\n /**\n * Transform columns before rendering.\n * Called during each render cycle before column headers and cells are rendered.\n * Use this to add, remove, or modify column definitions.\n *\n * @param columns - The current columns array (readonly to encourage returning a new array)\n * @returns The modified columns array to render\n *\n * @example\n * ```ts\n * processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n * // Add a selection checkbox column\n * return [\n * { field: '_select', header: '', width: 40 },\n * ...columns\n * ];\n * }\n * ```\n */\n processColumns?(columns: readonly ColumnConfig[]): ColumnConfig[];\n\n /**\n * Called before each render cycle begins.\n * Use this to prepare state or cache values needed during rendering.\n *\n * **Note:** This hook is currently a placeholder for future implementation.\n * It is defined in the interface but not yet invoked by the grid's render pipeline.\n * If you need this functionality, please open an issue or contribute an implementation.\n *\n * @example\n * ```ts\n * beforeRender(): void {\n * this.visibleRowCount = this.calculateVisibleRows();\n * }\n * ```\n */\n beforeRender?(): void;\n\n /**\n * Called after each render cycle completes.\n * Use this for DOM manipulation, adding event listeners to rendered elements,\n * or applying visual effects like selection highlights.\n *\n * @example\n * ```ts\n * afterRender(): void {\n * // Apply selection styling to rendered rows\n * const rows = this.gridElement?.querySelectorAll('.data-grid-row');\n * rows?.forEach((row, i) => {\n * row.classList.toggle('selected', this.selectedRows.has(i));\n * });\n * }\n * ```\n */\n afterRender?(): void;\n\n /**\n * Called synchronously immediately after the grid (re)builds its root DOM\n * structure, before the browser has a chance to paint.\n *\n * Unlike {@link afterRender} (which runs in the scheduler's STYLE phase and\n * may be deferred), this hook fires inside the same task as the structural\n * DOM build. It is the correct place for plugins that need to wrap, relocate,\n * or augment the freshly built grid DOM without a flash of unstyled/unwrapped\n * content — e.g. a shell that moves the grid content into a chrome wrapper.\n *\n * The grid emits this hook every time it performs a full structural rebuild\n * (initial connect and structural changes), but NOT on the scroll/data hot\n * path. Implementations MUST be idempotent: a full rebuild discards any DOM a\n * previous invocation produced, so re-create it, and no-op when the desired\n * structure is already present.\n *\n * @example\n * ```ts\n * afterStructuralRender(): void {\n * const root = this.grid?._renderRoot;\n * if (!root || root.querySelector('.my-wrapper > .tbw-grid-content')) return;\n * // build wrapper, move .tbw-grid-content inside it\n * }\n * ```\n */\n afterStructuralRender?(): void;\n\n /**\n * Called synchronously by the grid immediately before it tears down and\n * rebuilds its root DOM structure (a structural re-render). Plugins that\n * relocated existing light-DOM nodes into their own chrome (e.g. a shell that\n * moves toolbar buttons into the header bar) use this to move those nodes back\n * to their original container so they survive the rebuild. Generic\n * counterpart to {@link afterStructuralRender}. MUST be idempotent.\n */\n beforeStructuralRender?(): void;\n\n /**\n * Called by the grid after a config merge to ask whether the change requires a\n * full structural re-render (rather than a cheaper in-place update). A plugin\n * returns `true` when its rendered DOM signature no longer matches the new\n * effective config — e.g. a shell header appearing/disappearing or a tool\n * panel's count/position/mode changing. The grid performs a structural\n * re-render if ANY plugin returns `true`. MUST be side-effect free.\n */\n needsStructuralRerender?(): boolean;\n\n /**\n * Called by the grid to let a plugin (re-)parse its own light-DOM\n * contributions into plugin state ahead of a config merge. Generic seam that\n * keeps core free of plugin-specific light-DOM tag knowledge (the plugin reads\n * `this.grid._hostElement`). MUST be idempotent.\n */\n parseLightDom?(): void;\n\n /**\n * Called by the grid (from `refreshColumns` and the light-DOM observer) to\n * let a plugin re-parse its light-DOM contributions AND refresh any\n * already-rendered chrome in place when something changed — e.g. a shell\n * title or tool buttons that a framework projected asynchronously after the\n * initial render. Distinct from {@link parseLightDom}, which only updates\n * plugin state. Generic seam — core holds no plugin-specific knowledge. MUST\n * be idempotent and a no-op when the plugin's chrome is not yet rendered.\n */\n syncLightDom?(): void;\n\n /**\n * Called after each cell is rendered.\n * This hook is more efficient than `afterRender()` for cell-level modifications\n * because you receive the cell context directly - no DOM queries needed.\n *\n * Use cases:\n * - Adding selection/highlight classes to specific cells\n * - Injecting badges or decorations\n * - Applying conditional styling based on cell value\n *\n * Performance note: Called for every visible cell during render. Keep implementation fast.\n * This hook is also called during scroll when cells are recycled.\n *\n * @param context - The cell render context with row, column, value, and elements\n *\n * @example\n * ```ts\n * afterCellRender(context: AfterCellRenderContext): void {\n * // Add selection class without DOM queries\n * if (this.isSelected(context.rowIndex, context.colIndex)) {\n * context.cellElement.classList.add('selected');\n * }\n *\n * // Add validation error styling\n * if (this.hasError(context.row, context.column.field)) {\n * context.cellElement.classList.add('has-error');\n * }\n * }\n * ```\n */\n afterCellRender?(context: AfterCellRenderContext): void;\n\n /**\n * Called after a row is fully rendered (all cells complete).\n * Use this for row-level decorations, styling, or ARIA attributes.\n *\n * Common use cases:\n * - Adding selection classes to entire rows (row-focus, selected)\n * - Setting row-level ARIA attributes\n * - Applying row validation highlighting\n * - Tree indentation styling\n *\n * Performance note: Called for every visible row during render. Keep implementation fast.\n * This hook is also called during scroll when rows are recycled.\n *\n * @param context - The row render context with row data and element\n *\n * @example\n * ```ts\n * afterRowRender(context: AfterRowRenderContext): void {\n * // Add row selection class without DOM queries\n * if (this.isRowSelected(context.rowIndex)) {\n * context.rowElement.classList.add('selected', 'row-focus');\n * }\n *\n * // Add validation error styling\n * if (this.rowHasErrors(context.row)) {\n * context.rowElement.classList.add('has-errors');\n * }\n * }\n * ```\n */\n afterRowRender?(context: AfterRowRenderContext): void;\n\n /**\n * Called after scroll-triggered row rendering completes.\n * This is a lightweight hook for applying visual state to recycled DOM elements.\n * Use this instead of afterRender when you need to reapply styling during scroll.\n *\n * Performance note: This is called frequently during scroll. Keep implementation fast.\n *\n * @example\n * ```ts\n * onScrollRender(): void {\n * // Reapply selection state to visible cells\n * this.applySelectionToVisibleCells();\n * }\n * ```\n */\n onScrollRender?(): void;\n\n /**\n * Get the height of a specific row.\n * Used for synthetic rows (group headers, detail panels, etc.) that have fixed heights.\n * Return undefined if this plugin does not manage the height for this row.\n *\n * This hook is called during position cache rebuilds for variable row height virtualization.\n * Plugins that create synthetic rows should implement this to provide accurate heights.\n *\n * @param row - The row data\n * @param index - The row index in the processed rows array\n * @returns The row height in pixels, or undefined if not managed by this plugin\n */\n getRowHeight?(row: unknown, index: number): number | undefined;\n\n /**\n * Adjust the virtualization start index to render additional rows before the visible range.\n * Use this when expanded content (like detail rows) needs its parent row to remain rendered\n * even when the parent row itself has scrolled above the viewport.\n *\n * @param start - The calculated start row index\n * @param scrollTop - The current scroll position\n * @param rowHeight - The height of a single row\n * @returns The adjusted start index (lower than or equal to original start)\n *\n * @example\n * ```ts\n * adjustVirtualStart(start: number, scrollTop: number, rowHeight: number): number {\n * // If row 5 is expanded and scrolled partially, keep it rendered\n * for (const expandedRowIndex of this.expandedRowIndices) {\n * const expandedRowTop = expandedRowIndex * rowHeight;\n * const expandedRowBottom = expandedRowTop + rowHeight + this.detailHeight;\n * if (expandedRowBottom > scrollTop && expandedRowIndex < start) {\n * return expandedRowIndex;\n * }\n * }\n * return start;\n * }\n * ```\n */\n adjustVirtualStart?(start: number, scrollTop: number, rowHeight: number): number;\n\n /**\n * Render a custom row, bypassing the default row rendering.\n * Use this for special row types like group headers, detail rows, or footers.\n *\n * @param row - The row data object\n * @param rowEl - The row DOM element to render into\n * @param rowIndex - The index of the row in the data array\n * @returns `true` if the plugin handled rendering (prevents default), `false`/`void` for default rendering\n *\n * @example\n * ```ts\n * renderRow(row: any, rowEl: HTMLElement, rowIndex: number): boolean | void {\n * if (row._isGroupHeader) {\n * rowEl.innerHTML = `<div class=\"group-header\">${row._groupLabel}</div>`;\n * return true; // Handled - skip default rendering\n * }\n * // Return void to let default rendering proceed\n * }\n * ```\n */\n renderRow?(row: any, rowEl: HTMLElement, rowIndex: number): boolean | void;\n\n // #endregion\n\n // #region Inter-Plugin Communication\n\n /**\n * Handle queries from other plugins or the grid.\n *\n * Queries are declared in `manifest.queries` and dispatched via `grid.query()`.\n * This enables type-safe, discoverable inter-plugin communication.\n *\n * @category Plugin Development\n * @param query - The query object with type and context\n * @returns Query-specific response, or undefined if not handling this query\n *\n * @example\n * ```ts\n * // In manifest\n * static override readonly manifest: PluginManifest = {\n * queries: [\n * { type: 'canMoveColumn', description: 'Check if a column can be moved' },\n * ],\n * };\n *\n * // In plugin class\n * handleQuery(query: PluginQuery): unknown {\n * if (query.type === 'canMoveColumn') {\n * const column = query.context as ColumnConfig;\n * return !column.sticky; // Can't move sticky columns\n * }\n * }\n * ```\n */\n handleQuery?(query: PluginQuery): unknown;\n\n // #endregion\n\n // #region Interaction Hooks\n\n /**\n * Handle keyboard events on the grid.\n * Called when a key is pressed while the grid or a cell has focus.\n *\n * @param event - The native KeyboardEvent\n * @returns `true` to prevent default behavior and stop propagation, `false`/`void` to allow default\n *\n * @example\n * ```ts\n * onKeyDown(event: KeyboardEvent): boolean | void {\n * // Handle Ctrl+A for select all\n * if (event.ctrlKey && event.key === 'a') {\n * this.selectAllRows();\n * return true; // Prevent default browser select-all\n * }\n * }\n * ```\n */\n onKeyDown?(event: KeyboardEvent): boolean | void;\n\n /**\n * Handle cell click events.\n * Called when a data cell is clicked (not headers).\n *\n * @param event - Cell click event with row/column context\n * @returns `true` to prevent default behavior and stop propagation, `false`/`void` to allow default\n *\n * @example\n * ```ts\n * onCellClick(event: CellClickEvent): boolean | void {\n * if (event.field === '_select') {\n * this.toggleRowSelection(event.rowIndex);\n * return true; // Handled\n * }\n * }\n * ```\n */\n onCellClick?(event: CellClickEvent): boolean | void;\n\n /**\n * Handle row click events.\n * Called when any part of a data row is clicked.\n * Note: This is called in addition to onCellClick, not instead of.\n *\n * @param event - Row click event with row context\n * @returns `true` to prevent default behavior and stop propagation, `false`/`void` to allow default\n *\n * @example\n * ```ts\n * onRowClick(event: RowClickEvent): boolean | void {\n * if (this.config.mode === 'row') {\n * this.selectRow(event.rowIndex, event.originalEvent);\n * return true;\n * }\n * }\n * ```\n */\n onRowClick?(event: RowClickEvent): boolean | void;\n\n /**\n * Handle header click events.\n * Called when a column header is clicked. Commonly used for sorting.\n *\n * @param event - Header click event with column context\n * @returns `true` to prevent default behavior and stop propagation, `false`/`void` to allow default\n *\n * @example\n * ```ts\n * onHeaderClick(event: HeaderClickEvent): boolean | void {\n * if (event.column.sortable !== false) {\n * this.toggleSort(event.field);\n * return true;\n * }\n * }\n * ```\n */\n onHeaderClick?(event: HeaderClickEvent): boolean | void;\n\n /**\n * Handle scroll events on the grid viewport.\n * Called during scrolling. Note: This may be called frequently; debounce if needed.\n *\n * @param event - Scroll event with scroll position and viewport dimensions\n *\n * @example\n * ```ts\n * onScroll(event: ScrollEvent): void {\n * // Update sticky column positions\n * this.updateStickyPositions(event.scrollLeft);\n * }\n * ```\n */\n onScroll?(event: ScrollEvent): void;\n\n /**\n * Handle cell mousedown events.\n * Used for initiating drag operations like range selection or column resize.\n *\n * @param event - Mouse event with cell context\n * @returns `true` to indicate drag started (prevents text selection), `false`/`void` otherwise\n *\n * @example\n * ```ts\n * onCellMouseDown(event: CellMouseEvent): boolean | void {\n * if (event.rowIndex !== undefined && this.config.mode === 'range') {\n * this.startDragSelection(event.rowIndex, event.colIndex);\n * return true; // Prevent text selection\n * }\n * }\n * ```\n */\n onCellMouseDown?(event: CellMouseEvent): boolean | void;\n\n /**\n * Handle cell mousemove events during drag operations.\n * Only called when a drag is in progress (after mousedown returned true).\n *\n * @param event - Mouse event with current cell context\n * @returns `true` to continue handling the drag, `false`/`void` otherwise\n *\n * @example\n * ```ts\n * onCellMouseMove(event: CellMouseEvent): boolean | void {\n * if (this.isDragging && event.rowIndex !== undefined) {\n * this.extendSelection(event.rowIndex, event.colIndex);\n * return true;\n * }\n * }\n * ```\n */\n onCellMouseMove?(event: CellMouseEvent): boolean | void;\n\n /**\n * Handle cell mouseup events to end drag operations.\n *\n * @param event - Mouse event with final cell context\n * @returns `true` if drag was finalized, `false`/`void` otherwise\n *\n * @example\n * ```ts\n * onCellMouseUp(event: CellMouseEvent): boolean | void {\n * if (this.isDragging) {\n * this.finalizeDragSelection();\n * this.isDragging = false;\n * return true;\n * }\n * }\n * ```\n */\n onCellMouseUp?(event: CellMouseEvent): boolean | void;\n\n // Note: Context menu items are provided via handleQuery('getContextMenuItems').\n // This keeps the core decoupled from the context-menu plugin specifics.\n\n // #endregion\n\n // #region Column State Hooks\n\n /**\n * Contribute plugin-specific state for a column.\n * Called by the grid when collecting column state for serialization.\n * Plugins can add their own properties to the column state.\n *\n * @param field - The field name of the column\n * @returns Partial column state with plugin-specific properties, or undefined if no state to contribute\n *\n * @example\n * ```ts\n * getColumnState(field: string): Partial<ColumnState> | undefined {\n * const filterModel = this.filterModels.get(field);\n * if (filterModel) {\n * // Uses module augmentation to add filter property to ColumnState\n * return { filter: filterModel } as Partial<ColumnState>;\n * }\n * return undefined;\n * }\n * ```\n */\n getColumnState?(field: string): Partial<ColumnState> | undefined;\n\n /**\n * Apply plugin-specific state to a column.\n * Called by the grid when restoring column state from serialized data.\n * Plugins should restore their internal state based on the provided state.\n *\n * @param field - The field name of the column\n * @param state - The column state to apply (may contain plugin-specific properties)\n *\n * @example\n * ```ts\n * applyColumnState(field: string, state: ColumnState): void {\n * // Check for filter property added via module augmentation\n * const filter = (state as any).filter;\n * if (filter) {\n * this.filterModels.set(field, filter);\n * this.applyFilter();\n * }\n * }\n * ```\n */\n applyColumnState?(field: string, state: ColumnState): void;\n\n // #endregion\n\n // #region Scroll Boundary Hooks\n\n /**\n * Report horizontal scroll boundary offsets for this plugin.\n * Plugins that obscure part of the scroll area (e.g., pinned/sticky columns)\n * should return how much space they occupy on each side.\n * The keyboard navigation uses this to ensure focused cells are fully visible.\n *\n * @param rowEl - The row element (optional, for calculating widths from rendered cells)\n * @param focusedCell - The currently focused cell element (optional, to determine if scrolling should be skipped)\n * @returns Object with left/right pixel offsets and optional skipScroll flag, or undefined if plugin has no offsets\n *\n * @example\n * ```ts\n * getHorizontalScrollOffsets(rowEl?: HTMLElement, focusedCell?: HTMLElement): { left: number; right: number; skipScroll?: boolean } | undefined {\n * // Calculate total width of left-pinned columns\n * const leftCells = rowEl?.querySelectorAll('.sticky-left') ?? [];\n * let left = 0;\n * leftCells.forEach(el => { left += (el as HTMLElement).offsetWidth; });\n * // Skip scroll if focused cell is pinned (always visible)\n * const skipScroll = focusedCell?.classList.contains('sticky-left');\n * return { left, right: 0, skipScroll };\n * }\n * ```\n */\n getHorizontalScrollOffsets?(\n rowEl?: HTMLElement,\n focusedCell?: HTMLElement,\n ): { left: number; right: number; skipScroll?: boolean } | undefined;\n\n /**\n * Report vertical scroll boundary offsets for this plugin.\n * Plugins that overlay the top or bottom of the rows viewport (e.g. sticky\n * row clones) should return how much space they obscure on each edge, so\n * keyboard navigation can scroll a focused row clear of the overlay rather\n * than leaving it hidden underneath — WCAG 2.2 SC 2.4.11 Focus Not Obscured.\n *\n * Only report space that is painted *over* the scrollable rows. Content that\n * takes part in normal flow (pinned-row bars, the column header) already\n * shrinks the viewport and must NOT be reported here, or rows would scroll\n * twice as far as needed.\n *\n * @param focusedRowIndex - Index of the row being scrolled into view, so a plugin can report `skipScroll` when it already renders that row in a permanently visible overlay\n * @returns Object with top/bottom pixel offsets and optional skipScroll flag, or undefined if plugin obscures nothing\n *\n * @example\n * ```ts\n * getVerticalScrollOffsets(focusedRowIndex?: number): { top: number; bottom: number; skipScroll?: boolean } | undefined {\n * if (!this.overlayEl) return undefined;\n * // The row is already pinned in the overlay — it is visible where it is.\n * if (focusedRowIndex != null && this.stuckIndices.includes(focusedRowIndex)) {\n * return { top: 0, bottom: 0, skipScroll: true };\n * }\n * return { top: this.overlayEl.offsetHeight, bottom: 0 };\n * }\n * ```\n *\n * @since 3.6.0\n */\n getVerticalScrollOffsets?(\n focusedRowIndex?: number,\n ): { top: number; bottom: number; skipScroll?: boolean } | undefined;\n\n // #endregion\n\n // #region Shell Integration Hooks\n\n /**\n * Register a tool panel for this plugin.\n * Return undefined if plugin has no tool panel.\n * The shell will create a toolbar toggle button and render the panel content\n * when the user opens the panel.\n *\n * @returns Tool panel definition, or undefined if plugin has no panel\n *\n * @example\n * ```ts\n * getToolPanel(): ToolPanelDefinition | undefined {\n * return {\n * id: 'columns',\n * title: 'Columns',\n * icon: '☰',\n * tooltip: 'Show/hide columns',\n * order: 10,\n * render: (container) => {\n * this.renderColumnList(container);\n * return () => this.cleanup();\n * },\n * };\n * }\n * ```\n */\n getToolPanel?(): ToolPanelDefinition | undefined;\n\n /**\n * Register content for the shell header center section.\n * Return undefined if plugin has no header content.\n * Examples: search input, selection summary, status indicators.\n *\n * @returns Header content definition, or undefined if plugin has no header content\n *\n * @example\n * ```ts\n * getHeaderContent(): HeaderContentDefinition | undefined {\n * return {\n * id: 'quick-filter',\n * order: 10,\n * render: (container) => {\n * const input = document.createElement('input');\n * input.type = 'text';\n * input.placeholder = 'Search...';\n * input.addEventListener('input', this.handleInput);\n * container.appendChild(input);\n * return () => input.removeEventListener('input', this.handleInput);\n * },\n * };\n * }\n * ```\n */\n getHeaderContent?(): HeaderContentDefinition | undefined;\n\n // #endregion\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 * 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 { FlattenedTreeRow } from './types';\n\n/**\n * Given a flat row index in the viewport, find the index of the\n * top-level node (depth 0) that \"owns\" that row.\n *\n * Walk backwards from the row index until a depth-0 row is found,\n * then return its position among all depth-0 rows.\n */\nexport function getTopLevelNodeIndex(flattenedRows: FlattenedTreeRow[], flatRowIndex: number): number {\n // Clamp to valid range\n const idx = Math.min(flatRowIndex, flattenedRows.length - 1);\n if (idx < 0) return 0;\n\n // Walk backwards to find the owning top-level node\n let current = idx;\n while (current > 0 && flattenedRows[current].depth > 0) {\n current--;\n }\n\n // Count how many depth-0 nodes precede this one (inclusive)\n let topLevelIndex = 0;\n for (let i = 0; i <= current; i++) {\n if (flattenedRows[i].depth === 0) {\n topLevelIndex++;\n }\n }\n // Convert to 0-based\n return topLevelIndex - 1;\n}\n\n/**\n * Count the number of top-level (depth 0) nodes in the flattened rows.\n */\nexport function countTopLevelNodes(flattenedRows: FlattenedTreeRow[]): number {\n let count = 0;\n for (const row of flattenedRows) {\n if (row.depth === 0) count++;\n }\n return count;\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 if (!row) 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, SortHandler } from '../../core/types';\nimport type {\n DataSourceChildrenDetail,\n DataSourceDataDetail,\n DataSourceErrorDetail,\n FetchChildrenQuery,\n Subscribable,\n ViewportMappingQuery,\n ViewportMappingResponse,\n} from '../server-side/datasource-types';\nimport { collapseAll, expandAll, expandToKey, toggleExpand } from './tree-data';\nimport { countTopLevelNodes, getTopLevelNodeIndex } 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> {\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: 'groupingRows',\n reason:\n 'Both plugins transform the entire row model. TreePlugin flattens nested hierarchies while ' +\n 'GroupingRowsPlugin groups flat rows with synthetic headers. Use one approach per grid.',\n },\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 { 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 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 private sortState: { field: string; direction: 1 | -1 } | null = null;\n /** Keys of nodes that are currently loading lazy children. */\n private loadingKeys = new Set<string>();\n /**\n * Keys 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 private loadedKeys = new Set<string>();\n /** In-flight local `loadChildren` requests, keyed by node key. */\n #childRequests = new Map<string, AbortController>();\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 /** 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 // Restore default `role=\"grid\"` on the rows-body so the grid stays\n // ARIA-valid after the plugin is removed (template default lives in\n // `core/internal/dom-builder.ts`). See WAI-ARIA Treegrid pattern.\n const rowsBody = this.gridElement?.querySelector('.rows-body');\n rowsBody?.setAttribute('role', 'grid');\n\n this.expandedKeys.clear();\n this.initialExpansionDone = false;\n this.flattenedRows = [];\n this.rowKeyMap.clear();\n this.previousVisibleKeys.clear();\n this.keysToAnimate.clear();\n this.sortState = null;\n this.loadingKeys.clear();\n this.loadedKeys.clear();\n for (const controller of this.#childRequests.values()) controller.abort();\n this.#childRequests.clear();\n this.originalTreeColumnRenderer = undefined;\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\n const startNode = getTopLevelNodeIndex(this.flattenedRows, viewportStart);\n const endNode = getTopLevelNodeIndex(this.flattenedRows, viewportEnd) + 1; // exclusive\n const totalLoadedNodes = countTopLevelNodes(this.flattenedRows);\n\n return { startNode, endNode, totalLoadedNodes } satisfies ViewportMappingResponse;\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 this.#mergeChildren(parentRow, (d.rows ?? []) as TreeRow[]);\n this.loadingKeys.delete(key);\n this.broadcast<TreeLoadEndDetail>('tree-load-end', {\n key,\n row: parentRow,\n 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 key\n // stays in `loadingKeys` 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 if (!this.loadingKeys.delete(key)) return;\n this.broadcast<TreeLoadErrorDetail>('tree-load-error', {\n key,\n row: parentRow,\n depth: this.rowKeyMap.get(key)?.depth ?? 0,\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 childrenField = this.config.childrenField ?? 'children';\n\n const treeRows = rows as readonly TreeRow[];\n\n if (treeRows.length === 0 || !detectTreeStructure(treeRows, childrenField, this.config.hasChildren)) {\n this.flattenedRows = [];\n this.rowKeyMap.clear();\n this.previousVisibleKeys.clear();\n this.#syncTreeColumn();\n // _rows[i] must remain the user's row reference. Return a shallow array\n // copy (so callers can't mutate the input array via the returned ref)\n // but DO NOT spread/clone the row objects themselves.\n return [...rows] as TreeRow[];\n }\n\n // Initialize expansion if needed.\n // When MultiSort is active, use its model instead of local sort state so\n // Tree and MultiSort don't fight over sort ownership.\n const effectiveSortState = this.resolveEffectiveSortState();\n\n if (this.config.defaultExpanded && !this.initialExpansionDone) {\n this.expandedKeys = expandAll(treeRows, this.config);\n this.initialExpansionDone = true;\n }\n\n // Single pass: sort + flatten in one walk, never cloning row objects.\n // `data` on each FlattenedTreeRow stays === the user's source row.\n this.flattenedRows = this.#flattenWithSort(treeRows, this.expandedKeys, effectiveSortState, null, 0);\n\n // Reset per-row metadata so rows that are no longer in the flattened\n // output (e.g. children of a now-collapsed parent) don't keep returning\n // stale entries via getRowMeta(). WeakMap reassignment is cheap and the\n // old map becomes GC-eligible immediately.\n this.#rowMeta = new WeakMap();\n this.rowKeyMap.clear();\n this.keysToAnimate.clear();\n const currentKeys = new Set<string>();\n\n for (const row of this.flattenedRows) {\n this.rowKeyMap.set(row.key, row);\n this.#rowMeta.set(row.data as object, row);\n currentKeys.add(row.key);\n if (!this.previousVisibleKeys.has(row.key) && row.depth > 0) {\n this.keysToAnimate.add(row.key);\n }\n }\n this.previousVisibleKeys = currentKeys;\n\n this.#syncTreeColumn();\n\n // Return source row references directly. Tree metadata (depth/key/etc.)\n // is read by the renderer via `getRowMeta(row)` instead of being spread\n // onto cloned row objects \\u2014 this keeps `_rows[i]` === user's row so that\n // `grid.updateRow(s)` mutations survive the next ROWS-phase rebuild.\n return this.flattenedRows.map((r) => r.data);\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 /**\n * Recursive single-pass sort + flatten.\n * - Per-level sort uses `[...rows].sort(...)` which produces a new array of\n * the SAME row references in a new order \\u2014 never spreads the row objects.\n * - Children arrays are NOT mutated on the source rows; the sort produces a\n * transient ordering used only for traversal.\n */\n #flattenWithSort(\n rows: readonly TreeRow[],\n expanded: Set<string>,\n sort: { field: string; direction: 1 | -1 } | null,\n parentKey: string | null,\n depth: number,\n ): FlattenedTreeRow[] {\n const childrenField = this.config.childrenField ?? 'children';\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 < rows.length; i++) {\n this.#keyFor(rows[i], i, parentKey);\n }\n const ordered = sort ? this.#sortLevel(rows, sort.field, sort.direction) : rows;\n const result: FlattenedTreeRow[] = [];\n const hasChildrenFn = this.config.hasChildren;\n\n for (let i = 0; i < ordered.length; i++) {\n const row = ordered[i];\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 const hasChildren =\n embeddedChildren ||\n (hasChildrenFn ? hasChildrenFn(row) : children != null && !Array.isArray(children) && !!children);\n const isExpanded = expanded.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: ordered.length,\n });\n\n if (embeddedChildren && isExpanded) {\n result.push(...this.#flattenWithSort(children as TreeRow[], expanded, sort, key, depth + 1));\n }\n }\n return result;\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.loadedKeys.add(this.#keyOf(row));\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 has already resolved.\n */\n #needsChildFetch(row: TreeRow, key: string): boolean {\n if (this.loadedKeys.has(key)) 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 * 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, the node is already loading, or\n * its children are already embedded.\n */\n private requestLazyChildren(flatRow: FlattenedTreeRow): void {\n const { key, depth, data: row } = flatRow;\n if (this.loadingKeys.has(key)) return;\n if (!this.#needsChildFetch(row, key)) return;\n\n const isServerSideActive = this.queryBoolean('datasource:is-active');\n const { loadChildren } = this.config;\n if (!isServerSideActive && !loadChildren) return;\n\n this.loadingKeys.add(key);\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 } satisfies FetchChildrenQuery);\n return;\n }\n\n this.#loadChildrenLocally(key, row, depth);\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): void {\n // A callback is guaranteed by the caller's guard.\n const loadChildren = this.config.loadChildren as NonNullable<TreeConfig['loadChildren']>;\n const controller = new AbortController();\n this.#childRequests.set(key, controller);\n\n const finish = (): boolean => {\n // Superseded or detached — drop the result silently.\n if (controller.signal.aborted) return false;\n this.#childRequests.delete(key);\n this.loadingKeys.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 controller that `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) cols[idx] = { ...cols[idx], viewRenderer: this.originalTreeColumnRenderer };\n }\n this.#treeColumnWrapped = false;\n this.originalTreeColumnRenderer = undefined;\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.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.loadingKeys.has(meta.key)) {\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, viewRenderer: 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\n const focusRow = this.grid._focusRow;\n const flatRow = this.flattenedRows[focusRow];\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 // Tree introduces hierarchy → switch the rows-body role from `grid` to\n // `treegrid` per WAI-ARIA so `aria-expanded` / `aria-level` /\n // `aria-setsize` / `aria-posinset` are valid in context. Idempotent\n // setAttribute call; cheap on the hot path.\n const rowsBody = this.gridElement?.querySelector('.rows-body');\n if (rowsBody && rowsBody.getAttribute('role') !== 'treegrid') {\n rowsBody.setAttribute('role', 'treegrid');\n }\n\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 const cell = rowEl.querySelector('.cell[data-row]');\n const idx = cell ? parseInt(cell.getAttribute('data-row') ?? '-1', 10) : -1;\n const treeRow = this.flattenedRows[idx];\n if (!treeRow) continue;\n\n // WAI-ARIA Treegrid: every row carries level/setsize/posinset so screen\n // readers can announce \"level 2, item 3 of 5\" while navigating.\n rowEl.setAttribute('aria-level', String(treeRow.depth + 1));\n rowEl.setAttribute('aria-setsize', String(treeRow.setSize));\n rowEl.setAttribute('aria-posinset', String(treeRow.posInSet));\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`.\n if (this.loadingKeys.has(treeRow.key)) {\n rowEl.setAttribute('aria-busy', 'true');\n } else if (rowEl.hasAttribute('aria-busy')) {\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":"AAoCA,IAAa,EAuBD,WAvBC,EAiDE,cCxET,EACJ,4SACG,MAAM,KACN,IAAK,GAAM,EAAE,MAAM,IAAI,UAAU,KAAK,KA2BrC,GA1BY,IAAI,OAAO,uCAAuC,EAAG,MAAM,GAAG,KAAK,gBA0B9D,IAAI,IACzB,2KAA2K,MACzK,OAOE,EAAyB,WAKzB,EAAY,IAAI,IAAI,kEAAkE,MAAM,MAK5F,EAAyB,wCAsC/B,SAAgB,EAAmB,GACjC,MAAM,EAAW,SAAS,cAAc,YAKxC,OAJI,GAAwB,iBAAT,IACjB,EAAS,UAAY,EAqCzB,SAAsB,GACpB,MAAM,EAAsB,GAGtB,EAAW,EAAK,iBAAiB,KAEvC,IAAK,MAAM,KAAM,EAAU,CACzB,MAAM,EAAU,EAAG,QAAQ,cAG3B,GAAI,EAAe,IAAI,GAAU,CAC/B,EAAS,KAAK,GACd,QACF,CAGA,IAAgB,QAAZ,GAAyC,+BAApB,EAAG,eAEE,MAAM,KAAK,EAAG,YAAY,KACnD,GAAS,EAAuB,KAAK,EAAK,OAAuB,SAAd,EAAK,MAAiC,eAAd,EAAK,MAE1D,CACvB,EAAS,KAAK,GACd,QACF,CAIF,MAAM,EAA0B,GAChC,IAAK,MAAM,KAAQ,EAAG,WAAY,CAChC,MAAM,EAAW,EAAK,KAAK,cAGvB,EAAuB,KAAK,GAC9B,EAAc,KAAK,EAAK,MAMT,OAAb,GAMA,EAAU,IAAI,I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3B,KAAK,eACP,CAgBA,QAAA,CAAS,GACP,KAAK,aAAa,OAAO,GACzB,KAAK,eACP,CAgBA,MAAA,CAAO,GACL,KAAK,aAAe,EAAa,KAAK,aAAc,GACpD,MAAM,EAAU,KAAK,UAAU,IAAI,GAC/B,GAEE,KAAK,aAAa,IAAI,IACxB,KAAK,oBAAoB,GAE3B,KAAK,UAA4B,cAAe,CAC9C,MACA,IAAK,EAAQ,KACb,SAAU,KAAK,aAAa,IAAI,GAChC,MAAO,EAAQ,MACf,aAAc,IAAI,KAAK,iBAGzB,KAAK,gBAAgB,cAAe,CAAE,aAAc,IAAI,KAAK,gBAE/D,KAAK,eACP,CAcA,SAAA,GACE,KAAK,aAAe,EAAU,KAAK,KAAmB,KAAK,QAC3D,KAAK,gBAAgB,cAAe,CAAE,aAAc,IAAI,KAAK,gBAC7D,KAAK,eACP,CAcA,WAAA,GACE,KAAK,4BJ19BA,IAAI,II29BT,KAAK,gBAAgB,cAAe,CAAE,aAAc,IAAI,KAAK,gBAC7D,KAAK,eACP,CAQA,UAAA,CAAW,GACT,OAAO,KAAK,aAAa,IAAI,EAC/B,CAgBA,eAAA,GACE,MAAO,IAAI,KAAK,aAClB,CAUA,gBAAA,GACE,MAAO,IAAI,KAAK,cAClB,CAmBA,UAAA,CAAW,GACT,OAAO,MAAK,EAAS,IAAI,EAC3B,CAQA,WAAA,CAAY,GACV,OAAO,KAAK,UAAU,IAAI,IAAM,IAClC,CAiBA,WAAA,CAAY,GACV,KAAK,aAAe,EAAY,KAAK,KAAmB,EAAK,KAAK,OAAQ,KAAK,cAC/E,KAAK,eACP"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"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/core/defaults.ts","../../../../../../libs/grid/src/lib/core/internal/value-accessor.ts","../../../../../../libs/grid/src/lib/core/internal/sorting.ts","../../../../../../libs/grid/src/lib/core/internal/diagnostics.ts","../../../../../../libs/grid/src/lib/core/plugin/base-plugin.ts","../../../../../../libs/grid/src/lib/plugins/tree/tree-data.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 { GridConfig, LoadingContext } 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/**\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 */\nexport function setRowLoadingState(rowEl: HTMLElement, loading: boolean): 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 if (!rowEl.querySelector('.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 const spinner = document.createElement('div');\n spinner.className = 'tbw-row-loading-spinner';\n overlay.appendChild(spinner);\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 rowEl.querySelector('.tbw-row-loading-overlay')?.remove();\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 */\nexport function setCellLoadingState(cellEl: HTMLElement, loading: boolean): void {\n if (loading) {\n cellEl.classList.add('tbw-cell-loading');\n cellEl.setAttribute('aria-busy', 'true');\n } else {\n cellEl.classList.remove('tbw-cell-loading');\n cellEl.removeAttribute('aria-busy');\n }\n}\n","/**\n * Runtime default values for grid configuration.\n *\n * Kept out of `core/types.ts` so that file stays type-only apart from the two\n * enum-like consts whose `type` aliases are derived from them via `typeof`.\n * Import types from `./types`; import the values that back them from here.\n */\n\nimport type { A11yMessages, AnimationConfig, GridIcons } from './types';\n\n/**\n * Default English announcement messages.\n * Used when no custom messages are provided via {@link A11yConfig.messages}.\n * @since 2.0.0\n */\nexport const DEFAULT_A11Y_MESSAGES: Required<A11yMessages> = {\n sortApplied: (column, direction) => `Sorted by ${column}, ${direction}`,\n sortCleared: () => 'Sort cleared',\n filterApplied: (column) => `Filter applied on ${column}`,\n filterCleared: (column) => `Filter cleared from ${column}`,\n allFiltersCleared: () => 'All filters cleared',\n groupExpanded: (name, count) => `Group ${name} expanded, ${count} rows`,\n groupCollapsed: (name) => `Group ${name} collapsed`,\n selectionChanged: (count) => `${count} rows selected`,\n selectAllRows: () => 'Select all rows',\n selectRow: (rowIndex) => `Select row ${rowIndex + 1}`,\n columnSelected: (label) => `Column ${label} selected`,\n columnSelectionChanged: (count) => `${count} columns selected`,\n columnSelectionCleared: () => 'Column selection cleared',\n selectionAxisChanged: (toAxis) =>\n toAxis === 'column'\n ? 'Row selection cleared, column selection active'\n : 'Column selection cleared, row selection active',\n rangeSpanSelected: (axis, count) =>\n count === 1 ? `${axis === 'row' ? 'Row' : 'Column'} selected` : `${count} ${axis}s selected`,\n editingStarted: (rowIndex) => `Editing row ${rowIndex + 1}`,\n editingCommitted: (rowIndex) => `Row ${rowIndex + 1} saved`,\n dataLoaded: (count) => `${count} rows loaded`,\n};\n\n/**\n * Default animation configuration\n * @since 0.2.7\n */\nexport const DEFAULT_ANIMATION_CONFIG: Required<Omit<AnimationConfig, 'sort'>> = {\n mode: 'reduced-motion',\n duration: 200,\n easing: 'ease-out',\n};\n\n/**\n * Default icons used when not overridden. Most entries are short text/emoji;\n * `filter` and `filterActive` are empty strings because the actual rendering\n * is driven by the `--tbw-icon-filter[-active]-mask` CSS custom properties\n * (see `core/styles/variables.css`). Userland that wants an HTML/SVG fallback\n * via `gridConfig.icons.filter = '<svg…>'` is unaffected — that path overrides this default.\n * @since 0.1.1\n */\nexport const DEFAULT_GRID_ICONS: Required<GridIcons> = {\n expand: '▶',\n collapse: '▼',\n sortAsc: '▲',\n sortDesc: '▼',\n sortNone: '⇅',\n submenuArrow: '▶',\n dragHandle: '⋮⋮',\n toolPanel: '☰',\n filter: '',\n filterActive: '',\n print: '🖨️',\n};\n","/**\n * Value Accessor Module\n *\n * Single source of truth for resolving a column's value from a row.\n *\n * Resolution precedence:\n * 1. `column.valueAccessor({ row, column, rowIndex })` — when defined\n * 2. `row[column.field]` — direct field read (default)\n *\n * Per-column escape hatches (`sortComparator`, `filterValue`) still take\n * precedence over the accessor — the accessor is the *default* value source,\n * never an override. See {@link BaseColumnConfig.valueAccessor}.\n *\n * Performance: results are memoized per (row identity, column field) using a\n * `WeakMap`. Row identity changes (immutable updates) invalidate naturally;\n * in-place mutations must call {@link invalidateAccessorCache} on the row.\n */\n\nimport type { ColumnConfig } from '../types';\n\n// Box-wrapped values let the cache-hit path do a SINGLE `Map.get` instead of\n// `has()` + `get()`. A truthy box means cache hit (even when the cached value\n// itself is `undefined` / `null` / `0` / `''`).\ninterface CacheBox {\n v: unknown;\n}\nconst accessorCache = new WeakMap<object, Map<string, CacheBox>>();\n\n// #region Nested dotted-path field access (issue #438)\n\n// Prototype-pollution guard applied to every path segment on read AND write.\n// Uses explicit `===` comparisons (not a Set lookup) so static analyzers\n// recognize the barrier guarding the assignments in `setByPath`/`writeCellField`.\nfunction isUnsafeKey(key: string): boolean {\n return key === '__proto__' || key === 'constructor' || key === 'prototype';\n}\n\n// Parsed dotted-path cache: field string → segments. Only **dotted** fields are\n// cached; a plain key is recognised by a single `indexOf` scan, which is cheaper\n// than hashing the string for a Map probe and — critically — keeps the cache\n// from growing without bound when a plugin mints synthetic field names at\n// runtime (PivotPlugin derives one column per distinct pivot value).\nconst fieldPathCache = new Map<string, readonly string[]>();\n\n/**\n * Parse a column `field` into path segments, or `null` when it is a plain\n * top-level key (contains no `.`). Dotted results are memoized.\n *\n * @param field - The column field key (may be a dotted path like `a.b.c`).\n * @returns Frozen segment array for dotted paths, else `null`.\n * @since 3.3.0\n */\nexport function parseFieldPath(field: string): readonly string[] | null {\n if (field.indexOf('.') === -1) return null;\n let segments = fieldPathCache.get(field);\n if (segments === undefined) {\n segments = Object.freeze(field.split('.'));\n fieldPathCache.set(field, segments);\n }\n return segments;\n}\n\n/**\n * Read a nested value from `row` by pre-parsed path segments. Returns\n * `undefined` on any nullish/non-object hop. Prototype-pollution safe.\n *\n * @since 3.3.0\n */\nexport function getByPath(row: unknown, path: readonly string[]): unknown {\n let cur = row as Record<string, unknown> | null | undefined;\n for (let i = 0; i < path.length; i++) {\n if (cur == null || typeof cur !== 'object') return undefined;\n const seg = path[i];\n if (isUnsafeKey(seg)) return undefined;\n cur = cur[seg] as Record<string, unknown>;\n }\n return cur;\n}\n\n/**\n * Write `value` into `row` at the location described by pre-parsed path\n * segments. Walks **existing** objects only — it does NOT fabricate missing\n * intermediates — and returns `true` only when the write happened.\n * Prototype-pollution safe (every segment is guarded).\n *\n * @since 3.3.0\n */\nexport function setByPath(row: unknown, path: readonly string[], value: unknown): boolean {\n if (row == null || typeof row !== 'object') return false;\n let cur = row as Record<string, unknown>;\n for (let i = 0; i < path.length - 1; i++) {\n const seg = path[i];\n if (isUnsafeKey(seg)) return false;\n const next = cur[seg];\n if (next == null || typeof next !== 'object') return false;\n cur = next as Record<string, unknown>;\n }\n const last = path[path.length - 1];\n if (isUnsafeKey(last)) return false;\n cur[last] = value;\n return true;\n}\n\n/**\n * Read the raw stored value for `field` from `row`, honoring nested dotted\n * paths — the non-accessor counterpart to {@link resolveCellValue}.\n *\n * Resolution rules (back-compat critical, see `grid-core.md` DECIDED #438):\n * 1. Plain field (no `.`) → direct `row[field]` (identical to legacy path),\n * except prototype-polluting keys (`__proto__`/`constructor`/`prototype`)\n * which return `undefined` — symmetric with {@link writeCellField}.\n * 2. Dotted field whose literal key is an **own property** of `row` → that\n * flat value wins (preserves synthetic-key rows that really store `'a.b'`).\n * 3. Otherwise → nested traversal via {@link getByPath}.\n *\n * @since 3.3.0\n */\nexport function readCellField(row: unknown, field: string): unknown {\n if (row == null) return undefined;\n const path = parseFieldPath(field);\n const r = row as Record<string, unknown>;\n if (path === null) return isUnsafeKey(field) ? undefined : r[field];\n if (Object.prototype.hasOwnProperty.call(r, field)) return r[field];\n return getByPath(r, path);\n}\n\n/**\n * A precompiled reader that extracts one column's raw value from a row.\n *\n * @since 3.4.0\n */\nexport type FieldReader = (row: unknown) => unknown;\n\n/**\n * Build a {@link FieldReader} for `field`, resolving the plain / unsafe /\n * dotted decision **once** instead of on every cell read.\n *\n * Hoist the reader out of any per-row loop (sort comparators, compiled filter\n * predicates, aggregators, export writers). Semantics are identical to\n * {@link readCellField}; only the dispatch is paid up front.\n *\n * @param field - The column field key (may be a dotted path like `a.b.c`).\n * @returns A single-argument reader closure.\n *\n * @example\n * ```typescript\n * const read = createFieldReader(column.field);\n * rows.sort((a, b) => compare(read(a), read(b)));\n * ```\n * @since 3.4.0\n */\nexport function createFieldReader(field: string): FieldReader {\n const path = parseFieldPath(field);\n if (path === null) {\n if (isUnsafeKey(field)) return () => undefined;\n return (row) => (row == null ? undefined : (row as Record<string, unknown>)[field]);\n }\n return (row) => {\n if (row == null) return undefined;\n const r = row as Record<string, unknown>;\n // A literal own key containing a dot wins over traversal (see readCellField).\n if (Object.prototype.hasOwnProperty.call(r, field)) return r[field];\n return getByPath(r, path);\n };\n}\n\n/**\n * Whether `field` is a plain, safe top-level key — i.e. `row[field]` is exactly\n * equivalent to {@link readCellField} and callers may inline the property read.\n *\n * Used by benchmarked hot loops (compiled filter predicates) that keep a\n * hand-inlined fast path and only fall back to a {@link FieldReader} for the\n * dotted/unsafe minority.\n *\n * @since 3.4.0\n */\nexport function isPlainField(field: string): boolean {\n return field.indexOf('.') === -1 && !isUnsafeKey(field);\n}\n\n/**\n * Write `value` into `row` for `field`, honoring nested dotted paths and the\n * same back-compat precedence as {@link readCellField}. Returns `true` when a\n * write occurred. Prototype-pollution safe.\n *\n * @since 3.3.0\n */\nexport function writeCellField(row: unknown, field: string, value: unknown): boolean {\n if (row == null || typeof row !== 'object') return false;\n const path = parseFieldPath(field);\n const r = row as Record<string, unknown>;\n if (path === null) {\n if (isUnsafeKey(field)) return false;\n r[field] = value;\n return true;\n }\n // A literal own key containing a dot wins over traversal (symmetric with\n // readCellField). Such a key always contains `.`, so it can never be an\n // unsafe prototype key.\n if (Object.prototype.hasOwnProperty.call(r, field)) {\n r[field] = value;\n return true;\n }\n return setByPath(r, path, value);\n}\n\n// #endregion\n\n/**\n * Resolve the cell value for a column, honoring `valueAccessor` if defined,\n * otherwise reading `row[column.field]` (with nested dotted-path support).\n *\n * @param row - The row object\n * @param column - The column definition\n * @param rowIndex - The visible row index (passed to accessor; defaults to -1)\n * @returns The resolved cell value\n *\n * @example\n * ```typescript\n * const value = resolveCellValue(row, column);\n * ```\n * @since 2.2.0\n */\nexport function resolveCellValue<TRow>(row: TRow, column: ColumnConfig<TRow>, rowIndex = -1): unknown {\n if (!column.valueAccessor) {\n return readCellField(row, column.field);\n }\n // Non-object rows (primitives, null) bypass the cache.\n if (typeof row !== 'object' || row === null) {\n return column.valueAccessor({ row, column, rowIndex });\n }\n // After the guard above, `row` is provably a non-null object. Single\n // assertion (no `as unknown as`) bridges the generic `TRow` to the WeakMap\n // key type; see `.github/instructions/typescript-conventions.instructions.md`.\n const rowKey = row as object;\n const key = column.field;\n let cellMap = accessorCache.get(rowKey);\n if (cellMap) {\n const box = cellMap.get(key);\n if (box !== undefined) return box.v;\n } else {\n cellMap = new Map();\n accessorCache.set(rowKey, cellMap);\n }\n const value = column.valueAccessor({ row, column, rowIndex });\n cellMap.set(key, { v: value });\n return value;\n}\n\n/**\n * Invalidate cached accessor values for a row (after in-place mutation),\n * a single (row, field) pair, or — when called with no argument — clear\n * the entire cache. Immutable updates auto-invalidate via row identity.\n *\n * Edit/transaction paths that mutate row objects in-place must call this.\n * @since 2.2.0\n */\nexport function invalidateAccessorCache(row?: object, field?: string): void {\n if (!row) {\n // WeakMap can't be cleared in O(1); the GC handles unreferenced rows.\n // For an explicit full reset, callers should mutate row identities instead.\n return;\n }\n if (!field) {\n accessorCache.delete(row);\n return;\n }\n accessorCache.get(row)?.delete(field);\n}\n\n/**\n * Build a `(value, row) => unknown` extractor compatible with\n * `filterValue`-style APIs from a column's `valueAccessor`. Returns `undefined`\n * when the column has no accessor.\n *\n * Used by FilteringPlugin to bridge the two API shapes without duplicating\n * cache lookups.\n */\nexport function accessorAsFilterValue<TRow>(\n column: ColumnConfig<TRow>,\n): ((value: unknown, row: TRow) => unknown) | undefined {\n if (!column.valueAccessor) return undefined;\n return (_value, row) => resolveCellValue(row, column);\n}\n","/**\n * Sorting Module\n *\n * Handles column sorting state transitions and row ordering.\n */\n\nimport type { ColumnConfig, GridHost, InternalGrid, SortHandler, SortState } from '../types';\nimport { announce, getA11yMessage } from './aria';\nimport { createFieldReader, isPlainField, resolveCellValue } from './value-accessor';\n\n/**\n * Default comparator used when no column-level `sortComparator` is configured.\n * Pushes `null`/`undefined` to the end and compares remaining values via `>` / `<`\n * operators, which works correctly for numbers and falls back to lexicographic\n * comparison for strings.\n *\n * Use this as a fallback inside a custom `sortComparator` when you only need\n * special handling for certain values:\n *\n * @example\n * ```typescript\n * import { defaultComparator } from '@toolbox-web/grid';\n *\n * const column = {\n * field: 'priority',\n * sortComparator: (a, b, rowA, rowB) => {\n * // Pin \"urgent\" to the top, then fall back to default ordering\n * if (a === 'urgent') return -1;\n * if (b === 'urgent') return 1;\n * return defaultComparator(a, b);\n * },\n * };\n * ```\n *\n * @see {@link BaseColumnConfig.sortComparator} for column-level comparators\n * @see {@link builtInSort} for the full sort handler that uses this comparator\n * @category Factory Functions\n * @since 0.2.7\n */\nexport function defaultComparator(a: unknown, b: unknown): number {\n if (a == null && b == null) return 0;\n if (a == null) return -1;\n if (b == null) return 1;\n return a > b ? 1 : a < b ? -1 : 0;\n}\n\n/**\n * The default `sortHandler` used when none is provided in {@link GridConfig.sortHandler}.\n * Reads each column's `sortComparator` (falling back to {@link defaultComparator})\n * and returns a sorted copy of the rows array.\n *\n * **Contract:** This function is non-mutating — it copies the input array\n * (`[...rows].sort()`) before sorting and returns the new array. Public callers\n * may pass any array safely; internal callers that already own a mutable copy\n * should bypass this function and sort in place to avoid the extra allocation.\n * The non-mutation guarantee is part of the public API and must be preserved.\n *\n * Use this as a fallback inside a custom `sortHandler` when you only need to\n * intercept sorting for specific columns or add pre/post-processing:\n *\n * @example\n * ```typescript\n * import { builtInSort } from '@toolbox-web/grid';\n * import type { SortHandler } from '@toolbox-web/grid';\n *\n * const customSort: SortHandler<Employee> = (rows, state, columns) => {\n * // Server-side sort for the \"salary\" column, client-side for everything else\n * if (state.field === 'salary') {\n * return fetch(`/api/employees?sort=${state.field}&dir=${state.direction}`)\n * .then(res => res.json());\n * }\n * return builtInSort(rows, state, columns);\n * };\n *\n * grid.gridConfig = { sortHandler: customSort };\n * ```\n *\n * @see {@link GridConfig.sortHandler} for configuring the handler\n * @see {@link defaultComparator} for the comparator used per column\n * @category Factory Functions\n * @since 0.2.7\n */\nexport function builtInSort<T>(rows: T[], sortState: SortState, columns: ColumnConfig<T>[]): T[] {\n const sorted = [...rows];\n executeBuiltInSortInPlace(sorted, sortState.field, sortState.direction, columns as ColumnConfig<any>[]);\n return sorted;\n}\n\n/**\n * Sort an array in-place using the default comparator with direction folded in.\n * Shared between the public `builtInSort` (which copies first) and the internal\n * fast paths in `applySort` / `reapplyCoreSort` (which skip the copy).\n *\n * Pins `__loading` placeholder rows (e.g. ServerSidePlugin under `sortMode: 'local'`)\n * to the end regardless of direction.\n */\nfunction sortInPlace(rows: any[], field: string, direction: 1 | -1): void {\n // A plain top-level key is a monomorphic inline property load — cheaper read\n // than any indirection we could add. This comparator MUST stay fully inlined\n // (no shared helper call): it runs ~2·N·log N times, so even one extra call\n // per compare is measurable. See the INVARIANT in `.github/knowledge/grid-core.md`.\n if (isPlainField(field)) {\n rows.sort((rA: any, rB: any) => {\n const pinned = pinLoadingRows(rA, rB);\n if (pinned !== 0) return pinned;\n const a = rA[field];\n const b = rB[field];\n if (a == null && b == null) return 0;\n if (a == null) return -direction;\n if (b == null) return direction;\n return a > b ? direction : a < b ? -direction : 0;\n });\n return;\n }\n // Nested dotted path: each read walks the path, so hoist the extraction out\n // of the comparator (decorate-sort-undecorate). Touches every row once\n // instead of ~2·N·log N times.\n sortByExtractedKeys(rows, createFieldReader(field), direction);\n}\n\n/**\n * Decorate-sort-undecorate: extract every row's sort key once, sort an index\n * array, then permute the rows in place.\n *\n * Used when the key extraction is more than a single property load (nested\n * dotted paths, `valueAccessor`). Sorting indices keeps the sort **stable**,\n * because `Array.prototype.sort` is stable and equal keys fall back to\n * ascending index order — i.e. the original row order.\n */\nfunction sortByExtractedKeys(rows: any[], read: (row: unknown) => unknown, direction: 1 | -1): void {\n const n = rows.length;\n if (n < 2) return;\n\n const keys = new Array<unknown>(n);\n // `Uint8Array` keeps the placeholder flags off the JS heap's boxed path.\n const loading = new Uint8Array(n);\n const order = new Array<number>(n);\n for (let i = 0; i < n; i++) {\n const row = rows[i];\n order[i] = i;\n keys[i] = read(row);\n // Same test as `pinLoadingRows`, applied once per row instead of per compare.\n loading[i] = (row as { __loading?: unknown } | null)?.__loading === true ? 1 : 0;\n }\n\n // Inlined for the same reason as `sortInPlace` — this runs ~2·N·log N times.\n order.sort((ia, ib) => {\n const la = loading[ia];\n const lb = loading[ib];\n if (la !== lb) return la ? 1 : -1;\n const a = keys[ia];\n const b = keys[ib];\n if (a == null && b == null) return 0;\n if (a == null) return -direction;\n if (b == null) return direction;\n return (a as number) > (b as number) ? direction : (a as number) < (b as number) ? -direction : 0;\n });\n\n const sorted = new Array<unknown>(n);\n for (let i = 0; i < n; i++) sorted[i] = rows[order[i]];\n for (let i = 0; i < n; i++) rows[i] = sorted[i];\n}\n\n/**\n * Sort an array in-place using `column.valueAccessor` to extract each cell value.\n * Mirrors {@link sortInPlace} but routes value reads through the accessor +\n * shared per-row cache. Used when no `sortComparator` is configured.\n *\n * Pins `__loading` placeholder rows to the end regardless of direction.\n */\nfunction sortInPlaceWithAccessor(rows: any[], column: ColumnConfig<any>, direction: 1 | -1): void {\n sortByExtractedKeys(rows, (row) => resolveCellValue(row, column), direction);\n}\n\n/**\n * Pin `__loading` placeholder rows to the end of the sorted array regardless\n * of sort direction. Returns 0 when neither row is a placeholder.\n *\n * Applied only on the built-in default-comparator paths. Custom column\n * `sortComparator` callbacks receive the row pair and own placeholder handling.\n *\n * @internal\n */\nfunction pinLoadingRows(a: unknown, b: unknown): number {\n const aLoading = (a as { __loading?: unknown } | null)?.__loading === true;\n const bLoading = (b as { __loading?: unknown } | null)?.__loading === true;\n if (aLoading === bLoading) return 0;\n return aLoading ? 1 : -1;\n}\n\n/**\n * Execute the built-in sort on rows in-place, using a column-level custom\n * comparator when present, otherwise the default comparator.\n *\n * Shared by the public {@link builtInSort} (which copies first) and the internal\n * fast paths in `applySort` / `reapplyCoreSort` (which sort the live array).\n */\nfunction executeBuiltInSortInPlace(rows: any[], field: string, direction: 1 | -1, columns: ColumnConfig<any>[]): void {\n const col = columns.find((c) => c.field === field);\n const customComparator = col?.sortComparator;\n if (customComparator) {\n // Custom comparator path — keep the indirect call.\n // sortComparator wins over valueAccessor (per-column override).\n if (col?.valueAccessor) {\n rows.sort(\n (rA: any, rB: any) =>\n customComparator(resolveCellValue(rA, col), resolveCellValue(rB, col), rA, rB) * direction,\n );\n } else {\n const read = createFieldReader(field);\n rows.sort((rA: any, rB: any) => customComparator(read(rA), read(rB), rA, rB) * direction);\n }\n } else if (col?.valueAccessor) {\n // valueAccessor path — extract values via the accessor.\n sortInPlaceWithAccessor(rows, col, direction);\n } else {\n // Fast path — inline default comparator and fold direction to avoid\n // ~20M indirect function calls + multiplications at 1M rows.\n sortInPlace(rows, field, direction);\n }\n}\n\n/**\n * Apply sort result to grid and update UI.\n * Called after sync or async sort completes.\n */\nfunction finalizeSortResult<T>(grid: GridHost<T>, sortedRows: T[], col: ColumnConfig<T>, dir: 1 | -1): void {\n grid._rows = sortedRows;\n // Bump epoch so renderVisibleRows triggers full inline rebuild\n grid.__rowRenderEpoch++;\n // Invalidate pooled rows to guarantee rebuild\n for (let i = 0; i < grid._rowPool.length; i++) {\n grid._rowPool[i].__epoch = -1;\n }\n grid._schedulerRenderHeader();\n grid.refreshVirtualWindow(true);\n emitSortChange(grid, col, dir);\n}\n\n/**\n * Emit sort-change event, aria announcement, and state change request.\n * Shared by both the direct sort path and the scheduler-delegated path.\n *\n * Emits to BOTH channels:\n * - DOM CustomEvent — for external consumers (`grid.addEventListener('sort-change', …)`).\n * - Plugin event bus — for plugins that subscribe via `this.on('sort-change', …)`\n * (e.g. ServerSidePlugin purges its block cache on sort change). Without the\n * plugin-bus emit, the core sort path silently bypasses every plugin listener\n * while MultiSortPlugin (which uses `broadcast()`) works correctly.\n */\nfunction emitSortChange<T>(grid: GridHost<T>, col: ColumnConfig<T>, dir: 1 | -1 | 0): void {\n const detail = { field: col.field, direction: dir };\n grid.dispatchEvent(new CustomEvent('sort-change', { detail }));\n grid._pluginManager?.emitPluginEvent?.('sort-change', detail);\n announce(\n grid,\n getA11yMessage(\n grid,\n dir === 0 ? 'sortCleared' : 'sortApplied',\n col.header ?? col.field,\n dir === 1 ? 'ascending' : 'descending',\n ),\n );\n // Trigger state change after sort applied\n grid.requestStateChange?.();\n}\n\n/**\n * Check whether the grid has plugins that inject synthetic rows into `_rows`\n * (group headers, tree nodes, pivot aggregates, etc.).\n * When true, sorting must go through the render scheduler so the full row-model\n * pipeline (reapplyCoreSort → processRows) runs on the base rows instead of\n * directly mutating _rows which would corrupt plugin-generated row structures.\n *\n * This intentionally ignores plugins that only filter or reorder rows (Filtering,\n * MultiSort) — direct in-place sorting is safe for those.\n */\nfunction hasRowStructurePlugins(grid: GridHost): boolean {\n return grid._pluginManager?._hasRowStructurePlugins ?? false;\n}\n\n/**\n * Cycle sort state for a column: none -> ascending -> descending -> none.\n * Restores original row order when clearing sort.\n */\nexport function toggleSort(grid: GridHost, col: ColumnConfig<any>): void {\n if (!grid._sortState || grid._sortState.field !== col.field) {\n if (!grid._sortState) grid.__originalOrder = grid._rows.slice();\n applySort(grid, col, 1);\n } else if (grid._sortState.direction === 1) {\n applySort(grid, col, -1);\n } else {\n grid._sortState = null;\n\n // When row-model plugins are active (grouping, tree, etc.), delegate to the\n // render scheduler so #rebuildRowModel runs the full pipeline on base rows.\n if (hasRowStructurePlugins(grid)) {\n // RenderPhase.ROWS = 4 — triggers rebuildRowModel which skips reapplyCoreSort\n // when _sortState is null, then runs processRows to rebuild groups.\n grid._requestSchedulerPhase(4, 'sort-clear');\n emitSortChange(grid, col, 0);\n return;\n }\n\n // Fast path: no row-model plugins — direct _rows manipulation is safe.\n // Force full row rebuild after clearing sort so templated cells reflect original order\n grid.__rowRenderEpoch++;\n // Invalidate existing pooled row epochs so virtualization triggers a full inline rebuild\n for (let i = 0; i < grid._rowPool.length; i++) {\n grid._rowPool[i].__epoch = -1;\n }\n grid._rows = grid.__originalOrder.slice();\n grid.__originalOrder = [];\n grid._schedulerRenderHeader();\n // After re-render ensure cleared column shows aria-sort=\"none\" baseline.\n const headers = grid._headerRowEl?.querySelectorAll('[role=\"columnheader\"].sortable');\n if (headers) {\n for (let i = 0; i < headers.length; i++) {\n const h = headers[i];\n if (!h.getAttribute('aria-sort')) h.setAttribute('aria-sort', 'none');\n else if (h.getAttribute('aria-sort') === 'ascending' || h.getAttribute('aria-sort') === 'descending') {\n // The active column was re-rendered already, but normalize any missing ones.\n if (!grid._sortState) h.setAttribute('aria-sort', 'none');\n }\n }\n }\n grid.refreshVirtualWindow(true);\n emitSortChange(grid, col, 0);\n }\n}\n\n/**\n * Re-apply the current core sort to rows during #rebuildRowModel.\n * Updates __originalOrder so \"clear sort\" restores the current dataset.\n * Returns rows unchanged if no core sort is active or handler is async.\n *\n * @param skipOriginalOrderSave - When true, caller already saved __originalOrder.\n * Avoids an O(n) `rows.slice()` in the hot path.\n */\nexport function reapplyCoreSort<T>(grid: InternalGrid<T>, rows: T[], skipOriginalOrderSave = false): T[] {\n if (!grid._sortState) return rows;\n\n const handler: SortHandler<any> = grid.effectiveConfig?.sortHandler ?? builtInSort;\n\n // Reference equality gate: builtInSort is public API and must not mutate its input,\n // but internally we can bypass the copy when we know the caller already made one.\n // Do NOT replace with duck-typing or string comparison — the identity check is intentional.\n if (handler === builtInSort) {\n // Fast path: caller (#rebuildRowModel) already passed a copy of #rows.\n // Save a snapshot for \"clear sort\" unless the caller already did.\n if (!skipOriginalOrderSave) {\n grid.__originalOrder = rows.slice();\n }\n executeBuiltInSortInPlace(\n rows,\n grid._sortState!.field,\n grid._sortState!.direction,\n grid._columns as ColumnConfig<any>[],\n );\n return rows;\n }\n\n // Custom handler: preserve current behavior\n if (!skipOriginalOrderSave) {\n grid.__originalOrder = rows;\n }\n const result = handler(rows, grid._sortState, grid._columns as ColumnConfig<any>[]);\n if (result && typeof (result as Promise<unknown[]>).then === 'function') return rows;\n return result as T[];\n}\n\n/**\n * Apply a concrete sort direction to rows.\n *\n * Uses custom sortHandler from gridConfig if provided, otherwise uses built-in sorting.\n * Supports both sync and async handlers (for server-side sorting).\n *\n * When row-model plugins are active (grouping, tree, pivot), delegates to the render\n * scheduler so the full pipeline (reapplyCoreSort → processRows) runs on base rows.\n * This prevents sorting from corrupting plugin-generated row structures.\n */\nexport function applySort(grid: GridHost, col: ColumnConfig<any>, dir: 1 | -1): void {\n grid._sortState = { field: col.field, direction: dir };\n\n // When row-model plugins are active, delegate to the render scheduler.\n // #rebuildRowModel will call reapplyCoreSort on the base rows, then processRows\n // rebuilds groups/trees on the sorted data.\n if (hasRowStructurePlugins(grid)) {\n // RenderPhase.ROWS = 4\n grid._requestSchedulerPhase(4, 'sort-apply');\n emitSortChange(grid, col, dir);\n return;\n }\n\n // Fast path: no row-model plugins — sort _rows directly.\n const sortState: SortState = { field: col.field, direction: dir };\n const columns = grid._columns as ColumnConfig<any>[];\n\n // Get custom handler from effectiveConfig, or use built-in\n const handler: SortHandler<any> = grid.effectiveConfig?.sortHandler ?? builtInSort;\n\n // Reference equality gate — see comment in reapplyCoreSort above.\n if (handler === builtInSort) {\n // Fast path: sort grid._rows in-place — avoids allocating a 1M-element copy.\n // __originalOrder was already saved by toggleSort before calling applySort.\n executeBuiltInSortInPlace(grid._rows as any[], sortState.field, dir, columns);\n finalizeSortResult(grid, grid._rows, col, dir);\n return;\n }\n\n const result = handler(grid._rows, sortState, columns);\n\n // Handle async (Promise) or sync result\n if (result && typeof (result as Promise<unknown[]>).then === 'function') {\n // Async handler - wait for result\n (result as Promise<unknown[]>).then((sortedRows) => {\n finalizeSortResult(grid, sortedRows, col, dir);\n });\n } else {\n // Sync handler - apply immediately\n finalizeSortResult(grid, result as unknown[], col, dir);\n }\n}\n","/**\n * Centralized diagnostic messages for @toolbox-web/grid.\n *\n * Every user-facing warning, error, or info message in the grid has a unique\n * diagnostic code (e.g. `TBW001`). Each code maps to a section on the online\n * troubleshooting page, giving developers a direct link to resolution steps.\n *\n * ## Usage\n *\n * ```ts\n * import { MISSING_BREAKPOINT, warnDiagnostic, throwDiagnostic } from './diagnostics';\n *\n * // Warn with a code\n * warnDiagnostic(MISSING_BREAKPOINT, 'Set a breakpoint...', gridId);\n *\n * // Throw with a code\n * throwDiagnostic(MISSING_ROW_ID, 'Configure getRowId...', gridId);\n * ```\n *\n * Plugins should prefer `this.warn(MISSING_BREAKPOINT, message)` via BaseGridPlugin\n * instead of importing this module directly.\n *\n * @internal\n */\n\n// #region Grid Prefix\n\n/**\n * Build the `[tbw-grid]` or `[tbw-grid#my-id]` log prefix.\n * Pass `pluginName` for a scoped prefix like `[tbw-grid:SelectionPlugin]`.\n */\nexport function gridPrefix(gridId?: string, pluginName?: string): string {\n const id = gridId ? `#${gridId}` : '';\n const plugin = pluginName ? `:${pluginName}` : '';\n return `[tbw-grid${id}${plugin}]`;\n}\n\n// #endregion\n\n// #region Diagnostic Codes\n\n/**\n * Diagnostic codes used across the grid library.\n *\n * Each code is an individual export so that unused codes are tree-shaken\n * from bundles that don't reference them (esbuild can't tree-shake\n * properties from a single object).\n *\n * Naming: TBW + 3-digit number.\n * Ranges:\n * 001–019 Configuration validation (missing plugins, bad config)\n * 020–029 Plugin lifecycle (dependencies, incompatibilities, alias collapse)\n * 030–039 Feature registry\n * 040–049 Row operations (row ID, row mutations)\n * 050–059 Column operations (width, template)\n * 060–069 Rendering (callbacks, formatters, external views)\n * 070–079 Shell (tool panels, header/toolbar content)\n * 080–089 Editing & editors\n * 090–099 Print\n * 100–109 Clipboard\n * 110–119 Plugin-specific (responsive, undo-redo, grouping-columns)\n * 120–129 Style injection\n * 130–139 Attribute parsing\n * 140–149 DataSource / ServerSide\n */\n\n// --- Config validation (001–019) ---\n/** Column uses a plugin-owned property but the plugin is not loaded. */\nexport const MISSING_PLUGIN = 'TBW001' as const;\n/** Grid config uses a plugin-owned property but the plugin is not loaded. */\nexport const MISSING_PLUGIN_CONFIG = 'TBW002' as const;\n/** Plugin config rule violation (error severity). */\nexport const CONFIG_RULE_ERROR = 'TBW003' as const;\n/** Plugin config rule violation (warning severity). */\nexport const CONFIG_RULE_WARN = 'TBW004' as const;\n\n// --- Plugin lifecycle (020–029) ---\n/** Required plugin dependency is missing. */\nexport const MISSING_DEPENDENCY = 'TBW020' as const;\n/** Optional plugin dependency is missing. */\nexport const OPTIONAL_DEPENDENCY = 'TBW021' as const;\n/** Two loaded plugins are incompatible. */\nexport const INCOMPATIBLE_PLUGINS = 'TBW022' as const;\n/** Two plugin instances resolve to the same canonical name (alias collapse). */\nexport const PLUGIN_ALIAS_COLLAPSE = 'TBW023' as const;\n/** Error thrown inside a plugin event handler. */\nexport const PLUGIN_EVENT_ERROR = 'TBW024' as const;\n/** Conflicting config values found while merging alias-collapsed plugin instances. */\nexport const PLUGIN_ALIAS_CONFIG_CONFLICT = 'TBW025' as const;\n\n// --- Feature registry (030–039) ---\n/** Feature was re-registered (overwritten). */\nexport const FEATURE_REREGISTERED = 'TBW030' as const;\n/** Feature configured but not imported. */\nexport const FEATURE_NOT_IMPORTED = 'TBW031' as const;\n/** Feature depends on another feature that is not enabled. */\nexport const FEATURE_MISSING_DEP = 'TBW032' as const;\n\n// --- Row operations (040–049) ---\n/** Cannot determine row ID (no getRowId and no id property). */\nexport const MISSING_ROW_ID = 'TBW040' as const;\n/** Row with given ID not found. */\nexport const ROW_NOT_FOUND = 'TBW041' as const;\n\n// --- Column operations (050–059) ---\n/** Column has an invalid CSS width value. */\nexport const INVALID_COLUMN_WIDTH = 'TBW050' as const;\n\n// --- Rendering callbacks (060–069) ---\n/** rowClass callback threw an error. */\nexport const ROW_CLASS_ERROR = 'TBW060' as const;\n/** cellClass callback threw an error. */\nexport const CELL_CLASS_ERROR = 'TBW061' as const;\n/** Column format function threw an error. */\nexport const FORMAT_ERROR = 'TBW062' as const;\n/** External view mount() threw an error. */\nexport const VIEW_MOUNT_ERROR = 'TBW063' as const;\n/** External view event dispatch error. */\nexport const VIEW_DISPATCH_ERROR = 'TBW064' as const;\n\n// --- Shell (070–079) ---\n/** Tool panel missing required id. */\nexport const TOOL_PANEL_MISSING_ATTR = 'TBW070' as const;\n/** No tool panels registered. */\nexport const NO_TOOL_PANELS = 'TBW071' as const;\n/** Tool panel section not found. */\nexport const TOOL_PANEL_NOT_FOUND = 'TBW072' as const;\n/** Tool panel already registered. */\nexport const TOOL_PANEL_DUPLICATE = 'TBW073' as const;\n/** Header content already registered. */\nexport const HEADER_CONTENT_DUPLICATE = 'TBW074' as const;\n/** Toolbar content already registered. */\nexport const TOOLBAR_CONTENT_DUPLICATE = 'TBW075' as const;\n\n// --- Editing & editors (080–089) ---\n/** External editor mount() threw an error. */\nexport const EDITOR_MOUNT_ERROR = 'TBW080' as const;\n\n// --- Print (090–099) ---\n/** Print already in progress. */\nexport const PRINT_IN_PROGRESS = 'TBW090' as const;\n/** Grid not available for printing. */\nexport const PRINT_NO_GRID = 'TBW091' as const;\n/** Print operation failed. */\nexport const PRINT_FAILED = 'TBW092' as const;\n/** Multiple elements share the same grid ID (print isolation issue). */\nexport const PRINT_DUPLICATE_ID = 'TBW093' as const;\n\n// --- Clipboard (100–109) ---\n/** Clipboard API write failed. */\nexport const CLIPBOARD_FAILED = 'TBW100' as const;\n\n// --- Plugin-specific (110–119) ---\n/** ResponsivePlugin: no breakpoint configured. */\nexport const MISSING_BREAKPOINT = 'TBW110' as const;\n/** UndoRedoPlugin: transaction already in progress. */\nexport const TRANSACTION_IN_PROGRESS = 'TBW111' as const;\n/** UndoRedoPlugin: no transaction in progress. */\nexport const NO_TRANSACTION = 'TBW112' as const;\n/** GroupingColumnsPlugin: missing id or header on column group definition. */\nexport const COLUMN_GROUP_NO_ID = 'TBW113' as const;\n/** GroupingColumnsPlugin: conflicting columnGroups sources. */\nexport const COLUMN_GROUPS_CONFLICT = 'TBW114' as const;\n\n// --- Style injection (120–129) ---\n/** Failed to extract grid.css from document stylesheets. */\nexport const STYLE_EXTRACT_FAILED = 'TBW120' as const;\n/** Could not find grid.css in document.styleSheets. */\nexport const STYLE_NOT_FOUND = 'TBW121' as const;\n\n// --- Attribute parsing (130–139) ---\n/** Invalid JSON in an HTML attribute. */\nexport const INVALID_ATTRIBUTE_JSON = 'TBW130' as const;\n\n// --- DataSource / ServerSide (140–149) ---\n/** ServerSidePlugin: getRows() rejected. */\nexport const DATASOURCE_FETCH_ERROR = 'TBW140' as const;\n/** ServerSidePlugin: getChildRows() rejected. */\nexport const DATASOURCE_CHILD_FETCH_ERROR = 'TBW141' as const;\n/** ServerSidePlugin: getChildRows() not implemented but a plugin queried for children. */\nexport const DATASOURCE_NO_CHILD_HANDLER = 'TBW142' as const;\n/** ServerSidePlugin: concurrent request limit reached, request deferred. */\nexport const DATASOURCE_THROTTLED = 'TBW143' as const;\n\nexport type DiagnosticCode =\n | typeof MISSING_PLUGIN\n | typeof MISSING_PLUGIN_CONFIG\n | typeof CONFIG_RULE_ERROR\n | typeof CONFIG_RULE_WARN\n | typeof MISSING_DEPENDENCY\n | typeof OPTIONAL_DEPENDENCY\n | typeof INCOMPATIBLE_PLUGINS\n | typeof PLUGIN_ALIAS_COLLAPSE\n | typeof PLUGIN_EVENT_ERROR\n | typeof PLUGIN_ALIAS_CONFIG_CONFLICT\n | typeof FEATURE_REREGISTERED\n | typeof FEATURE_NOT_IMPORTED\n | typeof FEATURE_MISSING_DEP\n | typeof MISSING_ROW_ID\n | typeof ROW_NOT_FOUND\n | typeof INVALID_COLUMN_WIDTH\n | typeof ROW_CLASS_ERROR\n | typeof CELL_CLASS_ERROR\n | typeof FORMAT_ERROR\n | typeof VIEW_MOUNT_ERROR\n | typeof VIEW_DISPATCH_ERROR\n | typeof TOOL_PANEL_MISSING_ATTR\n | typeof NO_TOOL_PANELS\n | typeof TOOL_PANEL_NOT_FOUND\n | typeof TOOL_PANEL_DUPLICATE\n | typeof HEADER_CONTENT_DUPLICATE\n | typeof TOOLBAR_CONTENT_DUPLICATE\n | typeof EDITOR_MOUNT_ERROR\n | typeof PRINT_IN_PROGRESS\n | typeof PRINT_NO_GRID\n | typeof PRINT_FAILED\n | typeof PRINT_DUPLICATE_ID\n | typeof CLIPBOARD_FAILED\n | typeof MISSING_BREAKPOINT\n | typeof TRANSACTION_IN_PROGRESS\n | typeof NO_TRANSACTION\n | typeof COLUMN_GROUP_NO_ID\n | typeof COLUMN_GROUPS_CONFLICT\n | typeof STYLE_EXTRACT_FAILED\n | typeof STYLE_NOT_FOUND\n | typeof INVALID_ATTRIBUTE_JSON\n | typeof DATASOURCE_FETCH_ERROR\n | typeof DATASOURCE_CHILD_FETCH_ERROR\n | typeof DATASOURCE_NO_CHILD_HANDLER\n | typeof DATASOURCE_THROTTLED;\n\n// #endregion\n\n// #region Docs URL\n\nconst DOCS_BASE = 'https://toolboxjs.com/grid/errors';\n\n/** Build a direct link to the troubleshooting section for a code. */\nfunction docsUrl(code: DiagnosticCode): string {\n return `${DOCS_BASE}#${code.toLowerCase()}`;\n}\n\n// #endregion\n\n// #region Formatting\n\n/**\n * Format a diagnostic message with prefix, code, and docs link.\n *\n * Output format:\n * ```\n * [tbw-grid#my-id] TBW001: Your message here.\n *\n * → More info: https://toolboxjs.com/grid/errors#tbw001\n * ```\n */\nexport function formatDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): string {\n const prefix = gridPrefix(gridId, pluginName);\n return `${prefix} ${code}: ${message}\\n\\n → More info: ${docsUrl(code)}`;\n}\n\n// #endregion\n\n// #region Public API\n\n/**\n * Throw an error with a diagnostic code and docs link.\n * Use for configuration errors and API misuse that should halt execution.\n */\nexport function throwDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): never {\n throw new Error(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log a warning with a diagnostic code and docs link.\n * Use for recoverable issues the developer should fix.\n */\nexport function warnDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.warn(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log a debug message with a diagnostic code and docs link.\n * Use for optional/soft dependency notifications — visible only when\n * the browser DevTools \"Verbose\" log level is enabled.\n */\nexport function debugDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.debug(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log an error with a diagnostic code and docs link.\n * Use for non-throwing errors (e.g., failed async operations).\n */\nexport function errorDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.error(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n// #endregion\n","/**\n * Base Grid Plugin Class\n *\n * All plugins extend this abstract class.\n * Plugins are instantiated per-grid and manage their own state.\n */\n\n// Injected by Vite at build time from package.json (same as grid.ts)\ndeclare const __GRID_VERSION__: string;\n\nimport type { HeaderContentDefinition, ToolPanelDefinition } from '../../plugins/shell/types';\nimport { DEFAULT_GRID_ICONS } from '../defaults';\nimport {\n type DiagnosticCode,\n PLUGIN_ALIAS_CONFIG_CONFLICT,\n formatDiagnostic,\n gridPrefix,\n} from '../internal/diagnostics';\nimport { setSanitizedHTML } from '../internal/sanitize';\nimport type {\n ColumnConfig,\n ColumnState,\n GridConfig,\n GridIcons,\n GridPlugin,\n IconValue,\n PluginNameMap,\n Translate,\n} from '../types';\n\n// Re-export shared plugin types for convenience\nexport type {\n AfterCellRenderContext,\n AfterRowRenderContext,\n CellClickEvent,\n CellCoords,\n CellEditor,\n CellMouseEvent,\n CellRenderer,\n ContextMenuItem,\n ContextMenuParams,\n GridElementRef,\n HeaderClickEvent,\n HeaderRenderer,\n KeyboardModifiers,\n PluginCellRenderContext,\n PluginQuery,\n RowClickEvent,\n ScrollEvent,\n} from './types';\n\nimport type {\n AfterCellRenderContext,\n AfterRowRenderContext,\n CellClickEvent,\n CellEditor,\n CellMouseEvent,\n CellRenderer,\n GridElementRef,\n HeaderClickEvent,\n HeaderRenderer,\n PluginQuery,\n RowClickEvent,\n ScrollEvent,\n} from './types';\n\n/**\n * Grid element interface for plugins.\n * Extends GridElementRef with plugin-specific methods.\n * Note: effectiveConfig is already available from GridElementRef.\n */\nexport interface GridElement extends GridElementRef {\n getPlugin<T extends GridPlugin>(PluginClass: new (...args: any[]) => T): T | undefined;\n getPluginByName<K extends string>(\n name: K,\n ): (K extends keyof PluginNameMap ? PluginNameMap[K] : BaseGridPlugin) | undefined;\n /**\n * Get a plugin's state by plugin name.\n * This is a loose-coupling method for plugins to access other plugins' state\n * without importing the plugin class directly.\n * @internal Plugin API\n */\n getPluginState?(name: string): unknown;\n\n // Focus Management\n /** Register an external DOM element as a logical focus container. @internal Plugin API */\n registerExternalFocusContainer?(el: Element): void;\n /** Unregister a previously registered external focus container. @internal Plugin API */\n unregisterExternalFocusContainer?(el: Element): void;\n /** Check whether focus is logically inside this grid (own DOM + external containers). @internal Plugin API */\n containsFocus?(node?: Node | null): boolean;\n}\n\n/**\n * Header render context for plugin header renderers.\n */\nexport interface PluginHeaderRenderContext {\n /** Column configuration */\n column: ColumnConfig;\n /** Column index */\n colIndex: number;\n}\n\n// ============================================================================\n// Plugin Dependency Types\n// ============================================================================\n\n/**\n * Declares a dependency on another plugin.\n *\n * @category Plugin Development\n * @example\n * ```typescript\n * export class UndoRedoPlugin extends BaseGridPlugin {\n * static readonly dependencies: PluginDependency[] = [\n * { name: 'editing', required: true },\n * ];\n * }\n * ```\n * @since 0.4.1\n */\nexport interface PluginDependency {\n /**\n * The name of the required plugin (matches the plugin's `name` property).\n * Use string names for loose coupling - avoids static imports.\n */\n name: string;\n\n /**\n * Whether this dependency is required (hard) or optional (soft).\n * - `true`: Plugin cannot function without it. Throws error if missing.\n * - `false`: Plugin works with reduced functionality. Silent if missing\n * (set {@link severity} to `'warn'` or `'info'` to opt into a message).\n * @default true\n */\n required?: boolean;\n\n /**\n * Explicit severity when this dependency is missing. Overrides the default\n * derived from {@link required}.\n * - `'error'`: throw (halts grid setup). Default when `required` is not `false`.\n * - `'warn'`: log a console warning and continue (development only).\n * - `'info'`: log a verbose console.debug message and continue (development only).\n *\n * When omitted, a missing hard dependency throws and a missing soft\n * dependency is silent — preserving backward-compatible behavior.\n * @since 2.16.0\n */\n severity?: 'error' | 'warn' | 'info';\n\n /**\n * Optional predicate that gates whether this dependency applies, evaluated\n * against the depending plugin's own resolved configuration (defaults merged\n * with user config). Return `false` to skip the dependency entirely.\n *\n * Lets a plugin require/recommend another plugin only under certain config\n * — e.g. a plugin that needs a tool-panel host only when its tool panel is\n * enabled. When omitted, the dependency always applies.\n * @example when: (cfg: PivotConfig) => cfg.showToolPanel === true\n * @since 2.16.0\n */\n when?: (pluginConfig: unknown) => boolean;\n\n /**\n * Factory for a default instance of the dependency. When the dependency is\n * missing, the grid attaches the instance this returns (once per grid,\n * before the depending plugin) instead of reporting an error, so consumers\n * never have to add it themselves. An explicitly configured instance always\n * wins.\n *\n * Import the dependency's plugin module statically so it ships with the\n * depending plugin's module graph — never with `import()`.\n *\n * @example provide: () => new HierarchyPlugin()\n * @since 3.9.0\n */\n provide?: () => BaseGridPlugin;\n\n /**\n * Human-readable reason for this dependency.\n * Shown in error/info messages to help users understand why.\n * @example \"UndoRedoPlugin needs EditingPlugin to track cell edits\"\n */\n reason?: string;\n}\n\n/**\n * Declares an incompatibility between plugins.\n * When both plugins are loaded, a warning is logged to help users understand the conflict.\n *\n * @category Plugin Development\n */\nexport interface PluginIncompatibility {\n /**\n * The name of the incompatible plugin (matches the plugin's `name` property).\n */\n name: string;\n\n /**\n * Human-readable reason for the incompatibility.\n * Should explain why the plugins conflict and any workarounds.\n * @example \"Both transform the entire row model in different ways\"\n */\n reason: string;\n}\n\n// ============================================================================\n// Plugin Query & Event Definitions\n// ============================================================================\n\n/**\n * Defines a query that a plugin can handle.\n * Other plugins or the grid can send this query type to retrieve data.\n *\n * @category Plugin Development\n *\n * @example\n * ```typescript\n * // In manifest\n * queries: [\n * {\n * type: 'canMoveColumn',\n * description: 'Check if a column can be moved/reordered',\n * },\n * ]\n *\n * // In plugin class\n * handleQuery(query: PluginQuery): unknown {\n * if (query.type === 'canMoveColumn') {\n * return this.canMoveColumn(query.context);\n * }\n * }\n * ```\n * @since 1.8.0\n */\nexport interface QueryDefinition {\n /**\n * The query type identifier (e.g., 'canMoveColumn', 'getContextMenuItems').\n * Should be unique across all plugins.\n */\n type: string;\n\n /**\n * Human-readable description of what the query does.\n */\n description?: string;\n}\n\n/**\n * Defines an event that a plugin can emit.\n * Other plugins can subscribe to these events via the Event Bus.\n *\n * @category Plugin Development\n *\n * @example\n * ```typescript\n * // In manifest\n * events: [\n * {\n * type: 'filter-change',\n * description: 'Emitted when filter criteria change',\n * },\n * ]\n *\n * // In plugin class - emit\n * this.emitPluginEvent('filter-change', { field: 'name', value: 'Alice' });\n *\n * // In another plugin - subscribe\n * this.on('filter-change', (detail) => console.log('Filter changed:', detail));\n * ```\n * @since 1.8.0\n */\nexport interface EventDefinition {\n /**\n * The event type identifier (e.g., 'filter-change', 'selection-change').\n * Used when emitting and subscribing to events.\n */\n type: string;\n\n /**\n * Human-readable description of what the event represents.\n */\n description?: string;\n\n /**\n * Whether this event is cancelable via `event.preventDefault()`.\n * @default false\n */\n cancelable?: boolean;\n}\n\n// ============================================================================\n// Plugin Manifest Types\n// ============================================================================\n\n/**\n * Defines a property that a plugin \"owns\" - used for configuration validation.\n * When this property is used without the owning plugin loaded, an error is thrown.\n *\n * @category Plugin Development\n */\nexport interface PluginPropertyDefinition {\n /** The property name on column or grid config */\n property: string;\n /** Whether this is a column-level or config-level property */\n level: 'column' | 'config';\n /** Human-readable description for error messages (e.g., 'the \"editable\" column property') */\n description: string;\n /** Import path hint for error messages (e.g., \"import { EditingPlugin } from '@toolbox-web/grid/plugins/editing';\") */\n importHint?: string;\n /** Custom check for whether property is considered \"used\" (default: truthy value check) */\n isUsed?: (value: unknown) => boolean;\n}\n\n/**\n * A configuration validation rule for detecting invalid/conflicting settings.\n * Plugins declare rules in their manifest; the validator executes them during grid initialization.\n *\n * @category Plugin Development\n * @template TConfig - The plugin's configuration type\n */\nexport interface PluginConfigRule<TConfig = unknown> {\n /** Rule identifier for debugging (e.g., 'selection/range-dblclick') */\n id: string;\n /** Severity: 'error' throws, 'warn' logs warning */\n severity: 'error' | 'warn';\n /** Human-readable message shown when rule is violated */\n message: string;\n /** Predicate returning true if the rule is VIOLATED (i.e., config is invalid) */\n check: (pluginConfig: TConfig) => boolean;\n}\n\n/**\n * Hook names that can have execution priority configured.\n *\n * @category Plugin Development\n */\nexport type HookName =\n | 'processColumns'\n | 'processConfig'\n | 'processRows'\n | 'afterStructuralRender'\n | 'afterRender'\n | 'afterCellRender'\n | 'afterRowRender'\n | 'onCellClick'\n | 'onCellMouseDown'\n | 'onCellMouseMove'\n | 'onCellMouseUp'\n | 'onHeaderClick'\n | 'onKeyDown'\n | 'onRowClick'\n | 'onScroll'\n | 'onScrollRender';\n\n/**\n * Static metadata about a plugin's capabilities and requirements.\n * Declared as a static property on plugin classes.\n *\n * @category Plugin Development\n * @template TConfig - The plugin's configuration type\n *\n * @example\n * ```typescript\n * export class MyPlugin extends BaseGridPlugin<MyConfig> {\n * static override readonly manifest: PluginManifest<MyConfig> = {\n * ownedProperties: [\n * { property: 'myProp', level: 'column', description: 'the \"myProp\" column property' },\n * ],\n * configRules: [\n * { id: 'my-plugin/invalid-combo', severity: 'warn', message: '...', check: (c) => c.a && c.b },\n * ],\n * };\n * readonly name = 'myPlugin';\n * }\n * ```\n * @since 1.1.0\n */\nexport interface PluginManifest<TConfig = unknown> {\n /**\n * Properties this plugin owns - validated by validate-config.ts.\n * If a user uses one of these properties without loading the plugin, an error is thrown.\n */\n ownedProperties?: PluginPropertyDefinition[];\n\n /**\n * Hook execution priority (higher = later, default 0).\n * Use negative values to run earlier, positive to run later.\n */\n hookPriority?: Partial<Record<HookName, number>>;\n\n /**\n * Configuration validation rules - checked during grid initialization.\n * Rules with severity 'error' throw, 'warn' logs to console.\n */\n configRules?: PluginConfigRule<TConfig>[];\n\n /**\n * Plugins that are incompatible with this plugin.\n * When both plugins are loaded together, a warning is shown.\n *\n * @example\n * ```typescript\n * incompatibleWith: [\n * { name: 'tree', reason: 'Both transform the entire row model in different ways' },\n * ],\n * ```\n */\n incompatibleWith?: PluginIncompatibility[];\n\n /**\n * Queries this plugin can handle.\n * Declares what query types this plugin responds to via `handleQuery()`.\n * This replaces the centralized PLUGIN_QUERIES approach with manifest-declared queries.\n *\n * @example\n * ```typescript\n * queries: [\n * { type: 'canMoveColumn', description: 'Check if a column can be moved' },\n * ],\n * ```\n */\n queries?: QueryDefinition[];\n\n /**\n * Events this plugin can emit.\n * Declares what event types other plugins can subscribe to via `on()`.\n *\n * @example\n * ```typescript\n * events: [\n * { type: 'filter-change', description: 'Emitted when filter criteria change' },\n * ],\n * ```\n */\n events?: EventDefinition[];\n\n /**\n * Whether this plugin's `processRows` hook injects or removes rows\n * (group headers, tree nodes, pivot aggregates, placeholders, etc.).\n *\n * When true, the core sorting module delegates to the render scheduler\n * instead of sorting `_rows` in-place, because `_rows` may contain\n * plugin-generated marker objects that would be corrupted by a direct sort.\n *\n * Plugins that only **filter** or **reorder** existing rows (e.g. Filtering,\n * MultiSort) should leave this unset or set it to `false`.\n */\n modifiesRowStructure?: boolean;\n}\n\n/** Convert camelCase icon key to kebab-case data-icon attribute value. */\nexport function toIconAttr(key: string): string {\n return key.replace(/([A-Z])/g, '-$1').toLowerCase();\n}\n\n/**\n * Abstract base class for all grid plugins.\n *\n * @category Plugin Development\n * @template TConfig - Configuration type for the plugin\n * @since 0.1.1\n */\nexport abstract class BaseGridPlugin<TConfig = unknown> implements GridPlugin {\n /**\n * Plugin dependencies - declare other plugins this one requires.\n *\n * Dependencies are validated when the plugin is attached.\n * Required dependencies throw an error if missing. Optional dependencies are\n * silent by default; set a {@link PluginDependency.severity} of `'warn'` or\n * `'info'` to opt into a development-only log.\n *\n * @example\n * ```typescript\n * static readonly dependencies: PluginDependency[] = [\n * { name: 'editing', required: true, reason: 'Tracks cell edits for undo/redo' },\n * { name: 'selection', required: false, reason: 'Enables selection-based undo' },\n * ];\n * ```\n */\n static readonly dependencies?: PluginDependency[];\n\n /**\n * Plugin manifest - declares owned properties, config rules, and hook priorities.\n *\n * This is read by the configuration validator to:\n * - Validate that required plugins are loaded when their properties are used\n * - Execute configRules to detect invalid/conflicting settings\n * - Order hook execution based on priority\n *\n * @example\n * ```typescript\n * static override readonly manifest: PluginManifest<MyConfig> = {\n * ownedProperties: [\n * { property: 'myProp', level: 'column', description: 'the \"myProp\" column property' },\n * ],\n * configRules: [\n * { id: 'myPlugin/conflict', severity: 'warn', message: '...', check: (c) => c.a && c.b },\n * ],\n * };\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static readonly manifest?: PluginManifest<any>;\n\n /** Unique plugin identifier (derived from class name by default) */\n abstract readonly name: string;\n\n /**\n * Alternative names for backward compatibility.\n * `getPluginByName()` matches against both `name` and `aliases`.\n * @internal\n */\n readonly aliases?: readonly string[];\n\n /**\n * Plugin version - defaults to grid version for built-in plugins.\n * Third-party plugins can override with their own semver.\n */\n readonly version: string = typeof __GRID_VERSION__ !== 'undefined' ? __GRID_VERSION__ : 'dev';\n\n /** CSS styles to inject via `document.adoptedStyleSheets` */\n readonly styles?: string;\n\n /** Custom cell renderers keyed by type name */\n readonly cellRenderers?: Record<string, CellRenderer>;\n\n /** Custom header renderers keyed by type name */\n readonly headerRenderers?: Record<string, HeaderRenderer>;\n\n /** Custom cell editors keyed by type name */\n readonly cellEditors?: Record<string, CellEditor>;\n\n /** The grid instance this plugin is attached to */\n protected grid!: GridElement;\n\n /** Plugin configuration - merged with defaults in attach() */\n protected config!: TConfig;\n\n /** User-provided configuration from constructor */\n protected readonly userConfig: Partial<TConfig>;\n\n /**\n * Plugin-level AbortController for event listener cleanup.\n * Created fresh in attach(), aborted in detach().\n * This ensures event listeners are properly cleaned up when plugins are re-attached.\n */\n #abortController?: AbortController;\n\n /**\n * Default configuration - subclasses should override this getter.\n * Note: This must be a getter (not property initializer) for proper inheritance\n * since property initializers run after parent constructor.\n */\n protected get defaultConfig(): Partial<TConfig> {\n return {};\n }\n\n constructor(config: Partial<TConfig> = {}) {\n this.userConfig = config;\n }\n\n /**\n * Effective configuration (defaults merged with user config), resolved\n * eagerly so it is available **before** {@link attach} runs. Dependency\n * validation happens before `attach()` merges {@link config}, so config\n * -conditional dependency `when` predicates evaluate against this getter.\n *\n * While attached, returns the already-merged {@link config}; otherwise\n * recomputes `defaultConfig` + `userConfig` fresh. `config` is intentionally\n * **not** trusted when detached because {@link detach} does not clear it — a\n * re-validated plugin would otherwise see stale config from a prior\n * attachment. The {@link attach}-managed abort controller is the\n * attached/detached signal.\n * @internal Plugin infrastructure (used by `validatePluginDependencies`).\n */\n get resolvedConfig(): TConfig {\n return (this.#abortController ? this.config : { ...this.defaultConfig, ...this.userConfig }) as TConfig;\n }\n\n /**\n * Merge user-supplied configuration from other plugin instances into this\n * plugin's `userConfig`. Used by `PluginManager.attachAll()`'s alias-collapse\n * pre-pass: when a consumer instantiates the same plugin more than once (or\n * under an alias name), only one instance is attached, and the other\n * instances' configs are folded in via this method.\n *\n * Merge rules (shallow):\n *\n * - Same key, **same value** → silent.\n * - Same key, **different values** (incl. function vs function) → throws\n * a diagnostic naming the conflicting key. Conflicting callbacks\n * (`canDrag`, `canDrop`, etc.) cannot be reconciled automatically.\n * - **Disjoint keys** → merged cleanly.\n *\n * Subclasses may override to implement custom deep-merge logic, but should\n * call `super.mergeConfigsFrom(others)` to inherit the conflict-detection.\n *\n * @internal Plugin infrastructure (used by `PluginManager.attachAll`).\n * @throws Error with diagnostic code `TBW025` when configs conflict.\n */\n mergeConfigsFrom(others: readonly BaseGridPlugin<TConfig>[]): void {\n if (others.length === 0) return;\n const merged = { ...this.userConfig } as Record<string, unknown>;\n const sources: Record<string, BaseGridPlugin<TConfig>> = {};\n for (const key of Object.keys(merged)) sources[key] = this;\n for (const other of others) {\n const otherConfig = other.userConfig as Record<string, unknown>;\n for (const [key, value] of Object.entries(otherConfig)) {\n if (value === undefined) continue;\n if (!(key in merged)) {\n merged[key] = value;\n sources[key] = other;\n continue;\n }\n if (merged[key] === value) continue;\n // Conflict\n const ownerA = sources[key]?.constructor.name ?? this.constructor.name;\n const ownerB = other.constructor.name;\n const code = formatDiagnostic(\n PLUGIN_ALIAS_CONFIG_CONFLICT,\n `Cannot merge plugin configs for \"${this.name}\": conflicting value for \"${key}\" supplied by both ${ownerA} and ${ownerB}. Pass the option on a single instance, or remove the duplicate.`,\n undefined,\n this.name,\n );\n throw new Error(code);\n }\n }\n // Mutate userConfig in place so re-attach picks it up via attach().\n // `userConfig` is declared `readonly` to prevent reassigning the binding,\n // but the object's own properties are intentionally mutable for this\n // alias-collapse pre-pass. A single cast to a record is enough — no\n // `as unknown as` double-cast needed.\n Object.assign(this.userConfig as Record<string, unknown>, merged);\n }\n\n /**\n * Replace this plugin's `userConfig` with a freshly-resolved sibling\n * instance's config. Used by the grid's per-grid feature-instance gate\n * (`#initializePlugins`): when a feature is re-resolved across a config\n * change, the **existing** instance is reused — so its accumulated state\n * survives — but it must adopt the latest `gridConfig.features.<name>`\n * value. Unlike {@link mergeConfigsFrom}, this is last-write-wins with no\n * conflict detection: the re-resolved instance is authoritative.\n *\n * `attach()` recomputes {@link config} from `userConfig`, so updating\n * `userConfig` here is enough for the reused instance to pick up the new\n * config on its next attach during the same `#initializePlugins` pass.\n *\n * @internal Plugin infrastructure (used by the grid feature gate).\n */\n refreshUserConfigFrom(other: BaseGridPlugin<TConfig>): void {\n const target = this.userConfig as Record<string, unknown>;\n // Snapshot the source BEFORE clearing `target`. A feature factory may\n // store the consumer's config object by reference (e.g. `new\n // ContextMenuPlugin(config)`), and a consumer that passes the *same* config\n // object across re-resolutions (common when `gridConfig` is a recomputed\n // Angular `computed()`) makes `this.userConfig === other.userConfig`.\n // Without this snapshot, the `delete` loop below would empty that shared\n // object first, then `Object.assign` would copy back nothing — silently\n // wiping the config and falling back to plugin defaults. (#contextMenu)\n const source = { ...(other.userConfig as Record<string, unknown>) };\n for (const key of Object.keys(target)) delete target[key];\n Object.assign(target, source);\n }\n\n /**\n * Called when the plugin is attached to a grid.\n * Override to set up event listeners, initialize state, etc.\n *\n * @example\n * ```ts\n * attach(grid: GridElement): void {\n * super.attach(grid);\n * // Set up document-level listeners with auto-cleanup\n * document.addEventListener('keydown', this.handleEscape, {\n * signal: this.disconnectSignal\n * });\n * }\n * ```\n */\n attach(grid: GridElement): void {\n // Abort any previous abort controller (in case of re-attach without detach)\n this.#abortController?.abort();\n // Create fresh abort controller for this attachment\n this.#abortController = new AbortController();\n\n this.grid = grid;\n // Merge config here (after subclass construction is complete)\n this.config = { ...this.defaultConfig, ...this.userConfig } as TConfig;\n }\n\n /**\n * Called when the plugin is detached from a grid.\n * Override to clean up event listeners, timers, etc.\n *\n * @example\n * ```ts\n * detach(): void {\n * // Clean up any state not handled by disconnectSignal\n * this.selectedRows.clear();\n * this.cache = null;\n * }\n * ```\n */\n detach(): void {\n // Abort the plugin's abort controller to clean up all event listeners\n // registered with { signal: this.disconnectSignal }\n this.#abortController?.abort();\n this.#abortController = undefined;\n // Override in subclass for additional cleanup\n }\n\n /**\n * Called when another plugin is attached to the same grid.\n * Use for inter-plugin coordination, e.g., to integrate with new plugins.\n *\n * @param name - The name of the plugin that was attached\n * @param plugin - The plugin instance (for direct access if needed)\n *\n * @example\n * ```ts\n * onPluginAttached(name: string, plugin: BaseGridPlugin): void {\n * if (name === 'selection') {\n * // Integrate with selection plugin\n * this.selectionPlugin = plugin as SelectionPlugin;\n * }\n * }\n * ```\n */\n onPluginAttached?(name: string, plugin: BaseGridPlugin): void;\n\n /**\n * Called when another plugin is detached from the same grid.\n * Use to clean up inter-plugin references.\n *\n * @param name - The name of the plugin that was detached\n *\n * @example\n * ```ts\n * onPluginDetached(name: string): void {\n * if (name === 'selection') {\n * this.selectionPlugin = undefined;\n * }\n * }\n * ```\n */\n onPluginDetached?(name: string): void;\n\n /**\n * Get another plugin instance from the same grid.\n * Use for inter-plugin communication.\n *\n * **Prefer {@link BaseGridPlugin.grid grid.getPluginByName()}** when you don't need the class import.\n *\n * @example\n * ```ts\n * // Preferred: by name\n * const selection = this.grid?.getPluginByName('selection');\n *\n * // Alternative: by class\n * const selection = this.getPlugin(SelectionPlugin);\n * if (selection) {\n * const selectedRows = selection.getSelectedRows();\n * }\n * ```\n */\n protected getPlugin<T extends BaseGridPlugin>(PluginClass: new (...args: any[]) => T): T | undefined {\n return this.grid?.getPlugin(PluginClass);\n }\n\n /**\n * Emit a custom event from the grid.\n */\n protected emit<T>(eventName: string, detail: T): void {\n this.grid?.dispatchEvent?.(new CustomEvent(eventName, { detail, bubbles: true }));\n }\n\n /**\n * Emit a cancelable custom event from the grid.\n * @returns `true` if the event was cancelled (preventDefault called), `false` otherwise\n */\n protected emitCancelable<T>(eventName: string, detail: T): boolean {\n const event = new CustomEvent(eventName, { detail, bubbles: true, cancelable: true });\n this.grid?.dispatchEvent?.(event);\n return event.defaultPrevented;\n }\n\n // =========================================================================\n // Event Bus - Plugin-to-Plugin Communication\n // =========================================================================\n\n /**\n * Subscribe to an event from another plugin.\n * The subscription is automatically cleaned up when this plugin is detached.\n *\n * @category Plugin Development\n * @param eventType - The event type to listen for (e.g., 'filter-change')\n * @param callback - The callback to invoke when the event is emitted\n *\n * @example\n * ```typescript\n * // In attach() or other initialization\n * this.on('filter-change', (detail) => {\n * console.log('Filter changed:', detail);\n * });\n * ```\n */\n protected on<T = unknown>(eventType: string, callback: (detail: T) => void): void {\n this.grid?._pluginManager?.subscribe(this, eventType, callback as (detail: unknown) => void);\n }\n\n /**\n * Unsubscribe from a plugin event.\n *\n * @category Plugin Development\n * @param eventType - The event type to stop listening for\n *\n * @example\n * ```typescript\n * this.off('filter-change');\n * ```\n */\n protected off(eventType: string): void {\n this.grid?._pluginManager?.unsubscribe(this, eventType);\n }\n\n /**\n * Emit an event to other plugins via the Event Bus.\n * This is for inter-plugin communication only; it does NOT dispatch DOM events.\n * Use `emit()` to dispatch DOM events that external consumers can listen to.\n *\n * @category Plugin Development\n * @param eventType - The event type to emit (should be declared in manifest.events)\n * @param detail - The event payload\n *\n * @example\n * ```typescript\n * // Emit to other plugins (not DOM)\n * this.emitPluginEvent('filter-change', { field: 'name', value: 'Alice' });\n *\n * // For DOM events that consumers can addEventListener to:\n * this.emit('filter-change', { field: 'name', value: 'Alice' });\n * ```\n */\n protected emitPluginEvent<T>(eventType: string, detail: T): void {\n this.grid?._pluginManager?.emitPluginEvent(eventType, detail);\n }\n\n /**\n * Emit an event to **both** the plugin Event Bus (for inter-plugin communication)\n * **and** the DOM (for external consumers via `addEventListener`).\n *\n * Use this when a state change is relevant to both other plugins and external\n * consumers. For example, `sort-change` needs to invalidate Selection (plugin bus)\n * and notify the host application (DOM event).\n *\n * @category Plugin Development\n * @param eventType - The event type to broadcast\n * @param detail - The event payload\n *\n * @example\n * ```typescript\n * // Notify both plugins and consumers of a sort change\n * this.broadcast('sort-change', { sortModel: [...this.sortModel] });\n * ```\n */\n protected broadcast<T>(eventType: string, detail: T): void {\n this.emitPluginEvent(eventType, detail);\n this.emit(eventType, detail);\n }\n\n /**\n * Run a yes/no plugin query and reduce the responses to a single boolean.\n *\n * `grid.query()` always returns an **array** of responses (empty when no\n * plugin handles the query), and `[]` is truthy in JavaScript — so testing\n * the raw result directly (`if (grid.query(...))`) is always `true` and\n * silently takes the \"some plugin said yes\" branch even when nothing\n * answered. Always route boolean queries through this helper.\n *\n * @category Plugin Development\n * @param type - The query type to dispatch\n * @param context - Optional query context passed to the handlers\n * @returns `true` only when at least one plugin answered truthily\n *\n * @example\n * ```typescript\n * if (this.queryBoolean('datasource:is-active')) {\n * // A ServerSide data source really is installed\n * }\n * ```\n * @since 3.4.0\n */\n protected queryBoolean(type: string, context: unknown = null): boolean {\n const responses = this.grid?.query?.(type, context);\n // Tolerate hosts/tests that hand back a bare value instead of the array.\n return Array.isArray(responses) ? responses.some(Boolean) : !!responses;\n }\n\n /**\n * Request a re-render of the grid.\n * Uses ROWS phase - does NOT trigger processColumns hooks.\n */\n protected requestRender(): void {\n this.grid?.requestRender?.();\n }\n\n /**\n * Request a columns re-render of the grid.\n * Uses COLUMNS phase - triggers processColumns hooks.\n * Use this when your plugin needs to reprocess column configuration.\n */\n protected requestColumnsRender(): void {\n (this.grid as { requestColumnsRender?: () => void })?.requestColumnsRender?.();\n }\n\n /**\n * Request a re-render and restore focus styling afterward.\n * Use this when a plugin action (like expand/collapse) triggers a render\n * but needs to maintain keyboard navigation focus.\n */\n protected requestRenderWithFocus(): void {\n this.grid?.requestRenderWithFocus?.();\n }\n\n /**\n * Request a lightweight style update without rebuilding DOM.\n * Use this instead of requestRender() when only CSS classes need updating.\n */\n protected requestAfterRender(): void {\n this.grid?.requestAfterRender?.();\n }\n\n /**\n * Re-render visible rows without rebuilding the row model or recalculating geometry.\n * Use this when row data has been updated in-place (e.g., server-side block loads)\n * and only the visible viewport needs to re-render.\n */\n protected requestVirtualRefresh(): void {\n this.grid?.requestVirtualRefresh?.();\n }\n\n /**\n * Get the current rows from the grid.\n */\n protected get rows(): any[] {\n return this.grid?.rows ?? [];\n }\n\n /**\n * Get the original unfiltered/unprocessed rows from the grid.\n * Use this when you need all source data regardless of active filters.\n */\n protected get sourceRows(): any[] {\n return this.grid?.sourceRows ?? [];\n }\n\n /**\n * Get the current columns from the grid.\n */\n protected get columns(): ColumnConfig[] {\n return this.grid?.columns ?? [];\n }\n\n /**\n * Get only visible columns from the grid (excludes hidden).\n * Use this for rendering that needs to match the grid template.\n */\n protected get visibleColumns(): ColumnConfig[] {\n return this.grid?._visibleColumns ?? [];\n }\n\n /**\n * Get the grid as an HTMLElement for direct DOM operations.\n * Use sparingly - prefer the typed GridElementRef API when possible.\n *\n * @example\n * ```ts\n * const width = this.gridElement.clientWidth;\n * this.gridElement.classList.add('my-plugin-active');\n * ```\n */\n protected get gridElement(): HTMLElement {\n return this.grid?._hostElement;\n }\n\n /**\n * Get the disconnect signal for event listener cleanup.\n * This signal is aborted when the grid disconnects from the DOM.\n * Use this when adding event listeners that should be cleaned up automatically.\n *\n * Best for:\n * - Document/window-level listeners added in attach()\n * - Listeners on the grid element itself\n * - Any listener that should persist across renders\n *\n * Not needed for:\n * - Listeners on elements created in afterRender() (removed with element)\n *\n * @example\n * element.addEventListener('click', handler, { signal: this.disconnectSignal });\n * document.addEventListener('keydown', handler, { signal: this.disconnectSignal });\n */\n protected get disconnectSignal(): AbortSignal {\n // Return the plugin's own abort signal for proper cleanup on detach/re-attach\n // Falls back to grid's signal if plugin's controller not yet created\n return this.#abortController?.signal ?? this.grid?.disconnectSignal;\n }\n\n /**\n * Get the grid-level icons configuration.\n * Returns merged icons (user config + defaults).\n */\n protected get gridIcons(): Required<GridIcons> {\n const userIcons = this.grid?.gridConfig?.icons ?? {};\n return { ...DEFAULT_GRID_ICONS, ...userIcons };\n }\n\n /**\n * Resolve a user-visible string from {@link GridConfig.locale}, falling back to\n * the English default supplied at the call site.\n *\n * The fallback is passed inline rather than read from a shipped default map so\n * that a plugin's strings live in the plugin's own chunk.\n *\n * @param key - Namespaced message id, e.g. `'filter.apply'`.\n * @param fallback - English text used when the key is not overridden.\n * @since 3.5.0\n *\n * @example\n * ```ts\n * applyBtn.textContent = this.t('filter.apply', 'Apply');\n * ```\n */\n protected t(key: string, fallback: string): string {\n return this.grid?.effectiveConfig?.locale?.[key] ?? fallback;\n }\n\n /**\n * A bound `t()` suitable for handing to standalone renderer\n * helpers and public renderer callbacks.\n * @since 3.5.0\n */\n protected get translate(): Translate {\n return (key, fallback) => this.t(key, fallback);\n }\n\n // #region Animation Helpers\n\n /**\n * Check if animations are enabled at the grid level.\n * Respects gridConfig.animation.mode and the CSS variable set by the grid.\n *\n * Plugins should use this to skip animations when:\n * - Animation mode is 'off' or `false`\n * - User prefers reduced motion and mode is 'reduced-motion' (default)\n *\n * @example\n * ```ts\n * private get animationStyle(): 'slide' | 'fade' | false {\n * if (!this.isAnimationEnabled) return false;\n * return this.config.animation ?? 'slide';\n * }\n * ```\n */\n protected get isAnimationEnabled(): boolean {\n const mode = this.grid?.effectiveConfig?.animation?.mode ?? 'reduced-motion';\n\n // Explicit off = disabled\n if (mode === false || mode === 'off') return false;\n\n // Explicit on = always enabled\n if (mode === true || mode === 'on') return true;\n\n // reduced-motion: check CSS variable (set by grid based on media query)\n const host = this.gridElement;\n if (host) {\n const enabled = getComputedStyle(host).getPropertyValue('--tbw-animation-enabled').trim();\n return enabled !== '0';\n }\n\n return true; // Default to enabled\n }\n\n /**\n * Get the animation duration in milliseconds from CSS variable.\n * Falls back to 200ms if not set.\n *\n * Plugins can use this for their animation timing to stay consistent\n * with the grid-level animation.duration setting.\n *\n * @example\n * ```ts\n * element.animate(keyframes, { duration: this.animationDuration });\n * ```\n */\n protected get animationDuration(): number {\n const host = this.gridElement;\n if (host) {\n const durationStr = getComputedStyle(host).getPropertyValue('--tbw-animation-duration').trim();\n const parsed = parseInt(durationStr, 10);\n if (!isNaN(parsed)) return parsed;\n }\n return 200; // Default\n }\n\n // #endregion\n\n /**\n * Set an icon on an element using the CSS-first hybrid approach.\n *\n * Sets `data-icon` for CSS pseudo-element rendering and `data-expanded` for\n * expand/collapse toggle elements. Only injects DOM content when a JS override\n * is present (via `gridConfig.icons` or `pluginOverride`), which naturally\n * suppresses the CSS `::before` via the `:empty` selector.\n *\n * @param element - The element to set the icon on\n * @param iconKey - The icon key in GridIcons (e.g., 'expand', 'collapse')\n * @param pluginOverride - Optional plugin-level override (string or HTMLElement)\n */\n protected setIcon(element: HTMLElement, iconKey: keyof GridIcons, pluginOverride?: IconValue): void {\n // Set data-icon attribute for CSS targeting (always)\n element.dataset.icon = toIconAttr(iconKey);\n\n // Set data-expanded for toggle elements (tree, group, master-detail)\n if (iconKey === 'collapse') {\n element.dataset.expanded = '';\n } else if (iconKey === 'expand') {\n delete element.dataset.expanded;\n }\n\n // Resolve JS-only icon (returns undefined when CSS default should be used)\n const jsIcon = this.#resolveJsIcon(iconKey, pluginOverride);\n\n if (jsIcon !== undefined) {\n // JS override: inject content (suppresses CSS ::before via :empty)\n if (typeof jsIcon === 'string') {\n setSanitizedHTML(element, jsIcon);\n } else if (jsIcon instanceof HTMLElement) {\n element.replaceChildren(jsIcon.cloneNode(true));\n }\n } else {\n // CSS path: ensure element is empty so ::before renders\n element.innerHTML = '';\n }\n }\n\n /**\n * Resolve JS-only icon override. Returns undefined if CSS default should render.\n * Only returns a value when the user explicitly set gridConfig.icons[key] or\n * the plugin passed an override.\n */\n #resolveJsIcon(iconKey: keyof GridIcons, pluginOverride?: IconValue): IconValue | undefined {\n if (pluginOverride !== undefined) return pluginOverride;\n return this.grid?.gridConfig?.icons?.[iconKey];\n }\n\n /**\n * Create or replace a sort indicator on a header cell.\n *\n * Handles the full lifecycle: removes any existing indicator, creates a new\n * `<span part=\"sort-indicator\" class=\"sort-indicator\">` with the appropriate\n * icon, sets `aria-sort` / `data-sort` attributes, and inserts it before the\n * filter button or resize handle.\n *\n * Plugins decide **which** cells and **when** — this method handles **how**.\n *\n * @param cell - The header cell element\n * @param direction - `'asc'` | `'desc'` for sorted, `null` for unsorted idle state\n * @returns The created indicator element (useful for appending badges, etc.)\n */\n protected updateSortIndicator(cell: Element, direction: 'asc' | 'desc' | null): HTMLElement {\n // Remove any existing indicator (core uses part, plugins use class)\n cell.querySelector('[part~=\"sort-indicator\"], .sort-indicator')?.remove();\n\n const indicator = document.createElement('span');\n indicator.setAttribute('part', 'sort-indicator');\n indicator.className = 'sort-indicator';\n\n if (direction) {\n cell.setAttribute('aria-sort', direction === 'asc' ? 'ascending' : 'descending');\n cell.setAttribute('data-sort', direction);\n this.setIcon(indicator, direction === 'asc' ? 'sortAsc' : 'sortDesc');\n } else {\n cell.setAttribute('aria-sort', 'none');\n cell.removeAttribute('data-sort');\n this.setIcon(indicator, 'sortNone');\n }\n\n // Insert before filter button or resize handle to maintain DOM order\n const insertBefore = cell.querySelector('.tbw-filter-btn') ?? cell.querySelector('.resize-handle');\n if (insertBefore) {\n cell.insertBefore(indicator, insertBefore);\n } else {\n cell.appendChild(indicator);\n }\n\n return indicator;\n }\n\n /**\n * Log a warning with an optional diagnostic code.\n *\n * When a diagnostic code is provided, the message is formatted with the code\n * and a link to the troubleshooting docs.\n *\n * @example\n * ```ts\n * this.warn('Something went wrong'); // plain\n * this.warn(MISSING_BREAKPOINT, 'Set a breakpoint'); // with code + docs link\n * ```\n */\n protected warn(message: string): void;\n protected warn(code: DiagnosticCode, message: string): void;\n protected warn(codeOrMessage: DiagnosticCode | string, message?: string): void {\n if (message !== undefined) {\n // Called with (code, message)\n console.warn(formatDiagnostic(codeOrMessage as DiagnosticCode, message, this.gridElement.id, this.name));\n } else {\n // Called with (message) — plain warning, no diagnostic code\n console.warn(`${gridPrefix(this.gridElement.id, this.name)} ${codeOrMessage}`);\n }\n }\n\n /**\n * Throw an error with a diagnostic code and docs link.\n * Use for configuration errors and API misuse that should halt execution.\n */\n protected throwDiagnostic(code: DiagnosticCode, message: string): never {\n throw new Error(formatDiagnostic(code, message, this.gridElement.id, this.name));\n }\n\n // #region Lifecycle Hooks\n\n /**\n * Transform rows before rendering.\n * Called during each render cycle before rows are rendered to the DOM.\n * Use this to filter, sort, or add computed properties to rows.\n *\n * @param rows - The current rows array (readonly to encourage returning a new array)\n * @returns The modified rows array to render\n *\n * @example\n * ```ts\n * processRows(rows: readonly any[]): any[] {\n * // Filter out hidden rows\n * return rows.filter(row => !row._hidden);\n * }\n * ```\n *\n * @example\n * ```ts\n * processRows(rows: readonly any[]): any[] {\n * // Add computed properties\n * return rows.map(row => ({\n * ...row,\n * _fullName: `${row.firstName} ${row.lastName}`\n * }));\n * }\n * ```\n */\n processRows?(rows: readonly any[]): any[];\n\n /**\n * Contribute to the grid's effective configuration during each config merge.\n * Called by {@link ConfigManager.merge} after the base config is assembled,\n * before it becomes `effectiveConfig`. Mutate `config` in place to inject\n * plugin-derived settings (e.g. the shell plugin folds its light-DOM /\n * API-registered state into `config.shell`).\n *\n * This is the config-pipeline counterpart to {@link processColumns} /\n * {@link processRows}: it keeps the core config merge free of any plugin\n * knowledge — each plugin owns the shape it contributes.\n *\n * @param config - The mutable base config being assembled into effectiveConfig.\n *\n * @example\n * ```ts\n * processConfig(config: GridConfig): void {\n * config.shell = { ...config.shell, header: { title: this.#title } };\n * }\n * ```\n */\n processConfig?(config: GridConfig): void;\n\n /**\n * Transform columns before rendering.\n * Called during each render cycle before column headers and cells are rendered.\n * Use this to add, remove, or modify column definitions.\n *\n * @param columns - The current columns array (readonly to encourage returning a new array)\n * @returns The modified columns array to render\n *\n * @example\n * ```ts\n * processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n * // Add a selection checkbox column\n * return [\n * { field: '_select', header: '', width: 40 },\n * ...columns\n * ];\n * }\n * ```\n */\n processColumns?(columns: readonly ColumnConfig[]): ColumnConfig[];\n\n /**\n * Called before each render cycle begins.\n * Use this to prepare state or cache values needed during rendering.\n *\n * **Note:** This hook is currently a placeholder for future implementation.\n * It is defined in the interface but not yet invoked by the grid's render pipeline.\n * If you need this functionality, please open an issue or contribute an implementation.\n *\n * @example\n * ```ts\n * beforeRender(): void {\n * this.visibleRowCount = this.calculateVisibleRows();\n * }\n * ```\n */\n beforeRender?(): void;\n\n /**\n * Called after each render cycle completes.\n * Use this for DOM manipulation, adding event listeners to rendered elements,\n * or applying visual effects like selection highlights.\n *\n * @example\n * ```ts\n * afterRender(): void {\n * // Apply selection styling to rendered rows\n * const rows = this.gridElement?.querySelectorAll('.data-grid-row');\n * rows?.forEach((row, i) => {\n * row.classList.toggle('selected', this.selectedRows.has(i));\n * });\n * }\n * ```\n */\n afterRender?(): void;\n\n /**\n * Called synchronously immediately after the grid (re)builds its root DOM\n * structure, before the browser has a chance to paint.\n *\n * Unlike {@link afterRender} (which runs in the scheduler's STYLE phase and\n * may be deferred), this hook fires inside the same task as the structural\n * DOM build. It is the correct place for plugins that need to wrap, relocate,\n * or augment the freshly built grid DOM without a flash of unstyled/unwrapped\n * content — e.g. a shell that moves the grid content into a chrome wrapper.\n *\n * The grid emits this hook every time it performs a full structural rebuild\n * (initial connect and structural changes), but NOT on the scroll/data hot\n * path. Implementations MUST be idempotent: a full rebuild discards any DOM a\n * previous invocation produced, so re-create it, and no-op when the desired\n * structure is already present.\n *\n * @example\n * ```ts\n * afterStructuralRender(): void {\n * const root = this.grid?._renderRoot;\n * if (!root || root.querySelector('.my-wrapper > .tbw-grid-content')) return;\n * // build wrapper, move .tbw-grid-content inside it\n * }\n * ```\n */\n afterStructuralRender?(): void;\n\n /**\n * Called synchronously by the grid immediately before it tears down and\n * rebuilds its root DOM structure (a structural re-render). Plugins that\n * relocated existing light-DOM nodes into their own chrome (e.g. a shell that\n * moves toolbar buttons into the header bar) use this to move those nodes back\n * to their original container so they survive the rebuild. Generic\n * counterpart to {@link afterStructuralRender}. MUST be idempotent.\n */\n beforeStructuralRender?(): void;\n\n /**\n * Called by the grid after a config merge to ask whether the change requires a\n * full structural re-render (rather than a cheaper in-place update). A plugin\n * returns `true` when its rendered DOM signature no longer matches the new\n * effective config — e.g. a shell header appearing/disappearing or a tool\n * panel's count/position/mode changing. The grid performs a structural\n * re-render if ANY plugin returns `true`. MUST be side-effect free.\n */\n needsStructuralRerender?(): boolean;\n\n /**\n * Called by the grid to let a plugin (re-)parse its own light-DOM\n * contributions into plugin state ahead of a config merge. Generic seam that\n * keeps core free of plugin-specific light-DOM tag knowledge (the plugin reads\n * `this.grid._hostElement`). MUST be idempotent.\n */\n parseLightDom?(): void;\n\n /**\n * Called by the grid (from `refreshColumns` and the light-DOM observer) to\n * let a plugin re-parse its light-DOM contributions AND refresh any\n * already-rendered chrome in place when something changed — e.g. a shell\n * title or tool buttons that a framework projected asynchronously after the\n * initial render. Distinct from {@link parseLightDom}, which only updates\n * plugin state. Generic seam — core holds no plugin-specific knowledge. MUST\n * be idempotent and a no-op when the plugin's chrome is not yet rendered.\n */\n syncLightDom?(): void;\n\n /**\n * Called after each cell is rendered.\n * This hook is more efficient than `afterRender()` for cell-level modifications\n * because you receive the cell context directly - no DOM queries needed.\n *\n * Use cases:\n * - Adding selection/highlight classes to specific cells\n * - Injecting badges or decorations\n * - Applying conditional styling based on cell value\n *\n * Performance note: Called for every visible cell during render. Keep implementation fast.\n * This hook is also called during scroll when cells are recycled.\n *\n * @param context - The cell render context with row, column, value, and elements\n *\n * @example\n * ```ts\n * afterCellRender(context: AfterCellRenderContext): void {\n * // Add selection class without DOM queries\n * if (this.isSelected(context.rowIndex, context.colIndex)) {\n * context.cellElement.classList.add('selected');\n * }\n *\n * // Add validation error styling\n * if (this.hasError(context.row, context.column.field)) {\n * context.cellElement.classList.add('has-error');\n * }\n * }\n * ```\n */\n afterCellRender?(context: AfterCellRenderContext): void;\n\n /**\n * Called after a row is fully rendered (all cells complete).\n * Use this for row-level decorations, styling, or ARIA attributes.\n *\n * Common use cases:\n * - Adding selection classes to entire rows (row-focus, selected)\n * - Setting row-level ARIA attributes\n * - Applying row validation highlighting\n * - Tree indentation styling\n *\n * Performance note: Called for every visible row during render. Keep implementation fast.\n * This hook is also called during scroll when rows are recycled.\n *\n * @param context - The row render context with row data and element\n *\n * @example\n * ```ts\n * afterRowRender(context: AfterRowRenderContext): void {\n * // Add row selection class without DOM queries\n * if (this.isRowSelected(context.rowIndex)) {\n * context.rowElement.classList.add('selected', 'row-focus');\n * }\n *\n * // Add validation error styling\n * if (this.rowHasErrors(context.row)) {\n * context.rowElement.classList.add('has-errors');\n * }\n * }\n * ```\n */\n afterRowRender?(context: AfterRowRenderContext): void;\n\n /**\n * Called after scroll-triggered row rendering completes.\n * This is a lightweight hook for applying visual state to recycled DOM elements.\n * Use this instead of afterRender when you need to reapply styling during scroll.\n *\n * Performance note: This is called frequently during scroll. Keep implementation fast.\n *\n * @example\n * ```ts\n * onScrollRender(): void {\n * // Reapply selection state to visible cells\n * this.applySelectionToVisibleCells();\n * }\n * ```\n */\n onScrollRender?(): void;\n\n /**\n * Get the height of a specific row.\n * Used for synthetic rows (group headers, detail panels, etc.) that have fixed heights.\n * Return undefined if this plugin does not manage the height for this row.\n *\n * This hook is called during position cache rebuilds for variable row height virtualization.\n * Plugins that create synthetic rows should implement this to provide accurate heights.\n *\n * @param row - The row data\n * @param index - The row index in the processed rows array\n * @returns The row height in pixels, or undefined if not managed by this plugin\n */\n getRowHeight?(row: unknown, index: number): number | undefined;\n\n /**\n * Adjust the virtualization start index to render additional rows before the visible range.\n * Use this when expanded content (like detail rows) needs its parent row to remain rendered\n * even when the parent row itself has scrolled above the viewport.\n *\n * @param start - The calculated start row index\n * @param scrollTop - The current scroll position\n * @param rowHeight - The height of a single row\n * @returns The adjusted start index (lower than or equal to original start)\n *\n * @example\n * ```ts\n * adjustVirtualStart(start: number, scrollTop: number, rowHeight: number): number {\n * // If row 5 is expanded and scrolled partially, keep it rendered\n * for (const expandedRowIndex of this.expandedRowIndices) {\n * const expandedRowTop = expandedRowIndex * rowHeight;\n * const expandedRowBottom = expandedRowTop + rowHeight + this.detailHeight;\n * if (expandedRowBottom > scrollTop && expandedRowIndex < start) {\n * return expandedRowIndex;\n * }\n * }\n * return start;\n * }\n * ```\n */\n adjustVirtualStart?(start: number, scrollTop: number, rowHeight: number): number;\n\n /**\n * Render a custom row, bypassing the default row rendering.\n * Use this for special row types like group headers, detail rows, or footers.\n *\n * @param row - The row data object\n * @param rowEl - The row DOM element to render into\n * @param rowIndex - The index of the row in the data array\n * @returns `true` if the plugin handled rendering (prevents default), `false`/`void` for default rendering\n *\n * @example\n * ```ts\n * renderRow(row: any, rowEl: HTMLElement, rowIndex: number): boolean | void {\n * if (row._isGroupHeader) {\n * rowEl.innerHTML = `<div class=\"group-header\">${row._groupLabel}</div>`;\n * return true; // Handled - skip default rendering\n * }\n * // Return void to let default rendering proceed\n * }\n * ```\n */\n renderRow?(row: any, rowEl: HTMLElement, rowIndex: number): boolean | void;\n\n // #endregion\n\n // #region Inter-Plugin Communication\n\n /**\n * Handle queries from other plugins or the grid.\n *\n * Queries are declared in `manifest.queries` and dispatched via `grid.query()`.\n * This enables type-safe, discoverable inter-plugin communication.\n *\n * @category Plugin Development\n * @param query - The query object with type and context\n * @returns Query-specific response, or undefined if not handling this query\n *\n * @example\n * ```ts\n * // In manifest\n * static override readonly manifest: PluginManifest = {\n * queries: [\n * { type: 'canMoveColumn', description: 'Check if a column can be moved' },\n * ],\n * };\n *\n * // In plugin class\n * handleQuery(query: PluginQuery): unknown {\n * if (query.type === 'canMoveColumn') {\n * const column = query.context as ColumnConfig;\n * return !column.sticky; // Can't move sticky columns\n * }\n * }\n * ```\n */\n handleQuery?(query: PluginQuery): unknown;\n\n // #endregion\n\n // #region Interaction Hooks\n\n /**\n * Handle keyboard events on the grid.\n * Called when a key is pressed while the grid or a cell has focus.\n *\n * @param event - The native KeyboardEvent\n * @returns `true` to prevent default behavior and stop propagation, `false`/`void` to allow default\n *\n * @example\n * ```ts\n * onKeyDown(event: KeyboardEvent): boolean | void {\n * // Handle Ctrl+A for select all\n * if (event.ctrlKey && event.key === 'a') {\n * this.selectAllRows();\n * return true; // Prevent default browser select-all\n * }\n * }\n * ```\n */\n onKeyDown?(event: KeyboardEvent): boolean | void;\n\n /**\n * Handle cell click events.\n * Called when a data cell is clicked (not headers).\n *\n * @param event - Cell click event with row/column context\n * @returns `true` to prevent default behavior and stop propagation, `false`/`void` to allow default\n *\n * @example\n * ```ts\n * onCellClick(event: CellClickEvent): boolean | void {\n * if (event.field === '_select') {\n * this.toggleRowSelection(event.rowIndex);\n * return true; // Handled\n * }\n * }\n * ```\n */\n onCellClick?(event: CellClickEvent): boolean | void;\n\n /**\n * Handle row click events.\n * Called when any part of a data row is clicked.\n * Note: This is called in addition to onCellClick, not instead of.\n *\n * @param event - Row click event with row context\n * @returns `true` to prevent default behavior and stop propagation, `false`/`void` to allow default\n *\n * @example\n * ```ts\n * onRowClick(event: RowClickEvent): boolean | void {\n * if (this.config.mode === 'row') {\n * this.selectRow(event.rowIndex, event.originalEvent);\n * return true;\n * }\n * }\n * ```\n */\n onRowClick?(event: RowClickEvent): boolean | void;\n\n /**\n * Handle header click events.\n * Called when a column header is clicked. Commonly used for sorting.\n *\n * @param event - Header click event with column context\n * @returns `true` to prevent default behavior and stop propagation, `false`/`void` to allow default\n *\n * @example\n * ```ts\n * onHeaderClick(event: HeaderClickEvent): boolean | void {\n * if (event.column.sortable !== false) {\n * this.toggleSort(event.field);\n * return true;\n * }\n * }\n * ```\n */\n onHeaderClick?(event: HeaderClickEvent): boolean | void;\n\n /**\n * Handle scroll events on the grid viewport.\n * Called during scrolling. Note: This may be called frequently; debounce if needed.\n *\n * @param event - Scroll event with scroll position and viewport dimensions\n *\n * @example\n * ```ts\n * onScroll(event: ScrollEvent): void {\n * // Update sticky column positions\n * this.updateStickyPositions(event.scrollLeft);\n * }\n * ```\n */\n onScroll?(event: ScrollEvent): void;\n\n /**\n * Handle cell mousedown events.\n * Used for initiating drag operations like range selection or column resize.\n *\n * @param event - Mouse event with cell context\n * @returns `true` to indicate drag started (prevents text selection), `false`/`void` otherwise\n *\n * @example\n * ```ts\n * onCellMouseDown(event: CellMouseEvent): boolean | void {\n * if (event.rowIndex !== undefined && this.config.mode === 'range') {\n * this.startDragSelection(event.rowIndex, event.colIndex);\n * return true; // Prevent text selection\n * }\n * }\n * ```\n */\n onCellMouseDown?(event: CellMouseEvent): boolean | void;\n\n /**\n * Handle cell mousemove events during drag operations.\n * Only called when a drag is in progress (after mousedown returned true).\n *\n * @param event - Mouse event with current cell context\n * @returns `true` to continue handling the drag, `false`/`void` otherwise\n *\n * @example\n * ```ts\n * onCellMouseMove(event: CellMouseEvent): boolean | void {\n * if (this.isDragging && event.rowIndex !== undefined) {\n * this.extendSelection(event.rowIndex, event.colIndex);\n * return true;\n * }\n * }\n * ```\n */\n onCellMouseMove?(event: CellMouseEvent): boolean | void;\n\n /**\n * Handle cell mouseup events to end drag operations.\n *\n * @param event - Mouse event with final cell context\n * @returns `true` if drag was finalized, `false`/`void` otherwise\n *\n * @example\n * ```ts\n * onCellMouseUp(event: CellMouseEvent): boolean | void {\n * if (this.isDragging) {\n * this.finalizeDragSelection();\n * this.isDragging = false;\n * return true;\n * }\n * }\n * ```\n */\n onCellMouseUp?(event: CellMouseEvent): boolean | void;\n\n // Note: Context menu items are provided via handleQuery('getContextMenuItems').\n // This keeps the core decoupled from the context-menu plugin specifics.\n\n // #endregion\n\n // #region Column State Hooks\n\n /**\n * Contribute plugin-specific state for a column.\n * Called by the grid when collecting column state for serialization.\n * Plugins can add their own properties to the column state.\n *\n * @param field - The field name of the column\n * @returns Partial column state with plugin-specific properties, or undefined if no state to contribute\n *\n * @example\n * ```ts\n * getColumnState(field: string): Partial<ColumnState> | undefined {\n * const filterModel = this.filterModels.get(field);\n * if (filterModel) {\n * // Uses module augmentation to add filter property to ColumnState\n * return { filter: filterModel } as Partial<ColumnState>;\n * }\n * return undefined;\n * }\n * ```\n */\n getColumnState?(field: string): Partial<ColumnState> | undefined;\n\n /**\n * Apply plugin-specific state to a column.\n * Called by the grid when restoring column state from serialized data.\n * Plugins should restore their internal state based on the provided state.\n *\n * @param field - The field name of the column\n * @param state - The column state to apply (may contain plugin-specific properties)\n *\n * @example\n * ```ts\n * applyColumnState(field: string, state: ColumnState): void {\n * // Check for filter property added via module augmentation\n * const filter = (state as any).filter;\n * if (filter) {\n * this.filterModels.set(field, filter);\n * this.applyFilter();\n * }\n * }\n * ```\n */\n applyColumnState?(field: string, state: ColumnState): void;\n\n // #endregion\n\n // #region Scroll Boundary Hooks\n\n /**\n * Report horizontal scroll boundary offsets for this plugin.\n * Plugins that obscure part of the scroll area (e.g., pinned/sticky columns)\n * should return how much space they occupy on each side.\n * The keyboard navigation uses this to ensure focused cells are fully visible.\n *\n * @param rowEl - The row element (optional, for calculating widths from rendered cells)\n * @param focusedCell - The currently focused cell element (optional, to determine if scrolling should be skipped)\n * @returns Object with left/right pixel offsets and optional skipScroll flag, or undefined if plugin has no offsets\n *\n * @example\n * ```ts\n * getHorizontalScrollOffsets(rowEl?: HTMLElement, focusedCell?: HTMLElement): { left: number; right: number; skipScroll?: boolean } | undefined {\n * // Calculate total width of left-pinned columns\n * const leftCells = rowEl?.querySelectorAll('.sticky-left') ?? [];\n * let left = 0;\n * leftCells.forEach(el => { left += (el as HTMLElement).offsetWidth; });\n * // Skip scroll if focused cell is pinned (always visible)\n * const skipScroll = focusedCell?.classList.contains('sticky-left');\n * return { left, right: 0, skipScroll };\n * }\n * ```\n */\n getHorizontalScrollOffsets?(\n rowEl?: HTMLElement,\n focusedCell?: HTMLElement,\n ): { left: number; right: number; skipScroll?: boolean } | undefined;\n\n /**\n * Report vertical scroll boundary offsets for this plugin.\n * Plugins that overlay the top or bottom of the rows viewport (e.g. sticky\n * row clones) should return how much space they obscure on each edge, so\n * keyboard navigation can scroll a focused row clear of the overlay rather\n * than leaving it hidden underneath — WCAG 2.2 SC 2.4.11 Focus Not Obscured.\n *\n * Only report space that is painted *over* the scrollable rows. Content that\n * takes part in normal flow (pinned-row bars, the column header) already\n * shrinks the viewport and must NOT be reported here, or rows would scroll\n * twice as far as needed.\n *\n * @param focusedRowIndex - Index of the row being scrolled into view, so a plugin can report `skipScroll` when it already renders that row in a permanently visible overlay\n * @returns Object with top/bottom pixel offsets and optional skipScroll flag, or undefined if plugin obscures nothing\n *\n * @example\n * ```ts\n * getVerticalScrollOffsets(focusedRowIndex?: number): { top: number; bottom: number; skipScroll?: boolean } | undefined {\n * if (!this.overlayEl) return undefined;\n * // The row is already pinned in the overlay — it is visible where it is.\n * if (focusedRowIndex != null && this.stuckIndices.includes(focusedRowIndex)) {\n * return { top: 0, bottom: 0, skipScroll: true };\n * }\n * return { top: this.overlayEl.offsetHeight, bottom: 0 };\n * }\n * ```\n *\n * @since 3.6.0\n */\n getVerticalScrollOffsets?(\n focusedRowIndex?: number,\n ): { top: number; bottom: number; skipScroll?: boolean } | undefined;\n\n // #endregion\n\n // #region Shell Integration Hooks\n\n /**\n * Register a tool panel for this plugin.\n * Return undefined if plugin has no tool panel.\n * The shell will create a toolbar toggle button and render the panel content\n * when the user opens the panel.\n *\n * @returns Tool panel definition, or undefined if plugin has no panel\n *\n * @example\n * ```ts\n * getToolPanel(): ToolPanelDefinition | undefined {\n * return {\n * id: 'columns',\n * title: 'Columns',\n * icon: '☰',\n * tooltip: 'Show/hide columns',\n * order: 10,\n * render: (container) => {\n * this.renderColumnList(container);\n * return () => this.cleanup();\n * },\n * };\n * }\n * ```\n */\n getToolPanel?(): ToolPanelDefinition | undefined;\n\n /**\n * Register content for the shell header center section.\n * Return undefined if plugin has no header content.\n * Examples: search input, selection summary, status indicators.\n *\n * @returns Header content definition, or undefined if plugin has no header content\n *\n * @example\n * ```ts\n * getHeaderContent(): HeaderContentDefinition | undefined {\n * return {\n * id: 'quick-filter',\n * order: 10,\n * render: (container) => {\n * const input = document.createElement('input');\n * input.type = 'text';\n * input.placeholder = 'Search...';\n * input.addEventListener('input', this.handleInput);\n * container.appendChild(input);\n * return () => input.removeEventListener('input', this.handleInput);\n * },\n * };\n * }\n * ```\n */\n getHeaderContent?(): HeaderContentDefinition | undefined;\n\n // #endregion\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 * 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 if (!row) 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 { 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 /** Keys of nodes that are currently loading lazy children. */\n private loadingKeys = new Set<string>();\n /**\n * Keys 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 private loadedKeys = new Set<string>();\n /** In-flight local `loadChildren` requests, keyed by node key. */\n #childRequests = new Map<string, AbortController>();\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 /** 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.loadingKeys.clear();\n this.loadedKeys.clear();\n for (const controller of this.#childRequests.values()) controller.abort();\n this.#childRequests.clear();\n this.originalTreeColumnRenderer = undefined;\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 this.#mergeChildren(parentRow, (d.rows ?? []) as TreeRow[]);\n this.loadingKeys.delete(key);\n this.broadcast<TreeLoadEndDetail>('tree-load-end', {\n key,\n row: parentRow,\n 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 key\n // stays in `loadingKeys` 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 if (!this.loadingKeys.delete(key)) return;\n this.broadcast<TreeLoadErrorDetail>('tree-load-error', {\n key,\n row: parentRow,\n depth: this.rowKeyMap.get(key)?.depth ?? 0,\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.#syncTreeColumn();\n return false;\n }\n\n // When MultiSort is active, use its model instead of local sort state so\n // Tree and MultiSort don't fight over sort ownership.\n this.#levelSort = 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 const hasChildren =\n embeddedChildren ||\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 }\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.loadedKeys.add(this.#keyOf(row));\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 has already resolved.\n */\n #needsChildFetch(row: TreeRow, key: string): boolean {\n if (this.loadedKeys.has(key)) 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 * 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, the node is already loading, or\n * its children are already embedded.\n */\n private requestLazyChildren(flatRow: FlattenedTreeRow): void {\n const { key, depth, data: row } = flatRow;\n if (this.loadingKeys.has(key)) return;\n if (!this.#needsChildFetch(row, key)) return;\n\n const isServerSideActive = this.queryBoolean('datasource:is-active');\n const { loadChildren } = this.config;\n if (!isServerSideActive && !loadChildren) return;\n\n this.loadingKeys.add(key);\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 } satisfies FetchChildrenQuery);\n return;\n }\n\n this.#loadChildrenLocally(key, row, depth);\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): void {\n // A callback is guaranteed by the caller's guard.\n const loadChildren = this.config.loadChildren as NonNullable<TreeConfig['loadChildren']>;\n const controller = new AbortController();\n this.#childRequests.set(key, controller);\n\n const finish = (): boolean => {\n // Superseded or detached — drop the result silently.\n if (controller.signal.aborted) return false;\n this.#childRequests.delete(key);\n this.loadingKeys.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 controller that `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) cols[idx] = { ...cols[idx], viewRenderer: this.originalTreeColumnRenderer };\n }\n this.#treeColumnWrapped = false;\n this.originalTreeColumnRenderer = undefined;\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.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.loadingKeys.has(meta.key)) {\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, viewRenderer: 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\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`.\n if (this.loadingKeys.has(treeRow.key)) {\n rowEl.setAttribute('aria-busy', 'true');\n } else if (rowEl.hasAttribute('aria-busy')) {\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":"0FAoCA,IAAa,EAuBD,WAvBC,EAiDE,cCxET,EACJ,4SACG,MAAM,KACN,IAAK,GAAM,EAAE,MAAM,IAAI,UAAU,KAAK,KA2BrC,GA1BY,IAAI,OAAO,uCAAuC,EAAG,MAAM,GAAG,KAAK,gBA0B9D,IAAI,IACzB,2KAA2K,MACzK,OAOE,EAAyB,WAKzB,EAAY,IAAI,IAAI,kEAAkE,MAAM,MAK5F,EAAyB,wCAsC/B,SAAgB,EAAmB,GACjC,MAAM,EAAW,SAAS,cAAc,YAKxC,OAJI,GAAwB,iBAAT,IACjB,EAAS,UAAY,EAqCzB,SAAsB,GACpB,MAAM,EAAsB,GAGtB,EAAW,EAAK,iBAAiB,KAEvC,IAAK,MAAM,KAAM,EAAU,CACzB,MAAM,EAAU,EAAG,QAAQ,cAG3B,GAAI,EAAe,IAAI,GAAU,CAC/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