@toolbox-web/grid 3.8.3 → 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/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/features/registry.js +1 -1
- 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/selection/index.js +1 -1
- package/lib/plugins/selection/index.js.map +1 -1
- 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/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/selection.umd.js +1 -1
- package/umd/plugins/selection.umd.js.map +1 -1
- package/umd/plugins/tree.umd.js +1 -1
- package/umd/plugins/tree.umd.js.map +1 -1
package/umd/plugins/tree.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/constants"),require("../../core/internal/loading"),require("../../core/internal/sanitize"),require("../../core/internal/sorting"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/constants","../../core/internal/loading","../../core/internal/sanitize","../../core/internal/sorting","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_tree={},e.TbwGrid,e.TbwGrid,e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,r,i,n,s){function a(e,t,r){return void 0!==e.id?String(e.id):r?`${r}-${t}`:String(t)}function o(e,t){const r=new Set(e);return r.has(t)?r.delete(t):r.add(t),r}function d(e,t,r=null,i=0){const n=t.childrenField??"children",s=new Set;for(let o=0;o<e.length;o++){const l=e[o],h=a(l,o,r),c=l[n];if(Array.isArray(c)&&c.length>0){s.add(h);const e=d(c,t,h,i+1);for(const t of e)s.add(t)}}return s}function l(e,t,r,i=null,n=0){const s=r.childrenField??"children";for(let o=0;o<e.length;o++){const d=e[o],h=a(d,o,i);if(h===t)return[h];const c=d[s];if(Array.isArray(c)&&c.length>0){const e=l(c,t,r,h,n+1);if(e)return[h,...e]}}return null}function h(e,t,r,i){const n=l(e,t,r);if(!n)return i;const s=new Set(i);for(let a=0;a<n.length-1;a++)s.add(n[a]);return s}function c(e,t){const r=Math.min(t,e.length-1);if(r<0)return 0;let i=r;for(;i>0&&e[i].depth>0;)i--;let n=0;for(let s=0;s<=i;s++)0===e[s].depth&&n++;return n-1}function u(e){let t=0;for(const r of e)0===r.depth&&t++;return t}function p(e,t="children",r){if(!Array.isArray(e)||0===e.length)return!1;for(const i of e){if(!i)continue;const e=i[t];if(Array.isArray(e)&&e.length>0)return!0;if(null!=e&&!Array.isArray(e)&&e)return!0;if(r?.(i))return!0}return!1}Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function g(e,t,r){const i=String(r);e.getAttribute(t)!==i&&e.setAttribute(t,i)}var y=class extends s.BaseGridPlugin{static manifest={modifiesRowStructure:!0,hookPriority:{processRows:10},incompatibleWith:[{name:"groupingRows",reason:"Both plugins transform the entire row model. TreePlugin flattens nested hierarchies while GroupingRowsPlugin groups flat rows with synthetic headers. Use one approach per grid."},{name:"pivot",reason:"PivotPlugin replaces the entire row and column structure with aggregated pivot data. Tree hierarchy cannot coexist with pivot aggregation."}],events:[{type:"tree-expand",description:"Emitted when tree expansion state changes (toggle, expand all, collapse all). Broadcast to both DOM consumers and plugin bus."},{type:"tree-load-start",description:"Emitted when lazy child loading starts for a node whose children are not yet loaded."},{type:"tree-load-end",description:"Emitted when lazy child loading completes and children have been merged into the parent row."},{type:"tree-load-error",description:"Emitted when lazy child loading fails. The node leaves its loading state and can be retried."}],queries:[{type:"canMoveRow",description:"Returns false for rows with children (parent nodes cannot be reordered)"},{type:"datasource:viewport-mapping",description:"Translates flat viewport row indices to top-level node indices for ServerSide pagination."}]};static dependencies=[{name:"multiSort",required:!1,reason:"Queries sort model for coordinated tree sorting"},{name:"serverSide",required:!1,reason:"Consumes datasource events for lazy-loaded tree data"}];name="tree";styles='@layer tbw-plugins{tbw-grid .cell[data-field=__tbw_expander]{justify-content:flex-start;align-items:center;padding:0;display:flex;border-inline-end:none!important}tbw-grid .header-row .cell[data-field=__tbw_expander]{display:none}tbw-grid .header-row .cell[data-field=__tbw_expander]+.cell{grid-column:1/3}tbw-grid .tree-cell-wrapper{vertical-align:middle;align-items:center;padding-inline-start:calc(var(--tbw-tree-depth,0) * var(--tbw-tree-indent-width,var(--tbw-tree-toggle-size,1.25em)));display:inline-flex;overflow:visible}tbw-grid .tree-expander{box-sizing:border-box;justify-content:flex-start;align-items:center;width:100%;height:100%;display:flex}tbw-grid .tree-toggle{cursor:pointer;-webkit-user-select:none;user-select:none;width:var(--tbw-tree-toggle-size,1.25em);height:var(--tbw-tree-toggle-size,1.25em);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex}tbw-grid .tree-toggle:hover{color:var(--tbw-tree-accent,var(--tbw-color-accent))}tbw-grid .tree-toggle{position:relative}tbw-grid .tree-toggle:after{content:"";inline-size:var(--tbw-touch-target-min,24px);block-size:var(--tbw-touch-target-min,24px);position:absolute;inset-block-start:50%;inset-inline-start:50%;translate:-50% -50%}tbw-grid .tree-spacer{width:var(--tbw-tree-toggle-size,1.25em);height:var(--tbw-tree-toggle-size,1.25em);flex-shrink:0;display:inline-block}@media (pointer:coarse){tbw-grid .tree-toggle,tbw-grid .tree-spacer{min-width:var(--tbw-touch-target-min,24px);min-height:var(--tbw-touch-target-min,24px)}}tbw-grid .tree-loading{--tbw-spinner-size:var(--tbw-tree-toggle-size,1.25em);flex-shrink:0}tbw-grid .data-grid-row.tbw-tree-slide-in{animation:tbw-tree-slide-in var(--tbw-animation-duration,.2s) var(--tbw-animation-easing,ease-out) forwards}tbw-grid .data-grid-row.tbw-tree-fade-in{animation:tbw-tree-fade-in var(--tbw-animation-duration,.2s) var(--tbw-animation-easing,ease-out) forwards}@keyframes tbw-tree-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}@keyframes tbw-tree-fade-in{0%{opacity:0}to{opacity:1}}}';get defaultConfig(){return{childrenField:"children",autoDetect:!0,defaultExpanded:!1,indentWidth:20,showExpandIcons:!0,animation:"slide"}}expandedKeys=new Set;initialExpansionDone=!1;flattenedRows=[];rowKeyMap=new Map;previousVisibleKeys=new Set;keysToAnimate=new Set;sortState=null;loadingKeys=new Set;loadedKeys=new Set;#e=new Map;#t=new WeakMap;#r=new WeakMap;originalTreeColumnRenderer;wrappedTreeColumnField;#i=!1;#n=!1;detach(){(this.gridElement?.querySelector(".rows-body"))?.setAttribute("role","grid"),this.expandedKeys.clear(),this.initialExpansionDone=!1,this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.sortState=null,this.loadingKeys.clear(),this.loadedKeys.clear();for(const e of this.#e.values())e.abort();this.#e.clear(),this.originalTreeColumnRenderer=void 0,this.wrappedTreeColumnField=void 0,this.#i=!1}handleQuery(e){if("canMoveRow"===e.type){const t=e.context,r=this.config.childrenField??"children",i=t?.[r];if(Array.isArray(i)&&i.length>0)return!1}if("datasource:viewport-mapping"===e.type){const{viewportStart:t,viewportEnd:r}=e.context;if(0===this.flattenedRows.length)return;return{startNode:c(this.flattenedRows,t),endNode:c(this.flattenedRows,r)+1,totalLoadedNodes:u(this.flattenedRows)}}}attach(e){super.attach(e),this.on("datasource:data",e=>{const t=e;t.claimed||(t.claimed=!0)}),this.on("datasource:children",e=>{const t=e;if("tree"!==t.context?.source)return;t.claimed=!0;const r=t.context.parentNode;if(r){const e=this.#s(r);this.#a(r,t.rows??[]),this.loadingKeys.delete(e),this.broadcast("tree-load-end",{key:e,row:r,depth:this.rowKeyMap.get(e)?.depth??0,childCount:t.rows?.length??0}),this.requestRender()}}),this.on("datasource:error",e=>{const t=e;if("tree"!==t.context?.source)return;const r=t.context.parentNode;if(!r)return;const i=this.#s(r);this.loadingKeys.delete(i)&&(this.broadcast("tree-load-error",{key:i,row:r,depth:this.rowKeyMap.get(i)?.depth??0,error:t.error}),this.requestRender())})}get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}detect(e){if(!this.config.autoDetect)return!1;const t=e,r=this.config.childrenField??function(e){if(!Array.isArray(e)||0===e.length)return null;const t=["children","items","nodes","subRows","nested"];for(const r of e)if(r&&"object"==typeof r)for(const e of t){const t=r[e];if(Array.isArray(t)&&t.length>0)return e}return null}(t)??"children";return p(t,r)}processRows(e){const t=this.config.childrenField??"children",r=e;if(0===r.length||!p(r,t,this.config.hasChildren))return this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),this.#o(),[...e];const i=this.resolveEffectiveSortState();this.config.defaultExpanded&&!this.initialExpansionDone&&(this.expandedKeys=d(r,this.config),this.initialExpansionDone=!0),this.flattenedRows=this.#d(r,this.expandedKeys,i,null,0),this.#r=new WeakMap,this.rowKeyMap.clear(),this.keysToAnimate.clear();const n=new Set;for(const s of this.flattenedRows)this.rowKeyMap.set(s.key,s),this.#r.set(s.data,s),n.add(s.key),!this.previousVisibleKeys.has(s.key)&&s.depth>0&&this.keysToAnimate.add(s.key);return this.previousVisibleKeys=n,this.#o(),this.flattenedRows.map(e=>e.data)}#o(){this.#n||(this.#n=!0,queueMicrotask(()=>{this.#n=!1,this.grid&&this.#i!==this.flattenedRows.length>0&&this.requestColumnsRender()}))}#l(e,t,r){if(void 0!==e.id){const t=String(e.id);return this.#t.set(e,t),t}const i=this.#t.get(e);if(void 0!==i)return i;const n=r?`${r}-${t}`:String(t);return this.#t.set(e,n),n}#d(e,t,r,i,n){const s=this.config.childrenField??"children";for(let l=0;l<e.length;l++)this.#l(e[l],l,i);const a=r?this.#h(e,r.field,r.direction):e,o=[],d=this.config.hasChildren;for(let l=0;l<a.length;l++){const e=a[l],h=this.#l(e,l,i),c=e[s],u=Array.isArray(c)&&c.length>0,p=u||(d?d(e):null!=c&&!Array.isArray(c)&&!!c),g=t.has(h);o.push({key:h,data:e,depth:n,hasChildren:p,isExpanded:g,parentKey:i,posInSet:l+1,setSize:a.length}),u&&g&&o.push(...this.#d(c,t,r,h,n+1))}return o}#h(e,t,r){const i=this.grid,s=i?._columns??[],a={field:t,direction:r},o=[...e],d=(i?.effectiveConfig?.sortHandler??n.builtInSort)(o,a,s);return d&&"function"==typeof d.then?(d.catch(()=>{}),(0,n.builtInSort)(o,a,s)):d}#s(e){return this.#t.get(e)??String(e.id??"?")}#a(e,t){e[this.config.childrenField??"children"]=t,this.loadedKeys.add(this.#s(e))}#c(e,t){if(this.loadedKeys.has(t))return!1;const r=e[this.config.childrenField??"children"];if(Array.isArray(r)&&r.length>0)return!1;const i=this.config.hasChildren;return i?i(e):null!=r&&!Array.isArray(r)&&!!r}requestLazyChildren(e){const{key:t,depth:r,data:i}=e;if(this.loadingKeys.has(t))return;if(!this.#c(i,t))return;const n=this.queryBoolean("datasource:is-active"),{loadChildren:s}=this.config;(n||s)&&(this.loadingKeys.add(t),this.broadcast("tree-load-start",{key:t,row:i,depth:r}),n?this.grid.query("datasource:fetch-children",{context:{source:"tree",parentNode:i,nodePath:[t]}}):this.#u(t,i,r))}#u(e,t,r){const i=this.config.loadChildren,n=new AbortController;this.#e.set(e,n);const s=()=>!n.signal.aborted&&(this.#e.delete(e),this.loadingKeys.delete(e),!0),a=i=>{if(!s())return;const n=i??[];this.#a(t,n),this.broadcast("tree-load-end",{key:e,row:t,depth:r,childCount:n.length}),this.requestRender()},o=i=>{s()&&(this.broadcast("tree-load-error",{key:e,row:t,depth:r,error:i}),this.requestRender())};let d;try{d=i({row:t,key:e,depth:r,signal:n.signal})}catch(l){return void o(l)}if(d&&"function"==typeof d.subscribe){let e=!1,t=null;const r=()=>{e=!0,t?.unsubscribe(),t=null},i=d.subscribe({next:e=>{a(e),r()},error:e=>{o(e),r()}});return e?void i.unsubscribe():(t=i,void n.signal.addEventListener("abort",r,{once:!0}))}Promise.resolve(d).then(a,o)}resolveEffectiveSortState(){const e=this.grid?.query?.("sort:get-model",null);if(Array.isArray(e)&&e.length>0){const t=e[0];if(Array.isArray(t)&&t.length>0)return{field:t[0].field,direction:"desc"===t[0].direction?-1:1}}return this.sortState}processColumns(e){if(0===this.flattenedRows.length){const t=[...e];if(this.#i){const e=t.findIndex(e=>e.field===this.wrappedTreeColumnField);e>=0&&(t[e]={...t[e],viewRenderer:this.originalTreeColumnRenderer})}return this.#i=!1,this.originalTreeColumnRenderer=void 0,this.wrappedTreeColumnField=void 0,t}const n=[...e];if(0===n.length)return n;const{treeColumn:s}=this.config;let a=0;if(s){const e=n.findIndex(e=>e.field===s);e>=0&&(a=e)}const o=n[a],d=o.field;this.wrappedTreeColumnField!==d&&(this.originalTreeColumnRenderer=o.viewRenderer,this.wrappedTreeColumnField=d);const l=this.originalTreeColumnRenderer,h=()=>this.config,c=this.setIcon.bind(this);return n[a]={...o,viewRenderer:e=>{const{row:n,value:s}=e,{showExpandIcons:a=!0,indentWidth:o}=h(),d=this.#r.get(n),u=d?.depth??0,p=document.createElement("span");if(p.className="tree-cell-wrapper",p.style.setProperty("--tbw-tree-depth",String(u)),void 0!==o&&p.style.setProperty("--tbw-tree-indent-width",`${o}px`),a)if(d&&this.loadingKeys.has(d.key)){const e=(0,r.createDefaultSpinner)("small");e.classList.add("tree-loading"),p.appendChild(e)}else if(d&&d.hasChildren){const e=document.createElement("span");e.className=`${t.GridClasses.TREE_TOGGLE}${d.isExpanded?` ${t.GridClasses.EXPANDED}`:""}`,c(e,d.isExpanded?"collapse":"expand"),e.setAttribute("data-tree-key",d.key),p.appendChild(e)}else{const e=document.createElement("span");e.className="tree-spacer",p.appendChild(e)}const g=document.createElement("span");if(g.className="tree-content",l){const t=l(e);t instanceof Node?g.appendChild(t):"string"==typeof t&&(0,i.setSanitizedHTML)(g,t)}else g.textContent=null!=s?String(s):"";return p.appendChild(g),p}},this.#i=!0,n}onCellClick(e){const r=e.originalEvent?.target;if(!r?.classList.contains(t.GridClasses.TREE_TOGGLE))return!1;const i=r.getAttribute("data-tree-key");if(!i)return!1;const n=this.rowKeyMap.get(i);return!!n&&(this.expandedKeys=o(this.expandedKeys,i),this.expandedKeys.has(i)&&this.requestLazyChildren(n),this.broadcast("tree-expand",{key:i,row:n.data,expanded:this.expandedKeys.has(i),depth:n.depth,expandedKeys:[...this.expandedKeys]}),this.requestRender(),!0)}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusRow,r=this.flattenedRows[t];return r?.hasChildren?(e.preventDefault(),this.expandedKeys=o(this.expandedKeys,r.key),this.expandedKeys.has(r.key)&&this.requestLazyChildren(r),this.broadcast("tree-expand",{key:r.key,row:r.data,expanded:this.expandedKeys.has(r.key),depth:r.depth,expandedKeys:[...this.expandedKeys]}),this.requestRenderWithFocus(),!0):void 0}onHeaderClick(e){if(0===this.flattenedRows.length||!e.column.sortable)return!1;const t=this.grid?.query?.("sort:get-model",null);if(Array.isArray(t)&&t.length>0)return!1;const{field:r}=e.column;this.sortState&&this.sortState.field===r?1===this.sortState.direction?this.sortState={field:r,direction:-1}:this.sortState=null:this.sortState={field:r,direction:1};const i=this.grid;return void 0!==i._sortState&&(i._sortState=this.sortState?{...this.sortState}:null),this.broadcast("sort-change",{field:r,direction:this.sortState?.direction??0}),this.requestRender(),!0}afterRender(){const e=this.gridElement?.querySelector(".rows-body");e&&"treegrid"!==e.getAttribute("role")&&e.setAttribute("role","treegrid");const t=this.gridElement?.querySelector(".rows");if(!t)return;const r=this.animationStyle,i=!1!==r&&this.keysToAnimate.size>0,n="fade"===r?"tbw-tree-fade-in":"tbw-tree-slide-in";for(const s of t.querySelectorAll(".data-grid-row")){const e=s.querySelector(".cell[data-row]"),t=e?parseInt(e.getAttribute("data-row")??"-1",10):-1,r=this.flattenedRows[t];r&&(g(s,"aria-level",r.depth+1),g(s,"aria-setsize",r.setSize),g(s,"aria-posinset",r.posInSet),r.hasChildren?s.setAttribute("aria-expanded",String(r.isExpanded)):s.hasAttribute("aria-expanded")&&s.removeAttribute("aria-expanded"),s.classList.toggle("tbw-row-expanded",r.hasChildren&&r.isExpanded),this.loadingKeys.has(r.key)?s.setAttribute("aria-busy","true"):s.hasAttribute("aria-busy")&&s.removeAttribute("aria-busy"),i&&r.key&&this.keysToAnimate.has(r.key)&&(s.classList.add(n),s.addEventListener("animationend",()=>s.classList.remove(n),{once:!0})))}this.keysToAnimate.clear()}expand(e){this.expandedKeys.add(e);const t=this.rowKeyMap.get(e);t&&this.requestLazyChildren(t),this.requestRender()}collapse(e){this.expandedKeys.delete(e),this.requestRender()}toggle(e){this.expandedKeys=o(this.expandedKeys,e);const t=this.rowKeyMap.get(e);t?(this.expandedKeys.has(e)&&this.requestLazyChildren(t),this.broadcast("tree-expand",{key:e,row:t.data,expanded:this.expandedKeys.has(e),depth:t.depth,expandedKeys:[...this.expandedKeys]})):this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}expandAll(){this.expandedKeys=d(this.rows,this.config),this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=new Set,this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}getExpandedKeys(){return[...this.expandedKeys]}getFlattenedRows(){return[...this.flattenedRows]}getRowMeta(e){return this.#r.get(e)}getRowByKey(e){return this.rowKeyMap.get(e)?.data}expandToKey(e){this.expandedKeys=h(this.rows,e,this.config,this.expandedKeys),this.requestRender()}};e.TreePlugin=y});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/constants"),require("../../core/internal/loading"),require("../../core/internal/sanitize"),require("../../core/internal/sorting"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/constants","../../core/internal/loading","../../core/internal/sanitize","../../core/internal/sorting","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_tree={},e.TbwGrid,e.TbwGrid,e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,r,i,n,s){function o(e,t,r=new WeakMap){const i=[];for(const h of["structure","transform"])for(const r of t)r.hierarchyStage===h&&r.beginHierarchy(e)&&i.push(r);if(0===i.length)return[...e];const n=[],s=(e,t,r)=>{const n={parent:t?t.row:null,parentKey:t?.key??null,depth:r};for(const s of i)e=s.processSiblings(e,n);return e},o=(e,t)=>{const i=e.length;for(let a=0;a<i;a++){const d=e[a];n.push(d.row),"object"==typeof d.row&&null!==d.row&&r.set(d.row,{level:t+1,setSize:i,posInSet:a+1});const l=d.children;d.expanded&&l&&o(d.shaped?l:s(l,d,t+1),t+1)}},a=new Array(e.length);for(let h=0;h<e.length;h++)a[h]={row:e[h]};o(s(a,null,0),0);const d=e=>"object"==typeof e&&null!==e?r.get(e):void 0;let l=!1;for(const h of i)h.endHierarchy(n,d)&&(l=!0);if(!l)for(const h of n)"object"==typeof h&&null!==h&&r.delete(h);return n}function a(e,t,r){const i=String(r);e.getAttribute(t)!==i&&e.setAttribute(t,i)}function d(e){return"function"==typeof e.processSiblings}function l(e){return e.constructor.manifest?.hookPriority?.processRows??0}Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});var h=class extends s.BaseGridPlugin{static manifest={modifiesRowStructure:!0};name="hierarchy";#e=new WeakMap;detach(){this.gridElement?.querySelector(".rows-body")?.setAttribute("role","grid"),this.#e=new WeakMap}process(e,t){const r=this.#t();return r.includes(t)?r[r.length-1]!==t?e:(this.#e=new WeakMap,o(e,r,this.#e)):(this.#e=new WeakMap,o(e,[t],this.#e))}getRowMeta(e){return"object"==typeof e&&null!==e?this.#e.get(e):void 0}afterRender(){this.#r()}onScrollRender(){this.#r()}#t(){return(this.grid?._pluginManager?.getPlugins?.()??[]).filter(d).sort((e,t)=>l(e)-l(t))}#r(){if(0===this.#t().length)return;const e=this.gridElement?.querySelector(".rows");if(!e)return;let t=!1;for(const n of e.querySelectorAll(".data-grid-row")){const e=this.getRowMeta(n.__rowDataRef);e?(t=!0,a(n,"aria-level",e.level),a(n,"aria-setsize",e.setSize),a(n,"aria-posinset",e.posInSet)):(n.removeAttribute("aria-level"),n.removeAttribute("aria-setsize"),n.removeAttribute("aria-posinset"))}const r=t?"treegrid":"grid",i=this.gridElement?.querySelector(".rows-body");i&&i.getAttribute("role")!==r&&i.setAttribute("role",r)}};function c(e,t,r){return void 0!==e.id?String(e.id):r?`${r}-${t}`:String(t)}function u(e,t){const r=new Set(e);return r.has(t)?r.delete(t):r.add(t),r}function p(e,t,r=null,i=0){const n=t.childrenField??"children",s=new Set;for(let o=0;o<e.length;o++){const a=e[o],d=c(a,o,r),l=a[n];if(Array.isArray(l)&&l.length>0){s.add(d);const e=p(l,t,d,i+1);for(const t of e)s.add(t)}}return s}function g(e,t,r,i=null,n=0){const s=r.childrenField??"children";for(let o=0;o<e.length;o++){const a=e[o],d=c(a,o,i);if(d===t)return[d];const l=a[s];if(Array.isArray(l)&&l.length>0){const e=g(l,t,r,d,n+1);if(e)return[d,...e]}}return null}function y(e,t,r,i){const n=g(e,t,r);if(!n)return i;const s=new Set(i);for(let o=0;o<n.length-1;o++)s.add(n[o]);return s}function f(e,t="children",r){if(!Array.isArray(e)||0===e.length)return!1;for(const i of e){if(!i)continue;const e=i[t];if(Array.isArray(e)&&e.length>0)return!0;if(null!=e&&!Array.isArray(e)&&e)return!0;if(r?.(i))return!0}return!1}var w=class extends s.BaseGridPlugin{static manifest={modifiesRowStructure:!0,hookPriority:{processRows:10},incompatibleWith:[{name:"pivot",reason:"PivotPlugin replaces the entire row and column structure with aggregated pivot data. Tree hierarchy cannot coexist with pivot aggregation."}],events:[{type:"tree-expand",description:"Emitted when tree expansion state changes (toggle, expand all, collapse all). Broadcast to both DOM consumers and plugin bus."},{type:"tree-load-start",description:"Emitted when lazy child loading starts for a node whose children are not yet loaded."},{type:"tree-load-end",description:"Emitted when lazy child loading completes and children have been merged into the parent row."},{type:"tree-load-error",description:"Emitted when lazy child loading fails. The node leaves its loading state and can be retried."}],queries:[{type:"canMoveRow",description:"Returns false for rows with children (parent nodes cannot be reordered)"},{type:"datasource:viewport-mapping",description:"Translates flat viewport row indices to top-level node indices for ServerSide pagination."}]};static dependencies=[{name:"hierarchy",required:!0,reason:"Builds the hierarchical row model",provide:()=>new h},{name:"multiSort",required:!1,reason:"Queries sort model for coordinated tree sorting"},{name:"serverSide",required:!1,reason:"Consumes datasource events for lazy-loaded tree data"}];name="tree";hierarchyStage="structure";styles='@layer tbw-plugins{tbw-grid .cell[data-field=__tbw_expander]{justify-content:flex-start;align-items:center;padding:0;display:flex;border-inline-end:none!important}tbw-grid .header-row .cell[data-field=__tbw_expander]{display:none}tbw-grid .header-row .cell[data-field=__tbw_expander]+.cell{grid-column:1/3}tbw-grid .tree-cell-wrapper{vertical-align:middle;align-items:center;padding-inline-start:calc(var(--tbw-tree-depth,0) * var(--tbw-tree-indent-width,var(--tbw-tree-toggle-size,1.25em)));display:inline-flex;overflow:visible}tbw-grid .tree-expander{box-sizing:border-box;justify-content:flex-start;align-items:center;width:100%;height:100%;display:flex}tbw-grid .tree-toggle{cursor:pointer;-webkit-user-select:none;user-select:none;width:var(--tbw-tree-toggle-size,1.25em);height:var(--tbw-tree-toggle-size,1.25em);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex}tbw-grid .tree-toggle:hover{color:var(--tbw-tree-accent,var(--tbw-color-accent))}tbw-grid .tree-toggle{position:relative}tbw-grid .tree-toggle:after{content:"";inline-size:var(--tbw-touch-target-min,24px);block-size:var(--tbw-touch-target-min,24px);position:absolute;inset-block-start:50%;inset-inline-start:50%;translate:-50% -50%}tbw-grid .tree-spacer{width:var(--tbw-tree-toggle-size,1.25em);height:var(--tbw-tree-toggle-size,1.25em);flex-shrink:0;display:inline-block}@media (pointer:coarse){tbw-grid .tree-toggle,tbw-grid .tree-spacer{min-width:var(--tbw-touch-target-min,24px);min-height:var(--tbw-touch-target-min,24px)}}tbw-grid .tree-loading{--tbw-spinner-size:var(--tbw-tree-toggle-size,1.25em);flex-shrink:0}tbw-grid .data-grid-row.tbw-tree-slide-in{animation:tbw-tree-slide-in var(--tbw-animation-duration,.2s) var(--tbw-animation-easing,ease-out) forwards}tbw-grid .data-grid-row.tbw-tree-fade-in{animation:tbw-tree-fade-in var(--tbw-animation-duration,.2s) var(--tbw-animation-easing,ease-out) forwards}@keyframes tbw-tree-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}@keyframes tbw-tree-fade-in{0%{opacity:0}to{opacity:1}}}';get defaultConfig(){return{childrenField:"children",autoDetect:!0,defaultExpanded:!1,indentWidth:20,showExpandIcons:!0,animation:"slide"}}expandedKeys=new Set;initialExpansionDone=!1;flattenedRows=[];rowKeyMap=new Map;previousVisibleKeys=new Set;keysToAnimate=new Set;#i=[];#n=0;sortState=null;#s=null;loadingKeys=new Set;loadedKeys=new Set;#o=new Map;#a=new WeakMap;#d=new WeakMap;originalTreeColumnRenderer;wrappedTreeColumnField;#l=!1;#h=!1;detach(){this.expandedKeys.clear(),this.initialExpansionDone=!1,this.flattenedRows=[],this.#i=[],this.#n=0,this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.sortState=null,this.#s=null,this.loadingKeys.clear(),this.loadedKeys.clear();for(const e of this.#o.values())e.abort();this.#o.clear(),this.originalTreeColumnRenderer=void 0,this.wrappedTreeColumnField=void 0,this.#l=!1}handleQuery(e){if("canMoveRow"===e.type){const t=e.context,r=this.config.childrenField??"children",i=t?.[r];if(Array.isArray(i)&&i.length>0)return!1}if("datasource:viewport-mapping"===e.type){const{viewportStart:t,viewportEnd:r}=e.context;if(0===this.flattenedRows.length)return;return function(e,t,r,i){const n=e.length-1,s=t=>Math.max(0,e[Math.max(0,Math.min(t,n))]??0);return{startNode:s(r),endNode:s(i)+1,totalLoadedNodes:t}}(this.#i,this.#n,t,r)}}attach(e){super.attach(e),this.on("datasource:data",e=>{const t=e;t.claimed||(t.claimed=!0)}),this.on("datasource:children",e=>{const t=e;if("tree"!==t.context?.source)return;t.claimed=!0;const r=t.context.parentNode;if(r){const e=this.#c(r);this.#u(r,t.rows??[]),this.loadingKeys.delete(e),this.broadcast("tree-load-end",{key:e,row:r,depth:this.rowKeyMap.get(e)?.depth??0,childCount:t.rows?.length??0}),this.requestRender()}}),this.on("datasource:error",e=>{const t=e;if("tree"!==t.context?.source)return;const r=t.context.parentNode;if(!r)return;const i=this.#c(r);this.loadingKeys.delete(i)&&(this.broadcast("tree-load-error",{key:i,row:r,depth:this.rowKeyMap.get(i)?.depth??0,error:t.error}),this.requestRender())})}get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}detect(e){if(!this.config.autoDetect)return!1;const t=e,r=this.config.childrenField??function(e){if(!Array.isArray(e)||0===e.length)return null;const t=["children","items","nodes","subRows","nested"];for(const r of e)if(r&&"object"==typeof r)for(const e of t){const t=r[e];if(Array.isArray(t)&&t.length>0)return e}return null}(t)??"children";return f(t,r)}processRows(e){const t=this.grid?.getPluginByName?.("hierarchy");return t?t.process(e,this):o(e,[this])}beginHierarchy(e){const t=e;return 0!==t.length&&f(t,this.config.childrenField??"children",this.config.hasChildren)?(this.#s=this.resolveEffectiveSortState(),this.config.defaultExpanded&&!this.initialExpansionDone&&(this.expandedKeys=p(t,this.config),this.initialExpansionDone=!0),this.#d=new WeakMap,!0):(this.flattenedRows=[],this.#i=[],this.#n=0,this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),this.#p(),!1)}processSiblings(e,t){const{parentKey:r,depth:i}=t,n=this.config.childrenField??"children",s=this.config.hasChildren;for(let d=0;d<e.length;d++)this.#g(e[d].row,d,r);const o=this.#s,a=o?this.#y(e,o.field,o.direction):e;for(let d=0;d<a.length;d++){const e=a[d],t=e.row,o=this.#g(t,d,r),l=t[n],h=Array.isArray(l)&&l.length>0,c=h||(s?s(t):null!=l&&!Array.isArray(l)&&!!l),u=this.expandedKeys.has(o);this.#d.set(t,{key:o,data:t,depth:i,hasChildren:c,isExpanded:u,parentKey:r,posInSet:d+1,setSize:a.length}),e.key=o,h&&u&&(e.expanded=!0,e.children=l.map(e=>({row:e})))}return a}endHierarchy(e,t){const r=this.#d;this.#d=new WeakMap,this.flattenedRows=[],this.rowKeyMap.clear(),this.keysToAnimate.clear();const i=new Set,n=new Array(e.length);let s=-1;for(let o=0;o<e.length;o++){const a=e[o],d=r.get(a);if(null===d?.parentKey&&s++,n[o]=s,!d)continue;const l=t(a)?.level;void 0!==l&&(d.depth=l-1),this.flattenedRows.push(d),this.rowKeyMap.set(d.key,d),this.#d.set(a,d),i.add(d.key),!this.previousVisibleKeys.has(d.key)&&d.depth>0&&this.keysToAnimate.add(d.key)}return this.previousVisibleKeys=i,this.#i=n,this.#n=s+1,this.#p(),!0}#p(){this.#h||(this.#h=!0,queueMicrotask(()=>{this.#h=!1,this.grid&&this.#l!==this.flattenedRows.length>0&&this.requestColumnsRender()}))}#g(e,t,r){if(void 0!==e.id){const t=String(e.id);return this.#a.set(e,t),t}const i=this.#a.get(e);if(void 0!==i)return i;const n=r?`${r}-${t}`:String(t);return this.#a.set(e,n),n}#y(e,t,r){const i=new Map;for(const n of e)i.set(n.row,n);return this.#f(e.map(e=>e.row),t,r).map(e=>i.get(e)??{row:e})}#f(e,t,r){const i=this.grid,s=i?._columns??[],o={field:t,direction:r},a=[...e],d=(i?.effectiveConfig?.sortHandler??n.builtInSort)(a,o,s);return d&&"function"==typeof d.then?(d.catch(()=>{}),(0,n.builtInSort)(a,o,s)):d}#c(e){return this.#a.get(e)??String(e.id??"?")}#u(e,t){e[this.config.childrenField??"children"]=t,this.loadedKeys.add(this.#c(e))}#w(e,t){if(this.loadedKeys.has(t))return!1;const r=e[this.config.childrenField??"children"];if(Array.isArray(r)&&r.length>0)return!1;const i=this.config.hasChildren;return i?i(e):null!=r&&!Array.isArray(r)&&!!r}requestLazyChildren(e){const{key:t,depth:r,data:i}=e;if(this.loadingKeys.has(t))return;if(!this.#w(i,t))return;const n=this.queryBoolean("datasource:is-active"),{loadChildren:s}=this.config;(n||s)&&(this.loadingKeys.add(t),this.broadcast("tree-load-start",{key:t,row:i,depth:r}),n?this.grid.query("datasource:fetch-children",{context:{source:"tree",parentNode:i,nodePath:[t]}}):this.#m(t,i,r))}#m(e,t,r){const i=this.config.loadChildren,n=new AbortController;this.#o.set(e,n);const s=()=>!n.signal.aborted&&(this.#o.delete(e),this.loadingKeys.delete(e),!0),o=i=>{if(!s())return;const n=i??[];this.#u(t,n),this.broadcast("tree-load-end",{key:e,row:t,depth:r,childCount:n.length}),this.requestRender()},a=i=>{s()&&(this.broadcast("tree-load-error",{key:e,row:t,depth:r,error:i}),this.requestRender())};let d;try{d=i({row:t,key:e,depth:r,signal:n.signal})}catch(l){return void a(l)}if(d&&"function"==typeof d.subscribe){let e=!1,t=null;const r=()=>{e=!0,t?.unsubscribe(),t=null},i=d.subscribe({next:e=>{o(e),r()},error:e=>{a(e),r()}});return e?void i.unsubscribe():(t=i,void n.signal.addEventListener("abort",r,{once:!0}))}Promise.resolve(d).then(o,a)}resolveEffectiveSortState(){const e=this.grid?.query?.("sort:get-model",null);if(Array.isArray(e)&&e.length>0){const t=e[0];if(Array.isArray(t)&&t.length>0)return{field:t[0].field,direction:"desc"===t[0].direction?-1:1}}return this.sortState}processColumns(e){if(0===this.flattenedRows.length){const t=[...e];if(this.#l){const e=t.findIndex(e=>e.field===this.wrappedTreeColumnField);e>=0&&(t[e]={...t[e],viewRenderer:this.originalTreeColumnRenderer})}return this.#l=!1,this.originalTreeColumnRenderer=void 0,this.wrappedTreeColumnField=void 0,t}const n=[...e];if(0===n.length)return n;const{treeColumn:s}=this.config;let o=0;if(s){const e=n.findIndex(e=>e.field===s);e>=0&&(o=e)}const a=n[o],d=a.field;this.wrappedTreeColumnField!==d&&(this.originalTreeColumnRenderer=a.viewRenderer,this.wrappedTreeColumnField=d);const l=this.originalTreeColumnRenderer,h=()=>this.config,c=this.setIcon.bind(this);return n[o]={...a,viewRenderer:e=>{const{row:n,value:s}=e,{showExpandIcons:o=!0,indentWidth:a}=h(),d=this.#d.get(n),u=d?.depth??0,p=document.createElement("span");if(p.className="tree-cell-wrapper",p.style.setProperty("--tbw-tree-depth",String(u)),void 0!==a&&p.style.setProperty("--tbw-tree-indent-width",`${a}px`),o)if(d&&this.loadingKeys.has(d.key)){const e=(0,r.createDefaultSpinner)("small");e.classList.add("tree-loading"),p.appendChild(e)}else if(d&&d.hasChildren){const e=document.createElement("span");e.className=`${t.GridClasses.TREE_TOGGLE}${d.isExpanded?` ${t.GridClasses.EXPANDED}`:""}`,c(e,d.isExpanded?"collapse":"expand"),e.setAttribute("data-tree-key",d.key),p.appendChild(e)}else{const e=document.createElement("span");e.className="tree-spacer",p.appendChild(e)}const g=document.createElement("span");if(g.className="tree-content",l){const t=l(e);t instanceof Node?g.appendChild(t):"string"==typeof t&&(0,i.setSanitizedHTML)(g,t)}else g.textContent=null!=s?String(s):"";return p.appendChild(g),p}},this.#l=!0,n}onCellClick(e){const r=e.originalEvent?.target;if(!r?.classList.contains(t.GridClasses.TREE_TOGGLE))return!1;const i=r.getAttribute("data-tree-key");if(!i)return!1;const n=this.rowKeyMap.get(i);return!!n&&(this.expandedKeys=u(this.expandedKeys,i),this.expandedKeys.has(i)&&this.requestLazyChildren(n),this.broadcast("tree-expand",{key:i,row:n.data,expanded:this.expandedKeys.has(i),depth:n.depth,expandedKeys:[...this.expandedKeys]}),this.requestRender(),!0)}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusRow,r=this.#d.get(this.rows[t]);return r?.hasChildren?(e.preventDefault(),this.expandedKeys=u(this.expandedKeys,r.key),this.expandedKeys.has(r.key)&&this.requestLazyChildren(r),this.broadcast("tree-expand",{key:r.key,row:r.data,expanded:this.expandedKeys.has(r.key),depth:r.depth,expandedKeys:[...this.expandedKeys]}),this.requestRenderWithFocus(),!0):void 0}onHeaderClick(e){if(0===this.flattenedRows.length||!e.column.sortable)return!1;const t=this.grid?.query?.("sort:get-model",null);if(Array.isArray(t)&&t.length>0)return!1;const{field:r}=e.column;this.sortState&&this.sortState.field===r?1===this.sortState.direction?this.sortState={field:r,direction:-1}:this.sortState=null:this.sortState={field:r,direction:1};const i=this.grid;return void 0!==i._sortState&&(i._sortState=this.sortState?{...this.sortState}:null),this.broadcast("sort-change",{field:r,direction:this.sortState?.direction??0}),this.requestRender(),!0}afterRender(){const e=this.gridElement?.querySelector(".rows");if(!e)return;const t=this.animationStyle,r=!1!==t&&this.keysToAnimate.size>0,i="fade"===t?"tbw-tree-fade-in":"tbw-tree-slide-in";for(const n of e.querySelectorAll(".data-grid-row")){const e=this.#d.get(n.__rowDataRef);e&&(e.hasChildren?n.setAttribute("aria-expanded",String(e.isExpanded)):n.hasAttribute("aria-expanded")&&n.removeAttribute("aria-expanded"),n.classList.toggle("tbw-row-expanded",e.hasChildren&&e.isExpanded),this.loadingKeys.has(e.key)?n.setAttribute("aria-busy","true"):n.hasAttribute("aria-busy")&&n.removeAttribute("aria-busy"),r&&e.key&&this.keysToAnimate.has(e.key)&&(n.classList.add(i),n.addEventListener("animationend",()=>n.classList.remove(i),{once:!0})))}this.keysToAnimate.clear()}expand(e){this.expandedKeys.add(e);const t=this.rowKeyMap.get(e);t&&this.requestLazyChildren(t),this.requestRender()}collapse(e){this.expandedKeys.delete(e),this.requestRender()}toggle(e){this.expandedKeys=u(this.expandedKeys,e);const t=this.rowKeyMap.get(e);t?(this.expandedKeys.has(e)&&this.requestLazyChildren(t),this.broadcast("tree-expand",{key:e,row:t.data,expanded:this.expandedKeys.has(e),depth:t.depth,expandedKeys:[...this.expandedKeys]})):this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}expandAll(){this.expandedKeys=p(this.rows,this.config),this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=new Set,this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}getExpandedKeys(){return[...this.expandedKeys]}getFlattenedRows(){return[...this.flattenedRows]}getRowMeta(e){return this.#d.get(e)}getRowByKey(e){return this.rowKeyMap.get(e)?.data}expandToKey(e){this.expandedKeys=y(this.rows,e,this.config,this.expandedKeys),this.requestRender()}};e.TreePlugin=w});
|
|
2
2
|
//# sourceMappingURL=tree.umd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tree.umd.js","names":[],"sources":["../../../../../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 * 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/** Attribute write that skips the DOM mutation when the value is unchanged (per-frame hot path). */\nfunction setAttrIfChanged(el: Element, name: string, value: number): void {\n const next = String(value);\n if (el.getAttribute(name) !== next) el.setAttribute(name, next);\n}\n\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. Pooled\n // row elements keep their position across most frames — skip the\n // attribute mutation unless the value actually changed.\n setAttrIfChanged(rowEl, 'aria-level', treeRow.depth + 1);\n setAttrIfChanged(rowEl, 'aria-setsize', treeRow.setSize);\n setAttrIfChanged(rowEl, 'aria-posinset', 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":"ynBAYA,SAAgB,EAAe,EAAc,EAAe,GAC1D,YAAe,IAAX,EAAI,GAAyB,OAAO,EAAI,IACrC,EAAY,GAAG,KAAa,IAAU,OAAO,EACtD,CAwDA,SAAgB,EAAa,EAA2B,GACtD,MAAM,EAAc,IAAI,IAAI,GAM5B,OALI,EAAY,IAAI,GAClB,EAAY,OAAO,GAEnB,EAAY,IAAI,GAEX,CACT,CAMA,SAAgB,EACd,EACA,EACA,EAA2B,KAC3B,EAAQ,GAER,MAAM,EAAgB,EAAO,eAAiB,WACxC,EAAO,IAAI,IAEjB,IAAK,IAAI,EAAI,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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,aJl+BA,IAAI,IIm+BT,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":"tree.umd.js","names":[],"sources":["../../../../../libs/grid/src/lib/plugins/hierarchy/hierarchy.ts","../../../../../libs/grid/src/lib/plugins/hierarchy/hierarchy-plugin.ts","../../../../../libs/grid/src/lib/plugins/tree/tree-data.ts","../../../../../libs/grid/src/lib/plugins/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 * Hierarchy Engine\n *\n * Pure row-model builder shared by the HierarchyPlugin and its contributors.\n */\n\nimport type { HierarchyContributor, HierarchyNode, HierarchyRowMeta } from './types';\n\n/**\n * Build the flat row list for `rows` from every contributor's sibling-list\n * transforms, recording each emitted row's ARIA position in `meta`.\n *\n * Contributors whose `beginHierarchy` returns `false` sit out the rebuild.\n * With no active contributor the rows pass through unchanged. When every\n * active contributor's `endHierarchy` returns `false`, no position is kept in `meta`.\n *\n * This is what `HierarchyPlugin.process()` runs for all attached contributors.\n * Call it directly to run a contributor without a grid — e.g. as the\n * `processRows` fallback when no HierarchyPlugin is attached, or in unit tests.\n *\n * @example\n * ```ts\n * override processRows(rows: readonly unknown[]): unknown[] {\n * const hierarchy = this.grid?.getPluginByName('hierarchy');\n * return hierarchy ? hierarchy.process(rows, this) : buildHierarchy(rows, [this]);\n * }\n * ```\n *\n * @param rows - The root rows.\n * @param contributors - Contributors to run, in `processRows` hook order.\n * @param meta - Receives each emitted row's position. Pass a fresh map per rebuild.\n * @returns The flattened rows, in render order.\n * @since 3.9.0\n */\nexport function buildHierarchy(\n rows: readonly unknown[],\n contributors: readonly HierarchyContributor[],\n meta: WeakMap<object, HierarchyRowMeta> = new WeakMap(),\n): unknown[] {\n const active: HierarchyContributor[] = [];\n for (const stage of ['structure', 'transform'] as const) {\n for (const c of contributors) {\n if (c.hierarchyStage === stage && c.beginHierarchy(rows)) active.push(c);\n }\n }\n if (active.length === 0) return [...rows];\n\n const out: unknown[] = [];\n const process = (nodes: HierarchyNode[], parent: HierarchyNode | null, depth: number): HierarchyNode[] => {\n const context = { parent: parent ? parent.row : null, parentKey: parent?.key ?? null, depth };\n for (const c of active) nodes = c.processSiblings(nodes, context);\n return nodes;\n };\n const emit = (nodes: HierarchyNode[], depth: number): void => {\n const setSize = nodes.length;\n for (let i = 0; i < setSize; i++) {\n const node = nodes[i];\n out.push(node.row);\n if (typeof node.row === 'object' && node.row !== null) {\n meta.set(node.row, { level: depth + 1, setSize, posInSet: i + 1 });\n }\n const children = node.children;\n if (node.expanded && children) {\n emit(node.shaped ? children : process(children, node, depth + 1), depth + 1);\n }\n }\n };\n\n const roots: HierarchyNode[] = new Array(rows.length);\n for (let i = 0; i < rows.length; i++) roots[i] = { row: rows[i] };\n emit(process(roots, null, 0), 0);\n\n const positionOf = (row: unknown) => (typeof row === 'object' && row !== null ? meta.get(row) : undefined);\n let shaped = false;\n for (const c of active) if (c.endHierarchy(out, positionOf)) shaped = true;\n if (!shaped) {\n for (const row of out) if (typeof row === 'object' && row !== null) meta.delete(row);\n }\n return out;\n}\n","/**\n * Hierarchy Plugin\n *\n * Owns the hierarchical row model shared by structure-contributing plugins.\n */\n\nimport type { PluginManifest } from '../../core/plugin/base-plugin';\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { RowElementInternal } from '../../core/types';\nimport { buildHierarchy } from './hierarchy';\nimport type { HierarchyContributor, HierarchyRowMeta } from './types';\n\n/** Attribute write that skips the DOM mutation when the value is unchanged (per-frame hot path). */\nfunction setAttrIfChanged(el: Element, name: string, value: number): void {\n const next = String(value);\n if (el.getAttribute(name) !== next) el.setAttribute(name, next);\n}\n\nfunction isContributor(plugin: unknown): plugin is HierarchyContributor & BaseGridPlugin {\n return typeof (plugin as Partial<HierarchyContributor>).processSiblings === 'function';\n}\n\nfunction processRowsPriority(plugin: BaseGridPlugin): number {\n return (plugin.constructor as typeof BaseGridPlugin).manifest?.hookPriority?.processRows ?? 0;\n}\n\n/**\n * Hierarchy Plugin for tbw-grid\n *\n * Builds one hierarchical row model from every attached structure contributor\n * — {@link https://toolboxjs.com/grid/plugins/tree/ | TreePlugin} discovers\n * child rows, {@link https://toolboxjs.com/grid/plugins/grouping-rows/ | GroupingRowsPlugin}\n * groups sibling lists — and announces each row's position with the WAI-ARIA\n * treegrid pattern (`aria-level` / `aria-setsize` / `aria-posinset`).\n *\n * Contributors know nothing about each other, so they compose: a grid with\n * both Tree and GroupingRows groups the children of every tree level.\n *\n * You never need to add this plugin yourself — TreePlugin and\n * GroupingRowsPlugin declare it as a dependency and the grid attaches it\n * automatically. It has no configuration.\n *\n * @example Group the children of every tree node\n * ```ts\n * import { TreePlugin } from '@toolbox-web/grid/plugins/tree';\n * import { GroupingRowsPlugin } from '@toolbox-web/grid/plugins/grouping-rows';\n *\n * grid.gridConfig = {\n * plugins: [\n * new TreePlugin({ childrenField: 'children' }),\n * new GroupingRowsPlugin({\n * // Leave the root level ungrouped, group every child level by kind\n * groupOn: (row, { depth }) => (depth > 0 ? row.kind : null),\n * }),\n * ],\n * };\n * ```\n *\n * @since 3.9.0\n */\nexport class HierarchyPlugin extends BaseGridPlugin {\n /** @internal */\n static override readonly manifest: PluginManifest = {\n modifiesRowStructure: true,\n };\n\n /** @internal */\n readonly name = 'hierarchy';\n\n #meta = new WeakMap<object, HierarchyRowMeta>();\n\n /** @internal */\n override detach(): void {\n // Restore the default `role=\"grid\"` (template default in `core/internal/dom-builder.ts`).\n this.gridElement?.querySelector('.rows-body')?.setAttribute('role', 'grid');\n this.#meta = new WeakMap();\n }\n\n /**\n * Build the row model for a contributor's `processRows` hook.\n *\n * Every contributor forwards its hook here; only the one that runs last in\n * the `processRows` pipeline builds the model (for all contributors at\n * once) — the earlier ones pass their rows through untouched.\n *\n * @example\n * ```ts\n * override processRows(rows: readonly unknown[]): unknown[] {\n * return this.grid.getPluginByName('hierarchy')?.process(rows, this) ?? [...rows];\n * }\n * ```\n *\n * @since 3.9.0\n */\n process(rows: readonly unknown[], caller: HierarchyContributor): unknown[] {\n const contributors = this.#contributors();\n if (!contributors.includes(caller as HierarchyContributor & BaseGridPlugin)) {\n this.#meta = new WeakMap();\n return buildHierarchy(rows, [caller], this.#meta);\n }\n if (contributors[contributors.length - 1] !== caller) return rows as unknown[];\n this.#meta = new WeakMap();\n return buildHierarchy(rows, contributors, this.#meta);\n }\n\n /**\n * Hierarchy position of a row in the current row model, or `undefined` when\n * the row is not rendered (e.g. collapsed under a parent).\n *\n * @example\n * ```ts\n * const meta = grid.getPluginByName('hierarchy')?.getRowMeta(grid.rows[0]);\n * console.log(meta?.level, meta?.posInSet, meta?.setSize);\n * ```\n *\n * @since 3.9.0\n */\n getRowMeta(row: unknown): HierarchyRowMeta | undefined {\n return typeof row === 'object' && row !== null ? this.#meta.get(row) : undefined;\n }\n\n /** @internal */\n override afterRender(): void {\n this.#applyAria();\n }\n\n /** @internal */\n override onScrollRender(): void {\n this.#applyAria();\n }\n\n /** Attached contributors, in `processRows` hook order. */\n #contributors(): Array<HierarchyContributor & BaseGridPlugin> {\n const plugins = (this.grid?._pluginManager?.getPlugins?.() ?? []) as readonly BaseGridPlugin[];\n return plugins.filter(isContributor).sort((a, b) => processRowsPriority(a) - processRowsPriority(b));\n }\n\n #applyAria(): void {\n if (this.#contributors().length === 0) return;\n const body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n let hierarchical = false;\n for (const rowEl of body.querySelectorAll('.data-grid-row')) {\n const meta = this.getRowMeta((rowEl as RowElementInternal).__rowDataRef);\n if (!meta) {\n // Pooled row elements may carry a position from a previous row model.\n rowEl.removeAttribute('aria-level');\n rowEl.removeAttribute('aria-setsize');\n rowEl.removeAttribute('aria-posinset');\n continue;\n }\n hierarchical = true;\n setAttrIfChanged(rowEl, 'aria-level', meta.level);\n setAttrIfChanged(rowEl, 'aria-setsize', meta.setSize);\n setAttrIfChanged(rowEl, 'aria-posinset', meta.posInSet);\n }\n\n // `treegrid` only while the model has hierarchy, so per-row level/setsize/posinset are valid in context.\n const role = hierarchical ? 'treegrid' : 'grid';\n const rowsBody = this.gridElement?.querySelector('.rows-body');\n if (rowsBody && rowsBody.getAttribute('role') !== role) rowsBody.setAttribute('role', role);\n }\n}\n","/**\n * Core Tree Data Logic\n *\n * Pure functions for tree flattening, expansion, and traversal.\n */\n\nimport type { FlattenedTreeRow, TreeConfig, TreeRow } from './types';\n\n/**\n * Generates a unique key for a row.\n * Uses row.id if available, otherwise generates from path.\n */\nexport function generateRowKey(row: TreeRow, index: number, parentKey: string | null): string {\n if (row.id !== undefined) return String(row.id);\n return parentKey ? `${parentKey}-${index}` : String(index);\n}\n\n/**\n * Flattens a hierarchical tree into a flat array of rows with metadata.\n * Only includes children of expanded nodes.\n */\nexport function flattenTree(\n rows: readonly TreeRow[],\n config: TreeConfig,\n expandedKeys: Set<string>,\n parentKey: string | null = null,\n depth = 0,\n): FlattenedTreeRow[] {\n const childrenField = config.childrenField ?? 'children';\n const result: FlattenedTreeRow[] = [];\n appendFlattenedRows(rows, childrenField, expandedKeys, parentKey, depth, result);\n return result;\n}\n\nfunction appendFlattenedRows(\n rows: readonly TreeRow[],\n childrenField: string,\n expandedKeys: Set<string>,\n parentKey: string | null,\n depth: number,\n result: FlattenedTreeRow[],\n): void {\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const key = generateRowKey(row, i, parentKey);\n const children = row[childrenField];\n const hasChildren = Array.isArray(children) && children.length > 0;\n const isExpanded = expandedKeys.has(key);\n\n result.push({\n key,\n data: row,\n depth,\n hasChildren,\n isExpanded,\n parentKey,\n posInSet: i + 1,\n setSize: rows.length,\n });\n\n // Recursively add children if expanded\n if (hasChildren && isExpanded) {\n appendFlattenedRows(children as TreeRow[], childrenField, expandedKeys, key, depth + 1, result);\n }\n }\n}\n\n/**\n * Toggles the expansion state of a row.\n * Returns a new Set with the toggled state.\n */\nexport function toggleExpand(expandedKeys: Set<string>, key: string): Set<string> {\n const newExpanded = new Set(expandedKeys);\n if (newExpanded.has(key)) {\n newExpanded.delete(key);\n } else {\n newExpanded.add(key);\n }\n return newExpanded;\n}\n\n/**\n * Expands all nodes in the tree.\n * Returns a Set of all parent row keys.\n */\nexport function expandAll(\n rows: readonly TreeRow[],\n config: TreeConfig,\n parentKey: string | null = null,\n depth = 0,\n): Set<string> {\n const childrenField = config.childrenField ?? 'children';\n const keys = new Set<string>();\n\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const key = generateRowKey(row, i, parentKey);\n const children = row[childrenField];\n\n if (Array.isArray(children) && children.length > 0) {\n keys.add(key);\n const childKeys = expandAll(children as TreeRow[], config, key, depth + 1);\n for (const k of childKeys) keys.add(k);\n }\n }\n\n return keys;\n}\n\n/**\n * Collapses all nodes.\n * Returns an empty Set.\n */\nexport function collapseAll(): Set<string> {\n return new Set();\n}\n\n/**\n * Gets all descendants of a node from the flattened row list.\n * Useful for operations that need to affect an entire subtree.\n */\nexport function getDescendants(flattenedRows: FlattenedTreeRow[], parentKey: string): FlattenedTreeRow[] {\n const descendants: FlattenedTreeRow[] = [];\n let collecting = false;\n let parentDepth = -1;\n\n for (const row of flattenedRows) {\n if (row.key === parentKey) {\n collecting = true;\n parentDepth = row.depth;\n continue;\n }\n\n if (collecting) {\n if (row.depth > parentDepth) {\n descendants.push(row);\n } else {\n break; // No longer a descendant\n }\n }\n }\n\n return descendants;\n}\n\n/**\n * Finds the path from root to a specific row key.\n * Returns an array of keys from root to the target (inclusive).\n */\nexport function getPathToKey(\n rows: readonly TreeRow[],\n targetKey: string,\n config: TreeConfig,\n parentKey: string | null = null,\n depth = 0,\n): string[] | null {\n const childrenField = config.childrenField ?? 'children';\n\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const key = generateRowKey(row, i, parentKey);\n\n if (key === targetKey) {\n return [key];\n }\n\n const children = row[childrenField];\n if (Array.isArray(children) && children.length > 0) {\n const childPath = getPathToKey(children as TreeRow[], targetKey, config, key, depth + 1);\n if (childPath) {\n return [key, ...childPath];\n }\n }\n }\n\n return null;\n}\n\n/**\n * Expands all ancestors of a specific row to make it visible.\n * Returns a new Set with the required keys added.\n */\nexport function expandToKey(\n rows: readonly TreeRow[],\n targetKey: string,\n config: TreeConfig,\n existingExpanded: Set<string>,\n): Set<string> {\n const path = getPathToKey(rows, targetKey, config);\n if (!path) return existingExpanded;\n\n const newExpanded = new Set(existingExpanded);\n // Add all keys except the last one (the target itself)\n for (let i = 0; i < path.length - 1; i++) {\n newExpanded.add(path[i]);\n }\n return newExpanded;\n}\n","/**\n * 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 // #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