@toolbox-web/grid 1.23.2 → 1.23.4
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/README.md +2 -2
- package/all.js +2 -2
- package/all.js.map +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/lib/core/grid.d.ts +7 -0
- package/lib/core/grid.d.ts.map +1 -1
- package/lib/core/plugin/base-plugin.d.ts +6 -0
- package/lib/core/plugin/base-plugin.d.ts.map +1 -1
- package/lib/core/plugin/types.d.ts +1 -0
- package/lib/core/plugin/types.d.ts.map +1 -1
- package/lib/core/types.d.ts +10 -3
- package/lib/core/types.d.ts.map +1 -1
- package/lib/plugins/clipboard/ClipboardPlugin.d.ts +3 -3
- package/lib/plugins/clipboard/index.js.map +1 -1
- package/lib/plugins/clipboard/types.d.ts +1 -1
- package/lib/plugins/column-virtualization/index.js.map +1 -1
- package/lib/plugins/column-virtualization/types.d.ts +24 -2
- package/lib/plugins/column-virtualization/types.d.ts.map +1 -1
- package/lib/plugins/context-menu/index.js.map +1 -1
- package/lib/plugins/editing/EditingPlugin.d.ts +19 -122
- package/lib/plugins/editing/EditingPlugin.d.ts.map +1 -1
- package/lib/plugins/editing/editors.d.ts +4 -2
- package/lib/plugins/editing/editors.d.ts.map +1 -1
- package/lib/plugins/editing/index.d.ts +1 -1
- package/lib/plugins/editing/index.d.ts.map +1 -1
- package/lib/plugins/editing/index.js +1 -1
- package/lib/plugins/editing/index.js.map +1 -1
- package/lib/plugins/editing/internal/cell-validation.d.ts +80 -0
- package/lib/plugins/editing/internal/cell-validation.d.ts.map +1 -0
- package/lib/plugins/editing/internal/dirty-tracking-manager.d.ts +77 -0
- package/lib/plugins/editing/internal/dirty-tracking-manager.d.ts.map +1 -0
- package/lib/plugins/editing/internal/editor-injection.d.ts +33 -0
- package/lib/plugins/editing/internal/editor-injection.d.ts.map +1 -0
- package/lib/plugins/editing/internal/helpers.d.ts +55 -0
- package/lib/plugins/editing/internal/helpers.d.ts.map +1 -0
- package/lib/plugins/editing/types.d.ts +1 -1
- package/lib/plugins/export/ExportPlugin.d.ts +1 -1
- package/lib/plugins/export/index.js.map +1 -1
- package/lib/plugins/export/types.d.ts +9 -1
- package/lib/plugins/export/types.d.ts.map +1 -1
- package/lib/plugins/filtering/FilteringPlugin.d.ts +0 -20
- package/lib/plugins/filtering/FilteringPlugin.d.ts.map +1 -1
- package/lib/plugins/filtering/filter-panel-date.d.ts +14 -0
- package/lib/plugins/filtering/filter-panel-date.d.ts.map +1 -0
- package/lib/plugins/filtering/filter-panel-default.d.ts +23 -0
- package/lib/plugins/filtering/filter-panel-default.d.ts.map +1 -0
- package/lib/plugins/filtering/filter-panel-number.d.ts +14 -0
- package/lib/plugins/filtering/filter-panel-number.d.ts.map +1 -0
- package/lib/plugins/filtering/index.js +1 -1
- package/lib/plugins/filtering/index.js.map +1 -1
- package/lib/plugins/filtering/types.d.ts +158 -2
- package/lib/plugins/filtering/types.d.ts.map +1 -1
- package/lib/plugins/grouping-columns/GroupingColumnsPlugin.d.ts.map +1 -1
- package/lib/plugins/grouping-columns/grouping-columns.d.ts +7 -0
- package/lib/plugins/grouping-columns/grouping-columns.d.ts.map +1 -1
- package/lib/plugins/grouping-columns/index.js +1 -1
- package/lib/plugins/grouping-columns/index.js.map +1 -1
- package/lib/plugins/grouping-rows/index.js.map +1 -1
- package/lib/plugins/grouping-rows/types.d.ts +48 -3
- package/lib/plugins/grouping-rows/types.d.ts.map +1 -1
- package/lib/plugins/master-detail/index.js.map +1 -1
- package/lib/plugins/multi-sort/index.js.map +1 -1
- package/lib/plugins/multi-sort/types.d.ts +40 -6
- package/lib/plugins/multi-sort/types.d.ts.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/pinned-rows/types.d.ts +42 -4
- package/lib/plugins/pinned-rows/types.d.ts.map +1 -1
- package/lib/plugins/pivot/index.js.map +1 -1
- package/lib/plugins/pivot/types.d.ts +66 -1
- package/lib/plugins/pivot/types.d.ts.map +1 -1
- package/lib/plugins/print/PrintPlugin.d.ts +1 -1
- package/lib/plugins/print/index.js.map +1 -1
- package/lib/plugins/print/types.d.ts +9 -1
- package/lib/plugins/print/types.d.ts.map +1 -1
- package/lib/plugins/reorder/index.js.map +1 -1
- package/lib/plugins/reorder/types.d.ts +12 -1
- package/lib/plugins/reorder/types.d.ts.map +1 -1
- package/lib/plugins/responsive/index.js +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 +5 -5
- package/lib/plugins/selection/index.js.map +1 -1
- package/lib/plugins/server-side/index.js.map +1 -1
- package/lib/plugins/server-side/types.d.ts +82 -0
- package/lib/plugins/server-side/types.d.ts.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/VisibilityPlugin.d.ts +1 -1
- package/lib/plugins/visibility/index.js.map +1 -1
- package/lib/plugins/visibility/types.d.ts +16 -2
- package/lib/plugins/visibility/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/public.d.ts +1 -1
- package/public.d.ts.map +1 -1
- package/umd/grid.all.umd.js +1 -1
- package/umd/grid.all.umd.js.map +1 -1
- package/umd/grid.umd.js.map +1 -1
- package/umd/plugins/clipboard.umd.js.map +1 -1
- package/umd/plugins/editing.umd.js +1 -1
- package/umd/plugins/editing.umd.js.map +1 -1
- package/umd/plugins/export.umd.js.map +1 -1
- package/umd/plugins/filtering.umd.js +1 -1
- package/umd/plugins/filtering.umd.js.map +1 -1
- package/umd/plugins/grouping-columns.umd.js +1 -1
- package/umd/plugins/grouping-columns.umd.js.map +1 -1
- package/umd/plugins/print.umd.js.map +1 -1
- package/umd/plugins/responsive.umd.js +1 -1
- package/umd/plugins/responsive.umd.js.map +1 -1
- package/umd/plugins/selection.umd.js.map +1 -1
- package/umd/plugins/visibility.umd.js.map +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/plugin/base-plugin"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_groupingColumns={},e.TbwGrid)}(this,function(e,r){"use strict";function
|
|
1
|
+
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/plugin/base-plugin"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_groupingColumns={},e.TbwGrid)}(this,function(e,r){"use strict";function t(e){if(!e.length)return[];const r=new Map,t=[],o=(e,r)=>{if(!r.length)return;const o=t[t.length-1];o&&o.implicit&&o.firstIndex+o.columns.length===e?o.columns.push(...r):t.push({id:"__implicit__"+e,label:void 0,columns:r,firstIndex:e,implicit:!0})};let i=[],n=0;return e.forEach((e,s)=>{const l=e.group;if(!l)return 0===i.length&&(n=s),void i.push(e);i.length&&(o(n,i.slice()),i=[]);const d="string"==typeof l?l:l.id;let u=r.get(d);u||(u={id:d,label:"string"==typeof l?void 0:l.label,columns:[],firstIndex:s},r.set(d,u),t.push(u)),u.columns.push(e)}),i.length&&o(n,i),1===t.length&&t[0].implicit&&t[0].columns.length===e.length?[]:t}function o(e,r){const t=e.columns[0],o=e.columns[e.columns.length-1],i=t?r.findIndex(e=>e.field===t.field):-1,n=o?r.findIndex(e=>e.field===o.field):-1;return-1!==i&&-1!==n?[i,n]:null}function i(e,r){const t=new Set,i=[];for(const n of e){if(String(n.id).startsWith("__implicit__"))continue;const e=o(n,r);e&&i.push(e)}for(const n of e){if(!String(n.id).startsWith("__implicit__"))continue;const e=o(n,r);if(!e)continue;const[s,l]=e;i.some(([e,r])=>s>=e&&l<=r)&&t.add(String(n.id))}return t}class n extends r.BaseGridPlugin{static manifest={ownedProperties:[{property:"group",level:"column",description:'the "group" column property'},{property:"columnGroups",level:"config",description:'the "columnGroups" config property',isUsed:e=>Array.isArray(e)&&e.length>0}],queries:[{type:"getColumnGrouping",description:"Returns column group metadata for the visibility panel"}]};name="groupingColumns";styles="@layer tbw-plugins{.header-group-row{display:grid;grid-auto-flow:column;background:var(--tbw-grouping-columns-header-bg, var(--tbw-color-header-bg));border-bottom:1px solid var(--tbw-grouping-columns-border, var(--tbw-color-border))}.header-group-cell{display:flex;align-items:center;justify-content:center;padding:var(--tbw-button-padding-sm, .25rem .5rem);font-weight:600;font-size:var(--tbw-font-size-sm, .9em);text-transform:uppercase;letter-spacing:.5px;border-right:2px solid var(--tbw-grouping-columns-separator, var(--tbw-color-border-strong, var(--tbw-color-border)))}.header-group-cell:last-child{border-right:none}.header-row .cell.grouped{border-top:none}.header-row .cell.group-end{border-right:2px solid var(--tbw-grouping-columns-separator, var(--tbw-color-border-strong, var(--tbw-color-border)))}.header-row .cell.group-end:last-child{border-right:none}.rows .cell.group-end{border-right:2px solid var(--tbw-grouping-columns-separator, var(--tbw-color-border-strong, var(--tbw-color-border)))}.rows .cell.group-end:last-child{border-right:none}.header-group-row.no-borders{border-bottom:none}.header-group-row.no-borders .header-group-cell{border-right:none}.header-row.no-group-borders .cell.group-end{border-right:1px solid var(--tbw-color-border)}}";get defaultConfig(){return{showGroupBorders:!0,lockGroupOrder:!1}}groups=[];isActive=!1;#e=new Set;attach(e){super.attach(e),e.addEventListener("column-move",this.#r,{signal:this.disconnectSignal})}detach(){this.groups=[],this.isActive=!1,this.#e.clear()}#r=e=>{if(!this.isActive)return;const r=e,{field:t,columnOrder:o}=r.detail;if(this.config.lockGroupOrder)for(const i of this.groups)if(!i.id.startsWith("__implicit__")&&!this.#t(i,o))return r.preventDefault(),void this.#o(t);this.#i(o)};#i(e){this.#e.clear();const r=this.#n(e);for(const t of this.groups){const o=new Set(t.columns.map(e=>e.field));for(let t=e.length-1;t>=0;t--)if(o.has(e[t])){const o=e[t];o!==r&&this.#e.add(o);break}}}#n(e){if(0===this.groups.length)return null;for(let r=e.length-1;r>=0;r--){const t=e[r];for(const r of this.groups)if(r.columns.some(e=>e.field===t)){const t=new Set(r.columns.map(e=>e.field));for(let r=e.length-1;r>=0;r--)if(t.has(e[r]))return e[r]}}return null}#t(e,r){const t=e.columns.map(e=>r.indexOf(e.field)).filter(e=>-1!==e).sort((e,r)=>e-r);return t.length<=1||t.length===t[t.length-1]-t[0]+1}#o(e){const r=this.gridElement?.querySelector(`.header-row [part~="header-cell"][data-field="${e}"]`);r&&(r.style.setProperty("--_flash-color","var(--tbw-color-error)"),r.animate([{backgroundColor:"rgba(from var(--_flash-color) r g b / 30%)"},{backgroundColor:"transparent"}],{duration:400,easing:"ease-out"}))}handleQuery(e){if("getColumnGrouping"===e.type)return this.#s()}#s(){let e;const r=this.grid?.gridConfig?.columnGroups;if(r&&Array.isArray(r)&&r.length>0)e=r.filter(e=>e.children.length>0).map(e=>({id:e.id,label:e.header,fields:[...e.children]}));else if(this.isActive&&this.groups.length>0){e=this.groups.filter(e=>!e.id.startsWith("__implicit__")).map(e=>({id:e.id,label:e.label??e.id,fields:e.columns.map(e=>e.field)}));const r=this.columns;for(const t of r)if(t.hidden&&t.group){const r="string"==typeof t.group?t.group:t.group.id,o="string"==typeof t.group?t.group:t.group.label??t.group.id,i=e.find(e=>e.id===r);i?i.fields.includes(t.field)||i.fields.push(t.field):e.push({id:r,label:o,fields:[t.field]})}}else{const r=this.columns,t=new Map;for(const e of r){if(!e.group)continue;const r="string"==typeof e.group?e.group:e.group.id,o="string"==typeof e.group?e.group:e.group.label??e.group.id,i=t.get(r);i?i.fields.includes(e.field)||i.fields.push(e.field):t.set(r,{id:r,label:o,fields:[e.field]})}e=Array.from(t.values())}const t=this.grid?.getColumnOrder();if(t&&t.length>0){const r=new Map(t.map((e,r)=>[e,r]));for(const t of e)t.fields.sort((e,t)=>(r.get(e)??1/0)-(r.get(t)??1/0))}return e}static detect(e,r){if(r?.columnGroups&&Array.isArray(r.columnGroups)&&r.columnGroups.length>0)return!0;const t=r?.columns;return!!Array.isArray(t)&&function(e){return e.some(e=>null!=e.group)}(t)}processColumns(e){const r=this.grid?.gridConfig?.columnGroups;let o;if(r&&Array.isArray(r)&&r.length>0){const t=new Map;for(const e of r)for(const r of e.children)t.set(r,{id:e.id,label:e.header});o=e.map(e=>{const r=t.get(e.field);return r&&!e.group?{...e,group:r}:e})}else o=[...e];const i=t(o);if(0===i.length)return this.isActive=!1,this.groups=[],o;this.isActive=!0,this.groups=i,this.#e.clear();for(const t of i){const e=t.columns[t.columns.length-1];e?.field&&this.#e.add(e.field)}return o}afterRender(){if(!this.isActive){const e=this.gridElement?.querySelector(".header"),r=e?.querySelector(".header-group-row");return void(r&&r.remove())}const e=this.gridElement?.querySelector(".header");if(!e)return;const r=e.querySelector(".header-group-row");r&&r.remove();const n=this.visibleColumns,s=t(n);if(0===s.length)return;this.#e.clear();const l=i(s,n);for(let t=0;t<s.length;t++){const e=s[t];if(String(e.id).startsWith("__implicit__")&&l.has(String(e.id)))continue;const r=e.columns[e.columns.length-1];r?.field&&t<s.length-1&&this.#e.add(r.field)}const d=function(e,r){if(0===e.length)return null;const t=document.createElement("div");t.className="header-group-row",t.setAttribute("role","row");const n=i(e,r);for(const i of e){const e=String(i.id),s=e.startsWith("__implicit__");if(s&&n.has(e))continue;const l=o(i,r);if(!l)continue;const[d,u]=l,c=u-d+1,g=s?"":i.label||i.id,a=document.createElement("div");a.className="cell header-group-cell",s&&a.classList.add("implicit-group"),a.setAttribute("data-group",e),a.style.gridColumn=`${d+1} / span ${c}`,a.textContent=g,t.appendChild(a)}return t}(s,n);if(d){d.classList.toggle("no-borders",!this.config.showGroupBorders);const r=e.querySelector(".header-row");r?e.insertBefore(d,r):e.appendChild(d)}const u=e.querySelector(".header-row");u&&(u.classList.toggle("no-group-borders",!this.config.showGroupBorders),function(e,r,t){if(!r.length||!e)return;const o=i(r,t),n=new Map;for(const i of r)if(!String(i.id).startsWith("__implicit__")||!o.has(String(i.id)))for(const e of i.columns)e.field&&n.set(e.field,i.id);const s=Array.from(e.querySelectorAll(".cell[data-field]"));s.forEach(e=>{const r=e.getAttribute("data-field")||"",t=n.get(r);t&&(e.classList.add("grouped"),e.getAttribute("data-group")||e.setAttribute("data-group",t))});for(const i of r){if(String(i.id).startsWith("__implicit__")&&o.has(String(i.id)))continue;const e=i.columns[i.columns.length-1],r=s.find(r=>r.getAttribute("data-field")===e.field);r&&r.classList.add("group-end")}}(u,s,n))}afterCellRender(e){this.isActive&&this.config.showGroupBorders&&e.cellElement.classList.toggle("group-end",this.#e.has(e.column.field))}isGroupingActive(){return this.isActive}getGroups(){return this.groups}getGroupColumns(e){const r=this.groups.find(r=>r.id===e);return r?r.columns:[]}refresh(){this.requestRender()}}e.GroupingColumnsPlugin=n,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=grouping-columns.umd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"grouping-columns.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/grouping-columns/grouping-columns.ts","../../../../../libs/grid/src/lib/plugins/grouping-columns/GroupingColumnsPlugin.ts"],"sourcesContent":["/**\n * Column Groups Core Logic\n *\n * Pure functions for computing and managing column header groups.\n */\n\n// Import types to enable module augmentation\nimport type { ColumnConfig } from '../../core/types';\nimport './types';\nimport type { ColumnGroup, ColumnGroupInternal } from './types';\n\n/**\n * Compute column groups from column configuration.\n * Handles explicit groups (via column.group) and creates implicit groups for ungrouped columns.\n *\n * @param columns - Array of column configurations\n * @returns Array of column groups, or empty if no meaningful groups\n */\nexport function computeColumnGroups<T>(columns: ColumnConfig<T>[]): ColumnGroup<T>[] {\n if (!columns.length) return [];\n\n const explicitMap = new Map<string, ColumnGroupInternal<T>>();\n const groupsOrdered: ColumnGroupInternal<T>[] = [];\n\n // Helper to push unnamed implicit group for a run of ungrouped columns\n const pushImplicit = (startIdx: number, cols: ColumnConfig<T>[]) => {\n if (!cols.length) return;\n // Merge with previous implicit group if adjacent to reduce noise\n const prev = groupsOrdered[groupsOrdered.length - 1];\n if (prev && prev.implicit && prev.firstIndex + prev.columns.length === startIdx) {\n prev.columns.push(...cols);\n return;\n }\n groupsOrdered.push({\n id: '__implicit__' + startIdx,\n label: undefined,\n columns: cols,\n firstIndex: startIdx,\n implicit: true,\n });\n };\n\n let run: ColumnConfig<T>[] = [];\n let runStart = 0;\n\n columns.forEach((col, idx) => {\n const g = col.group;\n if (!g) {\n if (run.length === 0) runStart = idx;\n run.push(col);\n return;\n }\n // Close any pending implicit run\n if (run.length) {\n pushImplicit(runStart, run.slice());\n run = [];\n }\n const id = typeof g === 'string' ? g : g.id;\n let group = explicitMap.get(id);\n if (!group) {\n group = {\n id,\n label: typeof g === 'string' ? undefined : g.label,\n columns: [],\n firstIndex: idx,\n };\n explicitMap.set(id, group);\n groupsOrdered.push(group);\n }\n group.columns.push(col);\n });\n\n // Trailing implicit run\n if (run.length) pushImplicit(runStart, run);\n\n // If we only have a single implicit group covering all columns, treat as no groups\n if (groupsOrdered.length === 1 && groupsOrdered[0].implicit && groupsOrdered[0].columns.length === columns.length) {\n return [];\n }\n\n return groupsOrdered as ColumnGroup<T>[];\n}\n\n/**\n * Apply CSS classes to header cells based on their group membership.\n *\n * @param headerRowEl - The header row element\n * @param groups - The computed column groups\n * @param columns - The column configurations\n */\nexport function applyGroupedHeaderCellClasses(\n headerRowEl: HTMLElement | null,\n groups: ColumnGroup[],\n columns: ColumnConfig[],\n): void {\n if (!groups.length || !headerRowEl) return;\n\n const fieldToGroup = new Map<string, string>();\n for (const g of groups) {\n for (const c of g.columns) {\n if (c.field) {\n fieldToGroup.set(c.field, g.id);\n }\n }\n }\n\n const headerCells = Array.from(headerRowEl.querySelectorAll('.cell[data-field]')) as HTMLElement[];\n headerCells.forEach((cell) => {\n const f = cell.getAttribute('data-field') || '';\n const gid = fieldToGroup.get(f);\n if (gid) {\n cell.classList.add('grouped');\n if (!cell.getAttribute('data-group')) {\n cell.setAttribute('data-group', gid);\n }\n }\n });\n\n // Mark group end cells for styling\n for (const g of groups) {\n const last = g.columns[g.columns.length - 1];\n const cell = headerCells.find((c) => c.getAttribute('data-field') === last.field);\n if (cell) cell.classList.add('group-end');\n }\n}\n\n/**\n * Build the group header row element.\n *\n * @param groups - The computed column groups\n * @param columns - The column configurations (final array including any plugin-added columns)\n * @returns The group header row element, or null if no groups\n */\nexport function buildGroupHeaderRow(groups: ColumnGroup[], columns: ColumnConfig[]): HTMLElement | null {\n if (groups.length === 0) return null;\n\n const groupRow = document.createElement('div');\n groupRow.className = 'header-group-row';\n groupRow.setAttribute('role', 'row');\n\n for (const g of groups) {\n // Always compute start index from the current columns array, not stored firstIndex.\n // This accounts for plugin-added columns (e.g., expander) that weren't present\n // when the groups were initially computed during processColumns.\n const firstGroupCol = g.columns[0];\n const startIndex = firstGroupCol ? columns.findIndex((c) => c.field === firstGroupCol.field) : -1;\n if (startIndex === -1) continue; // Group columns not in final column list\n\n const isImplicit = String(g.id).startsWith('__implicit__');\n const label = isImplicit ? '' : g.label || g.id;\n\n const cell = document.createElement('div');\n cell.className = 'cell header-group-cell';\n if (isImplicit) cell.classList.add('implicit-group');\n cell.setAttribute('data-group', String(g.id));\n cell.style.gridColumn = `${startIndex + 1} / span ${g.columns.length}`;\n cell.textContent = label;\n groupRow.appendChild(cell);\n }\n\n return groupRow;\n}\n\n/**\n * Check if any columns have group configuration.\n *\n * @param columns - The column configurations\n * @returns True if at least one column has a group\n */\nexport function hasColumnGroups(columns: ColumnConfig[]): boolean {\n return columns.some((col) => col.group != null);\n}\n\n/**\n * Get group ID for a specific column.\n *\n * @param column - The column configuration\n * @returns The group ID, or undefined if not grouped\n */\nexport function getColumnGroupId(column: ColumnConfig): string | undefined {\n const g = column.group;\n if (!g) return undefined;\n return typeof g === 'string' ? g : g.id;\n}\n","/**\n * Column Groups Plugin (Class-based)\n *\n * Enables multi-level column header grouping.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { AfterCellRenderContext, PluginManifest, PluginQuery } from '../../core/plugin/base-plugin';\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport type { ColumnGroupInfo } from '../visibility/types';\nimport {\n applyGroupedHeaderCellClasses,\n buildGroupHeaderRow,\n computeColumnGroups,\n hasColumnGroups,\n} from './grouping-columns';\nimport styles from './grouping-columns.css?inline';\nimport type { ColumnGroup, GroupingColumnsConfig } from './types';\n\n/**\n * Column Grouping Plugin for tbw-grid\n *\n * Enables visual grouping of columns under shared headers. Supports two approaches:\n * declarative `columnGroups` at the grid level, or inline `group` property on columns.\n *\n * ## Installation\n *\n * ```ts\n * import { GroupingColumnsPlugin } from '@toolbox-web/grid/plugins/grouping-columns';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `showGroupBorders` | `boolean` | `true` | Show borders between groups |\n * | `groupHeaderRenderer` | `function` | - | Custom renderer for group header content |\n *\n * ## Grid Config: `columnGroups`\n *\n * | Property | Type | Description |\n * |----------|------|-------------|\n * | `id` | `string` | Unique group identifier |\n * | `header` | `string` | Display label for the group header |\n * | `children` | `string[]` | Array of column field names in this group |\n *\n * ## Column Config: `group`\n *\n * | Type | Description |\n * |------|-------------|\n * | `string` | Simple group ID (used as both id and label) |\n * | `{ id: string; label?: string }` | Group object with explicit id and optional label |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `isGroupingActive` | `() => boolean` | Check if grouping is active |\n * | `getGroups` | `() => ColumnGroup[]` | Get all computed groups |\n * | `getGroupColumns` | `(groupId) => ColumnConfig[]` | Get columns in a specific group |\n * | `refresh` | `() => void` | Force refresh of column groups |\n *\n * @example Declarative columnGroups (Recommended)\n * ```ts\n * import '@toolbox-web/grid';\n * import { GroupingColumnsPlugin } from '@toolbox-web/grid/plugins/grouping-columns';\n *\n * grid.gridConfig = {\n * columnGroups: [\n * { id: 'personal', header: 'Personal Info', children: ['firstName', 'lastName', 'email'] },\n * { id: 'work', header: 'Work Info', children: ['department', 'title', 'salary'] },\n * ],\n * columns: [\n * { field: 'firstName', header: 'First Name' },\n * { field: 'lastName', header: 'Last Name' },\n * // ...\n * ],\n * plugins: [new GroupingColumnsPlugin()],\n * };\n * ```\n *\n * @example Inline group Property\n * ```ts\n * grid.gridConfig = {\n * columns: [\n * { field: 'firstName', header: 'First Name', group: { id: 'personal', label: 'Personal Info' } },\n * { field: 'lastName', header: 'Last Name', group: 'personal' }, // string shorthand\n * ],\n * plugins: [new GroupingColumnsPlugin()],\n * };\n * ```\n *\n * @see {@link GroupingColumnsConfig} for all configuration options\n * @see {@link ColumnGroup} for the group structure\n * @see {@link ReorderPlugin} for drag-to-reorder within groups\n *\n * @internal Extends BaseGridPlugin\n */\nexport class GroupingColumnsPlugin extends BaseGridPlugin<GroupingColumnsConfig> {\n /**\n * Plugin manifest - declares owned properties for configuration validation.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n ownedProperties: [\n {\n property: 'group',\n level: 'column',\n description: 'the \"group\" column property',\n },\n {\n property: 'columnGroups',\n level: 'config',\n description: 'the \"columnGroups\" config property',\n isUsed: (v) => Array.isArray(v) && v.length > 0,\n },\n ],\n queries: [{ type: 'getColumnGrouping', description: 'Returns column group metadata for the visibility panel' }],\n };\n\n /** @internal */\n readonly name = 'groupingColumns';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<GroupingColumnsConfig> {\n return {\n showGroupBorders: true,\n lockGroupOrder: false,\n };\n }\n\n // #region Internal State\n private groups: ColumnGroup[] = [];\n private isActive = false;\n /** Fields that are the last column in a group (for group-end border class). */\n #groupEndFields = new Set<string>();\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: import('../../core/plugin/base-plugin').GridElement): void {\n super.attach(grid);\n\n // Listen for cancelable column-move events to enforce group contiguity\n (grid as unknown as HTMLElement).addEventListener('column-move', this.#onColumnMove, {\n signal: this.disconnectSignal,\n });\n }\n\n /** @internal */\n override detach(): void {\n this.groups = [];\n this.isActive = false;\n this.#groupEndFields.clear();\n }\n\n // #region Column Move Guard\n\n /**\n * Handle the cancelable column-move event.\n * - When lockGroupOrder is enabled, prevents moves that would break group contiguity.\n * - Always refreshes #groupEndFields after a successful move so that afterCellRender\n * applies group-end borders to the correct (reordered) last column.\n */\n #onColumnMove = (e: Event): void => {\n if (!this.isActive) return;\n\n const event = e as CustomEvent<{ field: string; columnOrder: string[] }>;\n const { field, columnOrder } = event.detail;\n\n if (this.config.lockGroupOrder) {\n // Check ALL explicit groups — moving any column (grouped or not) could break contiguity\n for (const group of this.groups) {\n if (group.id.startsWith('__implicit__')) continue;\n if (!this.#isGroupContiguous(group, columnOrder)) {\n event.preventDefault();\n this.#flashHeaderCell(field);\n return;\n }\n }\n }\n\n // Recompute group-end fields based on proposed column order.\n // setColumnOrder runs synchronously after this handler returns,\n // but afterCellRender (which reads #groupEndFields) fires during\n // the subsequent refreshVirtualWindow. Precompute using the\n // proposed columnOrder so the borders are correct immediately.\n this.#recomputeGroupEndFields(columnOrder);\n };\n\n /**\n * Recompute which fields are group-end based on a column order.\n * The last field of each explicit group in the order gets the group-end class.\n */\n #recomputeGroupEndFields(columnOrder: string[]): void {\n this.#groupEndFields.clear();\n // Find the last field of each group (including implicit groups between explicit ones).\n // Skip the very last group overall — no adjacent group follows it, so no separator needed.\n const lastGroupEndField = this.#findLastGroupEndField(columnOrder);\n for (const group of this.groups) {\n const groupFields = new Set(group.columns.map((c) => c.field));\n // Walk the column order in reverse to find the last member of this group\n for (let i = columnOrder.length - 1; i >= 0; i--) {\n if (groupFields.has(columnOrder[i])) {\n const field = columnOrder[i];\n // Don't mark the last group's trailing field — nothing follows it\n if (field !== lastGroupEndField) {\n this.#groupEndFields.add(field);\n }\n break;\n }\n }\n }\n }\n\n /**\n * Find the trailing field of the last group in column order (to exclude from group-end marking).\n */\n #findLastGroupEndField(columnOrder: string[]): string | null {\n if (this.groups.length === 0) return null;\n // Determine which group contains the last field in column order\n for (let i = columnOrder.length - 1; i >= 0; i--) {\n const field = columnOrder[i];\n for (const group of this.groups) {\n if (group.columns.some((c) => c.field === field)) {\n // This group is the last in display order — find its last field\n const groupFields = new Set(group.columns.map((c) => c.field));\n for (let j = columnOrder.length - 1; j >= 0; j--) {\n if (groupFields.has(columnOrder[j])) return columnOrder[j];\n }\n }\n }\n }\n return null;\n }\n\n /**\n * Check if all columns in a group are contiguous in the proposed column order.\n */\n #isGroupContiguous(group: ColumnGroup, columnOrder: string[]): boolean {\n const indices = group.columns\n .map((c) => columnOrder.indexOf(c.field))\n .filter((i) => i !== -1)\n .sort((a, b) => a - b);\n if (indices.length <= 1) return true;\n return indices.length === indices[indices.length - 1] - indices[0] + 1;\n }\n\n /**\n * Flash the header cell with an error color to indicate a blocked move.\n */\n #flashHeaderCell(field: string): void {\n const headerCell = this.gridElement?.querySelector(\n `.header-row [part~=\"header-cell\"][data-field=\"${field}\"]`,\n ) as HTMLElement;\n if (!headerCell) return;\n\n headerCell.style.setProperty('--_flash-color', 'var(--tbw-color-error)');\n headerCell.animate(\n [{ backgroundColor: 'rgba(from var(--_flash-color) r g b / 30%)' }, { backgroundColor: 'transparent' }],\n { duration: 400, easing: 'ease-out' },\n );\n }\n // #endregion\n\n /** @internal */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'getColumnGrouping') {\n return this.#getStableColumnGrouping();\n }\n return undefined;\n }\n\n /**\n * Get stable column grouping info that includes ALL columns (visible and hidden).\n * Used by the visibility panel to maintain group structure regardless of visibility state.\n * Fields within each group are sorted by current display order.\n */\n #getStableColumnGrouping(): ColumnGroupInfo[] {\n let result: ColumnGroupInfo[];\n\n // 1. Prefer declarative columnGroups - always complete, visibility-independent\n const columnGroups = this.grid?.gridConfig?.columnGroups;\n if (columnGroups && Array.isArray(columnGroups) && columnGroups.length > 0) {\n result = columnGroups\n .filter((g) => g.children.length > 0)\n .map((g) => ({\n id: g.id,\n label: g.header,\n fields: [...g.children],\n }));\n } else if (this.isActive && this.groups.length > 0) {\n // 2. If active groups exist from processColumns, use them\n result = this.groups\n .filter((g) => !g.id.startsWith('__implicit__'))\n .map<ColumnGroupInfo>((g) => ({\n id: g.id,\n label: g.label ?? g.id,\n fields: g.columns.map((c) => c.field),\n }));\n\n // Also check hidden columns for inline group properties not in active groups\n const allCols = this.columns as ColumnConfig[];\n for (const col of allCols) {\n if ((col as any).hidden && col.group) {\n const gId = typeof col.group === 'string' ? col.group : col.group.id;\n const gLabel = typeof col.group === 'string' ? col.group : (col.group.label ?? col.group.id);\n const existing = result.find((g) => g.id === gId);\n if (existing) {\n if (!existing.fields.includes(col.field)) existing.fields.push(col.field);\n } else {\n result.push({ id: gId, label: gLabel, fields: [col.field] });\n }\n }\n }\n } else {\n // 3. Fall back: scan ALL columns (including hidden) for inline group properties\n const allCols = this.columns as ColumnConfig[];\n const groupMap = new Map<string, ColumnGroupInfo>();\n for (const col of allCols) {\n if (!col.group) continue;\n const gId = typeof col.group === 'string' ? col.group : col.group.id;\n const gLabel = typeof col.group === 'string' ? col.group : (col.group.label ?? col.group.id);\n const existing = groupMap.get(gId);\n if (existing) {\n if (!existing.fields.includes(col.field)) existing.fields.push(col.field);\n } else {\n groupMap.set(gId, { id: gId, label: gLabel, fields: [col.field] });\n }\n }\n result = Array.from(groupMap.values());\n }\n\n // Sort fields within each group by current display order so consumers\n // (e.g. the visibility panel) render columns in their reordered positions.\n const displayOrder = this.grid?.getColumnOrder();\n if (displayOrder && displayOrder.length > 0) {\n const orderIndex = new Map(displayOrder.map((f, i) => [f, i]));\n for (const group of result) {\n group.fields.sort((a, b) => (orderIndex.get(a) ?? Infinity) - (orderIndex.get(b) ?? Infinity));\n }\n }\n\n return result;\n }\n // #endregion\n\n // #region Static Detection\n\n /**\n * Auto-detect column groups from column configuration.\n * Detects both inline `column.group` properties and declarative `columnGroups` config.\n */\n static detect(rows: readonly any[], config: any): boolean {\n // Check for declarative columnGroups in config\n if (config?.columnGroups && Array.isArray(config.columnGroups) && config.columnGroups.length > 0) {\n return true;\n }\n // Check for inline group properties on columns\n const columns = config?.columns;\n if (!Array.isArray(columns)) return false;\n return hasColumnGroups(columns);\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n // First, check if gridConfig.columnGroups is defined and apply to columns\n const columnGroups = this.grid?.gridConfig?.columnGroups;\n let processedColumns: ColumnConfig[];\n\n if (columnGroups && Array.isArray(columnGroups) && columnGroups.length > 0) {\n // Build a map of field -> group info from the declarative config\n const fieldToGroup = new Map<string, { id: string; label: string }>();\n for (const group of columnGroups) {\n for (const field of group.children) {\n fieldToGroup.set(field, { id: group.id, label: group.header });\n }\n }\n\n // Apply group property to columns that don't already have one\n processedColumns = columns.map((col) => {\n const groupInfo = fieldToGroup.get(col.field);\n if (groupInfo && !col.group) {\n return { ...col, group: groupInfo };\n }\n return col;\n });\n } else {\n processedColumns = [...columns];\n }\n\n // Compute groups from column definitions (now including applied groups)\n const groups = computeColumnGroups(processedColumns);\n\n if (groups.length === 0) {\n this.isActive = false;\n this.groups = [];\n return processedColumns;\n }\n\n this.isActive = true;\n this.groups = groups;\n\n // Pre-compute group-end fields for the afterCellRender hook\n this.#groupEndFields.clear();\n for (const g of groups) {\n const lastCol = g.columns[g.columns.length - 1];\n if (lastCol?.field) {\n this.#groupEndFields.add(lastCol.field);\n }\n }\n\n // Return columns with group info applied\n return processedColumns;\n }\n\n /** @internal */\n override afterRender(): void {\n if (!this.isActive) {\n // Remove any existing group header\n const header = this.gridElement?.querySelector('.header');\n const existingGroupRow = header?.querySelector('.header-group-row');\n if (existingGroupRow) existingGroupRow.remove();\n return;\n }\n\n const header = this.gridElement?.querySelector('.header');\n if (!header) return;\n\n // Remove existing group row if present\n const existingGroupRow = header.querySelector('.header-group-row');\n if (existingGroupRow) existingGroupRow.remove();\n\n // Recompute groups from visible columns only (hidden columns have no CSS grid track).\n // This also picks up any plugin-added columns (e.g. expander) that weren't present\n // during processColumns.\n const finalColumns = this.visibleColumns as ColumnConfig[];\n const groups = computeColumnGroups(finalColumns);\n if (groups.length === 0) return;\n\n // Keep #groupEndFields in sync for afterCellRender (covers scheduler-driven renders)\n this.#groupEndFields.clear();\n for (let gi = 0; gi < groups.length; gi++) {\n const g = groups[gi];\n const lastCol = g.columns[g.columns.length - 1];\n // Don't mark the last group — no adjacent group follows it\n if (lastCol?.field && gi < groups.length - 1) {\n this.#groupEndFields.add(lastCol.field);\n }\n }\n\n // Build and insert group header row\n const groupRow = buildGroupHeaderRow(groups, finalColumns);\n if (groupRow) {\n // Toggle border visibility class\n groupRow.classList.toggle('no-borders', !this.config.showGroupBorders);\n\n const headerRow = header.querySelector('.header-row');\n if (headerRow) {\n header.insertBefore(groupRow, headerRow);\n } else {\n header.appendChild(groupRow);\n }\n }\n\n // Apply classes to header cells\n const headerRow = header.querySelector('.header-row') as HTMLElement;\n if (headerRow) {\n // Toggle border visibility on header cells\n headerRow.classList.toggle('no-group-borders', !this.config.showGroupBorders);\n applyGroupedHeaderCellClasses(headerRow, groups, finalColumns);\n }\n }\n\n /**\n * Apply group-end class to individual cells during render and scroll.\n * This is more efficient than querySelectorAll in afterRender and ensures\n * cells recycled during scroll also get the class applied.\n * @internal\n */\n override afterCellRender(context: AfterCellRenderContext): void {\n if (!this.isActive || !this.config.showGroupBorders) return;\n context.cellElement.classList.toggle('group-end', this.#groupEndFields.has(context.column.field));\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Check if column groups are active.\n * @returns Whether grouping is active\n */\n isGroupingActive(): boolean {\n return this.isActive;\n }\n\n /**\n * Get the computed column groups.\n * @returns Array of column groups\n */\n getGroups(): ColumnGroup[] {\n return this.groups;\n }\n\n /**\n * Get columns in a specific group.\n * @param groupId - The group ID to find\n * @returns Array of columns in the group\n */\n getGroupColumns(groupId: string): ColumnConfig[] {\n const group = this.groups.find((g) => g.id === groupId);\n return group ? group.columns : [];\n }\n\n /**\n * Refresh column groups (recompute from current columns).\n */\n refresh(): void {\n this.requestRender();\n }\n // #endregion\n}\n"],"names":["computeColumnGroups","columns","length","explicitMap","Map","groupsOrdered","pushImplicit","startIdx","cols","prev","implicit","firstIndex","push","id","label","run","runStart","forEach","col","idx","g","group","slice","get","set","GroupingColumnsPlugin","BaseGridPlugin","static","ownedProperties","property","level","description","isUsed","v","Array","isArray","queries","type","name","styles","defaultConfig","showGroupBorders","lockGroupOrder","groups","isActive","groupEndFields","Set","attach","grid","super","addEventListener","this","onColumnMove","signal","disconnectSignal","detach","clear","e","event","field","columnOrder","detail","config","startsWith","isGroupContiguous","preventDefault","flashHeaderCell","recomputeGroupEndFields","lastGroupEndField","findLastGroupEndField","groupFields","map","c","i","has","add","some","j","indices","indexOf","filter","sort","a","b","headerCell","gridElement","querySelector","style","setProperty","animate","backgroundColor","duration","easing","handleQuery","query","getStableColumnGrouping","result","columnGroups","gridConfig","children","header","fields","allCols","hidden","gId","gLabel","existing","find","includes","groupMap","from","values","displayOrder","getColumnOrder","orderIndex","f","Infinity","detect","rows","hasColumnGroups","processColumns","processedColumns","fieldToGroup","groupInfo","lastCol","afterRender","existingGroupRow","remove","finalColumns","visibleColumns","gi","groupRow","document","createElement","className","setAttribute","firstGroupCol","startIndex","findIndex","isImplicit","String","cell","classList","gridColumn","textContent","appendChild","buildGroupHeaderRow","toggle","headerRow","insertBefore","headerRowEl","headerCells","querySelectorAll","getAttribute","gid","last","applyGroupedHeaderCellClasses","afterCellRender","context","cellElement","column","isGroupingActive","getGroups","getGroupColumns","groupId","refresh","requestRender"],"mappings":"yVAkBO,SAASA,EAAuBC,GACrC,IAAKA,EAAQC,OAAQ,MAAO,GAE5B,MAAMC,MAAkBC,IAClBC,EAA0C,GAG1CC,EAAe,CAACC,EAAkBC,KACtC,IAAKA,EAAKN,OAAQ,OAElB,MAAMO,EAAOJ,EAAcA,EAAcH,OAAS,GAC9CO,GAAQA,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hG,OACvEkF,GAAMA,EAAKC,UAAUnE,IAAI,YAC/B,CACF,CCkWMiF,CAA8BR,EAAWzG,GAE7C,CAQS,eAAAkH,CAAgBC,GAClB3G,KAAKP,UAAaO,KAAKW,OAAOrB,kBACnCqH,EAAQC,YAAYjB,UAAUK,OAAO,YAAahG,MAAKN,EAAgB6B,IAAIoF,EAAQE,OAAOrG,OAC5F,CASA,gBAAAsG,GACE,OAAO9G,KAAKP,QACd,CAMA,SAAAsH,GACE,OAAO/G,KAAKR,MACd,CAOA,eAAAwH,CAAgBC,GACd,MAAM/I,EAAQ8B,KAAKR,OAAOgE,KAAMvF,GAAMA,EAAEP,KAAOuJ,GAC/C,OAAO/I,EAAQA,EAAMpB,QAAU,EACjC,CAKA,OAAAoK,GACElH,KAAKmH,eACP"}
|
|
1
|
+
{"version":3,"file":"grouping-columns.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/grouping-columns/grouping-columns.ts","../../../../../libs/grid/src/lib/plugins/grouping-columns/GroupingColumnsPlugin.ts"],"sourcesContent":["/**\n * Column Groups Core Logic\n *\n * Pure functions for computing and managing column header groups.\n */\n\n// Import types to enable module augmentation\nimport type { ColumnConfig } from '../../core/types';\nimport './types';\nimport type { ColumnGroup, ColumnGroupInternal } from './types';\n\n/**\n * Compute column groups from column configuration.\n * Handles explicit groups (via column.group) and creates implicit groups for ungrouped columns.\n *\n * @param columns - Array of column configurations\n * @returns Array of column groups, or empty if no meaningful groups\n */\nexport function computeColumnGroups<T>(columns: ColumnConfig<T>[]): ColumnGroup<T>[] {\n if (!columns.length) return [];\n\n const explicitMap = new Map<string, ColumnGroupInternal<T>>();\n const groupsOrdered: ColumnGroupInternal<T>[] = [];\n\n // Helper to push unnamed implicit group for a run of ungrouped columns\n const pushImplicit = (startIdx: number, cols: ColumnConfig<T>[]) => {\n if (!cols.length) return;\n // Merge with previous implicit group if adjacent to reduce noise\n const prev = groupsOrdered[groupsOrdered.length - 1];\n if (prev && prev.implicit && prev.firstIndex + prev.columns.length === startIdx) {\n prev.columns.push(...cols);\n return;\n }\n groupsOrdered.push({\n id: '__implicit__' + startIdx,\n label: undefined,\n columns: cols,\n firstIndex: startIdx,\n implicit: true,\n });\n };\n\n let run: ColumnConfig<T>[] = [];\n let runStart = 0;\n\n columns.forEach((col, idx) => {\n const g = col.group;\n if (!g) {\n if (run.length === 0) runStart = idx;\n run.push(col);\n return;\n }\n // Close any pending implicit run\n if (run.length) {\n pushImplicit(runStart, run.slice());\n run = [];\n }\n const id = typeof g === 'string' ? g : g.id;\n let group = explicitMap.get(id);\n if (!group) {\n group = {\n id,\n label: typeof g === 'string' ? undefined : g.label,\n columns: [],\n firstIndex: idx,\n };\n explicitMap.set(id, group);\n groupsOrdered.push(group);\n }\n group.columns.push(col);\n });\n\n // Trailing implicit run\n if (run.length) pushImplicit(runStart, run);\n\n // If we only have a single implicit group covering all columns, treat as no groups\n if (groupsOrdered.length === 1 && groupsOrdered[0].implicit && groupsOrdered[0].columns.length === columns.length) {\n return [];\n }\n\n return groupsOrdered as ColumnGroup<T>[];\n}\n\n/**\n * Apply CSS classes to header cells based on their group membership.\n *\n * @param headerRowEl - The header row element\n * @param groups - The computed column groups\n * @param columns - The column configurations\n */\nexport function applyGroupedHeaderCellClasses(\n headerRowEl: HTMLElement | null,\n groups: ColumnGroup[],\n columns: ColumnConfig[],\n): void {\n if (!groups.length || !headerRowEl) return;\n\n const embedded = findEmbeddedImplicitGroups(groups, columns);\n\n const fieldToGroup = new Map<string, string>();\n for (const g of groups) {\n // Skip embedded implicit groups — their columns inherit the enclosing explicit group\n if (String(g.id).startsWith('__implicit__') && embedded.has(String(g.id))) continue;\n for (const c of g.columns) {\n if (c.field) {\n fieldToGroup.set(c.field, g.id);\n }\n }\n }\n\n const headerCells = Array.from(headerRowEl.querySelectorAll('.cell[data-field]')) as HTMLElement[];\n headerCells.forEach((cell) => {\n const f = cell.getAttribute('data-field') || '';\n const gid = fieldToGroup.get(f);\n if (gid) {\n cell.classList.add('grouped');\n if (!cell.getAttribute('data-group')) {\n cell.setAttribute('data-group', gid);\n }\n }\n });\n\n // Mark group end cells for styling (skip embedded implicit groups)\n for (const g of groups) {\n if (String(g.id).startsWith('__implicit__') && embedded.has(String(g.id))) continue;\n const last = g.columns[g.columns.length - 1];\n const cell = headerCells.find((c) => c.getAttribute('data-field') === last.field);\n if (cell) cell.classList.add('group-end');\n }\n}\n\n/**\n * Compute the grid range [start, end] for a group based on its first and last\n * column positions in the final columns array.\n */\nfunction computeGroupGridRange(group: ColumnGroup, columns: ColumnConfig[]): [number, number] | null {\n const first = group.columns[0];\n const last = group.columns[group.columns.length - 1];\n const start = first ? columns.findIndex((c) => c.field === first.field) : -1;\n const end = last ? columns.findIndex((c) => c.field === last.field) : -1;\n return start !== -1 && end !== -1 ? [start, end] : null;\n}\n\n/**\n * Find implicit groups whose column range falls entirely within an explicit\n * group's range (e.g. a utility column inserted between members of the same group).\n *\n * @returns Set of implicit group IDs that are visually embedded.\n */\nexport function findEmbeddedImplicitGroups(groups: ColumnGroup[], columns: ColumnConfig[]): Set<string> {\n const embedded = new Set<string>();\n\n // Collect ranges for explicit groups\n const explicitRanges: [number, number][] = [];\n for (const g of groups) {\n if (String(g.id).startsWith('__implicit__')) continue;\n const range = computeGroupGridRange(g, columns);\n if (range) explicitRanges.push(range);\n }\n\n // Check each implicit group\n for (const g of groups) {\n if (!String(g.id).startsWith('__implicit__')) continue;\n const range = computeGroupGridRange(g, columns);\n if (!range) continue;\n const [iStart, iEnd] = range;\n if (explicitRanges.some(([eStart, eEnd]) => iStart >= eStart && iEnd <= eEnd)) {\n embedded.add(String(g.id));\n }\n }\n\n return embedded;\n}\n\n/**\n * Build the group header row element.\n *\n * @param groups - The computed column groups\n * @param columns - The column configurations (final array including any plugin-added columns)\n * @returns The group header row element, or null if no groups\n */\nexport function buildGroupHeaderRow(groups: ColumnGroup[], columns: ColumnConfig[]): HTMLElement | null {\n if (groups.length === 0) return null;\n\n const groupRow = document.createElement('div');\n groupRow.className = 'header-group-row';\n groupRow.setAttribute('role', 'row');\n\n const embedded = findEmbeddedImplicitGroups(groups, columns);\n\n for (const g of groups) {\n const gid = String(g.id);\n const isImplicit = gid.startsWith('__implicit__');\n\n // Skip implicit groups that are visually embedded within an explicit group\n if (isImplicit && embedded.has(gid)) continue;\n\n // Compute actual range from first to last member in the final columns array.\n // This correctly spans over any interleaved utility columns (e.g. checkbox).\n const range = computeGroupGridRange(g, columns);\n if (!range) continue;\n const [startIndex, endIndex] = range;\n const span = endIndex - startIndex + 1;\n\n const label = isImplicit ? '' : g.label || g.id;\n\n const cell = document.createElement('div');\n cell.className = 'cell header-group-cell';\n if (isImplicit) cell.classList.add('implicit-group');\n cell.setAttribute('data-group', gid);\n cell.style.gridColumn = `${startIndex + 1} / span ${span}`;\n cell.textContent = label;\n groupRow.appendChild(cell);\n }\n\n return groupRow;\n}\n\n/**\n * Check if any columns have group configuration.\n *\n * @param columns - The column configurations\n * @returns True if at least one column has a group\n */\nexport function hasColumnGroups(columns: ColumnConfig[]): boolean {\n return columns.some((col) => col.group != null);\n}\n\n/**\n * Get group ID for a specific column.\n *\n * @param column - The column configuration\n * @returns The group ID, or undefined if not grouped\n */\nexport function getColumnGroupId(column: ColumnConfig): string | undefined {\n const g = column.group;\n if (!g) return undefined;\n return typeof g === 'string' ? g : g.id;\n}\n","/**\n * Column Groups Plugin (Class-based)\n *\n * Enables multi-level column header grouping.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { AfterCellRenderContext, PluginManifest, PluginQuery } from '../../core/plugin/base-plugin';\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport type { ColumnGroupInfo } from '../visibility/types';\nimport {\n applyGroupedHeaderCellClasses,\n buildGroupHeaderRow,\n computeColumnGroups,\n findEmbeddedImplicitGroups,\n hasColumnGroups,\n} from './grouping-columns';\nimport styles from './grouping-columns.css?inline';\nimport type { ColumnGroup, GroupingColumnsConfig } from './types';\n\n/**\n * Column Grouping Plugin for tbw-grid\n *\n * Enables visual grouping of columns under shared headers. Supports two approaches:\n * declarative `columnGroups` at the grid level, or inline `group` property on columns.\n *\n * ## Installation\n *\n * ```ts\n * import { GroupingColumnsPlugin } from '@toolbox-web/grid/plugins/grouping-columns';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `showGroupBorders` | `boolean` | `true` | Show borders between groups |\n * | `groupHeaderRenderer` | `function` | - | Custom renderer for group header content |\n *\n * ## Grid Config: `columnGroups`\n *\n * | Property | Type | Description |\n * |----------|------|-------------|\n * | `id` | `string` | Unique group identifier |\n * | `header` | `string` | Display label for the group header |\n * | `children` | `string[]` | Array of column field names in this group |\n *\n * ## Column Config: `group`\n *\n * | Type | Description |\n * |------|-------------|\n * | `string` | Simple group ID (used as both id and label) |\n * | `{ id: string; label?: string }` | Group object with explicit id and optional label |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `isGroupingActive` | `() => boolean` | Check if grouping is active |\n * | `getGroups` | `() => ColumnGroup[]` | Get all computed groups |\n * | `getGroupColumns` | `(groupId) => ColumnConfig[]` | Get columns in a specific group |\n * | `refresh` | `() => void` | Force refresh of column groups |\n *\n * @example Declarative columnGroups (Recommended)\n * ```ts\n * import '@toolbox-web/grid';\n * import { GroupingColumnsPlugin } from '@toolbox-web/grid/plugins/grouping-columns';\n *\n * grid.gridConfig = {\n * columnGroups: [\n * { id: 'personal', header: 'Personal Info', children: ['firstName', 'lastName', 'email'] },\n * { id: 'work', header: 'Work Info', children: ['department', 'title', 'salary'] },\n * ],\n * columns: [\n * { field: 'firstName', header: 'First Name' },\n * { field: 'lastName', header: 'Last Name' },\n * // ...\n * ],\n * plugins: [new GroupingColumnsPlugin()],\n * };\n * ```\n *\n * @example Inline group Property\n * ```ts\n * grid.gridConfig = {\n * columns: [\n * { field: 'firstName', header: 'First Name', group: { id: 'personal', label: 'Personal Info' } },\n * { field: 'lastName', header: 'Last Name', group: 'personal' }, // string shorthand\n * ],\n * plugins: [new GroupingColumnsPlugin()],\n * };\n * ```\n *\n * @see {@link GroupingColumnsConfig} for all configuration options\n * @see {@link ColumnGroup} for the group structure\n * @see {@link ReorderPlugin} for drag-to-reorder within groups\n *\n * @internal Extends BaseGridPlugin\n */\nexport class GroupingColumnsPlugin extends BaseGridPlugin<GroupingColumnsConfig> {\n /**\n * Plugin manifest - declares owned properties for configuration validation.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n ownedProperties: [\n {\n property: 'group',\n level: 'column',\n description: 'the \"group\" column property',\n },\n {\n property: 'columnGroups',\n level: 'config',\n description: 'the \"columnGroups\" config property',\n isUsed: (v) => Array.isArray(v) && v.length > 0,\n },\n ],\n queries: [{ type: 'getColumnGrouping', description: 'Returns column group metadata for the visibility panel' }],\n };\n\n /** @internal */\n readonly name = 'groupingColumns';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<GroupingColumnsConfig> {\n return {\n showGroupBorders: true,\n lockGroupOrder: false,\n };\n }\n\n // #region Internal State\n private groups: ColumnGroup[] = [];\n private isActive = false;\n /** Fields that are the last column in a group (for group-end border class). */\n #groupEndFields = new Set<string>();\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: import('../../core/plugin/base-plugin').GridElement): void {\n super.attach(grid);\n\n // Listen for cancelable column-move events to enforce group contiguity\n (grid as unknown as HTMLElement).addEventListener('column-move', this.#onColumnMove, {\n signal: this.disconnectSignal,\n });\n }\n\n /** @internal */\n override detach(): void {\n this.groups = [];\n this.isActive = false;\n this.#groupEndFields.clear();\n }\n\n // #region Column Move Guard\n\n /**\n * Handle the cancelable column-move event.\n * - When lockGroupOrder is enabled, prevents moves that would break group contiguity.\n * - Always refreshes #groupEndFields after a successful move so that afterCellRender\n * applies group-end borders to the correct (reordered) last column.\n */\n #onColumnMove = (e: Event): void => {\n if (!this.isActive) return;\n\n const event = e as CustomEvent<{ field: string; columnOrder: string[] }>;\n const { field, columnOrder } = event.detail;\n\n if (this.config.lockGroupOrder) {\n // Check ALL explicit groups — moving any column (grouped or not) could break contiguity\n for (const group of this.groups) {\n if (group.id.startsWith('__implicit__')) continue;\n if (!this.#isGroupContiguous(group, columnOrder)) {\n event.preventDefault();\n this.#flashHeaderCell(field);\n return;\n }\n }\n }\n\n // Recompute group-end fields based on proposed column order.\n // setColumnOrder runs synchronously after this handler returns,\n // but afterCellRender (which reads #groupEndFields) fires during\n // the subsequent refreshVirtualWindow. Precompute using the\n // proposed columnOrder so the borders are correct immediately.\n this.#recomputeGroupEndFields(columnOrder);\n };\n\n /**\n * Recompute which fields are group-end based on a column order.\n * The last field of each explicit group in the order gets the group-end class.\n */\n #recomputeGroupEndFields(columnOrder: string[]): void {\n this.#groupEndFields.clear();\n // Find the last field of each group (including implicit groups between explicit ones).\n // Skip the very last group overall — no adjacent group follows it, so no separator needed.\n const lastGroupEndField = this.#findLastGroupEndField(columnOrder);\n for (const group of this.groups) {\n const groupFields = new Set(group.columns.map((c) => c.field));\n // Walk the column order in reverse to find the last member of this group\n for (let i = columnOrder.length - 1; i >= 0; i--) {\n if (groupFields.has(columnOrder[i])) {\n const field = columnOrder[i];\n // Don't mark the last group's trailing field — nothing follows it\n if (field !== lastGroupEndField) {\n this.#groupEndFields.add(field);\n }\n break;\n }\n }\n }\n }\n\n /**\n * Find the trailing field of the last group in column order (to exclude from group-end marking).\n */\n #findLastGroupEndField(columnOrder: string[]): string | null {\n if (this.groups.length === 0) return null;\n // Determine which group contains the last field in column order\n for (let i = columnOrder.length - 1; i >= 0; i--) {\n const field = columnOrder[i];\n for (const group of this.groups) {\n if (group.columns.some((c) => c.field === field)) {\n // This group is the last in display order — find its last field\n const groupFields = new Set(group.columns.map((c) => c.field));\n for (let j = columnOrder.length - 1; j >= 0; j--) {\n if (groupFields.has(columnOrder[j])) return columnOrder[j];\n }\n }\n }\n }\n return null;\n }\n\n /**\n * Check if all columns in a group are contiguous in the proposed column order.\n */\n #isGroupContiguous(group: ColumnGroup, columnOrder: string[]): boolean {\n const indices = group.columns\n .map((c) => columnOrder.indexOf(c.field))\n .filter((i) => i !== -1)\n .sort((a, b) => a - b);\n if (indices.length <= 1) return true;\n return indices.length === indices[indices.length - 1] - indices[0] + 1;\n }\n\n /**\n * Flash the header cell with an error color to indicate a blocked move.\n */\n #flashHeaderCell(field: string): void {\n const headerCell = this.gridElement?.querySelector(\n `.header-row [part~=\"header-cell\"][data-field=\"${field}\"]`,\n ) as HTMLElement;\n if (!headerCell) return;\n\n headerCell.style.setProperty('--_flash-color', 'var(--tbw-color-error)');\n headerCell.animate(\n [{ backgroundColor: 'rgba(from var(--_flash-color) r g b / 30%)' }, { backgroundColor: 'transparent' }],\n { duration: 400, easing: 'ease-out' },\n );\n }\n // #endregion\n\n /** @internal */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'getColumnGrouping') {\n return this.#getStableColumnGrouping();\n }\n return undefined;\n }\n\n /**\n * Get stable column grouping info that includes ALL columns (visible and hidden).\n * Used by the visibility panel to maintain group structure regardless of visibility state.\n * Fields within each group are sorted by current display order.\n */\n #getStableColumnGrouping(): ColumnGroupInfo[] {\n let result: ColumnGroupInfo[];\n\n // 1. Prefer declarative columnGroups - always complete, visibility-independent\n const columnGroups = this.grid?.gridConfig?.columnGroups;\n if (columnGroups && Array.isArray(columnGroups) && columnGroups.length > 0) {\n result = columnGroups\n .filter((g) => g.children.length > 0)\n .map((g) => ({\n id: g.id,\n label: g.header,\n fields: [...g.children],\n }));\n } else if (this.isActive && this.groups.length > 0) {\n // 2. If active groups exist from processColumns, use them\n result = this.groups\n .filter((g) => !g.id.startsWith('__implicit__'))\n .map<ColumnGroupInfo>((g) => ({\n id: g.id,\n label: g.label ?? g.id,\n fields: g.columns.map((c) => c.field),\n }));\n\n // Also check hidden columns for inline group properties not in active groups\n const allCols = this.columns as ColumnConfig[];\n for (const col of allCols) {\n if ((col as any).hidden && col.group) {\n const gId = typeof col.group === 'string' ? col.group : col.group.id;\n const gLabel = typeof col.group === 'string' ? col.group : (col.group.label ?? col.group.id);\n const existing = result.find((g) => g.id === gId);\n if (existing) {\n if (!existing.fields.includes(col.field)) existing.fields.push(col.field);\n } else {\n result.push({ id: gId, label: gLabel, fields: [col.field] });\n }\n }\n }\n } else {\n // 3. Fall back: scan ALL columns (including hidden) for inline group properties\n const allCols = this.columns as ColumnConfig[];\n const groupMap = new Map<string, ColumnGroupInfo>();\n for (const col of allCols) {\n if (!col.group) continue;\n const gId = typeof col.group === 'string' ? col.group : col.group.id;\n const gLabel = typeof col.group === 'string' ? col.group : (col.group.label ?? col.group.id);\n const existing = groupMap.get(gId);\n if (existing) {\n if (!existing.fields.includes(col.field)) existing.fields.push(col.field);\n } else {\n groupMap.set(gId, { id: gId, label: gLabel, fields: [col.field] });\n }\n }\n result = Array.from(groupMap.values());\n }\n\n // Sort fields within each group by current display order so consumers\n // (e.g. the visibility panel) render columns in their reordered positions.\n const displayOrder = this.grid?.getColumnOrder();\n if (displayOrder && displayOrder.length > 0) {\n const orderIndex = new Map(displayOrder.map((f, i) => [f, i]));\n for (const group of result) {\n group.fields.sort((a, b) => (orderIndex.get(a) ?? Infinity) - (orderIndex.get(b) ?? Infinity));\n }\n }\n\n return result;\n }\n // #endregion\n\n // #region Static Detection\n\n /**\n * Auto-detect column groups from column configuration.\n * Detects both inline `column.group` properties and declarative `columnGroups` config.\n */\n static detect(rows: readonly any[], config: any): boolean {\n // Check for declarative columnGroups in config\n if (config?.columnGroups && Array.isArray(config.columnGroups) && config.columnGroups.length > 0) {\n return true;\n }\n // Check for inline group properties on columns\n const columns = config?.columns;\n if (!Array.isArray(columns)) return false;\n return hasColumnGroups(columns);\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n // First, check if gridConfig.columnGroups is defined and apply to columns\n const columnGroups = this.grid?.gridConfig?.columnGroups;\n let processedColumns: ColumnConfig[];\n\n if (columnGroups && Array.isArray(columnGroups) && columnGroups.length > 0) {\n // Build a map of field -> group info from the declarative config\n const fieldToGroup = new Map<string, { id: string; label: string }>();\n for (const group of columnGroups) {\n for (const field of group.children) {\n fieldToGroup.set(field, { id: group.id, label: group.header });\n }\n }\n\n // Apply group property to columns that don't already have one\n processedColumns = columns.map((col) => {\n const groupInfo = fieldToGroup.get(col.field);\n if (groupInfo && !col.group) {\n return { ...col, group: groupInfo };\n }\n return col;\n });\n } else {\n processedColumns = [...columns];\n }\n\n // Compute groups from column definitions (now including applied groups)\n const groups = computeColumnGroups(processedColumns);\n\n if (groups.length === 0) {\n this.isActive = false;\n this.groups = [];\n return processedColumns;\n }\n\n this.isActive = true;\n this.groups = groups;\n\n // Pre-compute group-end fields for the afterCellRender hook\n this.#groupEndFields.clear();\n for (const g of groups) {\n const lastCol = g.columns[g.columns.length - 1];\n if (lastCol?.field) {\n this.#groupEndFields.add(lastCol.field);\n }\n }\n\n // Return columns with group info applied\n return processedColumns;\n }\n\n /** @internal */\n override afterRender(): void {\n if (!this.isActive) {\n // Remove any existing group header\n const header = this.gridElement?.querySelector('.header');\n const existingGroupRow = header?.querySelector('.header-group-row');\n if (existingGroupRow) existingGroupRow.remove();\n return;\n }\n\n const header = this.gridElement?.querySelector('.header');\n if (!header) return;\n\n // Remove existing group row if present\n const existingGroupRow = header.querySelector('.header-group-row');\n if (existingGroupRow) existingGroupRow.remove();\n\n // Recompute groups from visible columns only (hidden columns have no CSS grid track).\n // This also picks up any plugin-added columns (e.g. expander) that weren't present\n // during processColumns.\n const finalColumns = this.visibleColumns as ColumnConfig[];\n const groups = computeColumnGroups(finalColumns);\n if (groups.length === 0) return;\n\n // Keep #groupEndFields in sync for afterCellRender (covers scheduler-driven renders)\n this.#groupEndFields.clear();\n const embedded = findEmbeddedImplicitGroups(groups, finalColumns);\n for (let gi = 0; gi < groups.length; gi++) {\n const g = groups[gi];\n // Skip embedded implicit groups (e.g. checkbox column within a pinned group)\n if (String(g.id).startsWith('__implicit__') && embedded.has(String(g.id))) continue;\n const lastCol = g.columns[g.columns.length - 1];\n // Don't mark the last group — no adjacent group follows it\n if (lastCol?.field && gi < groups.length - 1) {\n this.#groupEndFields.add(lastCol.field);\n }\n }\n\n // Build and insert group header row\n const groupRow = buildGroupHeaderRow(groups, finalColumns);\n if (groupRow) {\n // Toggle border visibility class\n groupRow.classList.toggle('no-borders', !this.config.showGroupBorders);\n\n const headerRow = header.querySelector('.header-row');\n if (headerRow) {\n header.insertBefore(groupRow, headerRow);\n } else {\n header.appendChild(groupRow);\n }\n }\n\n // Apply classes to header cells\n const headerRow = header.querySelector('.header-row') as HTMLElement;\n if (headerRow) {\n // Toggle border visibility on header cells\n headerRow.classList.toggle('no-group-borders', !this.config.showGroupBorders);\n applyGroupedHeaderCellClasses(headerRow, groups, finalColumns);\n }\n }\n\n /**\n * Apply group-end class to individual cells during render and scroll.\n * This is more efficient than querySelectorAll in afterRender and ensures\n * cells recycled during scroll also get the class applied.\n * @internal\n */\n override afterCellRender(context: AfterCellRenderContext): void {\n if (!this.isActive || !this.config.showGroupBorders) return;\n context.cellElement.classList.toggle('group-end', this.#groupEndFields.has(context.column.field));\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Check if column groups are active.\n * @returns Whether grouping is active\n */\n isGroupingActive(): boolean {\n return this.isActive;\n }\n\n /**\n * Get the computed column groups.\n * @returns Array of column groups\n */\n getGroups(): ColumnGroup[] {\n return this.groups;\n }\n\n /**\n * Get columns in a specific group.\n * @param groupId - The group ID to find\n * @returns Array of columns in the group\n */\n getGroupColumns(groupId: string): ColumnConfig[] {\n const group = this.groups.find((g) => g.id === groupId);\n return group ? group.columns : [];\n }\n\n /**\n * Refresh column groups (recompute from current columns).\n */\n refresh(): void {\n this.requestRender();\n }\n // #endregion\n}\n"],"names":["computeColumnGroups","columns","length","explicitMap","Map","groupsOrdered","pushImplicit","startIdx","cols","prev","implicit","firstIndex","push","id","label","run","runStart","forEach","col","idx","g","group","slice","get","set","computeGroupGridRange","first","last","start","findIndex","c","field","end","findEmbeddedImplicitGroups","groups","embedded","Set","explicitRanges","String","startsWith","range","iStart","iEnd","some","eStart","eEnd","add","GroupingColumnsPlugin","BaseGridPlugin","static","ownedProperties","property","level","description","isUsed","v","Array","isArray","queries","type","name","styles","defaultConfig","showGroupBorders","lockGroupOrder","isActive","groupEndFields","attach","grid","super","addEventListener","this","onColumnMove","signal","disconnectSignal","detach","clear","e","event","columnOrder","detail","config","isGroupContiguous","preventDefault","flashHeaderCell","recomputeGroupEndFields","lastGroupEndField","findLastGroupEndField","groupFields","map","i","has","j","indices","indexOf","filter","sort","a","b","headerCell","gridElement","querySelector","style","setProperty","animate","backgroundColor","duration","easing","handleQuery","query","getStableColumnGrouping","result","columnGroups","gridConfig","children","header","fields","allCols","hidden","gId","gLabel","existing","find","includes","groupMap","from","values","displayOrder","getColumnOrder","orderIndex","f","Infinity","detect","rows","hasColumnGroups","processColumns","processedColumns","fieldToGroup","groupInfo","lastCol","afterRender","existingGroupRow","remove","finalColumns","visibleColumns","gi","groupRow","document","createElement","className","setAttribute","gid","isImplicit","startIndex","endIndex","span","cell","classList","gridColumn","textContent","appendChild","buildGroupHeaderRow","toggle","headerRow","insertBefore","headerRowEl","headerCells","querySelectorAll","getAttribute","applyGroupedHeaderCellClasses","afterCellRender","context","cellElement","column","isGroupingActive","getGroups","getGroupColumns","groupId","refresh","requestRender"],"mappings":"yVAkBO,SAASA,EAAuBC,GACrC,IAAKA,EAAQC,OAAQ,MAAO,GAE5B,MAAMC,MAAkBC,IAClBC,EAA0C,GAG1CC,EAAe,CAACC,EAAkBC,KACtC,IAAKA,EAAKN,OAAQ,OAElB,MAAMO,EAAOJ,EAAcA,EAAcH,OAAS,GAC9CO,GAAQA,EAAKC,UAAYD,EAAKE,WAAaF,EAAKR,QAAQC,SAAWK,EACrEE,EAAKR,QAAQW,QAAQJ,GAGvBH,EAAcO,KAAK,CACjBC,GAAI,eAAiBN,EACrBO,WA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,eAAA2B,CAAgBC,GAClBpG,KAAKN,UAAaM,KAAKU,OAAOlB,kBACnC4G,EAAQC,YAAYf,UAAUK,OAAO,YAAa3F,MAAKL,EAAgByB,IAAIgF,EAAQE,OAAO9I,OAC5F,CASA,gBAAA+I,GACE,OAAOvG,KAAKN,QACd,CAMA,SAAA8G,GACE,OAAOxG,KAAKrC,MACd,CAOA,eAAA8I,CAAgBC,GACd,MAAM5J,EAAQkD,KAAKrC,OAAOwF,KAAMtG,GAAMA,EAAEP,KAAOoK,GAC/C,OAAO5J,EAAQA,EAAMpB,QAAU,EACjC,CAKA,OAAAiL,GACE3G,KAAK4G,eACP"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"print.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/print/print-isolated.ts","../../../../../libs/grid/src/lib/plugins/print/PrintPlugin.ts"],"sourcesContent":["/**\n * Utility for printing a grid in isolation by hiding all other page content.\n *\n * This approach keeps the grid in place (with virtualization disabled by PrintPlugin)\n * and uses CSS to hide everything else on the page during printing.\n */\n\nimport type { PrintOrientation } from './types';\n\nexport interface PrintIsolatedOptions {\n /** Page orientation hint */\n orientation?: PrintOrientation;\n}\n\n/** ID for the isolation stylesheet */\nconst ISOLATION_STYLE_ID = 'tbw-print-isolation-style';\n\n/**\n * Create a stylesheet that hides everything except the target grid.\n * Uses the grid's ID to target it specifically.\n */\nfunction createIsolationStylesheet(gridId: string, orientation: PrintOrientation): HTMLStyleElement {\n const style = document.createElement('style');\n style.id = ISOLATION_STYLE_ID;\n style.textContent = `\n /* Print isolation: hide everything except the target grid */\n @media print {\n /* Hide all body children by default */\n body > *:not(#${gridId}) {\n display: none !important;\n }\n\n /* But show the grid and ensure it's not hidden by ancestor rules */\n #${gridId} {\n display: block !important;\n position: static !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n width: 100% !important;\n max-height: none !important;\n margin: 0 !important;\n padding: 0 !important;\n transform: none !important;\n }\n\n /* If grid is nested, we need to show its ancestors too */\n #${gridId},\n #${gridId} * {\n visibility: visible !important;\n }\n\n /* Walk up the DOM and show all ancestors of the grid */\n body *:has(> #${gridId}),\n body *:has(#${gridId}) {\n display: block !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n position: static !important;\n transform: none !important;\n background: transparent !important;\n border: none !important;\n padding: 0 !important;\n margin: 0 !important;\n }\n\n /* Hide siblings of ancestors (everything that's not in the path to the grid) */\n body *:has(#${gridId}) > *:not(:has(#${gridId})):not(#${gridId}) {\n display: none !important;\n }\n\n /* Page settings */\n @page {\n size: ${orientation};\n margin: 1cm;\n }\n\n /* Ensure proper print styling */\n body {\n margin: 0 !important;\n padding: 0 !important;\n background: white !important;\n color-scheme: light !important;\n }\n }\n\n /* Screen: also apply isolation for print preview */\n @media screen {\n /* When this stylesheet is active, we're about to print */\n /* No screen-specific rules needed - isolation only applies to print */\n }\n `;\n return style;\n}\n\n/**\n * Print a grid in isolation by hiding all other page content.\n *\n * This function adds a temporary stylesheet that uses CSS to hide everything\n * on the page except the target grid during printing. The grid stays in place\n * with all its data (virtualization should be disabled separately).\n *\n * @param gridElement - The tbw-grid element to print (must have an ID)\n * @param options - Optional configuration\n * @returns Promise that resolves when the print dialog closes\n *\n * @example\n * ```typescript\n * import { printGridIsolated } from '@toolbox-web/grid/plugins/print';\n *\n * const grid = document.querySelector('tbw-grid');\n * await printGridIsolated(grid, { orientation: 'landscape' });\n * ```\n */\nexport async function printGridIsolated(gridElement: HTMLElement, options: PrintIsolatedOptions = {}): Promise<void> {\n const { orientation = 'landscape' } = options;\n\n const gridId = gridElement.id;\n\n // Warn if multiple elements share this ID (user-set IDs could collide)\n const elementsWithId = document.querySelectorAll(`#${CSS.escape(gridId)}`);\n if (elementsWithId.length > 1) {\n console.warn(\n `[tbw-grid:print] Multiple elements found with id=\"${gridId}\". ` +\n `Print isolation may not work correctly. Ensure each grid has a unique ID.`,\n );\n }\n\n // Remove any existing isolation stylesheet\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n\n // Add the isolation stylesheet\n const isolationStyle = createIsolationStylesheet(gridId, orientation);\n document.head.appendChild(isolationStyle);\n\n return new Promise((resolve) => {\n // Listen for afterprint event to cleanup\n const onAfterPrint = () => {\n window.removeEventListener('afterprint', onAfterPrint);\n // Remove isolation stylesheet\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n resolve();\n };\n window.addEventListener('afterprint', onAfterPrint);\n\n // Trigger print\n window.print();\n\n // Fallback timeout in case afterprint doesn't fire (some browsers)\n setTimeout(() => {\n window.removeEventListener('afterprint', onAfterPrint);\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n resolve();\n }, 5000);\n });\n}\n","/**\n * Print Plugin (Class-based)\n *\n * Provides print layout functionality for tbw-grid.\n * Temporarily disables virtualization to render all rows and uses\n * @media print CSS for print-optimized styling.\n */\n\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { InternalGrid, ToolbarContentDefinition } from '../../core/types';\nimport { printGridIsolated } from './print-isolated';\nimport styles from './print.css?inline';\nimport type { PrintCompleteDetail, PrintConfig, PrintParams, PrintStartDetail } from './types';\n\n/**\n * Extended grid interface for PrintPlugin internal access.\n * Includes registerToolbarContent which is available on the grid class\n * but not exposed in the standard plugin API.\n */\ninterface PrintGridRef extends InternalGrid {\n registerToolbarContent?(content: ToolbarContentDefinition): void;\n unregisterToolbarContent?(contentId: string): void;\n}\n\n/** Default configuration */\nconst DEFAULT_CONFIG: Required<PrintConfig> = {\n button: false,\n orientation: 'landscape',\n warnThreshold: 500,\n maxRows: 0,\n includeTitle: true,\n includeTimestamp: true,\n title: '',\n isolate: false,\n};\n\n/**\n * Print Plugin for tbw-grid\n *\n * Enables printing the full grid content by temporarily disabling virtualization\n * and applying print-optimized styles. Handles large datasets gracefully with\n * configurable row limits.\n *\n * ## Installation\n *\n * ```ts\n * import { PrintPlugin } from '@toolbox-web/grid/plugins/print';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `button` | `boolean` | `false` | Show print button in toolbar |\n * | `orientation` | `'portrait' \\| 'landscape'` | `'landscape'` | Page orientation |\n * | `warnThreshold` | `number` | `500` | Show confirmation dialog when rows exceed this (0 = no warning) |\n * | `maxRows` | `number` | `0` | Hard limit on printed rows (0 = unlimited) |\n * | `includeTitle` | `boolean` | `true` | Include grid title in print |\n * | `includeTimestamp` | `boolean` | `true` | Include timestamp in footer |\n * | `title` | `string` | `''` | Custom print title |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `print` | `(params?) => Promise<void>` | Trigger print dialog |\n * | `isPrinting` | `() => boolean` | Check if print is in progress |\n *\n * ## Events\n *\n * | Event | Detail | Description |\n * |-------|--------|-------------|\n * | `print-start` | `PrintStartDetail` | Fired when print begins |\n * | `print-complete` | `PrintCompleteDetail` | Fired when print completes |\n *\n * @example Basic Print\n * ```ts\n * import { PrintPlugin } from '@toolbox-web/grid/plugins/print';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * plugins: [new PrintPlugin()],\n * };\n *\n * // Trigger print\n * const printPlugin = grid.getPlugin(PrintPlugin);\n * await printPlugin.print();\n * ```\n *\n * @example With Toolbar Button\n * ```ts\n * grid.gridConfig = {\n * plugins: [new PrintPlugin({ button: true, orientation: 'landscape' })],\n * };\n * ```\n *\n * @see {@link PrintConfig} for all configuration options\n */\nexport class PrintPlugin extends BaseGridPlugin<PrintConfig> {\n /** @internal */\n readonly name = 'print';\n\n /** @internal */\n override readonly version = '1.0.0';\n\n /** CSS styles for print mode */\n override readonly styles = styles;\n\n /** Current print state */\n #printing = false;\n\n /** Saved column visibility state */\n #savedHiddenColumns: Map<string, boolean> | null = null;\n\n /** Saved virtualization state */\n #savedVirtualization: { bypassThreshold: number } | null = null;\n\n /** Saved rows when maxRows limit is applied */\n #savedRows: unknown[] | null = null;\n\n /** Print header element */\n #printHeader: HTMLElement | null = null;\n\n /** Print footer element */\n #printFooter: HTMLElement | null = null;\n\n /** Applied scale factor (legacy, used for cleanup) */\n #appliedScale: number | null = null;\n\n /**\n * Get the grid typed as PrintGridRef for internal access.\n */\n get #internalGrid(): PrintGridRef {\n return this.grid as unknown as PrintGridRef;\n }\n\n /**\n * Check if print is currently in progress\n */\n isPrinting(): boolean {\n return this.#printing;\n }\n\n /**\n * Trigger the browser print dialog\n *\n * This method:\n * 1. Validates row count against maxRows limit\n * 2. Disables virtualization to render all rows\n * 3. Applies print-specific CSS classes\n * 4. Opens the browser print dialog (or isolated window if `isolate: true`)\n * 5. Restores normal state after printing\n *\n * @param params - Optional parameters to override config for this print\n * @param params.isolate - If true, prints in an isolated window containing only the grid\n * @returns Promise that resolves when print dialog closes\n */\n async print(params?: PrintParams): Promise<void> {\n if (this.#printing) {\n console.warn('[PrintPlugin] Print already in progress');\n return;\n }\n\n const grid = this.gridElement;\n if (!grid) {\n console.warn('[PrintPlugin] Grid not available');\n return;\n }\n\n const config = { ...DEFAULT_CONFIG, ...this.config, ...params };\n const rows = this.rows;\n const originalRowCount = rows.length;\n let rowCount = originalRowCount;\n let limitApplied = false;\n\n // Check if we should warn about large datasets\n if (config.warnThreshold > 0 && originalRowCount > config.warnThreshold) {\n const limitInfo =\n config.maxRows > 0 ? `\\n\\nNote: Output will be limited to ${config.maxRows.toLocaleString()} rows.` : '';\n const proceed = confirm(\n `This grid has ${originalRowCount.toLocaleString()} rows. ` +\n `Printing large datasets may cause performance issues or browser slowdowns.${limitInfo}\\n\\n` +\n `Click OK to continue, or Cancel to abort.`,\n );\n if (!proceed) {\n return;\n }\n }\n\n // Apply hard row limit if configured\n if (config.maxRows > 0 && originalRowCount > config.maxRows) {\n rowCount = config.maxRows;\n limitApplied = true;\n }\n\n this.#printing = true;\n\n // Track timing for duration reporting\n const startTime = performance.now();\n\n // Emit print-start event\n this.emit<PrintStartDetail>('print-start', {\n rowCount,\n limitApplied,\n originalRowCount,\n });\n\n try {\n // Save current virtualization state\n const internalGrid = this.#internalGrid;\n this.#savedVirtualization = {\n bypassThreshold: internalGrid._virtualization?.bypassThreshold ?? 24,\n };\n\n // Hide columns marked with printHidden\n this.#hidePrintColumns();\n\n // Apply row limit if configured\n if (limitApplied) {\n this.#savedRows = this.sourceRows;\n // Set limited rows on the grid\n (this.grid as unknown as { rows: unknown[] }).rows = this.sourceRows.slice(0, rowCount);\n // Wait for grid to process new rows\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n\n // Add print header if configured\n if (config.includeTitle || config.includeTimestamp) {\n this.#addPrintHeader(config);\n }\n\n // Disable virtualization to render all rows\n // This forces the grid to render all rows in the DOM\n await this.#disableVirtualization();\n\n // Wait for next frame to ensure DOM is updated\n await new Promise((resolve) => requestAnimationFrame(resolve));\n await new Promise((resolve) => requestAnimationFrame(resolve));\n\n // Add orientation class for @page rules\n grid.classList.add(`print-${config.orientation}`);\n\n // Wait for next frame to ensure DOM is updated\n await new Promise((resolve) => requestAnimationFrame(resolve));\n await new Promise((resolve) => requestAnimationFrame(resolve));\n\n // Trigger browser print dialog (isolated or inline)\n if (config.isolate) {\n await this.#printInIsolatedWindow(config);\n } else {\n await this.#triggerPrint();\n }\n\n // Emit print-complete event\n this.emit<PrintCompleteDetail>('print-complete', {\n success: true,\n rowCount,\n duration: Math.round(performance.now() - startTime),\n });\n } catch (error) {\n console.error('[PrintPlugin] Print failed:', error);\n this.emit<PrintCompleteDetail>('print-complete', {\n success: false,\n rowCount: 0,\n duration: Math.round(performance.now() - startTime),\n });\n } finally {\n // Restore normal state\n this.#cleanup();\n this.#printing = false;\n }\n }\n\n /**\n * Add print header with title and timestamp\n */\n #addPrintHeader(config: Required<PrintConfig>): void {\n const grid = this.gridElement;\n if (!grid) return;\n\n // Create print header\n this.#printHeader = document.createElement('div');\n this.#printHeader.className = 'tbw-print-header';\n\n // Title\n if (config.includeTitle) {\n const title = config.title || this.grid.effectiveConfig?.shell?.header?.title || 'Grid Data';\n const titleEl = document.createElement('div');\n titleEl.className = 'tbw-print-header-title';\n titleEl.textContent = title;\n this.#printHeader.appendChild(titleEl);\n }\n\n // Timestamp\n if (config.includeTimestamp) {\n const timestampEl = document.createElement('div');\n timestampEl.className = 'tbw-print-header-timestamp';\n timestampEl.textContent = `Printed: ${new Date().toLocaleString()}`;\n this.#printHeader.appendChild(timestampEl);\n }\n\n // Insert at the beginning of the grid\n grid.insertBefore(this.#printHeader, grid.firstChild);\n\n // Create print footer\n this.#printFooter = document.createElement('div');\n this.#printFooter.className = 'tbw-print-footer';\n this.#printFooter.textContent = `Page generated from ${window.location.hostname}`;\n grid.appendChild(this.#printFooter);\n }\n\n /**\n * Disable virtualization to render all rows\n */\n async #disableVirtualization(): Promise<void> {\n const internalGrid = this.#internalGrid;\n if (!internalGrid._virtualization) return;\n\n // Set bypass threshold higher than total row count to disable virtualization\n // This makes the grid render all rows (up to maxRows) instead of just visible ones\n const totalRows = this.rows.length;\n internalGrid._virtualization.bypassThreshold = totalRows + 100;\n\n // Force a full refresh to re-render with virtualization disabled\n internalGrid.refreshVirtualWindow(true);\n\n // Wait for render to complete\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n /**\n * Trigger the browser print dialog\n */\n async #triggerPrint(): Promise<void> {\n return new Promise((resolve) => {\n // Listen for afterprint event\n const onAfterPrint = () => {\n window.removeEventListener('afterprint', onAfterPrint);\n resolve();\n };\n window.addEventListener('afterprint', onAfterPrint);\n\n // Trigger print\n window.print();\n\n // Fallback timeout in case afterprint doesn't fire (some browsers)\n setTimeout(() => {\n // Guard against test environment teardown where window may be undefined\n if (typeof window !== 'undefined') {\n window.removeEventListener('afterprint', onAfterPrint);\n }\n resolve();\n }, 1000);\n });\n }\n\n /**\n * Print in isolation by hiding all other page content.\n * This excludes navigation, sidebars, etc. while keeping the grid in place.\n */\n async #printInIsolatedWindow(config: Required<PrintConfig>): Promise<void> {\n const grid = this.gridElement;\n if (!grid) return;\n\n await printGridIsolated(grid, {\n orientation: config.orientation,\n });\n }\n\n /**\n * Hide columns marked with printHidden: true\n */\n #hidePrintColumns(): void {\n const columns = this.columns;\n if (!columns) return;\n\n // Save current hidden state and hide print columns\n this.#savedHiddenColumns = new Map();\n\n for (const col of columns) {\n if (col.printHidden && col.field) {\n // Save current visibility state (true = visible, false = hidden)\n this.#savedHiddenColumns.set(col.field, !col.hidden);\n // Hide the column for printing\n this.grid.setColumnVisible(col.field, false);\n }\n }\n }\n\n /**\n * Restore columns that were hidden for printing\n */\n #restorePrintColumns(): void {\n if (!this.#savedHiddenColumns) return;\n\n for (const [field, wasVisible] of this.#savedHiddenColumns) {\n // Restore original visibility\n this.grid.setColumnVisible(field, wasVisible);\n }\n\n this.#savedHiddenColumns = null;\n }\n\n /**\n * Cleanup after printing\n */\n #cleanup(): void {\n const grid = this.gridElement;\n if (!grid) return;\n\n // Restore columns that were hidden for printing\n this.#restorePrintColumns();\n\n // Remove orientation classes (both original and possibly switched)\n grid.classList.remove('print-portrait', 'print-landscape');\n\n // Remove scaling transform if applied (legacy)\n if (this.#appliedScale !== null) {\n grid.style.transform = '';\n grid.style.transformOrigin = '';\n grid.style.width = '';\n this.#appliedScale = null;\n }\n\n // Remove print header/footer\n if (this.#printHeader) {\n this.#printHeader.remove();\n this.#printHeader = null;\n }\n if (this.#printFooter) {\n this.#printFooter.remove();\n this.#printFooter = null;\n }\n\n // Restore virtualization\n const internalGrid = this.#internalGrid;\n if (this.#savedVirtualization && internalGrid._virtualization) {\n internalGrid._virtualization.bypassThreshold = this.#savedVirtualization.bypassThreshold;\n internalGrid.refreshVirtualWindow(true);\n this.#savedVirtualization = null;\n }\n\n // Restore original rows if they were limited\n if (this.#savedRows !== null) {\n (this.grid as unknown as { rows: unknown[] }).rows = this.#savedRows;\n this.#savedRows = null;\n }\n }\n\n /**\n * Register toolbar button if configured\n * @internal\n */\n override afterRender(): void {\n // Register toolbar on first render when button is enabled\n if (this.config?.button && !this.#toolbarRegistered) {\n this.#registerToolbarButton();\n this.#toolbarRegistered = true;\n }\n }\n\n /** Track if toolbar button is registered */\n #toolbarRegistered = false;\n\n /**\n * Register print button in toolbar\n */\n #registerToolbarButton(): void {\n const grid = this.#internalGrid;\n\n // Register toolbar content\n grid.registerToolbarContent?.({\n id: 'print-button',\n order: 900, // High order to appear at the end\n render: (container: HTMLElement) => {\n const button = document.createElement('button');\n button.className = 'tbw-toolbar-btn tbw-print-btn';\n button.title = 'Print grid';\n button.type = 'button';\n\n // Use print icon\n const icon = this.resolveIcon('print') || '🖨️';\n this.setIcon(button, icon);\n\n button.addEventListener(\n 'click',\n () => {\n this.print();\n },\n { signal: this.disconnectSignal },\n );\n\n container.appendChild(button);\n },\n });\n }\n}\n"],"names":["ISOLATION_STYLE_ID","async","printGridIsolated","gridElement","options","orientation","gridId","id","document","querySelectorAll","CSS","escape","length","console","warn","getElementById","remove","isolationStyle","style","createElement","textContent","createIsolationStylesheet","head","appendChild","Promise","resolve","onAfterPrint","window","removeEventListener","addEventListener","print","setTimeout","DEFAULT_CONFIG","button","warnThreshold","maxRows","includeTitle","includeTimestamp","title","isolate","PrintPlugin","BaseGridPlugin","name","version","styles","printing","savedHiddenColumns","savedVirtualization","savedRows","printHeader","printFooter","appliedScale","internalGrid","this","grid","isPrinting","params","config","originalRowCount","rows","rowCount","limitApplied","limitInfo","toLocaleString","confirm","startTime","performance","now","emit","bypassThreshold","_virtualization","hidePrintColumns","sourceRows","slice","addPrintHeader","disableVirtualization","requestAnimationFrame","classList","add","printInIsolatedWindow","triggerPrint","success","duration","Math","round","error","cleanup","className","effectiveConfig","shell","header","titleEl","timestampEl","Date","insertBefore","firstChild","location","hostname","totalRows","refreshVirtualWindow","columns","Map","col","printHidden","field","set","hidden","setColumnVisible","restorePrintColumns","wasVisible","transform","transformOrigin","width","afterRender","toolbarRegistered","registerToolbarButton","registerToolbarContent","order","render","container","type","icon","resolveIcon","setIcon","signal","disconnectSignal"],"mappings":"+UAeA,MAAMA,EAAqB,4BAsG3BC,eAAsBC,EAAkB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C,MAAKN,EAAuB,MAIN,OAApBM,MAAKL,IACNK,KAAKC,KAAwCK,KAAON,MAAKL,EAC1DK,MAAKL,EAAa,KAEtB,CAMS,WAAAiE,GAEH5D,KAAKI,QAAQxB,SAAWoB,MAAK6D,IAC/B7D,MAAK8D,IACL9D,MAAK6D,GAAqB,EAE9B,CAGAA,IAAqB,EAKrB,EAAAC,GACE,MAAM7D,EAAOD,MAAKD,EAGlBE,EAAK8D,yBAAyB,CAC5B7G,GAAI,eACJ8G,MAAO,IACPC,OAASC,IACP,MAAMtF,EAASzB,SAASW,cAAc,UACtCc,EAAOsD,UAAY,gCACnBtD,EAAOK,MAAQ,aACfL,EAAOuF,KAAO,SAGd,MAAMC,EAAOpE,KAAKqE,YAAY,UAAY,MAC1CrE,KAAKsE,QAAQ1F,EAAQwF,GAErBxF,EAAOJ,iBACL,QACA,KACEwB,KAAKvB,SAEP,CAAE8F,OAAQvE,KAAKwE,mBAGjBN,EAAUhG,YAAYU,KAG5B"}
|
|
1
|
+
{"version":3,"file":"print.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/print/print-isolated.ts","../../../../../libs/grid/src/lib/plugins/print/PrintPlugin.ts"],"sourcesContent":["/**\n * Utility for printing a grid in isolation by hiding all other page content.\n *\n * This approach keeps the grid in place (with virtualization disabled by PrintPlugin)\n * and uses CSS to hide everything else on the page during printing.\n */\n\nimport type { PrintOrientation } from './types';\n\nexport interface PrintIsolatedOptions {\n /** Page orientation hint */\n orientation?: PrintOrientation;\n}\n\n/** ID for the isolation stylesheet */\nconst ISOLATION_STYLE_ID = 'tbw-print-isolation-style';\n\n/**\n * Create a stylesheet that hides everything except the target grid.\n * Uses the grid's ID to target it specifically.\n */\nfunction createIsolationStylesheet(gridId: string, orientation: PrintOrientation): HTMLStyleElement {\n const style = document.createElement('style');\n style.id = ISOLATION_STYLE_ID;\n style.textContent = `\n /* Print isolation: hide everything except the target grid */\n @media print {\n /* Hide all body children by default */\n body > *:not(#${gridId}) {\n display: none !important;\n }\n\n /* But show the grid and ensure it's not hidden by ancestor rules */\n #${gridId} {\n display: block !important;\n position: static !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n width: 100% !important;\n max-height: none !important;\n margin: 0 !important;\n padding: 0 !important;\n transform: none !important;\n }\n\n /* If grid is nested, we need to show its ancestors too */\n #${gridId},\n #${gridId} * {\n visibility: visible !important;\n }\n\n /* Walk up the DOM and show all ancestors of the grid */\n body *:has(> #${gridId}),\n body *:has(#${gridId}) {\n display: block !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n position: static !important;\n transform: none !important;\n background: transparent !important;\n border: none !important;\n padding: 0 !important;\n margin: 0 !important;\n }\n\n /* Hide siblings of ancestors (everything that's not in the path to the grid) */\n body *:has(#${gridId}) > *:not(:has(#${gridId})):not(#${gridId}) {\n display: none !important;\n }\n\n /* Page settings */\n @page {\n size: ${orientation};\n margin: 1cm;\n }\n\n /* Ensure proper print styling */\n body {\n margin: 0 !important;\n padding: 0 !important;\n background: white !important;\n color-scheme: light !important;\n }\n }\n\n /* Screen: also apply isolation for print preview */\n @media screen {\n /* When this stylesheet is active, we're about to print */\n /* No screen-specific rules needed - isolation only applies to print */\n }\n `;\n return style;\n}\n\n/**\n * Print a grid in isolation by hiding all other page content.\n *\n * This function adds a temporary stylesheet that uses CSS to hide everything\n * on the page except the target grid during printing. The grid stays in place\n * with all its data (virtualization should be disabled separately).\n *\n * @param gridElement - The tbw-grid element to print (must have an ID)\n * @param options - Optional configuration\n * @returns Promise that resolves when the print dialog closes\n *\n * @example\n * ```typescript\n * import { printGridIsolated } from '@toolbox-web/grid/plugins/print';\n *\n * const grid = document.querySelector('tbw-grid');\n * await printGridIsolated(grid, { orientation: 'landscape' });\n * ```\n */\nexport async function printGridIsolated(gridElement: HTMLElement, options: PrintIsolatedOptions = {}): Promise<void> {\n const { orientation = 'landscape' } = options;\n\n const gridId = gridElement.id;\n\n // Warn if multiple elements share this ID (user-set IDs could collide)\n const elementsWithId = document.querySelectorAll(`#${CSS.escape(gridId)}`);\n if (elementsWithId.length > 1) {\n console.warn(\n `[tbw-grid:print] Multiple elements found with id=\"${gridId}\". ` +\n `Print isolation may not work correctly. Ensure each grid has a unique ID.`,\n );\n }\n\n // Remove any existing isolation stylesheet\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n\n // Add the isolation stylesheet\n const isolationStyle = createIsolationStylesheet(gridId, orientation);\n document.head.appendChild(isolationStyle);\n\n return new Promise((resolve) => {\n // Listen for afterprint event to cleanup\n const onAfterPrint = () => {\n window.removeEventListener('afterprint', onAfterPrint);\n // Remove isolation stylesheet\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n resolve();\n };\n window.addEventListener('afterprint', onAfterPrint);\n\n // Trigger print\n window.print();\n\n // Fallback timeout in case afterprint doesn't fire (some browsers)\n setTimeout(() => {\n window.removeEventListener('afterprint', onAfterPrint);\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n resolve();\n }, 5000);\n });\n}\n","/**\n * Print Plugin (Class-based)\n *\n * Provides print layout functionality for tbw-grid.\n * Temporarily disables virtualization to render all rows and uses\n * @media print CSS for print-optimized styling.\n */\n\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { InternalGrid, ToolbarContentDefinition } from '../../core/types';\nimport { printGridIsolated } from './print-isolated';\nimport styles from './print.css?inline';\nimport type { PrintCompleteDetail, PrintConfig, PrintParams, PrintStartDetail } from './types';\n\n/**\n * Extended grid interface for PrintPlugin internal access.\n * Includes registerToolbarContent which is available on the grid class\n * but not exposed in the standard plugin API.\n */\ninterface PrintGridRef extends InternalGrid {\n registerToolbarContent?(content: ToolbarContentDefinition): void;\n unregisterToolbarContent?(contentId: string): void;\n}\n\n/** Default configuration */\nconst DEFAULT_CONFIG: Required<PrintConfig> = {\n button: false,\n orientation: 'landscape',\n warnThreshold: 500,\n maxRows: 0,\n includeTitle: true,\n includeTimestamp: true,\n title: '',\n isolate: false,\n};\n\n/**\n * Print Plugin for tbw-grid\n *\n * Enables printing the full grid content by temporarily disabling virtualization\n * and applying print-optimized styles. Handles large datasets gracefully with\n * configurable row limits.\n *\n * ## Installation\n *\n * ```ts\n * import { PrintPlugin } from '@toolbox-web/grid/plugins/print';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `button` | `boolean` | `false` | Show print button in toolbar |\n * | `orientation` | `'portrait' \\| 'landscape'` | `'landscape'` | Page orientation |\n * | `warnThreshold` | `number` | `500` | Show confirmation dialog when rows exceed this (0 = no warning) |\n * | `maxRows` | `number` | `0` | Hard limit on printed rows (0 = unlimited) |\n * | `includeTitle` | `boolean` | `true` | Include grid title in print |\n * | `includeTimestamp` | `boolean` | `true` | Include timestamp in footer |\n * | `title` | `string` | `''` | Custom print title |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `print` | `(params?) => Promise<void>` | Trigger print dialog |\n * | `isPrinting` | `() => boolean` | Check if print is in progress |\n *\n * ## Events\n *\n * | Event | Detail | Description |\n * |-------|--------|-------------|\n * | `print-start` | `PrintStartDetail` | Fired when print begins |\n * | `print-complete` | `PrintCompleteDetail` | Fired when print completes |\n *\n * @example Basic Print\n * ```ts\n * import { PrintPlugin } from '@toolbox-web/grid/plugins/print';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * plugins: [new PrintPlugin()],\n * };\n *\n * // Trigger print\n * const printPlugin = grid.getPluginByName('print');\n * await printPlugin.print();\n * ```\n *\n * @example With Toolbar Button\n * ```ts\n * grid.gridConfig = {\n * plugins: [new PrintPlugin({ button: true, orientation: 'landscape' })],\n * };\n * ```\n *\n * @see {@link PrintConfig} for all configuration options\n */\nexport class PrintPlugin extends BaseGridPlugin<PrintConfig> {\n /** @internal */\n readonly name = 'print';\n\n /** @internal */\n override readonly version = '1.0.0';\n\n /** CSS styles for print mode */\n override readonly styles = styles;\n\n /** Current print state */\n #printing = false;\n\n /** Saved column visibility state */\n #savedHiddenColumns: Map<string, boolean> | null = null;\n\n /** Saved virtualization state */\n #savedVirtualization: { bypassThreshold: number } | null = null;\n\n /** Saved rows when maxRows limit is applied */\n #savedRows: unknown[] | null = null;\n\n /** Print header element */\n #printHeader: HTMLElement | null = null;\n\n /** Print footer element */\n #printFooter: HTMLElement | null = null;\n\n /** Applied scale factor (legacy, used for cleanup) */\n #appliedScale: number | null = null;\n\n /**\n * Get the grid typed as PrintGridRef for internal access.\n */\n get #internalGrid(): PrintGridRef {\n return this.grid as unknown as PrintGridRef;\n }\n\n /**\n * Check if print is currently in progress\n */\n isPrinting(): boolean {\n return this.#printing;\n }\n\n /**\n * Trigger the browser print dialog\n *\n * This method:\n * 1. Validates row count against maxRows limit\n * 2. Disables virtualization to render all rows\n * 3. Applies print-specific CSS classes\n * 4. Opens the browser print dialog (or isolated window if `isolate: true`)\n * 5. Restores normal state after printing\n *\n * @param params - Optional parameters to override config for this print\n * @param params.isolate - If true, prints in an isolated window containing only the grid\n * @returns Promise that resolves when print dialog closes\n */\n async print(params?: PrintParams): Promise<void> {\n if (this.#printing) {\n console.warn('[PrintPlugin] Print already in progress');\n return;\n }\n\n const grid = this.gridElement;\n if (!grid) {\n console.warn('[PrintPlugin] Grid not available');\n return;\n }\n\n const config = { ...DEFAULT_CONFIG, ...this.config, ...params };\n const rows = this.rows;\n const originalRowCount = rows.length;\n let rowCount = originalRowCount;\n let limitApplied = false;\n\n // Check if we should warn about large datasets\n if (config.warnThreshold > 0 && originalRowCount > config.warnThreshold) {\n const limitInfo =\n config.maxRows > 0 ? `\\n\\nNote: Output will be limited to ${config.maxRows.toLocaleString()} rows.` : '';\n const proceed = confirm(\n `This grid has ${originalRowCount.toLocaleString()} rows. ` +\n `Printing large datasets may cause performance issues or browser slowdowns.${limitInfo}\\n\\n` +\n `Click OK to continue, or Cancel to abort.`,\n );\n if (!proceed) {\n return;\n }\n }\n\n // Apply hard row limit if configured\n if (config.maxRows > 0 && originalRowCount > config.maxRows) {\n rowCount = config.maxRows;\n limitApplied = true;\n }\n\n this.#printing = true;\n\n // Track timing for duration reporting\n const startTime = performance.now();\n\n // Emit print-start event\n this.emit<PrintStartDetail>('print-start', {\n rowCount,\n limitApplied,\n originalRowCount,\n });\n\n try {\n // Save current virtualization state\n const internalGrid = this.#internalGrid;\n this.#savedVirtualization = {\n bypassThreshold: internalGrid._virtualization?.bypassThreshold ?? 24,\n };\n\n // Hide columns marked with printHidden\n this.#hidePrintColumns();\n\n // Apply row limit if configured\n if (limitApplied) {\n this.#savedRows = this.sourceRows;\n // Set limited rows on the grid\n (this.grid as unknown as { rows: unknown[] }).rows = this.sourceRows.slice(0, rowCount);\n // Wait for grid to process new rows\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n\n // Add print header if configured\n if (config.includeTitle || config.includeTimestamp) {\n this.#addPrintHeader(config);\n }\n\n // Disable virtualization to render all rows\n // This forces the grid to render all rows in the DOM\n await this.#disableVirtualization();\n\n // Wait for next frame to ensure DOM is updated\n await new Promise((resolve) => requestAnimationFrame(resolve));\n await new Promise((resolve) => requestAnimationFrame(resolve));\n\n // Add orientation class for @page rules\n grid.classList.add(`print-${config.orientation}`);\n\n // Wait for next frame to ensure DOM is updated\n await new Promise((resolve) => requestAnimationFrame(resolve));\n await new Promise((resolve) => requestAnimationFrame(resolve));\n\n // Trigger browser print dialog (isolated or inline)\n if (config.isolate) {\n await this.#printInIsolatedWindow(config);\n } else {\n await this.#triggerPrint();\n }\n\n // Emit print-complete event\n this.emit<PrintCompleteDetail>('print-complete', {\n success: true,\n rowCount,\n duration: Math.round(performance.now() - startTime),\n });\n } catch (error) {\n console.error('[PrintPlugin] Print failed:', error);\n this.emit<PrintCompleteDetail>('print-complete', {\n success: false,\n rowCount: 0,\n duration: Math.round(performance.now() - startTime),\n });\n } finally {\n // Restore normal state\n this.#cleanup();\n this.#printing = false;\n }\n }\n\n /**\n * Add print header with title and timestamp\n */\n #addPrintHeader(config: Required<PrintConfig>): void {\n const grid = this.gridElement;\n if (!grid) return;\n\n // Create print header\n this.#printHeader = document.createElement('div');\n this.#printHeader.className = 'tbw-print-header';\n\n // Title\n if (config.includeTitle) {\n const title = config.title || this.grid.effectiveConfig?.shell?.header?.title || 'Grid Data';\n const titleEl = document.createElement('div');\n titleEl.className = 'tbw-print-header-title';\n titleEl.textContent = title;\n this.#printHeader.appendChild(titleEl);\n }\n\n // Timestamp\n if (config.includeTimestamp) {\n const timestampEl = document.createElement('div');\n timestampEl.className = 'tbw-print-header-timestamp';\n timestampEl.textContent = `Printed: ${new Date().toLocaleString()}`;\n this.#printHeader.appendChild(timestampEl);\n }\n\n // Insert at the beginning of the grid\n grid.insertBefore(this.#printHeader, grid.firstChild);\n\n // Create print footer\n this.#printFooter = document.createElement('div');\n this.#printFooter.className = 'tbw-print-footer';\n this.#printFooter.textContent = `Page generated from ${window.location.hostname}`;\n grid.appendChild(this.#printFooter);\n }\n\n /**\n * Disable virtualization to render all rows\n */\n async #disableVirtualization(): Promise<void> {\n const internalGrid = this.#internalGrid;\n if (!internalGrid._virtualization) return;\n\n // Set bypass threshold higher than total row count to disable virtualization\n // This makes the grid render all rows (up to maxRows) instead of just visible ones\n const totalRows = this.rows.length;\n internalGrid._virtualization.bypassThreshold = totalRows + 100;\n\n // Force a full refresh to re-render with virtualization disabled\n internalGrid.refreshVirtualWindow(true);\n\n // Wait for render to complete\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n /**\n * Trigger the browser print dialog\n */\n async #triggerPrint(): Promise<void> {\n return new Promise((resolve) => {\n // Listen for afterprint event\n const onAfterPrint = () => {\n window.removeEventListener('afterprint', onAfterPrint);\n resolve();\n };\n window.addEventListener('afterprint', onAfterPrint);\n\n // Trigger print\n window.print();\n\n // Fallback timeout in case afterprint doesn't fire (some browsers)\n setTimeout(() => {\n // Guard against test environment teardown where window may be undefined\n if (typeof window !== 'undefined') {\n window.removeEventListener('afterprint', onAfterPrint);\n }\n resolve();\n }, 1000);\n });\n }\n\n /**\n * Print in isolation by hiding all other page content.\n * This excludes navigation, sidebars, etc. while keeping the grid in place.\n */\n async #printInIsolatedWindow(config: Required<PrintConfig>): Promise<void> {\n const grid = this.gridElement;\n if (!grid) return;\n\n await printGridIsolated(grid, {\n orientation: config.orientation,\n });\n }\n\n /**\n * Hide columns marked with printHidden: true\n */\n #hidePrintColumns(): void {\n const columns = this.columns;\n if (!columns) return;\n\n // Save current hidden state and hide print columns\n this.#savedHiddenColumns = new Map();\n\n for (const col of columns) {\n if (col.printHidden && col.field) {\n // Save current visibility state (true = visible, false = hidden)\n this.#savedHiddenColumns.set(col.field, !col.hidden);\n // Hide the column for printing\n this.grid.setColumnVisible(col.field, false);\n }\n }\n }\n\n /**\n * Restore columns that were hidden for printing\n */\n #restorePrintColumns(): void {\n if (!this.#savedHiddenColumns) return;\n\n for (const [field, wasVisible] of this.#savedHiddenColumns) {\n // Restore original visibility\n this.grid.setColumnVisible(field, wasVisible);\n }\n\n this.#savedHiddenColumns = null;\n }\n\n /**\n * Cleanup after printing\n */\n #cleanup(): void {\n const grid = this.gridElement;\n if (!grid) return;\n\n // Restore columns that were hidden for printing\n this.#restorePrintColumns();\n\n // Remove orientation classes (both original and possibly switched)\n grid.classList.remove('print-portrait', 'print-landscape');\n\n // Remove scaling transform if applied (legacy)\n if (this.#appliedScale !== null) {\n grid.style.transform = '';\n grid.style.transformOrigin = '';\n grid.style.width = '';\n this.#appliedScale = null;\n }\n\n // Remove print header/footer\n if (this.#printHeader) {\n this.#printHeader.remove();\n this.#printHeader = null;\n }\n if (this.#printFooter) {\n this.#printFooter.remove();\n this.#printFooter = null;\n }\n\n // Restore virtualization\n const internalGrid = this.#internalGrid;\n if (this.#savedVirtualization && internalGrid._virtualization) {\n internalGrid._virtualization.bypassThreshold = this.#savedVirtualization.bypassThreshold;\n internalGrid.refreshVirtualWindow(true);\n this.#savedVirtualization = null;\n }\n\n // Restore original rows if they were limited\n if (this.#savedRows !== null) {\n (this.grid as unknown as { rows: unknown[] }).rows = this.#savedRows;\n this.#savedRows = null;\n }\n }\n\n /**\n * Register toolbar button if configured\n * @internal\n */\n override afterRender(): void {\n // Register toolbar on first render when button is enabled\n if (this.config?.button && !this.#toolbarRegistered) {\n this.#registerToolbarButton();\n this.#toolbarRegistered = true;\n }\n }\n\n /** Track if toolbar button is registered */\n #toolbarRegistered = false;\n\n /**\n * Register print button in toolbar\n */\n #registerToolbarButton(): void {\n const grid = this.#internalGrid;\n\n // Register toolbar content\n grid.registerToolbarContent?.({\n id: 'print-button',\n order: 900, // High order to appear at the end\n render: (container: HTMLElement) => {\n const button = document.createElement('button');\n button.className = 'tbw-toolbar-btn tbw-print-btn';\n button.title = 'Print grid';\n button.type = 'button';\n\n // Use print icon\n const icon = this.resolveIcon('print') || '🖨️';\n this.setIcon(button, icon);\n\n button.addEventListener(\n 'click',\n () => {\n this.print();\n },\n { signal: this.disconnectSignal },\n );\n\n container.appendChild(button);\n },\n });\n }\n}\n"],"names":["ISOLATION_STYLE_ID","async","printGridIsolated","gridElement","options","orientation","gridId","id","document","querySelectorAll","CSS","escape","length","console","warn","getElementById","remove","isolationStyle","style","createElement","textContent","createIsolationStylesheet","head","appendChild","Promise","resolve","onAfterPrint","window","removeEventListener","addEventListener","print","setTimeout","DEFAULT_CONFIG","button","warnThreshold","maxRows","includeTitle","includeTimestamp","title","isolate","PrintPlugin","BaseGridPlugin","name","version","styles","printing","savedHiddenColumns","savedVirtualization","savedRows","printHeader","printFooter","appliedScale","internalGrid","this","grid","isPrinting","params","config","originalRowCount","rows","rowCount","limitApplied","limitInfo","toLocaleString","confirm","startTime","performance","now","emit","bypassThreshold","_virtualization","hidePrintColumns","sourceRows","slice","addPrintHeader","disableVirtualization","requestAnimationFrame","classList","add","printInIsolatedWindow","triggerPrint","success","duration","Math","round","error","cleanup","className","effectiveConfig","shell","header","titleEl","timestampEl","Date","insertBefore","firstChild","location","hostname","totalRows","refreshVirtualWindow","columns","Map","col","printHidden","field","set","hidden","setColumnVisible","restorePrintColumns","wasVisible","transform","transformOrigin","width","afterRender","toolbarRegistered","registerToolbarButton","registerToolbarContent","order","render","container","type","icon","resolveIcon","setIcon","signal","disconnectSignal"],"mappings":"+UAeA,MAAMA,EAAqB,4BAsG3BC,eAAsBC,EAAkBC,EAA0BC,EAAgC,IAChG,MAAMC,YAAEA,EAAc,aAAgBD,EAEhCE,EAASH,EAAYI,GAGJC,SAASC,iBAAiB,IAAIC,IAAIC,OAAOL,MAC7CM,OAAS,GAC1BC,QAAQC,KACN,qDAAqDR,iFAMzDE,SAASO,eAAef,IAAqBgB,SAG7C,MAAMC,EAlHR,SAAmCX,EAAgBD,GACjD,MAAMa,EAAQV,SAASW,cAAc,SAyErC,OAxEAD,EAAMX,GAAKP,EACXkB,EAAME,YAAc,+JAIAd,0IAKbA,meAeAA,cACAA,kJAKaA,0BACFA,6gBAeAA,oBAAyBA,YAAiBA,+GAM9CD,yeAmBPa,CACT,CAuCyBG,CAA0Bf,EAAQD,GAGzD,OAFAG,SAASc,KAAKC,YAAYN,GAEnB,IAAIO,QAASC,IAElB,MAAMC,EAAe,KACnBC,OAAOC,oBAAoB,aAAcF,GAEzClB,SAASO,eAAef,IAAqBgB,SAC7CS,KAEFE,OAAOE,iBAAiB,aAAcH,GAGtCC,OAAOG,QAGPC,WAAW,KACTJ,OAAOC,oBAAoB,aAAcF,GACzClB,SAASO,eAAef,IAAqBgB,SAC7CS,KACC,MAEP,OCrIMO,EAAwC,CAC5CC,QAAQ,EACR5B,YAAa,YACb6B,cAAe,IACfC,QAAS,EACTC,cAAc,EACdC,kBAAkB,EAClBC,MAAO,GACPC,SAAS,GAiEJ,MAAMC,UAAoBC,EAAAA,eAEtBC,KAAO,QAGEC,QAAU,QAGVC,kwEAGlBC,IAAY,EAGZC,GAAmD,KAGnDC,GAA2D,KAG3DC,GAA+B,KAG/BC,GAAmC,KAGnCC,GAAmC,KAGnCC,GAA+B,KAK/B,KAAIC,GACF,OAAOC,KAAKC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PG,MAAKH,EAAalC,SAClBqC,MAAKH,EAAe,MAItB,MAAME,EAAeC,MAAKD,EACtBC,MAAKN,GAAwBK,EAAakB,kBAC5ClB,EAAakB,gBAAgBD,gBAAkBhB,MAAKN,EAAqBsB,gBACzEjB,EAAa+C,sBAAqB,GAClC9C,MAAKN,EAAuB,MAIN,OAApBM,MAAKL,IACNK,KAAKC,KAAwCK,KAAON,MAAKL,EAC1DK,MAAKL,EAAa,KAEtB,CAMS,WAAAiE,GAEH5D,KAAKI,QAAQxB,SAAWoB,MAAK6D,IAC/B7D,MAAK8D,IACL9D,MAAK6D,GAAqB,EAE9B,CAGAA,IAAqB,EAKrB,EAAAC,GACE,MAAM7D,EAAOD,MAAKD,EAGlBE,EAAK8D,yBAAyB,CAC5B7G,GAAI,eACJ8G,MAAO,IACPC,OAASC,IACP,MAAMtF,EAASzB,SAASW,cAAc,UACtCc,EAAOsD,UAAY,gCACnBtD,EAAOK,MAAQ,aACfL,EAAOuF,KAAO,SAGd,MAAMC,EAAOpE,KAAKqE,YAAY,UAAY,MAC1CrE,KAAKsE,QAAQ1F,EAAQwF,GAErBxF,EAAOJ,iBACL,QACA,KACEwB,KAAKvB,SAEP,CAAE8F,OAAQvE,KAAKwE,mBAGjBN,EAAUhG,YAAYU,KAG5B"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/keyboard"),require("../../core/internal/sanitize"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/keyboard","../../core/internal/sanitize","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_responsive={},e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,i,r){"use strict";class s extends r.BaseGridPlugin{name="responsive";version="1.0.0";styles='tbw-grid[data-responsive-animate] .data-grid-row,tbw-grid[data-responsive-animate] .data-grid-row>.cell{transition:opacity var(--tbw-responsive-duration, .2s) ease-out,transform var(--tbw-responsive-duration, .2s) ease-out}tbw-grid[data-responsive][data-responsive-animate] .data-grid-row{animation:responsive-card-enter var(--tbw-responsive-duration, .2s) ease-out}@keyframes responsive-card-enter{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}tbw-grid[data-responsive] .header{display:none!important}tbw-grid[data-responsive] .footer-row{display:none}tbw-grid[data-responsive] .tbw-scroll-area{overflow-x:hidden;min-width:0!important}tbw-grid[data-responsive] .rows-body-wrapper{min-width:0!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row){display:block!important;grid-template-columns:none!important;padding:var(--tbw-cell-padding);padding-inline-start:var(--tbw-spacing-xl);border-bottom:1px solid var(--tbw-color-border);min-height:auto!important;height:auto!important;contain:none!important;content-visibility:visible!important;background:var(--tbw-color-bg);position:relative}tbw-grid[data-responsive] .data-grid-row:not(.group-row):nth-child(2n){background:var(--tbw-color-row-alt)}tbw-grid[data-responsive] .data-grid-row:not(.group-row):hover{background:var(--tbw-color-row-hover)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]{background:var(--tbw-color-selection)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]:before{content:"";position:absolute;inset-inline-start:0;top:0;bottom:0;width:4px;background:var(--tbw-color-accent)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell{display:flex!important;justify-content:space-between;align-items:center;padding:var(--tbw-spacing-xs) var(--tbw-spacing-md);width:100%!important;min-width:0!important;min-height:auto!important;height:auto!important;line-height:1.5!important;position:static!important;left:auto!important;right:auto!important;border:none!important;border-bottom:none!important;border-inline-end:none!important;background:transparent!important;white-space:normal!important;overflow:visible!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:before{content:attr(data-header) ": ";font-weight:600;color:var(--tbw-color-header-fg);flex-shrink:0;margin-inline-end:var(--tbw-spacing-md);min-width:100px}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:after{content:none}tbw-grid[data-responsive] .cell[data-utility]{display:none!important}tbw-grid[data-responsive] .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .cell[data-responsive-value-only]{justify-content:flex-start!important;font-weight:500}tbw-grid[data-responsive] .cell[data-responsive-value-only]:before{display:none!important}tbw-grid:not([data-responsive]) .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .tbw-footer,tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows{display:none!important}tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows,tbw-grid[data-responsive] .tbw-aggregation-row{min-width:0!important}tbw-grid[data-responsive] .data-grid-row.responsive-card{display:block!important;padding:var(--tbw-cell-padding);border-bottom:1px solid var(--tbw-color-border)}tbw-grid[data-responsive] .data-grid-row.responsive-card>*{width:100%}tbw-grid[data-responsive] .data-grid-row.responsive-card .cell:before{display:none}';static manifest={incompatibleWith:[{name:"groupingRows",reason:"Responsive card layout does not yet support row grouping. The variable row heights (cards vs group headers) cause scroll calculation issues."}],queries:[{type:"isCardMode",description:"Returns whether the grid is currently in responsive card mode"}]};#e;#t=!1;#i;#r=!1;#s=0;#o=new Set;#n=new Set;#a=null;#d=[];isResponsive(){return this.#t}setResponsive(e){e!==this.#t&&(this.#t=e,this.#h(),this.emit("responsive-change",{isResponsive:e,width:this.#s,breakpoint:this.config.breakpoint??0}))}setBreakpoint(e){this.config.breakpoint=e,this.#l(this.#s)}setCardRenderer(e){this.config.cardRenderer=e,this.#t&&this.requestRender()}getWidth(){return this.#s}getActiveBreakpoint(){return this.#a}attach(e){super.attach(e),this.#p(),this.#u(this.config.hiddenColumns),this.config.breakpoints?.length&&(this.#d=[...this.config.breakpoints].sort((e,t)=>t.maxWidth-e.maxWidth)),this.#e=new ResizeObserver(e=>{const t=e[0]?.contentRect.width??0;this.#s=t,clearTimeout(this.#i),this.#i=setTimeout(()=>{this.#l(t)},this.config.debounceMs??100)}),this.#e.observe(this.gridElement)}#p(){const e=this.grid;if(!e||"function"!=typeof e.querySelector)return;const t=e.querySelector("tbw-grid-responsive-card");if(!t)return;const r=e;if(r.__frameworkAdapter?.parseResponsiveCardElement){const e=r.__frameworkAdapter.parseResponsiveCardElement(t);e&&(this.config={...this.config,cardRenderer:e})}const s=t.getAttribute("breakpoint"),o=t.getAttribute("card-row-height"),n=t.getAttribute("hidden-columns"),a=t.getAttribute("hide-header"),d=t.getAttribute("debounce-ms"),h={};if(null!==s){const e=parseInt(s,10);isNaN(e)||(h.breakpoint=e)}if(null!==o&&(h.cardRowHeight="auto"===o?"auto":parseInt(o,10)),null!==n&&(h.hiddenColumns=n.split(",").map(e=>e.trim()).filter(e=>e.length>0)),null!==a&&(h.hideHeader="false"!==a),null!==d){const e=parseInt(d,10);isNaN(e)||(h.debounceMs=e)}const l=t.innerHTML.trim();!l||this.config.cardRenderer||r.__frameworkAdapter?.parseResponsiveCardElement||(h.cardRenderer=e=>{const t=i.evalTemplateString(l,{value:e,row:e}),r=i.sanitizeHTML(t),s=document.createElement("div");return s.className="tbw-responsive-card-content",s.innerHTML=r,s}),Object.keys(h).length>0&&(this.config={...this.config,...h})}#u(e){if(this.#o.clear(),this.#n.clear(),e)for(const t of e)"string"==typeof t?this.#o.add(t):t.showValue?this.#n.add(t.field):this.#o.add(t.field)}detach(){this.#e?.disconnect(),this.#e=void 0,clearTimeout(this.#i),this.#i=void 0,this.gridElement&&this.gridElement.removeAttribute("data-responsive"),super.detach()}handleQuery(e){if("isCardMode"===e.type)return this.#t}afterRender(){this.#g();if(!(this.#d.length>0?null!==this.#a:this.#t))return;const e=this.#o.size>0,t=this.#n.size>0;if(!e&&!t)return;const i=this.gridElement.querySelectorAll(".cell[data-field]");for(const r of i){const e=r.getAttribute("data-field");e&&(this.#o.has(e)?(r.setAttribute("data-responsive-hidden",""),r.removeAttribute("data-responsive-value-only")):this.#n.has(e)?(r.setAttribute("data-responsive-value-only",""),r.removeAttribute("data-responsive-hidden")):(r.removeAttribute("data-responsive-hidden"),r.removeAttribute("data-responsive-value-only")))}}#l(e){if(this.#d.length>0)return void this.#c(e);const t=this.config.breakpoint??0;0!==t||this.#r||(this.#r=!0,console.warn("[tbw-grid:ResponsivePlugin] No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count."));const i=t>0&&e<t;i!==this.#t&&(this.#t=i,this.#h(),this.emit("responsive-change",{isResponsive:i,width:e,breakpoint:t}),this.requestRender())}#c(e){let t=null;for(const i of this.#d)e<=i.maxWidth&&(t=i);if(t!==this.#a){this.#a=t,t?.hiddenColumns?this.#u(t.hiddenColumns):this.#u(this.config.hiddenColumns);const i=!0===t?.cardLayout;i!==this.#t&&(this.#t=i,this.#h()),this.emit("responsive-change",{isResponsive:this.#t,width:e,breakpoint:t?.maxWidth??0}),this.requestRender()}}#w;#h(){this.gridElement.toggleAttribute("data-responsive",this.#t);const e=!1!==this.config.animate;this.gridElement.toggleAttribute("data-responsive-animate",e),this.config.animationDuration&&this.gridElement.style.setProperty("--tbw-responsive-duration",`${this.config.animationDuration}ms`);const t=this.grid;if(this.#t){t._virtualization&&(this.#w=t._virtualization.rowHeight);const e=this.gridElement.querySelector(".tbw-scroll-area");e&&(e.scrollLeft=0)}else{const e=this.gridElement.querySelectorAll(".data-grid-row");for(const t of e)t.style.height="",t.classList.remove("responsive-card");this.#w&&this.#w>0&&t._virtualization&&(t._virtualization.rowHeight=this.#w,this.#w=void 0),this.#v=void 0,this.#m=void 0,this.#b=void 0}}renderRow(e,t,i){if(!this.#t||!this.config.cardRenderer)return;if(e.__isGroupRow)return;t.replaceChildren();const r=this.config.cardRenderer(e,i);t.className="data-grid-row responsive-card";const s=this.config.cardRowHeight??"auto";return t.style.height="auto"!==s?`${s}px`:"auto",t.appendChild(r),!0}onKeyDown(e){if(!this.#t)return!1;if(this.config.cardRenderer){if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return!1}const i=this.rows.length-1,r=this.visibleColumns.length-1;switch(e.key){case"ArrowDown":if(this.grid._focusCol<r)return this.grid._focusCol+=1,e.preventDefault(),t.ensureCellVisible(this.grid),!0;if(this.grid._focusRow<i)return this.grid._focusRow+=1,this.grid._focusCol=0,e.preventDefault(),t.ensureCellVisible(this.grid),!0;break;case"ArrowUp":if(this.grid._focusCol>0)return this.grid._focusCol-=1,e.preventDefault(),t.ensureCellVisible(this.grid),!0;if(this.grid._focusRow>0)return this.grid._focusRow-=1,this.grid._focusCol=r,e.preventDefault(),t.ensureCellVisible(this.grid),!0;break;case"ArrowRight":if(this.grid._focusRow<i)return this.grid._focusRow+=1,e.preventDefault(),t.ensureCellVisible(this.grid),!0;break;case"ArrowLeft":if(this.grid._focusRow>0)return this.grid._focusRow-=1,e.preventDefault(),t.ensureCellVisible(this.grid),!0}return!1}#v;#m;#b;#f(){if(this.#v&&this.#v>0)return this.#v;const e=this.config.cardRowHeight;return"number"==typeof e&&e>0?e:80}#R(){return this.#m&&this.#m>0?this.#m:this.#w??28}#C(){for(const e of this.rows)if(e.__isGroupRow)return!0;return!1}#y(){let e=0,t=0;for(const i of this.rows)i.__isGroupRow?e++:t++;return{groupCount:e,cardCount:t}}getExtraHeight(){if(!this.#t||!this.config.cardRenderer)return 0;if(!this.#C())return 0;const e=this.#w??28,t=this.#R(),i=this.#f(),{groupCount:r,cardCount:s}=this.#y();return r*Math.max(0,t-e)+s*Math.max(0,i-e)}getExtraHeightBefore(e){if(!this.#t||!this.config.cardRenderer)return 0;if(!this.#C())return 0;const t=this.#w??28,i=this.#R(),r=this.#f(),s=Math.max(0,i-t),o=Math.max(0,r-t);let n=0,a=0;const d=this.rows,h=Math.min(e,d.length);for(let l=0;l<h;l++)d[l].__isGroupRow?n++:a++;return n*s+a*o}getRowHeight(e,t){if(this.#t&&this.config.cardRenderer)return e.__isGroupRow?this.#R():this.#f()}#k(){let e=0;for(const t of this.rows)t.__isGroupRow||e++;return e}#H=!1;#g(){if(!this.#t||!this.config.cardRenderer)return;let e=!1;const t=this.grid,i=this.#C(),r=this.#k();if(r!==this.#b&&(this.#b=r,e=!0),i){const t=this.gridElement.querySelector(".data-grid-row.group-row");if(t){const i=t.getBoundingClientRect().height;i>0&&i!==this.#m&&(this.#m=i,e=!0)}}const s=this.gridElement.querySelector(".data-grid-row.responsive-card");if(s){const r=s.getBoundingClientRect().height;r>0&&r!==this.#v&&(this.#v=r,e=!0,!i&&t._virtualization&&(t._virtualization.rowHeight=r))}e&&!this.#H&&(this.#H=!0,queueMicrotask(()=>{this.#H=!1,this.grid&&this.#t&&this.grid.refreshVirtualWindow?.(!0,!0)}))}}e.ResponsivePlugin=s,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/keyboard"),require("../../core/internal/sanitize"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/keyboard","../../core/internal/sanitize","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_responsive={},e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,i,r){"use strict";class o extends r.BaseGridPlugin{name="responsive";version="1.0.0";styles='tbw-grid[data-responsive-animate] .data-grid-row,tbw-grid[data-responsive-animate] .data-grid-row>.cell{transition:opacity var(--tbw-responsive-duration, .2s) ease-out,transform var(--tbw-responsive-duration, .2s) ease-out}tbw-grid[data-responsive][data-responsive-animate] .data-grid-row{animation:responsive-card-enter var(--tbw-responsive-duration, .2s) ease-out}@keyframes responsive-card-enter{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}tbw-grid[data-responsive] .header{display:none!important}tbw-grid[data-responsive] .footer-row{display:none}tbw-grid[data-responsive] .tbw-scroll-area{overflow-x:hidden;min-width:0!important}tbw-grid[data-responsive] .rows-body-wrapper{min-width:0!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row){display:block!important;grid-template-columns:none!important;padding:var(--tbw-cell-padding);padding-inline-start:var(--tbw-spacing-xl);border-bottom:1px solid var(--tbw-color-border);min-height:auto!important;height:auto!important;contain:none!important;content-visibility:visible!important;background:var(--tbw-color-bg);position:relative}tbw-grid[data-responsive] .data-grid-row:not(.group-row):nth-child(2n){background:var(--tbw-color-row-alt)}tbw-grid[data-responsive] .data-grid-row:not(.group-row):hover{background:var(--tbw-color-row-hover)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]{background:var(--tbw-color-selection)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]:before{content:"";position:absolute;inset-inline-start:0;top:0;bottom:0;width:4px;background:var(--tbw-color-accent)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell{display:flex!important;justify-content:space-between;align-items:center;padding:var(--tbw-spacing-xs) var(--tbw-spacing-md);width:100%!important;min-width:0!important;min-height:auto!important;height:auto!important;line-height:1.5!important;position:static!important;left:auto!important;right:auto!important;border:none!important;border-bottom:none!important;border-inline-end:none!important;background:transparent!important;white-space:normal!important;overflow:visible!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:before{content:attr(data-header) ": ";font-weight:600;color:var(--tbw-color-header-fg);flex-shrink:0;margin-inline-end:var(--tbw-spacing-md);min-width:100px}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:after{content:none}tbw-grid[data-responsive] .cell[data-utility]{display:none!important}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-value-only]{justify-content:flex-start!important;font-weight:500}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-value-only]:before{display:none!important}tbw-grid:not([data-responsive]) .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .tbw-footer,tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows{display:none!important}tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows,tbw-grid[data-responsive] .tbw-aggregation-row{min-width:0!important}tbw-grid[data-responsive] .data-grid-row.responsive-card{display:block!important;padding:var(--tbw-cell-padding);border-bottom:1px solid var(--tbw-color-border)}tbw-grid[data-responsive] .data-grid-row.responsive-card>*{width:100%}tbw-grid[data-responsive] .data-grid-row.responsive-card .cell:before{display:none}';static manifest={incompatibleWith:[{name:"groupingRows",reason:"Responsive card layout does not yet support row grouping. The variable row heights (cards vs group headers) cause scroll calculation issues."}],queries:[{type:"isCardMode",description:"Returns whether the grid is currently in responsive card mode"}]};#e;#t=!1;#i;#r=!1;#o=0;#s=new Set;#n=new Set;#a=null;#d=[];isResponsive(){return this.#t}setResponsive(e){e!==this.#t&&(this.#t=e,this.#h(),this.emit("responsive-change",{isResponsive:e,width:this.#o,breakpoint:this.config.breakpoint??0}))}setBreakpoint(e){this.config.breakpoint=e,this.#l(this.#o)}setCardRenderer(e){this.config.cardRenderer=e,this.#t&&this.requestRender()}getWidth(){return this.#o}getActiveBreakpoint(){return this.#a}attach(e){super.attach(e),this.#p(),this.#u(this.config.hiddenColumns),this.config.breakpoints?.length&&(this.#d=[...this.config.breakpoints].sort((e,t)=>t.maxWidth-e.maxWidth)),this.#e=new ResizeObserver(e=>{const t=e[0]?.contentRect.width??0;this.#o=t,clearTimeout(this.#i),this.#i=setTimeout(()=>{this.#l(t)},this.config.debounceMs??100)}),this.#e.observe(this.gridElement)}#p(){const e=this.grid;if(!e||"function"!=typeof e.querySelector)return;const t=e.querySelector("tbw-grid-responsive-card");if(!t)return;const r=e;if(r.__frameworkAdapter?.parseResponsiveCardElement){const e=r.__frameworkAdapter.parseResponsiveCardElement(t);e&&(this.config={...this.config,cardRenderer:e})}const o=t.getAttribute("breakpoint"),s=t.getAttribute("card-row-height"),n=t.getAttribute("hidden-columns"),a=t.getAttribute("hide-header"),d=t.getAttribute("debounce-ms"),h={};if(null!==o){const e=parseInt(o,10);isNaN(e)||(h.breakpoint=e)}if(null!==s&&(h.cardRowHeight="auto"===s?"auto":parseInt(s,10)),null!==n&&(h.hiddenColumns=n.split(",").map(e=>e.trim()).filter(e=>e.length>0)),null!==a&&(h.hideHeader="false"!==a),null!==d){const e=parseInt(d,10);isNaN(e)||(h.debounceMs=e)}const l=t.innerHTML.trim();!l||this.config.cardRenderer||r.__frameworkAdapter?.parseResponsiveCardElement||(h.cardRenderer=e=>{const t=i.evalTemplateString(l,{value:e,row:e}),r=i.sanitizeHTML(t),o=document.createElement("div");return o.className="tbw-responsive-card-content",o.innerHTML=r,o}),Object.keys(h).length>0&&(this.config={...this.config,...h})}#u(e){if(this.#s.clear(),this.#n.clear(),e)for(const t of e)"string"==typeof t?this.#s.add(t):t.showValue?this.#n.add(t.field):this.#s.add(t.field)}detach(){this.#e?.disconnect(),this.#e=void 0,clearTimeout(this.#i),this.#i=void 0,this.gridElement&&this.gridElement.removeAttribute("data-responsive"),super.detach()}handleQuery(e){if("isCardMode"===e.type)return this.#t}afterRender(){this.#g();if(!(this.#d.length>0?null!==this.#a:this.#t))return;const e=this.#s.size>0,t=this.#n.size>0;if(!e&&!t)return;const i=this.gridElement.querySelectorAll(".cell[data-field]");for(const r of i){const e=r.getAttribute("data-field");e&&(this.#s.has(e)?(r.setAttribute("data-responsive-hidden",""),r.removeAttribute("data-responsive-value-only")):this.#n.has(e)?(r.setAttribute("data-responsive-value-only",""),r.removeAttribute("data-responsive-hidden")):(r.removeAttribute("data-responsive-hidden"),r.removeAttribute("data-responsive-value-only")))}}#l(e){if(this.#d.length>0)return void this.#c(e);const t=this.config.breakpoint??0;0!==t||this.#r||(this.#r=!0,console.warn("[tbw-grid:ResponsivePlugin] No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count."));const i=t>0&&e<t;i!==this.#t&&(this.#t=i,this.#h(),this.emit("responsive-change",{isResponsive:i,width:e,breakpoint:t}),this.requestRender())}#c(e){let t=null;for(const i of this.#d)e<=i.maxWidth&&(t=i);if(t!==this.#a){this.#a=t,t?.hiddenColumns?this.#u(t.hiddenColumns):this.#u(this.config.hiddenColumns);const i=!0===t?.cardLayout;i!==this.#t&&(this.#t=i,this.#h()),this.emit("responsive-change",{isResponsive:this.#t,width:e,breakpoint:t?.maxWidth??0}),this.requestRender()}}#w;#h(){this.gridElement.toggleAttribute("data-responsive",this.#t);const e=!1!==this.config.animate;this.gridElement.toggleAttribute("data-responsive-animate",e),this.config.animationDuration&&this.gridElement.style.setProperty("--tbw-responsive-duration",`${this.config.animationDuration}ms`);const t=this.grid;if(this.#t){t._virtualization&&(this.#w=t._virtualization.rowHeight);const e=this.gridElement.querySelector(".tbw-scroll-area");e&&(e.scrollLeft=0)}else{const e=this.gridElement.querySelectorAll(".data-grid-row");for(const t of e)t.style.height="",t.classList.remove("responsive-card");this.#w&&this.#w>0&&t._virtualization&&(t._virtualization.rowHeight=this.#w,this.#w=void 0),this.#v=void 0,this.#m=void 0,this.#b=void 0}}renderRow(e,t,i){if(!this.#t||!this.config.cardRenderer)return;if(e.__isGroupRow)return;t.replaceChildren();const r=this.config.cardRenderer(e,i);t.className="data-grid-row responsive-card";const o=this.config.cardRowHeight??"auto";return t.style.height="auto"!==o?`${o}px`:"auto",t.appendChild(r),!0}onKeyDown(e){if(!this.#t)return!1;if(this.config.cardRenderer){if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return!1}const i=this.rows.length-1,r=this.visibleColumns.length-1;switch(e.key){case"ArrowDown":if(this.grid._focusCol<r)return this.grid._focusCol+=1,e.preventDefault(),t.ensureCellVisible(this.grid),!0;if(this.grid._focusRow<i)return this.grid._focusRow+=1,this.grid._focusCol=0,e.preventDefault(),t.ensureCellVisible(this.grid),!0;break;case"ArrowUp":if(this.grid._focusCol>0)return this.grid._focusCol-=1,e.preventDefault(),t.ensureCellVisible(this.grid),!0;if(this.grid._focusRow>0)return this.grid._focusRow-=1,this.grid._focusCol=r,e.preventDefault(),t.ensureCellVisible(this.grid),!0;break;case"ArrowRight":if(this.grid._focusRow<i)return this.grid._focusRow+=1,e.preventDefault(),t.ensureCellVisible(this.grid),!0;break;case"ArrowLeft":if(this.grid._focusRow>0)return this.grid._focusRow-=1,e.preventDefault(),t.ensureCellVisible(this.grid),!0}return!1}#v;#m;#b;#f(){if(this.#v&&this.#v>0)return this.#v;const e=this.config.cardRowHeight;return"number"==typeof e&&e>0?e:80}#R(){return this.#m&&this.#m>0?this.#m:this.#w??28}#C(){for(const e of this.rows)if(e.__isGroupRow)return!0;return!1}#y(){let e=0,t=0;for(const i of this.rows)i.__isGroupRow?e++:t++;return{groupCount:e,cardCount:t}}getExtraHeight(){if(!this.#t||!this.config.cardRenderer)return 0;if(!this.#C())return 0;const e=this.#w??28,t=this.#R(),i=this.#f(),{groupCount:r,cardCount:o}=this.#y();return r*Math.max(0,t-e)+o*Math.max(0,i-e)}getExtraHeightBefore(e){if(!this.#t||!this.config.cardRenderer)return 0;if(!this.#C())return 0;const t=this.#w??28,i=this.#R(),r=this.#f(),o=Math.max(0,i-t),s=Math.max(0,r-t);let n=0,a=0;const d=this.rows,h=Math.min(e,d.length);for(let l=0;l<h;l++)d[l].__isGroupRow?n++:a++;return n*o+a*s}getRowHeight(e,t){if(this.#t&&this.config.cardRenderer)return e.__isGroupRow?this.#R():this.#f()}#k(){let e=0;for(const t of this.rows)t.__isGroupRow||e++;return e}#H=!1;#g(){if(!this.#t||!this.config.cardRenderer)return;let e=!1;const t=this.grid,i=this.#C(),r=this.#k();if(r!==this.#b&&(this.#b=r,e=!0),i){const t=this.gridElement.querySelector(".data-grid-row.group-row");if(t){const i=t.getBoundingClientRect().height;i>0&&i!==this.#m&&(this.#m=i,e=!0)}}const o=this.gridElement.querySelector(".data-grid-row.responsive-card");if(o){const r=o.getBoundingClientRect().height;r>0&&r!==this.#v&&(this.#v=r,e=!0,!i&&t._virtualization&&(t._virtualization.rowHeight=r))}e&&!this.#H&&(this.#H=!0,queueMicrotask(()=>{this.#H=!1,this.grid&&this.#t&&this.grid.refreshVirtualWindow?.(!0,!0)}))}}e.ResponsivePlugin=o,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=responsive.umd.js.map
|