@toolbox-web/grid 1.21.1 → 1.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -8
- package/all.js +2 -6850
- package/all.js.map +1 -1
- package/index.js +1 -4352
- package/index.js.map +1 -1
- package/lib/core/grid.d.ts +75 -8
- package/lib/core/grid.d.ts.map +1 -1
- package/lib/core/internal/rows.d.ts.map +1 -1
- package/lib/core/plugin/base-plugin.d.ts +8 -2
- package/lib/core/plugin/base-plugin.d.ts.map +1 -1
- package/lib/core/styles/index.d.ts.map +1 -1
- package/lib/core/types.d.ts +84 -2
- package/lib/core/types.d.ts.map +1 -1
- package/lib/plugins/clipboard/index.js +1 -733
- package/lib/plugins/clipboard/index.js.map +1 -1
- package/lib/plugins/clipboard/types.d.ts +5 -0
- package/lib/plugins/clipboard/types.d.ts.map +1 -1
- package/lib/plugins/column-virtualization/index.js +1 -560
- package/lib/plugins/column-virtualization/index.js.map +1 -1
- package/lib/plugins/column-virtualization/types.d.ts +5 -0
- package/lib/plugins/column-virtualization/types.d.ts.map +1 -1
- package/lib/plugins/context-menu/index.js +1 -754
- package/lib/plugins/context-menu/index.js.map +1 -1
- package/lib/plugins/context-menu/types.d.ts +5 -0
- package/lib/plugins/context-menu/types.d.ts.map +1 -1
- package/lib/plugins/editing/EditingPlugin.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 -1539
- package/lib/plugins/editing/index.js.map +1 -1
- package/lib/plugins/editing/types.d.ts +49 -0
- package/lib/plugins/editing/types.d.ts.map +1 -1
- package/lib/plugins/export/index.js +1 -589
- package/lib/plugins/export/index.js.map +1 -1
- package/lib/plugins/export/types.d.ts +5 -0
- package/lib/plugins/export/types.d.ts.map +1 -1
- package/lib/plugins/filtering/FilteringPlugin.d.ts.map +1 -1
- package/lib/plugins/filtering/filter-model.d.ts.map +1 -1
- package/lib/plugins/filtering/index.js +1 -1283
- package/lib/plugins/filtering/index.js.map +1 -1
- package/lib/plugins/filtering/types.d.ts +7 -2
- package/lib/plugins/filtering/types.d.ts.map +1 -1
- package/lib/plugins/grouping-columns/index.js +1 -726
- package/lib/plugins/grouping-columns/index.js.map +1 -1
- package/lib/plugins/grouping-columns/types.d.ts +3 -0
- package/lib/plugins/grouping-columns/types.d.ts.map +1 -1
- package/lib/plugins/grouping-rows/index.js +2 -905
- package/lib/plugins/grouping-rows/index.js.map +1 -1
- package/lib/plugins/grouping-rows/types.d.ts +5 -0
- package/lib/plugins/grouping-rows/types.d.ts.map +1 -1
- package/lib/plugins/master-detail/index.js +1 -950
- package/lib/plugins/master-detail/index.js.map +1 -1
- package/lib/plugins/master-detail/types.d.ts +5 -0
- package/lib/plugins/master-detail/types.d.ts.map +1 -1
- package/lib/plugins/multi-sort/index.js +1 -553
- package/lib/plugins/multi-sort/index.js.map +1 -1
- package/lib/plugins/multi-sort/types.d.ts +5 -0
- package/lib/plugins/multi-sort/types.d.ts.map +1 -1
- package/lib/plugins/pinned-columns/index.js +1 -688
- package/lib/plugins/pinned-columns/index.js.map +1 -1
- package/lib/plugins/pinned-columns/types.d.ts +3 -0
- package/lib/plugins/pinned-columns/types.d.ts.map +1 -1
- package/lib/plugins/pinned-rows/index.js +1 -704
- package/lib/plugins/pinned-rows/index.js.map +1 -1
- package/lib/plugins/pinned-rows/types.d.ts +5 -0
- package/lib/plugins/pinned-rows/types.d.ts.map +1 -1
- package/lib/plugins/pivot/index.js +1 -1191
- package/lib/plugins/pivot/index.js.map +1 -1
- package/lib/plugins/pivot/types.d.ts +5 -0
- package/lib/plugins/pivot/types.d.ts.map +1 -1
- package/lib/plugins/print/index.js +1 -691
- package/lib/plugins/print/index.js.map +1 -1
- package/lib/plugins/print/types.d.ts +3 -0
- package/lib/plugins/print/types.d.ts.map +1 -1
- package/lib/plugins/reorder/index.js +1 -703
- package/lib/plugins/reorder/index.js.map +1 -1
- package/lib/plugins/reorder/types.d.ts +5 -0
- package/lib/plugins/reorder/types.d.ts.map +1 -1
- package/lib/plugins/responsive/index.js +1 -971
- package/lib/plugins/responsive/index.js.map +1 -1
- package/lib/plugins/responsive/types.d.ts +5 -0
- package/lib/plugins/responsive/types.d.ts.map +1 -1
- package/lib/plugins/row-reorder/index.js +1 -728
- package/lib/plugins/row-reorder/index.js.map +1 -1
- package/lib/plugins/row-reorder/types.d.ts +5 -0
- package/lib/plugins/row-reorder/types.d.ts.map +1 -1
- package/lib/plugins/selection/index.js +1 -1071
- package/lib/plugins/selection/index.js.map +1 -1
- package/lib/plugins/selection/types.d.ts +3 -0
- package/lib/plugins/selection/types.d.ts.map +1 -1
- package/lib/plugins/server-side/index.js +1 -521
- package/lib/plugins/server-side/index.js.map +1 -1
- package/lib/plugins/server-side/types.d.ts +5 -0
- package/lib/plugins/server-side/types.d.ts.map +1 -1
- package/lib/plugins/tree/index.js +1 -686
- package/lib/plugins/tree/index.js.map +1 -1
- package/lib/plugins/tree/types.d.ts +5 -0
- package/lib/plugins/tree/types.d.ts.map +1 -1
- package/lib/plugins/undo-redo/index.js +1 -584
- package/lib/plugins/undo-redo/index.js.map +1 -1
- package/lib/plugins/undo-redo/types.d.ts +5 -0
- package/lib/plugins/undo-redo/types.d.ts.map +1 -1
- package/lib/plugins/visibility/index.js +1 -792
- package/lib/plugins/visibility/index.js.map +1 -1
- package/lib/plugins/visibility/types.d.ts +5 -0
- package/lib/plugins/visibility/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/umd/grid.all.umd.js +1 -186
- package/umd/grid.all.umd.js.map +1 -1
- package/umd/grid.umd.js +1 -90
- package/umd/grid.umd.js.map +1 -1
- package/umd/plugins/clipboard.umd.js +1 -6
- package/umd/plugins/clipboard.umd.js.map +1 -1
- package/umd/plugins/column-virtualization.umd.js +1 -1
- package/umd/plugins/column-virtualization.umd.js.map +1 -1
- package/umd/plugins/context-menu.umd.js +1 -1
- package/umd/plugins/context-menu.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 +1 -13
- 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/grouping-rows.umd.js +1 -4
- package/umd/plugins/grouping-rows.umd.js.map +1 -1
- package/umd/plugins/master-detail.umd.js +1 -1
- package/umd/plugins/master-detail.umd.js.map +1 -1
- package/umd/plugins/multi-sort.umd.js +1 -1
- package/umd/plugins/multi-sort.umd.js.map +1 -1
- package/umd/plugins/pinned-columns.umd.js +1 -1
- package/umd/plugins/pinned-columns.umd.js.map +1 -1
- package/umd/plugins/pinned-rows.umd.js +1 -1
- package/umd/plugins/pinned-rows.umd.js.map +1 -1
- package/umd/plugins/pivot.umd.js +1 -1
- package/umd/plugins/pivot.umd.js.map +1 -1
- package/umd/plugins/print.umd.js +1 -75
- package/umd/plugins/print.umd.js.map +1 -1
- package/umd/plugins/reorder.umd.js +1 -1
- package/umd/plugins/reorder.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/row-reorder.umd.js +1 -1
- package/umd/plugins/row-reorder.umd.js.map +1 -1
- package/umd/plugins/selection.umd.js +1 -3
- package/umd/plugins/selection.umd.js.map +1 -1
- package/umd/plugins/server-side.umd.js +1 -1
- package/umd/plugins/server-side.umd.js.map +1 -1
- package/umd/plugins/tree.umd.js +1 -1
- package/umd/plugins/tree.umd.js.map +1 -1
- package/umd/plugins/undo-redo.umd.js +1 -1
- package/umd/plugins/undo-redo.umd.js.map +1 -1
- package/umd/plugins/visibility.umd.js +1 -1
- package/umd/plugins/visibility.umd.js.map +1 -1
|
@@ -1,7 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
`,s=c.replace(/\r\n/g,`
|
|
3
|
-
`).replace(/\r/g,`
|
|
4
|
-
`),o=[];let r=[],l="",a=!1;for(let i=0;i<s.length;i++){const d=s[i];d==='"'&&!a?a=!0:d==='"'&&a?s[i+1]==='"'?(l+='"',i++):a=!1:d===e&&!a?(r.push(l),l=""):d===n&&!a?(r.push(l),l="",(r.length>1||r.some(u=>u.trim()!==""))&&o.push(r),r=[]):l+=d}return r.push(l),(r.length>1||r.some(i=>i.trim()!==""))&&o.push(r),o}async function P(){try{return await navigator.clipboard.readText()}catch{return""}}function x(c,t){const{rows:e,target:n,fields:s}=c;if(!n)return;const o=t.rows,r=t.effectiveConfig.columns??[],l=r.map(u=>u.field),a=new Map;r.forEach(u=>{a.set(u.field,u.editable===!0)});const i=[...o],d=n.bounds?n.bounds.endRow:1/0;e.forEach((u,m)=>{const f=n.row+m;if(!(f>d)){if(n.bounds){if(f>=i.length)return}else for(;f>=i.length;){const g={};l.forEach(w=>g[w]=""),i.push(g)}i[f]={...i[f]},u.forEach((g,w)=>{const p=s[w];p&&a.get(p)&&(i[f][p]=g)})}}),t.rows=i}class M extends y.BaseGridPlugin{static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:" ",newline:`
|
|
5
|
-
`,quoteStrings:!1}}lastCopied=null;attach(t){super.attach(t),t.addEventListener("paste",n=>this.#o(n),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}onKeyDown(t){return(t.ctrlKey||t.metaKey)&&t.key==="c"?(t.preventDefault(),this.#s(t.target),!0):!1}#s(t){const e=this.#e();if(e&&e.ranges.length===0){const n=this.#r(t);if(!n)return;const s=this.columns[n.col];if(!s)return;this.copy({rowIndices:[n.row],columns:[s.field]});return}this.copy()}#o(t){const e=t.clipboardData?.getData("text/plain");if(!e)return;t.preventDefault();const n=b(e,this.config),s=this.#e(),o=s?.ranges?.[0],r=o?.from.row??0,l=o?.from.col??0,i=o&&(s?.mode==="range"||s?.mode==="row")&&(o.from.row!==o.to.row||o.from.col!==o.to.col)?{endRow:o.to.row,endCol:o.to.col}:null,d=i?.endCol??this.visibleColumns.length-1,u=this.visibleColumns[l],m=u?{row:r,col:l,field:u.field,bounds:i}:null,f=[],g=n[0]?.length??0;for(let p=0;p<g&&l+p<=d;p++){const R=this.visibleColumns[l+p];R&&f.push(R.field)}const w={rows:n,text:e,target:m,fields:f};this.emit("paste",w),this.#i(w)}#i(t){if(!this.grid)return;const{pasteHandler:e}=this.config;if(e===null)return;(e??x)(t,this.grid)}#e(){return this.grid?.query("getSelection")?.[0]}#t(t){const e=this.#e();let n;if(t?.columns)n=C(this.columns,t.columns);else if(e?.ranges.length&&e.mode!=="row"){const o=e.ranges[e.ranges.length-1],r=Math.min(o.from.col,o.to.col),l=Math.max(o.from.col,o.to.col);n=C(this.visibleColumns.slice(r,l+1))}else n=C(this.columns);let s;if(t?.rowIndices)s=S(this.rows,t.rowIndices);else if(e?.ranges.length){const o=e.ranges[e.ranges.length-1],r=Math.min(o.from.row,o.to.row),l=Math.max(o.from.row,o.to.row);s=[];for(let a=r;a<=l;a++){const i=this.rows[a];i&&s.push(i)}}else s=this.rows;return{columns:n,rows:s}}#n(t,e,n){const s=n?.delimiter??this.config.delimiter??" ",o=n?.newline??this.config.newline??`
|
|
6
|
-
`,r=n?.includeHeaders??this.config.includeHeaders??!1,l=n?.processCell??this.config.processCell,a=[];r&&a.push(t.map(i=>i.header||i.field).join(s));for(const i of e){const d=t.map(u=>{const m=i[u.field];return l?l(m,u.field,i):T(m)});a.push(d.join(s))}return a.join(o)}#r(t){const e=t.closest("[data-field-cache]");if(!e)return null;const n=e.dataset.fieldCache,s=e.dataset.row;if(!n||!s)return null;const o=parseInt(s,10);if(isNaN(o))return null;const r=this.columns.findIndex(l=>l.field===n);return r===-1?null:{row:o,col:r}}getSelectionAsText(t){const{columns:e,rows:n}=this.#t(t);return e.length===0||n.length===0?"":this.#n(e,n,t)}async copy(t){const{columns:e,rows:n}=this.#t(t);if(e.length===0||n.length===0)return"";const s=this.#n(e,n,t);return await I(s),this.lastCopied={text:s,timestamp:Date.now()},this.emit("copy",{text:s,rowCount:n.length,columnCount:e.length}),s}async copyRows(t,e){return t.length===0?"":this.copy({...e,rowIndices:t})}async paste(){const t=await P();return t?b(t,this.config):null}getLastCopied(){return this.lastCopied}}h.ClipboardPlugin=M,h.defaultPasteHandler=x,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_clipboard={},e.TbwGrid)}(this,function(e,t){"use strict";function n(e,t,n=!0){let o=e;if(n&&(o=o.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.meta?.utility)),t?.length){const e=new Set(t);o=o.filter(t=>e.has(t.field))}return o}function o(e){return null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}function i(e,t){const n=t.delimiter??"\t",o=t.newline??"\n",i=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),s=[];let l=[],r="",c=!1;for(let a=0;a<i.length;a++){const e=i[a];'"'!==e||c?'"'===e&&c?'"'===i[a+1]?(r+='"',a++):c=!1:e!==n||c?e!==o||c?r+=e:(l.push(r),r="",(l.length>1||l.some(e=>""!==e.trim()))&&s.push(l),l=[]):(l.push(r),r=""):c=!0}return l.push(r),(l.length>1||l.some(e=>""!==e.trim()))&&s.push(l),s}function s(e,t){const{rows:n,target:o,fields:i}=e;if(!o)return;const s=t.rows,l=t.effectiveConfig.columns??[],r=l.map(e=>e.field),c=new Map;l.forEach(e=>{c.set(e.field,!0===e.editable)});const a=[...s],u=o.bounds?o.bounds.endRow:1/0;n.forEach((e,t)=>{const n=o.row+t;if(!(n>u)){if(o.bounds){if(n>=a.length)return}else for(;n>=a.length;){const e={};r.forEach(t=>e[t]=""),a.push(e)}a[n]={...a[n]},e.forEach((e,t)=>{const o=i[t];o&&c.get(o)&&(a[n][o]=e)})}}),t.rows=a}class l extends t.BaseGridPlugin{static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:"\t",newline:"\n",quoteStrings:!1}}lastCopied=null;attach(e){super.attach(e);e.addEventListener("paste",e=>this.#e(e),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#t(e.target),!0)}#t(e){const t=this.#n();if(t&&0===t.ranges.length){const t=this.#o(e);if(!t)return;const n=this.columns[t.col];if(!n)return;return void this.copy({rowIndices:[t.row],columns:[n.field]})}this.copy()}#e(e){const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const n=i(t,this.config),o=this.#n(),s=o?.ranges?.[0],l=s?.from.row??0,r=s?.from.col??0,c=s&&("range"===o?.mode||"row"===o?.mode)&&(s.from.row!==s.to.row||s.from.col!==s.to.col)?{endRow:s.to.row,endCol:s.to.col}:null,a=c?.endCol??this.visibleColumns.length-1,u=this.visibleColumns[r],d=u?{row:l,col:r,field:u.field,bounds:c}:null,f=[],h=n[0]?.length??0;for(let i=0;i<h&&r+i<=a;i++){const e=this.visibleColumns[r+i];e&&f.push(e.field)}const g={rows:n,text:t,target:d,fields:f};this.emit("paste",g),this.#i(g)}#i(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??s)(e,this.grid)}#n(){const e=this.grid?.query("getSelection");return e?.[0]}#s(e){const t=this.#n();let o,i;if(e?.columns)o=n(this.columns,e.columns);else if(t?.ranges.length&&"row"!==t.mode){const e=t.ranges[t.ranges.length-1],i=Math.min(e.from.col,e.to.col),s=Math.max(e.from.col,e.to.col);o=n(this.visibleColumns.slice(i,s+1))}else o=n(this.columns);if(e?.rowIndices)i=function(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}(this.rows,e.rowIndices);else if(t?.ranges.length){const e=t.ranges[t.ranges.length-1],n=Math.min(e.from.row,e.to.row),o=Math.max(e.from.row,e.to.row);i=[];for(let t=n;t<=o;t++){const e=this.rows[t];e&&i.push(e)}}else i=this.rows;return{columns:o,rows:i}}#l(e,t,n){const i=n?.delimiter??this.config.delimiter??"\t",s=n?.newline??this.config.newline??"\n",l=n?.includeHeaders??this.config.includeHeaders??!1,r=n?.processCell??this.config.processCell,c=[];l&&c.push(e.map(e=>e.header||e.field).join(i));for(const a of t){const t=e.map(e=>{const t=a[e.field];return r?r(t,e.field,a):o(t)});c.push(t.join(i))}return c.join(s)}#o(e){const t=e.closest("[data-field-cache]");if(!t)return null;const n=t.dataset.fieldCache,o=t.dataset.row;if(!n||!o)return null;const i=parseInt(o,10);if(isNaN(i))return null;const s=this.columns.findIndex(e=>e.field===n);return-1===s?null:{row:i,col:s}}getSelectionAsText(e){const{columns:t,rows:n}=this.#s(e);return 0===t.length||0===n.length?"":this.#l(t,n,e)}async copy(e){const{columns:t,rows:n}=this.#s(e);if(0===t.length||0===n.length)return"";const o=this.#l(t,n,e);return await async function(e){try{return await navigator.clipboard.writeText(e),!0}catch(t){console.warn("[copyToClipboard] Clipboard API failed:",t);const n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",n.style.pointerEvents="none",document.body.appendChild(n),n.select();const o=document.execCommand("copy");return document.body.removeChild(n),o}}(o),this.lastCopied={text:o,timestamp:Date.now()},this.emit("copy",{text:o,rowCount:n.length,columnCount:t.length}),o}async copyRows(e,t){return 0===e.length?"":this.copy({...t,rowIndices:e})}async paste(){const e=await async function(){try{return await navigator.clipboard.readText()}catch{return""}}();return e?i(e,this.config):null}getLastCopied(){return this.lastCopied}}e.ClipboardPlugin=l,e.defaultPasteHandler=s,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
7
2
|
//# sourceMappingURL=clipboard.umd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clipboard.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/shared/data-collection.ts","../../../../../libs/grid/src/lib/plugins/clipboard/copy.ts","../../../../../libs/grid/src/lib/plugins/clipboard/paste.ts","../../../../../libs/grid/src/lib/plugins/clipboard/types.ts","../../../../../libs/grid/src/lib/plugins/clipboard/ClipboardPlugin.ts"],"sourcesContent":["/**\n * Shared Data Collection Utilities\n *\n * Pure functions for resolving columns and formatting values, shared between\n * the Clipboard and Export plugins. Each plugin bundles its own copy of this\n * module (no chunk splitting) since plugin builds inline sibling imports.\n *\n * @internal\n */\n\nimport type { ColumnConfig } from '../../core/types';\n\n/**\n * Resolve which columns to include in a data export or copy operation.\n *\n * Filters out hidden columns, utility columns (`meta.utility`), and\n * internal columns (`__`-prefixed fields). Optionally restricts to an\n * explicit set of field names.\n *\n * @param columns - All column configurations\n * @param fields - If provided, only include columns whose field is in this list\n * @param onlyVisible - When `true` (default), exclude hidden and internal columns\n * @returns Filtered column array preserving original order\n */\nexport function resolveColumns(\n columns: readonly ColumnConfig[],\n fields?: string[],\n onlyVisible = true,\n): ColumnConfig[] {\n let result = columns as ColumnConfig[];\n\n if (onlyVisible) {\n result = result.filter((c) => !c.hidden && !c.field.startsWith('__') && c.meta?.utility !== true);\n }\n\n if (fields?.length) {\n const fieldSet = new Set(fields);\n result = result.filter((c) => fieldSet.has(c.field));\n }\n\n return result;\n}\n\n/**\n * Resolve which rows to include, optionally filtered to specific indices.\n *\n * @param rows - All row data\n * @param indices - If provided, only include rows at these indices (sorted ascending)\n * @returns Filtered row array\n */\nexport function resolveRows<T>(rows: readonly T[], indices?: number[]): T[] {\n if (!indices?.length) return rows as T[];\n\n return [...indices]\n .sort((a, b) => a - b)\n .map((i) => rows[i])\n .filter((r): r is T => r != null);\n}\n\n/**\n * Format a raw cell value as a text string.\n *\n * Provides the common null / Date / object → string conversion shared by\n * both clipboard and export output builders.\n *\n * @param value - The cell value to format\n * @returns A plain-text representation of the value\n */\nexport function formatValueAsText(value: unknown): string {\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n return String(value);\n}\n","/**\n * Clipboard Copy Logic\n *\n * Pure functions for copying grid data to clipboard.\n */\n\nimport type { ColumnConfig } from '../../core/types';\nimport type { ClipboardConfig } from './types';\n\n/** Parameters for building clipboard text */\nexport interface CopyParams {\n /** All grid rows */\n rows: unknown[];\n /** Column configurations */\n columns: ColumnConfig[];\n /** Selected row indices */\n selectedIndices: Set<number> | number[];\n /** Clipboard configuration */\n config: ClipboardConfig;\n}\n\n/**\n * Format a cell value for clipboard output.\n *\n * Uses custom processCell if provided, otherwise applies default formatting:\n * - null/undefined → empty string\n * - Date → ISO string\n * - Object → JSON string\n * - Other → String conversion with optional quoting\n *\n * @param value - The cell value to format\n * @param field - The field name\n * @param row - The full row object\n * @param config - Clipboard configuration\n * @returns Formatted string value\n */\nexport function formatCellValue(value: unknown, field: string, row: unknown, config: ClipboardConfig): string {\n if (config.processCell) {\n return config.processCell(value, field, row);\n }\n\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n\n const str = String(value);\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Quote if contains delimiter, newline, or quotes (or if quoteStrings is enabled)\n if (config.quoteStrings || str.includes(delimiter) || str.includes(newline) || str.includes('\"')) {\n return `\"${str.replace(/\"/g, '\"\"')}\"`;\n }\n\n return str;\n}\n\n/**\n * Build clipboard text from selected rows and columns.\n *\n * @param params - Copy parameters including rows, columns, selection, and config\n * @returns Tab-separated (or custom delimiter) text ready for clipboard\n */\nexport function buildClipboardText(params: CopyParams): string {\n const { rows, columns, selectedIndices, config } = params;\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Filter to visible columns (not hidden, not internal __ prefixed)\n const visibleColumns = columns.filter((c) => !c.hidden && !c.field.startsWith('__'));\n\n const lines: string[] = [];\n\n // Add header row if configured\n if (config.includeHeaders) {\n const headerCells = visibleColumns.map((c) => {\n const header = c.header || c.field;\n // Quote headers if they contain special characters\n if (header.includes(delimiter) || header.includes(newline) || header.includes('\"')) {\n return `\"${header.replace(/\"/g, '\"\"')}\"`;\n }\n return header;\n });\n lines.push(headerCells.join(delimiter));\n }\n\n // Convert indices to sorted array\n const indices = selectedIndices instanceof Set ? [...selectedIndices] : selectedIndices;\n const sortedIndices = [...indices].sort((a, b) => a - b);\n\n // Build data rows\n for (const idx of sortedIndices) {\n const row = rows[idx];\n if (!row) continue;\n\n const cells = visibleColumns.map((col) =>\n formatCellValue((row as Record<string, unknown>)[col.field], col.field, row, config),\n );\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n}\n\n/**\n * Copy text to the system clipboard.\n *\n * Uses the modern Clipboard API when available, with fallback\n * to execCommand for older browsers.\n *\n * @param text - The text to copy\n * @returns Promise resolving to true if successful, false otherwise\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch (err) {\n console.warn('[copyToClipboard] Clipboard API failed:', err);\n // Fallback for older browsers or when Clipboard API is not available\n const textarea = document.createElement('textarea');\n textarea.value = text;\n textarea.style.position = 'fixed';\n textarea.style.opacity = '0';\n textarea.style.pointerEvents = 'none';\n document.body.appendChild(textarea);\n textarea.select();\n const success = document.execCommand('copy');\n document.body.removeChild(textarea);\n return success;\n }\n}\n","/**\n * Clipboard Paste Logic\n *\n * Pure functions for reading and parsing clipboard data.\n */\n\nimport type { ClipboardConfig } from './types';\n\n/**\n * Parse clipboard text into a 2D array of cell values.\n *\n * Handles:\n * - Quoted values (with escaped double quotes \"\")\n * - Multi-line quoted values (newlines within quotes are preserved)\n * - Custom delimiters and newlines\n * - Empty lines (filtered out only if they contain no data)\n *\n * @param text - Raw clipboard text\n * @param config - Clipboard configuration\n * @returns 2D array where each sub-array is a row of cell values\n */\nexport function parseClipboardText(text: string, config: ClipboardConfig): string[][] {\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Handle Windows CRLF line endings\n const normalizedText = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n\n // Parse the entire text handling quoted fields that may span multiple lines\n const rows: string[][] = [];\n let currentRow: string[] = [];\n let currentCell = '';\n let inQuotes = false;\n\n for (let i = 0; i < normalizedText.length; i++) {\n const char = normalizedText[i];\n\n if (char === '\"' && !inQuotes) {\n // Start of quoted field\n inQuotes = true;\n } else if (char === '\"' && inQuotes) {\n // Check for escaped quote (\"\")\n if (normalizedText[i + 1] === '\"') {\n currentCell += '\"';\n i++; // Skip the second quote\n } else {\n // End of quoted field\n inQuotes = false;\n }\n } else if (char === delimiter && !inQuotes) {\n // Field separator\n currentRow.push(currentCell);\n currentCell = '';\n } else if (char === newline && !inQuotes) {\n // Row separator (only if not inside quotes)\n currentRow.push(currentCell);\n currentCell = '';\n // Only add non-empty rows (at least one non-empty cell or multiple cells)\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n currentRow = [];\n } else {\n currentCell += char;\n }\n }\n\n // Handle the last cell and row\n currentRow.push(currentCell);\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n\n return rows;\n}\n\n/**\n * Read text from the system clipboard.\n *\n * Uses the modern Clipboard API. Returns empty string if\n * the API is not available or permission is denied.\n *\n * @returns Promise resolving to clipboard text or empty string\n */\nexport async function readFromClipboard(): Promise<string> {\n try {\n return await navigator.clipboard.readText();\n } catch {\n // Permission denied or API not available\n return '';\n }\n}\n","/**\n * Clipboard Plugin Types\n *\n * Type definitions for clipboard copy/paste functionality.\n */\n\nimport type { GridElement } from '../../core/plugin/base-plugin';\n\n/**\n * Custom paste handler function.\n *\n * @param detail - The parsed paste data with target and field info\n * @param grid - The grid element to update\n * @returns `false` to prevent the default paste behavior, or `void`/`true` to allow it\n *\n * @example\n * ```ts\n * // Custom handler that validates before pasting\n * new ClipboardPlugin({\n * pasteHandler: (detail, grid) => {\n * if (!detail.target) return false;\n * // Apply custom validation/transformation...\n * applyPasteData(detail, grid);\n * return false; // We handled it, skip default\n * }\n * })\n * ```\n */\nexport type PasteHandler = (detail: PasteDetail, grid: GridElement) => boolean | void;\n\n/**\n * Options for programmatic copy operations.\n *\n * Allows callers to control exactly which columns and rows are included\n * in a copy, independently of the current selection state.\n *\n * @example Copy specific columns from selected rows\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * // User selected rows 0, 2, 4 via a dialog, chose columns to include\n * const text = await clipboard.copy({\n * rowIndices: [0, 2, 4],\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * ```\n */\nexport interface CopyOptions {\n /** Specific column fields to include. If omitted, uses current selection or all visible columns. */\n columns?: string[];\n /** Specific row indices to copy. If omitted, uses current selection or all rows. */\n rowIndices?: number[];\n /** Include column headers in copied text. Defaults to the plugin config value. */\n includeHeaders?: boolean;\n /** Column delimiter override. Defaults to the plugin config value. */\n delimiter?: string;\n /** Row delimiter override. Defaults to the plugin config value. */\n newline?: string;\n /** Custom cell value processor for this operation. Overrides the plugin config's `processCell`. */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n}\n\n/** Configuration options for the clipboard plugin */\nexport interface ClipboardConfig {\n /** Include column headers in copied text (default: false) */\n includeHeaders?: boolean;\n /** Column delimiter character (default: '\\t' for tab) */\n delimiter?: string;\n /** Row delimiter/newline character (default: '\\n') */\n newline?: string;\n /** Wrap string values with quotes (default: false) */\n quoteStrings?: boolean;\n /** Custom cell value processor for copy operations */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n /**\n * Custom paste handler. By default, the plugin applies pasted data to `grid.rows`\n * starting at the target cell.\n *\n * - Set to a custom function to handle paste yourself\n * - Set to `null` to disable auto-paste (event still fires)\n * - Return `false` from handler to prevent default behavior\n *\n * @default defaultPasteHandler (auto-applies paste data)\n */\n pasteHandler?: PasteHandler | null;\n}\n\n/** Internal state managed by the clipboard plugin */\nexport interface ClipboardState {\n /** The last copied text (for reference/debugging) */\n lastCopied: string | null;\n}\n\n/** Event detail emitted after a successful copy operation */\nexport interface CopyDetail {\n /** The text that was copied to clipboard */\n text: string;\n /** Number of rows copied */\n rowCount: number;\n /** Number of columns copied */\n columnCount: number;\n}\n\n/** Target cell coordinates and bounds for paste operations */\nexport interface PasteTarget {\n /** Target row index (top-left of paste area) */\n row: number;\n /** Target column index (top-left of paste area) */\n col: number;\n /** Target column field name (for easy data mapping) */\n field: string;\n /**\n * Selection bounds that constrain the paste area.\n * If set, paste data will be clipped to fit within these bounds.\n * If null, paste expands freely from the target cell.\n */\n bounds: {\n /** End row index (inclusive) */\n endRow: number;\n /** End column index (inclusive) */\n endCol: number;\n } | null;\n}\n\n/** Event detail emitted after a paste operation */\nexport interface PasteDetail {\n /** Parsed rows from clipboard (2D array of cell values) */\n rows: string[][];\n /** Raw text that was pasted */\n text: string;\n /** The target cell where paste starts (top-left of paste area). Null if no cell is selected. */\n target: PasteTarget | null;\n /**\n * Column fields for each column in the paste range, starting from target.col.\n * Useful for mapping parsed cell values to data fields.\n * Length matches the width of the pasted data (or available columns, whichever is smaller).\n */\n fields: string[];\n}\n\n/**\n * Default paste handler that applies pasted data to grid.rows.\n *\n * This is the built-in handler used when no custom `pasteHandler` is configured.\n * It clones the rows array for immutability and applies values starting at the target cell.\n *\n * Behavior:\n * - Single cell selection: paste expands freely, adds new rows if needed\n * - Range/row selection: paste is clipped to fit within selection bounds\n * - Non-editable columns: values are skipped (column alignment preserved)\n *\n * @param detail - The parsed paste data from clipboard\n * @param grid - The grid element to update\n */\nexport function defaultPasteHandler(detail: PasteDetail, grid: GridElement): void {\n const { rows: pastedRows, target, fields } = detail;\n\n // No target = nothing to do\n if (!target) return;\n\n // Get current rows and columns from grid\n const currentRows = grid.rows as Record<string, unknown>[];\n const columns = grid.effectiveConfig.columns ?? [];\n const allFields = columns.map((col) => col.field);\n\n // Build a map of field -> editable for quick lookup\n const editableMap = new Map<string, boolean>();\n columns.forEach((col) => {\n editableMap.set(col.field, col.editable === true);\n });\n\n // Clone data for immutability\n const newRows = [...currentRows];\n\n // Calculate row bounds\n const maxPasteRow = target.bounds ? target.bounds.endRow : Infinity;\n\n // Apply pasted data starting at target cell\n pastedRows.forEach((rowData, rowOffset) => {\n const targetRowIndex = target.row + rowOffset;\n\n // Stop if we've exceeded the selection bounds\n if (targetRowIndex > maxPasteRow) return;\n\n // Only grow array if no bounds (single cell selection)\n if (!target.bounds) {\n while (targetRowIndex >= newRows.length) {\n const emptyRow: Record<string, unknown> = {};\n allFields.forEach((field) => (emptyRow[field] = ''));\n newRows.push(emptyRow);\n }\n } else if (targetRowIndex >= newRows.length) {\n // With bounds, don't paste beyond existing rows\n return;\n }\n\n // Clone the target row and apply values\n newRows[targetRowIndex] = { ...newRows[targetRowIndex] };\n rowData.forEach((cellValue, colOffset) => {\n // fields array is already constrained by bounds in ClipboardPlugin\n const field = fields[colOffset];\n if (field && editableMap.get(field)) {\n // Only paste into editable columns\n newRows[targetRowIndex][field] = cellValue;\n }\n });\n });\n\n // Update grid with new data\n grid.rows = newRows;\n}\n","/**\n * Clipboard Plugin (Class-based)\n *\n * Provides copy/paste functionality for tbw-grid.\n * Supports Ctrl+C/Cmd+C for copying and Ctrl+V/Cmd+V for pasting.\n *\n * **With Selection plugin:** Copies selected cells/rows/range\n * **Without Selection plugin:** Copies entire grid\n */\n\nimport { BaseGridPlugin, type GridElement, type PluginDependency } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport { formatValueAsText, resolveColumns, resolveRows } from '../shared/data-collection';\nimport { copyToClipboard } from './copy';\nimport { parseClipboardText, readFromClipboard } from './paste';\nimport {\n defaultPasteHandler,\n type ClipboardConfig,\n type CopyDetail,\n type CopyOptions,\n type PasteDetail,\n type PasteTarget,\n} from './types';\n\n/**\n * Clipboard Plugin for tbw-grid\n *\n * Brings familiar copy/cut/paste functionality with full keyboard shortcut support\n * (Ctrl+C, Ctrl+X, Ctrl+V). Handles single cells, multi-cell selections, and integrates\n * seamlessly with Excel and other spreadsheet applications via tab-delimited output.\n *\n * > **Optional Dependency:** Works best with SelectionPlugin for copying/pasting selected\n * > cells. Without SelectionPlugin, copies the entire grid and pastes at row 0, column 0.\n *\n * ## Installation\n *\n * ```ts\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `includeHeaders` | `boolean` | `false` | Include column headers in copied data |\n * | `delimiter` | `string` | `'\\t'` | Column delimiter (tab for Excel compatibility) |\n * | `newline` | `string` | `'\\n'` | Row delimiter |\n * | `quoteStrings` | `boolean` | `false` | Wrap string values in quotes |\n * | `processCell` | `(value, field, row) => string` | - | Custom cell value processor |\n * | `pasteHandler` | `PasteHandler \\| null` | `defaultPasteHandler` | Custom paste handler |\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Ctrl+C` / `Cmd+C` | Copy selected cells |\n * | `Ctrl+V` / `Cmd+V` | Paste into selected cells |\n * | `Ctrl+X` / `Cmd+X` | Cut selected cells |\n *\n * ## Paste Behavior by Selection Type\n *\n * | Selection Type | Paste Behavior |\n * |----------------|----------------|\n * | Single cell | Paste expands freely from that cell |\n * | Range selection | Paste is clipped to fit within the selected range |\n * | Row selection | Paste is clipped to the selected rows |\n * | No selection | Paste starts at row 0, column 0 |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `copy` | `(options?: CopyOptions) => Promise<string>` | Copy to clipboard with optional column/row control |\n * | `copyRows` | `(indices, options?) => Promise<string>` | Copy specific rows to clipboard |\n * | `paste` | `() => Promise<string[][] \\| null>` | Read and parse clipboard content |\n * | `getSelectionAsText` | `(options?: CopyOptions) => string` | Get clipboard text without writing to clipboard |\n * | `getLastCopied` | `() => { text, timestamp } \\| null` | Get info about last copy operation |\n *\n * @example Basic Usage with Excel Compatibility\n * ```ts\n * import '@toolbox-web/grid';\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [\n * new SelectionPlugin({ mode: 'range' }),\n * new ClipboardPlugin({\n * includeHeaders: true,\n * delimiter: '\\t', // Tab for Excel\n * }),\n * ],\n * };\n * ```\n *\n * @example Custom Paste Handler\n * ```ts\n * new ClipboardPlugin({\n * pasteHandler: (grid, target, data) => {\n * // Validate or transform data before applying\n * console.log('Pasting', data.length, 'rows');\n * return defaultPasteHandler(grid, target, data);\n * },\n * })\n * ```\n *\n * @see {@link ClipboardConfig} for all configuration options\n * @see {@link SelectionPlugin} for enhanced copy/paste with selection\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {\n /**\n * Plugin dependencies - ClipboardPlugin works best with SelectionPlugin.\n *\n * Without SelectionPlugin: copies entire grid, pastes at row 0 col 0.\n * With SelectionPlugin: copies/pastes based on selection.\n */\n /** @internal */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'selection', required: false, reason: 'Enables copy/paste of selected cells instead of entire grid' },\n ];\n\n /** @internal */\n readonly name = 'clipboard';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ClipboardConfig> {\n return {\n includeHeaders: false,\n delimiter: '\\t',\n newline: '\\n',\n quoteStrings: false,\n };\n }\n\n // #region Internal State\n /** The last copied text (for reference/debugging) */\n private lastCopied: { text: string; timestamp: number } | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Listen for native paste events to get clipboard data synchronously\n // This is more reliable than the async Clipboard API in iframe contexts\n const el = grid as unknown as HTMLElement;\n el.addEventListener('paste', (e: Event) => this.#handleNativePaste(e as ClipboardEvent), {\n signal: this.disconnectSignal,\n });\n }\n\n /** @internal */\n override detach(): void {\n this.lastCopied = null;\n }\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean {\n const isCopy = (event.ctrlKey || event.metaKey) && event.key === 'c';\n\n if (isCopy) {\n // Prevent the browser's default copy action so it doesn't overwrite\n // our clipboard write with whatever text is selected in the DOM.\n event.preventDefault();\n this.#handleCopy(event.target as HTMLElement);\n return true;\n }\n\n // For paste, we do NOT return true - let the native paste event fire\n // so we can access clipboardData synchronously in #handleNativePaste\n return false;\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Handle copy operation from keyboard shortcut.\n *\n * For keyboard-triggered copies, respects the current selection or\n * falls back to the focused cell from the DOM.\n */\n #handleCopy(target: HTMLElement): void {\n const selection = this.#getSelection();\n\n // Selection plugin exists but nothing selected → try focused cell from DOM\n if (selection && selection.ranges.length === 0) {\n const focused = this.#getFocusedCellFromDOM(target);\n if (!focused) return;\n const col = this.columns[focused.col];\n if (!col) return;\n this.copy({ rowIndices: [focused.row], columns: [col.field] });\n return;\n }\n\n // Delegate to the public copy() method (selection or full grid)\n this.copy();\n }\n\n /**\n * Handle native paste event (preferred method - works in iframes).\n * Uses synchronous clipboardData from the native paste event.\n *\n * Flow:\n * 1. Parse clipboard text\n * 2. Build target/fields info from selection\n * 3. Emit 'paste' event (for listeners)\n * 4. Call paste handler (if configured) to apply data to grid\n *\n * Selection behavior:\n * - Single cell: paste starts at cell, expands freely\n * - Range/row: paste is clipped to fit within selection bounds\n * - No selection: paste starts at row 0, col 0\n */\n #handleNativePaste(event: ClipboardEvent): void {\n const text = event.clipboardData?.getData('text/plain');\n if (!text) return;\n\n // Prevent default to avoid pasting into contenteditable elements\n event.preventDefault();\n\n const parsed = parseClipboardText(text, this.config);\n\n // Get target cell from selection via query\n const selection = this.#getSelection();\n const firstRange = selection?.ranges?.[0];\n\n // Determine target cell and bounds\n const targetRow = firstRange?.from.row ?? 0;\n const targetCol = firstRange?.from.col ?? 0;\n\n // Check if multi-cell selection (range with different start/end)\n const isMultiCell =\n firstRange &&\n (selection?.mode === 'range' || selection?.mode === 'row') &&\n (firstRange.from.row !== firstRange.to.row || firstRange.from.col !== firstRange.to.col);\n\n const bounds = isMultiCell ? { endRow: firstRange.to.row, endCol: firstRange.to.col } : null;\n // Selection range indices are visible-column indices (from data-col)\n const maxCol = bounds?.endCol ?? this.visibleColumns.length - 1;\n\n // Build target info\n const column = this.visibleColumns[targetCol];\n const target: PasteTarget | null = column ? { row: targetRow, col: targetCol, field: column.field, bounds } : null;\n\n // Build field list for paste width (constrained by bounds if set)\n const fields: string[] = [];\n const pasteWidth = parsed[0]?.length ?? 0;\n for (let i = 0; i < pasteWidth && targetCol + i <= maxCol; i++) {\n const col = this.visibleColumns[targetCol + i];\n if (col) {\n fields.push(col.field);\n }\n }\n\n const detail: PasteDetail = { rows: parsed, text, target, fields };\n\n // Emit the event for any listeners\n this.emit<PasteDetail>('paste', detail);\n\n // Apply paste data using the configured handler (or default)\n this.#applyPasteHandler(detail);\n }\n\n /**\n * Apply the paste handler to update grid data.\n *\n * Uses the configured `pasteHandler`, or the default handler if not specified.\n * Set `pasteHandler: null` in config to disable auto-paste.\n */\n #applyPasteHandler(detail: PasteDetail): void {\n if (!this.grid) return;\n\n const { pasteHandler } = this.config;\n\n // pasteHandler: null means explicitly disabled\n if (pasteHandler === null) return;\n\n // Use custom handler or default\n const handler = pasteHandler ?? defaultPasteHandler;\n handler(detail, this.grid);\n }\n\n /**\n * Get the current selection via Query System.\n * Returns undefined if no selection plugin is loaded or nothing is selected.\n */\n #getSelection(): SelectionQueryResult | undefined {\n const responses = this.grid?.query<SelectionQueryResult>('getSelection');\n return responses?.[0];\n }\n\n /**\n * Resolve columns and rows to include based on options and/or current selection.\n *\n * Priority for columns:\n * 1. `options.columns` (explicit field list)\n * 2. Selection range column bounds (range/cell mode only)\n * 3. All visible non-utility columns\n *\n * Priority for rows:\n * 1. `options.rowIndices` (explicit indices)\n * 2. Selection range row bounds\n * 3. All rows\n */\n #resolveData(options?: CopyOptions): { columns: ColumnConfig[]; rows: Record<string, unknown>[] } {\n const selection = this.#getSelection();\n\n // --- Columns ---\n let columns: ColumnConfig[];\n if (options?.columns) {\n // Caller specified exact fields\n columns = resolveColumns(this.columns, options.columns);\n } else if (selection?.ranges.length && selection.mode !== 'row') {\n // Range/cell selection: restrict to selection column bounds\n // Selection indices are visible-column indices (from data-col)\n const range = selection.ranges[selection.ranges.length - 1];\n const minCol = Math.min(range.from.col, range.to.col);\n const maxCol = Math.max(range.from.col, range.to.col);\n columns = resolveColumns(this.visibleColumns.slice(minCol, maxCol + 1));\n } else {\n // Row selection or no selection: all visible columns\n columns = resolveColumns(this.columns);\n }\n\n // --- Rows ---\n let rows: Record<string, unknown>[];\n if (options?.rowIndices) {\n // Caller specified exact row indices\n rows = resolveRows(this.rows as Record<string, unknown>[], options.rowIndices);\n } else if (selection?.ranges.length) {\n // Selection range: extract contiguous row range\n const range = selection.ranges[selection.ranges.length - 1];\n const minRow = Math.min(range.from.row, range.to.row);\n const maxRow = Math.max(range.from.row, range.to.row);\n rows = [];\n for (let r = minRow; r <= maxRow; r++) {\n const row = this.rows[r] as Record<string, unknown> | undefined;\n if (row) rows.push(row);\n }\n } else {\n // No selection: all rows\n rows = this.rows as Record<string, unknown>[];\n }\n\n return { columns, rows };\n }\n\n /**\n * Build delimited text from resolved columns and rows.\n */\n #buildText(columns: ColumnConfig[], rows: Record<string, unknown>[], options?: CopyOptions): string {\n const delimiter = options?.delimiter ?? this.config.delimiter ?? '\\t';\n const newline = options?.newline ?? this.config.newline ?? '\\n';\n const includeHeaders = options?.includeHeaders ?? this.config.includeHeaders ?? false;\n const processCell = options?.processCell ?? this.config.processCell;\n\n const lines: string[] = [];\n\n // Header row\n if (includeHeaders) {\n lines.push(columns.map((c) => c.header || c.field).join(delimiter));\n }\n\n // Data rows\n for (const row of rows) {\n const cells = columns.map((col) => {\n const value = row[col.field];\n if (processCell) return processCell(value, col.field, row);\n return formatValueAsText(value);\n });\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n }\n\n /**\n * Get focused cell coordinates from DOM.\n * Used as fallback when SelectionPlugin has no selection.\n */\n #getFocusedCellFromDOM(target: HTMLElement): { row: number; col: number } | null {\n const cell = target.closest('[data-field-cache]') as HTMLElement | null;\n if (!cell) return null;\n\n const field = cell.dataset.fieldCache;\n const rowIndexStr = cell.dataset.row;\n if (!field || !rowIndexStr) return null;\n\n const row = parseInt(rowIndexStr, 10);\n if (isNaN(row)) return null;\n\n const col = this.columns.findIndex((c) => c.field === field);\n if (col === -1) return null;\n\n return { row, col };\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Get the text representation of the current selection (or specified data)\n * without writing to the system clipboard.\n *\n * Useful for previewing what would be copied, or for feeding the text into\n * a custom UI (e.g., a \"copy with column picker\" dialog).\n *\n * @param options - Control which columns/rows to include\n * @returns Delimited text, or empty string if nothing to copy\n *\n * @example Get text for specific columns\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * const text = clipboard.getSelectionAsText({\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * console.log(text);\n * // \"Name\\tEmail\\nAlice\\talice@example.com\\n...\"\n * ```\n */\n getSelectionAsText(options?: CopyOptions): string {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) return '';\n return this.#buildText(columns, rows, options);\n }\n\n /**\n * Copy data to the system clipboard.\n *\n * Without options, copies the current selection (or entire grid if no selection).\n * With options, copies exactly the specified columns and/or rows — ideal for\n * \"copy with column picker\" workflows where the user selects rows first,\n * then chooses which columns to include via a dialog.\n *\n * @param options - Control which columns/rows to include\n * @returns The copied text\n *\n * @example Copy current selection (default)\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * await clipboard.copy();\n * ```\n *\n * @example Copy specific columns from specific rows\n * ```ts\n * // User selected rows in the grid, then picked columns in a dialog\n * const selectedRowIndices = [0, 3, 7];\n * const chosenColumns = ['name', 'department', 'salary'];\n * await clipboard.copy({\n * rowIndices: selectedRowIndices,\n * columns: chosenColumns,\n * includeHeaders: true,\n * });\n * ```\n */\n async copy(options?: CopyOptions): Promise<string> {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) {\n return '';\n }\n\n const text = this.#buildText(columns, rows, options);\n await copyToClipboard(text);\n this.lastCopied = { text, timestamp: Date.now() };\n this.emit<CopyDetail>('copy', {\n text,\n rowCount: rows.length,\n columnCount: columns.length,\n });\n return text;\n }\n\n /**\n * Copy specific rows by index to clipboard.\n *\n * Convenience wrapper around {@link copy} for row-based workflows.\n * Supports non-contiguous row indices (e.g., `[0, 3, 7]`).\n *\n * @param indices - Array of row indices to copy\n * @param options - Additional copy options (columns, headers, etc.)\n * @returns The copied text\n *\n * @example\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * // Copy only rows 0 and 5, including just name and email columns\n * await clipboard.copyRows([0, 5], { columns: ['name', 'email'] });\n * ```\n */\n async copyRows(indices: number[], options?: Omit<CopyOptions, 'rowIndices'>): Promise<string> {\n if (indices.length === 0) return '';\n return this.copy({ ...options, rowIndices: indices });\n }\n\n /**\n * Read and parse clipboard content.\n * @returns Parsed 2D array of cell values, or null if clipboard is empty\n */\n async paste(): Promise<string[][] | null> {\n const text = await readFromClipboard();\n if (!text) return null;\n return parseClipboardText(text, this.config);\n }\n\n /**\n * Get the last copied text and timestamp.\n * @returns The last copied info or null\n */\n getLastCopied(): { text: string; timestamp: number } | null {\n return this.lastCopied;\n }\n // #endregion\n}\n\n// #region Internal Types\n\n/**\n * Range representation for clipboard operations.\n */\ninterface CellRange {\n from: { row: number; col: number };\n to: { row: number; col: number };\n}\n\n/**\n * Selection result returned by the Query System.\n * Matches the SelectionResult type from SelectionPlugin.\n */\ninterface SelectionQueryResult {\n mode: 'cell' | 'row' | 'range';\n ranges: CellRange[];\n anchor: { row: number; col: number } | null;\n}\n// #endregion\n\n// Re-export types\nexport type { ClipboardConfig, CopyDetail, CopyOptions, PasteDetail } from './types';\n"],"names":["resolveColumns","columns","fields","onlyVisible","result","c","fieldSet","resolveRows","rows","indices","a","b","i","r","formatValueAsText","value","copyToClipboard","text","err","textarea","success","parseClipboardText","config","delimiter","newline","normalizedText","currentRow","currentCell","inQuotes","char","readFromClipboard","defaultPasteHandler","detail","grid","pastedRows","target","currentRows","allFields","col","editableMap","newRows","maxPasteRow","rowData","rowOffset","targetRowIndex","emptyRow","field","cellValue","colOffset","ClipboardPlugin","BaseGridPlugin","e","#handleNativePaste","event","#handleCopy","selection","#getSelection","focused","#getFocusedCellFromDOM","parsed","firstRange","targetRow","targetCol","bounds","maxCol","column","pasteWidth","#applyPasteHandler","pasteHandler","#resolveData","options","range","minCol","minRow","maxRow","row","#buildText","includeHeaders","processCell","lines","cells","cell","rowIndexStr"],"mappings":"qUAwBO,SAASA,EACdC,EACAC,EACAC,EAAc,GACE,CAChB,IAAIC,EAASH,EAMb,GAJIE,IACFC,EAASA,EAAO,OAAQC,GAAM,CAACA,EAAE,QAAU,CAACA,EAAE,MAAM,WAAW,IAAI,GAAKA,EAAE,MAAM,UAAY,EAAI,GAG9FH,GAAQ,OAAQ,CAClB,MAAMI,EAAW,IAAI,IAAIJ,CAAM,EAC/BE,EAASA,EAAO,OAAQC,GAAMC,EAAS,IAAID,EAAE,KAAK,CAAC,CACrD,CAEA,OAAOD,CACT,CASO,SAASG,EAAeC,EAAoBC,EAAyB,CAC1E,OAAKA,GAAS,OAEP,CAAC,GAAGA,CAAO,EACf,KAAK,CAACC,EAAGC,IAAMD,EAAIC,CAAC,EACpB,IAAKC,GAAMJ,EAAKI,CAAC,CAAC,EAClB,OAAQC,GAAcA,GAAK,IAAI,EALLL,CAM/B,CAWO,SAASM,EAAkBC,EAAwB,CACxD,O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AAa,CAAE,KAAAA,EAAM,UAAW,KAAK,KAAI,EAC9C,KAAK,KAAiB,OAAQ,CAC5B,KAAAA,EACA,SAAUT,EAAK,OACf,YAAaP,EAAQ,MAAA,CACtB,EACMgB,CACT,CAmBA,MAAM,SAASR,EAAmB6D,EAA4D,CAC5F,OAAI7D,EAAQ,SAAW,EAAU,GAC1B,KAAK,KAAK,CAAE,GAAG6D,EAAS,WAAY7D,EAAS,CACtD,CAMA,MAAM,OAAoC,CACxC,MAAMQ,EAAO,MAAMa,EAAA,EACnB,OAAKb,EACEI,EAAmBJ,EAAM,KAAK,MAAM,EADzB,IAEpB,CAMA,eAA4D,CAC1D,OAAO,KAAK,UACd,CAEF"}
|
|
1
|
+
{"version":3,"file":"clipboard.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/shared/data-collection.ts","../../../../../libs/grid/src/lib/plugins/clipboard/paste.ts","../../../../../libs/grid/src/lib/plugins/clipboard/types.ts","../../../../../libs/grid/src/lib/plugins/clipboard/ClipboardPlugin.ts","../../../../../libs/grid/src/lib/plugins/clipboard/copy.ts"],"sourcesContent":["/**\n * Shared Data Collection Utilities\n *\n * Pure functions for resolving columns and formatting values, shared between\n * the Clipboard and Export plugins. Each plugin bundles its own copy of this\n * module (no chunk splitting) since plugin builds inline sibling imports.\n *\n * @internal\n */\n\nimport type { ColumnConfig } from '../../core/types';\n\n/**\n * Resolve which columns to include in a data export or copy operation.\n *\n * Filters out hidden columns, utility columns (`meta.utility`), and\n * internal columns (`__`-prefixed fields). Optionally restricts to an\n * explicit set of field names.\n *\n * @param columns - All column configurations\n * @param fields - If provided, only include columns whose field is in this list\n * @param onlyVisible - When `true` (default), exclude hidden and internal columns\n * @returns Filtered column array preserving original order\n */\nexport function resolveColumns(\n columns: readonly ColumnConfig[],\n fields?: string[],\n onlyVisible = true,\n): ColumnConfig[] {\n let result = columns as ColumnConfig[];\n\n if (onlyVisible) {\n result = result.filter((c) => !c.hidden && !c.field.startsWith('__') && c.meta?.utility !== true);\n }\n\n if (fields?.length) {\n const fieldSet = new Set(fields);\n result = result.filter((c) => fieldSet.has(c.field));\n }\n\n return result;\n}\n\n/**\n * Resolve which rows to include, optionally filtered to specific indices.\n *\n * @param rows - All row data\n * @param indices - If provided, only include rows at these indices (sorted ascending)\n * @returns Filtered row array\n */\nexport function resolveRows<T>(rows: readonly T[], indices?: number[]): T[] {\n if (!indices?.length) return rows as T[];\n\n return [...indices]\n .sort((a, b) => a - b)\n .map((i) => rows[i])\n .filter((r): r is T => r != null);\n}\n\n/**\n * Format a raw cell value as a text string.\n *\n * Provides the common null / Date / object → string conversion shared by\n * both clipboard and export output builders.\n *\n * @param value - The cell value to format\n * @returns A plain-text representation of the value\n */\nexport function formatValueAsText(value: unknown): string {\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n return String(value);\n}\n","/**\n * Clipboard Paste Logic\n *\n * Pure functions for reading and parsing clipboard data.\n */\n\nimport type { ClipboardConfig } from './types';\n\n/**\n * Parse clipboard text into a 2D array of cell values.\n *\n * Handles:\n * - Quoted values (with escaped double quotes \"\")\n * - Multi-line quoted values (newlines within quotes are preserved)\n * - Custom delimiters and newlines\n * - Empty lines (filtered out only if they contain no data)\n *\n * @param text - Raw clipboard text\n * @param config - Clipboard configuration\n * @returns 2D array where each sub-array is a row of cell values\n */\nexport function parseClipboardText(text: string, config: ClipboardConfig): string[][] {\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Handle Windows CRLF line endings\n const normalizedText = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n\n // Parse the entire text handling quoted fields that may span multiple lines\n const rows: string[][] = [];\n let currentRow: string[] = [];\n let currentCell = '';\n let inQuotes = false;\n\n for (let i = 0; i < normalizedText.length; i++) {\n const char = normalizedText[i];\n\n if (char === '\"' && !inQuotes) {\n // Start of quoted field\n inQuotes = true;\n } else if (char === '\"' && inQuotes) {\n // Check for escaped quote (\"\")\n if (normalizedText[i + 1] === '\"') {\n currentCell += '\"';\n i++; // Skip the second quote\n } else {\n // End of quoted field\n inQuotes = false;\n }\n } else if (char === delimiter && !inQuotes) {\n // Field separator\n currentRow.push(currentCell);\n currentCell = '';\n } else if (char === newline && !inQuotes) {\n // Row separator (only if not inside quotes)\n currentRow.push(currentCell);\n currentCell = '';\n // Only add non-empty rows (at least one non-empty cell or multiple cells)\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n currentRow = [];\n } else {\n currentCell += char;\n }\n }\n\n // Handle the last cell and row\n currentRow.push(currentCell);\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n\n return rows;\n}\n\n/**\n * Read text from the system clipboard.\n *\n * Uses the modern Clipboard API. Returns empty string if\n * the API is not available or permission is denied.\n *\n * @returns Promise resolving to clipboard text or empty string\n */\nexport async function readFromClipboard(): Promise<string> {\n try {\n return await navigator.clipboard.readText();\n } catch {\n // Permission denied or API not available\n return '';\n }\n}\n","/**\n * Clipboard Plugin Types\n *\n * Type definitions for clipboard copy/paste functionality.\n */\n\nimport type { GridElement } from '../../core/plugin/base-plugin';\n\n/**\n * Custom paste handler function.\n *\n * @param detail - The parsed paste data with target and field info\n * @param grid - The grid element to update\n * @returns `false` to prevent the default paste behavior, or `void`/`true` to allow it\n *\n * @example\n * ```ts\n * // Custom handler that validates before pasting\n * new ClipboardPlugin({\n * pasteHandler: (detail, grid) => {\n * if (!detail.target) return false;\n * // Apply custom validation/transformation...\n * applyPasteData(detail, grid);\n * return false; // We handled it, skip default\n * }\n * })\n * ```\n */\nexport type PasteHandler = (detail: PasteDetail, grid: GridElement) => boolean | void;\n\n/**\n * Options for programmatic copy operations.\n *\n * Allows callers to control exactly which columns and rows are included\n * in a copy, independently of the current selection state.\n *\n * @example Copy specific columns from selected rows\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * // User selected rows 0, 2, 4 via a dialog, chose columns to include\n * const text = await clipboard.copy({\n * rowIndices: [0, 2, 4],\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * ```\n */\nexport interface CopyOptions {\n /** Specific column fields to include. If omitted, uses current selection or all visible columns. */\n columns?: string[];\n /** Specific row indices to copy. If omitted, uses current selection or all rows. */\n rowIndices?: number[];\n /** Include column headers in copied text. Defaults to the plugin config value. */\n includeHeaders?: boolean;\n /** Column delimiter override. Defaults to the plugin config value. */\n delimiter?: string;\n /** Row delimiter override. Defaults to the plugin config value. */\n newline?: string;\n /** Custom cell value processor for this operation. Overrides the plugin config's `processCell`. */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n}\n\n/** Configuration options for the clipboard plugin */\nexport interface ClipboardConfig {\n /** Include column headers in copied text (default: false) */\n includeHeaders?: boolean;\n /** Column delimiter character (default: '\\t' for tab) */\n delimiter?: string;\n /** Row delimiter/newline character (default: '\\n') */\n newline?: string;\n /** Wrap string values with quotes (default: false) */\n quoteStrings?: boolean;\n /** Custom cell value processor for copy operations */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n /**\n * Custom paste handler. By default, the plugin applies pasted data to `grid.rows`\n * starting at the target cell.\n *\n * - Set to a custom function to handle paste yourself\n * - Set to `null` to disable auto-paste (event still fires)\n * - Return `false` from handler to prevent default behavior\n *\n * @default defaultPasteHandler (auto-applies paste data)\n */\n pasteHandler?: PasteHandler | null;\n}\n\n/** Internal state managed by the clipboard plugin */\nexport interface ClipboardState {\n /** The last copied text (for reference/debugging) */\n lastCopied: string | null;\n}\n\n/** Event detail emitted after a successful copy operation */\nexport interface CopyDetail {\n /** The text that was copied to clipboard */\n text: string;\n /** Number of rows copied */\n rowCount: number;\n /** Number of columns copied */\n columnCount: number;\n}\n\n/** Target cell coordinates and bounds for paste operations */\nexport interface PasteTarget {\n /** Target row index (top-left of paste area) */\n row: number;\n /** Target column index (top-left of paste area) */\n col: number;\n /** Target column field name (for easy data mapping) */\n field: string;\n /**\n * Selection bounds that constrain the paste area.\n * If set, paste data will be clipped to fit within these bounds.\n * If null, paste expands freely from the target cell.\n */\n bounds: {\n /** End row index (inclusive) */\n endRow: number;\n /** End column index (inclusive) */\n endCol: number;\n } | null;\n}\n\n/** Event detail emitted after a paste operation */\nexport interface PasteDetail {\n /** Parsed rows from clipboard (2D array of cell values) */\n rows: string[][];\n /** Raw text that was pasted */\n text: string;\n /** The target cell where paste starts (top-left of paste area). Null if no cell is selected. */\n target: PasteTarget | null;\n /**\n * Column fields for each column in the paste range, starting from target.col.\n * Useful for mapping parsed cell values to data fields.\n * Length matches the width of the pasted data (or available columns, whichever is smaller).\n */\n fields: string[];\n}\n\n/**\n * Default paste handler that applies pasted data to grid.rows.\n *\n * This is the built-in handler used when no custom `pasteHandler` is configured.\n * It clones the rows array for immutability and applies values starting at the target cell.\n *\n * Behavior:\n * - Single cell selection: paste expands freely, adds new rows if needed\n * - Range/row selection: paste is clipped to fit within selection bounds\n * - Non-editable columns: values are skipped (column alignment preserved)\n *\n * @param detail - The parsed paste data from clipboard\n * @param grid - The grid element to update\n */\nexport function defaultPasteHandler(detail: PasteDetail, grid: GridElement): void {\n const { rows: pastedRows, target, fields } = detail;\n\n // No target = nothing to do\n if (!target) return;\n\n // Get current rows and columns from grid\n const currentRows = grid.rows as Record<string, unknown>[];\n const columns = grid.effectiveConfig.columns ?? [];\n const allFields = columns.map((col) => col.field);\n\n // Build a map of field -> editable for quick lookup\n const editableMap = new Map<string, boolean>();\n columns.forEach((col) => {\n editableMap.set(col.field, col.editable === true);\n });\n\n // Clone data for immutability\n const newRows = [...currentRows];\n\n // Calculate row bounds\n const maxPasteRow = target.bounds ? target.bounds.endRow : Infinity;\n\n // Apply pasted data starting at target cell\n pastedRows.forEach((rowData, rowOffset) => {\n const targetRowIndex = target.row + rowOffset;\n\n // Stop if we've exceeded the selection bounds\n if (targetRowIndex > maxPasteRow) return;\n\n // Only grow array if no bounds (single cell selection)\n if (!target.bounds) {\n while (targetRowIndex >= newRows.length) {\n const emptyRow: Record<string, unknown> = {};\n allFields.forEach((field) => (emptyRow[field] = ''));\n newRows.push(emptyRow);\n }\n } else if (targetRowIndex >= newRows.length) {\n // With bounds, don't paste beyond existing rows\n return;\n }\n\n // Clone the target row and apply values\n newRows[targetRowIndex] = { ...newRows[targetRowIndex] };\n rowData.forEach((cellValue, colOffset) => {\n // fields array is already constrained by bounds in ClipboardPlugin\n const field = fields[colOffset];\n if (field && editableMap.get(field)) {\n // Only paste into editable columns\n newRows[targetRowIndex][field] = cellValue;\n }\n });\n });\n\n // Update grid with new data\n grid.rows = newRows;\n}\n\n// Module Augmentation - Register plugin name for type-safe getPluginByName()\ndeclare module '../../core/types' {\n interface PluginNameMap {\n clipboard: import('./ClipboardPlugin').ClipboardPlugin;\n }\n}\n","/**\n * Clipboard Plugin (Class-based)\n *\n * Provides copy/paste functionality for tbw-grid.\n * Supports Ctrl+C/Cmd+C for copying and Ctrl+V/Cmd+V for pasting.\n *\n * **With Selection plugin:** Copies selected cells/rows/range\n * **Without Selection plugin:** Copies entire grid\n */\n\nimport { BaseGridPlugin, type GridElement, type PluginDependency } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport { formatValueAsText, resolveColumns, resolveRows } from '../shared/data-collection';\nimport { copyToClipboard } from './copy';\nimport { parseClipboardText, readFromClipboard } from './paste';\nimport {\n defaultPasteHandler,\n type ClipboardConfig,\n type CopyDetail,\n type CopyOptions,\n type PasteDetail,\n type PasteTarget,\n} from './types';\n\n/**\n * Clipboard Plugin for tbw-grid\n *\n * Brings familiar copy/cut/paste functionality with full keyboard shortcut support\n * (Ctrl+C, Ctrl+X, Ctrl+V). Handles single cells, multi-cell selections, and integrates\n * seamlessly with Excel and other spreadsheet applications via tab-delimited output.\n *\n * > **Optional Dependency:** Works best with SelectionPlugin for copying/pasting selected\n * > cells. Without SelectionPlugin, copies the entire grid and pastes at row 0, column 0.\n *\n * ## Installation\n *\n * ```ts\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `includeHeaders` | `boolean` | `false` | Include column headers in copied data |\n * | `delimiter` | `string` | `'\\t'` | Column delimiter (tab for Excel compatibility) |\n * | `newline` | `string` | `'\\n'` | Row delimiter |\n * | `quoteStrings` | `boolean` | `false` | Wrap string values in quotes |\n * | `processCell` | `(value, field, row) => string` | - | Custom cell value processor |\n * | `pasteHandler` | `PasteHandler \\| null` | `defaultPasteHandler` | Custom paste handler |\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Ctrl+C` / `Cmd+C` | Copy selected cells |\n * | `Ctrl+V` / `Cmd+V` | Paste into selected cells |\n * | `Ctrl+X` / `Cmd+X` | Cut selected cells |\n *\n * ## Paste Behavior by Selection Type\n *\n * | Selection Type | Paste Behavior |\n * |----------------|----------------|\n * | Single cell | Paste expands freely from that cell |\n * | Range selection | Paste is clipped to fit within the selected range |\n * | Row selection | Paste is clipped to the selected rows |\n * | No selection | Paste starts at row 0, column 0 |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `copy` | `(options?: CopyOptions) => Promise<string>` | Copy to clipboard with optional column/row control |\n * | `copyRows` | `(indices, options?) => Promise<string>` | Copy specific rows to clipboard |\n * | `paste` | `() => Promise<string[][] \\| null>` | Read and parse clipboard content |\n * | `getSelectionAsText` | `(options?: CopyOptions) => string` | Get clipboard text without writing to clipboard |\n * | `getLastCopied` | `() => { text, timestamp } \\| null` | Get info about last copy operation |\n *\n * @example Basic Usage with Excel Compatibility\n * ```ts\n * import '@toolbox-web/grid';\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [\n * new SelectionPlugin({ mode: 'range' }),\n * new ClipboardPlugin({\n * includeHeaders: true,\n * delimiter: '\\t', // Tab for Excel\n * }),\n * ],\n * };\n * ```\n *\n * @example Custom Paste Handler\n * ```ts\n * new ClipboardPlugin({\n * pasteHandler: (grid, target, data) => {\n * // Validate or transform data before applying\n * console.log('Pasting', data.length, 'rows');\n * return defaultPasteHandler(grid, target, data);\n * },\n * })\n * ```\n *\n * @see {@link ClipboardConfig} for all configuration options\n * @see {@link SelectionPlugin} for enhanced copy/paste with selection\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {\n /**\n * Plugin dependencies - ClipboardPlugin works best with SelectionPlugin.\n *\n * Without SelectionPlugin: copies entire grid, pastes at row 0 col 0.\n * With SelectionPlugin: copies/pastes based on selection.\n */\n /** @internal */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'selection', required: false, reason: 'Enables copy/paste of selected cells instead of entire grid' },\n ];\n\n /** @internal */\n readonly name = 'clipboard';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ClipboardConfig> {\n return {\n includeHeaders: false,\n delimiter: '\\t',\n newline: '\\n',\n quoteStrings: false,\n };\n }\n\n // #region Internal State\n /** The last copied text (for reference/debugging) */\n private lastCopied: { text: string; timestamp: number } | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Listen for native paste events to get clipboard data synchronously\n // This is more reliable than the async Clipboard API in iframe contexts\n const el = grid as unknown as HTMLElement;\n el.addEventListener('paste', (e: Event) => this.#handleNativePaste(e as ClipboardEvent), {\n signal: this.disconnectSignal,\n });\n }\n\n /** @internal */\n override detach(): void {\n this.lastCopied = null;\n }\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean {\n const isCopy = (event.ctrlKey || event.metaKey) && event.key === 'c';\n\n if (isCopy) {\n // Prevent the browser's default copy action so it doesn't overwrite\n // our clipboard write with whatever text is selected in the DOM.\n event.preventDefault();\n this.#handleCopy(event.target as HTMLElement);\n return true;\n }\n\n // For paste, we do NOT return true - let the native paste event fire\n // so we can access clipboardData synchronously in #handleNativePaste\n return false;\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Handle copy operation from keyboard shortcut.\n *\n * For keyboard-triggered copies, respects the current selection or\n * falls back to the focused cell from the DOM.\n */\n #handleCopy(target: HTMLElement): void {\n const selection = this.#getSelection();\n\n // Selection plugin exists but nothing selected → try focused cell from DOM\n if (selection && selection.ranges.length === 0) {\n const focused = this.#getFocusedCellFromDOM(target);\n if (!focused) return;\n const col = this.columns[focused.col];\n if (!col) return;\n this.copy({ rowIndices: [focused.row], columns: [col.field] });\n return;\n }\n\n // Delegate to the public copy() method (selection or full grid)\n this.copy();\n }\n\n /**\n * Handle native paste event (preferred method - works in iframes).\n * Uses synchronous clipboardData from the native paste event.\n *\n * Flow:\n * 1. Parse clipboard text\n * 2. Build target/fields info from selection\n * 3. Emit 'paste' event (for listeners)\n * 4. Call paste handler (if configured) to apply data to grid\n *\n * Selection behavior:\n * - Single cell: paste starts at cell, expands freely\n * - Range/row: paste is clipped to fit within selection bounds\n * - No selection: paste starts at row 0, col 0\n */\n #handleNativePaste(event: ClipboardEvent): void {\n const text = event.clipboardData?.getData('text/plain');\n if (!text) return;\n\n // Prevent default to avoid pasting into contenteditable elements\n event.preventDefault();\n\n const parsed = parseClipboardText(text, this.config);\n\n // Get target cell from selection via query\n const selection = this.#getSelection();\n const firstRange = selection?.ranges?.[0];\n\n // Determine target cell and bounds\n const targetRow = firstRange?.from.row ?? 0;\n const targetCol = firstRange?.from.col ?? 0;\n\n // Check if multi-cell selection (range with different start/end)\n const isMultiCell =\n firstRange &&\n (selection?.mode === 'range' || selection?.mode === 'row') &&\n (firstRange.from.row !== firstRange.to.row || firstRange.from.col !== firstRange.to.col);\n\n const bounds = isMultiCell ? { endRow: firstRange.to.row, endCol: firstRange.to.col } : null;\n // Selection range indices are visible-column indices (from data-col)\n const maxCol = bounds?.endCol ?? this.visibleColumns.length - 1;\n\n // Build target info\n const column = this.visibleColumns[targetCol];\n const target: PasteTarget | null = column ? { row: targetRow, col: targetCol, field: column.field, bounds } : null;\n\n // Build field list for paste width (constrained by bounds if set)\n const fields: string[] = [];\n const pasteWidth = parsed[0]?.length ?? 0;\n for (let i = 0; i < pasteWidth && targetCol + i <= maxCol; i++) {\n const col = this.visibleColumns[targetCol + i];\n if (col) {\n fields.push(col.field);\n }\n }\n\n const detail: PasteDetail = { rows: parsed, text, target, fields };\n\n // Emit the event for any listeners\n this.emit<PasteDetail>('paste', detail);\n\n // Apply paste data using the configured handler (or default)\n this.#applyPasteHandler(detail);\n }\n\n /**\n * Apply the paste handler to update grid data.\n *\n * Uses the configured `pasteHandler`, or the default handler if not specified.\n * Set `pasteHandler: null` in config to disable auto-paste.\n */\n #applyPasteHandler(detail: PasteDetail): void {\n if (!this.grid) return;\n\n const { pasteHandler } = this.config;\n\n // pasteHandler: null means explicitly disabled\n if (pasteHandler === null) return;\n\n // Use custom handler or default\n const handler = pasteHandler ?? defaultPasteHandler;\n handler(detail, this.grid);\n }\n\n /**\n * Get the current selection via Query System.\n * Returns undefined if no selection plugin is loaded or nothing is selected.\n */\n #getSelection(): SelectionQueryResult | undefined {\n const responses = this.grid?.query<SelectionQueryResult>('getSelection');\n return responses?.[0];\n }\n\n /**\n * Resolve columns and rows to include based on options and/or current selection.\n *\n * Priority for columns:\n * 1. `options.columns` (explicit field list)\n * 2. Selection range column bounds (range/cell mode only)\n * 3. All visible non-utility columns\n *\n * Priority for rows:\n * 1. `options.rowIndices` (explicit indices)\n * 2. Selection range row bounds\n * 3. All rows\n */\n #resolveData(options?: CopyOptions): { columns: ColumnConfig[]; rows: Record<string, unknown>[] } {\n const selection = this.#getSelection();\n\n // --- Columns ---\n let columns: ColumnConfig[];\n if (options?.columns) {\n // Caller specified exact fields\n columns = resolveColumns(this.columns, options.columns);\n } else if (selection?.ranges.length && selection.mode !== 'row') {\n // Range/cell selection: restrict to selection column bounds\n // Selection indices are visible-column indices (from data-col)\n const range = selection.ranges[selection.ranges.length - 1];\n const minCol = Math.min(range.from.col, range.to.col);\n const maxCol = Math.max(range.from.col, range.to.col);\n columns = resolveColumns(this.visibleColumns.slice(minCol, maxCol + 1));\n } else {\n // Row selection or no selection: all visible columns\n columns = resolveColumns(this.columns);\n }\n\n // --- Rows ---\n let rows: Record<string, unknown>[];\n if (options?.rowIndices) {\n // Caller specified exact row indices\n rows = resolveRows(this.rows as Record<string, unknown>[], options.rowIndices);\n } else if (selection?.ranges.length) {\n // Selection range: extract contiguous row range\n const range = selection.ranges[selection.ranges.length - 1];\n const minRow = Math.min(range.from.row, range.to.row);\n const maxRow = Math.max(range.from.row, range.to.row);\n rows = [];\n for (let r = minRow; r <= maxRow; r++) {\n const row = this.rows[r] as Record<string, unknown> | undefined;\n if (row) rows.push(row);\n }\n } else {\n // No selection: all rows\n rows = this.rows as Record<string, unknown>[];\n }\n\n return { columns, rows };\n }\n\n /**\n * Build delimited text from resolved columns and rows.\n */\n #buildText(columns: ColumnConfig[], rows: Record<string, unknown>[], options?: CopyOptions): string {\n const delimiter = options?.delimiter ?? this.config.delimiter ?? '\\t';\n const newline = options?.newline ?? this.config.newline ?? '\\n';\n const includeHeaders = options?.includeHeaders ?? this.config.includeHeaders ?? false;\n const processCell = options?.processCell ?? this.config.processCell;\n\n const lines: string[] = [];\n\n // Header row\n if (includeHeaders) {\n lines.push(columns.map((c) => c.header || c.field).join(delimiter));\n }\n\n // Data rows\n for (const row of rows) {\n const cells = columns.map((col) => {\n const value = row[col.field];\n if (processCell) return processCell(value, col.field, row);\n return formatValueAsText(value);\n });\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n }\n\n /**\n * Get focused cell coordinates from DOM.\n * Used as fallback when SelectionPlugin has no selection.\n */\n #getFocusedCellFromDOM(target: HTMLElement): { row: number; col: number } | null {\n const cell = target.closest('[data-field-cache]') as HTMLElement | null;\n if (!cell) return null;\n\n const field = cell.dataset.fieldCache;\n const rowIndexStr = cell.dataset.row;\n if (!field || !rowIndexStr) return null;\n\n const row = parseInt(rowIndexStr, 10);\n if (isNaN(row)) return null;\n\n const col = this.columns.findIndex((c) => c.field === field);\n if (col === -1) return null;\n\n return { row, col };\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Get the text representation of the current selection (or specified data)\n * without writing to the system clipboard.\n *\n * Useful for previewing what would be copied, or for feeding the text into\n * a custom UI (e.g., a \"copy with column picker\" dialog).\n *\n * @param options - Control which columns/rows to include\n * @returns Delimited text, or empty string if nothing to copy\n *\n * @example Get text for specific columns\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * const text = clipboard.getSelectionAsText({\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * console.log(text);\n * // \"Name\\tEmail\\nAlice\\talice@example.com\\n...\"\n * ```\n */\n getSelectionAsText(options?: CopyOptions): string {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) return '';\n return this.#buildText(columns, rows, options);\n }\n\n /**\n * Copy data to the system clipboard.\n *\n * Without options, copies the current selection (or entire grid if no selection).\n * With options, copies exactly the specified columns and/or rows — ideal for\n * \"copy with column picker\" workflows where the user selects rows first,\n * then chooses which columns to include via a dialog.\n *\n * @param options - Control which columns/rows to include\n * @returns The copied text\n *\n * @example Copy current selection (default)\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * await clipboard.copy();\n * ```\n *\n * @example Copy specific columns from specific rows\n * ```ts\n * // User selected rows in the grid, then picked columns in a dialog\n * const selectedRowIndices = [0, 3, 7];\n * const chosenColumns = ['name', 'department', 'salary'];\n * await clipboard.copy({\n * rowIndices: selectedRowIndices,\n * columns: chosenColumns,\n * includeHeaders: true,\n * });\n * ```\n */\n async copy(options?: CopyOptions): Promise<string> {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) {\n return '';\n }\n\n const text = this.#buildText(columns, rows, options);\n await copyToClipboard(text);\n this.lastCopied = { text, timestamp: Date.now() };\n this.emit<CopyDetail>('copy', {\n text,\n rowCount: rows.length,\n columnCount: columns.length,\n });\n return text;\n }\n\n /**\n * Copy specific rows by index to clipboard.\n *\n * Convenience wrapper around {@link copy} for row-based workflows.\n * Supports non-contiguous row indices (e.g., `[0, 3, 7]`).\n *\n * @param indices - Array of row indices to copy\n * @param options - Additional copy options (columns, headers, etc.)\n * @returns The copied text\n *\n * @example\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * // Copy only rows 0 and 5, including just name and email columns\n * await clipboard.copyRows([0, 5], { columns: ['name', 'email'] });\n * ```\n */\n async copyRows(indices: number[], options?: Omit<CopyOptions, 'rowIndices'>): Promise<string> {\n if (indices.length === 0) return '';\n return this.copy({ ...options, rowIndices: indices });\n }\n\n /**\n * Read and parse clipboard content.\n * @returns Parsed 2D array of cell values, or null if clipboard is empty\n */\n async paste(): Promise<string[][] | null> {\n const text = await readFromClipboard();\n if (!text) return null;\n return parseClipboardText(text, this.config);\n }\n\n /**\n * Get the last copied text and timestamp.\n * @returns The last copied info or null\n */\n getLastCopied(): { text: string; timestamp: number } | null {\n return this.lastCopied;\n }\n // #endregion\n}\n\n// #region Internal Types\n\n/**\n * Range representation for clipboard operations.\n */\ninterface CellRange {\n from: { row: number; col: number };\n to: { row: number; col: number };\n}\n\n/**\n * Selection result returned by the Query System.\n * Matches the SelectionResult type from SelectionPlugin.\n */\ninterface SelectionQueryResult {\n mode: 'cell' | 'row' | 'range';\n ranges: CellRange[];\n anchor: { row: number; col: number } | null;\n}\n// #endregion\n\n// Re-export types\nexport type { ClipboardConfig, CopyDetail, CopyOptions, PasteDetail } from './types';\n","/**\n * Clipboard Copy Logic\n *\n * Pure functions for copying grid data to clipboard.\n */\n\nimport type { ColumnConfig } from '../../core/types';\nimport type { ClipboardConfig } from './types';\n\n/** Parameters for building clipboard text */\nexport interface CopyParams {\n /** All grid rows */\n rows: unknown[];\n /** Column configurations */\n columns: ColumnConfig[];\n /** Selected row indices */\n selectedIndices: Set<number> | number[];\n /** Clipboard configuration */\n config: ClipboardConfig;\n}\n\n/**\n * Format a cell value for clipboard output.\n *\n * Uses custom processCell if provided, otherwise applies default formatting:\n * - null/undefined → empty string\n * - Date → ISO string\n * - Object → JSON string\n * - Other → String conversion with optional quoting\n *\n * @param value - The cell value to format\n * @param field - The field name\n * @param row - The full row object\n * @param config - Clipboard configuration\n * @returns Formatted string value\n */\nexport function formatCellValue(value: unknown, field: string, row: unknown, config: ClipboardConfig): string {\n if (config.processCell) {\n return config.processCell(value, field, row);\n }\n\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n\n const str = String(value);\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Quote if contains delimiter, newline, or quotes (or if quoteStrings is enabled)\n if (config.quoteStrings || str.includes(delimiter) || str.includes(newline) || str.includes('\"')) {\n return `\"${str.replace(/\"/g, '\"\"')}\"`;\n }\n\n return str;\n}\n\n/**\n * Build clipboard text from selected rows and columns.\n *\n * @param params - Copy parameters including rows, columns, selection, and config\n * @returns Tab-separated (or custom delimiter) text ready for clipboard\n */\nexport function buildClipboardText(params: CopyParams): string {\n const { rows, columns, selectedIndices, config } = params;\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Filter to visible columns (not hidden, not internal __ prefixed)\n const visibleColumns = columns.filter((c) => !c.hidden && !c.field.startsWith('__'));\n\n const lines: string[] = [];\n\n // Add header row if configured\n if (config.includeHeaders) {\n const headerCells = visibleColumns.map((c) => {\n const header = c.header || c.field;\n // Quote headers if they contain special characters\n if (header.includes(delimiter) || header.includes(newline) || header.includes('\"')) {\n return `\"${header.replace(/\"/g, '\"\"')}\"`;\n }\n return header;\n });\n lines.push(headerCells.join(delimiter));\n }\n\n // Convert indices to sorted array\n const indices = selectedIndices instanceof Set ? [...selectedIndices] : selectedIndices;\n const sortedIndices = [...indices].sort((a, b) => a - b);\n\n // Build data rows\n for (const idx of sortedIndices) {\n const row = rows[idx];\n if (!row) continue;\n\n const cells = visibleColumns.map((col) =>\n formatCellValue((row as Record<string, unknown>)[col.field], col.field, row, config),\n );\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n}\n\n/**\n * Copy text to the system clipboard.\n *\n * Uses the modern Clipboard API when available, with fallback\n * to execCommand for older browsers.\n *\n * @param text - The text to copy\n * @returns Promise resolving to true if successful, false otherwise\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch (err) {\n console.warn('[copyToClipboard] Clipboard API failed:', err);\n // Fallback for older browsers or when Clipboard API is not available\n const textarea = document.createElement('textarea');\n textarea.value = text;\n textarea.style.position = 'fixed';\n textarea.style.opacity = '0';\n textarea.style.pointerEvents = 'none';\n document.body.appendChild(textarea);\n textarea.select();\n const success = document.execCommand('copy');\n document.body.removeChild(textarea);\n return success;\n }\n}\n"],"names":["resolveColumns","columns","fields","onlyVisible","result","filter","c","hidden","field","startsWith","meta","utility","length","fieldSet","Set","has","formatValueAsText","value","Date","toISOString","JSON","stringify","String","parseClipboardText","text","config","delimiter","newline","normalizedText","replace","rows","currentRow","currentCell","inQuotes","i","char","push","some","trim","defaultPasteHandler","detail","grid","pastedRows","target","currentRows","effectiveConfig","allFields","map","col","editableMap","Map","forEach","set","editable","newRows","maxPasteRow","bounds","endRow","Infinity","rowData","rowOffset","targetRowIndex","row","emptyRow","cellValue","colOffset","get","ClipboardPlugin","BaseGridPlugin","static","name","required","reason","defaultConfig","includeHeaders","quoteStrings","lastCopied","attach","super","addEventListener","e","this","handleNativePaste","signal","disconnectSignal","detach","onKeyDown","event","ctrlKey","metaKey","key","preventDefault","handleCopy","selection","getSelection","ranges","focused","getFocusedCellFromDOM","copy","rowIndices","clipboardData","getData","parsed","firstRange","targetRow","from","targetCol","mode","to","endCol","maxCol","visibleColumns","column","pasteWidth","emit","applyPasteHandler","pasteHandler","responses","query","resolveData","options","range","minCol","Math","min","max","slice","indices","sort","a","b","r","resolveRows","minRow","maxRow","buildText","processCell","lines","header","join","cells","cell","closest","dataset","fieldCache","rowIndexStr","parseInt","isNaN","findIndex","getSelectionAsText","async","navigator","clipboard","writeText","err","console","warn","textarea","document","createElement","style","position","opacity","pointerEvents","body","appendChild","select","success","execCommand","removeChild","copyToClipboard","timestamp","now","rowCount","columnCount","copyRows","paste","readText","readFromClipboard","getLastCopied"],"mappings":"mVAwBO,SAASA,EACdC,EACAC,EACAC,GAAc,GAEd,IAAIC,EAASH,EAMb,GAJIE,IACFC,EAASA,EAAOC,OAAQC,IAAOA,EAAEC,SAAWD,EAAEE,MAAMC,WAAW,QAA6B,IAApBH,EAAEI,MAAMC,UAG9ET,GAAQU,OAAQ,CAClB,MAAMC,EAAW,IAAIC,IAAIZ,GACzBE,EAASA,EAAOC,OAAQC,GAAMO,EAASE,IAAIT,EAAEE,OAC/C,CAEA,OAAOJ,CACT,CA2BO,SAASY,EAAkBC,GAChC,OAAa,MAATA,EAAsB,GACtBA,aAAiBC,KAAaD,EAAME,cACnB,iBAAVF,EAA2BG,KAAKC,UAAUJ,GAC9CK,OAAOL,EAChB,CCpDO,SAASM,EAAmBC,EAAcC,GAC/C,MAAMC,EAAYD,EAAOC,WAAa,KAChCC,EAAUF,EAAOE,SAAW,KAG5BC,EAAiBJ,EAAKK,QAAQ,QAAS,MAAMA,QAAQ,MAAO,MAG5DC,EAAmB,GACzB,IAAIC,EAAuB,GACvBC,EAAc,GACdC,GAAW,EAEf,IAAA,IAASC,EAAI,EAAGA,EAAIN,EAAehB,OAAQsB,IAAK,CAC9C,MAAMC,EAAOP,EAAeM,GAEf,MAATC,GAAiBF,EAGD,MAATE,GAAgBF,EAEK,MAA1BL,EAAeM,EAAI,IACrBF,GAAe,IACfE,KAGAD,GAAW,EAEJE,IAAST,GAAcO,EAIvBE,IAASR,GAAYM,EAU9BD,GAAeG,GAR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7B,CACT,OAASkI,GACPC,QAAQC,KAAK,0CAA2CF,GAExD,MAAMG,EAAWC,SAASC,cAAc,YACxCF,EAAS5I,MAAQO,EACjBqI,EAASG,MAAMC,SAAW,QAC1BJ,EAASG,MAAME,QAAU,IACzBL,EAASG,MAAMG,cAAgB,OAC/BL,SAASM,KAAKC,YAAYR,GAC1BA,EAASS,SACT,MAAMC,EAAUT,SAASU,YAAY,QAErC,OADAV,SAASM,KAAKK,YAAYZ,GACnBU,CACT,CACF,CDwVUG,CAAgBlJ,GACtByD,KAAKL,WAAa,CAAEpD,OAAMmJ,UAAWzJ,KAAK0J,OAC1C3F,KAAKiC,KAAiB,OAAQ,CAC5B1F,OACAqJ,SAAU/I,EAAKlB,OACfkK,YAAa7K,EAAQW,SAEhBY,CACT,CAmBA,cAAMuJ,CAAShD,EAAmBP,GAChC,OAAuB,IAAnBO,EAAQnH,OAAqB,GAC1BqE,KAAKiB,KAAK,IAAKsB,EAASrB,WAAY4B,GAC7C,CAMA,WAAMiD,GACJ,MAAMxJ,QF5aV8H,iBACE,IACE,aAAaC,UAAUC,UAAUyB,UACnC,CAAA,MAEE,MAAO,EACT,CACF,CEqauBC,GACnB,OAAK1J,EACED,EAAmBC,EAAMyD,KAAKxD,QADnB,IAEpB,CAMA,aAAA0J,GACE,OAAOlG,KAAKL,UACd"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/plugin/base-plugin"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TbwGridPlugin_columnVirtualization={},t.TbwGrid)}(this,function(t,e){"use strict";function i(t){if(null==t)return 100;if("number"==typeof t)return t;const e=parseFloat(t);return isNaN(e)?100:e}function s(t){return t.map(t=>i(t.width))}function o(t){const e=[];let s=0;for(const o of t)e.push(s),s+=i(o.width);return e}function l(t){return t.reduce((t,e)=>t+i(e.width),0)}function n(t,e,i,s,o){const l=i.length;if(0===l)return{startCol:0,endCol:0,visibleColumns:[]};let n=function(t,e,i){let s=0,o=e.length-1;for(;s<o;){const l=Math.floor((s+o)/2);e[l]+i[l]<=t?s=l+1:o=l}return s}(t,i,s);n=Math.max(0,n-o);const r=t+e;let h=n;for(let a=n;a<l;a++){if(i[a]>=r){h=a-1;break}h=a}h=Math.min(l-1,h+o);const u=[];for(let a=n;a<=h;a++)u.push(a);return{startCol:n,endCol:h,visibleColumns:u}}class r extends e.BaseGridPlugin{name="columnVirtualization";get defaultConfig(){return{autoEnable:!0,threshold:30,overscan:3}}isVirtualized=!1;startCol=0;endCol=0;scrollLeft=0;totalWidth=0;columnWidths=[];columnOffsets=[];originalColumns=[];attach(t){super.attach(t);const e=this.columns;this.columnWidths=s(e),this.columnOffsets=o(e),this.totalWidth=l(e),this.endCol=e.length-1}detach(){this.#t(),this.columnWidths=[],this.columnOffsets=[],this.originalColumns=[],this.isVirtualized=!1,this.startCol=0,this.endCol=0,this.scrollLeft=0,this.totalWidth=0}#t(){const t=this.gridElement;if(!t)return;const e=t.querySelector(".header-row");e&&(e.style.paddingLeft="",e.style.minWidth="");t.querySelectorAll(".data-grid-row").forEach(t=>{t.style.paddingLeft=""});const i=t.querySelector(".rows-viewport .rows");i&&(i.style.width="");const s=t.querySelector(".rows-body");s&&(s.style.minWidth="")}processColumns(t){(0===this.originalColumns.length||t.length>=this.originalColumns.length)&&(this.originalColumns=t,this.columnWidths=s(t),this.columnOffsets=o(t),this.totalWidth=l(t));const e=this.originalColumns,i=(r=e.length,h=this.config.threshold??30,!!(this.config.autoEnable??!0)&&r>h);var r,h;if(this.isVirtualized=i??!1,!i)return this.startCol=0,this.endCol=e.length-1,[...e];const u=this.grid.clientWidth||800,a=n(this.scrollLeft,u,this.columnOffsets,this.columnWidths,this.config.overscan??3);return this.startCol=a.startCol,this.endCol=a.endCol,a.visibleColumns.map(t=>e[t])}afterRender(){if(!this.isVirtualized)return;const t=this.gridElement;if(!t)return;const e=this.columnOffsets[this.startCol]??0,i=t.querySelector(".header-row"),s=t.querySelectorAll(".data-grid-row");i&&(i.style.paddingLeft=`${e}px`,i.style.minWidth=`${this.totalWidth}px`),s.forEach(t=>{t.style.paddingLeft=`${e}px`});const o=t.querySelector(".rows-viewport .rows");o&&(o.style.width=`${this.totalWidth}px`);const l=t.querySelector(".rows-body");l&&(l.style.minWidth=`${this.totalWidth}px`)}onScroll(t){if(!this.isVirtualized)return;Math.abs(t.scrollLeft-this.scrollLeft)<1||(this.scrollLeft=t.scrollLeft,this.requestColumnsRender())}getIsVirtualized(){return this.isVirtualized}getVisibleColumnRange(){return{start:this.startCol,end:this.endCol}}scrollToColumn(t){const e=this.columnOffsets[t]??0;this.grid.scrollLeft=e}getColumnOffset(t){return this.columnOffsets[t]??0}getTotalWidth(){return this.totalWidth}}t.ColumnVirtualizationPlugin=r,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=column-virtualization.umd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"column-virtualization.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/column-virtualization/column-virtualization.ts","../../../../../libs/grid/src/lib/plugins/column-virtualization/ColumnVirtualizationPlugin.ts"],"sourcesContent":["/**\n * Column Virtualization Core Logic\n *\n * Pure functions for horizontal column virtualization operations.\n */\n\nimport type { ColumnConfig } from '../../core/types';\nimport type { ColumnVirtualizationViewport } from './types';\n\n/** Default column width when not specified */\nconst DEFAULT_COLUMN_WIDTH = 100;\n\n/**\n * Parse a column width value to pixels.\n * Handles number (px) and string formats.\n *\n * @param width - The width value from column config\n * @returns Width in pixels\n */\nexport function parseColumnWidth(width: string | number | undefined): number {\n if (width === undefined || width === null) {\n return DEFAULT_COLUMN_WIDTH;\n }\n\n if (typeof width === 'number') {\n return width;\n }\n\n // Handle string values - extract numeric part\n const numeric = parseFloat(width);\n if (!isNaN(numeric)) {\n return numeric;\n }\n\n return DEFAULT_COLUMN_WIDTH;\n}\n\n/**\n * Get array of column widths in pixels.\n *\n * @param columns - Column configurations\n * @returns Array of widths in pixels\n */\nexport function getColumnWidths(columns: readonly ColumnConfig[]): number[] {\n return columns.map((col) => parseColumnWidth(col.width));\n}\n\n/**\n * Compute cumulative left offsets for each column.\n *\n * @param columns - Column configurations\n * @returns Array of left offsets in pixels\n */\nexport function computeColumnOffsets(columns: readonly ColumnConfig[]): number[] {\n const offsets: number[] = [];\n let offset = 0;\n\n for (const col of columns) {\n offsets.push(offset);\n offset += parseColumnWidth(col.width);\n }\n\n return offsets;\n}\n\n/**\n * Compute total width of all columns.\n *\n * @param columns - Column configurations\n * @returns Total width in pixels\n */\nexport function computeTotalWidth(columns: readonly ColumnConfig[]): number {\n return columns.reduce((sum, col) => sum + parseColumnWidth(col.width), 0);\n}\n\n/**\n * Find the visible column range based on scroll position.\n * Uses binary search for efficient lookup in large column sets.\n *\n * @param scrollLeft - Current horizontal scroll position\n * @param viewportWidth - Width of the visible viewport\n * @param columnOffsets - Array of column left offsets\n * @param columnWidths - Array of column widths\n * @param overscan - Number of extra columns to render on each side\n * @returns Viewport information with visible column indices\n */\nexport function getVisibleColumnRange(\n scrollLeft: number,\n viewportWidth: number,\n columnOffsets: number[],\n columnWidths: number[],\n overscan: number\n): ColumnVirtualizationViewport {\n const columnCount = columnOffsets.length;\n\n if (columnCount === 0) {\n return { startCol: 0, endCol: 0, visibleColumns: [] };\n }\n\n // Binary search for first visible column\n let startCol = binarySearchFirstVisible(scrollLeft, columnOffsets, columnWidths);\n startCol = Math.max(0, startCol - overscan);\n\n // Find last visible column (without overscan first)\n const rightEdge = scrollLeft + viewportWidth;\n let endCol = startCol;\n\n for (let i = startCol; i < columnCount; i++) {\n if (columnOffsets[i] >= rightEdge) {\n endCol = i - 1;\n break;\n }\n endCol = i;\n }\n\n // Apply overscan to end (only once)\n endCol = Math.min(columnCount - 1, endCol + overscan);\n\n // Build array of visible column indices\n const visibleColumns: number[] = [];\n for (let i = startCol; i <= endCol; i++) {\n visibleColumns.push(i);\n }\n\n return { startCol, endCol, visibleColumns };\n}\n\n/**\n * Binary search to find the first column that is visible.\n *\n * @param scrollLeft - Current scroll position\n * @param columnOffsets - Array of column offsets\n * @param columnWidths - Array of column widths\n * @returns Index of first visible column\n */\nfunction binarySearchFirstVisible(scrollLeft: number, columnOffsets: number[], columnWidths: number[]): number {\n let low = 0;\n let high = columnOffsets.length - 1;\n\n while (low < high) {\n const mid = Math.floor((low + high) / 2);\n const colRight = columnOffsets[mid] + columnWidths[mid];\n\n if (colRight <= scrollLeft) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n\n return low;\n}\n\n/**\n * Determine if column virtualization should be active.\n *\n * @param columnCount - Number of columns\n * @param threshold - Column count threshold\n * @param autoEnable - Whether auto-enable is configured\n * @returns True if virtualization should be active\n */\nexport function shouldVirtualize(columnCount: number, threshold: number, autoEnable: boolean): boolean {\n if (!autoEnable) return false;\n return columnCount > threshold;\n}\n","/**\n * Column Virtualization Plugin (Class-based)\n *\n * Provides horizontal column virtualization for grids with many columns.\n * Significantly improves rendering performance when dealing with >30 columns.\n */\n\nimport { BaseGridPlugin, ScrollEvent } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport {\n computeColumnOffsets,\n computeTotalWidth,\n getColumnWidths,\n getVisibleColumnRange,\n shouldVirtualize,\n} from './column-virtualization';\nimport type { ColumnVirtualizationConfig } from './types';\n\n/**\n * Column Virtualization Plugin for tbw-grid\n *\n * Provides horizontal column virtualization for grids with many columns (30+).\n * Only renders visible columns plus overscan, significantly improving rendering\n * performance for wide grids.\n *\n * ## Installation\n *\n * ```ts\n * import { ColumnVirtualizationPlugin } from '@toolbox-web/grid/plugins/column-virtualization';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `autoEnable` | `boolean` | `true` | Auto-enable when column count exceeds threshold |\n * | `threshold` | `number` | `30` | Column count threshold for auto-enable |\n * | `overscan` | `number` | `3` | Extra columns to render beyond visible |\n *\n * ## Requirements\n *\n * - Grid must use `fitMode: 'fixed'`\n * - Columns must have explicit widths\n * - Grid must have fixed height\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `isEnabled` | `() => boolean` | Check if virtualization is active |\n * | `setEnabled` | `(enabled: boolean) => void` | Enable/disable virtualization |\n * | `getVisibleRange` | `() => { start, end }` | Get visible column range |\n *\n * @example Wide Grid with Column Virtualization\n * ```ts\n * import '@toolbox-web/grid';\n * import { ColumnVirtualizationPlugin } from '@toolbox-web/grid/plugins/column-virtualization';\n *\n * grid.gridConfig = {\n * columns: generateManyColumns(100), // 100 columns\n * fitMode: 'fixed', // Required\n * plugins: [\n * new ColumnVirtualizationPlugin({\n * threshold: 30, // Enable when >30 columns\n * overscan: 3, // Render 3 extra columns each side\n * }),\n * ],\n * };\n * ```\n *\n * @see {@link ColumnVirtualizationConfig} for configuration options\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ColumnVirtualizationPlugin extends BaseGridPlugin<ColumnVirtualizationConfig> {\n /** @internal */\n readonly name = 'columnVirtualization';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ColumnVirtualizationConfig> {\n return {\n autoEnable: true,\n threshold: 30,\n overscan: 3,\n };\n }\n\n // #region Internal State\n private isVirtualized = false;\n private startCol = 0;\n private endCol = 0;\n private scrollLeft = 0;\n private totalWidth = 0;\n private columnWidths: number[] = [];\n private columnOffsets: number[] = [];\n /** Store the original full column set for virtualization calculations */\n private originalColumns: readonly ColumnConfig[] = [];\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 // Initialize state from current columns\n const columns = this.columns;\n this.columnWidths = getColumnWidths(columns);\n this.columnOffsets = computeColumnOffsets(columns);\n this.totalWidth = computeTotalWidth(columns);\n this.endCol = columns.length - 1;\n }\n\n /** @internal */\n override detach(): void {\n // Clean up inline styles set by this plugin\n this.#cleanupStyles();\n\n this.columnWidths = [];\n this.columnOffsets = [];\n this.originalColumns = [];\n this.isVirtualized = false;\n this.startCol = 0;\n this.endCol = 0;\n this.scrollLeft = 0;\n this.totalWidth = 0;\n }\n\n /**\n * Remove inline styles set by this plugin for proper cleanup.\n */\n #cleanupStyles(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const headerRow = gridEl.querySelector('.header-row') as HTMLElement | null;\n if (headerRow) {\n headerRow.style.paddingLeft = '';\n headerRow.style.minWidth = '';\n }\n\n const bodyRows = gridEl.querySelectorAll('.data-grid-row');\n bodyRows.forEach((row) => {\n (row as HTMLElement).style.paddingLeft = '';\n });\n\n const rowsContainer = gridEl.querySelector('.rows-viewport .rows') as HTMLElement | null;\n if (rowsContainer) {\n rowsContainer.style.width = '';\n }\n\n const rowsBody = gridEl.querySelector('.rows-body') as HTMLElement | null;\n if (rowsBody) {\n rowsBody.style.minWidth = '';\n }\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n // Detect if this is a new column set or just a scroll-triggered re-render.\n // We consider it \"new\" if:\n // 1. We don't have any stored yet (first time)\n // 2. Incoming has AS MANY OR MORE columns than we stored (genuine new config)\n // When virtualization is active, our output is a SUBSET (fewer columns),\n // so a scroll-triggered re-render will have fewer columns than originalColumns.\n // When virtualization is off, our output has the same count as originalColumns,\n // but any config change (e.g., pinning a column) also has the same count.\n // Using >= ensures we pick up property-only changes (like adding `pinned`).\n const isNewColumnSet = this.originalColumns.length === 0 || columns.length >= this.originalColumns.length;\n\n if (isNewColumnSet) {\n // Store the full column set\n this.originalColumns = columns;\n this.columnWidths = getColumnWidths(columns);\n this.columnOffsets = computeColumnOffsets(columns);\n this.totalWidth = computeTotalWidth(columns);\n }\n\n // Use the original (full) column set for virtualization decisions\n const fullColumns = this.originalColumns;\n const isVirtualized = shouldVirtualize(\n fullColumns.length,\n this.config.threshold ?? 30,\n this.config.autoEnable ?? true,\n );\n\n this.isVirtualized = isVirtualized ?? false;\n\n if (!isVirtualized) {\n this.startCol = 0;\n this.endCol = fullColumns.length - 1;\n return [...fullColumns];\n }\n\n // Get viewport width from grid element\n const viewportWidth = (this.grid as unknown as HTMLElement).clientWidth || 800;\n const viewport = getVisibleColumnRange(\n this.scrollLeft,\n viewportWidth,\n this.columnOffsets,\n this.columnWidths,\n this.config.overscan ?? 3,\n );\n\n this.startCol = viewport.startCol;\n this.endCol = viewport.endCol;\n\n // Return only visible columns from the ORIGINAL full set\n return viewport.visibleColumns.map((i) => fullColumns[i]);\n }\n\n /** @internal */\n override afterRender(): void {\n if (!this.isVirtualized) return;\n\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n // Apply left padding to offset scrolled-out columns\n const leftPadding = this.columnOffsets[this.startCol] ?? 0;\n\n const headerRow = gridEl.querySelector('.header-row') as HTMLElement | null;\n const bodyRows = gridEl.querySelectorAll('.data-grid-row');\n\n if (headerRow) {\n headerRow.style.paddingLeft = `${leftPadding}px`;\n // Set min-width on header row to enable horizontal scrolling\n headerRow.style.minWidth = `${this.totalWidth}px`;\n }\n\n bodyRows.forEach((row) => {\n (row as HTMLElement).style.paddingLeft = `${leftPadding}px`;\n });\n\n // Set total width for horizontal scrolling on the rows container\n const rowsContainer = gridEl.querySelector('.rows-viewport .rows') as HTMLElement | null;\n if (rowsContainer) {\n rowsContainer.style.width = `${this.totalWidth}px`;\n }\n\n // Also set min-width on .rows-body to ensure the scroll container knows the total scrollable width\n const rowsBody = gridEl.querySelector('.rows-body') as HTMLElement | null;\n if (rowsBody) {\n rowsBody.style.minWidth = `${this.totalWidth}px`;\n }\n }\n\n /** @internal */\n override onScroll(event: ScrollEvent): void {\n if (!this.isVirtualized) return;\n\n // Check if horizontal scroll position changed significantly\n const scrollDelta = Math.abs(event.scrollLeft - this.scrollLeft);\n if (scrollDelta < 1) return;\n\n // Update scroll position\n this.scrollLeft = event.scrollLeft;\n\n // Recalculate visible columns and request re-render\n // Must use requestColumnsRender() to trigger COLUMNS phase (processColumns hook)\n // requestRender() only requests ROWS phase which doesn't reprocess columns\n this.requestColumnsRender();\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Check if column virtualization is currently active.\n */\n getIsVirtualized(): boolean {\n return this.isVirtualized;\n }\n\n /**\n * Get the current visible column range.\n */\n getVisibleColumnRange(): { start: number; end: number } {\n return { start: this.startCol, end: this.endCol };\n }\n\n /**\n * Scroll the grid to bring a specific column into view.\n * @param columnIndex - Index of the column to scroll to\n */\n scrollToColumn(columnIndex: number): void {\n const offset = this.columnOffsets[columnIndex] ?? 0;\n const gridEl = this.grid as unknown as HTMLElement;\n // Scroll the grid element itself (it's the scroll container)\n gridEl.scrollLeft = offset;\n }\n\n /**\n * Get the left offset for a specific column.\n * @param columnIndex - Index of the column\n */\n getColumnOffset(columnIndex: number): number {\n return this.columnOffsets[columnIndex] ?? 0;\n }\n\n /**\n * Get the total width of all columns.\n */\n getTotalWidth(): number {\n return this.totalWidth;\n }\n // #endregion\n}\n"],"names":["parseColumnWidth","width","numeric","getColumnWidths","columns","col","computeColumnOffsets","offsets","offset","computeTotalWidth","sum","getVisibleColumnRange","scrollLeft","viewportWidth","columnOffsets","columnWidths","overscan","columnCount","startCol","binarySearchFirstVisible","rightEdge","endCol","i","visibleColumns","low","high","mid","shouldVirtualize","threshold","autoEnable","ColumnVirtualizationPlugin","BaseGridPlugin","grid","#cleanupStyles","gridEl","headerRow","row","rowsContainer","rowsBody","fullColumns","isVirtualized","viewport","leftPadding","bodyRows","event","columnIndex"],"mappings":"gVAmBO,SAASA,EAAiBC,EAA4C,CAC3E,GAA2BA,GAAU,KACnC,MAAO,KAGT,GAAI,OAAOA,GAAU,SACnB,OAAOA,EAIT,MAAMC,EAAU,WAAWD,CAAK,EAChC,OAAK,MAAMC,CAAO,EAIX,IAHEA,CAIX,CAQO,SAASC,EAAgBC,EAA4C,CAC1E,OAAOA,EAAQ,IA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AAU,KAEhD,CAGS,SAASM,EAA0B,CACtC,CAAC,KAAK,eAGU,KAAK,IAAIA,EAAM,WAAa,KAAK,UAAU,EAC7C,IAGlB,KAAK,WAAaA,EAAM,WAKxB,KAAK,qBAAA,EACP,CAQA,kBAA4B,CAC1B,OAAO,KAAK,aACd,CAKA,uBAAwD,CACtD,MAAO,CAAE,MAAO,KAAK,SAAU,IAAK,KAAK,MAAA,CAC3C,CAMA,eAAeC,EAA2B,CACxC,MAAMrC,EAAS,KAAK,cAAcqC,CAAW,GAAK,EAC5CX,EAAS,KAAK,KAEpBA,EAAO,WAAa1B,CACtB,CAMA,gBAAgBqC,EAA6B,CAC3C,OAAO,KAAK,cAAcA,CAAW,GAAK,CAC5C,CAKA,eAAwB,CACtB,OAAO,KAAK,UACd,CAEF"}
|
|
1
|
+
{"version":3,"file":"column-virtualization.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/column-virtualization/column-virtualization.ts","../../../../../libs/grid/src/lib/plugins/column-virtualization/ColumnVirtualizationPlugin.ts"],"sourcesContent":["/**\n * Column Virtualization Core Logic\n *\n * Pure functions for horizontal column virtualization operations.\n */\n\nimport type { ColumnConfig } from '../../core/types';\nimport type { ColumnVirtualizationViewport } from './types';\n\n/** Default column width when not specified */\nconst DEFAULT_COLUMN_WIDTH = 100;\n\n/**\n * Parse a column width value to pixels.\n * Handles number (px) and string formats.\n *\n * @param width - The width value from column config\n * @returns Width in pixels\n */\nexport function parseColumnWidth(width: string | number | undefined): number {\n if (width === undefined || width === null) {\n return DEFAULT_COLUMN_WIDTH;\n }\n\n if (typeof width === 'number') {\n return width;\n }\n\n // Handle string values - extract numeric part\n const numeric = parseFloat(width);\n if (!isNaN(numeric)) {\n return numeric;\n }\n\n return DEFAULT_COLUMN_WIDTH;\n}\n\n/**\n * Get array of column widths in pixels.\n *\n * @param columns - Column configurations\n * @returns Array of widths in pixels\n */\nexport function getColumnWidths(columns: readonly ColumnConfig[]): number[] {\n return columns.map((col) => parseColumnWidth(col.width));\n}\n\n/**\n * Compute cumulative left offsets for each column.\n *\n * @param columns - Column configurations\n * @returns Array of left offsets in pixels\n */\nexport function computeColumnOffsets(columns: readonly ColumnConfig[]): number[] {\n const offsets: number[] = [];\n let offset = 0;\n\n for (const col of columns) {\n offsets.push(offset);\n offset += parseColumnWidth(col.width);\n }\n\n return offsets;\n}\n\n/**\n * Compute total width of all columns.\n *\n * @param columns - Column configurations\n * @returns Total width in pixels\n */\nexport function computeTotalWidth(columns: readonly ColumnConfig[]): number {\n return columns.reduce((sum, col) => sum + parseColumnWidth(col.width), 0);\n}\n\n/**\n * Find the visible column range based on scroll position.\n * Uses binary search for efficient lookup in large column sets.\n *\n * @param scrollLeft - Current horizontal scroll position\n * @param viewportWidth - Width of the visible viewport\n * @param columnOffsets - Array of column left offsets\n * @param columnWidths - Array of column widths\n * @param overscan - Number of extra columns to render on each side\n * @returns Viewport information with visible column indices\n */\nexport function getVisibleColumnRange(\n scrollLeft: number,\n viewportWidth: number,\n columnOffsets: number[],\n columnWidths: number[],\n overscan: number\n): ColumnVirtualizationViewport {\n const columnCount = columnOffsets.length;\n\n if (columnCount === 0) {\n return { startCol: 0, endCol: 0, visibleColumns: [] };\n }\n\n // Binary search for first visible column\n let startCol = binarySearchFirstVisible(scrollLeft, columnOffsets, columnWidths);\n startCol = Math.max(0, startCol - overscan);\n\n // Find last visible column (without overscan first)\n const rightEdge = scrollLeft + viewportWidth;\n let endCol = startCol;\n\n for (let i = startCol; i < columnCount; i++) {\n if (columnOffsets[i] >= rightEdge) {\n endCol = i - 1;\n break;\n }\n endCol = i;\n }\n\n // Apply overscan to end (only once)\n endCol = Math.min(columnCount - 1, endCol + overscan);\n\n // Build array of visible column indices\n const visibleColumns: number[] = [];\n for (let i = startCol; i <= endCol; i++) {\n visibleColumns.push(i);\n }\n\n return { startCol, endCol, visibleColumns };\n}\n\n/**\n * Binary search to find the first column that is visible.\n *\n * @param scrollLeft - Current scroll position\n * @param columnOffsets - Array of column offsets\n * @param columnWidths - Array of column widths\n * @returns Index of first visible column\n */\nfunction binarySearchFirstVisible(scrollLeft: number, columnOffsets: number[], columnWidths: number[]): number {\n let low = 0;\n let high = columnOffsets.length - 1;\n\n while (low < high) {\n const mid = Math.floor((low + high) / 2);\n const colRight = columnOffsets[mid] + columnWidths[mid];\n\n if (colRight <= scrollLeft) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n\n return low;\n}\n\n/**\n * Determine if column virtualization should be active.\n *\n * @param columnCount - Number of columns\n * @param threshold - Column count threshold\n * @param autoEnable - Whether auto-enable is configured\n * @returns True if virtualization should be active\n */\nexport function shouldVirtualize(columnCount: number, threshold: number, autoEnable: boolean): boolean {\n if (!autoEnable) return false;\n return columnCount > threshold;\n}\n","/**\n * Column Virtualization Plugin (Class-based)\n *\n * Provides horizontal column virtualization for grids with many columns.\n * Significantly improves rendering performance when dealing with >30 columns.\n */\n\nimport { BaseGridPlugin, ScrollEvent } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport {\n computeColumnOffsets,\n computeTotalWidth,\n getColumnWidths,\n getVisibleColumnRange,\n shouldVirtualize,\n} from './column-virtualization';\nimport type { ColumnVirtualizationConfig } from './types';\n\n/**\n * Column Virtualization Plugin for tbw-grid\n *\n * Provides horizontal column virtualization for grids with many columns (30+).\n * Only renders visible columns plus overscan, significantly improving rendering\n * performance for wide grids.\n *\n * ## Installation\n *\n * ```ts\n * import { ColumnVirtualizationPlugin } from '@toolbox-web/grid/plugins/column-virtualization';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `autoEnable` | `boolean` | `true` | Auto-enable when column count exceeds threshold |\n * | `threshold` | `number` | `30` | Column count threshold for auto-enable |\n * | `overscan` | `number` | `3` | Extra columns to render beyond visible |\n *\n * ## Requirements\n *\n * - Grid must use `fitMode: 'fixed'`\n * - Columns must have explicit widths\n * - Grid must have fixed height\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `isEnabled` | `() => boolean` | Check if virtualization is active |\n * | `setEnabled` | `(enabled: boolean) => void` | Enable/disable virtualization |\n * | `getVisibleRange` | `() => { start, end }` | Get visible column range |\n *\n * @example Wide Grid with Column Virtualization\n * ```ts\n * import '@toolbox-web/grid';\n * import { ColumnVirtualizationPlugin } from '@toolbox-web/grid/plugins/column-virtualization';\n *\n * grid.gridConfig = {\n * columns: generateManyColumns(100), // 100 columns\n * fitMode: 'fixed', // Required\n * plugins: [\n * new ColumnVirtualizationPlugin({\n * threshold: 30, // Enable when >30 columns\n * overscan: 3, // Render 3 extra columns each side\n * }),\n * ],\n * };\n * ```\n *\n * @see {@link ColumnVirtualizationConfig} for configuration options\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ColumnVirtualizationPlugin extends BaseGridPlugin<ColumnVirtualizationConfig> {\n /** @internal */\n readonly name = 'columnVirtualization';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ColumnVirtualizationConfig> {\n return {\n autoEnable: true,\n threshold: 30,\n overscan: 3,\n };\n }\n\n // #region Internal State\n private isVirtualized = false;\n private startCol = 0;\n private endCol = 0;\n private scrollLeft = 0;\n private totalWidth = 0;\n private columnWidths: number[] = [];\n private columnOffsets: number[] = [];\n /** Store the original full column set for virtualization calculations */\n private originalColumns: readonly ColumnConfig[] = [];\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 // Initialize state from current columns\n const columns = this.columns;\n this.columnWidths = getColumnWidths(columns);\n this.columnOffsets = computeColumnOffsets(columns);\n this.totalWidth = computeTotalWidth(columns);\n this.endCol = columns.length - 1;\n }\n\n /** @internal */\n override detach(): void {\n // Clean up inline styles set by this plugin\n this.#cleanupStyles();\n\n this.columnWidths = [];\n this.columnOffsets = [];\n this.originalColumns = [];\n this.isVirtualized = false;\n this.startCol = 0;\n this.endCol = 0;\n this.scrollLeft = 0;\n this.totalWidth = 0;\n }\n\n /**\n * Remove inline styles set by this plugin for proper cleanup.\n */\n #cleanupStyles(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const headerRow = gridEl.querySelector('.header-row') as HTMLElement | null;\n if (headerRow) {\n headerRow.style.paddingLeft = '';\n headerRow.style.minWidth = '';\n }\n\n const bodyRows = gridEl.querySelectorAll('.data-grid-row');\n bodyRows.forEach((row) => {\n (row as HTMLElement).style.paddingLeft = '';\n });\n\n const rowsContainer = gridEl.querySelector('.rows-viewport .rows') as HTMLElement | null;\n if (rowsContainer) {\n rowsContainer.style.width = '';\n }\n\n const rowsBody = gridEl.querySelector('.rows-body') as HTMLElement | null;\n if (rowsBody) {\n rowsBody.style.minWidth = '';\n }\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n // Detect if this is a new column set or just a scroll-triggered re-render.\n // We consider it \"new\" if:\n // 1. We don't have any stored yet (first time)\n // 2. Incoming has AS MANY OR MORE columns than we stored (genuine new config)\n // When virtualization is active, our output is a SUBSET (fewer columns),\n // so a scroll-triggered re-render will have fewer columns than originalColumns.\n // When virtualization is off, our output has the same count as originalColumns,\n // but any config change (e.g., pinning a column) also has the same count.\n // Using >= ensures we pick up property-only changes (like adding `pinned`).\n const isNewColumnSet = this.originalColumns.length === 0 || columns.length >= this.originalColumns.length;\n\n if (isNewColumnSet) {\n // Store the full column set\n this.originalColumns = columns;\n this.columnWidths = getColumnWidths(columns);\n this.columnOffsets = computeColumnOffsets(columns);\n this.totalWidth = computeTotalWidth(columns);\n }\n\n // Use the original (full) column set for virtualization decisions\n const fullColumns = this.originalColumns;\n const isVirtualized = shouldVirtualize(\n fullColumns.length,\n this.config.threshold ?? 30,\n this.config.autoEnable ?? true,\n );\n\n this.isVirtualized = isVirtualized ?? false;\n\n if (!isVirtualized) {\n this.startCol = 0;\n this.endCol = fullColumns.length - 1;\n return [...fullColumns];\n }\n\n // Get viewport width from grid element\n const viewportWidth = (this.grid as unknown as HTMLElement).clientWidth || 800;\n const viewport = getVisibleColumnRange(\n this.scrollLeft,\n viewportWidth,\n this.columnOffsets,\n this.columnWidths,\n this.config.overscan ?? 3,\n );\n\n this.startCol = viewport.startCol;\n this.endCol = viewport.endCol;\n\n // Return only visible columns from the ORIGINAL full set\n return viewport.visibleColumns.map((i) => fullColumns[i]);\n }\n\n /** @internal */\n override afterRender(): void {\n if (!this.isVirtualized) return;\n\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n // Apply left padding to offset scrolled-out columns\n const leftPadding = this.columnOffsets[this.startCol] ?? 0;\n\n const headerRow = gridEl.querySelector('.header-row') as HTMLElement | null;\n const bodyRows = gridEl.querySelectorAll('.data-grid-row');\n\n if (headerRow) {\n headerRow.style.paddingLeft = `${leftPadding}px`;\n // Set min-width on header row to enable horizontal scrolling\n headerRow.style.minWidth = `${this.totalWidth}px`;\n }\n\n bodyRows.forEach((row) => {\n (row as HTMLElement).style.paddingLeft = `${leftPadding}px`;\n });\n\n // Set total width for horizontal scrolling on the rows container\n const rowsContainer = gridEl.querySelector('.rows-viewport .rows') as HTMLElement | null;\n if (rowsContainer) {\n rowsContainer.style.width = `${this.totalWidth}px`;\n }\n\n // Also set min-width on .rows-body to ensure the scroll container knows the total scrollable width\n const rowsBody = gridEl.querySelector('.rows-body') as HTMLElement | null;\n if (rowsBody) {\n rowsBody.style.minWidth = `${this.totalWidth}px`;\n }\n }\n\n /** @internal */\n override onScroll(event: ScrollEvent): void {\n if (!this.isVirtualized) return;\n\n // Check if horizontal scroll position changed significantly\n const scrollDelta = Math.abs(event.scrollLeft - this.scrollLeft);\n if (scrollDelta < 1) return;\n\n // Update scroll position\n this.scrollLeft = event.scrollLeft;\n\n // Recalculate visible columns and request re-render\n // Must use requestColumnsRender() to trigger COLUMNS phase (processColumns hook)\n // requestRender() only requests ROWS phase which doesn't reprocess columns\n this.requestColumnsRender();\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Check if column virtualization is currently active.\n */\n getIsVirtualized(): boolean {\n return this.isVirtualized;\n }\n\n /**\n * Get the current visible column range.\n */\n getVisibleColumnRange(): { start: number; end: number } {\n return { start: this.startCol, end: this.endCol };\n }\n\n /**\n * Scroll the grid to bring a specific column into view.\n * @param columnIndex - Index of the column to scroll to\n */\n scrollToColumn(columnIndex: number): void {\n const offset = this.columnOffsets[columnIndex] ?? 0;\n const gridEl = this.grid as unknown as HTMLElement;\n // Scroll the grid element itself (it's the scroll container)\n gridEl.scrollLeft = offset;\n }\n\n /**\n * Get the left offset for a specific column.\n * @param columnIndex - Index of the column\n */\n getColumnOffset(columnIndex: number): number {\n return this.columnOffsets[columnIndex] ?? 0;\n }\n\n /**\n * Get the total width of all columns.\n */\n getTotalWidth(): number {\n return this.totalWidth;\n }\n // #endregion\n}\n"],"names":["parseColumnWidth","width","numeric","parseFloat","isNaN","getColumnWidths","columns","map","col","computeColumnOffsets","offsets","offset","push","computeTotalWidth","reduce","sum","getVisibleColumnRange","scrollLeft","viewportWidth","columnOffsets","columnWidths","overscan","columnCount","length","startCol","endCol","visibleColumns","low","high","mid","Math","floor","binarySearchFirstVisible","max","rightEdge","i","min","ColumnVirtualizationPlugin","BaseGridPlugin","name","defaultConfig","autoEnable","threshold","isVirtualized","totalWidth","originalColumns","attach","grid","super","this","detach","cleanupStyles","gridEl","gridElement","headerRow","querySelector","style","paddingLeft","minWidth","querySelectorAll","forEach","row","rowsContainer","rowsBody","processColumns","fullColumns","config","clientWidth","viewport","afterRender","leftPadding","bodyRows","onScroll","event","abs","requestColumnsRender","getIsVirtualized","start","end","scrollToColumn","columnIndex","getColumnOffset","getTotalWidth"],"mappings":"8VAmBO,SAASA,EAAiBC,GAC/B,GAAIA,QACF,OAXyB,IAc3B,GAAqB,iBAAVA,EACT,OAAOA,EAIT,MAAMC,EAAUC,WAAWF,GAC3B,OAAKG,MAAMF,GApBgB,IAqBlBA,CAIX,CAQO,SAASG,EAAgBC,GAC9B,OAAOA,EAAQC,I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AAC,GACE,OAAO3B,KAAKN,aACd,CAKA,qBAAA3B,GACE,MAAO,CAAE6D,MAAO5B,KAAKzB,SAAUsD,IAAK7B,KAAKxB,OAC3C,CAMA,cAAAsD,CAAeC,GACb,MAAMrE,EAASsC,KAAK9B,cAAc6D,IAAgB,EACnC/B,KAAKF,KAEb9B,WAAaN,CACtB,CAMA,eAAAsE,CAAgBD,GACd,OAAO/B,KAAK9B,cAAc6D,IAAgB,CAC5C,CAKA,aAAAE,GACE,OAAOjC,KAAKL,UACd"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(b,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("../../core/plugin/base-plugin"),require("../../core/types")):typeof define=="function"&&define.amd?define(["exports","../../core/plugin/base-plugin","../../core/types"],g):(b=typeof globalThis<"u"?globalThis:b||self,g(b.TbwGridPlugin_contextMenu={},b.TbwGrid,b.TbwGrid))})(this,(function(b,g,O){"use strict";const x="@layer tbw-plugins{.tbw-context-menu{position:fixed;background:var(--tbw-context-menu-bg, var(--tbw-color-panel-bg));color:var(--tbw-context-menu-fg, var(--tbw-color-fg));border:1px solid var(--tbw-context-menu-border, var(--tbw-color-border));border-radius:var(--tbw-context-menu-radius, var(--tbw-border-radius));box-shadow:var(--tbw-context-menu-shadow, 0 2px 10px var(--tbw-color-shadow));min-width:var(--tbw-context-menu-min-width, var(--tbw-menu-min-width));padding:var(--tbw-spacing-xs) 0;z-index:10000;font-size:var(--tbw-context-menu-font-size, var(--tbw-font-size-sm));font-family:var(--tbw-context-menu-font-family, var(--tbw-font-family))}.tbw-context-menu-item{display:flex;align-items:center;padding:var(--tbw-context-menu-item-padding, var(--tbw-menu-item-padding));cursor:pointer;gap:var(--tbw-context-menu-item-gap, var(--tbw-menu-item-gap))}.tbw-context-menu-item:hover:not(.disabled){background:var(--tbw-context-menu-hover, var(--tbw-color-row-hover))}.tbw-context-menu-item.disabled{opacity:.5;cursor:default}.tbw-context-menu-item.danger{color:var(--tbw-context-menu-danger, var(--tbw-color-danger))}.tbw-context-menu-icon{width:var(--tbw-context-menu-icon-size, var(--tbw-icon-size));text-align:center}.tbw-context-menu-label{flex:1}.tbw-context-menu-shortcut kbd{color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted));font-size:var(--tbw-context-menu-shortcut-size, var(--tbw-font-size-xs))}.tbw-context-menu-arrow{font-size:var(--tbw-context-menu-arrow-size, var(--tbw-font-size-2xs));color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted))}.tbw-context-menu-separator{height:1px;background:var(--tbw-context-menu-border, var(--tbw-color-border));margin:var(--tbw-spacing-xs) 0}}";function v(l,e){return(typeof l=="function"?l(e):l).filter(t=>!(t.hidden===!0||typeof t.hidden=="function"&&t.hidden(e)))}function M(l){const e=[];for(const o of l)o.separator&&(e.length===0||e[e.length-1].separator)||e.push(o);return e.length>0&&e[e.length-1].separator&&e.pop(),e}function T(l,e){return l.disabled===!0?!0:typeof l.disabled=="function"?l.disabled(e):!1}function y(l,e,o,t=O.DEFAULT_GRID_ICONS.submenuArrow){const s=document.createElement("div");s.className="tbw-context-menu",s.setAttribute("role","menu");const u=l.some(n=>!n.separator&&n.icon);for(const n of l){if(n.separator){const r=document.createElement("div");r.className="tbw-context-menu-separator",r.setAttribute("role","separator"),s.appendChild(r);continue}const i=document.createElement("div");i.className="tbw-context-menu-item",n.cssClass&&i.classList.add(n.cssClass),i.setAttribute("role","menuitem"),i.setAttribute("data-id",n.id);const d=T(n,e);if(d&&(i.classList.add("disabled"),i.setAttribute("aria-disabled","true")),n.icon){const r=document.createElement("span");r.className="tbw-context-menu-icon",r.innerHTML=n.icon,i.appendChild(r)}else if(u){const r=document.createElement("span");r.className="tbw-context-menu-icon",r.innerHTML=" ",i.appendChild(r)}const w=document.createElement("span");if(w.className="tbw-context-menu-label",w.textContent=n.name,i.appendChild(w),n.shortcut){const r=document.createElement("span");if(r.className="tbw-context-menu-shortcut",Array.isArray(n.shortcut))n.shortcut.forEach((c,m)=>{m>0&&r.appendChild(document.createTextNode("+"));const a=document.createElement("kbd");a.textContent=c,r.appendChild(a)});else{const c=document.createElement("kbd");c.textContent=n.shortcut,r.appendChild(c)}i.appendChild(r)}if(n.subMenu?.length){const r=document.createElement("span");r.className="tbw-context-menu-arrow",typeof t=="string"?r.innerHTML=t:t instanceof HTMLElement&&r.appendChild(t.cloneNode(!0)),i.appendChild(r),i.addEventListener("mouseenter",()=>{if(i.querySelector(".tbw-context-menu")||!n.subMenu)return;const m=v(n.subMenu,e),a=y(m,e,o,t);a.classList.add("tbw-context-submenu"),a.style.position="absolute",a.style.left="100%",a.style.top="0",i.style.position="relative",i.appendChild(a)}),i.addEventListener("mouseleave",()=>{const c=i.querySelector(".tbw-context-menu");c&&c.remove()})}!d&&n.action&&!n.subMenu&&i.addEventListener("click",r=>{r.stopPropagation(),o(n)}),s.appendChild(i)}return s}function S(l,e,o){l.style.position="fixed",l.style.left=`${e}px`,l.style.top=`${o}px`,l.style.visibility="hidden",l.style.zIndex="10000";const t=l.getBoundingClientRect(),s=window.innerWidth,u=window.innerHeight;let n=e,i=o;e+t.width>s&&(n=e-t.width),o+t.height>u&&(i=o-t.height),n=Math.max(0,n),i=Math.max(0,i),l.style.left=`${n}px`,l.style.top=`${i}px`,l.style.visibility="visible"}const z="getContextMenuItems";let f=null,h=null,p=null,E=0;const C=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:l=>{l.grid?.plugins?.clipboard?.copy?.()}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:l=>{l.grid?.plugins?.export?.exportCsv?.()}}];class I extends g.BaseGridPlugin{static manifest={queries:[{type:z,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:C}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),E++}detach(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen=!1,this.params=null,this.uninstallGlobalHandlers()}syncSelectionOnContextMenu(e){if(e<0)return[];const t=this.grid?.query("getSelectedRowIndices")?.[0];return t?t.includes(e)?t:(this.grid?.query("selectRows",[e]),[e]):[e]}static CSS_VARS_TO_COPY=["--tbw-color-panel-bg","--tbw-color-fg","--tbw-color-fg-muted","--tbw-color-border","--tbw-color-row-hover","--tbw-color-shadow","--tbw-color-danger","--tbw-border-radius","--tbw-font-family","--tbw-font-size-sm","--tbw-font-size-xs","--tbw-font-size-2xs","--tbw-spacing-xs","--tbw-icon-size","--tbw-menu-min-width","--tbw-menu-item-padding","--tbw-menu-item-gap","--tbw-context-menu-bg","--tbw-context-menu-fg","--tbw-context-menu-border","--tbw-context-menu-radius","--tbw-context-menu-shadow","--tbw-context-menu-hover","--tbw-context-menu-danger","--tbw-context-menu-muted","--tbw-context-menu-min-width","--tbw-context-menu-font-size","--tbw-context-menu-font-family","--tbw-context-menu-item-padding","--tbw-context-menu-item-gap","--tbw-context-menu-icon-size","--tbw-context-menu-shortcut-size","--tbw-context-menu-arrow-size"];copyGridStyles(e){const o=this.gridElement;if(!o)return;const t=getComputedStyle(o),s=[],u=t.getPropertyValue("color-scheme").trim();u&&s.push(`color-scheme: ${u}`);for(const n of I.CSS_VARS_TO_COPY){const i=t.getPropertyValue(n).trim();i&&s.push(`${n}: ${i}`)}if(s.length>0){const n=e.getAttribute("style")||"";e.setAttribute("style",n+s.join("; ")+";")}}installGlobalHandlers(){!p&&typeof document<"u"&&typeof x=="string"&&x&&(p=document.createElement("style"),p.id="tbw-context-menu-styles",p.textContent=x,document.head.appendChild(p)),f||(f=()=>{document.querySelectorAll(".tbw-context-menu").forEach(o=>o.remove())},document.addEventListener("click",f)),h||(h=e=>{e.key==="Escape"&&document.querySelectorAll(".tbw-context-menu").forEach(t=>t.remove())},document.addEventListener("keydown",h))}uninstallGlobalHandlers(){E--,!(E>0)&&(f&&(document.removeEventListener("click",f),f=null),h&&(document.removeEventListener("keydown",h),h=null),p&&(p.remove(),p=null))}collectPluginItems(e){if(!this.grid)return[];const o=this.grid.query(z,e),t=[];for(const s of o)Array.isArray(s)&&t.push(...s);return t.sort((s,u)=>(s.order??100)-(u.order??100)),this.insertGroupSeparators(t)}insertGroupSeparators(e){if(e.length<=1)return e;const o=[];let t=-1;for(const s of e){if(s.separator){o.push(s);continue}const u=Math.floor((s.order??100)/10);t>=0&&u!==t&&o.push({id:`__sep-${t}-${u}`,label:"",separator:!0,action:()=>{}}),t=u,o.push(s)}return o}convertPluginItems(e){return e.map(o=>({id:o.id,name:o.label,icon:o.icon,shortcut:o.shortcut,disabled:o.disabled??!1,action:()=>o.action(),separator:o.separator,cssClass:o.cssClass}))}afterRender(){const e=this.gridElement;if(!e)return;const o=e.querySelector(".tbw-grid-root");o&&o.getAttribute("data-context-menu-bound")!=="true"&&(o.setAttribute("data-context-menu-bound","true"),o.addEventListener("contextmenu",t=>{const s=t;s.preventDefault();const u=s.target,n=u.closest("[data-row][data-col]"),i=u.closest('[part~="header-cell"]');let d;if(n){const c=parseInt(n.getAttribute("data-row")??"-1",10),m=parseInt(n.getAttribute("data-col")??"-1",10),a=this.visibleColumns[m],A=this.rows[c],_=this.syncSelectionOnContextMenu(c);d={row:A,rowIndex:c,column:a,columnIndex:m,field:a?.field??"",value:A?.[a?.field]??null,isHeader:!1,event:s,selectedRows:_}}else if(i){const c=parseInt(i.getAttribute("data-col")??"-1",10),m=this.visibleColumns[c];d={row:null,rowIndex:-1,column:m,columnIndex:c,field:m?.field??"",value:null,isHeader:!0,event:s,selectedRows:[]}}else return;this.params=d,this.position={x:s.clientX,y:s.clientY};const w=this.collectPluginItems(d);let r=v(this.config.items??C,d);if(w.length>0){const c=this.convertPluginItems(w);r.length>0&&c.length>0?r=[...r,{id:"__plugin-sep",name:"",separator:!0},...c]:r=[...r,...c]}r=M(r),r.length&&(this.menuElement&&this.menuElement.remove(),this.menuElement=y(r,d,c=>{c.action&&c.action(d),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),S(this.menuElement,s.clientX,s.clientY),this.isOpen=!0,this.emit("context-menu-open",{params:d,items:r}))}))}showMenu(e,o,t){const s={row:t.row??null,rowIndex:t.rowIndex??-1,column:t.column??null,columnIndex:t.columnIndex??-1,field:t.field??"",value:t.value??null,isHeader:t.isHeader??!1,event:t.event??new MouseEvent("contextmenu"),selectedRows:t.selectedRows??[]},u=this.collectPluginItems(s);let n=v(this.config.items??C,s);if(u.length>0){const i=this.convertPluginItems(u);n.length>0&&i.length>0?n=[...n,{id:"__plugin-sep",name:"",separator:!0},...i]:n=[...n,...i]}n=M(n),this.menuElement&&this.menuElement.remove(),this.menuElement=y(n,s,i=>{i.action&&i.action(s),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),S(this.menuElement,e,o),this.isOpen=!0}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null,this.isOpen=!1)}isMenuOpen(){return this.isOpen}}b.ContextMenuPlugin=I,Object.defineProperty(b,Symbol.toStringTag,{value:"Module"})}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/plugin/base-plugin"),require("../../core/types")):"function"==typeof define&&define.amd?define(["exports","../../core/plugin/base-plugin","../../core/types"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_contextMenu={},e.TbwGrid,e.TbwGrid)}(this,function(e,t,n){"use strict";const o="@layer tbw-plugins{.tbw-context-menu{position:fixed;background:var(--tbw-context-menu-bg, var(--tbw-color-panel-bg));color:var(--tbw-context-menu-fg, var(--tbw-color-fg));border:1px solid var(--tbw-context-menu-border, var(--tbw-color-border));border-radius:var(--tbw-context-menu-radius, var(--tbw-border-radius));box-shadow:var(--tbw-context-menu-shadow, 0 2px 10px var(--tbw-color-shadow));min-width:var(--tbw-context-menu-min-width, var(--tbw-menu-min-width));padding:var(--tbw-spacing-xs) 0;z-index:10000;font-size:var(--tbw-context-menu-font-size, var(--tbw-font-size-sm));font-family:var(--tbw-context-menu-font-family, var(--tbw-font-family))}.tbw-context-menu-item{display:flex;align-items:center;padding:var(--tbw-context-menu-item-padding, var(--tbw-menu-item-padding));cursor:pointer;gap:var(--tbw-context-menu-item-gap, var(--tbw-menu-item-gap))}.tbw-context-menu-item:hover:not(.disabled){background:var(--tbw-context-menu-hover, var(--tbw-color-row-hover))}.tbw-context-menu-item.disabled{opacity:.5;cursor:default}.tbw-context-menu-item.danger{color:var(--tbw-context-menu-danger, var(--tbw-color-danger))}.tbw-context-menu-icon{width:var(--tbw-context-menu-icon-size, var(--tbw-icon-size));text-align:center}.tbw-context-menu-label{flex:1}.tbw-context-menu-shortcut kbd{color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted));font-size:var(--tbw-context-menu-shortcut-size, var(--tbw-font-size-xs))}.tbw-context-menu-arrow{font-size:var(--tbw-context-menu-arrow-size, var(--tbw-font-size-2xs));color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted))}.tbw-context-menu-separator{height:1px;background:var(--tbw-context-menu-border, var(--tbw-color-border));margin:var(--tbw-spacing-xs) 0}}";function i(e,t){return("function"==typeof e?e(t):e).filter(e=>!0!==e.hidden&&("function"!=typeof e.hidden||!e.hidden(t)))}function s(e){const t=[];for(const n of e)n.separator&&(0===t.length||t[t.length-1].separator)||t.push(n);return t.length>0&&t[t.length-1].separator&&t.pop(),t}function r(e,t){return!0===e.disabled||"function"==typeof e.disabled&&e.disabled(t)}function l(e,t,o,s=n.DEFAULT_GRID_ICONS.submenuArrow){const c=document.createElement("div");c.className="tbw-context-menu",c.setAttribute("role","menu");const a=e.some(e=>!e.separator&&e.icon);for(const n of e){if(n.separator){const e=document.createElement("div");e.className="tbw-context-menu-separator",e.setAttribute("role","separator"),c.appendChild(e);continue}const e=document.createElement("div");e.className="tbw-context-menu-item",n.cssClass&&e.classList.add(n.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",n.id);const u=r(n,t);if(u&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),n.icon){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=n.icon,e.appendChild(t)}else if(a){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=" ",e.appendChild(t)}const d=document.createElement("span");if(d.className="tbw-context-menu-label",d.textContent=n.name,e.appendChild(d),n.shortcut){const t=document.createElement("span");if(t.className="tbw-context-menu-shortcut",Array.isArray(n.shortcut))n.shortcut.forEach((e,n)=>{n>0&&t.appendChild(document.createTextNode("+"));const o=document.createElement("kbd");o.textContent=e,t.appendChild(o)});else{const e=document.createElement("kbd");e.textContent=n.shortcut,t.appendChild(e)}e.appendChild(t)}if(n.subMenu?.length){const r=document.createElement("span");r.className="tbw-context-menu-arrow","string"==typeof s?r.innerHTML=s:s instanceof HTMLElement&&r.appendChild(s.cloneNode(!0)),e.appendChild(r),e.addEventListener("mouseenter",()=>{if(e.querySelector(".tbw-context-menu"))return;if(!n.subMenu)return;const r=l(i(n.subMenu,t),t,o,s);r.classList.add("tbw-context-submenu"),r.style.position="absolute",r.style.left="100%",r.style.top="0",e.style.position="relative",e.appendChild(r)}),e.addEventListener("mouseleave",()=>{const t=e.querySelector(".tbw-context-menu");t&&t.remove()})}u||!n.action||n.subMenu||e.addEventListener("click",e=>{e.stopPropagation(),o(n)}),c.appendChild(e)}return c}function c(e,t,n){e.style.position="fixed",e.style.left=`${t}px`,e.style.top=`${n}px`,e.style.visibility="hidden",e.style.zIndex="10000";const o=e.getBoundingClientRect(),i=window.innerWidth,s=window.innerHeight;let r=t,l=n;t+o.width>i&&(r=t-o.width),n+o.height>s&&(l=n-o.height),r=Math.max(0,r),l=Math.max(0,l),e.style.left=`${r}px`,e.style.top=`${l}px`,e.style.visibility="visible"}const a="getContextMenuItems";let u=null,d=null,m=null,b=0;const p=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:e=>{const t=e.grid;t?.plugins?.clipboard?.copy?.()}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:e=>{const t=e.grid;t?.plugins?.export?.exportCsv?.()}}];class h extends t.BaseGridPlugin{static manifest={queries:[{type:a,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:p}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),b++}detach(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen=!1,this.params=null,this.uninstallGlobalHandlers()}syncSelectionOnContextMenu(e){if(e<0)return[];const t=this.grid?.query("getSelectedRowIndices"),n=t?.[0];return n?n.includes(e)?n:(this.grid?.query("selectRows",[e]),[e]):[e]}static CSS_VARS_TO_COPY=["--tbw-color-panel-bg","--tbw-color-fg","--tbw-color-fg-muted","--tbw-color-border","--tbw-color-row-hover","--tbw-color-shadow","--tbw-color-danger","--tbw-border-radius","--tbw-font-family","--tbw-font-size-sm","--tbw-font-size-xs","--tbw-font-size-2xs","--tbw-spacing-xs","--tbw-icon-size","--tbw-menu-min-width","--tbw-menu-item-padding","--tbw-menu-item-gap","--tbw-context-menu-bg","--tbw-context-menu-fg","--tbw-context-menu-border","--tbw-context-menu-radius","--tbw-context-menu-shadow","--tbw-context-menu-hover","--tbw-context-menu-danger","--tbw-context-menu-muted","--tbw-context-menu-min-width","--tbw-context-menu-font-size","--tbw-context-menu-font-family","--tbw-context-menu-item-padding","--tbw-context-menu-item-gap","--tbw-context-menu-icon-size","--tbw-context-menu-shortcut-size","--tbw-context-menu-arrow-size"];copyGridStyles(e){const t=this.gridElement;if(!t)return;const n=getComputedStyle(t),o=[],i=n.getPropertyValue("color-scheme").trim();i&&o.push(`color-scheme: ${i}`);for(const s of h.CSS_VARS_TO_COPY){const e=n.getPropertyValue(s).trim();e&&o.push(`${s}: ${e}`)}if(o.length>0){const t=e.getAttribute("style")||"";e.setAttribute("style",t+o.join("; ")+";")}}installGlobalHandlers(){!m&&"undefined"!=typeof document&&o&&(m=document.createElement("style"),m.id="tbw-context-menu-styles",m.textContent=o,document.head.appendChild(m)),u||(u=()=>{document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove())},document.addEventListener("click",u)),d||(d=e=>{if("Escape"===e.key){document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove())}},document.addEventListener("keydown",d))}uninstallGlobalHandlers(){b--,b>0||(u&&(document.removeEventListener("click",u),u=null),d&&(document.removeEventListener("keydown",d),d=null),m&&(m.remove(),m=null))}collectPluginItems(e){if(!this.grid)return[];const t=this.grid.query(a,e),n=[];for(const o of t)Array.isArray(o)&&n.push(...o);return n.sort((e,t)=>(e.order??100)-(t.order??100)),this.insertGroupSeparators(n)}insertGroupSeparators(e){if(e.length<=1)return e;const t=[];let n=-1;for(const o of e){if(o.separator){t.push(o);continue}const e=Math.floor((o.order??100)/10);n>=0&&e!==n&&t.push({id:`__sep-${n}-${e}`,label:"",separator:!0,action:()=>{}}),n=e,t.push(o)}return t}convertPluginItems(e){return e.map(e=>({id:e.id,name:e.label,icon:e.icon,shortcut:e.shortcut,disabled:e.disabled??!1,action:()=>e.action(),separator:e.separator,cssClass:e.cssClass}))}afterRender(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-grid-root");t&&"true"!==t.getAttribute("data-context-menu-bound")&&(t.setAttribute("data-context-menu-bound","true"),t.addEventListener("contextmenu",e=>{const t=e;t.preventDefault();const n=t.target,o=n.closest("[data-row][data-col]"),r=n.closest('[part~="header-cell"]');let a;if(o){const e=parseInt(o.getAttribute("data-row")??"-1",10),n=parseInt(o.getAttribute("data-col")??"-1",10),i=this.visibleColumns[n],s=this.rows[e],r=this.syncSelectionOnContextMenu(e);a={row:s,rowIndex:e,column:i,columnIndex:n,field:i?.field??"",value:s?.[i?.field]??null,isHeader:!1,event:t,selectedRows:r}}else{if(!r)return;{const e=parseInt(r.getAttribute("data-col")??"-1",10),n=this.visibleColumns[e];a={row:null,rowIndex:-1,column:n,columnIndex:e,field:n?.field??"",value:null,isHeader:!0,event:t,selectedRows:[]}}}this.params=a,this.position={x:t.clientX,y:t.clientY};const u=this.collectPluginItems(a);let d=i(this.config.items??p,a);if(u.length>0){const e=this.convertPluginItems(u);d=d.length>0&&e.length>0?[...d,{id:"__plugin-sep",name:"",separator:!0},...e]:[...d,...e]}d=s(d),d.length&&(this.menuElement&&this.menuElement.remove(),this.menuElement=l(d,a,e=>{e.action&&e.action(a),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),c(this.menuElement,t.clientX,t.clientY),this.isOpen=!0,this.emit("context-menu-open",{params:a,items:d}))}))}showMenu(e,t,n){const o={row:n.row??null,rowIndex:n.rowIndex??-1,column:n.column??null,columnIndex:n.columnIndex??-1,field:n.field??"",value:n.value??null,isHeader:n.isHeader??!1,event:n.event??new MouseEvent("contextmenu"),selectedRows:n.selectedRows??[]},r=this.collectPluginItems(o);let a=i(this.config.items??p,o);if(r.length>0){const e=this.convertPluginItems(r);a=a.length>0&&e.length>0?[...a,{id:"__plugin-sep",name:"",separator:!0},...e]:[...a,...e]}a=s(a),this.menuElement&&this.menuElement.remove(),this.menuElement=l(a,o,e=>{e.action&&e.action(o),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),c(this.menuElement,e,t),this.isOpen=!0}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null,this.isOpen=!1)}isMenuOpen(){return this.isOpen}}e.ContextMenuPlugin=h,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=context-menu.umd.js.map
|