@toolbox-web/grid 1.19.0 → 1.19.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/all.js +97 -86
- package/all.js.map +1 -1
- package/index.js +367 -341
- package/index.js.map +1 -1
- package/lib/core/grid.d.ts.map +1 -1
- package/lib/core/internal/rows.d.ts.map +1 -1
- package/lib/core/internal/utils.d.ts +2 -2
- package/lib/core/internal/utils.d.ts.map +1 -1
- package/lib/core/plugin/types.d.ts +0 -2
- package/lib/core/plugin/types.d.ts.map +1 -1
- package/lib/core/types.d.ts +11 -0
- package/lib/core/types.d.ts.map +1 -1
- package/lib/plugins/clipboard/index.js.map +1 -1
- package/lib/plugins/column-virtualization/index.js.map +1 -1
- package/lib/plugins/context-menu/index.js.map +1 -1
- package/lib/plugins/editing/index.js.map +1 -1
- package/lib/plugins/export/index.js.map +1 -1
- package/lib/plugins/filtering/index.js.map +1 -1
- package/lib/plugins/grouping-columns/index.js.map +1 -1
- package/lib/plugins/grouping-rows/index.js.map +1 -1
- package/lib/plugins/master-detail/MasterDetailPlugin.d.ts.map +1 -1
- package/lib/plugins/master-detail/index.js +62 -55
- package/lib/plugins/master-detail/index.js.map +1 -1
- package/lib/plugins/multi-sort/index.js.map +1 -1
- package/lib/plugins/pinned-columns/index.js.map +1 -1
- package/lib/plugins/pinned-rows/index.js.map +1 -1
- package/lib/plugins/pivot/index.js.map +1 -1
- package/lib/plugins/print/index.js.map +1 -1
- package/lib/plugins/reorder/index.js.map +1 -1
- package/lib/plugins/responsive/index.js.map +1 -1
- package/lib/plugins/row-reorder/index.js.map +1 -1
- package/lib/plugins/selection/SelectionPlugin.d.ts +3 -0
- package/lib/plugins/selection/SelectionPlugin.d.ts.map +1 -1
- package/lib/plugins/selection/index.js +179 -175
- package/lib/plugins/selection/index.js.map +1 -1
- package/lib/plugins/selection/types.d.ts +26 -0
- package/lib/plugins/selection/types.d.ts.map +1 -1
- package/lib/plugins/server-side/index.js.map +1 -1
- package/lib/plugins/tree/index.js.map +1 -1
- package/lib/plugins/undo-redo/index.js.map +1 -1
- package/lib/plugins/visibility/index.js.map +1 -1
- package/package.json +1 -1
- package/umd/grid.all.umd.js +24 -24
- package/umd/grid.all.umd.js.map +1 -1
- package/umd/grid.umd.js +11 -11
- package/umd/grid.umd.js.map +1 -1
- package/umd/plugins/master-detail.umd.js +1 -1
- package/umd/plugins/master-detail.umd.js.map +1 -1
- package/umd/plugins/selection.umd.js +2 -2
- package/umd/plugins/selection.umd.js.map +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(g,w){typeof exports=="object"&&typeof module<"u"?w(exports,require("../../core/internal/sanitize"),require("../../core/plugin/base-plugin"),require("../../core/plugin/expander-column")):typeof define=="function"&&define.amd?define(["exports","../../core/internal/sanitize","../../core/plugin/base-plugin","../../core/plugin/expander-column"],w):(g=typeof globalThis<"u"?globalThis:g||self,w(g.TbwGridPlugin_masterDetail={},g.TbwGrid,g.TbwGrid,g.TbwGrid))})(this,(function(g,w,E,m){"use strict";function b(f,e){const t=new Set(f);return t.has(e)?t.delete(e):t.add(e),t}function A(f,e){const t=new Set(f);return t.add(e),t}function v(f,e){const t=new Set(f);return t.delete(e),t}function y(f,e){return f.has(e)}function D(f,e,t,i){const s=document.createElement("div");s.className="master-detail-row",s.setAttribute("data-detail-for",String(e)),s.setAttribute("role","row");const n=document.createElement("div");n.className="master-detail-cell",n.setAttribute("role","cell"),n.style.gridColumn=`1 / ${i+1}`;const c=t(f,e);return typeof c=="string"?n.innerHTML=c:c instanceof HTMLElement&&n.appendChild(c),s.appendChild(n),s}const H="@layer tbw-plugins{tbw-grid .cell[data-field=__tbw_expander]{border-right:none!important;padding:0;display:flex;align-items:center;justify-content:center}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 .master-detail-expander{display:flex;align-items:center;justify-content:center;width:100%;height:100%}tbw-grid .master-detail-toggle{cursor:pointer;opacity:.7;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center}tbw-grid .master-detail-toggle:hover{opacity:1}tbw-grid .master-detail-row{grid-column:1 / -1;display:grid;background:var(--tbw-master-detail-bg, var(--tbw-color-row-alt));border-bottom:1px solid var(--tbw-master-detail-border, var(--tbw-color-border));overflow:hidden}tbw-grid .master-detail-cell{padding:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem));overflow:auto}tbw-grid .master-detail-row.tbw-expanding{animation:tbw-detail-expand var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}tbw-grid .master-detail-row.tbw-collapsing{animation:tbw-detail-collapse var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-detail-expand{0%{opacity:0;max-height:0;padding-top:0;padding-bottom:0}to{opacity:1;max-height:var(--tbw-detail-max-height, 31.25rem);padding-top:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem));padding-bottom:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem))}}@keyframes tbw-detail-collapse{0%{opacity:1;max-height:var(--tbw-detail-max-height, 31.25rem)}to{opacity:0;max-height:0}}}";class x extends E.BaseGridPlugin{name="masterDetail";styles=H;get defaultConfig(){return{detailHeight:"auto",expandOnRowClick:!1,collapseOnClickOutside:!1,animation:"slide"}}attach(e){super.attach(e),this.parseLightDomDetail()}parseLightDomDetail(){const e=this.grid;if(!e||typeof e.querySelector!="function")return;const t=e.querySelector("tbw-grid-detail");if(!t)return;const i=e;if(i.__frameworkAdapter?.parseDetailElement){const r=i.__frameworkAdapter.parseDetailElement(t);if(r){this.config={...this.config,detailRenderer:r};return}}const s=t.getAttribute("animation"),n=t.getAttribute("show-expand-column"),c=t.getAttribute("expand-on-row-click"),h=t.getAttribute("collapse-on-click-outside"),d=t.getAttribute("height"),o={};s!==null&&(o.animation=s==="false"?!1:s),n!==null&&(o.showExpandColumn=n!=="false"),c!==null&&(o.expandOnRowClick=c==="true"),h!==null&&(o.collapseOnClickOutside=h==="true"),d!==null&&(o.detailHeight=d==="auto"?"auto":parseInt(d,10));const a=t.innerHTML.trim();a&&!this.config.detailRenderer&&(o.detailRenderer=(r,l)=>{const u=w.evalTemplateString(a,{value:r,row:r});return w.sanitizeHTML(u)}),Object.keys(o).length>0&&(this.config={...this.config,...o})}get animationStyle(){return this.isAnimationEnabled?this.config.animation??"slide":!1}animateExpand(e,t,i){if(!this.isAnimationEnabled||this.animationStyle===!1)return!1;e.classList.add("tbw-expanding");let s=!1;const n=()=>{s||(s=!0,e.classList.remove("tbw-expanding"),t!==void 0&&i!==void 0&&this.#t(e,t,i))};return e.addEventListener("animationend",n,{once:!0}),setTimeout(n,this.animationDuration+50),!0}animateCollapse(e,t){if(!this.isAnimationEnabled||this.animationStyle===!1){t();return}e.classList.add("tbw-collapsing");const i=()=>{e.classList.remove("tbw-collapsing"),t()};e.addEventListener("animationend",i,{once:!0}),setTimeout(i,this.animationDuration+50)}#t(e,t,i){if(!e.isConnected)return;const s=e.offsetHeight;if(s>0){const n=this.measuredDetailHeights.get(t);this.measuredDetailHeights.set(t,s),n!==s&&this.grid.invalidateRowHeight(i)}}expandedRows=new Set;detailElements=new Map;measuredDetailHeights=new Map;rowsToAnimate=new Set;static DEFAULT_DETAIL_HEIGHT=150;getDetailHeight(e){const t=this.detailElements.get(e);if(t&&!(t.classList.contains("tbw-expanding")||t.classList.contains("tbw-collapsing"))){const n=t.offsetHeight;if(n>0)return this.measuredDetailHeights.set(e,n),n}const i=this.measuredDetailHeights.get(e);return i&&i>0?i:typeof this.config?.detailHeight=="number"?this.config.detailHeight:x.DEFAULT_DETAIL_HEIGHT}toggleAndEmit(e,t){this.expandedRows=b(this.expandedRows,e);const i=this.expandedRows.has(e);i&&this.rowsToAnimate.add(e),this.emit("detail-expand",{rowIndex:t,row:e,expanded:i}),this.requestRender()}detach(){this.expandedRows.clear(),this.detailElements.clear(),this.measuredDetailHeights.clear(),this.rowsToAnimate.clear()}processColumns(e){if(!(this.config.showExpandColumn===!0||this.config.showExpandColumn!==!1&&!!this.config.detailRenderer))return[...e];const i=[...e];if(m.findExpanderColumn(i))return i;const n=m.createExpanderColumnConfig(this.name);return n.viewRenderer=c=>{const{row:h}=c,d=this.expandedRows.has(h),o=document.createElement("span");o.className="master-detail-expander expander-cell";const a=document.createElement("span");return a.className=`master-detail-toggle${d?" expanded":""}`,this.setIcon(a,this.resolveIcon(d?"collapse":"expand")),a.setAttribute("role","button"),a.setAttribute("tabindex","0"),a.setAttribute("aria-expanded",String(d)),a.setAttribute("aria-label",d?"Collapse details":"Expand details"),o.appendChild(a),o},[n,...i]}onRowClick(e){if(!(!this.config.expandOnRowClick||!this.config.detailRenderer))return this.toggleAndEmit(e.row,e.rowIndex),!1}onCellClick(e){if(e.originalEvent?.target?.classList.contains("master-detail-toggle"))return this.toggleAndEmit(e.row,e.rowIndex),!0;this.expandedRows.size>0&&queueMicrotask(()=>this.#e())}onKeyDown(e){if(e.key!==" ")return;const t=this.grid._focusCol,i=this.grid._focusRow,s=this.columns[t];if(!s||!m.isExpanderColumn(s))return;const n=this.rows[i];if(n)return e.preventDefault(),this.toggleAndEmit(n,i),this.requestRenderWithFocus(),!0}afterRender(){this.#e()}onScrollRender(){!this.config.detailRenderer||this.expandedRows.size===0||this.#e()}#e(){if(!this.config.detailRenderer)return;const e=this.gridElement?.querySelector(".rows");if(!e)return;const t=this.grid,i=t._rowPool,s=t._virtualization?.start??0,n=t._virtualization?.end??0,c=this.columns.length,h=s,d=n,o=new Map;if(i){const a=Math.min(i.length,d-h);for(let r=0;r<a;r++){const l=i[r];l.parentNode===e&&o.set(h+r,l)}}else{const a=e.querySelectorAll(".data-grid-row");for(const r of a){const l=r.querySelector(".cell[data-row]"),u=l?parseInt(l.getAttribute("data-row")??"-1",10):-1;u>=0&&o.set(u,r)}}for(const[a,r]of this.detailElements){const l=this.rows.indexOf(a),u=this.expandedRows.has(a),p=l>=0&&o.has(l);(!u||!p)&&(r.parentNode&&r.remove(),this.detailElements.delete(a))}for(const[a,r]of o){const l=this.rows[a];if(!l||!this.expandedRows.has(l))continue;const u=this.detailElements.get(l);if(u){u.previousElementSibling!==r&&r.after(u);continue}const p=D(l,a,this.config.detailRenderer,c);typeof this.config.detailHeight=="number"&&(p.style.height=`${this.config.detailHeight}px`),r.after(p),this.detailElements.set(l,p);const R=this.rowsToAnimate.has(l);R&&this.rowsToAnimate.delete(l),R&&this.animateExpand(p,l,a)||requestAnimationFrame(()=>{this.#t(p,l,a)})}}getExtraHeight(){let e=0;for(const t of this.expandedRows)e+=this.getDetailHeight(t);return e}getExtraHeightBefore(e){let t=0;for(const i of this.expandedRows){const s=this.rows.indexOf(i);s>=0&&s<e&&(t+=this.getDetailHeight(i))}return t}getRowHeight(e,t){if(!this.expandedRows.has(e))return;const s=this.grid.defaultRowHeight??28,n=this.getDetailHeight(e);return s+n}adjustVirtualStart(e,t,i){if(this.expandedRows.size===0)return e;const s=this.grid?._virtualization?.positionCache;let n=e;if(s&&s.length>0)for(const c of this.expandedRows){const h=this.rows.indexOf(c);if(h<0||h>=e)continue;s[h].offset+s[h].height>t&&h<n&&(n=h)}else{const c=[];for(const d of this.expandedRows){const o=this.rows.indexOf(d);o>=0&&c.push({index:o,row:d})}c.sort((d,o)=>d.index-o.index);let h=0;for(const{index:d,row:o}of c){const a=d*i+h,r=this.getDetailHeight(o),l=a+i+r;h+=r,!(d>=e)&&l>t&&d<n&&(n=d)}}return n}expand(e){const t=this.rows[e];t&&(this.rowsToAnimate.add(t),this.expandedRows=A(this.expandedRows,t),this.requestRender())}collapse(e){const t=this.rows[e];t&&(this.expandedRows=v(this.expandedRows,t),this.requestRender())}toggle(e){const t=this.rows[e];t&&(this.expandedRows=b(this.expandedRows,t),this.expandedRows.has(t)&&this.rowsToAnimate.add(t),this.requestRender())}isExpanded(e){const t=this.rows[e];return t?y(this.expandedRows,t):!1}expandAll(){for(const e of this.rows)this.rowsToAnimate.add(e),this.expandedRows.add(e);this.requestRender()}collapseAll(){this.expandedRows.clear(),this.requestRender()}getExpandedRows(){const e=[];for(const t of this.expandedRows){const i=this.rows.indexOf(t);i>=0&&e.push(i)}return e}getDetailElement(e){const t=this.rows[e];return t?this.detailElements.get(t):void 0}refreshDetailRenderer(){const e=this.config.detailRenderer;if(this.config={...this.config,detailRenderer:void 0},this.parseLightDomDetail(),!this.config.detailRenderer&&e&&(this.config={...this.config,detailRenderer:e}),this.config.detailRenderer){const t=this.grid;typeof t.refreshColumns=="function"?t.refreshColumns():this.requestRender()}}}g.MasterDetailPlugin=x,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})}));
|
|
1
|
+
(function(g,w){typeof exports=="object"&&typeof module<"u"?w(exports,require("../../core/internal/sanitize"),require("../../core/plugin/base-plugin"),require("../../core/plugin/expander-column")):typeof define=="function"&&define.amd?define(["exports","../../core/internal/sanitize","../../core/plugin/base-plugin","../../core/plugin/expander-column"],w):(g=typeof globalThis<"u"?globalThis:g||self,w(g.TbwGridPlugin_masterDetail={},g.TbwGrid,g.TbwGrid,g.TbwGrid))})(this,(function(g,w,A,x){"use strict";function R(f,e){const t=new Set(f);return t.has(e)?t.delete(e):t.add(e),t}function v(f,e){const t=new Set(f);return t.add(e),t}function y(f,e){const t=new Set(f);return t.delete(e),t}function D(f,e){return f.has(e)}function H(f,e,t,i){const s=document.createElement("div");s.className="master-detail-row",s.setAttribute("data-detail-for",String(e)),s.setAttribute("role","row");const n=document.createElement("div");n.className="master-detail-cell",n.setAttribute("role","cell"),n.style.gridColumn=`1 / ${i+1}`;const c=t(f,e);return typeof c=="string"?n.innerHTML=c:c instanceof HTMLElement&&n.appendChild(c),s.appendChild(n),s}const C="@layer tbw-plugins{tbw-grid .cell[data-field=__tbw_expander]{border-right:none!important;padding:0;display:flex;align-items:center;justify-content:center}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 .master-detail-expander{display:flex;align-items:center;justify-content:center;width:100%;height:100%}tbw-grid .master-detail-toggle{cursor:pointer;opacity:.7;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center}tbw-grid .master-detail-toggle:hover{opacity:1}tbw-grid .master-detail-row{grid-column:1 / -1;display:grid;background:var(--tbw-master-detail-bg, var(--tbw-color-row-alt));border-bottom:1px solid var(--tbw-master-detail-border, var(--tbw-color-border));overflow:hidden}tbw-grid .master-detail-cell{padding:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem));overflow:auto}tbw-grid .master-detail-row.tbw-expanding{animation:tbw-detail-expand var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}tbw-grid .master-detail-row.tbw-collapsing{animation:tbw-detail-collapse var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-detail-expand{0%{opacity:0;max-height:0;padding-top:0;padding-bottom:0}to{opacity:1;max-height:var(--tbw-detail-max-height, 31.25rem);padding-top:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem));padding-bottom:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem))}}@keyframes tbw-detail-collapse{0%{opacity:1;max-height:var(--tbw-detail-max-height, 31.25rem)}to{opacity:0;max-height:0}}}";class b extends A.BaseGridPlugin{name="masterDetail";styles=C;get defaultConfig(){return{detailHeight:"auto",expandOnRowClick:!1,collapseOnClickOutside:!1,animation:"slide"}}attach(e){super.attach(e),this.parseLightDomDetail()}parseLightDomDetail(){const e=this.grid;if(!e||typeof e.querySelector!="function")return;const t=e.querySelector("tbw-grid-detail");if(!t)return;const i=e;if(i.__frameworkAdapter?.parseDetailElement){const r=i.__frameworkAdapter.parseDetailElement(t);if(r){this.config={...this.config,detailRenderer:r};return}}const s=t.getAttribute("animation"),n=t.getAttribute("show-expand-column"),c=t.getAttribute("expand-on-row-click"),h=t.getAttribute("collapse-on-click-outside"),d=t.getAttribute("height"),o={};s!==null&&(o.animation=s==="false"?!1:s),n!==null&&(o.showExpandColumn=n!=="false"),c!==null&&(o.expandOnRowClick=c==="true"),h!==null&&(o.collapseOnClickOutside=h==="true"),d!==null&&(o.detailHeight=d==="auto"?"auto":parseInt(d,10));const a=t.innerHTML.trim();a&&!this.config.detailRenderer&&(o.detailRenderer=(r,l)=>{const u=w.evalTemplateString(a,{value:r,row:r});return w.sanitizeHTML(u)}),Object.keys(o).length>0&&(this.config={...this.config,...o})}get animationStyle(){return this.isAnimationEnabled?this.config.animation??"slide":!1}animateExpand(e,t,i){if(!this.isAnimationEnabled||this.animationStyle===!1)return!1;e.classList.add("tbw-expanding");let s=!1;const n=()=>{s||(s=!0,e.classList.remove("tbw-expanding"),t!==void 0&&i!==void 0&&this.#t(e,t,i))};return e.addEventListener("animationend",n,{once:!0}),setTimeout(n,this.animationDuration+50),!0}animateCollapse(e,t){if(!this.isAnimationEnabled||this.animationStyle===!1){t();return}e.classList.add("tbw-collapsing");const i=()=>{e.classList.remove("tbw-collapsing"),t()};e.addEventListener("animationend",i,{once:!0}),setTimeout(i,this.animationDuration+50)}#t(e,t,i){if(!e.isConnected)return;const s=e.offsetHeight;if(s>0){const n=this.measuredDetailHeights.get(t);this.measuredDetailHeights.set(t,s),n!==s&&this.grid.invalidateRowHeight(i)}}expandedRows=new Set;detailElements=new Map;measuredDetailHeights=new Map;rowsToAnimate=new Set;static DEFAULT_DETAIL_HEIGHT=150;getDetailHeight(e){const t=this.detailElements.get(e);if(t&&!(t.classList.contains("tbw-expanding")||t.classList.contains("tbw-collapsing"))){const n=t.offsetHeight;if(n>0)return this.measuredDetailHeights.set(e,n),n}const i=this.measuredDetailHeights.get(e);return i&&i>0?i:typeof this.config?.detailHeight=="number"?this.config.detailHeight:b.DEFAULT_DETAIL_HEIGHT}toggleAndEmit(e,t){this.expandedRows=R(this.expandedRows,e);const i=this.expandedRows.has(e);i&&this.rowsToAnimate.add(e),this.emit("detail-expand",{rowIndex:t,row:e,expanded:i}),this.requestRender()}detach(){this.expandedRows.clear(),this.detailElements.clear(),this.measuredDetailHeights.clear(),this.rowsToAnimate.clear()}processColumns(e){if(!(this.config.showExpandColumn===!0||this.config.showExpandColumn!==!1&&!!this.config.detailRenderer))return[...e];const i=[...e];if(x.findExpanderColumn(i))return i;const n=x.createExpanderColumnConfig(this.name);return n.viewRenderer=c=>{const{row:h}=c,d=this.expandedRows.has(h),o=document.createElement("span");o.className="master-detail-expander expander-cell";const a=document.createElement("span");return a.className=`master-detail-toggle${d?" expanded":""}`,this.setIcon(a,this.resolveIcon(d?"collapse":"expand")),a.setAttribute("role","button"),a.setAttribute("tabindex","0"),a.setAttribute("aria-expanded",String(d)),a.setAttribute("aria-label",d?"Collapse details":"Expand details"),o.appendChild(a),o},[n,...i]}onRowClick(e){if(!(!this.config.expandOnRowClick||!this.config.detailRenderer))return this.toggleAndEmit(e.row,e.rowIndex),!1}onCellClick(e){if(e.originalEvent?.target?.classList.contains("master-detail-toggle"))return this.toggleAndEmit(e.row,e.rowIndex),!0;this.expandedRows.size>0&&queueMicrotask(()=>this.#e())}onKeyDown(e){if(e.key!==" ")return;const t=this.grid._focusCol,i=this.grid._focusRow,s=this.columns[t];if(!s||!x.isExpanderColumn(s))return;const n=this.rows[i];if(n)return e.preventDefault(),this.toggleAndEmit(n,i),this.requestRenderWithFocus(),!0}afterRender(){this.#e()}onScrollRender(){!this.config.detailRenderer||this.expandedRows.size===0||this.#e()}#e(){if(!this.config.detailRenderer)return;const e=this.gridElement?.querySelector(".rows");if(!e)return;const t=this.grid,i=t._rowPool,s=t._virtualization?.start??0,n=t._virtualization?.end??0,c=this.columns.length,h=s,d=n,o=new Map;if(i){const a=Math.min(i.length,d-h);for(let r=0;r<a;r++){const l=i[r];l.parentNode===e&&o.set(h+r,l)}}else{const a=e.querySelectorAll(".data-grid-row");for(const r of a){const l=r.querySelector(".cell[data-row]"),u=l?parseInt(l.getAttribute("data-row")??"-1",10):-1;u>=0&&o.set(u,r)}}for(const[a,r]of this.detailElements){const l=this.rows.indexOf(a),u=this.expandedRows.has(a),p=l>=0&&o.has(l);if(!u||!p){const m=this.grid.__frameworkAdapter;if(m?.unmount){const E=r.querySelector(".master-detail-cell")?.firstElementChild;E&&m.unmount(E)}r.parentNode&&r.remove(),this.detailElements.delete(a)}}for(const[a,r]of o){const l=this.rows[a];if(!l||!this.expandedRows.has(l))continue;const u=this.detailElements.get(l);if(u){u.previousElementSibling!==r&&r.after(u);continue}const p=H(l,a,this.config.detailRenderer,c);typeof this.config.detailHeight=="number"&&(p.style.height=`${this.config.detailHeight}px`),r.after(p),this.detailElements.set(l,p);const m=this.rowsToAnimate.has(l);m&&this.rowsToAnimate.delete(l),m&&this.animateExpand(p,l,a)||requestAnimationFrame(()=>{this.#t(p,l,a)})}}getExtraHeight(){let e=0;for(const t of this.expandedRows)e+=this.getDetailHeight(t);return e}getExtraHeightBefore(e){let t=0;for(const i of this.expandedRows){const s=this.rows.indexOf(i);s>=0&&s<e&&(t+=this.getDetailHeight(i))}return t}getRowHeight(e,t){if(!this.expandedRows.has(e))return;const s=this.grid.defaultRowHeight??28,n=this.getDetailHeight(e);return s+n}adjustVirtualStart(e,t,i){if(this.expandedRows.size===0)return e;const s=this.grid?._virtualization?.positionCache;let n=e;if(s&&s.length>0)for(const c of this.expandedRows){const h=this.rows.indexOf(c);if(h<0||h>=e)continue;s[h].offset+s[h].height>t&&h<n&&(n=h)}else{const c=[];for(const d of this.expandedRows){const o=this.rows.indexOf(d);o>=0&&c.push({index:o,row:d})}c.sort((d,o)=>d.index-o.index);let h=0;for(const{index:d,row:o}of c){const a=d*i+h,r=this.getDetailHeight(o),l=a+i+r;h+=r,!(d>=e)&&l>t&&d<n&&(n=d)}}return n}expand(e){const t=this.rows[e];t&&(this.rowsToAnimate.add(t),this.expandedRows=v(this.expandedRows,t),this.requestRender())}collapse(e){const t=this.rows[e];t&&(this.expandedRows=y(this.expandedRows,t),this.requestRender())}toggle(e){const t=this.rows[e];t&&(this.expandedRows=R(this.expandedRows,t),this.expandedRows.has(t)&&this.rowsToAnimate.add(t),this.requestRender())}isExpanded(e){const t=this.rows[e];return t?D(this.expandedRows,t):!1}expandAll(){for(const e of this.rows)this.rowsToAnimate.add(e),this.expandedRows.add(e);this.requestRender()}collapseAll(){this.expandedRows.clear(),this.requestRender()}getExpandedRows(){const e=[];for(const t of this.expandedRows){const i=this.rows.indexOf(t);i>=0&&e.push(i)}return e}getDetailElement(e){const t=this.rows[e];return t?this.detailElements.get(t):void 0}refreshDetailRenderer(){const e=this.config.detailRenderer;if(this.config={...this.config,detailRenderer:void 0},this.parseLightDomDetail(),!this.config.detailRenderer&&e&&(this.config={...this.config,detailRenderer:e}),this.config.detailRenderer){const t=this.grid;typeof t.refreshColumns=="function"?t.refreshColumns():this.requestRender()}}}g.MasterDetailPlugin=b,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})}));
|
|
2
2
|
//# sourceMappingURL=master-detail.umd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"master-detail.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/master-detail/master-detail.ts","../../../../../libs/grid/src/lib/plugins/master-detail/MasterDetailPlugin.ts"],"sourcesContent":["/**\n * Master/Detail Core Logic\n *\n * Pure functions for managing detail row expansion state.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n// Uses `any` for maximum flexibility with user-defined row types.\n\n/**\n * Toggle the expansion state of a detail row.\n * Returns a new Set with the updated state.\n */\nexport function toggleDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n if (newExpanded.has(row)) {\n newExpanded.delete(row);\n } else {\n newExpanded.add(row);\n }\n return newExpanded;\n}\n\n/**\n * Expand a detail row.\n * Returns a new Set with the row added.\n */\nexport function expandDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n newExpanded.add(row);\n return newExpanded;\n}\n\n/**\n * Collapse a detail row.\n * Returns a new Set with the row removed.\n */\nexport function collapseDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n newExpanded.delete(row);\n return newExpanded;\n}\n\n/**\n * Check if a detail row is expanded.\n */\nexport function isDetailExpanded(expandedRows: Set<object>, row: object): boolean {\n return expandedRows.has(row);\n}\n\n/**\n * Create a detail element for a given row.\n * The element spans all columns and contains the rendered content.\n */\nexport function createDetailElement(\n row: any,\n rowIndex: number,\n renderer: (row: any, rowIndex: number) => HTMLElement | string,\n columnCount: number\n): HTMLElement {\n const detailRow = document.createElement('div');\n detailRow.className = 'master-detail-row';\n detailRow.setAttribute('data-detail-for', String(rowIndex));\n detailRow.setAttribute('role', 'row');\n\n const detailCell = document.createElement('div');\n detailCell.className = 'master-detail-cell';\n detailCell.setAttribute('role', 'cell');\n detailCell.style.gridColumn = `1 / ${columnCount + 1}`;\n\n const content = renderer(row, rowIndex);\n if (typeof content === 'string') {\n detailCell.innerHTML = content;\n } else if (content instanceof HTMLElement) {\n detailCell.appendChild(content);\n }\n\n detailRow.appendChild(detailCell);\n return detailRow;\n}\n","/**\n * Master/Detail Plugin (Class-based)\n *\n * Enables expandable detail rows showing additional content for each row.\n * Animation style is plugin-configured; respects grid-level animation.mode.\n */\n\nimport { evalTemplateString, sanitizeHTML } from '../../core/internal/sanitize';\nimport { BaseGridPlugin, CellClickEvent, GridElement, RowClickEvent } from '../../core/plugin/base-plugin';\nimport { createExpanderColumnConfig, findExpanderColumn, isExpanderColumn } from '../../core/plugin/expander-column';\nimport type { ColumnConfig } from '../../core/types';\nimport {\n collapseDetailRow,\n createDetailElement,\n expandDetailRow,\n isDetailExpanded,\n toggleDetailRow,\n} from './master-detail';\nimport styles from './master-detail.css?inline';\nimport type { DetailExpandDetail, ExpandCollapseAnimation, MasterDetailConfig } from './types';\n\n/**\n * Master-Detail Plugin for tbw-grid\n *\n * Creates expandable detail rows that reveal additional content beneath each master row.\n * Perfect for order/line-item UIs, employee/department views, or any scenario where\n * you need to show related data without navigating away.\n *\n * ## Installation\n *\n * ```ts\n * import { MasterDetailPlugin } from '@toolbox-web/grid/plugins/master-detail';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `detailRenderer` | `(row) => HTMLElement \\| string` | required | Render function for detail content |\n * | `expandOnRowClick` | `boolean` | `false` | Expand when clicking the row |\n * | `detailHeight` | `number \\| 'auto'` | `'auto'` | Fixed height or auto-size |\n * | `collapseOnClickOutside` | `boolean` | `false` | Collapse when clicking outside |\n * | `showExpandColumn` | `boolean` | `true` | Show expand/collapse column |\n * | `animation` | `false \\| 'slide' \\| 'fade'` | `'slide'` | Animation style |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `expandRow` | `(rowIndex) => void` | Expand a specific row |\n * | `collapseRow` | `(rowIndex) => void` | Collapse a specific row |\n * | `toggleRow` | `(rowIndex) => void` | Toggle row expansion |\n * | `expandAll` | `() => void` | Expand all rows |\n * | `collapseAll` | `() => void` | Collapse all rows |\n * | `isRowExpanded` | `(rowIndex) => boolean` | Check if row is expanded |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-master-detail-bg` | `var(--tbw-color-row-alt)` | Detail row background |\n * | `--tbw-master-detail-border` | `var(--tbw-color-border)` | Detail row border |\n * | `--tbw-detail-padding` | `1em` | Detail content padding |\n * | `--tbw-animation-duration` | `200ms` | Expand/collapse animation |\n *\n * @example Basic Master-Detail with HTML Template\n * ```ts\n * import '@toolbox-web/grid';\n * import { MasterDetailPlugin } from '@toolbox-web/grid/plugins/master-detail';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'orderId', header: 'Order ID' },\n * { field: 'customer', header: 'Customer' },\n * { field: 'total', header: 'Total', type: 'currency' },\n * ],\n * plugins: [\n * new MasterDetailPlugin({\n * detailRenderer: (row) => `\n * <div class=\"order-details\">\n * <h4>Order Items</h4>\n * <ul>${row.items.map(i => `<li>${i.name} - $${i.price}</li>`).join('')}</ul>\n * </div>\n * `,\n * }),\n * ],\n * };\n * ```\n *\n * @example Nested Grid in Detail\n * ```ts\n * new MasterDetailPlugin({\n * detailRenderer: (row) => {\n * const childGrid = document.createElement('tbw-grid');\n * childGrid.style.height = '200px';\n * childGrid.gridConfig = { columns: [...] };\n * childGrid.rows = row.items || [];\n * return childGrid;\n * },\n * })\n * ```\n *\n * @see {@link MasterDetailConfig} for all configuration options\n * @see {@link DetailExpandDetail} for expand/collapse event details\n *\n * @internal Extends BaseGridPlugin\n */\nexport class MasterDetailPlugin extends BaseGridPlugin<MasterDetailConfig> {\n /** @internal */\n readonly name = 'masterDetail';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<MasterDetailConfig> {\n return {\n detailHeight: 'auto',\n expandOnRowClick: false,\n collapseOnClickOutside: false,\n // Note: showExpandColumn is intentionally NOT defaulted here.\n // If undefined, processColumns() adds expander only when detailRenderer is provided.\n // Set to true for framework adapters that register renderers asynchronously.\n animation: 'slide', // Plugin's own default\n };\n }\n\n // #region Light DOM Parsing\n\n /**\n * Called when plugin is attached to the grid.\n * Parses light DOM for `<tbw-grid-detail>` elements to configure detail templates.\n * @internal\n */\n override attach(grid: GridElement): void {\n super.attach(grid);\n this.parseLightDomDetail();\n }\n\n /**\n * Parse `<tbw-grid-detail>` elements from the grid's light DOM.\n *\n * Allows declarative configuration:\n * ```html\n * <tbw-grid [rows]=\"data\">\n * <tbw-grid-detail>\n * <div class=\"detail-content\">\n * <p>Name: {{ row.name }}</p>\n * <p>Email: {{ row.email }}</p>\n * </div>\n * </tbw-grid-detail>\n * </tbw-grid>\n * ```\n *\n * Attributes:\n * - `animation`: 'slide' | 'fade' | 'false' (default: 'slide')\n * - `show-expand-column`: 'true' | 'false' (default: 'true')\n * - `expand-on-row-click`: 'true' | 'false' (default: 'false')\n * - `collapse-on-click-outside`: 'true' | 'false' (default: 'false')\n * - `height`: number (pixels) or 'auto' (default: 'auto')\n */\n private parseLightDomDetail(): void {\n const gridEl = this.grid as unknown as Element;\n if (!gridEl || typeof gridEl.querySelector !== 'function') return;\n\n const detailEl = gridEl.querySelector('tbw-grid-detail');\n if (!detailEl) return;\n\n // Check if a framework adapter wants to handle this element\n // (e.g., Angular adapter intercepts for ng-template rendering)\n const gridWithAdapter = gridEl as unknown as {\n __frameworkAdapter?: {\n parseDetailElement?: (el: Element) => ((row: any, rowIndex: number) => HTMLElement | string) | undefined;\n };\n };\n if (gridWithAdapter.__frameworkAdapter?.parseDetailElement) {\n const adapterRenderer = gridWithAdapter.__frameworkAdapter.parseDetailElement(detailEl);\n if (adapterRenderer) {\n this.config = { ...this.config, detailRenderer: adapterRenderer };\n return;\n }\n }\n\n // Parse attributes for configuration\n const animation = detailEl.getAttribute('animation');\n const showExpandColumn = detailEl.getAttribute('show-expand-column');\n const expandOnRowClick = detailEl.getAttribute('expand-on-row-click');\n const collapseOnClickOutside = detailEl.getAttribute('collapse-on-click-outside');\n const heightAttr = detailEl.getAttribute('height');\n\n const configUpdates: Partial<MasterDetailConfig> = {};\n\n if (animation !== null) {\n configUpdates.animation = animation === 'false' ? false : (animation as 'slide' | 'fade');\n }\n if (showExpandColumn !== null) {\n configUpdates.showExpandColumn = showExpandColumn !== 'false';\n }\n if (expandOnRowClick !== null) {\n configUpdates.expandOnRowClick = expandOnRowClick === 'true';\n }\n if (collapseOnClickOutside !== null) {\n configUpdates.collapseOnClickOutside = collapseOnClickOutside === 'true';\n }\n if (heightAttr !== null) {\n configUpdates.detailHeight = heightAttr === 'auto' ? 'auto' : parseInt(heightAttr, 10);\n }\n\n // Get template content from innerHTML\n const templateHTML = detailEl.innerHTML.trim();\n if (templateHTML && !this.config.detailRenderer) {\n // Create a template-based renderer using the inner HTML\n configUpdates.detailRenderer = (row: any, _rowIndex: number): string => {\n // Evaluate template expressions like {{ row.field }}\n const evaluated = evalTemplateString(templateHTML, { value: row, row });\n // Sanitize the result to prevent XSS\n return sanitizeHTML(evaluated);\n };\n }\n\n // Merge updates into config\n if (Object.keys(configUpdates).length > 0) {\n this.config = { ...this.config, ...configUpdates };\n }\n }\n\n // #endregion\n\n // #region Animation Helpers\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 /**\n * Apply expand animation to a detail element.\n * Returns true if animation was applied, false if skipped.\n * When animated, height measurement is deferred to animationend to avoid\n * measuring during the max-height: 0 CSS animation constraint.\n */\n private animateExpand(detailEl: HTMLElement, row?: any, rowIndex?: number): boolean {\n if (!this.isAnimationEnabled || this.animationStyle === false) return false;\n\n detailEl.classList.add('tbw-expanding');\n\n let measured = false;\n const measureOnce = () => {\n if (measured) return;\n measured = true;\n detailEl.classList.remove('tbw-expanding');\n\n // Measure height AFTER animation completes - the element now has its\n // natural height without the max-height constraint from the animation.\n if (row !== undefined && rowIndex !== undefined) {\n this.#measureAndCacheDetailHeight(detailEl, row, rowIndex);\n }\n };\n\n detailEl.addEventListener('animationend', measureOnce, { once: true });\n // Fallback timeout in case animationend doesn't fire (e.g., element detached,\n // animation removed, or framework rendering delays). Matches animateCollapse pattern.\n setTimeout(measureOnce, this.animationDuration + 50);\n return true;\n }\n\n /**\n * Apply collapse animation to a detail element and remove after animation.\n */\n private animateCollapse(detailEl: HTMLElement, onComplete: () => void): void {\n if (!this.isAnimationEnabled || this.animationStyle === false) {\n onComplete();\n return;\n }\n\n detailEl.classList.add('tbw-collapsing');\n const cleanup = () => {\n detailEl.classList.remove('tbw-collapsing');\n onComplete();\n };\n detailEl.addEventListener('animationend', cleanup, { once: true });\n // Fallback timeout in case animation doesn't fire\n setTimeout(cleanup, this.animationDuration + 50);\n }\n\n /**\n * Measure a detail element's height and update the position cache if it changed.\n * Used after layout settles (RAF) or after animation completes (animationend).\n */\n #measureAndCacheDetailHeight(detailEl: HTMLElement, row: any, rowIndex: number): void {\n if (!detailEl.isConnected) return;\n\n const height = detailEl.offsetHeight;\n if (height > 0) {\n const previousHeight = this.measuredDetailHeights.get(row);\n this.measuredDetailHeights.set(row, height);\n\n // Only invalidate if height actually changed\n // This triggers an incremental position cache update, not a full rebuild\n if (previousHeight !== height) {\n this.grid.invalidateRowHeight(rowIndex);\n }\n }\n }\n\n // #endregion\n\n // #region Internal State\n private expandedRows: Set<any> = new Set();\n private detailElements: Map<any, HTMLElement> = new Map();\n /** Cached measured heights - persists even when elements are virtualized out */\n private measuredDetailHeights: Map<any, number> = new Map();\n /** Rows that were just expanded by user action and should animate.\n * Prevents re-animation when rows scroll back into the virtual window. */\n private rowsToAnimate: Set<any> = new Set();\n\n /** Default height for detail rows when not configured */\n private static readonly DEFAULT_DETAIL_HEIGHT = 150;\n\n /**\n * Get the estimated height for a detail row.\n * Uses cached measured height when available (survives virtualization).\n * Avoids reading offsetHeight during CSS animations to prevent poisoning the cache.\n */\n private getDetailHeight(row: any): number {\n // Try DOM element first - works for tests and when element is connected\n const detailEl = this.detailElements.get(row);\n if (detailEl) {\n // Skip DOM measurement if currently animating (max-height constraint gives wrong value)\n const isAnimating = detailEl.classList.contains('tbw-expanding') || detailEl.classList.contains('tbw-collapsing');\n if (!isAnimating) {\n const height = detailEl.offsetHeight;\n if (height > 0) {\n // Cache the measurement for when this row is virtualized out\n this.measuredDetailHeights.set(row, height);\n return height;\n }\n }\n }\n\n // DOM element missing, detached, or animating - check cached measurement\n const cachedHeight = this.measuredDetailHeights.get(row);\n if (cachedHeight && cachedHeight > 0) {\n return cachedHeight;\n }\n\n // Fallback to config or default\n return typeof this.config?.detailHeight === 'number'\n ? this.config.detailHeight\n : MasterDetailPlugin.DEFAULT_DETAIL_HEIGHT;\n }\n\n /**\n * Toggle a row's detail and emit event.\n */\n private toggleAndEmit(row: any, rowIndex: number): void {\n this.expandedRows = toggleDetailRow(this.expandedRows, row as object);\n const expanded = this.expandedRows.has(row as object);\n if (expanded) {\n this.rowsToAnimate.add(row);\n }\n this.emit<DetailExpandDetail>('detail-expand', {\n rowIndex,\n row: row as Record<string, unknown>,\n expanded,\n });\n this.requestRender();\n }\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override detach(): void {\n this.expandedRows.clear();\n this.detailElements.clear();\n this.measuredDetailHeights.clear();\n this.rowsToAnimate.clear();\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n // Determine whether to add the expander column:\n // 1. If showExpandColumn === false: never add (explicit opt-out)\n // 2. If showExpandColumn === true: always add (explicit opt-in, for framework adapters)\n // 3. If showExpandColumn is undefined: add only if detailRenderer is provided\n //\n // This supports React/Angular adapters which register renderers asynchronously via light DOM.\n // They must set showExpandColumn: true to get the column immediately, avoiding layout shift.\n const shouldAddExpander =\n this.config.showExpandColumn === true || (this.config.showExpandColumn !== false && !!this.config.detailRenderer);\n\n if (!shouldAddExpander) {\n return [...columns];\n }\n\n const cols = [...columns];\n\n // Check if expander column already exists (from this or another plugin)\n const existingExpander = findExpanderColumn(cols);\n if (existingExpander) {\n // Another plugin already added an expander column - don't add duplicate\n // Our expand logic will be handled via onCellClick on the expander column\n return cols;\n }\n\n // Create dedicated expander column that stays fixed at position 0\n const expanderCol = createExpanderColumnConfig(this.name);\n expanderCol.viewRenderer = (renderCtx) => {\n const { row } = renderCtx;\n const isExpanded = this.expandedRows.has(row as object);\n\n const container = document.createElement('span');\n container.className = 'master-detail-expander expander-cell';\n\n // Expand/collapse toggle icon\n const toggle = document.createElement('span');\n toggle.className = `master-detail-toggle${isExpanded ? ' expanded' : ''}`;\n // Use grid-level icons (fall back to defaults)\n this.setIcon(toggle, this.resolveIcon(isExpanded ? 'collapse' : 'expand'));\n // role=\"button\" is required for aria-expanded to be valid\n toggle.setAttribute('role', 'button');\n toggle.setAttribute('tabindex', '0');\n toggle.setAttribute('aria-expanded', String(isExpanded));\n toggle.setAttribute('aria-label', isExpanded ? 'Collapse details' : 'Expand details');\n container.appendChild(toggle);\n\n return container;\n };\n\n // Prepend expander column to ensure it's always first\n return [expanderCol, ...cols];\n }\n\n /** @internal */\n override onRowClick(event: RowClickEvent): boolean | void {\n if (!this.config.expandOnRowClick || !this.config.detailRenderer) return;\n this.toggleAndEmit(event.row, event.rowIndex);\n return false;\n }\n\n /** @internal */\n override onCellClick(event: CellClickEvent): boolean | void {\n // Handle click on master-detail toggle icon (same pattern as TreePlugin)\n const target = event.originalEvent?.target as HTMLElement;\n if (target?.classList.contains('master-detail-toggle')) {\n this.toggleAndEmit(event.row, event.rowIndex);\n return true; // Prevent default handling\n }\n\n // Sync detail rows after cell click triggers refreshVirtualWindow\n // This runs in microtask to ensure DOM updates are complete\n if (this.expandedRows.size > 0) {\n queueMicrotask(() => this.#syncDetailRows());\n }\n return; // Don't prevent default\n }\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n // SPACE toggles expansion when focus is on the expander column\n if (event.key !== ' ') return;\n\n const focusCol = this.grid._focusCol;\n const focusRow = this.grid._focusRow;\n const column = this.columns[focusCol];\n\n // Only handle SPACE on expander column\n if (!column || !isExpanderColumn(column)) return;\n\n const row = this.rows[focusRow];\n if (!row) return;\n\n event.preventDefault();\n this.toggleAndEmit(row, focusRow);\n\n // Restore focus styling after render completes via render pipeline\n this.requestRenderWithFocus();\n return true;\n }\n\n /** @internal */\n override afterRender(): void {\n this.#syncDetailRows();\n }\n\n /**\n * Called on scroll to sync detail elements with visible rows.\n * Removes details for rows that scrolled out of view and reattaches for visible rows.\n * @internal\n */\n override onScrollRender(): void {\n if (!this.config.detailRenderer || this.expandedRows.size === 0) return;\n // Full sync needed on scroll to clean up orphaned details\n this.#syncDetailRows();\n }\n\n /**\n * Full sync of detail rows - cleans up stale elements and creates new ones.\n * Detail rows are inserted as siblings AFTER their master row to survive row rebuilds.\n *\n * PERF: Uses the grid's row pool (_rowPool) and virtual window (_virtualization.start/end)\n * to avoid querySelectorAll on every scroll frame. The pool is index-aligned with the\n * virtual window, so pool[i] corresponds to row index (start + i).\n */\n #syncDetailRows(): void {\n if (!this.config.detailRenderer) return;\n\n const body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n // Use grid's virtualization state and row pool for O(1) lookups instead of querySelectorAll.\n // The row pool is an array of DOM elements aligned to the virtual window:\n // _rowPool[i] renders row data at index (_virtualization.start + i).\n const gridInternal = this.grid as any;\n const rowPool: HTMLElement[] | undefined = gridInternal._rowPool;\n const vStart: number = gridInternal._virtualization?.start ?? 0;\n const vEnd: number = gridInternal._virtualization?.end ?? 0;\n const columnCount = this.columns.length;\n\n // Build visible row index set from the virtual window range\n const visibleStart = vStart;\n const visibleEnd = vEnd;\n\n // Build a map of row index -> row element using the pool (O(n) where n = visible rows)\n const visibleRowMap = new Map<number, Element>();\n if (rowPool) {\n const poolLen = Math.min(rowPool.length, visibleEnd - visibleStart);\n for (let i = 0; i < poolLen; i++) {\n const rowEl = rowPool[i];\n if (rowEl.parentNode === body) {\n visibleRowMap.set(visibleStart + i, rowEl);\n }\n }\n } else {\n // Fallback: use querySelectorAll if pool is not accessible\n const dataRows = body.querySelectorAll('.data-grid-row');\n for (const rowEl of dataRows) {\n const firstCell = rowEl.querySelector('.cell[data-row]');\n const rowIndex = firstCell ? parseInt(firstCell.getAttribute('data-row') ?? '-1', 10) : -1;\n if (rowIndex >= 0) {\n visibleRowMap.set(rowIndex, rowEl);\n }\n }\n }\n\n // Remove detail rows whose parent row is no longer visible or no longer expanded.\n // Iterate the detailElements map (which we own) instead of querySelectorAll.\n for (const [row, detailEl] of this.detailElements) {\n const rowIndex = this.rows.indexOf(row);\n const isStillExpanded = this.expandedRows.has(row);\n const isRowVisible = rowIndex >= 0 && visibleRowMap.has(rowIndex);\n\n if (!isStillExpanded || !isRowVisible) {\n if (detailEl.parentNode) detailEl.remove();\n this.detailElements.delete(row);\n }\n }\n\n // Insert detail rows for expanded rows that are visible\n for (const [rowIndex, rowEl] of visibleRowMap) {\n const row = this.rows[rowIndex];\n if (!row || !this.expandedRows.has(row)) continue;\n\n // Check if detail already exists for this row\n const existingDetail = this.detailElements.get(row);\n if (existingDetail) {\n // Ensure it's positioned correctly (as next sibling of row element)\n if (existingDetail.previousElementSibling !== rowEl) {\n rowEl.after(existingDetail);\n }\n continue;\n }\n\n // Create new detail element\n const detailEl = createDetailElement(row, rowIndex, this.config.detailRenderer, columnCount);\n\n if (typeof this.config.detailHeight === 'number') {\n detailEl.style.height = `${this.config.detailHeight}px`;\n }\n\n // Insert as sibling after the row element (not as child)\n rowEl.after(detailEl);\n this.detailElements.set(row, detailEl);\n\n // Only animate if this row was just expanded by a user action (click, keyboard, API).\n // Rows re-appearing from scroll (virtualization) should not re-animate.\n const shouldAnimate = this.rowsToAnimate.has(row);\n if (shouldAnimate) {\n this.rowsToAnimate.delete(row);\n }\n\n const willAnimate = shouldAnimate && this.animateExpand(detailEl, row, rowIndex);\n\n if (!willAnimate) {\n // No animation - measure height after layout settles via RAF\n requestAnimationFrame(() => {\n this.#measureAndCacheDetailHeight(detailEl, row, rowIndex);\n });\n }\n // When animating, measurement is deferred to animationend callback\n // (inside animateExpand) to avoid measuring during max-height: 0 constraint\n }\n }\n\n /**\n * Return total extra height from all expanded detail rows.\n * Used by grid virtualization to adjust scrollbar height.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v3.0.\n */\n override getExtraHeight(): number {\n let totalHeight = 0;\n for (const row of this.expandedRows) {\n totalHeight += this.getDetailHeight(row);\n }\n return totalHeight;\n }\n\n /**\n * Return extra height that appears before a given row index.\n * This is the sum of heights of all expanded details whose parent row is before the given index.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v3.0.\n */\n override getExtraHeightBefore(beforeRowIndex: number): number {\n let totalHeight = 0;\n for (const row of this.expandedRows) {\n const rowIndex = this.rows.indexOf(row);\n // Include detail if it's for a row before the given index\n if (rowIndex >= 0 && rowIndex < beforeRowIndex) {\n totalHeight += this.getDetailHeight(row);\n }\n }\n return totalHeight;\n }\n\n /**\n * Get the height of a specific row, including any expanded detail content.\n * Always returns a height to ensure the position cache uses plugin-controlled values\n * rather than stale DOM measurements.\n *\n * @param row - The row data\n * @param _index - The row index (unused, but part of the interface)\n * @returns The row height in pixels (base height for collapsed, base + detail for expanded)\n */\n override getRowHeight(row: unknown, _index: number): number | undefined {\n const isExpanded = this.expandedRows.has(row as object);\n\n if (!isExpanded) {\n // Collapsed row - return undefined to let the grid use its measured/estimated height.\n // This ensures the position cache uses the correct row height from CSS/config.\n return undefined;\n }\n\n // Row is expanded - return base height plus detail height\n // Use grid's defaultRowHeight which reflects the actual measured/configured height\n const baseHeight = this.grid.defaultRowHeight ?? 28;\n const detailHeight = this.getDetailHeight(row);\n\n return baseHeight + detailHeight;\n }\n\n /**\n * Adjust the virtualization start index to keep expanded row visible while its detail is visible.\n * This ensures the detail scrolls smoothly out of view instead of disappearing abruptly.\n */\n override adjustVirtualStart(start: number, scrollTop: number, rowHeight: number): number {\n if (this.expandedRows.size === 0) return start;\n\n // Use position cache for accurate row positions when available (variable heights mode)\n const positionCache = (this.grid as any)?._virtualization?.positionCache as\n | Array<{ offset: number; height: number }>\n | undefined;\n\n let minStart = start;\n\n if (positionCache && positionCache.length > 0) {\n // Variable heights: use position cache for accurate offset\n for (const row of this.expandedRows) {\n const rowIndex = this.rows.indexOf(row);\n if (rowIndex < 0 || rowIndex >= start) continue;\n\n // Position cache already includes cumulative heights from all expanded details\n const detailBottom = positionCache[rowIndex].offset + positionCache[rowIndex].height;\n\n if (detailBottom > scrollTop && rowIndex < minStart) {\n minStart = rowIndex;\n }\n }\n } else {\n // Fixed heights fallback: accumulate detail heights manually\n // Build sorted list of expanded row indices for cumulative height calculation\n const expandedIndices: Array<{ index: number; row: any }> = [];\n for (const row of this.expandedRows) {\n const index = this.rows.indexOf(row);\n if (index >= 0) {\n expandedIndices.push({ index, row });\n }\n }\n expandedIndices.sort((a, b) => a.index - b.index);\n\n let cumulativeExtraHeight = 0;\n\n for (const { index: rowIndex, row } of expandedIndices) {\n const actualRowTop = rowIndex * rowHeight + cumulativeExtraHeight;\n const detailHeight = this.getDetailHeight(row);\n const actualDetailBottom = actualRowTop + rowHeight + detailHeight;\n\n cumulativeExtraHeight += detailHeight;\n\n if (rowIndex >= start) continue;\n\n if (actualDetailBottom > scrollTop && rowIndex < minStart) {\n minStart = rowIndex;\n }\n }\n }\n\n return minStart;\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Expand the detail row at the given index.\n * @param rowIndex - Index of the row to expand\n */\n expand(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.rowsToAnimate.add(row);\n this.expandedRows = expandDetailRow(this.expandedRows, row);\n this.requestRender();\n }\n }\n\n /**\n * Collapse the detail row at the given index.\n * @param rowIndex - Index of the row to collapse\n */\n collapse(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.expandedRows = collapseDetailRow(this.expandedRows, row);\n this.requestRender();\n }\n }\n\n /**\n * Toggle the detail row at the given index.\n * @param rowIndex - Index of the row to toggle\n */\n toggle(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.expandedRows = toggleDetailRow(this.expandedRows, row);\n if (this.expandedRows.has(row)) {\n this.rowsToAnimate.add(row);\n }\n this.requestRender();\n }\n }\n\n /**\n * Check if the detail row at the given index is expanded.\n * @param rowIndex - Index of the row to check\n * @returns Whether the detail row is expanded\n */\n isExpanded(rowIndex: number): boolean {\n const row = this.rows[rowIndex];\n return row ? isDetailExpanded(this.expandedRows, row) : false;\n }\n\n /**\n * Expand all detail rows.\n */\n expandAll(): void {\n for (const row of this.rows) {\n this.rowsToAnimate.add(row);\n this.expandedRows.add(row);\n }\n this.requestRender();\n }\n\n /**\n * Collapse all detail rows.\n */\n collapseAll(): void {\n this.expandedRows.clear();\n this.requestRender();\n }\n\n /**\n * Get the indices of all expanded rows.\n * @returns Array of row indices that are expanded\n */\n getExpandedRows(): number[] {\n const indices: number[] = [];\n for (const row of this.expandedRows) {\n const idx = this.rows.indexOf(row);\n if (idx >= 0) indices.push(idx);\n }\n return indices;\n }\n\n /**\n * Get the detail element for a specific row.\n * @param rowIndex - Index of the row\n * @returns The detail HTMLElement or undefined\n */\n getDetailElement(rowIndex: number): HTMLElement | undefined {\n const row = this.rows[rowIndex];\n return row ? this.detailElements.get(row) : undefined;\n }\n\n /**\n * Re-parse light DOM to refresh the detail renderer.\n * Call this after framework templates are registered (e.g., Angular ngAfterContentInit).\n *\n * This allows frameworks to register templates asynchronously and then\n * update the plugin's detailRenderer.\n */\n refreshDetailRenderer(): void {\n // Force re-parse by temporarily clearing the renderer\n const currentRenderer = this.config.detailRenderer;\n this.config = { ...this.config, detailRenderer: undefined };\n this.parseLightDomDetail();\n\n // If no new renderer was found, restore the original\n if (!this.config.detailRenderer && currentRenderer) {\n this.config = { ...this.config, detailRenderer: currentRenderer };\n }\n\n // Request a COLUMNS phase re-render so processColumns runs again with the new detailRenderer\n // This ensures the expand toggle is added to the first column.\n // Must use refreshColumns() (COLUMNS phase) not requestRender() (ROWS phase)\n // because processColumns only runs at COLUMNS phase or higher.\n if (this.config.detailRenderer) {\n const grid = this.grid as unknown as { refreshColumns?: () => void };\n if (typeof grid.refreshColumns === 'function') {\n grid.refreshColumns();\n } else {\n // Fallback to requestRender if refreshColumns not available\n this.requestRender();\n }\n }\n }\n // #endregion\n}\n"],"names":["toggleDetailRow","expandedRows","row","newExpanded","expandDetailRow","collapseDetailRow","isDetailExpanded","createDetailElement","rowIndex","renderer","columnCount","detailRow","detailCell","content","MasterDetailPlugin","BaseGridPlugin","styles","grid","gridEl","detailEl","gridWithAdapter","adapterRenderer","animation","showExpandColumn","expandOnRowClick","collapseOnClickOutside","heightAttr","configUpdates","templateHTML","_rowIndex","evaluated","evalTemplateString","sanitizeHTML","measured","measureOnce","#measureAndCacheDetailHeight","onComplete","cleanup","height","previousHeight","cachedHeight","expanded","columns","cols","findExpanderColumn","expanderCol","createExpanderColumnConfig","renderCtx","isExpanded","container","toggle","event","#syncDetailRows","focusCol","focusRow","column","isExpanderColumn","body","gridInternal","rowPool","vStart","vEnd","visibleStart","visibleEnd","visibleRowMap","poolLen","i","rowEl","dataRows","firstCell","isStillExpanded","isRowVisible","existingDetail","shouldAnimate","totalHeight","beforeRowIndex","_index","baseHeight","detailHeight","start","scrollTop","rowHeight","positionCache","minStart","expandedIndices","index","a","b","cumulativeExtraHeight","actualRowTop","actualDetailBottom","indices","idx","currentRenderer"],"mappings":"wfAaO,SAASA,EAAgBC,EAA2BC,EAA0B,CACnF,MAAMC,EAAc,IAAI,IAAIF,CAAY,EACxC,OAAIE,EAAY,IAAID,CAAG,EACrBC,EAAY,OAAOD,CAAG,EAEtBC,EAAY,IAAID,CAAG,EAEdC,CACT,CAMO,SAASC,EAAgBH,EAA2BC,EAA0B,CACnF,MAAMC,EAAc,IAAI,IAAIF,CAAY,EACxC,OAAAE,EAAY,IAAID,CAAG,EACZC,CACT,CAMO,SAASE,EAAkBJ,EAA2BC,EAA0B,CACrF,MAAMC,EAAc,IAAI,IAAIF,CAAY,EACxC,OAAAE,EAAY,OAAOD,CAAG,EACfC,CACT,CAKO,SAASG,EAAiBL,EAA2BC,EAAsB,CAChF,OAAOD,EAAa,IAAIC,CAAG,CAC7B,CAMO,SAASK,EACdL,EACAM,EACAC,EACAC,EACa,CACb,MAAMC,EAAY,SAAS,cAAc,KAAK,EAC9CA,EAAU,UAAY,oBACtBA,EAAU,aAAa,kBAAmB,OAAOH,CAAQ,CAAC,EAC1DG,EAAU,aAAa,OAAQ,KAAK,EAEpC,MAAMC,EAAa,SAAS,cAAc,KAAK,EAC/CA,EAAW,UAAY,qBACvBA,EAAW,aAAa,OAAQ,MAAM,EACtCA,EAAW,MAAM,WAAa,OAAOF,EAAc,CAAC,GAEpD,MAAMG,EAAUJ,EAASP,EAAKM,CAAQ,EACtC,OAAI,OAAOK,GAAY,SACrBD,EAAW,UAAYC,EACdA,aAAmB,aAC5BD,EAAW,YAAYC,CAAO,EAGhCF,EAAU,YAAYC,CAAU,EACzBD,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L,KAAK,cAAA,CAET,CACF,CAEF"}
|
|
1
|
+
{"version":3,"file":"master-detail.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/master-detail/master-detail.ts","../../../../../libs/grid/src/lib/plugins/master-detail/MasterDetailPlugin.ts"],"sourcesContent":["/**\n * Master/Detail Core Logic\n *\n * Pure functions for managing detail row expansion state.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n// Uses `any` for maximum flexibility with user-defined row types.\n\n/**\n * Toggle the expansion state of a detail row.\n * Returns a new Set with the updated state.\n */\nexport function toggleDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n if (newExpanded.has(row)) {\n newExpanded.delete(row);\n } else {\n newExpanded.add(row);\n }\n return newExpanded;\n}\n\n/**\n * Expand a detail row.\n * Returns a new Set with the row added.\n */\nexport function expandDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n newExpanded.add(row);\n return newExpanded;\n}\n\n/**\n * Collapse a detail row.\n * Returns a new Set with the row removed.\n */\nexport function collapseDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n newExpanded.delete(row);\n return newExpanded;\n}\n\n/**\n * Check if a detail row is expanded.\n */\nexport function isDetailExpanded(expandedRows: Set<object>, row: object): boolean {\n return expandedRows.has(row);\n}\n\n/**\n * Create a detail element for a given row.\n * The element spans all columns and contains the rendered content.\n */\nexport function createDetailElement(\n row: any,\n rowIndex: number,\n renderer: (row: any, rowIndex: number) => HTMLElement | string,\n columnCount: number\n): HTMLElement {\n const detailRow = document.createElement('div');\n detailRow.className = 'master-detail-row';\n detailRow.setAttribute('data-detail-for', String(rowIndex));\n detailRow.setAttribute('role', 'row');\n\n const detailCell = document.createElement('div');\n detailCell.className = 'master-detail-cell';\n detailCell.setAttribute('role', 'cell');\n detailCell.style.gridColumn = `1 / ${columnCount + 1}`;\n\n const content = renderer(row, rowIndex);\n if (typeof content === 'string') {\n detailCell.innerHTML = content;\n } else if (content instanceof HTMLElement) {\n detailCell.appendChild(content);\n }\n\n detailRow.appendChild(detailCell);\n return detailRow;\n}\n","/**\n * Master/Detail Plugin (Class-based)\n *\n * Enables expandable detail rows showing additional content for each row.\n * Animation style is plugin-configured; respects grid-level animation.mode.\n */\n\nimport { evalTemplateString, sanitizeHTML } from '../../core/internal/sanitize';\nimport { BaseGridPlugin, CellClickEvent, GridElement, RowClickEvent } from '../../core/plugin/base-plugin';\nimport { createExpanderColumnConfig, findExpanderColumn, isExpanderColumn } from '../../core/plugin/expander-column';\nimport type { ColumnConfig } from '../../core/types';\nimport {\n collapseDetailRow,\n createDetailElement,\n expandDetailRow,\n isDetailExpanded,\n toggleDetailRow,\n} from './master-detail';\nimport styles from './master-detail.css?inline';\nimport type { DetailExpandDetail, ExpandCollapseAnimation, MasterDetailConfig } from './types';\n\n/**\n * Master-Detail Plugin for tbw-grid\n *\n * Creates expandable detail rows that reveal additional content beneath each master row.\n * Perfect for order/line-item UIs, employee/department views, or any scenario where\n * you need to show related data without navigating away.\n *\n * ## Installation\n *\n * ```ts\n * import { MasterDetailPlugin } from '@toolbox-web/grid/plugins/master-detail';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `detailRenderer` | `(row) => HTMLElement \\| string` | required | Render function for detail content |\n * | `expandOnRowClick` | `boolean` | `false` | Expand when clicking the row |\n * | `detailHeight` | `number \\| 'auto'` | `'auto'` | Fixed height or auto-size |\n * | `collapseOnClickOutside` | `boolean` | `false` | Collapse when clicking outside |\n * | `showExpandColumn` | `boolean` | `true` | Show expand/collapse column |\n * | `animation` | `false \\| 'slide' \\| 'fade'` | `'slide'` | Animation style |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `expandRow` | `(rowIndex) => void` | Expand a specific row |\n * | `collapseRow` | `(rowIndex) => void` | Collapse a specific row |\n * | `toggleRow` | `(rowIndex) => void` | Toggle row expansion |\n * | `expandAll` | `() => void` | Expand all rows |\n * | `collapseAll` | `() => void` | Collapse all rows |\n * | `isRowExpanded` | `(rowIndex) => boolean` | Check if row is expanded |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-master-detail-bg` | `var(--tbw-color-row-alt)` | Detail row background |\n * | `--tbw-master-detail-border` | `var(--tbw-color-border)` | Detail row border |\n * | `--tbw-detail-padding` | `1em` | Detail content padding |\n * | `--tbw-animation-duration` | `200ms` | Expand/collapse animation |\n *\n * @example Basic Master-Detail with HTML Template\n * ```ts\n * import '@toolbox-web/grid';\n * import { MasterDetailPlugin } from '@toolbox-web/grid/plugins/master-detail';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'orderId', header: 'Order ID' },\n * { field: 'customer', header: 'Customer' },\n * { field: 'total', header: 'Total', type: 'currency' },\n * ],\n * plugins: [\n * new MasterDetailPlugin({\n * detailRenderer: (row) => `\n * <div class=\"order-details\">\n * <h4>Order Items</h4>\n * <ul>${row.items.map(i => `<li>${i.name} - $${i.price}</li>`).join('')}</ul>\n * </div>\n * `,\n * }),\n * ],\n * };\n * ```\n *\n * @example Nested Grid in Detail\n * ```ts\n * new MasterDetailPlugin({\n * detailRenderer: (row) => {\n * const childGrid = document.createElement('tbw-grid');\n * childGrid.style.height = '200px';\n * childGrid.gridConfig = { columns: [...] };\n * childGrid.rows = row.items || [];\n * return childGrid;\n * },\n * })\n * ```\n *\n * @see {@link MasterDetailConfig} for all configuration options\n * @see {@link DetailExpandDetail} for expand/collapse event details\n *\n * @internal Extends BaseGridPlugin\n */\nexport class MasterDetailPlugin extends BaseGridPlugin<MasterDetailConfig> {\n /** @internal */\n readonly name = 'masterDetail';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<MasterDetailConfig> {\n return {\n detailHeight: 'auto',\n expandOnRowClick: false,\n collapseOnClickOutside: false,\n // Note: showExpandColumn is intentionally NOT defaulted here.\n // If undefined, processColumns() adds expander only when detailRenderer is provided.\n // Set to true for framework adapters that register renderers asynchronously.\n animation: 'slide', // Plugin's own default\n };\n }\n\n // #region Light DOM Parsing\n\n /**\n * Called when plugin is attached to the grid.\n * Parses light DOM for `<tbw-grid-detail>` elements to configure detail templates.\n * @internal\n */\n override attach(grid: GridElement): void {\n super.attach(grid);\n this.parseLightDomDetail();\n }\n\n /**\n * Parse `<tbw-grid-detail>` elements from the grid's light DOM.\n *\n * Allows declarative configuration:\n * ```html\n * <tbw-grid [rows]=\"data\">\n * <tbw-grid-detail>\n * <div class=\"detail-content\">\n * <p>Name: {{ row.name }}</p>\n * <p>Email: {{ row.email }}</p>\n * </div>\n * </tbw-grid-detail>\n * </tbw-grid>\n * ```\n *\n * Attributes:\n * - `animation`: 'slide' | 'fade' | 'false' (default: 'slide')\n * - `show-expand-column`: 'true' | 'false' (default: 'true')\n * - `expand-on-row-click`: 'true' | 'false' (default: 'false')\n * - `collapse-on-click-outside`: 'true' | 'false' (default: 'false')\n * - `height`: number (pixels) or 'auto' (default: 'auto')\n */\n private parseLightDomDetail(): void {\n const gridEl = this.grid as unknown as Element;\n if (!gridEl || typeof gridEl.querySelector !== 'function') return;\n\n const detailEl = gridEl.querySelector('tbw-grid-detail');\n if (!detailEl) return;\n\n // Check if a framework adapter wants to handle this element\n // (e.g., Angular adapter intercepts for ng-template rendering)\n const gridWithAdapter = gridEl as unknown as {\n __frameworkAdapter?: {\n parseDetailElement?: (el: Element) => ((row: any, rowIndex: number) => HTMLElement | string) | undefined;\n };\n };\n if (gridWithAdapter.__frameworkAdapter?.parseDetailElement) {\n const adapterRenderer = gridWithAdapter.__frameworkAdapter.parseDetailElement(detailEl);\n if (adapterRenderer) {\n this.config = { ...this.config, detailRenderer: adapterRenderer };\n return;\n }\n }\n\n // Parse attributes for configuration\n const animation = detailEl.getAttribute('animation');\n const showExpandColumn = detailEl.getAttribute('show-expand-column');\n const expandOnRowClick = detailEl.getAttribute('expand-on-row-click');\n const collapseOnClickOutside = detailEl.getAttribute('collapse-on-click-outside');\n const heightAttr = detailEl.getAttribute('height');\n\n const configUpdates: Partial<MasterDetailConfig> = {};\n\n if (animation !== null) {\n configUpdates.animation = animation === 'false' ? false : (animation as 'slide' | 'fade');\n }\n if (showExpandColumn !== null) {\n configUpdates.showExpandColumn = showExpandColumn !== 'false';\n }\n if (expandOnRowClick !== null) {\n configUpdates.expandOnRowClick = expandOnRowClick === 'true';\n }\n if (collapseOnClickOutside !== null) {\n configUpdates.collapseOnClickOutside = collapseOnClickOutside === 'true';\n }\n if (heightAttr !== null) {\n configUpdates.detailHeight = heightAttr === 'auto' ? 'auto' : parseInt(heightAttr, 10);\n }\n\n // Get template content from innerHTML\n const templateHTML = detailEl.innerHTML.trim();\n if (templateHTML && !this.config.detailRenderer) {\n // Create a template-based renderer using the inner HTML\n configUpdates.detailRenderer = (row: any, _rowIndex: number): string => {\n // Evaluate template expressions like {{ row.field }}\n const evaluated = evalTemplateString(templateHTML, { value: row, row });\n // Sanitize the result to prevent XSS\n return sanitizeHTML(evaluated);\n };\n }\n\n // Merge updates into config\n if (Object.keys(configUpdates).length > 0) {\n this.config = { ...this.config, ...configUpdates };\n }\n }\n\n // #endregion\n\n // #region Animation Helpers\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 /**\n * Apply expand animation to a detail element.\n * Returns true if animation was applied, false if skipped.\n * When animated, height measurement is deferred to animationend to avoid\n * measuring during the max-height: 0 CSS animation constraint.\n */\n private animateExpand(detailEl: HTMLElement, row?: any, rowIndex?: number): boolean {\n if (!this.isAnimationEnabled || this.animationStyle === false) return false;\n\n detailEl.classList.add('tbw-expanding');\n\n let measured = false;\n const measureOnce = () => {\n if (measured) return;\n measured = true;\n detailEl.classList.remove('tbw-expanding');\n\n // Measure height AFTER animation completes - the element now has its\n // natural height without the max-height constraint from the animation.\n if (row !== undefined && rowIndex !== undefined) {\n this.#measureAndCacheDetailHeight(detailEl, row, rowIndex);\n }\n };\n\n detailEl.addEventListener('animationend', measureOnce, { once: true });\n // Fallback timeout in case animationend doesn't fire (e.g., element detached,\n // animation removed, or framework rendering delays). Matches animateCollapse pattern.\n setTimeout(measureOnce, this.animationDuration + 50);\n return true;\n }\n\n /**\n * Apply collapse animation to a detail element and remove after animation.\n */\n private animateCollapse(detailEl: HTMLElement, onComplete: () => void): void {\n if (!this.isAnimationEnabled || this.animationStyle === false) {\n onComplete();\n return;\n }\n\n detailEl.classList.add('tbw-collapsing');\n const cleanup = () => {\n detailEl.classList.remove('tbw-collapsing');\n onComplete();\n };\n detailEl.addEventListener('animationend', cleanup, { once: true });\n // Fallback timeout in case animation doesn't fire\n setTimeout(cleanup, this.animationDuration + 50);\n }\n\n /**\n * Measure a detail element's height and update the position cache if it changed.\n * Used after layout settles (RAF) or after animation completes (animationend).\n */\n #measureAndCacheDetailHeight(detailEl: HTMLElement, row: any, rowIndex: number): void {\n if (!detailEl.isConnected) return;\n\n const height = detailEl.offsetHeight;\n if (height > 0) {\n const previousHeight = this.measuredDetailHeights.get(row);\n this.measuredDetailHeights.set(row, height);\n\n // Only invalidate if height actually changed\n // This triggers an incremental position cache update, not a full rebuild\n if (previousHeight !== height) {\n this.grid.invalidateRowHeight(rowIndex);\n }\n }\n }\n\n // #endregion\n\n // #region Internal State\n private expandedRows: Set<any> = new Set();\n private detailElements: Map<any, HTMLElement> = new Map();\n /** Cached measured heights - persists even when elements are virtualized out */\n private measuredDetailHeights: Map<any, number> = new Map();\n /** Rows that were just expanded by user action and should animate.\n * Prevents re-animation when rows scroll back into the virtual window. */\n private rowsToAnimate: Set<any> = new Set();\n\n /** Default height for detail rows when not configured */\n private static readonly DEFAULT_DETAIL_HEIGHT = 150;\n\n /**\n * Get the estimated height for a detail row.\n * Uses cached measured height when available (survives virtualization).\n * Avoids reading offsetHeight during CSS animations to prevent poisoning the cache.\n */\n private getDetailHeight(row: any): number {\n // Try DOM element first - works for tests and when element is connected\n const detailEl = this.detailElements.get(row);\n if (detailEl) {\n // Skip DOM measurement if currently animating (max-height constraint gives wrong value)\n const isAnimating = detailEl.classList.contains('tbw-expanding') || detailEl.classList.contains('tbw-collapsing');\n if (!isAnimating) {\n const height = detailEl.offsetHeight;\n if (height > 0) {\n // Cache the measurement for when this row is virtualized out\n this.measuredDetailHeights.set(row, height);\n return height;\n }\n }\n }\n\n // DOM element missing, detached, or animating - check cached measurement\n const cachedHeight = this.measuredDetailHeights.get(row);\n if (cachedHeight && cachedHeight > 0) {\n return cachedHeight;\n }\n\n // Fallback to config or default\n return typeof this.config?.detailHeight === 'number'\n ? this.config.detailHeight\n : MasterDetailPlugin.DEFAULT_DETAIL_HEIGHT;\n }\n\n /**\n * Toggle a row's detail and emit event.\n */\n private toggleAndEmit(row: any, rowIndex: number): void {\n this.expandedRows = toggleDetailRow(this.expandedRows, row as object);\n const expanded = this.expandedRows.has(row as object);\n if (expanded) {\n this.rowsToAnimate.add(row);\n }\n this.emit<DetailExpandDetail>('detail-expand', {\n rowIndex,\n row: row as Record<string, unknown>,\n expanded,\n });\n this.requestRender();\n }\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override detach(): void {\n this.expandedRows.clear();\n this.detailElements.clear();\n this.measuredDetailHeights.clear();\n this.rowsToAnimate.clear();\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n // Determine whether to add the expander column:\n // 1. If showExpandColumn === false: never add (explicit opt-out)\n // 2. If showExpandColumn === true: always add (explicit opt-in, for framework adapters)\n // 3. If showExpandColumn is undefined: add only if detailRenderer is provided\n //\n // This supports React/Angular adapters which register renderers asynchronously via light DOM.\n // They must set showExpandColumn: true to get the column immediately, avoiding layout shift.\n const shouldAddExpander =\n this.config.showExpandColumn === true || (this.config.showExpandColumn !== false && !!this.config.detailRenderer);\n\n if (!shouldAddExpander) {\n return [...columns];\n }\n\n const cols = [...columns];\n\n // Check if expander column already exists (from this or another plugin)\n const existingExpander = findExpanderColumn(cols);\n if (existingExpander) {\n // Another plugin already added an expander column - don't add duplicate\n // Our expand logic will be handled via onCellClick on the expander column\n return cols;\n }\n\n // Create dedicated expander column that stays fixed at position 0\n const expanderCol = createExpanderColumnConfig(this.name);\n expanderCol.viewRenderer = (renderCtx) => {\n const { row } = renderCtx;\n const isExpanded = this.expandedRows.has(row as object);\n\n const container = document.createElement('span');\n container.className = 'master-detail-expander expander-cell';\n\n // Expand/collapse toggle icon\n const toggle = document.createElement('span');\n toggle.className = `master-detail-toggle${isExpanded ? ' expanded' : ''}`;\n // Use grid-level icons (fall back to defaults)\n this.setIcon(toggle, this.resolveIcon(isExpanded ? 'collapse' : 'expand'));\n // role=\"button\" is required for aria-expanded to be valid\n toggle.setAttribute('role', 'button');\n toggle.setAttribute('tabindex', '0');\n toggle.setAttribute('aria-expanded', String(isExpanded));\n toggle.setAttribute('aria-label', isExpanded ? 'Collapse details' : 'Expand details');\n container.appendChild(toggle);\n\n return container;\n };\n\n // Prepend expander column to ensure it's always first\n return [expanderCol, ...cols];\n }\n\n /** @internal */\n override onRowClick(event: RowClickEvent): boolean | void {\n if (!this.config.expandOnRowClick || !this.config.detailRenderer) return;\n this.toggleAndEmit(event.row, event.rowIndex);\n return false;\n }\n\n /** @internal */\n override onCellClick(event: CellClickEvent): boolean | void {\n // Handle click on master-detail toggle icon (same pattern as TreePlugin)\n const target = event.originalEvent?.target as HTMLElement;\n if (target?.classList.contains('master-detail-toggle')) {\n this.toggleAndEmit(event.row, event.rowIndex);\n return true; // Prevent default handling\n }\n\n // Sync detail rows after cell click triggers refreshVirtualWindow\n // This runs in microtask to ensure DOM updates are complete\n if (this.expandedRows.size > 0) {\n queueMicrotask(() => this.#syncDetailRows());\n }\n return; // Don't prevent default\n }\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n // SPACE toggles expansion when focus is on the expander column\n if (event.key !== ' ') return;\n\n const focusCol = this.grid._focusCol;\n const focusRow = this.grid._focusRow;\n const column = this.columns[focusCol];\n\n // Only handle SPACE on expander column\n if (!column || !isExpanderColumn(column)) return;\n\n const row = this.rows[focusRow];\n if (!row) return;\n\n event.preventDefault();\n this.toggleAndEmit(row, focusRow);\n\n // Restore focus styling after render completes via render pipeline\n this.requestRenderWithFocus();\n return true;\n }\n\n /** @internal */\n override afterRender(): void {\n this.#syncDetailRows();\n }\n\n /**\n * Called on scroll to sync detail elements with visible rows.\n * Removes details for rows that scrolled out of view and reattaches for visible rows.\n * @internal\n */\n override onScrollRender(): void {\n if (!this.config.detailRenderer || this.expandedRows.size === 0) return;\n // Full sync needed on scroll to clean up orphaned details\n this.#syncDetailRows();\n }\n\n /**\n * Full sync of detail rows - cleans up stale elements and creates new ones.\n * Detail rows are inserted as siblings AFTER their master row to survive row rebuilds.\n *\n * PERF: Uses the grid's row pool (_rowPool) and virtual window (_virtualization.start/end)\n * to avoid querySelectorAll on every scroll frame. The pool is index-aligned with the\n * virtual window, so pool[i] corresponds to row index (start + i).\n */\n #syncDetailRows(): void {\n if (!this.config.detailRenderer) return;\n\n const body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n // Use grid's virtualization state and row pool for O(1) lookups instead of querySelectorAll.\n // The row pool is an array of DOM elements aligned to the virtual window:\n // _rowPool[i] renders row data at index (_virtualization.start + i).\n const gridInternal = this.grid as any;\n const rowPool: HTMLElement[] | undefined = gridInternal._rowPool;\n const vStart: number = gridInternal._virtualization?.start ?? 0;\n const vEnd: number = gridInternal._virtualization?.end ?? 0;\n const columnCount = this.columns.length;\n\n // Build visible row index set from the virtual window range\n const visibleStart = vStart;\n const visibleEnd = vEnd;\n\n // Build a map of row index -> row element using the pool (O(n) where n = visible rows)\n const visibleRowMap = new Map<number, Element>();\n if (rowPool) {\n const poolLen = Math.min(rowPool.length, visibleEnd - visibleStart);\n for (let i = 0; i < poolLen; i++) {\n const rowEl = rowPool[i];\n if (rowEl.parentNode === body) {\n visibleRowMap.set(visibleStart + i, rowEl);\n }\n }\n } else {\n // Fallback: use querySelectorAll if pool is not accessible\n const dataRows = body.querySelectorAll('.data-grid-row');\n for (const rowEl of dataRows) {\n const firstCell = rowEl.querySelector('.cell[data-row]');\n const rowIndex = firstCell ? parseInt(firstCell.getAttribute('data-row') ?? '-1', 10) : -1;\n if (rowIndex >= 0) {\n visibleRowMap.set(rowIndex, rowEl);\n }\n }\n }\n\n // Remove detail rows whose parent row is no longer visible or no longer expanded.\n // Iterate the detailElements map (which we own) instead of querySelectorAll.\n for (const [row, detailEl] of this.detailElements) {\n const rowIndex = this.rows.indexOf(row);\n const isStillExpanded = this.expandedRows.has(row);\n const isRowVisible = rowIndex >= 0 && visibleRowMap.has(rowIndex);\n\n if (!isStillExpanded || !isRowVisible) {\n // Clean up framework adapter resources (React root, Vue app, Angular view)\n // before removing to prevent memory leaks.\n const adapter = (this.grid as unknown as { __frameworkAdapter?: { unmount?(c: HTMLElement): void } })\n .__frameworkAdapter;\n if (adapter?.unmount) {\n const detailCell = detailEl.querySelector('.master-detail-cell');\n const container = detailCell?.firstElementChild as HTMLElement | null;\n if (container) adapter.unmount(container);\n }\n if (detailEl.parentNode) detailEl.remove();\n this.detailElements.delete(row);\n }\n }\n\n // Insert detail rows for expanded rows that are visible\n for (const [rowIndex, rowEl] of visibleRowMap) {\n const row = this.rows[rowIndex];\n if (!row || !this.expandedRows.has(row)) continue;\n\n // Check if detail already exists for this row\n const existingDetail = this.detailElements.get(row);\n if (existingDetail) {\n // Ensure it's positioned correctly (as next sibling of row element)\n if (existingDetail.previousElementSibling !== rowEl) {\n rowEl.after(existingDetail);\n }\n continue;\n }\n\n // Create new detail element\n const detailEl = createDetailElement(row, rowIndex, this.config.detailRenderer, columnCount);\n\n if (typeof this.config.detailHeight === 'number') {\n detailEl.style.height = `${this.config.detailHeight}px`;\n }\n\n // Insert as sibling after the row element (not as child)\n rowEl.after(detailEl);\n this.detailElements.set(row, detailEl);\n\n // Only animate if this row was just expanded by a user action (click, keyboard, API).\n // Rows re-appearing from scroll (virtualization) should not re-animate.\n const shouldAnimate = this.rowsToAnimate.has(row);\n if (shouldAnimate) {\n this.rowsToAnimate.delete(row);\n }\n\n const willAnimate = shouldAnimate && this.animateExpand(detailEl, row, rowIndex);\n\n if (!willAnimate) {\n // No animation - measure height after layout settles via RAF\n requestAnimationFrame(() => {\n this.#measureAndCacheDetailHeight(detailEl, row, rowIndex);\n });\n }\n // When animating, measurement is deferred to animationend callback\n // (inside animateExpand) to avoid measuring during max-height: 0 constraint\n }\n }\n\n /**\n * Return total extra height from all expanded detail rows.\n * Used by grid virtualization to adjust scrollbar height.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v3.0.\n */\n override getExtraHeight(): number {\n let totalHeight = 0;\n for (const row of this.expandedRows) {\n totalHeight += this.getDetailHeight(row);\n }\n return totalHeight;\n }\n\n /**\n * Return extra height that appears before a given row index.\n * This is the sum of heights of all expanded details whose parent row is before the given index.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v3.0.\n */\n override getExtraHeightBefore(beforeRowIndex: number): number {\n let totalHeight = 0;\n for (const row of this.expandedRows) {\n const rowIndex = this.rows.indexOf(row);\n // Include detail if it's for a row before the given index\n if (rowIndex >= 0 && rowIndex < beforeRowIndex) {\n totalHeight += this.getDetailHeight(row);\n }\n }\n return totalHeight;\n }\n\n /**\n * Get the height of a specific row, including any expanded detail content.\n * Always returns a height to ensure the position cache uses plugin-controlled values\n * rather than stale DOM measurements.\n *\n * @param row - The row data\n * @param _index - The row index (unused, but part of the interface)\n * @returns The row height in pixels (base height for collapsed, base + detail for expanded)\n */\n override getRowHeight(row: unknown, _index: number): number | undefined {\n const isExpanded = this.expandedRows.has(row as object);\n\n if (!isExpanded) {\n // Collapsed row - return undefined to let the grid use its measured/estimated height.\n // This ensures the position cache uses the correct row height from CSS/config.\n return undefined;\n }\n\n // Row is expanded - return base height plus detail height\n // Use grid's defaultRowHeight which reflects the actual measured/configured height\n const baseHeight = this.grid.defaultRowHeight ?? 28;\n const detailHeight = this.getDetailHeight(row);\n\n return baseHeight + detailHeight;\n }\n\n /**\n * Adjust the virtualization start index to keep expanded row visible while its detail is visible.\n * This ensures the detail scrolls smoothly out of view instead of disappearing abruptly.\n */\n override adjustVirtualStart(start: number, scrollTop: number, rowHeight: number): number {\n if (this.expandedRows.size === 0) return start;\n\n // Use position cache for accurate row positions when available (variable heights mode)\n const positionCache = (this.grid as any)?._virtualization?.positionCache as\n | Array<{ offset: number; height: number }>\n | undefined;\n\n let minStart = start;\n\n if (positionCache && positionCache.length > 0) {\n // Variable heights: use position cache for accurate offset\n for (const row of this.expandedRows) {\n const rowIndex = this.rows.indexOf(row);\n if (rowIndex < 0 || rowIndex >= start) continue;\n\n // Position cache already includes cumulative heights from all expanded details\n const detailBottom = positionCache[rowIndex].offset + positionCache[rowIndex].height;\n\n if (detailBottom > scrollTop && rowIndex < minStart) {\n minStart = rowIndex;\n }\n }\n } else {\n // Fixed heights fallback: accumulate detail heights manually\n // Build sorted list of expanded row indices for cumulative height calculation\n const expandedIndices: Array<{ index: number; row: any }> = [];\n for (const row of this.expandedRows) {\n const index = this.rows.indexOf(row);\n if (index >= 0) {\n expandedIndices.push({ index, row });\n }\n }\n expandedIndices.sort((a, b) => a.index - b.index);\n\n let cumulativeExtraHeight = 0;\n\n for (const { index: rowIndex, row } of expandedIndices) {\n const actualRowTop = rowIndex * rowHeight + cumulativeExtraHeight;\n const detailHeight = this.getDetailHeight(row);\n const actualDetailBottom = actualRowTop + rowHeight + detailHeight;\n\n cumulativeExtraHeight += detailHeight;\n\n if (rowIndex >= start) continue;\n\n if (actualDetailBottom > scrollTop && rowIndex < minStart) {\n minStart = rowIndex;\n }\n }\n }\n\n return minStart;\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Expand the detail row at the given index.\n * @param rowIndex - Index of the row to expand\n */\n expand(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.rowsToAnimate.add(row);\n this.expandedRows = expandDetailRow(this.expandedRows, row);\n this.requestRender();\n }\n }\n\n /**\n * Collapse the detail row at the given index.\n * @param rowIndex - Index of the row to collapse\n */\n collapse(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.expandedRows = collapseDetailRow(this.expandedRows, row);\n this.requestRender();\n }\n }\n\n /**\n * Toggle the detail row at the given index.\n * @param rowIndex - Index of the row to toggle\n */\n toggle(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.expandedRows = toggleDetailRow(this.expandedRows, row);\n if (this.expandedRows.has(row)) {\n this.rowsToAnimate.add(row);\n }\n this.requestRender();\n }\n }\n\n /**\n * Check if the detail row at the given index is expanded.\n * @param rowIndex - Index of the row to check\n * @returns Whether the detail row is expanded\n */\n isExpanded(rowIndex: number): boolean {\n const row = this.rows[rowIndex];\n return row ? isDetailExpanded(this.expandedRows, row) : false;\n }\n\n /**\n * Expand all detail rows.\n */\n expandAll(): void {\n for (const row of this.rows) {\n this.rowsToAnimate.add(row);\n this.expandedRows.add(row);\n }\n this.requestRender();\n }\n\n /**\n * Collapse all detail rows.\n */\n collapseAll(): void {\n this.expandedRows.clear();\n this.requestRender();\n }\n\n /**\n * Get the indices of all expanded rows.\n * @returns Array of row indices that are expanded\n */\n getExpandedRows(): number[] {\n const indices: number[] = [];\n for (const row of this.expandedRows) {\n const idx = this.rows.indexOf(row);\n if (idx >= 0) indices.push(idx);\n }\n return indices;\n }\n\n /**\n * Get the detail element for a specific row.\n * @param rowIndex - Index of the row\n * @returns The detail HTMLElement or undefined\n */\n getDetailElement(rowIndex: number): HTMLElement | undefined {\n const row = this.rows[rowIndex];\n return row ? this.detailElements.get(row) : undefined;\n }\n\n /**\n * Re-parse light DOM to refresh the detail renderer.\n * Call this after framework templates are registered (e.g., Angular ngAfterContentInit).\n *\n * This allows frameworks to register templates asynchronously and then\n * update the plugin's detailRenderer.\n */\n refreshDetailRenderer(): void {\n // Force re-parse by temporarily clearing the renderer\n const currentRenderer = this.config.detailRenderer;\n this.config = { ...this.config, detailRenderer: undefined };\n this.parseLightDomDetail();\n\n // If no new renderer was found, restore the original\n if (!this.config.detailRenderer && currentRenderer) {\n this.config = { ...this.config, detailRenderer: currentRenderer };\n }\n\n // Request a COLUMNS phase re-render so processColumns runs again with the new detailRenderer\n // This ensures the expand toggle is added to the first column.\n // Must use refreshColumns() (COLUMNS phase) not requestRender() (ROWS phase)\n // because processColumns only runs at COLUMNS phase or higher.\n if (this.config.detailRenderer) {\n const grid = this.grid as unknown as { refreshColumns?: () => void };\n if (typeof grid.refreshColumns === 'function') {\n grid.refreshColumns();\n } else {\n // Fallback to requestRender if refreshColumns not available\n this.requestRender();\n }\n }\n }\n // #endregion\n}\n"],"names":["toggleDetailRow","expandedRows","row","newExpanded","expandDetailRow","collapseDetailRow","isDetailExpanded","createDetailElement","rowIndex","renderer","columnCount","detailRow","detailCell","content","MasterDetailPlugin","BaseGridPlugin","styles","grid","gridEl","detailEl","gridWithAdapter","adapterRenderer","animation","showExpandColumn","expandOnRowClick","collapseOnClickOutside","heightAttr","configUpdates","templateHTML","_rowIndex","evaluated","evalTemplateString","sanitizeHTML","measured","measureOnce","#measureAndCacheDetailHeight","onComplete","cleanup","height","previousHeight","cachedHeight","expanded","columns","cols","findExpanderColumn","expanderCol","createExpanderColumnConfig","renderCtx","isExpanded","container","toggle","event","#syncDetailRows","focusCol","focusRow","column","isExpanderColumn","body","gridInternal","rowPool","vStart","vEnd","visibleStart","visibleEnd","visibleRowMap","poolLen","i","rowEl","dataRows","firstCell","isStillExpanded","isRowVisible","adapter","existingDetail","shouldAnimate","totalHeight","beforeRowIndex","_index","baseHeight","detailHeight","start","scrollTop","rowHeight","positionCache","minStart","expandedIndices","index","a","b","cumulativeExtraHeight","actualRowTop","actualDetailBottom","indices","idx","currentRenderer"],"mappings":"wfAaO,SAASA,EAAgBC,EAA2BC,EAA0B,CACnF,MAAMC,EAAc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/base-plugin"),require("../../core/plugin/expander-column")):typeof define=="function"&&define.amd?define(["exports","../../core/internal/utils","../../core/plugin/base-plugin","../../core/plugin/expander-column"],g):(f=typeof globalThis<"u"?globalThis:f||self,g(f.TbwGridPlugin_selection={},f.TbwGrid,f.TbwGrid,f.TbwGrid))})(this,(function(f,g,y,w){"use strict";function b(n){return{startRow:Math.min(n.startRow,n.endRow),startCol:Math.min(n.startCol,n.endCol),endRow:Math.max(n.startRow,n.endRow),endCol:Math.max(n.startCol,n.endCol)}}function x(n){const e=b(n);return{from:{row:e.startRow,col:e.startCol},to:{row:e.endRow,col:e.endCol}}}function S(n){return n.map(x)}function A(n,e,t){const s=b(t);return n>=s.startRow&&n<=s.endRow&&e>=s.startCol&&e<=s.endCol}function k(n,e,t){return t.some(s=>A(n,e,s))}function v(n){const e=[],t=b(n);for(let s=t.startRow;s<=t.endRow;s++)for(let i=t.startCol;i<=t.endCol;i++)e.push({row:s,col:i});return e}function E(n){const e=new Map;for(const t of n)for(const s of v(t))e.set(`${s.row},${s.col}`,s);return[...e.values()]}function p(n,e){return{startRow:n.row,startCol:n.col,endRow:e.row,endCol:e.col}}function m(n,e){const t=b(n),s=b(e);return t.startRow===s.startRow&&t.startCol===s.startCol&&t.endRow===s.endRow&&t.endCol===s.endCol}const I='@layer tbw-plugins{tbw-grid.selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}tbw-grid:has(.selection){-webkit-user-select:none;user-select:none}tbw-grid .data-grid-row.row-focus{background-color:var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%));outline:none;position:relative}tbw-grid .data-grid-row.row-focus:after{content:"";position:absolute;inset:0;pointer-events:none;border-width:0;border-style:var(--tbw-selection-border-style, var(--tbw-border-style));border-color:var(--tbw-range-border-color, var(--tbw-color-accent));border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width));border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width));z-index:1}tbw-grid .data-grid-row.row-focus+.data-grid-row.row-focus:after{border-top-width:0}tbw-grid .data-grid-row.row-focus:has(+.data-grid-row.row-focus):after{border-bottom-width:0}tbw-grid[data-selection-mode=row] .cell-focus,tbw-grid[data-selection-mode=row] .row-focus,tbw-grid[data-selection-mode=range] .cell-focus{outline:none}tbw-grid .data-grid-row>.cell.selected{background-color:var(--tbw-range-selection-bg);position:relative}tbw-grid .data-grid-row>.cell.selected:after{content:"";position:absolute;inset:0;pointer-events:none;border:0 var(--tbw-selection-border-style, var(--tbw-border-style)) var(--tbw-range-border-color);z-index:1}tbw-grid .data-grid-row>.cell.selected.top:after{border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.bottom:after{border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.first:after{border-left-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.last:after{border-right-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row[data-selectable=false].row-focus{background-color:var(--tbw-color-row-alt)}tbw-grid .data-grid-row>.cell[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row>.cell[data-selectable=false].selected{background-color:var(--tbw-selection-warning-bg, rgba(from var(--tbw-color-error) r g b / 50%))}tbw-grid .tbw-selection-summary{font-size:var(--tbw-font-size-sm, .8125rem);color:var(--tbw-color-fg-muted);white-space:nowrap}tbw-grid .data-grid-row>.cell[data-field=__tbw_checkbox],tbw-grid .header-row>.cell[data-field=__tbw_checkbox]{text-align:center;cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .tbw-select-row-checkbox{pointer-events:none;margin:0;cursor:pointer}tbw-grid .tbw-checkbox-header{display:flex;justify-content:center;align-items:center;height:100%}tbw-grid .tbw-select-all-checkbox{margin:0;cursor:pointer}}',C="__tbw_checkbox";function K(n,e,t){if(n==="cell"&&e.selectedCell)return{mode:n,ranges:[{from:{row:e.selectedCell.row,col:e.selectedCell.col},to:{row:e.selectedCell.row,col:e.selectedCell.col}}]};if(n==="row"&&e.selected.size>0){const s=[...e.selected].sort((o,d)=>o-d),i=[];let l=s[0],r=l;for(let o=1;o<s.length;o++)s[o]===r+1?r=s[o]:(i.push({from:{row:l,col:0},to:{row:r,col:t-1}}),l=s[o],r=l);return i.push({from:{row:l,col:0},to:{row:r,col:t-1}}),{mode:n,ranges:i}}return n==="range"&&e.ranges.length>0?{mode:n,ranges:S(e.ranges)}:{mode:n,ranges:[]}}class q extends y.BaseGridPlugin{static manifest={queries:[{type:"getSelection",description:"Get the current selection state"},{type:"selectRows",description:"Select specific rows by index (row mode only)"},{type:"getSelectedRowIndices",description:"Get sorted array of selected row indices"},{type:"getSelectedRows",description:"Get actual row objects for the current selection (works in all modes)"}],configRules:[{id:"selection/range-dblclick",severity:"warn",message:`"triggerOn: 'dblclick'" has no effect when mode is "range".
|
|
2
2
|
→ Range selection uses drag interaction (mousedown → mousemove), not click events.
|
|
3
|
-
→ The "triggerOn" option only affects "cell" and "row" selection modes.`,check:e=>e.mode==="range"&&e.triggerOn==="dblclick"}]};name="selection";styles=I;get defaultConfig(){return{mode:"cell",triggerOn:"click",enabled:!0}}selected=new Set;lastSelected=null;anchor=null;ranges=[];activeRange=null;cellAnchor=null;isDragging=!1;pendingKeyboardUpdate=null;selectedCell=null;lastSyncedFocusRow=-1;lastSyncedFocusCol=-1;explicitSelection=!1;isSelectionEnabled(){return this.config.enabled===!1?!1:this.grid.effectiveConfig?.selectable!==!1}checkSelectable(e,t){const{isSelectable:s}=this.config;if(!s)return!0;const i=this.rows[e];if(!i)return!1;const l=t!==void 0?this.columns[t]:void 0;return s(i,e,l,t)}isRowSelectable(e){return this.checkSelectable(e)}isCellSelectable(e,t){return this.checkSelectable(e,t)}attach(e){super.attach(e),this.on("filter-applied",()=>this.clearSelectionSilent()),this.on("grouping-state-change",()=>this.clearSelectionSilent()),this.on("tree-state-change",()=>this.clearSelectionSilent())}handleQuery(e){if(e.type==="getSelection")return this.getSelection();if(e.type==="getSelectedRowIndices")return this.getSelectedRowIndices();if(e.type==="getSelectedRows")return this.getSelectedRows();if(e.type==="selectRows")return this.selectRows(e.context),!0}detach(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.isDragging=!1,this.selectedCell=null,this.pendingKeyboardUpdate=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1}clearSelectionSilent(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.selectedCell=null,this.lastSelected=null,this.anchor=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1,this.requestAfterRender()}onCellClick(e){if(!this.isSelectionEnabled())return!1;const{rowIndex:t,colIndex:s,originalEvent:i}=e,{mode:l,triggerOn:r="click"}=this.config;if(i.type!==r)return!1;const o=this.columns[s],d=o&&w.isUtilityColumn(o);if(l==="cell"){if(d||!this.isCellSelectable(t,s))return!1;const a=this.selectedCell;return a&&a.row===t&&a.col===s||(this.selectedCell={row:t,col:s},this.emit("selection-change",this.#e()),this.requestAfterRender()),!1}if(l==="row"){if(!this.isRowSelectable(t))return!1;const a=i.shiftKey,h=i.ctrlKey||i.metaKey,c=o?.meta?.checkboxColumn===!0;if(a&&this.anchor!==null){const f=Math.min(this.anchor,t),M=Math.max(this.anchor,t);h||this.selected.clear();for(let R=f;R<=M;R++)this.isRowSelectable(R)&&this.selected.add(R)}else if(h||c)this.selected.has(t)?this.selected.delete(t):this.selected.add(t),this.anchor=t;else{if(this.selected.size===1&&this.selected.has(t))return!1;this.selected.clear(),this.selected.add(t),this.anchor=t}return this.lastSelected=t,this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender(),!1}if(l==="range"){if(d||!this.isCellSelectable(t,s))return!1;const a=i.shiftKey,h=i.ctrlKey||i.metaKey;if(a&&this.cellAnchor){const c=p(this.cellAnchor,{row:t,col:s}),f=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(f&&m(f,c))return!1;h?this.ranges.length>0?this.ranges[this.ranges.length-1]=c:this.ranges.push(c):this.ranges=[c],this.activeRange=c}else if(h){const c={startRow:t,startCol:s,endRow:t,endCol:s};this.ranges.push(c),this.activeRange=c,this.cellAnchor={row:t,col:s}}else{const c={startRow:t,startCol:s,endRow:t,endCol:s};if(this.ranges.length===1&&m(this.ranges[0],c))return!1;this.ranges=[c],this.activeRange=c,this.cellAnchor={row:t,col:s}}return this.emit("selection-change",this.#e()),this.requestAfterRender(),!1}return!1}onKeyDown(e){if(!this.isSelectionEnabled())return!1;const{mode:t}=this.config,i=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End","PageUp","PageDown"].includes(e.key);if(e.key==="Escape")return this.grid.query("isEditing").some(Boolean)?!1:(t==="cell"?this.selectedCell=null:t==="row"?(this.selected.clear(),this.anchor=null):t==="range"&&(this.ranges=[],this.activeRange=null,this.cellAnchor=null),this.emit("selection-change",this.#e()),this.requestAfterRender(),!0);if(t==="cell"&&i)return queueMicrotask(()=>{const l=this.grid._focusRow,r=this.grid._focusCol;this.isCellSelectable(l,r)?this.selectedCell={row:l,col:r}:this.selectedCell=null,this.emit("selection-change",this.#e()),this.requestAfterRender()}),!1;if(t==="row"){if(e.key==="ArrowUp"||e.key==="ArrowDown"){const l=e.shiftKey;return l&&this.anchor===null&&(this.anchor=this.grid._focusRow),queueMicrotask(()=>{const r=this.grid._focusRow;if(l&&this.anchor!==null){this.selected.clear();const o=Math.min(this.anchor,r),d=Math.max(this.anchor,r);for(let a=o;a<=d;a++)this.isRowSelectable(a)&&this.selected.add(a)}else this.isRowSelectable(r)?(this.selected.clear(),this.selected.add(r),this.anchor=r):this.selected.clear();this.lastSelected=r,this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender()}),!1}if(e.key==="a"&&(e.ctrlKey||e.metaKey))return this.grid.query("isEditing").some(Boolean)?!1:(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}if(t==="range"&&i){const l=e.key==="Tab",r=e.shiftKey&&!l;return r&&!this.cellAnchor&&(this.cellAnchor={row:this.grid._focusRow,col:this.grid._focusCol}),this.pendingKeyboardUpdate={shiftKey:r},queueMicrotask(()=>this.requestAfterRender()),!1}return t==="range"&&e.key==="a"&&(e.ctrlKey||e.metaKey)?this.grid.query("isEditing").some(Boolean)?!1:(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0):!1}onCellMouseDown(e){if(!this.isSelectionEnabled()||this.config.mode!=="range"||e.rowIndex===void 0||e.colIndex===void 0||e.rowIndex<0)return;const t=this.columns[e.colIndex];if(t&&w.isUtilityColumn(t)||!this.isCellSelectable(e.rowIndex,e.colIndex)||e.originalEvent.shiftKey&&this.cellAnchor)return;this.isDragging=!0;const s=e.rowIndex,i=e.colIndex,l=e.originalEvent.ctrlKey||e.originalEvent.metaKey,r={startRow:s,startCol:i,endRow:s,endCol:i};return!l&&this.ranges.length===1&&m(this.ranges[0],r)?(this.cellAnchor={row:s,col:i},!0):(this.cellAnchor={row:s,col:i},l||(this.ranges=[]),this.ranges.push(r),this.activeRange=r,this.emit("selection-change",this.#e()),this.requestAfterRender(),!0)}onCellMouseMove(e){if(!this.isSelectionEnabled()||this.config.mode!=="range"||!this.isDragging||!this.cellAnchor||e.rowIndex===void 0||e.colIndex===void 0||e.rowIndex<0)return;let t=e.colIndex;const s=this.columns[t];if(s&&w.isUtilityColumn(s)){const r=this.columns.findIndex(o=>!w.isUtilityColumn(o));r>=0&&(t=r)}const i=p(this.cellAnchor,{row:e.rowIndex,col:t}),l=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return l&&m(l,i)||(this.ranges.length>0?this.ranges[this.ranges.length-1]=i:this.ranges.push(i),this.activeRange=i,this.emit("selection-change",this.#e()),this.requestAfterRender()),!0}onCellMouseUp(e){if(this.isSelectionEnabled()&&this.config.mode==="range"&&this.isDragging)return this.isDragging=!1,!0}processColumns(e){if(this.config.checkbox&&this.config.mode==="row"){if(e.some(l=>l.field===y))return e;const t=this.#s(),s=e.findIndex(w.isExpanderColumn),i=s>=0?s+1:0;return[...e.slice(0,i),t,...e.slice(i)]}return e}#s(){return{field:y,header:"",width:32,resizable:!1,sortable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0,checkboxColumn:!0},headerRenderer:()=>{const e=document.createElement("div");e.className="tbw-checkbox-header";const t=document.createElement("input");return t.type="checkbox",t.className="tbw-select-all-checkbox",t.addEventListener("click",s=>{s.stopPropagation(),s.target.checked?this.selectAll():this.clearSelection()}),e.appendChild(t),e},renderer:e=>{const t=document.createElement("input");t.type="checkbox",t.className="tbw-select-row-checkbox";const s=e.cellEl;if(s){const i=parseInt(s.getAttribute("data-row")??"-1",10);i>=0&&(t.checked=this.selected.has(i))}return t}}}#i(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(i=>{const l=i.closest(".cell"),r=l?u.getRowIndexFromCell(l):-1;r>=0&&(i.checked=this.selected.has(r))});const s=e.querySelector(".tbw-select-all-checkbox");if(s){const i=this.rows.length;let l=0;if(this.config.isSelectable)for(let d=0;d<i;d++)this.isRowSelectable(d)&&l++;else l=i;const r=l>0&&this.selected.size>=l,o=this.selected.size>0;s.checked=r,s.indeterminate=o&&!r}}#r(e){const t=this.grid._focusRow,s=this.grid._focusCol;if(e==="row"){if(this.explicitSelection){this.explicitSelection=!1,this.lastSyncedFocusRow=t;return}t!==this.lastSyncedFocusRow&&(this.lastSyncedFocusRow=t,this.isRowSelectable(t)&&(!this.selected.has(t)||this.selected.size!==1)&&(this.selected.clear(),this.selected.add(t),this.lastSelected=t,this.anchor=t,this.emit("selection-change",this.#e())))}if(e==="cell"){if(this.explicitSelection){this.explicitSelection=!1,this.lastSyncedFocusRow=t,this.lastSyncedFocusCol=s;return}if((t!==this.lastSyncedFocusRow||s!==this.lastSyncedFocusCol)&&(this.lastSyncedFocusRow=t,this.lastSyncedFocusCol=s,this.isCellSelectable(t,s))){const i=this.selectedCell;(!i||i.row!==t||i.col!==s)&&(this.selectedCell={row:t,col:s},this.emit("selection-change",this.#e()))}}}#t(){const e=this.gridElement;if(!e)return;const{mode:t}=this.config,s=!!this.config.isSelectable;e.querySelectorAll(".cell").forEach(r=>{r.classList.remove("selected","top","bottom","first","last"),s&&r.removeAttribute("data-selectable")});const l=e.querySelectorAll(".data-grid-row");if(l.forEach(r=>{r.classList.remove("selected","row-focus"),s&&r.removeAttribute("data-selectable")}),t==="row"&&(u.clearCellFocus(e),l.forEach(r=>{const o=r.querySelector(".cell[data-row]"),d=u.getRowIndexFromCell(o);d>=0&&(s&&!this.isRowSelectable(d)&&r.setAttribute("data-selectable","false"),this.selected.has(d)&&r.classList.add("selected","row-focus"))}),this.config.checkbox&&this.#i(e)),(t==="cell"||t==="range")&&s&&e.querySelectorAll(".cell[data-row][data-col]").forEach(o=>{const d=parseInt(o.getAttribute("data-row")??"-1",10),a=parseInt(o.getAttribute("data-col")??"-1",10);d>=0&&a>=0&&(this.isCellSelectable(d,a)||o.setAttribute("data-selectable","false"))}),t==="range"&&this.ranges.length>0){u.clearCellFocus(e);const r=this.ranges.map(b),o=(a,h)=>{for(const c of r)if(a>=c.startRow&&a<=c.endRow&&h>=c.startCol&&h<=c.endCol)return!0;return!1};e.querySelectorAll(".cell[data-row][data-col]").forEach(a=>{const h=parseInt(a.getAttribute("data-row")??"-1",10),c=parseInt(a.getAttribute("data-col")??"-1",10);if(h>=0&&c>=0){const f=this.columns[c];if(f&&w.isUtilityColumn(f))return;o(h,c)&&(a.classList.add("selected"),o(h-1,c)||a.classList.add("top"),o(h+1,c)||a.classList.add("bottom"),o(h,c-1)||a.classList.add("first"),o(h,c+1)||a.classList.add("last"))}})}}afterRender(){if(!this.isSelectionEnabled())return;const e=this.gridElement;if(!e)return;const t=e.children[0],{mode:s}=this.config;if(this.pendingKeyboardUpdate&&s==="range"){const{shiftKey:i}=this.pendingKeyboardUpdate;this.pendingKeyboardUpdate=null;const l=this.grid._focusRow,r=this.grid._focusCol;if(i&&this.cellAnchor){const o=p(this.cellAnchor,{row:l,col:r});this.ranges=[o],this.activeRange=o}else i||(this.ranges=[],this.activeRange=null,this.cellAnchor={row:l,col:r});this.emit("selection-change",this.#e())}this.#r(s),this.grid.setAttribute("data-selection-mode",s),t&&t.classList.toggle("selecting",this.isDragging),this.#t()}onScrollRender(){this.isSelectionEnabled()&&this.#t()}getSelection(){return{mode:this.config.mode,ranges:this.#e().ranges,anchor:this.cellAnchor}}getSelectedCells(){return E(this.ranges)}isCellSelected(e,t){return k(e,t,this.ranges)}selectAll(){const{mode:e}=this.config;if(e==="row"){this.selected.clear();for(let t=0;t<this.rows.length;t++)this.isRowSelectable(t)&&this.selected.add(t);this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender()}else if(e==="range"){const t=this.rows.length,s=this.columns.length;if(t>0&&s>0){const i={startRow:0,startCol:0,endRow:t-1,endCol:s-1};this.ranges=[i],this.activeRange=i,this.emit("selection-change",this.#e()),this.requestAfterRender()}}}selectRows(e){if(this.config.mode==="row"){this.selected.clear();for(const t of e)t>=0&&t<this.rows.length&&this.isRowSelectable(t)&&this.selected.add(t);this.anchor=e.length>0?e[e.length-1]:null,this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender()}}getSelectedRowIndices(){return[...this.selected].sort((e,t)=>e-t)}getSelectedRows(){const{mode:e}=this.config,t=this.rows;if(e==="row")return this.getSelectedRowIndices().filter(s=>s>=0&&s<t.length).map(s=>t[s]);if(e==="cell"&&this.selectedCell){const{row:s}=this.selectedCell;return s>=0&&s<t.length?[t[s]]:[]}if(e==="range"&&this.ranges.length>0){const s=new Set;for(const i of this.ranges){const l=Math.max(0,Math.min(i.startRow,i.endRow)),r=Math.min(t.length-1,Math.max(i.startRow,i.endRow));for(let o=l;o<=r;o++)s.add(o)}return[...s].sort((i,l)=>i-l).map(i=>t[i])}return[]}clearSelection(){this.selectedCell=null,this.selected.clear(),this.anchor=null,this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.emit("selection-change",{mode:this.config.mode,ranges:[]}),this.requestAfterRender()}setRanges(e){this.ranges=e.map(t=>({startRow:t.from.row,startCol:t.from.col,endRow:t.to.row,endCol:t.to.col})),this.activeRange=this.ranges.length>0?this.ranges[this.ranges.length-1]:null,this.emit("selection-change",{mode:this.config.mode,ranges:C(this.ranges)}),this.requestAfterRender()}#e(){return K(this.config.mode,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges},this.columns.length)}}g.SelectionPlugin=q,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})}));
|
|
3
|
+
→ The "triggerOn" option only affects "cell" and "row" selection modes.`,check:e=>e.mode==="range"&&e.triggerOn==="dblclick"}]};name="selection";styles=I;get defaultConfig(){return{mode:"cell",triggerOn:"click",enabled:!0,multiSelect:!0}}selected=new Set;lastSelected=null;anchor=null;ranges=[];activeRange=null;cellAnchor=null;isDragging=!1;pendingKeyboardUpdate=null;selectedCell=null;lastSyncedFocusRow=-1;lastSyncedFocusCol=-1;explicitSelection=!1;isSelectionEnabled(){return this.config.enabled===!1?!1:this.grid.effectiveConfig?.selectable!==!1}checkSelectable(e,t){const{isSelectable:s}=this.config;if(!s)return!0;const i=this.rows[e];if(!i)return!1;const l=t!==void 0?this.columns[t]:void 0;return s(i,e,l,t)}isRowSelectable(e){return this.checkSelectable(e)}isCellSelectable(e,t){return this.checkSelectable(e,t)}attach(e){super.attach(e),this.on("filter-applied",()=>this.clearSelectionSilent()),this.on("grouping-state-change",()=>this.clearSelectionSilent()),this.on("tree-state-change",()=>this.clearSelectionSilent())}handleQuery(e){if(e.type==="getSelection")return this.getSelection();if(e.type==="getSelectedRowIndices")return this.getSelectedRowIndices();if(e.type==="getSelectedRows")return this.getSelectedRows();if(e.type==="selectRows")return this.selectRows(e.context),!0}detach(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.isDragging=!1,this.selectedCell=null,this.pendingKeyboardUpdate=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1}clearSelectionSilent(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.selectedCell=null,this.lastSelected=null,this.anchor=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1,this.requestAfterRender()}onCellClick(e){if(!this.isSelectionEnabled())return!1;const{rowIndex:t,colIndex:s,originalEvent:i}=e,{mode:l,triggerOn:r="click"}=this.config;if(i.type!==r)return!1;const o=this.columns[s],d=o&&w.isUtilityColumn(o);if(l==="cell"){if(d||!this.isCellSelectable(t,s))return!1;const a=this.selectedCell;return a&&a.row===t&&a.col===s||(this.selectedCell={row:t,col:s},this.emit("selection-change",this.#e()),this.requestAfterRender()),!1}if(l==="row"){if(!this.isRowSelectable(t))return!1;const a=this.config.multiSelect!==!1,h=i.shiftKey&&a,c=(i.ctrlKey||i.metaKey)&&a,u=o?.meta?.checkboxColumn===!0;if(h&&this.anchor!==null){const M=Math.min(this.anchor,t),_=Math.max(this.anchor,t);c||this.selected.clear();for(let R=M;R<=_;R++)this.isRowSelectable(R)&&this.selected.add(R)}else if(c||u&&a)this.selected.has(t)?this.selected.delete(t):this.selected.add(t),this.anchor=t;else{if(this.selected.size===1&&this.selected.has(t))return!1;this.selected.clear(),this.selected.add(t),this.anchor=t}return this.lastSelected=t,this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender(),!1}if(l==="range"){if(d||!this.isCellSelectable(t,s))return!1;const a=i.shiftKey,h=(i.ctrlKey||i.metaKey)&&this.config.multiSelect!==!1;if(a&&this.cellAnchor){const c=p(this.cellAnchor,{row:t,col:s}),u=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(u&&m(u,c))return!1;h?this.ranges.length>0?this.ranges[this.ranges.length-1]=c:this.ranges.push(c):this.ranges=[c],this.activeRange=c}else if(h){const c={startRow:t,startCol:s,endRow:t,endCol:s};this.ranges.push(c),this.activeRange=c,this.cellAnchor={row:t,col:s}}else{const c={startRow:t,startCol:s,endRow:t,endCol:s};if(this.ranges.length===1&&m(this.ranges[0],c))return!1;this.ranges=[c],this.activeRange=c,this.cellAnchor={row:t,col:s}}return this.emit("selection-change",this.#e()),this.requestAfterRender(),!1}return!1}onKeyDown(e){if(!this.isSelectionEnabled())return!1;const{mode:t}=this.config,i=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End","PageUp","PageDown"].includes(e.key);if(e.key==="Escape")return this.grid.query("isEditing").some(Boolean)?!1:(t==="cell"?this.selectedCell=null:t==="row"?(this.selected.clear(),this.anchor=null):t==="range"&&(this.ranges=[],this.activeRange=null,this.cellAnchor=null),this.emit("selection-change",this.#e()),this.requestAfterRender(),!0);if(t==="cell"&&i)return queueMicrotask(()=>{const l=this.grid._focusRow,r=this.grid._focusCol;this.isCellSelectable(l,r)?this.selectedCell={row:l,col:r}:this.selectedCell=null,this.emit("selection-change",this.#e()),this.requestAfterRender()}),!1;if(t==="row"){const l=this.config.multiSelect!==!1;if(e.key==="ArrowUp"||e.key==="ArrowDown"){const r=e.shiftKey&&l;return r&&this.anchor===null&&(this.anchor=this.grid._focusRow),queueMicrotask(()=>{const o=this.grid._focusRow;if(r&&this.anchor!==null){this.selected.clear();const d=Math.min(this.anchor,o),a=Math.max(this.anchor,o);for(let h=d;h<=a;h++)this.isRowSelectable(h)&&this.selected.add(h)}else this.isRowSelectable(o)?(this.selected.clear(),this.selected.add(o),this.anchor=o):this.selected.clear();this.lastSelected=o,this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender()}),!1}if(l&&e.key==="a"&&(e.ctrlKey||e.metaKey))return this.grid.query("isEditing").some(Boolean)?!1:(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}if(t==="range"&&i){const l=e.key==="Tab",r=e.shiftKey&&!l;return r&&!this.cellAnchor&&(this.cellAnchor={row:this.grid._focusRow,col:this.grid._focusCol}),this.pendingKeyboardUpdate={shiftKey:r},queueMicrotask(()=>this.requestAfterRender()),!1}return t==="range"&&this.config.multiSelect!==!1&&e.key==="a"&&(e.ctrlKey||e.metaKey)?this.grid.query("isEditing").some(Boolean)?!1:(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0):!1}onCellMouseDown(e){if(!this.isSelectionEnabled()||this.config.mode!=="range"||e.rowIndex===void 0||e.colIndex===void 0||e.rowIndex<0)return;const t=this.columns[e.colIndex];if(t&&w.isUtilityColumn(t)||!this.isCellSelectable(e.rowIndex,e.colIndex)||e.originalEvent.shiftKey&&this.cellAnchor)return;this.isDragging=!0;const s=e.rowIndex,i=e.colIndex,l=(e.originalEvent.ctrlKey||e.originalEvent.metaKey)&&this.config.multiSelect!==!1,r={startRow:s,startCol:i,endRow:s,endCol:i};return!l&&this.ranges.length===1&&m(this.ranges[0],r)?(this.cellAnchor={row:s,col:i},!0):(this.cellAnchor={row:s,col:i},l||(this.ranges=[]),this.ranges.push(r),this.activeRange=r,this.emit("selection-change",this.#e()),this.requestAfterRender(),!0)}onCellMouseMove(e){if(!this.isSelectionEnabled()||this.config.mode!=="range"||!this.isDragging||!this.cellAnchor||e.rowIndex===void 0||e.colIndex===void 0||e.rowIndex<0)return;let t=e.colIndex;const s=this.columns[t];if(s&&w.isUtilityColumn(s)){const r=this.columns.findIndex(o=>!w.isUtilityColumn(o));r>=0&&(t=r)}const i=p(this.cellAnchor,{row:e.rowIndex,col:t}),l=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return l&&m(l,i)||(this.ranges.length>0?this.ranges[this.ranges.length-1]=i:this.ranges.push(i),this.activeRange=i,this.emit("selection-change",this.#e()),this.requestAfterRender()),!0}onCellMouseUp(e){if(this.isSelectionEnabled()&&this.config.mode==="range"&&this.isDragging)return this.isDragging=!1,!0}processColumns(e){if(this.config.checkbox&&this.config.mode==="row"){if(e.some(l=>l.field===C))return e;const t=this.#s(),s=e.findIndex(w.isExpanderColumn),i=s>=0?s+1:0;return[...e.slice(0,i),t,...e.slice(i)]}return e}#s(){return{field:C,header:"",width:32,resizable:!1,sortable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0,checkboxColumn:!0},headerRenderer:()=>{const e=document.createElement("div");if(e.className="tbw-checkbox-header",this.config.multiSelect===!1)return e;const t=document.createElement("input");return t.type="checkbox",t.className="tbw-select-all-checkbox",t.addEventListener("click",s=>{s.stopPropagation(),s.target.checked?this.selectAll():this.clearSelection()}),e.appendChild(t),e},renderer:e=>{const t=document.createElement("input");t.type="checkbox",t.className="tbw-select-row-checkbox";const s=e.cellEl;if(s){const i=parseInt(s.getAttribute("data-row")??"-1",10);i>=0&&(t.checked=this.selected.has(i))}return t}}}#i(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(i=>{const l=i.closest(".cell"),r=l?g.getRowIndexFromCell(l):-1;r>=0&&(i.checked=this.selected.has(r))});const s=e.querySelector(".tbw-select-all-checkbox");if(s){const i=this.rows.length;let l=0;if(this.config.isSelectable)for(let d=0;d<i;d++)this.isRowSelectable(d)&&l++;else l=i;const r=l>0&&this.selected.size>=l,o=this.selected.size>0;s.checked=r,s.indeterminate=o&&!r}}#l(e){const t=this.grid._focusRow,s=this.grid._focusCol;if(e==="row"){if(this.explicitSelection){this.explicitSelection=!1,this.lastSyncedFocusRow=t;return}t!==this.lastSyncedFocusRow&&(this.lastSyncedFocusRow=t,this.isRowSelectable(t)&&(!this.selected.has(t)||this.selected.size!==1)&&(this.selected.clear(),this.selected.add(t),this.lastSelected=t,this.anchor=t,this.emit("selection-change",this.#e())))}if(e==="cell"){if(this.explicitSelection){this.explicitSelection=!1,this.lastSyncedFocusRow=t,this.lastSyncedFocusCol=s;return}if((t!==this.lastSyncedFocusRow||s!==this.lastSyncedFocusCol)&&(this.lastSyncedFocusRow=t,this.lastSyncedFocusCol=s,this.isCellSelectable(t,s))){const i=this.selectedCell;(!i||i.row!==t||i.col!==s)&&(this.selectedCell={row:t,col:s},this.emit("selection-change",this.#e()))}}}#t(){const e=this.gridElement;if(!e)return;const{mode:t}=this.config,s=!!this.config.isSelectable;e.querySelectorAll(".cell").forEach(r=>{r.classList.remove("selected","top","bottom","first","last"),s&&r.removeAttribute("data-selectable")});const l=e.querySelectorAll(".data-grid-row");if(l.forEach(r=>{r.classList.remove("selected","row-focus"),s&&r.removeAttribute("data-selectable")}),t==="row"&&(g.clearCellFocus(e),l.forEach(r=>{const o=r.querySelector(".cell[data-row]"),d=g.getRowIndexFromCell(o);d>=0&&(s&&!this.isRowSelectable(d)&&r.setAttribute("data-selectable","false"),this.selected.has(d)&&r.classList.add("selected","row-focus"))}),this.config.checkbox&&this.#i(e)),(t==="cell"||t==="range")&&s&&e.querySelectorAll(".cell[data-row][data-col]").forEach(o=>{const d=parseInt(o.getAttribute("data-row")??"-1",10),a=parseInt(o.getAttribute("data-col")??"-1",10);d>=0&&a>=0&&(this.isCellSelectable(d,a)||o.setAttribute("data-selectable","false"))}),t==="range"&&this.ranges.length>0){g.clearCellFocus(e);const r=this.ranges.map(b),o=(a,h)=>{for(const c of r)if(a>=c.startRow&&a<=c.endRow&&h>=c.startCol&&h<=c.endCol)return!0;return!1};e.querySelectorAll(".cell[data-row][data-col]").forEach(a=>{const h=parseInt(a.getAttribute("data-row")??"-1",10),c=parseInt(a.getAttribute("data-col")??"-1",10);if(h>=0&&c>=0){const u=this.columns[c];if(u&&w.isUtilityColumn(u))return;o(h,c)&&(a.classList.add("selected"),o(h-1,c)||a.classList.add("top"),o(h+1,c)||a.classList.add("bottom"),o(h,c-1)||a.classList.add("first"),o(h,c+1)||a.classList.add("last"))}})}}afterRender(){if(!this.isSelectionEnabled())return;const e=this.gridElement;if(!e)return;const t=e.children[0],{mode:s}=this.config;if(this.pendingKeyboardUpdate&&s==="range"){const{shiftKey:i}=this.pendingKeyboardUpdate;this.pendingKeyboardUpdate=null;const l=this.grid._focusRow,r=this.grid._focusCol;if(i&&this.cellAnchor){const o=p(this.cellAnchor,{row:l,col:r});this.ranges=[o],this.activeRange=o}else i||(this.ranges=[],this.activeRange=null,this.cellAnchor={row:l,col:r});this.emit("selection-change",this.#e())}this.#l(s),this.grid.setAttribute("data-selection-mode",s),t&&t.classList.toggle("selecting",this.isDragging),this.#t()}onScrollRender(){this.isSelectionEnabled()&&this.#t()}getSelection(){return{mode:this.config.mode,ranges:this.#e().ranges,anchor:this.cellAnchor}}getSelectedCells(){return E(this.ranges)}isCellSelected(e,t){return k(e,t,this.ranges)}selectAll(){const{mode:e,multiSelect:t}=this.config;if(t!==!1){if(e==="row"){this.selected.clear();for(let s=0;s<this.rows.length;s++)this.isRowSelectable(s)&&this.selected.add(s);this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender()}else if(e==="range"){const s=this.rows.length,i=this.columns.length;if(s>0&&i>0){const l={startRow:0,startCol:0,endRow:s-1,endCol:i-1};this.ranges=[l],this.activeRange=l,this.emit("selection-change",this.#e()),this.requestAfterRender()}}}}selectRows(e){if(this.config.mode!=="row")return;const t=this.config.multiSelect===!1&&e.length>1?[e[e.length-1]]:e;this.selected.clear();for(const s of t)s>=0&&s<this.rows.length&&this.isRowSelectable(s)&&this.selected.add(s);this.anchor=t.length>0?t[t.length-1]:null,this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender()}getSelectedRowIndices(){return[...this.selected].sort((e,t)=>e-t)}getSelectedRows(){const{mode:e}=this.config,t=this.rows;if(e==="row")return this.getSelectedRowIndices().filter(s=>s>=0&&s<t.length).map(s=>t[s]);if(e==="cell"&&this.selectedCell){const{row:s}=this.selectedCell;return s>=0&&s<t.length?[t[s]]:[]}if(e==="range"&&this.ranges.length>0){const s=new Set;for(const i of this.ranges){const l=Math.max(0,Math.min(i.startRow,i.endRow)),r=Math.min(t.length-1,Math.max(i.startRow,i.endRow));for(let o=l;o<=r;o++)s.add(o)}return[...s].sort((i,l)=>i-l).map(i=>t[i])}return[]}clearSelection(){this.selectedCell=null,this.selected.clear(),this.anchor=null,this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.emit("selection-change",{mode:this.config.mode,ranges:[]}),this.requestAfterRender()}setRanges(e){this.ranges=e.map(t=>({startRow:t.from.row,startCol:t.from.col,endRow:t.to.row,endCol:t.to.col})),this.activeRange=this.ranges.length>0?this.ranges[this.ranges.length-1]:null,this.emit("selection-change",{mode:this.config.mode,ranges:S(this.ranges)}),this.requestAfterRender()}#e(){return K(this.config.mode,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges},this.columns.length)}}f.SelectionPlugin=q,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
|
|
4
4
|
//# sourceMappingURL=selection.umd.js.map
|