@agile-team/mach-table 0.32.0 → 0.33.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.
Files changed (48) hide show
  1. package/README.md +9 -2
  2. package/dist/adapter.cjs +1 -1
  3. package/dist/adapter.d.cts +28 -26
  4. package/dist/adapter.d.ts +28 -26
  5. package/dist/adapter.js +1 -1
  6. package/dist/analysis.cjs +2 -2
  7. package/dist/analysis.d.cts +2 -2
  8. package/dist/analysis.d.ts +2 -2
  9. package/dist/analysis.js +2 -2
  10. package/dist/{api-pOhyuSQk.d.cts → api-CZkd8tYy.d.cts} +39 -4
  11. package/dist/{api-pOhyuSQk.d.ts → api-CZkd8tYy.d.ts} +39 -4
  12. package/dist/{configuration-SYWVjGft.d.ts → configuration-D10N9PqG.d.ts} +5 -2
  13. package/dist/{configuration-gAE1eZuB.d.cts → configuration-XdxYEMiS.d.cts} +5 -2
  14. package/dist/import.cjs +1 -0
  15. package/dist/import.d.cts +47 -0
  16. package/dist/import.d.ts +47 -0
  17. package/dist/import.js +1 -0
  18. package/dist/index.cjs +6 -6
  19. package/dist/index.d.cts +8 -4
  20. package/dist/index.d.ts +8 -4
  21. package/dist/index.js +6 -6
  22. package/dist/multi-range.cjs +2 -2
  23. package/dist/multi-range.d.cts +1 -1
  24. package/dist/multi-range.d.ts +1 -1
  25. package/dist/multi-range.js +3 -3
  26. package/dist/ordering.cjs +1 -1
  27. package/dist/ordering.d.cts +1 -1
  28. package/dist/ordering.d.ts +1 -1
  29. package/dist/ordering.js +1 -1
  30. package/dist/preferences.cjs +1 -1
  31. package/dist/preferences.d.cts +1 -1
  32. package/dist/preferences.d.ts +1 -1
  33. package/dist/preferences.js +1 -1
  34. package/dist/server-side.cjs +1 -1
  35. package/dist/server-side.d.cts +1 -1
  36. package/dist/server-side.d.ts +1 -1
  37. package/dist/server-side.js +1 -1
  38. package/dist/{shared-Bi8hAuzn.d.cts → shared-BS_wes40.d.cts} +1 -1
  39. package/dist/{shared-Bn77TiBm.d.ts → shared-ujm7RteA.d.ts} +1 -1
  40. package/dist/workbench.cjs +1 -1
  41. package/dist/workbench.d.cts +3 -3
  42. package/dist/workbench.d.ts +3 -3
  43. package/dist/workbench.js +1 -1
  44. package/dist/worker.cjs +1 -1
  45. package/dist/worker.d.cts +4 -2
  46. package/dist/worker.d.ts +4 -2
  47. package/dist/worker.js +1 -1
  48. package/package.json +12 -2
@@ -1,4 +1,4 @@
1
- "use strict";var u=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames;var b=Object.prototype.hasOwnProperty;var G=(n,t)=>{for(var r in t)u(n,r,{get:t[r],enumerable:!0})},C=(n,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of D(t))!b.call(n,i)&&i!==r&&u(n,i,{get:()=>t[i],enumerable:!(e=A(t,i))||e.enumerable});return n};var E=n=>C(u({},"__esModule",{value:!0}),n);var F={};G(F,{createMultiRangeSelection:()=>S});module.exports=E(F);var m=Symbol.for("mach-table.adapter.lifecycle.v1");function y(n,t,r){return n.isDestroyed()?"":n[m]?.readCell(t,r)??""}function w(n,t){n.isDestroyed()||n[m]?.writeInput(t)}function v(n){return typeof n!="string"||n===""||/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(n)?n:/^[\s\u0000-\u001f]*[=+\-@]/.test(n)?"'"+n:n}function I(n,t){let r=t?v(n):n,e=r==null?"":String(r);return/["\t\n\r]/.test(e)?'"'+e.replace(/"/g,'""')+'"':e}function x(n,t=!0){return n.map(r=>r.map(e=>I(e,t)).join(" ")).join(`
2
- `)}var g=32,R=1e5;function d(n){let t=[...new Map(n.map(r=>[JSON.stringify(r.range),r])).values()];if(t.length>g)throw new RangeError("At most 32 ranges are supported.");if(t.reduce((r,e)=>r+e.rows.length*e.columns.length,0)>R)throw new RangeError("A multi-range operation may affect at most 100000 cells.");return t}function M(n){let t=n.columns.getWorkbenchItems().filter(r=>r.visible);return["left",null,"right"].flatMap(r=>t.filter(e=>e.pinned===r).map(e=>e.colId))}function S(){return new f}var f=class{constructor(){this.key="multi-range";this.context=null;this.saved=[];this.e=0;this.r=null}setup(t){if(this.context)throw new Error("Create a separate multi-range feature for each grid.");if(!t.api.getOption("enableRangeSelection"))throw new Error("Multi-range selection requires enableRangeSelection: true.");this.context=t;let r=null;t.onCleanup(()=>{cancelAnimationFrame(this.e),this.e=0;try{r?.disconnect()}finally{this.o(),this.saved=[],this.context===t&&(this.context=null)}});let{root:e}=t,i=(o,s)=>{t.addManagedDomListener(e,o,a=>{try{s(a)}catch(c){a.preventDefault(),a.stopImmediatePropagation(),t.reportError(c,"multi-range")}},!0)};i("mousedown",o=>this.s(o)),i("keydown",o=>this.a(o)),i("copy",o=>this.i(o)),i("cut",o=>this.i(o,!0)),t.addEventListener("rangeSelectionChanged",()=>this.t()),r=new MutationObserver(()=>this.t()),r.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-id","data-col-id"]}),t.addEventListener("modelUpdated",()=>this.clear())}snapshot(t){let r=this.context?.api;if(!r)return null;let e=M(r),i=e.indexOf(t.colId1),o=e.indexOf(t.colId2),s=Math.max(0,Math.min(t.row1,t.row2)),a=Math.min(r.rows.getCount()-1,Math.max(t.row1,t.row2));if(i<0||o<0||!Number.isInteger(s)||!Number.isInteger(a)||a<s)return null;let c=e.slice(Math.min(i,o),Math.max(i,o)+1);if((a-s+1)*c.length>R)throw new RangeError("A range may contain at most 100000 cells.");let h=[];for(let p=s;p<=a;p++){let l=r.rows.getAt(p);l?.data&&!l.isGroup&&!l.isDetail&&!l.loading&&h.push(l.id)}return{range:{row1:s,row2:a,colId1:e[Math.min(i,o)],colId2:e[Math.max(i,o)]},rows:h,columns:c}}n(){let t=this.context?.api.selection.getRange(),r=t?this.snapshot(t):null,e=r?[...this.saved,r]:[...this.saved];return d(e)}getRanges(){return this.n().map(t=>({...t.range}))}setRanges(t){if(!this.context)throw new Error("Install the multi-range feature before setting ranges.");if(t.length>g)throw new RangeError("At most 32 ranges are supported.");let r=d(t.map(e=>this.snapshot(e)).filter(e=>e!==null));this.context.api.selection.clearRange(),this.saved=r,this.t()}clear(){this.saved=[],this.context?.api.selection.clearRange(),this.o(),this.t()}getText(){let t=this.context?.api;return t?this.n().map(r=>x(r.rows.map(e=>r.columns.map(i=>y(t,e,i))))).join(`
1
+ "use strict";var u=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames;var E=Object.prototype.hasOwnProperty;var G=(n,t)=>{for(var r in t)u(n,r,{get:t[r],enumerable:!0})},C=(n,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of A(t))!E.call(n,i)&&i!==r&&u(n,i,{get:()=>t[i],enumerable:!(e=D(t,i))||e.enumerable});return n};var I=n=>C(u({},"__esModule",{value:!0}),n);var L={};G(L,{createMultiRangeSelection:()=>T});module.exports=I(L);var m=Symbol.for("mach-table.adapter.lifecycle.v1");function y(n,t,r){return n.isDestroyed()?"":n[m]?.readCell(t,r)??""}function w(n,t){n.isDestroyed()||n[m]?.writeInput(t)}var v=/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/;function x(n){return typeof n!="string"||n===""||v.test(n)?n:/^[\s\u0000-\u001f]*[=+\-@]/.test(n)?"'"+n:n}function M(n){return n==null?"":String(n)}function S(n,t){let r=t?x(n):n,e=M(r);return/["\t\n\r]/.test(e)?'"'+e.replace(/"/g,'""')+'"':e}function b(n,t=!0){return n.map(r=>r.map(e=>S(e,t)).join(" ")).join(`
2
+ `)}var g=32,R=1e5;function d(n){let t=[...new Map(n.map(r=>[JSON.stringify(r.range),r])).values()];if(t.length>g)throw new RangeError("At most 32 ranges are supported.");if(t.reduce((r,e)=>r+e.rows.length*e.columns.length,0)>R)throw new RangeError("A multi-range operation may affect at most 100000 cells.");return t}function F(n){let t=n.columns.getWorkbenchItems().filter(r=>r.visible);return["left",null,"right"].flatMap(r=>t.filter(e=>e.pinned===r).map(e=>e.colId))}function T(){return new f}var f=class{constructor(){this.key="multi-range";this.context=null;this.saved=[];this.e=0;this.r=null}setup(t){if(this.context)throw new Error("Create a separate multi-range feature for each grid.");if(!t.api.getOption("enableRangeSelection"))throw new Error("Multi-range selection requires enableRangeSelection: true.");this.context=t;let r=null;t.onCleanup(()=>{cancelAnimationFrame(this.e),this.e=0;try{r?.disconnect()}finally{this.o(),this.saved=[],this.context===t&&(this.context=null)}});let{root:e}=t,i=(o,s)=>{t.addManagedDomListener(e,o,a=>{try{s(a)}catch(c){a.preventDefault(),a.stopImmediatePropagation(),t.reportError(c,"multi-range")}},!0)};i("mousedown",o=>this.s(o)),i("keydown",o=>this.a(o)),i("copy",o=>this.i(o)),i("cut",o=>this.i(o,!0)),t.addEventListener("rangeSelectionChanged",()=>this.t()),r=new MutationObserver(()=>this.t()),r.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-id","data-col-id"]}),t.addEventListener("modelUpdated",()=>this.clear())}snapshot(t){let r=this.context?.api;if(!r)return null;let e=F(r),i=e.indexOf(t.colId1),o=e.indexOf(t.colId2),s=Math.max(0,Math.min(t.row1,t.row2)),a=Math.min(r.rows.getCount()-1,Math.max(t.row1,t.row2));if(i<0||o<0||!Number.isInteger(s)||!Number.isInteger(a)||a<s)return null;let c=e.slice(Math.min(i,o),Math.max(i,o)+1);if((a-s+1)*c.length>R)throw new RangeError("A range may contain at most 100000 cells.");let h=[];for(let p=s;p<=a;p++){let l=r.rows.getAt(p);l?.data&&!l.isGroup&&!l.isDetail&&!l.loading&&h.push(l.id)}return{range:{row1:s,row2:a,colId1:e[Math.min(i,o)],colId2:e[Math.max(i,o)]},rows:h,columns:c}}n(){let t=this.context?.api.selection.getRange(),r=t?this.snapshot(t):null,e=r?[...this.saved,r]:[...this.saved];return d(e)}getRanges(){return this.n().map(t=>({...t.range}))}setRanges(t){if(!this.context)throw new Error("Install the multi-range feature before setting ranges.");if(t.length>g)throw new RangeError("At most 32 ranges are supported.");let r=d(t.map(e=>this.snapshot(e)).filter(e=>e!==null));this.context.api.selection.clearRange(),this.saved=r,this.t()}clear(){this.saved=[],this.context?.api.selection.clearRange(),this.o(),this.t()}getText(){let t=this.context?.api;return t?this.n().map(r=>b(r.rows.map(e=>r.columns.map(i=>y(t,e,i))))).join(`
3
3
 
4
4
  `):""}clearValues(){let t=this.context?.api;if(!t)return;let r=new Map;for(let e of this.n())for(let i of e.rows)for(let o of e.columns)r.set(JSON.stringify([i,o]),{rowId:i,colId:o,value:null});w(t,[...r.values()])}s(t){if(!(!t.target.closest(".mach-cell")||t.button!==0)){if(t.ctrlKey||t.metaKey){let e=this.context?.api.selection.getRange(),i=e?this.snapshot(e):null,o=d(i?[...this.saved,i]:this.saved);if(o.length>=g)throw new RangeError("At most 32 ranges are supported.");this.saved=o}else t.shiftKey||(this.saved=[]);this.t()}}a(t){if(!t.target.closest("input,textarea,select,[contenteditable=true]")){if(t.key==="Escape"){this.clear();return}t.key!=="Delete"&&t.key!=="Backspace"||this.saved.length===0||this.n().length<2||(t.preventDefault(),t.stopImmediatePropagation(),this.clearValues())}}i(t,r=!1){t.target.closest("input,textarea,select,[contenteditable=true]")||this.saved.length===0||this.n().length<2||this.context?.api.getOption("suppressClipboard")||t.clipboardData&&(t.clipboardData.setData("text/plain",this.getText()),t.preventDefault(),t.stopImmediatePropagation(),r&&this.clearValues())}t(){!this.context||this.e||(this.e=requestAnimationFrame(()=>{this.e=0,this.l()}))}o(){this.r?.(),this.r=null}l(){if(this.o(),!this.context)return;let t=this.saved.map(e=>({rows:new Set(e.rows),columns:new Set(e.columns)})),r=[];for(let e of this.context.root.querySelectorAll(".mach-cell")){let i=e.closest(".mach-row");t.some(o=>o.rows.has(i?.dataset.id??"")&&o.columns.has(e.dataset.colId??""))&&(e.classList.add("mach-cell--multi-range"),r.push(e))}this.r=()=>r.forEach(e=>e.classList.remove("mach-cell--multi-range"))}};0&&(module.exports={createMultiRangeSelection});
@@ -1,4 +1,4 @@
1
- import { G as GridFeature, a as GridCellRange } from './api-pOhyuSQk.cjs';
1
+ import { G as GridFeature, a as GridCellRange } from './api-CZkd8tYy.cjs';
2
2
 
3
3
  interface MultiRangeSelection extends GridFeature {
4
4
  getRanges(): GridCellRange[];
@@ -1,4 +1,4 @@
1
- import { G as GridFeature, a as GridCellRange } from './api-pOhyuSQk.js';
1
+ import { G as GridFeature, a as GridCellRange } from './api-CZkd8tYy.js';
2
2
 
3
3
  interface MultiRangeSelection extends GridFeature {
4
4
  getRanges(): GridCellRange[];
@@ -1,4 +1,4 @@
1
- var h=Symbol.for("mach-table.adapter.lifecycle.v1");function m(n,t,r){return n.isDestroyed()?"":n[h]?.readCell(t,r)??""}function y(n,t){n.isDestroyed()||n[h]?.writeInput(t)}function w(n){return typeof n!="string"||n===""||/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(n)?n:/^[\s\u0000-\u001f]*[=+\-@]/.test(n)?"'"+n:n}function R(n,t){let r=t?w(n):n,e=r==null?"":String(r);return/["\t\n\r]/.test(e)?'"'+e.replace(/"/g,'""')+'"':e}function v(n,t=!0){return n.map(r=>r.map(e=>R(e,t)).join(" ")).join(`
2
- `)}var d=32,x=1e5;function u(n){let t=[...new Map(n.map(r=>[JSON.stringify(r.range),r])).values()];if(t.length>d)throw new RangeError("At most 32 ranges are supported.");if(t.reduce((r,e)=>r+e.rows.length*e.columns.length,0)>x)throw new RangeError("A multi-range operation may affect at most 100000 cells.");return t}function A(n){let t=n.columns.getWorkbenchItems().filter(r=>r.visible);return["left",null,"right"].flatMap(r=>t.filter(e=>e.pinned===r).map(e=>e.colId))}function M(){return new g}var g=class{constructor(){this.key="multi-range";this.context=null;this.saved=[];this.e=0;this.r=null}setup(t){if(this.context)throw new Error("Create a separate multi-range feature for each grid.");if(!t.api.getOption("enableRangeSelection"))throw new Error("Multi-range selection requires enableRangeSelection: true.");this.context=t;let r=null;t.onCleanup(()=>{cancelAnimationFrame(this.e),this.e=0;try{r?.disconnect()}finally{this.o(),this.saved=[],this.context===t&&(this.context=null)}});let{root:e}=t,o=(i,s)=>{t.addManagedDomListener(e,i,a=>{try{s(a)}catch(c){a.preventDefault(),a.stopImmediatePropagation(),t.reportError(c,"multi-range")}},!0)};o("mousedown",i=>this.s(i)),o("keydown",i=>this.a(i)),o("copy",i=>this.i(i)),o("cut",i=>this.i(i,!0)),t.addEventListener("rangeSelectionChanged",()=>this.t()),r=new MutationObserver(()=>this.t()),r.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-id","data-col-id"]}),t.addEventListener("modelUpdated",()=>this.clear())}snapshot(t){let r=this.context?.api;if(!r)return null;let e=A(r),o=e.indexOf(t.colId1),i=e.indexOf(t.colId2),s=Math.max(0,Math.min(t.row1,t.row2)),a=Math.min(r.rows.getCount()-1,Math.max(t.row1,t.row2));if(o<0||i<0||!Number.isInteger(s)||!Number.isInteger(a)||a<s)return null;let c=e.slice(Math.min(o,i),Math.max(o,i)+1);if((a-s+1)*c.length>x)throw new RangeError("A range may contain at most 100000 cells.");let f=[];for(let p=s;p<=a;p++){let l=r.rows.getAt(p);l?.data&&!l.isGroup&&!l.isDetail&&!l.loading&&f.push(l.id)}return{range:{row1:s,row2:a,colId1:e[Math.min(o,i)],colId2:e[Math.max(o,i)]},rows:f,columns:c}}n(){let t=this.context?.api.selection.getRange(),r=t?this.snapshot(t):null,e=r?[...this.saved,r]:[...this.saved];return u(e)}getRanges(){return this.n().map(t=>({...t.range}))}setRanges(t){if(!this.context)throw new Error("Install the multi-range feature before setting ranges.");if(t.length>d)throw new RangeError("At most 32 ranges are supported.");let r=u(t.map(e=>this.snapshot(e)).filter(e=>e!==null));this.context.api.selection.clearRange(),this.saved=r,this.t()}clear(){this.saved=[],this.context?.api.selection.clearRange(),this.o(),this.t()}getText(){let t=this.context?.api;return t?this.n().map(r=>v(r.rows.map(e=>r.columns.map(o=>m(t,e,o))))).join(`
1
+ var h=Symbol.for("mach-table.adapter.lifecycle.v1");function m(n,t,r){return n.isDestroyed()?"":n[h]?.readCell(t,r)??""}function y(n,t){n.isDestroyed()||n[h]?.writeInput(t)}var w=/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/;function v(n){return typeof n!="string"||n===""||w.test(n)?n:/^[\s\u0000-\u001f]*[=+\-@]/.test(n)?"'"+n:n}function R(n){return n==null?"":String(n)}function D(n,t){let r=t?v(n):n,e=R(r);return/["\t\n\r]/.test(e)?'"'+e.replace(/"/g,'""')+'"':e}function x(n,t=!0){return n.map(r=>r.map(e=>D(e,t)).join(" ")).join(`
2
+ `)}var d=32,b=1e5;function u(n){let t=[...new Map(n.map(r=>[JSON.stringify(r.range),r])).values()];if(t.length>d)throw new RangeError("At most 32 ranges are supported.");if(t.reduce((r,e)=>r+e.rows.length*e.columns.length,0)>b)throw new RangeError("A multi-range operation may affect at most 100000 cells.");return t}function A(n){let t=n.columns.getWorkbenchItems().filter(r=>r.visible);return["left",null,"right"].flatMap(r=>t.filter(e=>e.pinned===r).map(e=>e.colId))}function L(){return new g}var g=class{constructor(){this.key="multi-range";this.context=null;this.saved=[];this.e=0;this.r=null}setup(t){if(this.context)throw new Error("Create a separate multi-range feature for each grid.");if(!t.api.getOption("enableRangeSelection"))throw new Error("Multi-range selection requires enableRangeSelection: true.");this.context=t;let r=null;t.onCleanup(()=>{cancelAnimationFrame(this.e),this.e=0;try{r?.disconnect()}finally{this.o(),this.saved=[],this.context===t&&(this.context=null)}});let{root:e}=t,o=(i,s)=>{t.addManagedDomListener(e,i,a=>{try{s(a)}catch(c){a.preventDefault(),a.stopImmediatePropagation(),t.reportError(c,"multi-range")}},!0)};o("mousedown",i=>this.s(i)),o("keydown",i=>this.a(i)),o("copy",i=>this.i(i)),o("cut",i=>this.i(i,!0)),t.addEventListener("rangeSelectionChanged",()=>this.t()),r=new MutationObserver(()=>this.t()),r.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-id","data-col-id"]}),t.addEventListener("modelUpdated",()=>this.clear())}snapshot(t){let r=this.context?.api;if(!r)return null;let e=A(r),o=e.indexOf(t.colId1),i=e.indexOf(t.colId2),s=Math.max(0,Math.min(t.row1,t.row2)),a=Math.min(r.rows.getCount()-1,Math.max(t.row1,t.row2));if(o<0||i<0||!Number.isInteger(s)||!Number.isInteger(a)||a<s)return null;let c=e.slice(Math.min(o,i),Math.max(o,i)+1);if((a-s+1)*c.length>b)throw new RangeError("A range may contain at most 100000 cells.");let f=[];for(let p=s;p<=a;p++){let l=r.rows.getAt(p);l?.data&&!l.isGroup&&!l.isDetail&&!l.loading&&f.push(l.id)}return{range:{row1:s,row2:a,colId1:e[Math.min(o,i)],colId2:e[Math.max(o,i)]},rows:f,columns:c}}n(){let t=this.context?.api.selection.getRange(),r=t?this.snapshot(t):null,e=r?[...this.saved,r]:[...this.saved];return u(e)}getRanges(){return this.n().map(t=>({...t.range}))}setRanges(t){if(!this.context)throw new Error("Install the multi-range feature before setting ranges.");if(t.length>d)throw new RangeError("At most 32 ranges are supported.");let r=u(t.map(e=>this.snapshot(e)).filter(e=>e!==null));this.context.api.selection.clearRange(),this.saved=r,this.t()}clear(){this.saved=[],this.context?.api.selection.clearRange(),this.o(),this.t()}getText(){let t=this.context?.api;return t?this.n().map(r=>x(r.rows.map(e=>r.columns.map(o=>m(t,e,o))))).join(`
3
3
 
4
- `):""}clearValues(){let t=this.context?.api;if(!t)return;let r=new Map;for(let e of this.n())for(let o of e.rows)for(let i of e.columns)r.set(JSON.stringify([o,i]),{rowId:o,colId:i,value:null});y(t,[...r.values()])}s(t){if(!(!t.target.closest(".mach-cell")||t.button!==0)){if(t.ctrlKey||t.metaKey){let e=this.context?.api.selection.getRange(),o=e?this.snapshot(e):null,i=u(o?[...this.saved,o]:this.saved);if(i.length>=d)throw new RangeError("At most 32 ranges are supported.");this.saved=i}else t.shiftKey||(this.saved=[]);this.t()}}a(t){if(!t.target.closest("input,textarea,select,[contenteditable=true]")){if(t.key==="Escape"){this.clear();return}t.key!=="Delete"&&t.key!=="Backspace"||this.saved.length===0||this.n().length<2||(t.preventDefault(),t.stopImmediatePropagation(),this.clearValues())}}i(t,r=!1){t.target.closest("input,textarea,select,[contenteditable=true]")||this.saved.length===0||this.n().length<2||this.context?.api.getOption("suppressClipboard")||t.clipboardData&&(t.clipboardData.setData("text/plain",this.getText()),t.preventDefault(),t.stopImmediatePropagation(),r&&this.clearValues())}t(){!this.context||this.e||(this.e=requestAnimationFrame(()=>{this.e=0,this.l()}))}o(){this.r?.(),this.r=null}l(){if(this.o(),!this.context)return;let t=this.saved.map(e=>({rows:new Set(e.rows),columns:new Set(e.columns)})),r=[];for(let e of this.context.root.querySelectorAll(".mach-cell")){let o=e.closest(".mach-row");t.some(i=>i.rows.has(o?.dataset.id??"")&&i.columns.has(e.dataset.colId??""))&&(e.classList.add("mach-cell--multi-range"),r.push(e))}this.r=()=>r.forEach(e=>e.classList.remove("mach-cell--multi-range"))}};export{M as createMultiRangeSelection};
4
+ `):""}clearValues(){let t=this.context?.api;if(!t)return;let r=new Map;for(let e of this.n())for(let o of e.rows)for(let i of e.columns)r.set(JSON.stringify([o,i]),{rowId:o,colId:i,value:null});y(t,[...r.values()])}s(t){if(!(!t.target.closest(".mach-cell")||t.button!==0)){if(t.ctrlKey||t.metaKey){let e=this.context?.api.selection.getRange(),o=e?this.snapshot(e):null,i=u(o?[...this.saved,o]:this.saved);if(i.length>=d)throw new RangeError("At most 32 ranges are supported.");this.saved=i}else t.shiftKey||(this.saved=[]);this.t()}}a(t){if(!t.target.closest("input,textarea,select,[contenteditable=true]")){if(t.key==="Escape"){this.clear();return}t.key!=="Delete"&&t.key!=="Backspace"||this.saved.length===0||this.n().length<2||(t.preventDefault(),t.stopImmediatePropagation(),this.clearValues())}}i(t,r=!1){t.target.closest("input,textarea,select,[contenteditable=true]")||this.saved.length===0||this.n().length<2||this.context?.api.getOption("suppressClipboard")||t.clipboardData&&(t.clipboardData.setData("text/plain",this.getText()),t.preventDefault(),t.stopImmediatePropagation(),r&&this.clearValues())}t(){!this.context||this.e||(this.e=requestAnimationFrame(()=>{this.e=0,this.l()}))}o(){this.r?.(),this.r=null}l(){if(this.o(),!this.context)return;let t=this.saved.map(e=>({rows:new Set(e.rows),columns:new Set(e.columns)})),r=[];for(let e of this.context.root.querySelectorAll(".mach-cell")){let o=e.closest(".mach-row");t.some(i=>i.rows.has(o?.dataset.id??"")&&i.columns.has(e.dataset.colId??""))&&(e.classList.add("mach-cell--multi-range"),r.push(e))}this.r=()=>r.forEach(e=>e.classList.remove("mach-cell--multi-range"))}};export{L as createMultiRangeSelection};
package/dist/ordering.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var ie=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var He=Object.prototype.hasOwnProperty;var qe=(r,e)=>{for(var t in e)ie(r,t,{get:e[t],enumerable:!0})},Be=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Fe(e))!He.call(r,o)&&o!==t&&ie(r,o,{get:()=>e[o],enumerable:!(n=Ne(e,o))||n.enumerable});return r};var Ke=r=>Be(ie({},"__esModule",{value:!0}),r);var et={};qe(et,{RowOrderConflictError:()=>P,createRowOrderController:()=>Ae,moveTreeNodes:()=>V,reorderRows:()=>X});module.exports=Ke(et);var Ue=new Set(["__proto__","prototype","constructor"]);function Ye(r){return typeof r!="string"||r.length===0?!1:r.split(".").every(t=>t.length>0&&!Ue.has(t))}function j(r,e){if(r==null||!Ye(e))return;if(e.indexOf(".")<0)return r[e];let n=r,o=0;for(;o<e.length;){if(n==null)return;let i=e.indexOf(".",o);if(i<0){n=n[e.slice(o)];break}n=n[e.slice(o,i)],o=i+1}return n}function _e(r,e){let t=typeof e.rowKey=="function"?e.rowKey(r):j(r,e.rowKey);if(t==null||String(t).length===0)throw new Error("[MachTable] Row ordering requires a non-empty stable row key.");return String(t)}function ze(r,e){let t=r[e];if(t==null)return[];if(!Array.isArray(t))throw new Error(`[MachTable] Tree ordering expects an array at "${e}".`);return t}function K(r,e,t,n){let o={entries:[],byId:new Map,byRow:new Map,children:new Map([[null,r]])},i=[...r].reverse().map(d=>({row:d,parentId:null,selectedAncestor:!1})),a=t.childrenKey??"children";for(;i.length;){let d=i.pop(),c=_e(d.row,t);if(o.byId.has(c))throw new Error(`[MachTable] Row ordering found duplicate or cyclic row key "${c}".`);let l=n?ze(d.row,a):[],h={...d,id:c,children:l};o.entries.push(h),o.byId.set(c,h),o.byRow.set(h.row,h),o.children.set(c,l);for(let f=l.length-1;f>=0;f--)i.push({row:l[f],parentId:c,selectedAncestor:d.selectedAncestor||e.has(c)})}return o}function $e(r){if(!["before","after","inside"].includes(r.position))throw new Error("[MachTable] Unknown row ordering position.");let e=[...new Set(r.rowIds.map(String))];if(!e.length)throw new Error("[MachTable] Row ordering requires at least one source row.");return{...r,rowIds:e,targetId:String(r.targetId)}}function ae(r,e){for(let n of e)if(!r.byId.has(n))throw new Error(`[MachTable] Ordering source "${n}" is unavailable.`);let t=new Set(e);return{selected:t,moved:r.entries.filter(n=>t.has(n.id)&&!n.selectedAncestor)}}function be(r,e,t,n){let o=r.byId.get(t.targetId);if(!o)throw new Error(`[MachTable] Ordering target "${t.targetId}" is unavailable.`);if(e.selected.has(o.id)||o.selectedAncestor)throw new Error("[MachTable] A row cannot be moved into or relative to its own subtree.");let i=t.position==="inside"?o.id:o.parentId,a=i===null?null:r.byId.get(i).row;if(n.canMove)for(let d of e.moved){let c=d.parentId===null?null:r.byId.get(d.parentId).row,l=n.canMove({row:d.row,previousParent:c,parent:a,target:o.row,intent:t});if(l===!1||typeof l=="string")throw new Error(typeof l=="string"?l:"[MachTable] This row cannot be moved to the selected parent.")}return i}function Re(r,e,t,n){let o=[...new Set(e.map(String))];if(!o.length)throw new Error("[MachTable] Row ordering requires at least one source row.");let i=K(r,new Set(o),t,n),a=ae(i,o);return d=>{if(!n&&d.position==="inside")throw new Error("[MachTable] Flat rows cannot have child destinations.");be(i,a,d,t)}}function We(r,e,t,n){let o=new Set(e.map(l=>l.id)),i=new Map;for(let l of e)i.has(l.parentId)||i.set(l.parentId,r.children.get(l.parentId).filter(h=>!o.has(r.byRow.get(h).id)));let a=i.get(t)??r.children.get(t),d=a.findIndex(l=>l===r.byId.get(n.targetId).row),c=n.position==="inside"?a.length:d+ +(n.position==="after");return i.set(t,[...a.slice(0,c),...e.map(l=>l.row),...a.slice(c)]),i}function ve(r,e){return r.length===e.length&&r.every((t,n)=>t===e[n])}function je(r,e,t,n){let o=new Map,i=n.childrenKey??"children";for(let d=e.entries.length-1;d>=0;d--){let c=e.entries[d],h=(t.get(c.id)??c.children).map(f=>o.get(f)??f);ve(c.children,h)||o.set(c.row,{...c.row,[i]:h})}let a=(t.get(null)??r).map(d=>o.get(d)??d);return ve(r,a)?r:a}function Xe(r,e,t,n){let o=t.indexOf(e[0].row),i=o+e.length;return{...r,rowIds:e.map(a=>a.id),beforeId:o>0?n.byRow.get(t[o-1]).id:null,afterId:i<t.length?n.byRow.get(t[i]).id:null}}function Te(r,e,t){let n=K(r.before,new Set(r.rowIds),e,t),o=new Map;for(let i of n.children.values())i.forEach((a,d)=>o.set(n.byRow.get(a).id,d));return ae(n,r.rowIds).moved.reverse().map(i=>{let a=n.children.get(i.parentId),d=o.get(i.id),c=a[d+1];if(c)return{rowIds:[i.id],targetId:n.byRow.get(c).id,position:"before"};if(i.parentId!==null)return{rowIds:[i.id],targetId:i.parentId,position:"inside"};let l=a[d-1];if(!l)throw new Error("[MachTable] Row ordering cannot restore an isolated root.");return{rowIds:[i.id],targetId:n.byRow.get(l).id,position:"after"}})}function Ie(r,e,t,n,o){if(!n.canMove)return;let i=K(r,new Set,n,o),a=K(e,new Set,n,o);for(let d of t)for(let c of d.rowIds){let l=i.byId.get(c),h=a.byId.get(c),f=h.parentId===null?null:i.byId.get(h.parentId).row,x=l.parentId===null?null:i.byId.get(l.parentId).row,E=n.canMove({row:l.row,previousParent:x,parent:f,target:i.byId.get(d.targetId).row,intent:d});if(E===!1||typeof E=="string")throw new Error(typeof E=="string"?E:"[MachTable] This row cannot be restored to its previous parent.")}}function De(r,e,t,n){let o=$e(e);if(!n&&o.position==="inside")throw new Error("[MachTable] Flat rows cannot have child destinations.");let i=K(r,new Set(o.rowIds),t,n),{moved:a,selected:d}=ae(i,o.rowIds),c=be(i,{moved:a,selected:d},o,t),l=We(i,a,c,o),h=je(r,i,l,t),f=Xe(o,a,l.get(c),i);return{before:r,after:h,intent:f,rowIds:f.rowIds,changed:r!==h}}function X(r,e,t){return De(r,e,t,!1)}function V(r,e,t){return De(r,e,t,!0)}function se(r,e,t){let n=document.createElement(r);if(e&&(n.className=e),t)for(let o of Object.keys(t))n.setAttribute(o,t[o]);return n}function M(r,e,t){return r<e?e:r>t?t:r}var de=Symbol.for("mach-table.adapter.lifecycle.v1");function J(r){return!r.isDestroyed()&&(r[de]?.canReplaceData()??!1)}function le(r,e){let t=r[de]?.rowDrag;return t?.original===e&&t.policy===r.getOption("rowDragPolicy")}function ce(r,e){let t=r[de];if(!t)return()=>{};t.rowDrag?.activeInteraction?.destroy();let n={original:e,policy:r.getOption("rowDragPolicy"),factory:o=>(n.activeInteraction=e(o),n.activeInteraction)};return t.rowDrag=n,()=>{n.activeInteraction?.destroy(),t.rowDrag===n&&(t.rowDrag=void 0)}}function Oe(r,e){return new Promise((t,n)=>{let o=()=>n(Object.assign(new Error("[MachTable] Operation cancelled."),{name:"AbortError"}));if(r.then(t,n).finally(()=>e.removeEventListener("abort",o)),e.aborted){o();return}e.addEventListener("abort",o,{once:!0})})}function ue(r,e,t){return r.replace("{a}",String(e)).replace("{b}",String(t))}function Ve(r,e,t){return r&&e>.25&&e<.75?"inside":t}function xe(r,e){let t=0,n=r.length;for(;t<n;){let o=t+n>>>1;r[o]<e?t=o+1:n=o}return t}function Je(r,e,t,n,o,i){let a=r.getOption("locale")??{},d=e>1?ue(a.rowDragSelection??"\u5DF2\u9009 {a} \u884C \u2192 \u7B2C {b} \u884C",e,n+1):ue(a.rowDragPosition??"\u7B2C {a} \u884C \u2192 \u7B2C {b} \u884C",t+1,n+1),c=o==="inside"?a.rowDragInside??"\u79FB\u5165":o==="before"?a.rowDragBefore??"\u4E4B\u524D":a.rowDragAfter??"\u4E4B\u540E";return{text:`${d} \xB7 ${c}`,indicatorStyle:o==="inside"?`height:${i}px;background:color-mix(in srgb,var(--mach-primary) 12%,transparent);box-shadow:inset 0 0 0 1px var(--mach-primary)`:void 0}}function Qe(r,e,t){let n={parents:new Map,siblings:new Map([[null,[]]]),depths:new Map},o=[...r].reverse().map(a=>({row:a,parent:null,depth:0})),i=e.childrenKey??"children";for(;o.length;){let{row:a,parent:d,depth:c}=o.pop(),l=String(typeof e.rowKey=="function"?e.rowKey(a):j(a,e.rowKey));if(n.depths.has(l))throw new Error("[MachTable] Row ordering requires unique, acyclic row keys.");n.depths.set(l,c),n.siblings.get(d).push(l),n.siblings.set(l,[]),d!==null&&n.parents.set(l,d);let h=t?a[i]:void 0;if(h!=null&&!Array.isArray(h))throw new Error("[MachTable] Row ordering children must be an array.");for(let f=(h?.length??0)-1;f>=0;f--)o.push({row:h[f],parent:l,depth:c+1})}return n}function Ee(r,e,t,n,o,i){let a=new Map;r.rows.forEach(u=>{!u.loading&&!u.isDetail&&!u.isGroup&&u.data!=null&&a.set(u.id,u)});let d=Qe(t,n,o),c=new Set(e.selected?[...d.depths.keys()].filter(u=>a.get(u)?.selected):[e.id]),l=[...c],h=u=>{let y=u;for(;y!==void 0;){if(c.has(y))return!0;y=d.parents.get(y)}return!1},f=new Map,x=new Map;for(let[u,y]of d.siblings){let m=y.filter(v=>!c.has(v));f.set(u,m),m.forEach((v,g)=>x.set(v,g))}let E=new Map,S=[],I=[],A=0;r.rows.forEachDisplayed(u=>{h(u.id)&&S.push(u.rowIndex),A=u.rowIndex+1;let y=d.depths.get(u.id)??0;for(;I.length&&(d.depths.get(I[I.length-1].id)??0)>=y;)E.set(I.pop().id,u.rowIndex);d.siblings.get(u.id)?.length&&I.push(u)});for(let u of I)E.set(u.id,A);return{rowIds:l,isSource:h,validate:()=>{for(let u of l){let y=a.get(u);if(y.treeLoading)return!1;let m=r.getOption("rowDragPolicy")?.canDrag?.({node:y,api:r});if(m===!1||typeof m=="string")return m}return!0},resolve:({targetNode:u,position:y,fraction:m,height:v})=>{let g=Ve(o,m,y);if(h(u.id))return"Cannot target own subtree.";if(!o&&g==="inside")return!1;let _=g==="inside"?u.id:d.parents.get(u.id)??null,C=f.get(_)??[],L=g==="inside"?C.length:(x.get(u.id)??0)+ +(g==="after"),G=g==="before"?u.rowIndex:E.get(u.id)??u.rowIndex+1,z=G-xe(S,G)+xe(S,e.rowIndex);return{intent:{rowIds:l,targetId:u.id,position:g,beforeId:C[L-1]??null,afterId:C[L]??null,expectedRevision:i},indicatorIndex:g==="inside"?u.rowIndex:g==="after"?E.get(u.id):void 0,toIndex:G,targetIndex:z,...Je(r,l.length,e.rowIndex,u.rowIndex,g,v)}},keyboardTarget:u=>{let y=e.id;for(;c.has(d.parents.get(y)??"");)y=d.parents.get(y);let m=d.siblings.get(d.parents.get(y)??null)??[],v=m.indexOf(y)+u;for(;v>=0&&v<m.length;){let g=m[v];if(!h(g)&&a.has(g))return a.get(g);v+=u}}}}var Q=class{constructor(e){this.host=e;this.drag=null;this.t=0;this.r=0;this.s=e=>{let t=this.drag;if(!(!t||e.pointerId!==t.pointerId)){if(t.clientX=e.clientX,t.clientY=e.clientY,!t.active){if(Math.abs(e.clientY-t.startY)<5)return;t.active=!0,this.host.root.classList.add("mach-root--row-dragging"),this.host.root.querySelectorAll(".mach-row").forEach(n=>n.classList.toggle("mach-row--drag-source",this.sourceContains(n.dataset.id??"")))}this.d()}};this.h=()=>{if(this.t=0,!!this.drag?.active){if(!this.current()){this.destroy();return}this.c(),this.g()&&this.d()}};this.a=e=>{let t=this.drag;if(!(!t||e.pointerId!==t.pointerId)){t.clientX=e.clientX,t.clientY=e.clientY,t.active&&this.current()&&this.c(),this.u();try{t.active&&t.drop?.valid&&this.o(e.clientX,e.clientY)&&this.current()&&this.commitDrop(t.drop)}finally{this.release()}}};this.l=e=>{e.key==="Escape"&&(e.preventDefault(),this.destroy())};this.n=e=>{e.type==="pointercancel"&&e.pointerId!==this.drag?.pointerId||this.destroy()}}begin(e){let t=this.host.containers.map(o=>{let i=se("div","mach-row-drop-indicator");return i.hidden=!0,o.append(i),i}),n=se("div","mach-row-drag-preview");n.setAttribute("role","status"),n.hidden=!0,this.host.root.append(n),this.drag={startY:e.clientY,clientX:e.clientX,clientY:e.clientY,pointerId:e.pointerId,indicators:t,preview:n,drop:null,active:!1},window.addEventListener("pointermove",this.s),window.addEventListener("pointerup",this.a),window.addEventListener("pointercancel",this.n),window.addEventListener("keydown",this.l),window.addEventListener("blur",this.n)}draggingSource(e){return this.drag?.active===!0&&this.sourceContains(e)}focusHandle(e,t=()=>!0){this.r=requestAnimationFrame(()=>{this.r=0,t()&&[...this.host.root.querySelectorAll(".mach-row-drag-handle")].find(n=>n.closest(".mach-row")?.dataset.id===e)?.focus()})}d(){this.t||(this.t=requestAnimationFrame(this.h))}o(e,t,n=0){let o=this.host.body.getBoundingClientRect();return e>=o.left&&e<=o.right&&t>=o.top-n&&t<=o.bottom+n}g(){let e=this.drag;if(!e||!this.o(e.clientX,e.clientY,28))return!1;let t=this.host.viewport,n=t.getBoundingClientRect(),o=Math.min(36,n.height/3);if(o<=0)return!1;let i=e.clientY<n.top+o?-Math.ceil(14*M((n.top+o-e.clientY)/o,0,1)):Math.ceil(14*M((e.clientY-n.bottom+o)/o,0,1)),a=t.scrollTop;return t.scrollTop=M(a+i,0,Math.max(0,t.scrollHeight-t.clientHeight)),t.scrollTop!==a}c(){let e=this.drag;if(!e?.active)return;let t=e.clientY-this.host.viewport.getBoundingClientRect().top+this.host.viewport.scrollTop,n=this.describe(t);e.drop=n;let o=this.o(e.clientX,e.clientY);for(let a of e.indicators)a.hidden=!o||!n?.valid,n&&(a.dataset.dropPosition=n.position??"",a.style.cssText=n.style??"",a.style.transform=`translate3d(0, ${this.host.getRowTop(n.boundary)}px, 0)`);let i=this.host.root.getBoundingClientRect();e.preview.hidden=!1,e.preview.textContent=o?n?.text??this.outsideText():this.outsideText(),e.preview.style.transform=`translate3d(${M(e.clientX-i.left+16,8,Math.max(8,i.width-224))}px, ${M(e.clientY-i.top+16,8,Math.max(8,i.height-48))}px, 0)`}u(){let e=this.drag;this.drag=null,window.removeEventListener("pointermove",this.s),window.removeEventListener("pointerup",this.a),window.removeEventListener("pointercancel",this.n),window.removeEventListener("keydown",this.l),window.removeEventListener("blur",this.n),cancelAnimationFrame(this.t),this.t=0,this.host.root?.classList.remove("mach-root--row-dragging"),this.host.root?.querySelectorAll(".mach-row--drag-source").forEach(t=>t.classList.remove("mach-row--drag-source")),e?.indicators.forEach(t=>t.remove()),e?.preview.remove()}destroy(){this.u(),this.release(),cancelAnimationFrame(this.r),this.r=0}};var Z=class extends Q{constructor(t,n,o){super(t);this.bridge=t;this.prepare=n;this.requestFocus=o;this.scope=null;this.i=!1}e(t,n,o){try{return n()}catch(i){return this.scope&&(this.scope.failed=!0),this.bridge.report(i,t),o}}p(t){return this.e("prepare",()=>{let n=this.bridge.capture(t),o=this.prepare(t);return this.scope={node:t,from:t.rowIndex,guard:n,session:o,sourceDecision:!0,failed:!1},this.scope.sourceDecision=o.validate(),this.scope},null)}start(t,n){this.destroy(),this.p(n)&&this.current()&&this.begin(t)}moveWithKeyboard(t,n){this.destroy();let o=this.p(n);if(!(!o||!this.current())){this.i=!0;try{let i=t.key==="ArrowUp"?-1:1,a=this.e("keyboardTarget",()=>o.session.keyboardTarget(i),void 0);a&&this.commitDrop(this.destination(a,i<0?0:1))}finally{this.i=!1,this.release()}}}isSource(t){return this.draggingSource(t.id)}current(){return!!(this.scope&&!this.scope.failed&&this.scope.guard.current()&&this.bridge.api.rows.getById(this.scope.node.id)===this.scope.node)}sourceContains(t){return this.e("isSource",()=>this.scope?.session.isSource(t)??!1,!1)}release(){this.scope=null}outsideText(){return this.bridge.api.getOption("locale")?.rowDragOutside??"\u79FB\u56DE\u8868\u683C\u5185\u653E\u7F6E \xB7 Esc \u53D6\u6D88"}describe(t){let n=this.bridge.api,o=M(this.host.findRowAt(t),0,n.rows.getCount()-1),i=n.rows.getAt(o);if(i?.isDetail&&(i=n.rows.getById(i.masterId)),!i)return null;let a=this.host.getRowTop(i.rowIndex),d=this.host.getRowTop(i.rowIndex+1)-a;return this.destination(i,(t-a)/Math.max(1,d))}destination(t,n){let o=this.scope,i=n<.5?"before":"after",a=this.host.getRowTop(t.rowIndex+1)-this.host.getRowTop(t.rowIndex),d=this.e("resolve",()=>o.session.resolve({targetNode:t,position:i,fraction:n,height:a}),!1),c=typeof o.sourceDecision=="string"?o.sourceDecision:typeof d=="string"?d:"\u6B64\u4F4D\u7F6E\u4E0D\u53EF\u653E\u7F6E",l={node:t,fraction:n,boundary:t.rowIndex,valid:!1,text:c};if(!d||typeof d=="string"||o.sourceDecision!==!0||t.loading||t.treeLoading||t.isGroup)return l;l.intent=d.intent,l.position=d.intent.position,l.toIndex=d.toIndex,l.targetIndex=d.targetIndex,l.boundary=d.indicatorIndex??t.rowIndex+ +(d.intent.position==="after"),l.style=d.indicatorStyle,l.text=d.text??c;let h=this.e("canDrop",()=>this.bridge.api.getOption("rowDragPolicy")?.canDrop?.({node:o.node,api:this.bridge.api,targetNode:t,intent:d.intent})??!0,!1);return l.valid=h===!0,typeof h=="string"&&(l.text=h),l}commitDrop(t){let n=this.scope;if(!n||!this.current()||this.e("validate",()=>n.session.validate(),!1)!==!0||!this.current())return!1;let o=this.destination(t.node,t.fraction);return!o.valid||!o.intent||!this.current()?!1:(this.i&&this.requestFocus(o.intent,i=>this.focusHandle(n.node.id,i)),this.bridge.emit(n.node,n.from,o.toIndex,o.targetIndex,o.intent),!0)}};function U(r,e,t){let n=[],o=[...r].reverse().map(a=>({row:a,parent:null})),i=new Set;for(;o.length;){let a=o.pop();if(i.has(a.row))throw new Error("[MachTable] Installed order contains duplicate or cyclic rows.");i.add(a.row),n.push(a);let d=t?a.row[e]??[]:[];for(let c=d.length-1;c>=0;c--)o.push({row:d[c],parent:a.row})}return n}function H(r,e,t,n){try{let o=U(r,t,n);return o.length===e.length&&o.every((i,a)=>i.row===e[a].row&&i.parent===e[a].parent)}catch{return!1}}function pe(r){let e=[];return r?.rows.forEach(t=>e.push({node:t,data:t.data})),e}function Y(r,e){if(!r)return!0;if(r.isDestroyed())return!1;let t=0,n=!0;return r.rows.forEach(o=>{let i=e[t++];(i?.node!==o||i.data!==o.data)&&(n=!1)}),n&&t===e.length}var ee=class{constructor(){this.entries=[];this.cursor=0}get canUndo(){return this.cursor>0}get canRedo(){return this.cursor<this.entries.length}peek(e){return this.entries[e==="undo"?this.cursor-1:this.cursor]}commit(e,t){e==="undo"?this.cursor--:e==="redo"?this.cursor++:(this.entries.splice(this.cursor),this.entries.push(t),this.entries.length>50&&this.entries.shift(),this.cursor=this.entries.length)}clear(){this.entries=[],this.cursor=0}};var P=class extends Error{constructor(t="The row order changed on the server. Reload before trying again.",n){super(t);this.serverRevision=n;this.name="RowOrderConflictError"}};function Ze(r){if(r?.status==="conflict")throw new P(r.message,r.revision);return r?.revision}function Se(r){if(r.targetId===null)throw new Error("[MachTable] Row ordering requires an existing destination.");return{...r,targetId:r.targetId}}function Ae(r){let e={status:"idle",error:null,revision:r.getRevision?.(),plan:null,canUndo:!1,canRedo:!1},t=0,n=!1,o=null,i=null,a=null,d=()=>{},c=()=>{},l=0,h=null,f=new ee,x=null,E=new Set,S=r.childrenKey??"children",I=null,A=()=>{f.clear(),x=null},u=()=>{if(!o)return!1;let s=o;return t++,o=null,i=null,s.abort(),!0},y=(s=e.status)=>({canUndo:!n&&s!=="saving"&&f.canUndo,canRedo:!n&&s!=="saving"&&f.canRedo}),m=s=>{e=Object.freeze({...s,...y(s.status)}),a&&!a.isDestroyed()&&a.view.refreshCells();let p=[w=>r.onStateChange?.(w),...E];for(let w of p)try{w?.(e)}catch(b){console.error("[MachTable] Row order state observer failed",b)}},v=()=>r.getRevision?.()??e.revision,g=(s=h)=>{s?.release(),h===s&&(h=null)},_=()=>{!i||i()||(u(),A(),g(),m({...e,status:"idle",plan:null,error:null}))},C=s=>new Z(s,p=>Ee(s.api,p,r.getRows(),r,r.treeData===!0,v()),(p,w)=>{g();let b=document.activeElement,T=N=>{N.target!==b&&N.target!==document.body&&g(R)},R={api:s.api,intent:p,restore:w,generation:t+1,release:()=>document.removeEventListener("focusin",T,!0)};h=R,document.addEventListener("focusin",T,!0)}),L=()=>{_(),!o&&x&&(x.api!==a||x.revision!==v()||!Y(a,x.nodes)||!H(r.getRows(),x.rows,S,r.treeData===!0))&&A();let s=y();(e.canUndo!==s.canUndo||e.canRedo!==s.canRedo)&&(e=Object.freeze({...e,...s}))},G=s=>{if(s===a){_(),le(s,C)||(c(),c=ce(s,C));return}let p=u();d(),c(),g(),A(),a=s,c=ce(s,C),d=s.on("cellValueChanged",()=>{l++;let w=f.canUndo||f.canRedo;A(),w&&m({...e,status:o?"saving":"idle",plan:o?e.plan:null,error:null})}),p&&m({...e,status:"idle",plan:null,error:null})},z=s=>{if(L(),n)throw new Error("[MachTable] The row order controller is disposed.");if(o)throw new Error("[MachTable] A row order save is already in progress.");let p=v();if(p!==void 0&&s.expectedRevision!==void 0&&s.expectedRevision!==p)throw new P;let w={...s,expectedRevision:s.expectedRevision??p};return(r.treeData?V:X)(r.getRows(),w,r)},he=async(s,p,w,b,T)=>{if(!s.changed)return s;let R=a;if(R&&!J(R))throw new Error("[MachTable] Save or discard edited rows before changing their order.");let N=++t;I=null;let $=new AbortController;o=$,i=null;let W=v(),Le=l,F=null,q=[],ye=!1,te=!1,re=W,me=D=>{if(!T)return;if(!D||T!==h||T.api!==a){g(T);return}let O=x;T.restore(()=>{let oe=O!==null&&O===x&&O.revision===v()&&Y(T.api,O.nodes)&&H(r.getRows(),O.rows,S,r.treeData===!0)&&h===T&&!n&&t===T.generation&&a===T.api&&le(T.api,C);return g(T),oe})},k=()=>!n&&t===N,ne=()=>k()&&(!R||a===R&&!R.isDestroyed())&&F!==null&&v()===W&&Y(R,q)&&H(r.getRows(),F,S,r.treeData===!0),ke=D=>{if(!ne()){k()&&!F&&m({...e,status:"error",error:D,plan:s});return}let O=!R||J(R),B=O?D:Object.assign(new Error("[MachTable] Row order could not be saved. Automatic rollback was skipped to preserve new edits. Save or discard those edits, then reload the row order."),{cause:D});if(O){i=null;try{r.applyRows(s.before),te=!0}catch(oe){B=Object.assign(new Error("[MachTable] Row order could not be saved or restored. Reload the row order before trying again."),{cause:D,rollbackError:oe})}}k()&&(te||A(),m({...e,status:D instanceof P?"conflict":"error",error:B}))},Ge=()=>{if(!k()){me(!1);return}let D=v(),O=!1;ye&&k()&&(D===W||D===re)&&Y(R,q)&&H(r.getRows(),F,S,r.treeData===!0)?(x={rows:F,nodes:q,api:R,revision:D},O=!0):te&&k()?(x={rows:U(r.getRows(),S,r.treeData===!0),nodes:pe(R),api:R,revision:D},O=H(r.getRows(),U(s.before,S,r.treeData===!0),S,r.treeData===!0)):A(),o===$&&(o=null,i=null,a&&!a.isDestroyed()&&a.view.refreshCells()),k()&&e.status==="saving"&&m({...e,status:"idle",plan:null}),L(),me(O)};try{r.applyRows(s.after),F=U(r.getRows(),S,r.treeData===!0),q=pe(R);let D=r.getRows(),O=q[0]?.node;if(i=R&&O?()=>!R.isDestroyed()&&R.rows.getById(O.id)===O:()=>r.getRows()===D,m({...e,status:"saving",error:null,plan:s}),!ne())return s;let B=Ze(await Oe(Promise.resolve(r.save?.(s.intent,{signal:$.signal,plan:s,operation:p,operations:w})),$.signal));return ne()&&(ye=!0,re=B??W,l===Le?f.commit(p,b):A(),m({...e,status:"saved",revision:re})),s}catch(D){throw ke(D),D}finally{Ge()}},we=async(s,p)=>{p!==h&&(p=void 0),h!==p&&g();let w=z(s);w.changed||g(p);let b=w.changed?Te(w,r,r.treeData===!0):[];return he(w,"move",[w.intent],{plan:w,inverse:b},p)},Ce=s=>we(s),ge=async s=>{if(g(),L(),n||o)throw new Error("[MachTable] Row ordering is unavailable while disposed or saving.");let p=f.peek(s);if(!p)throw new Error(`[MachTable] Nothing to ${s}.`);let w=(s==="undo"?p.inverse:[p.plan.intent]).map(N=>({...N,expectedRevision:v()})),b=r.getRows(),T=s==="undo"?p.plan.before:p.plan.after;Ie(b,T,w,r,r.treeData===!0);let R={before:b,after:T,intent:w[0],rowIds:p.plan.rowIds,changed:!0};return he(R,s,w,p)},Me=s=>{try{if(n||o)return!1;let p=r.getRows(),w=v();if(w!==void 0&&s.expectedRevision!==void 0&&s.expectedRevision!==w)return!1;let b=I?.rowIds===s.rowIds?I.sources:JSON.stringify(s.rowIds.map(String));return(!I||I.rows!==p||I.revision!==w||I.sources!==b)&&(I={rows:p,revision:w,sources:b,rowIds:s.rowIds,validate:Re(p,s.rowIds,r,r.treeData===!0)}),I.rowIds=s.rowIds,I.validate(s),!0}catch(p){return p instanceof Error?p.message:!1}},Pe=s=>{let p=s.intent;if(s.applied||!p)return;G(s.api);let w=t,b=h?.intent===p?h:void 0;Promise.resolve().then(()=>we(Se(p),b)).catch(T=>{b&&b.generation!==t&&g(b),!n&&t===w&&e.status!=="saving"&&m({...e,status:T instanceof P?"conflict":"error",error:T})})},fe=s=>n?!1:(G(s),o?"Wait for the current row order to finish saving.":J(s)||"Save or discard edited rows before changing their order.");return{get state(){return L(),e},bindings:{applyRowDrag:!1,rowDragPolicy:{canDrag:({api:s})=>fe(s),canDrop:({intent:s,api:p})=>{let w=fe(p);if(w!==!0)return w;try{return Me(Se(s))}catch(b){return b instanceof Error?b.message:!1}},getRevision:v},onRowDragEnd:Pe},preview:z,move:Ce,undo:()=>ge("undo"),redo:()=>ge("redo"),subscribe(s){return n?()=>{}:(E.add(s),()=>{E.delete(s)})},dispose(){n=!0,t++,o?.abort(),o=null,i=null,d(),c(),g(),A(),a&&!a.isDestroyed()&&a.view.refreshCells(),a=null,I=null,E.clear(),e=Object.freeze({...e,status:"idle",error:null,plan:null,canUndo:!1,canRedo:!1})}}}0&&(module.exports={RowOrderConflictError,createRowOrderController,moveTreeNodes,reorderRows});
1
+ "use strict";var ae=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var qe=Object.prototype.hasOwnProperty;var Be=(r,e)=>{for(var t in e)ae(r,t,{get:e[t],enumerable:!0})},Ke=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of He(e))!qe.call(r,o)&&o!==t&&ae(r,o,{get:()=>e[o],enumerable:!(n=Fe(e,o))||n.enumerable});return r};var Ue=r=>Ke(ae({},"__esModule",{value:!0}),r);var nt={};Be(nt,{RowOrderConflictError:()=>L,createRowOrderController:()=>Me,moveTreeNodes:()=>Q,reorderRows:()=>J});module.exports=Ue(nt);var Ye=new Set(["__proto__","prototype","constructor"]),Y=new Map;function _e(r){if(typeof r!="string"||r.length===0)return null;let e=Y.get(r);if(e!==void 0)return e;let t=r.split("."),n=t.every(o=>o.length>0&&!Ye.has(o))?t:null;return r.length<=1024&&(Y.size>=256&&Y.delete(Y.keys().next().value),Y.set(r,n)),n}function V(r,e){if(r==null)return;let t=_e(e);if(!t)return;let n=r;for(let o of t){if(n==null)return;n=n[o]}return n}function $e(r,e){let t=typeof e.rowKey=="function"?e.rowKey(r):V(r,e.rowKey);if(t==null||String(t).length===0)throw new Error("[MachTable] Row ordering requires a non-empty stable row key.");return String(t)}function We(r,e){let t=r[e];if(t==null)return[];if(!Array.isArray(t))throw new Error(`[MachTable] Tree ordering expects an array at "${e}".`);return t}function _(r,e,t,n){let o={entries:[],byId:new Map,byRow:new Map,children:new Map([[null,r]])},i=[...r].reverse().map(a=>({row:a,parentId:null,selectedAncestor:!1})),s=t.childrenKey??"children";for(;i.length;){let a=i.pop(),c=$e(a.row,t);if(o.byId.has(c))throw new Error(`[MachTable] Row ordering found duplicate or cyclic row key "${c}".`);let l=n?We(a.row,s):[],w={...a,id:c,children:l};o.entries.push(w),o.byId.set(c,w),o.byRow.set(w.row,w),o.children.set(c,l);for(let f=l.length-1;f>=0;f--)i.push({row:l[f],parentId:c,selectedAncestor:a.selectedAncestor||e.has(c)})}return o}function ze(r){if(!["before","after","inside"].includes(r.position))throw new Error("[MachTable] Unknown row ordering position.");let e=[...new Set(r.rowIds.map(String))];if(!e.length)throw new Error("[MachTable] Row ordering requires at least one source row.");return{...r,rowIds:e,targetId:String(r.targetId)}}function de(r,e){for(let n of e)if(!r.byId.has(n))throw new Error(`[MachTable] Ordering source "${n}" is unavailable.`);let t=new Set(e);return{selected:t,moved:r.entries.filter(n=>t.has(n.id)&&!n.selectedAncestor)}}function Re(r,e,t,n){let o=r.byId.get(t.targetId);if(!o)throw new Error(`[MachTable] Ordering target "${t.targetId}" is unavailable.`);if(e.selected.has(o.id)||o.selectedAncestor)throw new Error("[MachTable] A row cannot be moved into or relative to its own subtree.");let i=t.position==="inside"?o.id:o.parentId,s=i===null?null:r.byId.get(i).row;if(n.canMove)for(let a of e.moved){let c=a.parentId===null?null:r.byId.get(a.parentId).row,l=n.canMove({row:a.row,previousParent:c,parent:s,target:o.row,intent:t});if(l===!1||typeof l=="string")throw new Error(typeof l=="string"?l:"[MachTable] This row cannot be moved to the selected parent.")}return i}function Te(r,e,t,n){let o=[...new Set(e.map(String))];if(!o.length)throw new Error("[MachTable] Row ordering requires at least one source row.");let i=_(r,new Set(o),t,n),s=de(i,o);return a=>{if(!n&&a.position==="inside")throw new Error("[MachTable] Flat rows cannot have child destinations.");Re(i,s,a,t)}}function je(r,e,t,n){let o=new Set(e.map(l=>l.id)),i=new Map;for(let l of e)i.has(l.parentId)||i.set(l.parentId,r.children.get(l.parentId).filter(w=>!o.has(r.byRow.get(w).id)));let s=i.get(t)??r.children.get(t),a=s.findIndex(l=>l===r.byId.get(n.targetId).row),c=n.position==="inside"?s.length:a+ +(n.position==="after");return i.set(t,[...s.slice(0,c),...e.map(l=>l.row),...s.slice(c)]),i}function be(r,e){return r.length===e.length&&r.every((t,n)=>t===e[n])}function Xe(r,e,t,n){let o=new Map,i=n.childrenKey??"children";for(let a=e.entries.length-1;a>=0;a--){let c=e.entries[a],w=(t.get(c.id)??c.children).map(f=>o.get(f)??f);be(c.children,w)||o.set(c.row,{...c.row,[i]:w})}let s=(t.get(null)??r).map(a=>o.get(a)??a);return be(r,s)?r:s}function Ve(r,e,t,n){let o=t.indexOf(e[0].row),i=o+e.length;return{...r,rowIds:e.map(s=>s.id),beforeId:o>0?n.byRow.get(t[o-1]).id:null,afterId:i<t.length?n.byRow.get(t[i]).id:null}}function Ie(r,e,t){let n=_(r.before,new Set(r.rowIds),e,t),o=new Map;for(let i of n.children.values())i.forEach((s,a)=>o.set(n.byRow.get(s).id,a));return de(n,r.rowIds).moved.reverse().map(i=>{let s=n.children.get(i.parentId),a=o.get(i.id),c=s[a+1];if(c)return{rowIds:[i.id],targetId:n.byRow.get(c).id,position:"before"};if(i.parentId!==null)return{rowIds:[i.id],targetId:i.parentId,position:"inside"};let l=s[a-1];if(!l)throw new Error("[MachTable] Row ordering cannot restore an isolated root.");return{rowIds:[i.id],targetId:n.byRow.get(l).id,position:"after"}})}function De(r,e,t,n,o){if(!n.canMove)return;let i=_(r,new Set,n,o),s=_(e,new Set,n,o);for(let a of t)for(let c of a.rowIds){let l=i.byId.get(c),w=s.byId.get(c),f=w.parentId===null?null:i.byId.get(w.parentId).row,O=l.parentId===null?null:i.byId.get(l.parentId).row,S=n.canMove({row:l.row,previousParent:O,parent:f,target:i.byId.get(a.targetId).row,intent:a});if(S===!1||typeof S=="string")throw new Error(typeof S=="string"?S:"[MachTable] This row cannot be restored to its previous parent.")}}function Oe(r,e,t,n){let o=ze(e);if(!n&&o.position==="inside")throw new Error("[MachTable] Flat rows cannot have child destinations.");let i=_(r,new Set(o.rowIds),t,n),{moved:s,selected:a}=de(i,o.rowIds),c=Re(i,{moved:s,selected:a},o,t),l=je(i,s,c,o),w=Xe(r,i,l,t),f=Ve(o,s,l.get(c),i);return{before:r,after:w,intent:f,rowIds:f.rowIds,changed:r!==w}}function J(r,e,t){return Oe(r,e,t,!1)}function Q(r,e,t){return Oe(r,e,t,!0)}function le(r,e,t){let n=document.createElement(r);if(e&&(n.className=e),t)for(let o of Object.keys(t))n.setAttribute(o,t[o]);return n}function C(r,e,t){return r<e?e:r>t?t:r}var ce=Symbol.for("mach-table.adapter.lifecycle.v1");function Z(r){return!r.isDestroyed()&&(r[ce]?.canReplaceData()??!1)}function ue(r,e){let t=r[ce]?.rowDrag;return t?.original===e&&t.policy===r.getOption("rowDragPolicy")}function pe(r,e){let t=r[ce];if(!t)return()=>{};t.rowDrag?.activeInteraction?.destroy();let n={original:e,policy:r.getOption("rowDragPolicy"),factory:o=>(n.activeInteraction=e(o),n.activeInteraction)};return t.rowDrag=n,()=>{n.activeInteraction?.destroy(),t.rowDrag===n&&(t.rowDrag=void 0)}}function Je(r,e){if(r instanceof Error)return r;let t=new Error(typeof r=="string"?r:e);return t.name="AbortError",t}var Qe=()=>Je(void 0,"[MachTable] Operation cancelled.");function xe(r,e,t=Qe){return e?new Promise((n,o)=>{let i=()=>{e.removeEventListener("abort",i),o(t())};if(r.then(n,o).finally(()=>e.removeEventListener("abort",i)),e.aborted){i();return}e.addEventListener("abort",i,{once:!0})}):r}function we(r,e,t){return r.replace("{a}",String(e)).replace("{b}",String(t))}function Ze(r,e,t){return r&&e>.25&&e<.75?"inside":t}function Ee(r,e){let t=0,n=r.length;for(;t<n;){let o=t+n>>>1;r[o]<e?t=o+1:n=o}return t}function et(r,e,t,n,o,i){let s=r.getOption("locale")??{},a=e>1?we(s.rowDragSelection??"\u5DF2\u9009 {a} \u884C \u2192 \u7B2C {b} \u884C",e,n+1):we(s.rowDragPosition??"\u7B2C {a} \u884C \u2192 \u7B2C {b} \u884C",t+1,n+1),c=o==="inside"?s.rowDragInside??"\u79FB\u5165":o==="before"?s.rowDragBefore??"\u4E4B\u524D":s.rowDragAfter??"\u4E4B\u540E";return{text:`${a} \xB7 ${c}`,indicatorStyle:o==="inside"?`height:${i}px;background:color-mix(in srgb,var(--mach-primary) 12%,transparent);box-shadow:inset 0 0 0 1px var(--mach-primary)`:void 0}}function tt(r,e,t){let n={parents:new Map,siblings:new Map([[null,[]]]),depths:new Map},o=[...r].reverse().map(s=>({row:s,parent:null,depth:0})),i=e.childrenKey??"children";for(;o.length;){let{row:s,parent:a,depth:c}=o.pop(),l=String(typeof e.rowKey=="function"?e.rowKey(s):V(s,e.rowKey));if(n.depths.has(l))throw new Error("[MachTable] Row ordering requires unique, acyclic row keys.");n.depths.set(l,c),n.siblings.get(a).push(l),n.siblings.set(l,[]),a!==null&&n.parents.set(l,a);let w=t?s[i]:void 0;if(w!=null&&!Array.isArray(w))throw new Error("[MachTable] Row ordering children must be an array.");for(let f=(w?.length??0)-1;f>=0;f--)o.push({row:w[f],parent:l,depth:c+1})}return n}function Se(r,e,t,n,o,i){let s=new Map;r.rows.forEach(u=>{!u.loading&&!u.isDetail&&!u.isGroup&&u.data!=null&&s.set(u.id,u)});let a=tt(t,n,o),c=new Set(e.selected?[...a.depths.keys()].filter(u=>s.get(u)?.selected):[e.id]),l=[...c],w=u=>{let g=u;for(;g!==void 0;){if(c.has(g))return!0;g=a.parents.get(g)}return!1},f=new Map,O=new Map;for(let[u,g]of a.siblings){let y=g.filter(m=>!c.has(m));f.set(u,y),y.forEach((m,T)=>O.set(m,T))}let S=new Map,A=new Set,x=[],E=[],q=0;r.rows.forEachDisplayed(u=>{A.add(u.id),w(u.id)&&x.push(u.rowIndex),q=u.rowIndex+1;let g=a.depths.get(u.id)??0;for(;E.length&&(a.depths.get(E[E.length-1].id)??0)>=g;)S.set(E.pop().id,u.rowIndex);a.siblings.get(u.id)?.length&&E.push(u)});for(let u of E)S.set(u.id,q);return{rowIds:l,isSource:w,validate:()=>{for(let u of l){let g=s.get(u);if(g.treeLoading)return!1;let y=r.getOption("rowDragPolicy")?.canDrag?.({node:g,api:r});if(y===!1||typeof y=="string")return y}return!0},resolve:({targetNode:u,position:g,fraction:y,height:m})=>{let T=Ze(o,y,g);if(w(u.id))return"Cannot target own subtree.";if(!o&&T==="inside")return!1;let k=T==="inside"?u.id:a.parents.get(u.id)??null,M=f.get(k)??[],B=T==="inside"?M.length:(O.get(u.id)??0)+ +(T==="after"),N=T==="before"?u.rowIndex:S.get(u.id)??u.rowIndex+1,z=N-Ee(x,N)+Ee(x,e.rowIndex);return{intent:{rowIds:l,targetId:u.id,position:T,beforeId:M[B-1]??null,afterId:M[B]??null,expectedRevision:i},indicatorIndex:T==="inside"?u.rowIndex:T==="after"?S.get(u.id):void 0,toIndex:N,targetIndex:z,...et(r,l.length,e.rowIndex,u.rowIndex,T,m)}},keyboardTarget:u=>{let g=e.id;for(;c.has(a.parents.get(g)??"");)g=a.parents.get(g);let y=a.siblings.get(a.parents.get(g)??null)??[],m=y.indexOf(g)+u;for(;m>=0&&m<y.length;){let T=y[m];if(!w(T)&&A.has(T)&&s.has(T))return s.get(T);m+=u}}}}var ee=class{constructor(e){this.host=e;this.drag=null;this.r=0;this.n=0;this.a=e=>{let t=this.drag;if(!(!t||e.pointerId!==t.pointerId)){if(t.clientX=e.clientX,t.clientY=e.clientY,!t.active){if(Math.abs(e.clientY-t.startY)<5)return;t.active=!0,this.host.root.classList.add("mach-root--row-dragging"),this.host.root.querySelectorAll(".mach-row").forEach(n=>n.classList.toggle("mach-row--drag-source",this.sourceContains(n.dataset.id??"")))}this.c()}};this.f=()=>{if(this.r=0,!!this.drag?.active){if(!this.current()){this.destroy();return}this.u(),this.m()&&this.c()}};this.l=e=>{let t=this.drag;if(!(!t||e.pointerId!==t.pointerId)){t.clientX=e.clientX,t.clientY=e.clientY,t.active&&this.current()&&this.u(),this.p();try{t.active&&t.drop?.valid&&this.i(e.clientX,e.clientY)&&this.current()&&this.commitDrop(t.drop)}finally{this.release()}}};this.d=e=>{e.key==="Escape"&&(e.preventDefault(),this.destroy())};this.o=e=>{e.type==="pointercancel"&&e.pointerId!==this.drag?.pointerId||this.destroy()}}begin(e){let t=this.host.containers.map(o=>{let i=le("div","mach-row-drop-indicator");return i.hidden=!0,o.append(i),i}),n=le("div","mach-row-drag-preview");n.setAttribute("role","status"),n.hidden=!0,this.host.root.append(n),this.drag={startY:e.clientY,clientX:e.clientX,clientY:e.clientY,pointerId:e.pointerId,indicators:t,preview:n,drop:null,active:!1},window.addEventListener("pointermove",this.a),window.addEventListener("pointerup",this.l),window.addEventListener("pointercancel",this.o),window.addEventListener("keydown",this.d),window.addEventListener("blur",this.o)}w(e){return this.drag?.active===!0&&this.sourceContains(e)}g(e,t=()=>!0){this.n=requestAnimationFrame(()=>{this.n=0,t()&&[...this.host.root.querySelectorAll(".mach-row-drag-handle")].find(n=>n.closest(".mach-row")?.dataset.id===e)?.focus()})}c(){this.r||(this.r=requestAnimationFrame(this.f))}i(e,t,n=0){let o=this.host.body.getBoundingClientRect();return e>=o.left&&e<=o.right&&t>=o.top-n&&t<=o.bottom+n}m(){let e=this.drag;if(!e||!this.i(e.clientX,e.clientY,28))return!1;let t=this.host.viewport,n=t.getBoundingClientRect(),o=Math.min(36,n.height/3);if(o<=0)return!1;let i=e.clientY<n.top+o?-Math.ceil(14*C((n.top+o-e.clientY)/o,0,1)):Math.ceil(14*C((e.clientY-n.bottom+o)/o,0,1));if(this.host.scrollBy)return this.host.scrollBy(i);let s=t.scrollTop;return t.scrollTop=C(s+i,0,Math.max(0,t.scrollHeight-t.clientHeight)),t.scrollTop!==s}u(){let e=this.drag;if(!e?.active)return;let t=e.clientY-this.host.viewport.getBoundingClientRect().top+this.host.viewport.scrollTop,n=this.describe(t);e.drop=n;let o=this.i(e.clientX,e.clientY);for(let s of e.indicators){if(s.hidden=!o||!n?.valid,!n)continue;s.dataset.dropPosition=n.position??"",s.style.cssText=n.style??"";let a=parseFloat(s.parentElement.style.height),c=Math.min(this.host.getRowTop(n.boundary),Number.isFinite(a)?Math.max(0,a-2):1/0);s.style.transform=`translate3d(0, ${c}px, 0)`}let i=this.host.root.getBoundingClientRect();e.preview.hidden=!1,e.preview.textContent=o?n?.text??this.outsideText():this.outsideText(),e.preview.style.transform=`translate3d(${C(e.clientX-i.left+16,8,Math.max(8,i.width-224))}px, ${C(e.clientY-i.top+16,8,Math.max(8,i.height-48))}px, 0)`}p(){let e=this.drag;this.drag=null,window.removeEventListener("pointermove",this.a),window.removeEventListener("pointerup",this.l),window.removeEventListener("pointercancel",this.o),window.removeEventListener("keydown",this.d),window.removeEventListener("blur",this.o),cancelAnimationFrame(this.r),this.r=0,this.host.root?.classList.remove("mach-root--row-dragging"),this.host.root?.querySelectorAll(".mach-row--drag-source").forEach(t=>t.classList.remove("mach-row--drag-source")),e?.indicators.forEach(t=>t.remove()),e?.preview.remove()}destroy(){this.p(),this.release(),cancelAnimationFrame(this.n),this.n=0}};var te=class extends ee{constructor(t,n,o){super(t);this.e=t;this.prepare=n;this.y=o;this.scope=null;this.s=!1}t(t,n,o){try{return n()}catch(i){return this.scope&&(this.scope.failed=!0),this.e.report(i,t),o}}h(t){return this.t("prepare",()=>{let n=this.e.capture(t),o=this.prepare(t);return this.scope={node:t,from:t.rowIndex,guard:n,session:o,sourceDecision:!0,failed:!1},this.scope.sourceDecision=o.validate(),this.scope},null)}start(t,n){this.destroy(),this.h(n)&&this.current()&&this.begin(t)}moveWithKeyboard(t,n){this.destroy();let o=this.h(n);if(!(!o||!this.current())){this.s=!0;try{let i=t.key==="ArrowUp"?-1:1,s=this.t("keyboardTarget",()=>o.session.keyboardTarget(i),void 0);s&&this.commitDrop(this.destination(s,i<0?0:1))}finally{this.s=!1,this.release()}}}isSource(t){return this.w(t.id)}current(){return!!(this.scope&&!this.scope.failed&&this.scope.guard.current()&&this.e.api.rows.getById(this.scope.node.id)===this.scope.node)}sourceContains(t){return this.t("isSource",()=>this.scope?.session.isSource(t)??!1,!1)}release(){this.scope=null}outsideText(){return this.e.api.getOption("locale")?.rowDragOutside??"\u79FB\u56DE\u8868\u683C\u5185\u653E\u7F6E \xB7 Esc \u53D6\u6D88"}describe(t){let n=this.e.api,o=C(this.host.findRowAt(t),0,n.rows.getCount()-1),i=n.rows.getAt(o);if(i?.isDetail&&(i=n.rows.getById(i.masterId)),!i)return null;let s=this.host.getRowTop(i.rowIndex),a=this.host.getRowTop(i.rowIndex+1)-s;return this.destination(i,(t-s)/Math.max(1,a))}destination(t,n){let o=this.scope,i=n<.5?"before":"after",s=this.host.getRowTop(t.rowIndex+1)-this.host.getRowTop(t.rowIndex),a=this.t("resolve",()=>o.session.resolve({targetNode:t,position:i,fraction:n,height:s}),!1),c=typeof o.sourceDecision=="string"?o.sourceDecision:typeof a=="string"?a:"\u6B64\u4F4D\u7F6E\u4E0D\u53EF\u653E\u7F6E",l={node:t,fraction:n,boundary:t.rowIndex,valid:!1,text:c};if(!a||typeof a=="string"||o.sourceDecision!==!0||t.loading||t.treeLoading||t.isGroup)return l;l.intent=a.intent,l.position=a.intent.position,l.toIndex=a.toIndex,l.targetIndex=a.targetIndex,l.boundary=a.indicatorIndex??t.rowIndex+ +(a.intent.position==="after"),l.style=a.indicatorStyle,l.text=a.text??c;let w=this.t("canDrop",()=>this.e.api.getOption("rowDragPolicy")?.canDrop?.({node:o.node,api:this.e.api,targetNode:t,intent:a.intent})??!0,!1);return l.valid=w===!0,typeof w=="string"&&(l.text=w),l}commitDrop(t){let n=this.scope;if(!n||!this.current()||this.t("validate",()=>n.session.validate(),!1)!==!0||!this.current())return!1;let o=this.destination(t.node,t.fraction);return!o.valid||!o.intent||!this.current()?!1:(this.s&&this.y(o.intent,i=>this.g(n.node.id,i)),this.e.emit(n.node,n.from,o.toIndex,o.targetIndex,o.intent),!0)}};function $(r,e,t){let n=[],o=[...r].reverse().map(s=>({row:s,parent:null})),i=new Set;for(;o.length;){let s=o.pop();if(i.has(s.row))throw new Error("[MachTable] Installed order contains duplicate or cyclic rows.");i.add(s.row),n.push(s);let a=t?s.row[e]??[]:[];for(let c=a.length-1;c>=0;c--)o.push({row:a[c],parent:s.row})}return n}function H(r,e,t,n){try{let o=$(r,t,n);return o.length===e.length&&o.every((i,s)=>i.row===e[s].row&&i.parent===e[s].parent)}catch{return!1}}function he(r){let e=[];return r?.rows.forEach(t=>e.push({node:t,data:t.data})),e}function W(r,e){if(!r)return!0;if(r.isDestroyed())return!1;let t=0,n=!0;return r.rows.forEach(o=>{let i=e[t++];(i?.node!==o||i.data!==o.data)&&(n=!1)}),n&&t===e.length}var re=class{constructor(){this.entries=[];this.cursor=0}get canUndo(){return this.cursor>0}get canRedo(){return this.cursor<this.entries.length}peek(e){return this.entries[e==="undo"?this.cursor-1:this.cursor]}commit(e,t){e==="undo"?this.cursor--:e==="redo"?this.cursor++:(this.entries.splice(this.cursor),this.entries.push(t),this.entries.length>50&&this.entries.shift(),this.cursor=this.entries.length)}clear(){this.entries=[],this.cursor=0}};var L=class extends Error{constructor(t="The row order changed on the server. Reload before trying again.",n){super(t);this.serverRevision=n;this.name="RowOrderConflictError"}};function rt(r){if(r?.status==="conflict")throw new L(r.message,r.revision);return r?.revision}function Ae(r){if(r.targetId===null)throw new Error("[MachTable] Row ordering requires an existing destination.");return{...r,targetId:r.targetId}}function Me(r){let e={status:"idle",error:null,revision:r.getRevision?.(),plan:null,canUndo:!1,canRedo:!1},t=0,n=!1,o=null,i=null,s=null,a=()=>{},c=()=>{},l=0,w=null,f=new re,O=null,S=new Set,A=r.childrenKey??"children",x=null,E=()=>{f.clear(),O=null},q=()=>{if(!o)return!1;let d=o;return t++,o=null,i=null,d.abort(),!0},u=(d=e.status)=>({canUndo:!n&&d!=="saving"&&f.canUndo,canRedo:!n&&d!=="saving"&&f.canRedo}),g=d=>{e=Object.freeze({...d,...u(d.status)}),s&&!s.isDestroyed()&&s.view.refreshCells();let p=[h=>r.onStateChange?.(h),...S];for(let h of p)try{h?.(e)}catch(v){console.error("[MachTable] Row order state observer failed",v)}},y=()=>r.getRevision?.()??e.revision,m=(d=w)=>{d?.release(),w===d&&(w=null)},T=()=>{!i||i()||(q(),E(),m(),g({...e,status:"idle",plan:null,error:null}))},k=d=>new te(d,p=>Se(d.api,p,r.getRows(),r,r.treeData===!0,y()),(p,h)=>{m();let v=document.activeElement,R=G=>{G.target!==v&&G.target!==document.body&&m(b)},b={api:d.api,intent:p,restore:h,generation:t+1,release:()=>document.removeEventListener("focusin",R,!0)};w=b,document.addEventListener("focusin",R,!0)}),M=()=>{T(),!o&&O&&(O.api!==s||O.revision!==y()||!W(s,O.nodes)||!H(r.getRows(),O.rows,A,r.treeData===!0))&&E();let d=u();(e.canUndo!==d.canUndo||e.canRedo!==d.canRedo)&&(e=Object.freeze({...e,...d}))},B=d=>{if(d===s){T(),ue(d,k)||(c(),c=pe(d,k));return}let p=q();a(),c(),m(),E(),s=d,c=pe(d,k),a=d.on("cellValueChanged",()=>{l++;let h=f.canUndo||f.canRedo;E(),h&&g({...e,status:o?"saving":"idle",plan:o?e.plan:null,error:null})}),p&&g({...e,status:"idle",plan:null,error:null})},N=d=>{if(M(),n)throw new Error("[MachTable] The row order controller is disposed.");if(o)throw new Error("[MachTable] A row order save is already in progress.");let p=y();if(p!==void 0&&d.expectedRevision!==void 0&&d.expectedRevision!==p)throw new L;let h={...d,expectedRevision:d.expectedRevision??p};return(r.treeData?Q:J)(r.getRows(),h,r)},z=async(d,p,h,v,R)=>{if(!d.changed)return d;let b=s;if(b&&!Z(b))throw new Error("[MachTable] Save or discard edited rows before changing their order.");let G=++t;x=null;let j=new AbortController;o=j,i=null;let X=y(),ke=l,F=null,K=[],me=!1,ne=!1,oe=X,ve=I=>{if(!R)return;if(!I||R!==w||R.api!==s){m(R);return}let D=O;R.restore(()=>{let se=D!==null&&D===O&&D.revision===y()&&W(R.api,D.nodes)&&H(r.getRows(),D.rows,A,r.treeData===!0)&&w===R&&!n&&t===R.generation&&s===R.api&&ue(R.api,k);return m(R),se})},P=()=>!n&&t===G,ie=()=>P()&&(!b||s===b&&!b.isDestroyed())&&F!==null&&y()===X&&W(b,K)&&H(r.getRows(),F,A,r.treeData===!0),Ne=I=>{if(!ie()){P()&&!F&&g({...e,status:"error",error:I,plan:d});return}let D=!b||Z(b),U=D?I:Object.assign(new Error("[MachTable] Row order could not be saved. Automatic rollback was skipped to preserve new edits. Save or discard those edits, then reload the row order."),{cause:I});if(D){i=null;try{r.applyRows(d.before),ne=!0}catch(se){U=Object.assign(new Error("[MachTable] Row order could not be saved or restored. Reload the row order before trying again."),{cause:I,rollbackError:se})}}P()&&(ne||E(),g({...e,status:I instanceof L?"conflict":"error",error:U}))},Ge=()=>{if(!P()){ve(!1);return}let I=y(),D=!1;me&&P()&&(I===X||I===oe)&&W(b,K)&&H(r.getRows(),F,A,r.treeData===!0)?(O={rows:F,nodes:K,api:b,revision:I},D=!0):ne&&P()?(O={rows:$(r.getRows(),A,r.treeData===!0),nodes:he(b),api:b,revision:I},D=H(r.getRows(),$(d.before,A,r.treeData===!0),A,r.treeData===!0)):E(),o===j&&(o=null,i=null,s&&!s.isDestroyed()&&s.view.refreshCells()),P()&&e.status==="saving"&&g({...e,status:"idle",plan:null}),M(),ve(D)};try{r.applyRows(d.after),F=$(r.getRows(),A,r.treeData===!0),K=he(b);let I=r.getRows(),D=K[0]?.node;if(i=b&&D?()=>!b.isDestroyed()&&b.rows.getById(D.id)===D:()=>r.getRows()===I,g({...e,status:"saving",error:null,plan:d}),!ie())return d;let U=rt(await xe(Promise.resolve(r.save?.(d.intent,{signal:j.signal,plan:d,operation:p,operations:h})),j.signal));return ie()&&(me=!0,oe=U??X,l===ke?f.commit(p,v):E(),g({...e,status:"saved",revision:oe})),d}catch(I){throw Ne(I),I}finally{Ge()}},ge=async(d,p)=>{p!==w&&(p=void 0),w!==p&&m();let h=N(d);h.changed||m(p);let v=h.changed?Ie(h,r,r.treeData===!0):[];return z(h,"move",[h.intent],{plan:h,inverse:v},p)},Ce=d=>ge(d),fe=async d=>{if(m(),M(),n||o)throw new Error("[MachTable] Row ordering is unavailable while disposed or saving.");let p=f.peek(d);if(!p)throw new Error(`[MachTable] Nothing to ${d}.`);let h=(d==="undo"?p.inverse:[p.plan.intent]).map(G=>({...G,expectedRevision:y()})),v=r.getRows(),R=d==="undo"?p.plan.before:p.plan.after;De(v,R,h,r,r.treeData===!0);let b={before:v,after:R,intent:h[0],rowIds:p.plan.rowIds,changed:!0};return z(b,d,h,p)},Le=d=>{try{if(n||o)return!1;let p=r.getRows(),h=y();if(h!==void 0&&d.expectedRevision!==void 0&&d.expectedRevision!==h)return!1;let v=x?.rowIds===d.rowIds?x.sources:JSON.stringify(d.rowIds.map(String));return(!x||x.rows!==p||x.revision!==h||x.sources!==v)&&(x={rows:p,revision:h,sources:v,rowIds:d.rowIds,validate:Te(p,d.rowIds,r,r.treeData===!0)}),x.rowIds=d.rowIds,x.validate(d),!0}catch(p){return p instanceof Error?p.message:!1}},Pe=d=>{let p=d.intent;if(d.applied||!p)return;B(d.api);let h=t,v=w?.intent===p?w:void 0;Promise.resolve().then(()=>ge(Ae(p),v)).catch(R=>{v&&v.generation!==t&&m(v),!n&&t===h&&e.status!=="saving"&&g({...e,status:R instanceof L?"conflict":"error",error:R})})},ye=d=>n?!1:(B(d),o?"Wait for the current row order to finish saving.":Z(d)||"Save or discard edited rows before changing their order.");return{get state(){return M(),e},bindings:{applyRowDrag:!1,rowDragPolicy:{canDrag:({api:d})=>ye(d),canDrop:({intent:d,api:p})=>{let h=ye(p);if(h!==!0)return h;try{return Le(Ae(d))}catch(v){return v instanceof Error?v.message:!1}},getRevision:y},onRowDragEnd:Pe},preview:N,move:Ce,undo:()=>fe("undo"),redo:()=>fe("redo"),subscribe(d){return n?()=>{}:(S.add(d),()=>{S.delete(d)})},dispose(){n=!0,t++,o?.abort(),o=null,i=null,a(),c(),m(),E(),s&&!s.isDestroyed()&&s.view.refreshCells(),s=null,x=null,S.clear(),e=Object.freeze({...e,status:"idle",error:null,plan:null,canUndo:!1,canRedo:!1})}}}0&&(module.exports={RowOrderConflictError,createRowOrderController,moveTreeNodes,reorderRows});
@@ -1,4 +1,4 @@
1
- import { c as GridOptions } from './api-pOhyuSQk.cjs';
1
+ import { c as GridOptions } from './api-CZkd8tYy.cjs';
2
2
 
3
3
  /** Persist relative business IDs instead of viewport indexes or fractional ranks. */
4
4
  interface RowOrderIntent {
@@ -1,4 +1,4 @@
1
- import { c as GridOptions } from './api-pOhyuSQk.js';
1
+ import { c as GridOptions } from './api-CZkd8tYy.js';
2
2
 
3
3
  /** Persist relative business IDs instead of viewport indexes or fractional ranks. */
4
4
  interface RowOrderIntent {
package/dist/ordering.js CHANGED
@@ -1 +1 @@
1
- var ke=new Set(["__proto__","prototype","constructor"]);function Ge(r){return typeof r!="string"||r.length===0?!1:r.split(".").every(t=>t.length>0&&!ke.has(t))}function j(r,e){if(r==null||!Ge(e))return;if(e.indexOf(".")<0)return r[e];let n=r,o=0;for(;o<e.length;){if(n==null)return;let i=e.indexOf(".",o);if(i<0){n=n[e.slice(o)];break}n=n[e.slice(o,i)],o=i+1}return n}function Ne(r,e){let t=typeof e.rowKey=="function"?e.rowKey(r):j(r,e.rowKey);if(t==null||String(t).length===0)throw new Error("[MachTable] Row ordering requires a non-empty stable row key.");return String(t)}function Fe(r,e){let t=r[e];if(t==null)return[];if(!Array.isArray(t))throw new Error(`[MachTable] Tree ordering expects an array at "${e}".`);return t}function K(r,e,t,n){let o={entries:[],byId:new Map,byRow:new Map,children:new Map([[null,r]])},i=[...r].reverse().map(d=>({row:d,parentId:null,selectedAncestor:!1})),a=t.childrenKey??"children";for(;i.length;){let d=i.pop(),c=Ne(d.row,t);if(o.byId.has(c))throw new Error(`[MachTable] Row ordering found duplicate or cyclic row key "${c}".`);let l=n?Fe(d.row,a):[],h={...d,id:c,children:l};o.entries.push(h),o.byId.set(c,h),o.byRow.set(h.row,h),o.children.set(c,l);for(let f=l.length-1;f>=0;f--)i.push({row:l[f],parentId:c,selectedAncestor:d.selectedAncestor||e.has(c)})}return o}function He(r){if(!["before","after","inside"].includes(r.position))throw new Error("[MachTable] Unknown row ordering position.");let e=[...new Set(r.rowIds.map(String))];if(!e.length)throw new Error("[MachTable] Row ordering requires at least one source row.");return{...r,rowIds:e,targetId:String(r.targetId)}}function ne(r,e){for(let n of e)if(!r.byId.has(n))throw new Error(`[MachTable] Ordering source "${n}" is unavailable.`);let t=new Set(e);return{selected:t,moved:r.entries.filter(n=>t.has(n.id)&&!n.selectedAncestor)}}function ve(r,e,t,n){let o=r.byId.get(t.targetId);if(!o)throw new Error(`[MachTable] Ordering target "${t.targetId}" is unavailable.`);if(e.selected.has(o.id)||o.selectedAncestor)throw new Error("[MachTable] A row cannot be moved into or relative to its own subtree.");let i=t.position==="inside"?o.id:o.parentId,a=i===null?null:r.byId.get(i).row;if(n.canMove)for(let d of e.moved){let c=d.parentId===null?null:r.byId.get(d.parentId).row,l=n.canMove({row:d.row,previousParent:c,parent:a,target:o.row,intent:t});if(l===!1||typeof l=="string")throw new Error(typeof l=="string"?l:"[MachTable] This row cannot be moved to the selected parent.")}return i}function be(r,e,t,n){let o=[...new Set(e.map(String))];if(!o.length)throw new Error("[MachTable] Row ordering requires at least one source row.");let i=K(r,new Set(o),t,n),a=ne(i,o);return d=>{if(!n&&d.position==="inside")throw new Error("[MachTable] Flat rows cannot have child destinations.");ve(i,a,d,t)}}function qe(r,e,t,n){let o=new Set(e.map(l=>l.id)),i=new Map;for(let l of e)i.has(l.parentId)||i.set(l.parentId,r.children.get(l.parentId).filter(h=>!o.has(r.byRow.get(h).id)));let a=i.get(t)??r.children.get(t),d=a.findIndex(l=>l===r.byId.get(n.targetId).row),c=n.position==="inside"?a.length:d+ +(n.position==="after");return i.set(t,[...a.slice(0,c),...e.map(l=>l.row),...a.slice(c)]),i}function me(r,e){return r.length===e.length&&r.every((t,n)=>t===e[n])}function Be(r,e,t,n){let o=new Map,i=n.childrenKey??"children";for(let d=e.entries.length-1;d>=0;d--){let c=e.entries[d],h=(t.get(c.id)??c.children).map(f=>o.get(f)??f);me(c.children,h)||o.set(c.row,{...c.row,[i]:h})}let a=(t.get(null)??r).map(d=>o.get(d)??d);return me(r,a)?r:a}function Ke(r,e,t,n){let o=t.indexOf(e[0].row),i=o+e.length;return{...r,rowIds:e.map(a=>a.id),beforeId:o>0?n.byRow.get(t[o-1]).id:null,afterId:i<t.length?n.byRow.get(t[i]).id:null}}function Re(r,e,t){let n=K(r.before,new Set(r.rowIds),e,t),o=new Map;for(let i of n.children.values())i.forEach((a,d)=>o.set(n.byRow.get(a).id,d));return ne(n,r.rowIds).moved.reverse().map(i=>{let a=n.children.get(i.parentId),d=o.get(i.id),c=a[d+1];if(c)return{rowIds:[i.id],targetId:n.byRow.get(c).id,position:"before"};if(i.parentId!==null)return{rowIds:[i.id],targetId:i.parentId,position:"inside"};let l=a[d-1];if(!l)throw new Error("[MachTable] Row ordering cannot restore an isolated root.");return{rowIds:[i.id],targetId:n.byRow.get(l).id,position:"after"}})}function Te(r,e,t,n,o){if(!n.canMove)return;let i=K(r,new Set,n,o),a=K(e,new Set,n,o);for(let d of t)for(let c of d.rowIds){let l=i.byId.get(c),h=a.byId.get(c),f=h.parentId===null?null:i.byId.get(h.parentId).row,x=l.parentId===null?null:i.byId.get(l.parentId).row,E=n.canMove({row:l.row,previousParent:x,parent:f,target:i.byId.get(d.targetId).row,intent:d});if(E===!1||typeof E=="string")throw new Error(typeof E=="string"?E:"[MachTable] This row cannot be restored to its previous parent.")}}function Ie(r,e,t,n){let o=He(e);if(!n&&o.position==="inside")throw new Error("[MachTable] Flat rows cannot have child destinations.");let i=K(r,new Set(o.rowIds),t,n),{moved:a,selected:d}=ne(i,o.rowIds),c=ve(i,{moved:a,selected:d},o,t),l=qe(i,a,c,o),h=Be(r,i,l,t),f=Ke(o,a,l.get(c),i);return{before:r,after:h,intent:f,rowIds:f.rowIds,changed:r!==h}}function oe(r,e,t){return Ie(r,e,t,!1)}function ie(r,e,t){return Ie(r,e,t,!0)}function ae(r,e,t){let n=document.createElement(r);if(e&&(n.className=e),t)for(let o of Object.keys(t))n.setAttribute(o,t[o]);return n}function M(r,e,t){return r<e?e:r>t?t:r}var se=Symbol.for("mach-table.adapter.lifecycle.v1");function X(r){return!r.isDestroyed()&&(r[se]?.canReplaceData()??!1)}function de(r,e){let t=r[se]?.rowDrag;return t?.original===e&&t.policy===r.getOption("rowDragPolicy")}function le(r,e){let t=r[se];if(!t)return()=>{};t.rowDrag?.activeInteraction?.destroy();let n={original:e,policy:r.getOption("rowDragPolicy"),factory:o=>(n.activeInteraction=e(o),n.activeInteraction)};return t.rowDrag=n,()=>{n.activeInteraction?.destroy(),t.rowDrag===n&&(t.rowDrag=void 0)}}function De(r,e){return new Promise((t,n)=>{let o=()=>n(Object.assign(new Error("[MachTable] Operation cancelled."),{name:"AbortError"}));if(r.then(t,n).finally(()=>e.removeEventListener("abort",o)),e.aborted){o();return}e.addEventListener("abort",o,{once:!0})})}function ce(r,e,t){return r.replace("{a}",String(e)).replace("{b}",String(t))}function Ue(r,e,t){return r&&e>.25&&e<.75?"inside":t}function Oe(r,e){let t=0,n=r.length;for(;t<n;){let o=t+n>>>1;r[o]<e?t=o+1:n=o}return t}function Ye(r,e,t,n,o,i){let a=r.getOption("locale")??{},d=e>1?ce(a.rowDragSelection??"\u5DF2\u9009 {a} \u884C \u2192 \u7B2C {b} \u884C",e,n+1):ce(a.rowDragPosition??"\u7B2C {a} \u884C \u2192 \u7B2C {b} \u884C",t+1,n+1),c=o==="inside"?a.rowDragInside??"\u79FB\u5165":o==="before"?a.rowDragBefore??"\u4E4B\u524D":a.rowDragAfter??"\u4E4B\u540E";return{text:`${d} \xB7 ${c}`,indicatorStyle:o==="inside"?`height:${i}px;background:color-mix(in srgb,var(--mach-primary) 12%,transparent);box-shadow:inset 0 0 0 1px var(--mach-primary)`:void 0}}function _e(r,e,t){let n={parents:new Map,siblings:new Map([[null,[]]]),depths:new Map},o=[...r].reverse().map(a=>({row:a,parent:null,depth:0})),i=e.childrenKey??"children";for(;o.length;){let{row:a,parent:d,depth:c}=o.pop(),l=String(typeof e.rowKey=="function"?e.rowKey(a):j(a,e.rowKey));if(n.depths.has(l))throw new Error("[MachTable] Row ordering requires unique, acyclic row keys.");n.depths.set(l,c),n.siblings.get(d).push(l),n.siblings.set(l,[]),d!==null&&n.parents.set(l,d);let h=t?a[i]:void 0;if(h!=null&&!Array.isArray(h))throw new Error("[MachTable] Row ordering children must be an array.");for(let f=(h?.length??0)-1;f>=0;f--)o.push({row:h[f],parent:l,depth:c+1})}return n}function xe(r,e,t,n,o,i){let a=new Map;r.rows.forEach(u=>{!u.loading&&!u.isDetail&&!u.isGroup&&u.data!=null&&a.set(u.id,u)});let d=_e(t,n,o),c=new Set(e.selected?[...d.depths.keys()].filter(u=>a.get(u)?.selected):[e.id]),l=[...c],h=u=>{let y=u;for(;y!==void 0;){if(c.has(y))return!0;y=d.parents.get(y)}return!1},f=new Map,x=new Map;for(let[u,y]of d.siblings){let m=y.filter(v=>!c.has(v));f.set(u,m),m.forEach((v,g)=>x.set(v,g))}let E=new Map,S=[],I=[],A=0;r.rows.forEachDisplayed(u=>{h(u.id)&&S.push(u.rowIndex),A=u.rowIndex+1;let y=d.depths.get(u.id)??0;for(;I.length&&(d.depths.get(I[I.length-1].id)??0)>=y;)E.set(I.pop().id,u.rowIndex);d.siblings.get(u.id)?.length&&I.push(u)});for(let u of I)E.set(u.id,A);return{rowIds:l,isSource:h,validate:()=>{for(let u of l){let y=a.get(u);if(y.treeLoading)return!1;let m=r.getOption("rowDragPolicy")?.canDrag?.({node:y,api:r});if(m===!1||typeof m=="string")return m}return!0},resolve:({targetNode:u,position:y,fraction:m,height:v})=>{let g=Ue(o,m,y);if(h(u.id))return"Cannot target own subtree.";if(!o&&g==="inside")return!1;let _=g==="inside"?u.id:d.parents.get(u.id)??null,C=f.get(_)??[],P=g==="inside"?C.length:(x.get(u.id)??0)+ +(g==="after"),G=g==="before"?u.rowIndex:E.get(u.id)??u.rowIndex+1,z=G-Oe(S,G)+Oe(S,e.rowIndex);return{intent:{rowIds:l,targetId:u.id,position:g,beforeId:C[P-1]??null,afterId:C[P]??null,expectedRevision:i},indicatorIndex:g==="inside"?u.rowIndex:g==="after"?E.get(u.id):void 0,toIndex:G,targetIndex:z,...Ye(r,l.length,e.rowIndex,u.rowIndex,g,v)}},keyboardTarget:u=>{let y=e.id;for(;c.has(d.parents.get(y)??"");)y=d.parents.get(y);let m=d.siblings.get(d.parents.get(y)??null)??[],v=m.indexOf(y)+u;for(;v>=0&&v<m.length;){let g=m[v];if(!h(g)&&a.has(g))return a.get(g);v+=u}}}}var V=class{constructor(e){this.host=e;this.drag=null;this.t=0;this.r=0;this.s=e=>{let t=this.drag;if(!(!t||e.pointerId!==t.pointerId)){if(t.clientX=e.clientX,t.clientY=e.clientY,!t.active){if(Math.abs(e.clientY-t.startY)<5)return;t.active=!0,this.host.root.classList.add("mach-root--row-dragging"),this.host.root.querySelectorAll(".mach-row").forEach(n=>n.classList.toggle("mach-row--drag-source",this.sourceContains(n.dataset.id??"")))}this.d()}};this.h=()=>{if(this.t=0,!!this.drag?.active){if(!this.current()){this.destroy();return}this.c(),this.g()&&this.d()}};this.a=e=>{let t=this.drag;if(!(!t||e.pointerId!==t.pointerId)){t.clientX=e.clientX,t.clientY=e.clientY,t.active&&this.current()&&this.c(),this.u();try{t.active&&t.drop?.valid&&this.o(e.clientX,e.clientY)&&this.current()&&this.commitDrop(t.drop)}finally{this.release()}}};this.l=e=>{e.key==="Escape"&&(e.preventDefault(),this.destroy())};this.n=e=>{e.type==="pointercancel"&&e.pointerId!==this.drag?.pointerId||this.destroy()}}begin(e){let t=this.host.containers.map(o=>{let i=ae("div","mach-row-drop-indicator");return i.hidden=!0,o.append(i),i}),n=ae("div","mach-row-drag-preview");n.setAttribute("role","status"),n.hidden=!0,this.host.root.append(n),this.drag={startY:e.clientY,clientX:e.clientX,clientY:e.clientY,pointerId:e.pointerId,indicators:t,preview:n,drop:null,active:!1},window.addEventListener("pointermove",this.s),window.addEventListener("pointerup",this.a),window.addEventListener("pointercancel",this.n),window.addEventListener("keydown",this.l),window.addEventListener("blur",this.n)}draggingSource(e){return this.drag?.active===!0&&this.sourceContains(e)}focusHandle(e,t=()=>!0){this.r=requestAnimationFrame(()=>{this.r=0,t()&&[...this.host.root.querySelectorAll(".mach-row-drag-handle")].find(n=>n.closest(".mach-row")?.dataset.id===e)?.focus()})}d(){this.t||(this.t=requestAnimationFrame(this.h))}o(e,t,n=0){let o=this.host.body.getBoundingClientRect();return e>=o.left&&e<=o.right&&t>=o.top-n&&t<=o.bottom+n}g(){let e=this.drag;if(!e||!this.o(e.clientX,e.clientY,28))return!1;let t=this.host.viewport,n=t.getBoundingClientRect(),o=Math.min(36,n.height/3);if(o<=0)return!1;let i=e.clientY<n.top+o?-Math.ceil(14*M((n.top+o-e.clientY)/o,0,1)):Math.ceil(14*M((e.clientY-n.bottom+o)/o,0,1)),a=t.scrollTop;return t.scrollTop=M(a+i,0,Math.max(0,t.scrollHeight-t.clientHeight)),t.scrollTop!==a}c(){let e=this.drag;if(!e?.active)return;let t=e.clientY-this.host.viewport.getBoundingClientRect().top+this.host.viewport.scrollTop,n=this.describe(t);e.drop=n;let o=this.o(e.clientX,e.clientY);for(let a of e.indicators)a.hidden=!o||!n?.valid,n&&(a.dataset.dropPosition=n.position??"",a.style.cssText=n.style??"",a.style.transform=`translate3d(0, ${this.host.getRowTop(n.boundary)}px, 0)`);let i=this.host.root.getBoundingClientRect();e.preview.hidden=!1,e.preview.textContent=o?n?.text??this.outsideText():this.outsideText(),e.preview.style.transform=`translate3d(${M(e.clientX-i.left+16,8,Math.max(8,i.width-224))}px, ${M(e.clientY-i.top+16,8,Math.max(8,i.height-48))}px, 0)`}u(){let e=this.drag;this.drag=null,window.removeEventListener("pointermove",this.s),window.removeEventListener("pointerup",this.a),window.removeEventListener("pointercancel",this.n),window.removeEventListener("keydown",this.l),window.removeEventListener("blur",this.n),cancelAnimationFrame(this.t),this.t=0,this.host.root?.classList.remove("mach-root--row-dragging"),this.host.root?.querySelectorAll(".mach-row--drag-source").forEach(t=>t.classList.remove("mach-row--drag-source")),e?.indicators.forEach(t=>t.remove()),e?.preview.remove()}destroy(){this.u(),this.release(),cancelAnimationFrame(this.r),this.r=0}};var J=class extends V{constructor(t,n,o){super(t);this.bridge=t;this.prepare=n;this.requestFocus=o;this.scope=null;this.i=!1}e(t,n,o){try{return n()}catch(i){return this.scope&&(this.scope.failed=!0),this.bridge.report(i,t),o}}p(t){return this.e("prepare",()=>{let n=this.bridge.capture(t),o=this.prepare(t);return this.scope={node:t,from:t.rowIndex,guard:n,session:o,sourceDecision:!0,failed:!1},this.scope.sourceDecision=o.validate(),this.scope},null)}start(t,n){this.destroy(),this.p(n)&&this.current()&&this.begin(t)}moveWithKeyboard(t,n){this.destroy();let o=this.p(n);if(!(!o||!this.current())){this.i=!0;try{let i=t.key==="ArrowUp"?-1:1,a=this.e("keyboardTarget",()=>o.session.keyboardTarget(i),void 0);a&&this.commitDrop(this.destination(a,i<0?0:1))}finally{this.i=!1,this.release()}}}isSource(t){return this.draggingSource(t.id)}current(){return!!(this.scope&&!this.scope.failed&&this.scope.guard.current()&&this.bridge.api.rows.getById(this.scope.node.id)===this.scope.node)}sourceContains(t){return this.e("isSource",()=>this.scope?.session.isSource(t)??!1,!1)}release(){this.scope=null}outsideText(){return this.bridge.api.getOption("locale")?.rowDragOutside??"\u79FB\u56DE\u8868\u683C\u5185\u653E\u7F6E \xB7 Esc \u53D6\u6D88"}describe(t){let n=this.bridge.api,o=M(this.host.findRowAt(t),0,n.rows.getCount()-1),i=n.rows.getAt(o);if(i?.isDetail&&(i=n.rows.getById(i.masterId)),!i)return null;let a=this.host.getRowTop(i.rowIndex),d=this.host.getRowTop(i.rowIndex+1)-a;return this.destination(i,(t-a)/Math.max(1,d))}destination(t,n){let o=this.scope,i=n<.5?"before":"after",a=this.host.getRowTop(t.rowIndex+1)-this.host.getRowTop(t.rowIndex),d=this.e("resolve",()=>o.session.resolve({targetNode:t,position:i,fraction:n,height:a}),!1),c=typeof o.sourceDecision=="string"?o.sourceDecision:typeof d=="string"?d:"\u6B64\u4F4D\u7F6E\u4E0D\u53EF\u653E\u7F6E",l={node:t,fraction:n,boundary:t.rowIndex,valid:!1,text:c};if(!d||typeof d=="string"||o.sourceDecision!==!0||t.loading||t.treeLoading||t.isGroup)return l;l.intent=d.intent,l.position=d.intent.position,l.toIndex=d.toIndex,l.targetIndex=d.targetIndex,l.boundary=d.indicatorIndex??t.rowIndex+ +(d.intent.position==="after"),l.style=d.indicatorStyle,l.text=d.text??c;let h=this.e("canDrop",()=>this.bridge.api.getOption("rowDragPolicy")?.canDrop?.({node:o.node,api:this.bridge.api,targetNode:t,intent:d.intent})??!0,!1);return l.valid=h===!0,typeof h=="string"&&(l.text=h),l}commitDrop(t){let n=this.scope;if(!n||!this.current()||this.e("validate",()=>n.session.validate(),!1)!==!0||!this.current())return!1;let o=this.destination(t.node,t.fraction);return!o.valid||!o.intent||!this.current()?!1:(this.i&&this.requestFocus(o.intent,i=>this.focusHandle(n.node.id,i)),this.bridge.emit(n.node,n.from,o.toIndex,o.targetIndex,o.intent),!0)}};function U(r,e,t){let n=[],o=[...r].reverse().map(a=>({row:a,parent:null})),i=new Set;for(;o.length;){let a=o.pop();if(i.has(a.row))throw new Error("[MachTable] Installed order contains duplicate or cyclic rows.");i.add(a.row),n.push(a);let d=t?a.row[e]??[]:[];for(let c=d.length-1;c>=0;c--)o.push({row:d[c],parent:a.row})}return n}function H(r,e,t,n){try{let o=U(r,t,n);return o.length===e.length&&o.every((i,a)=>i.row===e[a].row&&i.parent===e[a].parent)}catch{return!1}}function ue(r){let e=[];return r?.rows.forEach(t=>e.push({node:t,data:t.data})),e}function Y(r,e){if(!r)return!0;if(r.isDestroyed())return!1;let t=0,n=!0;return r.rows.forEach(o=>{let i=e[t++];(i?.node!==o||i.data!==o.data)&&(n=!1)}),n&&t===e.length}var Q=class{constructor(){this.entries=[];this.cursor=0}get canUndo(){return this.cursor>0}get canRedo(){return this.cursor<this.entries.length}peek(e){return this.entries[e==="undo"?this.cursor-1:this.cursor]}commit(e,t){e==="undo"?this.cursor--:e==="redo"?this.cursor++:(this.entries.splice(this.cursor),this.entries.push(t),this.entries.length>50&&this.entries.shift(),this.cursor=this.entries.length)}clear(){this.entries=[],this.cursor=0}};var k=class extends Error{constructor(t="The row order changed on the server. Reload before trying again.",n){super(t);this.serverRevision=n;this.name="RowOrderConflictError"}};function ze(r){if(r?.status==="conflict")throw new k(r.message,r.revision);return r?.revision}function Ee(r){if(r.targetId===null)throw new Error("[MachTable] Row ordering requires an existing destination.");return{...r,targetId:r.targetId}}function $e(r){let e={status:"idle",error:null,revision:r.getRevision?.(),plan:null,canUndo:!1,canRedo:!1},t=0,n=!1,o=null,i=null,a=null,d=()=>{},c=()=>{},l=0,h=null,f=new Q,x=null,E=new Set,S=r.childrenKey??"children",I=null,A=()=>{f.clear(),x=null},u=()=>{if(!o)return!1;let s=o;return t++,o=null,i=null,s.abort(),!0},y=(s=e.status)=>({canUndo:!n&&s!=="saving"&&f.canUndo,canRedo:!n&&s!=="saving"&&f.canRedo}),m=s=>{e=Object.freeze({...s,...y(s.status)}),a&&!a.isDestroyed()&&a.view.refreshCells();let p=[w=>r.onStateChange?.(w),...E];for(let w of p)try{w?.(e)}catch(b){console.error("[MachTable] Row order state observer failed",b)}},v=()=>r.getRevision?.()??e.revision,g=(s=h)=>{s?.release(),h===s&&(h=null)},_=()=>{!i||i()||(u(),A(),g(),m({...e,status:"idle",plan:null,error:null}))},C=s=>new J(s,p=>xe(s.api,p,r.getRows(),r,r.treeData===!0,v()),(p,w)=>{g();let b=document.activeElement,T=N=>{N.target!==b&&N.target!==document.body&&g(R)},R={api:s.api,intent:p,restore:w,generation:t+1,release:()=>document.removeEventListener("focusin",T,!0)};h=R,document.addEventListener("focusin",T,!0)}),P=()=>{_(),!o&&x&&(x.api!==a||x.revision!==v()||!Y(a,x.nodes)||!H(r.getRows(),x.rows,S,r.treeData===!0))&&A();let s=y();(e.canUndo!==s.canUndo||e.canRedo!==s.canRedo)&&(e=Object.freeze({...e,...s}))},G=s=>{if(s===a){_(),de(s,C)||(c(),c=le(s,C));return}let p=u();d(),c(),g(),A(),a=s,c=le(s,C),d=s.on("cellValueChanged",()=>{l++;let w=f.canUndo||f.canRedo;A(),w&&m({...e,status:o?"saving":"idle",plan:o?e.plan:null,error:null})}),p&&m({...e,status:"idle",plan:null,error:null})},z=s=>{if(P(),n)throw new Error("[MachTable] The row order controller is disposed.");if(o)throw new Error("[MachTable] A row order save is already in progress.");let p=v();if(p!==void 0&&s.expectedRevision!==void 0&&s.expectedRevision!==p)throw new k;let w={...s,expectedRevision:s.expectedRevision??p};return(r.treeData?ie:oe)(r.getRows(),w,r)},pe=async(s,p,w,b,T)=>{if(!s.changed)return s;let R=a;if(R&&!X(R))throw new Error("[MachTable] Save or discard edited rows before changing their order.");let N=++t;I=null;let $=new AbortController;o=$,i=null;let W=v(),Me=l,F=null,q=[],fe=!1,Z=!1,ee=W,ye=D=>{if(!T)return;if(!D||T!==h||T.api!==a){g(T);return}let O=x;T.restore(()=>{let re=O!==null&&O===x&&O.revision===v()&&Y(T.api,O.nodes)&&H(r.getRows(),O.rows,S,r.treeData===!0)&&h===T&&!n&&t===T.generation&&a===T.api&&de(T.api,C);return g(T),re})},L=()=>!n&&t===N,te=()=>L()&&(!R||a===R&&!R.isDestroyed())&&F!==null&&v()===W&&Y(R,q)&&H(r.getRows(),F,S,r.treeData===!0),Pe=D=>{if(!te()){L()&&!F&&m({...e,status:"error",error:D,plan:s});return}let O=!R||X(R),B=O?D:Object.assign(new Error("[MachTable] Row order could not be saved. Automatic rollback was skipped to preserve new edits. Save or discard those edits, then reload the row order."),{cause:D});if(O){i=null;try{r.applyRows(s.before),Z=!0}catch(re){B=Object.assign(new Error("[MachTable] Row order could not be saved or restored. Reload the row order before trying again."),{cause:D,rollbackError:re})}}L()&&(Z||A(),m({...e,status:D instanceof k?"conflict":"error",error:B}))},Le=()=>{if(!L()){ye(!1);return}let D=v(),O=!1;fe&&L()&&(D===W||D===ee)&&Y(R,q)&&H(r.getRows(),F,S,r.treeData===!0)?(x={rows:F,nodes:q,api:R,revision:D},O=!0):Z&&L()?(x={rows:U(r.getRows(),S,r.treeData===!0),nodes:ue(R),api:R,revision:D},O=H(r.getRows(),U(s.before,S,r.treeData===!0),S,r.treeData===!0)):A(),o===$&&(o=null,i=null,a&&!a.isDestroyed()&&a.view.refreshCells()),L()&&e.status==="saving"&&m({...e,status:"idle",plan:null}),P(),ye(O)};try{r.applyRows(s.after),F=U(r.getRows(),S,r.treeData===!0),q=ue(R);let D=r.getRows(),O=q[0]?.node;if(i=R&&O?()=>!R.isDestroyed()&&R.rows.getById(O.id)===O:()=>r.getRows()===D,m({...e,status:"saving",error:null,plan:s}),!te())return s;let B=ze(await De(Promise.resolve(r.save?.(s.intent,{signal:$.signal,plan:s,operation:p,operations:w})),$.signal));return te()&&(fe=!0,ee=B??W,l===Me?f.commit(p,b):A(),m({...e,status:"saved",revision:ee})),s}catch(D){throw Pe(D),D}finally{Le()}},he=async(s,p)=>{p!==h&&(p=void 0),h!==p&&g();let w=z(s);w.changed||g(p);let b=w.changed?Re(w,r,r.treeData===!0):[];return pe(w,"move",[w.intent],{plan:w,inverse:b},p)},Se=s=>he(s),we=async s=>{if(g(),P(),n||o)throw new Error("[MachTable] Row ordering is unavailable while disposed or saving.");let p=f.peek(s);if(!p)throw new Error(`[MachTable] Nothing to ${s}.`);let w=(s==="undo"?p.inverse:[p.plan.intent]).map(N=>({...N,expectedRevision:v()})),b=r.getRows(),T=s==="undo"?p.plan.before:p.plan.after;Te(b,T,w,r,r.treeData===!0);let R={before:b,after:T,intent:w[0],rowIds:p.plan.rowIds,changed:!0};return pe(R,s,w,p)},Ae=s=>{try{if(n||o)return!1;let p=r.getRows(),w=v();if(w!==void 0&&s.expectedRevision!==void 0&&s.expectedRevision!==w)return!1;let b=I?.rowIds===s.rowIds?I.sources:JSON.stringify(s.rowIds.map(String));return(!I||I.rows!==p||I.revision!==w||I.sources!==b)&&(I={rows:p,revision:w,sources:b,rowIds:s.rowIds,validate:be(p,s.rowIds,r,r.treeData===!0)}),I.rowIds=s.rowIds,I.validate(s),!0}catch(p){return p instanceof Error?p.message:!1}},Ce=s=>{let p=s.intent;if(s.applied||!p)return;G(s.api);let w=t,b=h?.intent===p?h:void 0;Promise.resolve().then(()=>he(Ee(p),b)).catch(T=>{b&&b.generation!==t&&g(b),!n&&t===w&&e.status!=="saving"&&m({...e,status:T instanceof k?"conflict":"error",error:T})})},ge=s=>n?!1:(G(s),o?"Wait for the current row order to finish saving.":X(s)||"Save or discard edited rows before changing their order.");return{get state(){return P(),e},bindings:{applyRowDrag:!1,rowDragPolicy:{canDrag:({api:s})=>ge(s),canDrop:({intent:s,api:p})=>{let w=ge(p);if(w!==!0)return w;try{return Ae(Ee(s))}catch(b){return b instanceof Error?b.message:!1}},getRevision:v},onRowDragEnd:Ce},preview:z,move:Se,undo:()=>we("undo"),redo:()=>we("redo"),subscribe(s){return n?()=>{}:(E.add(s),()=>{E.delete(s)})},dispose(){n=!0,t++,o?.abort(),o=null,i=null,d(),c(),g(),A(),a&&!a.isDestroyed()&&a.view.refreshCells(),a=null,I=null,E.clear(),e=Object.freeze({...e,status:"idle",error:null,plan:null,canUndo:!1,canRedo:!1})}}}export{k as RowOrderConflictError,$e as createRowOrderController,ie as moveTreeNodes,oe as reorderRows};
1
+ var Ne=new Set(["__proto__","prototype","constructor"]),Y=new Map;function Ge(r){if(typeof r!="string"||r.length===0)return null;let t=Y.get(r);if(t!==void 0)return t;let e=r.split("."),n=e.every(o=>o.length>0&&!Ne.has(o))?e:null;return r.length<=1024&&(Y.size>=256&&Y.delete(Y.keys().next().value),Y.set(r,n)),n}function V(r,t){if(r==null)return;let e=Ge(t);if(!e)return;let n=r;for(let o of e){if(n==null)return;n=n[o]}return n}function Fe(r,t){let e=typeof t.rowKey=="function"?t.rowKey(r):V(r,t.rowKey);if(e==null||String(e).length===0)throw new Error("[MachTable] Row ordering requires a non-empty stable row key.");return String(e)}function He(r,t){let e=r[t];if(e==null)return[];if(!Array.isArray(e))throw new Error(`[MachTable] Tree ordering expects an array at "${t}".`);return e}function _(r,t,e,n){let o={entries:[],byId:new Map,byRow:new Map,children:new Map([[null,r]])},i=[...r].reverse().map(a=>({row:a,parentId:null,selectedAncestor:!1})),s=e.childrenKey??"children";for(;i.length;){let a=i.pop(),c=Fe(a.row,e);if(o.byId.has(c))throw new Error(`[MachTable] Row ordering found duplicate or cyclic row key "${c}".`);let l=n?He(a.row,s):[],w={...a,id:c,children:l};o.entries.push(w),o.byId.set(c,w),o.byRow.set(w.row,w),o.children.set(c,l);for(let f=l.length-1;f>=0;f--)i.push({row:l[f],parentId:c,selectedAncestor:a.selectedAncestor||t.has(c)})}return o}function qe(r){if(!["before","after","inside"].includes(r.position))throw new Error("[MachTable] Unknown row ordering position.");let t=[...new Set(r.rowIds.map(String))];if(!t.length)throw new Error("[MachTable] Row ordering requires at least one source row.");return{...r,rowIds:t,targetId:String(r.targetId)}}function ie(r,t){for(let n of t)if(!r.byId.has(n))throw new Error(`[MachTable] Ordering source "${n}" is unavailable.`);let e=new Set(t);return{selected:e,moved:r.entries.filter(n=>e.has(n.id)&&!n.selectedAncestor)}}function be(r,t,e,n){let o=r.byId.get(e.targetId);if(!o)throw new Error(`[MachTable] Ordering target "${e.targetId}" is unavailable.`);if(t.selected.has(o.id)||o.selectedAncestor)throw new Error("[MachTable] A row cannot be moved into or relative to its own subtree.");let i=e.position==="inside"?o.id:o.parentId,s=i===null?null:r.byId.get(i).row;if(n.canMove)for(let a of t.moved){let c=a.parentId===null?null:r.byId.get(a.parentId).row,l=n.canMove({row:a.row,previousParent:c,parent:s,target:o.row,intent:e});if(l===!1||typeof l=="string")throw new Error(typeof l=="string"?l:"[MachTable] This row cannot be moved to the selected parent.")}return i}function Re(r,t,e,n){let o=[...new Set(t.map(String))];if(!o.length)throw new Error("[MachTable] Row ordering requires at least one source row.");let i=_(r,new Set(o),e,n),s=ie(i,o);return a=>{if(!n&&a.position==="inside")throw new Error("[MachTable] Flat rows cannot have child destinations.");be(i,s,a,e)}}function Be(r,t,e,n){let o=new Set(t.map(l=>l.id)),i=new Map;for(let l of t)i.has(l.parentId)||i.set(l.parentId,r.children.get(l.parentId).filter(w=>!o.has(r.byRow.get(w).id)));let s=i.get(e)??r.children.get(e),a=s.findIndex(l=>l===r.byId.get(n.targetId).row),c=n.position==="inside"?s.length:a+ +(n.position==="after");return i.set(e,[...s.slice(0,c),...t.map(l=>l.row),...s.slice(c)]),i}function ve(r,t){return r.length===t.length&&r.every((e,n)=>e===t[n])}function Ke(r,t,e,n){let o=new Map,i=n.childrenKey??"children";for(let a=t.entries.length-1;a>=0;a--){let c=t.entries[a],w=(e.get(c.id)??c.children).map(f=>o.get(f)??f);ve(c.children,w)||o.set(c.row,{...c.row,[i]:w})}let s=(e.get(null)??r).map(a=>o.get(a)??a);return ve(r,s)?r:s}function Ue(r,t,e,n){let o=e.indexOf(t[0].row),i=o+t.length;return{...r,rowIds:t.map(s=>s.id),beforeId:o>0?n.byRow.get(e[o-1]).id:null,afterId:i<e.length?n.byRow.get(e[i]).id:null}}function Te(r,t,e){let n=_(r.before,new Set(r.rowIds),t,e),o=new Map;for(let i of n.children.values())i.forEach((s,a)=>o.set(n.byRow.get(s).id,a));return ie(n,r.rowIds).moved.reverse().map(i=>{let s=n.children.get(i.parentId),a=o.get(i.id),c=s[a+1];if(c)return{rowIds:[i.id],targetId:n.byRow.get(c).id,position:"before"};if(i.parentId!==null)return{rowIds:[i.id],targetId:i.parentId,position:"inside"};let l=s[a-1];if(!l)throw new Error("[MachTable] Row ordering cannot restore an isolated root.");return{rowIds:[i.id],targetId:n.byRow.get(l).id,position:"after"}})}function Ie(r,t,e,n,o){if(!n.canMove)return;let i=_(r,new Set,n,o),s=_(t,new Set,n,o);for(let a of e)for(let c of a.rowIds){let l=i.byId.get(c),w=s.byId.get(c),f=w.parentId===null?null:i.byId.get(w.parentId).row,O=l.parentId===null?null:i.byId.get(l.parentId).row,S=n.canMove({row:l.row,previousParent:O,parent:f,target:i.byId.get(a.targetId).row,intent:a});if(S===!1||typeof S=="string")throw new Error(typeof S=="string"?S:"[MachTable] This row cannot be restored to its previous parent.")}}function De(r,t,e,n){let o=qe(t);if(!n&&o.position==="inside")throw new Error("[MachTable] Flat rows cannot have child destinations.");let i=_(r,new Set(o.rowIds),e,n),{moved:s,selected:a}=ie(i,o.rowIds),c=be(i,{moved:s,selected:a},o,e),l=Be(i,s,c,o),w=Ke(r,i,l,e),f=Ue(o,s,l.get(c),i);return{before:r,after:w,intent:f,rowIds:f.rowIds,changed:r!==w}}function se(r,t,e){return De(r,t,e,!1)}function ae(r,t,e){return De(r,t,e,!0)}function de(r,t,e){let n=document.createElement(r);if(t&&(n.className=t),e)for(let o of Object.keys(e))n.setAttribute(o,e[o]);return n}function C(r,t,e){return r<t?t:r>e?e:r}var le=Symbol.for("mach-table.adapter.lifecycle.v1");function J(r){return!r.isDestroyed()&&(r[le]?.canReplaceData()??!1)}function ce(r,t){let e=r[le]?.rowDrag;return e?.original===t&&e.policy===r.getOption("rowDragPolicy")}function ue(r,t){let e=r[le];if(!e)return()=>{};e.rowDrag?.activeInteraction?.destroy();let n={original:t,policy:r.getOption("rowDragPolicy"),factory:o=>(n.activeInteraction=t(o),n.activeInteraction)};return e.rowDrag=n,()=>{n.activeInteraction?.destroy(),e.rowDrag===n&&(e.rowDrag=void 0)}}function Ye(r,t){if(r instanceof Error)return r;let e=new Error(typeof r=="string"?r:t);return e.name="AbortError",e}var _e=()=>Ye(void 0,"[MachTable] Operation cancelled.");function Oe(r,t,e=_e){return t?new Promise((n,o)=>{let i=()=>{t.removeEventListener("abort",i),o(e())};if(r.then(n,o).finally(()=>t.removeEventListener("abort",i)),t.aborted){i();return}t.addEventListener("abort",i,{once:!0})}):r}function pe(r,t,e){return r.replace("{a}",String(t)).replace("{b}",String(e))}function $e(r,t,e){return r&&t>.25&&t<.75?"inside":e}function xe(r,t){let e=0,n=r.length;for(;e<n;){let o=e+n>>>1;r[o]<t?e=o+1:n=o}return e}function We(r,t,e,n,o,i){let s=r.getOption("locale")??{},a=t>1?pe(s.rowDragSelection??"\u5DF2\u9009 {a} \u884C \u2192 \u7B2C {b} \u884C",t,n+1):pe(s.rowDragPosition??"\u7B2C {a} \u884C \u2192 \u7B2C {b} \u884C",e+1,n+1),c=o==="inside"?s.rowDragInside??"\u79FB\u5165":o==="before"?s.rowDragBefore??"\u4E4B\u524D":s.rowDragAfter??"\u4E4B\u540E";return{text:`${a} \xB7 ${c}`,indicatorStyle:o==="inside"?`height:${i}px;background:color-mix(in srgb,var(--mach-primary) 12%,transparent);box-shadow:inset 0 0 0 1px var(--mach-primary)`:void 0}}function ze(r,t,e){let n={parents:new Map,siblings:new Map([[null,[]]]),depths:new Map},o=[...r].reverse().map(s=>({row:s,parent:null,depth:0})),i=t.childrenKey??"children";for(;o.length;){let{row:s,parent:a,depth:c}=o.pop(),l=String(typeof t.rowKey=="function"?t.rowKey(s):V(s,t.rowKey));if(n.depths.has(l))throw new Error("[MachTable] Row ordering requires unique, acyclic row keys.");n.depths.set(l,c),n.siblings.get(a).push(l),n.siblings.set(l,[]),a!==null&&n.parents.set(l,a);let w=e?s[i]:void 0;if(w!=null&&!Array.isArray(w))throw new Error("[MachTable] Row ordering children must be an array.");for(let f=(w?.length??0)-1;f>=0;f--)o.push({row:w[f],parent:l,depth:c+1})}return n}function Ee(r,t,e,n,o,i){let s=new Map;r.rows.forEach(u=>{!u.loading&&!u.isDetail&&!u.isGroup&&u.data!=null&&s.set(u.id,u)});let a=ze(e,n,o),c=new Set(t.selected?[...a.depths.keys()].filter(u=>s.get(u)?.selected):[t.id]),l=[...c],w=u=>{let g=u;for(;g!==void 0;){if(c.has(g))return!0;g=a.parents.get(g)}return!1},f=new Map,O=new Map;for(let[u,g]of a.siblings){let y=g.filter(m=>!c.has(m));f.set(u,y),y.forEach((m,T)=>O.set(m,T))}let S=new Map,A=new Set,x=[],E=[],q=0;r.rows.forEachDisplayed(u=>{A.add(u.id),w(u.id)&&x.push(u.rowIndex),q=u.rowIndex+1;let g=a.depths.get(u.id)??0;for(;E.length&&(a.depths.get(E[E.length-1].id)??0)>=g;)S.set(E.pop().id,u.rowIndex);a.siblings.get(u.id)?.length&&E.push(u)});for(let u of E)S.set(u.id,q);return{rowIds:l,isSource:w,validate:()=>{for(let u of l){let g=s.get(u);if(g.treeLoading)return!1;let y=r.getOption("rowDragPolicy")?.canDrag?.({node:g,api:r});if(y===!1||typeof y=="string")return y}return!0},resolve:({targetNode:u,position:g,fraction:y,height:m})=>{let T=$e(o,y,g);if(w(u.id))return"Cannot target own subtree.";if(!o&&T==="inside")return!1;let k=T==="inside"?u.id:a.parents.get(u.id)??null,M=f.get(k)??[],B=T==="inside"?M.length:(O.get(u.id)??0)+ +(T==="after"),N=T==="before"?u.rowIndex:S.get(u.id)??u.rowIndex+1,z=N-xe(x,N)+xe(x,t.rowIndex);return{intent:{rowIds:l,targetId:u.id,position:T,beforeId:M[B-1]??null,afterId:M[B]??null,expectedRevision:i},indicatorIndex:T==="inside"?u.rowIndex:T==="after"?S.get(u.id):void 0,toIndex:N,targetIndex:z,...We(r,l.length,t.rowIndex,u.rowIndex,T,m)}},keyboardTarget:u=>{let g=t.id;for(;c.has(a.parents.get(g)??"");)g=a.parents.get(g);let y=a.siblings.get(a.parents.get(g)??null)??[],m=y.indexOf(g)+u;for(;m>=0&&m<y.length;){let T=y[m];if(!w(T)&&A.has(T)&&s.has(T))return s.get(T);m+=u}}}}var Q=class{constructor(t){this.host=t;this.drag=null;this.r=0;this.n=0;this.a=t=>{let e=this.drag;if(!(!e||t.pointerId!==e.pointerId)){if(e.clientX=t.clientX,e.clientY=t.clientY,!e.active){if(Math.abs(t.clientY-e.startY)<5)return;e.active=!0,this.host.root.classList.add("mach-root--row-dragging"),this.host.root.querySelectorAll(".mach-row").forEach(n=>n.classList.toggle("mach-row--drag-source",this.sourceContains(n.dataset.id??"")))}this.c()}};this.f=()=>{if(this.r=0,!!this.drag?.active){if(!this.current()){this.destroy();return}this.u(),this.m()&&this.c()}};this.l=t=>{let e=this.drag;if(!(!e||t.pointerId!==e.pointerId)){e.clientX=t.clientX,e.clientY=t.clientY,e.active&&this.current()&&this.u(),this.p();try{e.active&&e.drop?.valid&&this.i(t.clientX,t.clientY)&&this.current()&&this.commitDrop(e.drop)}finally{this.release()}}};this.d=t=>{t.key==="Escape"&&(t.preventDefault(),this.destroy())};this.o=t=>{t.type==="pointercancel"&&t.pointerId!==this.drag?.pointerId||this.destroy()}}begin(t){let e=this.host.containers.map(o=>{let i=de("div","mach-row-drop-indicator");return i.hidden=!0,o.append(i),i}),n=de("div","mach-row-drag-preview");n.setAttribute("role","status"),n.hidden=!0,this.host.root.append(n),this.drag={startY:t.clientY,clientX:t.clientX,clientY:t.clientY,pointerId:t.pointerId,indicators:e,preview:n,drop:null,active:!1},window.addEventListener("pointermove",this.a),window.addEventListener("pointerup",this.l),window.addEventListener("pointercancel",this.o),window.addEventListener("keydown",this.d),window.addEventListener("blur",this.o)}w(t){return this.drag?.active===!0&&this.sourceContains(t)}g(t,e=()=>!0){this.n=requestAnimationFrame(()=>{this.n=0,e()&&[...this.host.root.querySelectorAll(".mach-row-drag-handle")].find(n=>n.closest(".mach-row")?.dataset.id===t)?.focus()})}c(){this.r||(this.r=requestAnimationFrame(this.f))}i(t,e,n=0){let o=this.host.body.getBoundingClientRect();return t>=o.left&&t<=o.right&&e>=o.top-n&&e<=o.bottom+n}m(){let t=this.drag;if(!t||!this.i(t.clientX,t.clientY,28))return!1;let e=this.host.viewport,n=e.getBoundingClientRect(),o=Math.min(36,n.height/3);if(o<=0)return!1;let i=t.clientY<n.top+o?-Math.ceil(14*C((n.top+o-t.clientY)/o,0,1)):Math.ceil(14*C((t.clientY-n.bottom+o)/o,0,1));if(this.host.scrollBy)return this.host.scrollBy(i);let s=e.scrollTop;return e.scrollTop=C(s+i,0,Math.max(0,e.scrollHeight-e.clientHeight)),e.scrollTop!==s}u(){let t=this.drag;if(!t?.active)return;let e=t.clientY-this.host.viewport.getBoundingClientRect().top+this.host.viewport.scrollTop,n=this.describe(e);t.drop=n;let o=this.i(t.clientX,t.clientY);for(let s of t.indicators){if(s.hidden=!o||!n?.valid,!n)continue;s.dataset.dropPosition=n.position??"",s.style.cssText=n.style??"";let a=parseFloat(s.parentElement.style.height),c=Math.min(this.host.getRowTop(n.boundary),Number.isFinite(a)?Math.max(0,a-2):1/0);s.style.transform=`translate3d(0, ${c}px, 0)`}let i=this.host.root.getBoundingClientRect();t.preview.hidden=!1,t.preview.textContent=o?n?.text??this.outsideText():this.outsideText(),t.preview.style.transform=`translate3d(${C(t.clientX-i.left+16,8,Math.max(8,i.width-224))}px, ${C(t.clientY-i.top+16,8,Math.max(8,i.height-48))}px, 0)`}p(){let t=this.drag;this.drag=null,window.removeEventListener("pointermove",this.a),window.removeEventListener("pointerup",this.l),window.removeEventListener("pointercancel",this.o),window.removeEventListener("keydown",this.d),window.removeEventListener("blur",this.o),cancelAnimationFrame(this.r),this.r=0,this.host.root?.classList.remove("mach-root--row-dragging"),this.host.root?.querySelectorAll(".mach-row--drag-source").forEach(e=>e.classList.remove("mach-row--drag-source")),t?.indicators.forEach(e=>e.remove()),t?.preview.remove()}destroy(){this.p(),this.release(),cancelAnimationFrame(this.n),this.n=0}};var Z=class extends Q{constructor(e,n,o){super(e);this.e=e;this.prepare=n;this.y=o;this.scope=null;this.s=!1}t(e,n,o){try{return n()}catch(i){return this.scope&&(this.scope.failed=!0),this.e.report(i,e),o}}h(e){return this.t("prepare",()=>{let n=this.e.capture(e),o=this.prepare(e);return this.scope={node:e,from:e.rowIndex,guard:n,session:o,sourceDecision:!0,failed:!1},this.scope.sourceDecision=o.validate(),this.scope},null)}start(e,n){this.destroy(),this.h(n)&&this.current()&&this.begin(e)}moveWithKeyboard(e,n){this.destroy();let o=this.h(n);if(!(!o||!this.current())){this.s=!0;try{let i=e.key==="ArrowUp"?-1:1,s=this.t("keyboardTarget",()=>o.session.keyboardTarget(i),void 0);s&&this.commitDrop(this.destination(s,i<0?0:1))}finally{this.s=!1,this.release()}}}isSource(e){return this.w(e.id)}current(){return!!(this.scope&&!this.scope.failed&&this.scope.guard.current()&&this.e.api.rows.getById(this.scope.node.id)===this.scope.node)}sourceContains(e){return this.t("isSource",()=>this.scope?.session.isSource(e)??!1,!1)}release(){this.scope=null}outsideText(){return this.e.api.getOption("locale")?.rowDragOutside??"\u79FB\u56DE\u8868\u683C\u5185\u653E\u7F6E \xB7 Esc \u53D6\u6D88"}describe(e){let n=this.e.api,o=C(this.host.findRowAt(e),0,n.rows.getCount()-1),i=n.rows.getAt(o);if(i?.isDetail&&(i=n.rows.getById(i.masterId)),!i)return null;let s=this.host.getRowTop(i.rowIndex),a=this.host.getRowTop(i.rowIndex+1)-s;return this.destination(i,(e-s)/Math.max(1,a))}destination(e,n){let o=this.scope,i=n<.5?"before":"after",s=this.host.getRowTop(e.rowIndex+1)-this.host.getRowTop(e.rowIndex),a=this.t("resolve",()=>o.session.resolve({targetNode:e,position:i,fraction:n,height:s}),!1),c=typeof o.sourceDecision=="string"?o.sourceDecision:typeof a=="string"?a:"\u6B64\u4F4D\u7F6E\u4E0D\u53EF\u653E\u7F6E",l={node:e,fraction:n,boundary:e.rowIndex,valid:!1,text:c};if(!a||typeof a=="string"||o.sourceDecision!==!0||e.loading||e.treeLoading||e.isGroup)return l;l.intent=a.intent,l.position=a.intent.position,l.toIndex=a.toIndex,l.targetIndex=a.targetIndex,l.boundary=a.indicatorIndex??e.rowIndex+ +(a.intent.position==="after"),l.style=a.indicatorStyle,l.text=a.text??c;let w=this.t("canDrop",()=>this.e.api.getOption("rowDragPolicy")?.canDrop?.({node:o.node,api:this.e.api,targetNode:e,intent:a.intent})??!0,!1);return l.valid=w===!0,typeof w=="string"&&(l.text=w),l}commitDrop(e){let n=this.scope;if(!n||!this.current()||this.t("validate",()=>n.session.validate(),!1)!==!0||!this.current())return!1;let o=this.destination(e.node,e.fraction);return!o.valid||!o.intent||!this.current()?!1:(this.s&&this.y(o.intent,i=>this.g(n.node.id,i)),this.e.emit(n.node,n.from,o.toIndex,o.targetIndex,o.intent),!0)}};function $(r,t,e){let n=[],o=[...r].reverse().map(s=>({row:s,parent:null})),i=new Set;for(;o.length;){let s=o.pop();if(i.has(s.row))throw new Error("[MachTable] Installed order contains duplicate or cyclic rows.");i.add(s.row),n.push(s);let a=e?s.row[t]??[]:[];for(let c=a.length-1;c>=0;c--)o.push({row:a[c],parent:s.row})}return n}function H(r,t,e,n){try{let o=$(r,e,n);return o.length===t.length&&o.every((i,s)=>i.row===t[s].row&&i.parent===t[s].parent)}catch{return!1}}function we(r){let t=[];return r?.rows.forEach(e=>t.push({node:e,data:e.data})),t}function W(r,t){if(!r)return!0;if(r.isDestroyed())return!1;let e=0,n=!0;return r.rows.forEach(o=>{let i=t[e++];(i?.node!==o||i.data!==o.data)&&(n=!1)}),n&&e===t.length}var ee=class{constructor(){this.entries=[];this.cursor=0}get canUndo(){return this.cursor>0}get canRedo(){return this.cursor<this.entries.length}peek(t){return this.entries[t==="undo"?this.cursor-1:this.cursor]}commit(t,e){t==="undo"?this.cursor--:t==="redo"?this.cursor++:(this.entries.splice(this.cursor),this.entries.push(e),this.entries.length>50&&this.entries.shift(),this.cursor=this.entries.length)}clear(){this.entries=[],this.cursor=0}};var P=class extends Error{constructor(e="The row order changed on the server. Reload before trying again.",n){super(e);this.serverRevision=n;this.name="RowOrderConflictError"}};function je(r){if(r?.status==="conflict")throw new P(r.message,r.revision);return r?.revision}function Se(r){if(r.targetId===null)throw new Error("[MachTable] Row ordering requires an existing destination.");return{...r,targetId:r.targetId}}function Xe(r){let t={status:"idle",error:null,revision:r.getRevision?.(),plan:null,canUndo:!1,canRedo:!1},e=0,n=!1,o=null,i=null,s=null,a=()=>{},c=()=>{},l=0,w=null,f=new ee,O=null,S=new Set,A=r.childrenKey??"children",x=null,E=()=>{f.clear(),O=null},q=()=>{if(!o)return!1;let d=o;return e++,o=null,i=null,d.abort(),!0},u=(d=t.status)=>({canUndo:!n&&d!=="saving"&&f.canUndo,canRedo:!n&&d!=="saving"&&f.canRedo}),g=d=>{t=Object.freeze({...d,...u(d.status)}),s&&!s.isDestroyed()&&s.view.refreshCells();let p=[h=>r.onStateChange?.(h),...S];for(let h of p)try{h?.(t)}catch(v){console.error("[MachTable] Row order state observer failed",v)}},y=()=>r.getRevision?.()??t.revision,m=(d=w)=>{d?.release(),w===d&&(w=null)},T=()=>{!i||i()||(q(),E(),m(),g({...t,status:"idle",plan:null,error:null}))},k=d=>new Z(d,p=>Ee(d.api,p,r.getRows(),r,r.treeData===!0,y()),(p,h)=>{m();let v=document.activeElement,R=G=>{G.target!==v&&G.target!==document.body&&m(b)},b={api:d.api,intent:p,restore:h,generation:e+1,release:()=>document.removeEventListener("focusin",R,!0)};w=b,document.addEventListener("focusin",R,!0)}),M=()=>{T(),!o&&O&&(O.api!==s||O.revision!==y()||!W(s,O.nodes)||!H(r.getRows(),O.rows,A,r.treeData===!0))&&E();let d=u();(t.canUndo!==d.canUndo||t.canRedo!==d.canRedo)&&(t=Object.freeze({...t,...d}))},B=d=>{if(d===s){T(),ce(d,k)||(c(),c=ue(d,k));return}let p=q();a(),c(),m(),E(),s=d,c=ue(d,k),a=d.on("cellValueChanged",()=>{l++;let h=f.canUndo||f.canRedo;E(),h&&g({...t,status:o?"saving":"idle",plan:o?t.plan:null,error:null})}),p&&g({...t,status:"idle",plan:null,error:null})},N=d=>{if(M(),n)throw new Error("[MachTable] The row order controller is disposed.");if(o)throw new Error("[MachTable] A row order save is already in progress.");let p=y();if(p!==void 0&&d.expectedRevision!==void 0&&d.expectedRevision!==p)throw new P;let h={...d,expectedRevision:d.expectedRevision??p};return(r.treeData?ae:se)(r.getRows(),h,r)},z=async(d,p,h,v,R)=>{if(!d.changed)return d;let b=s;if(b&&!J(b))throw new Error("[MachTable] Save or discard edited rows before changing their order.");let G=++e;x=null;let j=new AbortController;o=j,i=null;let X=y(),Le=l,F=null,K=[],ye=!1,te=!1,re=X,me=I=>{if(!R)return;if(!I||R!==w||R.api!==s){m(R);return}let D=O;R.restore(()=>{let oe=D!==null&&D===O&&D.revision===y()&&W(R.api,D.nodes)&&H(r.getRows(),D.rows,A,r.treeData===!0)&&w===R&&!n&&e===R.generation&&s===R.api&&ce(R.api,k);return m(R),oe})},L=()=>!n&&e===G,ne=()=>L()&&(!b||s===b&&!b.isDestroyed())&&F!==null&&y()===X&&W(b,K)&&H(r.getRows(),F,A,r.treeData===!0),Pe=I=>{if(!ne()){L()&&!F&&g({...t,status:"error",error:I,plan:d});return}let D=!b||J(b),U=D?I:Object.assign(new Error("[MachTable] Row order could not be saved. Automatic rollback was skipped to preserve new edits. Save or discard those edits, then reload the row order."),{cause:I});if(D){i=null;try{r.applyRows(d.before),te=!0}catch(oe){U=Object.assign(new Error("[MachTable] Row order could not be saved or restored. Reload the row order before trying again."),{cause:I,rollbackError:oe})}}L()&&(te||E(),g({...t,status:I instanceof P?"conflict":"error",error:U}))},ke=()=>{if(!L()){me(!1);return}let I=y(),D=!1;ye&&L()&&(I===X||I===re)&&W(b,K)&&H(r.getRows(),F,A,r.treeData===!0)?(O={rows:F,nodes:K,api:b,revision:I},D=!0):te&&L()?(O={rows:$(r.getRows(),A,r.treeData===!0),nodes:we(b),api:b,revision:I},D=H(r.getRows(),$(d.before,A,r.treeData===!0),A,r.treeData===!0)):E(),o===j&&(o=null,i=null,s&&!s.isDestroyed()&&s.view.refreshCells()),L()&&t.status==="saving"&&g({...t,status:"idle",plan:null}),M(),me(D)};try{r.applyRows(d.after),F=$(r.getRows(),A,r.treeData===!0),K=we(b);let I=r.getRows(),D=K[0]?.node;if(i=b&&D?()=>!b.isDestroyed()&&b.rows.getById(D.id)===D:()=>r.getRows()===I,g({...t,status:"saving",error:null,plan:d}),!ne())return d;let U=je(await Oe(Promise.resolve(r.save?.(d.intent,{signal:j.signal,plan:d,operation:p,operations:h})),j.signal));return ne()&&(ye=!0,re=U??X,l===Le?f.commit(p,v):E(),g({...t,status:"saved",revision:re})),d}catch(I){throw Pe(I),I}finally{ke()}},he=async(d,p)=>{p!==w&&(p=void 0),w!==p&&m();let h=N(d);h.changed||m(p);let v=h.changed?Te(h,r,r.treeData===!0):[];return z(h,"move",[h.intent],{plan:h,inverse:v},p)},Ae=d=>he(d),ge=async d=>{if(m(),M(),n||o)throw new Error("[MachTable] Row ordering is unavailable while disposed or saving.");let p=f.peek(d);if(!p)throw new Error(`[MachTable] Nothing to ${d}.`);let h=(d==="undo"?p.inverse:[p.plan.intent]).map(G=>({...G,expectedRevision:y()})),v=r.getRows(),R=d==="undo"?p.plan.before:p.plan.after;Ie(v,R,h,r,r.treeData===!0);let b={before:v,after:R,intent:h[0],rowIds:p.plan.rowIds,changed:!0};return z(b,d,h,p)},Me=d=>{try{if(n||o)return!1;let p=r.getRows(),h=y();if(h!==void 0&&d.expectedRevision!==void 0&&d.expectedRevision!==h)return!1;let v=x?.rowIds===d.rowIds?x.sources:JSON.stringify(d.rowIds.map(String));return(!x||x.rows!==p||x.revision!==h||x.sources!==v)&&(x={rows:p,revision:h,sources:v,rowIds:d.rowIds,validate:Re(p,d.rowIds,r,r.treeData===!0)}),x.rowIds=d.rowIds,x.validate(d),!0}catch(p){return p instanceof Error?p.message:!1}},Ce=d=>{let p=d.intent;if(d.applied||!p)return;B(d.api);let h=e,v=w?.intent===p?w:void 0;Promise.resolve().then(()=>he(Se(p),v)).catch(R=>{v&&v.generation!==e&&m(v),!n&&e===h&&t.status!=="saving"&&g({...t,status:R instanceof P?"conflict":"error",error:R})})},fe=d=>n?!1:(B(d),o?"Wait for the current row order to finish saving.":J(d)||"Save or discard edited rows before changing their order.");return{get state(){return M(),t},bindings:{applyRowDrag:!1,rowDragPolicy:{canDrag:({api:d})=>fe(d),canDrop:({intent:d,api:p})=>{let h=fe(p);if(h!==!0)return h;try{return Me(Se(d))}catch(v){return v instanceof Error?v.message:!1}},getRevision:y},onRowDragEnd:Ce},preview:N,move:Ae,undo:()=>ge("undo"),redo:()=>ge("redo"),subscribe(d){return n?()=>{}:(S.add(d),()=>{S.delete(d)})},dispose(){n=!0,e++,o?.abort(),o=null,i=null,a(),c(),m(),E(),s&&!s.isDestroyed()&&s.view.refreshCells(),s=null,x=null,S.clear(),t=Object.freeze({...t,status:"idle",error:null,plan:null,canUndo:!1,canRedo:!1})}}}export{P as RowOrderConflictError,Xe as createRowOrderController,ae as moveTreeNodes,se as reorderRows};
@@ -1 +1 @@
1
- "use strict";var w=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var Y=(e,n)=>{for(var t in n)w(e,t,{get:n[t],enumerable:!0})},Z=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of $(n))!B.call(e,o)&&o!==t&&w(e,o,{get:()=>n[o],enumerable:!(r=W(n,o))||r.enumerable});return e};var J=e=>Z(w({},"__esModule",{value:!0}),e);var Ne={};Y(Ne,{GridPreferenceConflictError:()=>T,createGridPreferenceStore:()=>Q,migrateGridState:()=>b});module.exports=J(Ne);var ee=new Set(["contains","notContains","equals","notEquals","startsWith","endsWith","blank","notBlank"]),ne=new Set(["equals","notEquals","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","inRange","blank","notBlank"]),te=new Set(["equals","notEquals","lessThan","greaterThan","inRange","blank","notBlank"]);function re(e){return e==null||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function oe(e){return e==="text"?ee:e==="number"?ne:te}function ie(e,n,t){if(e==null||typeof e!="object")return null;let r=e;return typeof r.match!="string"||!t.has(r.match)?null:{match:r.match,...le(r,n)}}function le(e,n){let t=n==="number"?N(e.value):typeof e.value=="string"?e.value:void 0,r=n==="number"?N(e.value2):typeof e.value2=="string"?e.value2:void 0;return{...t!==void 0?{value:t}:{},...r!==void 0?{value2:r}:{}}}function N(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function se(e,n){let t=[],r=oe(n);for(let o of e.slice(0,20)){let i=ie(o,n,r);i&&t.push(i)}return t}function A(e){if(e==null||typeof e!="object")return null;let n=e;return n.type==="set"?Array.isArray(n.values)?{type:"set",values:n.values.filter(re).slice(0,2e3)}:null:n.type!=="text"&&n.type!=="number"&&n.type!=="date"||!Array.isArray(n.conditions)?null:{type:n.type,...n.operator==="or"||n.operator==="and"?{operator:n.operator}:{},conditions:se(n.conditions,n.type)}}function ae(e,n){if(typeof e.colId!="string"||!e.colId.trim())return null;let t=e.colId.trim();if(n.validColumnIds?.has(t)===!1)return null;let r=A(e.filter);return r?{kind:"condition",colId:t,filter:r}:null}function de(e,n,t){if(!Array.isArray(e.children))return null;let r=[];for(let o of e.children){let i=P(o,n+1,t);i&&r.push(i)}return r.length===0?null:{kind:"group",operator:e.operator==="or"?"or":"and",children:r,...e.not===!0?{not:!0}:{}}}function ue(e,n,t){return n<=16&&t.nodes<512&&e!=null&&typeof e=="object"}function P(e,n,t){if(!ue(e,n,t)||t.ancestors.has(e))return null;t.ancestors.add(e),t.nodes++;let r=e,o=r.kind==="condition"?ae(r,t):r.kind==="group"?de(r,n,t):null;return t.ancestors.delete(e),o}function _(e,n){if(e==null||typeof e!="object")return null;let t=e;if(t.version!==1||t.root==null)return null;let r=P(t.root,0,{ancestors:new WeakSet,nodes:0,validColumnIds:n});return r?{version:1,root:r}:null}function O(e,n){if(e==null||typeof e!="object"||Array.isArray(e))return{};let t={};for(let[r,o]of Object.entries(e).slice(0,2e3)){let i=r.trim();if(!i||n?.has(i)===!1)continue;let s=A(o);s&&(t[i]=s)}return t}var L=2e3,ce=1e5,k=512,fe=1e4;function G(e){return Array.isArray(e)?[...new Set(e.slice(0,ce).filter(n=>typeof n=="string"&&n.length>0&&n.length<=k))]:[]}function x(e,n){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):n}function D(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function pe(e,n){let t=D(n.flex);for(let r of["width","contentWidth"]){let o=D(n[r]);o!==void 0&&(e[r]=o)}n.flex===null?e.flex=null:t!==void 0&&(e.flex=t),(n.widthMode==="auto"||n.widthMode==="manual")&&(e.widthMode=n.widthMode)}function me(e,n){typeof n.hide=="boolean"&&(e.hide=n.hide),(n.pinned===null||n.pinned==="left"||n.pinned==="right")&&(e.pinned=n.pinned)}function ge(e,n){if(e==null||typeof e!="object")return null;let t=e,r=typeof t.colId=="string"?t.colId.trim():"";if(!r||r.length>k||n.has(r))return null;n.add(r);let o={colId:r};return me(o,t),pe(o,t),o}function ye(e){if(!Array.isArray(e))return[];let n=[],t=new Set;for(let r of e.slice(0,L)){let o=ge(r,t);o&&n.push(o)}return n}function Me(e){if(!Array.isArray(e))return[];let n=[],t=new Set;for(let r of e.slice(0,L)){if(r==null||typeof r!="object")continue;let o=r,i=typeof o.colId=="string"?o.colId.trim():"";!i||i.length>k||t.has(i)||o.direction!=="asc"&&o.direction!=="desc"||(t.add(i),n.push({colId:i,direction:o.direction}))}return n}function q(e){if(e==null||typeof e!="object")return null;let n=e;if(n.version!==2||!Array.isArray(n.columns)||!Array.isArray(n.sortModel))return null;let t=n.pagination!=null&&typeof n.pagination=="object"?n.pagination:{};return{version:2,columns:ye(n.columns),sortModel:Me(n.sortModel),filterModel:O(n.filterModel),advancedFilterModel:_(n.advancedFilterModel),quickFilterText:typeof n.quickFilterText=="string"&&n.quickFilterText.trim()?n.quickFilterText.slice(0,fe):null,pagination:{enabled:t.enabled===!0,page:x(t.page,1),pageSize:x(t.pageSize,20)},selectedRowIds:G(n.selectedRowIds),expandedRowIds:G(n.expandedRowIds),expandedGroupIds:G(n.expandedGroupIds)}}var S=2e3,z=256,C=512;function g(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:null}function F(e){return typeof e=="string"&&e.length<=512&&e.trim().length>0&&!["__proto__","prototype","constructor"].includes(e)}function f(e,n){e.length<z-1?e.push(n):e.length===z-1&&e.push({code:"LIMIT_EXCEEDED",path:"report"})}function Ie(e,n){if(e.columns.length>S||e.columns.some(o=>!F(o)||o!==o.trim()))throw new TypeError("[MachTable] Preference columns must contain at most 2000 valid stable IDs.");let t=new Set(e.columns);if(t.size!==e.columns.length)throw new TypeError("[MachTable] Preference column IDs must be unique.");let r=new Map(Object.entries(e.renameColumns??{}));if(r.size>S||[...r].some(([o,i])=>!F(o)||!t.has(i)))throw new TypeError("[MachTable] Preference rename targets must identify current columns.");return(o,i)=>{if(!F(o))return f(n,{code:"REMOVED_COLUMN",path:i}),null;let s=o.trim(),c=r.get(s)??s;return t.has(c)?(s!==c&&f(n,{code:"RENAMED_COLUMN",path:i,from:s,to:c}),c):(f(n,{code:"REMOVED_COLUMN",path:i,from:s}),null)}}function he(e){let n=Object.entries(e.columnTypes??{}),t=new Set(e.columns);if(n.length>S||n.some(([r,o])=>!t.has(r)||!["text","number","date","set",!1].includes(o)))throw new TypeError("[MachTable] Preference filter types must identify current columns and supported types.");return new Map(n)}function Se(e,n){return n.match==="blank"||n.match==="notBlank"?!0:e==="number"?typeof n.value!="number"||!Number.isFinite(n.value)?!1:n.match!=="inRange"||typeof n.value2=="number"&&Number.isFinite(n.value2)&&n.value2>=n.value:typeof n.value!="string"?!1:e==="text"?!0:Number.isFinite(Date.parse(n.value))?n.match!=="inRange"||typeof n.value2=="string"&&Number.isFinite(Date.parse(n.value2))&&Date.parse(n.value2)>=Date.parse(n.value):!1}function be(e,n){let t=typeof e=="string"?e.length:0;return t>1024||n.filterCharacters<t?!1:(n.filterCharacters-=t,!0)}function j(e,n){return n.filterItems<=0?!1:(n.filterItems--,e.every(t=>be(t,n)))}function ve(e){let n=g(e);return n?.operator!==void 0&&n.operator!=="and"&&n.operator!=="or"?null:A(n&&{type:n.type,operator:n.operator,values:Array.isArray(n.values)?n.values.slice(0,2e3):void 0,conditions:Array.isArray(n.conditions)?n.conditions.slice(0,20):void 0})}function U(e,n,t,r){let o=r.report;if(r.filterItems<=0)return f(o,{code:"LIMIT_EXCEEDED",path:t}),null;let i=ve(e);if(!i)return f(o,{code:"INVALID_FILTER",path:t}),null;let s=r.types.get(n);if(s!==void 0&&s!==i.type)return f(o,{code:"TYPE_CHANGED",path:t,from:i.type,to:s===!1?"disabled":s}),null;if(i.type==="set"){let y=i.values.filter(M=>(M===null||typeof M=="string"||typeof M=="number")&&j([M],r)),h=g(e)?.values;return Array.isArray(h)&&h.length!==y.length&&f(o,{code:"NORMALIZED",path:t}),{type:"set",values:y}}let c=i.conditions.filter(y=>j(Object.values(y),r)&&Se(i.type,y)),p=g(e)?.conditions;return Array.isArray(p)&&p.length!==c.length&&f(o,{code:"INVALID_FILTER",path:t}),c.length?{...i,conditions:c}:null}function Ae(e,n,t){let r=t.resolve(e.colId,`${n}.colId`);if(!r)return null;let o=U(e.filter,r,`${n}.filter`,t);return o?{kind:"condition",colId:r,filter:o}:null}function Ee(e,n,t,r){if(!Array.isArray(e.children)||!["and","or"].includes(e.operator))return f(r.report,{code:"INVALID_FILTER",path:n}),null;let o=[];for(let i=0;i<Math.min(e.children.length,C);i++){let s=H(e.children[i],`${n}.children[${i}]`,t+1,r);s&&o.push(s)}return e.children.length>C&&f(r.report,{code:"LIMIT_EXCEEDED",path:n}),o.length?{kind:"group",operator:e.operator,children:o,...e.not===!0?{not:!0}:{}}:null}function H(e,n,t,r){let o=g(e);if(!o||t>16||r.nodes>=C||r.ancestors.has(o))return f(r.report,{code:"LIMIT_EXCEEDED",path:n}),null;r.nodes++,r.ancestors.add(o);let i=null;return o.kind==="condition"?i=Ae(o,n,r):o.kind==="group"?i=Ee(o,n,t,r):f(r.report,{code:"INVALID_FILTER",path:n}),r.ancestors.delete(o),i}function V(e,n,t){let r=new Set;return e.flatMap((o,i)=>{let s=t.resolve(o.colId,`${n}[${i}]`);return s?r.has(s)?(f(t.report,{code:"DUPLICATE_COLUMN",path:n,from:o.colId,to:s}),[]):(r.add(s),[{...o,colId:s}]):[]})}function Te(e,n){let t=g(e.filterModel),r=Object.create(null);if(!t)return r;let o=0;for(let i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;if(o++>=S){f(n.report,{code:"LIMIT_EXCEEDED",path:"filterModel"});break}let s=`filterModel.${i.slice(0,512)}`,c=n.resolve(i,s);if(!c)continue;if(Object.prototype.hasOwnProperty.call(r,c)){f(n.report,{code:"DUPLICATE_COLUMN",path:"filterModel",from:i,to:c});continue}let p=U(t[i],c,s,n);p&&(r[c]=p)}return r}function Re(e){let n=g(e.pagination);return g(e.filterModel)!==null&&n!==null&&typeof n.enabled=="boolean"&&typeof n.page=="number"&&typeof n.pageSize=="number"&&(e.quickFilterText===null||typeof e.quickFilterText=="string")&&[e.selectedRowIds,e.expandedRowIds,e.expandedGroupIds].every(Array.isArray)}function we(e,n){if(e.version!==2||e.advancedFilterModel==null)return null;let t=g(e.advancedFilterModel);if(t?.version!==1)return f(n.report,{code:"INVALID_FILTER",path:"advancedFilterModel"}),null;let r=H(t.root,"advancedFilterModel.root",0,n);return r?{version:1,root:r}:null}function X(e){return Array.isArray(e)?e.slice(0,S).filter(n=>{let t=g(n)?.colId;return typeof t!="string"||t.length<=512}):e}function b(e,n){let t=[],r=g(e),o=Ie(n,t),i=he(n);if(!r||![1,2].includes(r.version))return f(t,{code:"UNSUPPORTED_VERSION",path:"version"}),{state:null,report:t};let s=q({version:2,columns:X(r.columns),sortModel:X(r.sortModel),filterModel:{},advancedFilterModel:null,quickFilterText:typeof r.quickFilterText=="string"?r.quickFilterText.slice(0,1e4):r.quickFilterText,pagination:r.pagination,selectedRowIds:r.selectedRowIds,expandedRowIds:r.expandedRowIds,expandedGroupIds:r.expandedGroupIds});if(!s||!Array.isArray(r.columns)||!Array.isArray(r.sortModel))return f(t,{code:"INVALID_STATE",path:"state"}),{state:null,report:t};if(r.version===1&&!Re(r))return{state:null,report:[{code:"INVALID_STATE",path:"state"}]};r.version===1&&f(t,{code:"VERSION_MIGRATED",path:"version",from:"1",to:"2"});let c={report:t,resolve:o,types:i,ancestors:new WeakSet,nodes:0,filterItems:1e4,filterCharacters:64e3};for(let p of["columns","sortModel"])r[p].length!==s[p].length&&f(t,{code:"NORMALIZED",path:p});return s.columns=V(s.columns,"columns",c),s.sortModel=V(s.sortModel,"sortModel",c),s.filterModel=Te(r,c),s.advancedFilterModel=we(r,c),{state:s,report:t}}var Ge=64,ke=64;function I(){let e=new Error("[MachTable] Preference operation no longer belongs to the current identity.");return e.name="AbortError",e}function E(e){return typeof e=="string"&&e.length<=512&&e.trim().length>0}function Fe(e){if(e==null)return null;let{tenantId:n,userId:t,pageId:r,schemaId:o}=e;if(![n,t,r,o].every(E))throw new TypeError("[MachTable] Invalid preference identity.");return Object.freeze({tenantId:n,userId:t,pageId:r,schemaId:o})}function Ce(e){return e?JSON.stringify([e.tenantId,e.userId,e.pageId,e.schemaId]):""}function K(e,n){return new Promise((t,r)=>{let o=()=>r(I());if(e.then(t,r).finally(()=>n.removeEventListener("abort",o)),n.aborted){r(I());return}n.addEventListener("abort",o,{once:!0})})}function v(e){let n=Promise.reject(e instanceof Error?e:new Error(String(e)));return n.catch(()=>{}),n}function Q(e){let n={columns:[...e.columns],renameColumns:{...e.renameColumns},columnTypes:{...e.columnTypes}};b(null,n);let t=null,r=!1,o=()=>{if(r)throw I();let l=Fe(e.identity()),d=Ce(l);if(t?.fingerprint===d)return t;if(t)throw r=!0,t.controller.abort(),t.keys.clear(),t=null,I();return t=l?{identity:l,fingerprint:d,controller:new AbortController,keys:new Map}:null,t},i=l=>{if(r||l.controller.signal.aborted||o()!==l)throw I()},s=(l,d)=>{if(!E(d))throw new TypeError("[MachTable] Invalid preference table key.");let u=l.keys.get(d);if(u)return l.keys.delete(d),l.keys.set(d,u),u;if(l.keys.size>=Ge){let m=[...l.keys].find(([,R])=>R.pending===0);if(!m)throw new RangeError("[MachTable] Too many active preference keys (maximum 64).");l.keys.delete(m[0])}let a={tail:Promise.resolve(),pending:0,revision:void 0};return l.keys.set(d,a),a},c=(l,d,u)=>{let a;try{if(a=s(l,d),a.pending>=ke)throw new RangeError("[MachTable] Too many pending preference operations for one key (maximum 64).")}catch(R){return v(R)}a.pending++;let m=a.tail.then(()=>(i(l),u(a)));return a.tail=m.then(()=>{},()=>{}).finally(()=>{a.pending--}),m},p=(l,d)=>({identity:l.identity,key:d,signal:l.controller.signal}),y=async(l,d,u)=>{i(l);let a=await K(Promise.resolve().then(()=>(i(l),e.load(p(l,d)))),l.controller.signal);if(i(l),a!=null&&!E(a.revision))throw new TypeError("[MachTable] Preference transport returned an invalid revision.");return u.revision=a?.revision??null,a},h=(l,d,u)=>{let a=b(l,n);if(a.report.length)try{e.onMigration?.(a,p(d,u))}catch{}return a},M=async(l,d,u,a)=>{a.revision===void 0&&await y(l,d,a),i(l);let m=await K(Promise.resolve().then(()=>(i(l),e.save({...p(l,d),state:u,expectedRevision:a.revision??null}))),l.controller.signal);if(i(l),!m||!E(m.revision))throw new TypeError("[MachTable] Preference save must return its committed revision.");a.revision=m.revision};return o(),{load(l){try{let d=o();return d?c(d,l,async u=>{let a=await y(d,l,u),m=a?h(a.state,d,l).state:null;return i(d),m}).catch(u=>{if(u?.name==="AbortError")return null;throw u}):Promise.resolve(null)}catch(d){return v(d)}},save(l,d){try{let u=o();if(!u)return v(I());let a=h(d,u,l).state;return a?c(u,l,m=>M(u,l,a,m)):v(new TypeError("[MachTable] Cannot save invalid grid preferences."))}catch(u){return v(u)}},dispose(){r||(r=!0,t?.controller.abort(),t?.keys.clear(),t=null)}}}var T=class extends Error{constructor(n,t){super("[MachTable] Grid preference revision conflict; reload and review before saving again."),this.name="GridPreferenceConflictError",this.expectedRevision=n,this.actualRevision=t}};0&&(module.exports={GridPreferenceConflictError,createGridPreferenceStore,migrateGridState});
1
+ "use strict";var k=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var J=Object.prototype.hasOwnProperty;var ee=(e,n)=>{for(var r in n)k(e,r,{get:n[r],enumerable:!0})},ne=(e,n,r,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Z(n))!J.call(e,o)&&o!==r&&k(e,o,{get:()=>n[o],enumerable:!(t=Y(n,o))||t.enumerable});return e};var te=e=>ne(k({},"__esModule",{value:!0}),e);var Le={};ee(Le,{GridPreferenceConflictError:()=>T,createGridPreferenceStore:()=>B,migrateGridState:()=>v});module.exports=te(Le);var R={text:["contains","notContains","equals","notEquals","startsWith","endsWith","blank","notBlank"],number:["equals","notEquals","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","inRange","blank","notBlank"],date:["equals","notEquals","lessThan","greaterThan","inRange","blank","notBlank"]};var re=16,oe=512,ie=20,se=2e3,le=2e3,ae={text:new Set(R.text),number:new Set(R.number),date:new Set(R.date)};function de(e){return e==null||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function ue(e,n,r){if(e==null||typeof e!="object")return null;let t=e;return typeof t.match!="string"||!r.has(t.match)?null:{match:t.match,...ce(t,n)}}function ce(e,n){let r=n==="number"?_(e.value):typeof e.value=="string"?e.value:void 0,t=n==="number"?_(e.value2):typeof e.value2=="string"?e.value2:void 0;return{...r!==void 0?{value:r}:{},...t!==void 0?{value2:t}:{}}}function _(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function fe(e,n){let r=[],t=ae[n];for(let o of e.slice(0,ie)){let i=ue(o,n,t);i&&r.push(i)}return r}function E(e){if(e==null||typeof e!="object")return null;let n=e;return n.type==="set"?Array.isArray(n.values)?{type:"set",values:n.values.filter(de).slice(0,se)}:null:n.type!=="text"&&n.type!=="number"&&n.type!=="date"||!Array.isArray(n.conditions)?null:{type:n.type,...n.operator==="or"||n.operator==="and"?{operator:n.operator}:{},conditions:fe(n.conditions,n.type)}}function pe(e,n){if(typeof e.colId!="string"||!e.colId.trim())return null;let r=e.colId.trim();if(n.validColumnIds?.has(r)===!1)return null;let t=E(e.filter);return t?{kind:"condition",colId:r,filter:t}:null}function me(e,n,r){if(!Array.isArray(e.children))return null;let t=[];for(let o of e.children){let i=N(o,n+1,r);i&&t.push(i)}return t.length===0?null:{kind:"group",operator:e.operator==="or"?"or":"and",children:t,...e.not===!0?{not:!0}:{}}}function ge(e,n,r){return n<=re&&r.nodes<oe&&e!=null&&typeof e=="object"}function N(e,n,r){if(!ge(e,n,r)||r.ancestors.has(e))return null;r.ancestors.add(e),r.nodes++;let t=e,o=t.kind==="condition"?pe(t,r):t.kind==="group"?me(t,n,r):null;return r.ancestors.delete(e),o}function x(e,n){if(e==null||typeof e!="object")return null;let r=e;if(r.version!==1||r.root==null)return null;let t=N(r.root,0,{ancestors:new WeakSet,nodes:0,validColumnIds:n});return t?{version:1,root:t}:null}function O(e,n){if(e==null||typeof e!="object"||Array.isArray(e))return{};let r={};for(let[t,o]of Object.entries(e).slice(0,le)){let i=t.trim();if(!i||n?.has(i)===!1)continue;let l=E(o);l&&(r[i]=l)}return r}var D="group:";var j=2e3,F=1e5,S=512,Me=1e4;function L(e){return Array.isArray(e)?[...new Set(e.slice(0,F).filter(n=>typeof n=="string"&&n.length>0&&n.length<=S))]:[]}function Ie(e){if(!Array.isArray(e))return[];let n=new Set,r=F*S;for(let t of e.slice(0,F)){if(typeof t!="string"||!t.length||n.has(t))continue;let o=t.startsWith(D)?65536:S;t.length>o||t.length>r||(n.add(t),r-=t.length)}return[...n]}function q(e,n){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):n}function z(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function he(e,n){let r=z(n.flex);for(let t of["width","contentWidth"]){let o=z(n[t]);o!==void 0&&(e[t]=o)}n.flex===null?e.flex=null:r!==void 0&&(e.flex=r),(n.widthMode==="auto"||n.widthMode==="manual")&&(e.widthMode=n.widthMode)}function Se(e,n){typeof n.hide=="boolean"&&(e.hide=n.hide),(n.pinned===null||n.pinned==="left"||n.pinned==="right")&&(e.pinned=n.pinned)}function be(e,n){if(e==null||typeof e!="object")return null;let r=e,t=typeof r.colId=="string"?r.colId.trim():"";if(!t||t.length>S||n.has(t))return null;n.add(t);let o={colId:t};return Se(o,r),he(o,r),o}function ve(e){if(!Array.isArray(e))return[];let n=[],r=new Set;for(let t of e.slice(0,j)){let o=be(t,r);o&&n.push(o)}return n}function Ae(e){if(!Array.isArray(e))return[];let n=[],r=new Set;for(let t of e.slice(0,j)){if(t==null||typeof t!="object")continue;let o=t,i=typeof o.colId=="string"?o.colId.trim():"";!i||i.length>S||r.has(i)||o.direction!=="asc"&&o.direction!=="desc"||(r.add(i),n.push({colId:i,direction:o.direction}))}return n}function V(e){if(e==null||typeof e!="object")return null;let n=e;if(n.version!==2||!Array.isArray(n.columns)||!Array.isArray(n.sortModel))return null;let r=n.pagination!=null&&typeof n.pagination=="object"?n.pagination:{};return{version:2,columns:ve(n.columns),sortModel:Ae(n.sortModel),filterModel:O(n.filterModel),advancedFilterModel:x(n.advancedFilterModel),quickFilterText:typeof n.quickFilterText=="string"&&n.quickFilterText.trim()?n.quickFilterText.slice(0,Me):null,pagination:{enabled:r.enabled===!0,page:q(r.page,1),pageSize:q(r.pageSize,20)},selectedRowIds:L(n.selectedRowIds),expandedRowIds:L(n.expandedRowIds),expandedGroupIds:Ie(n.expandedGroupIds)}}var b=2e3,U=256,P=512;function g(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:null}function C(e){return typeof e=="string"&&e.length<=512&&e.trim().length>0&&!["__proto__","prototype","constructor"].includes(e)}function f(e,n){e.length<U-1?e.push(n):e.length===U-1&&e.push({code:"LIMIT_EXCEEDED",path:"report"})}function Re(e,n){if(e.columns.length>b||e.columns.some(o=>!C(o)||o!==o.trim()))throw new TypeError("[MachTable] Preference columns must contain at most 2000 valid stable IDs.");let r=new Set(e.columns);if(r.size!==e.columns.length)throw new TypeError("[MachTable] Preference column IDs must be unique.");let t=new Map(Object.entries(e.renameColumns??{}));if(t.size>b||[...t].some(([o,i])=>!C(o)||!r.has(i)))throw new TypeError("[MachTable] Preference rename targets must identify current columns.");return(o,i)=>{if(!C(o))return f(n,{code:"REMOVED_COLUMN",path:i}),null;let l=o.trim(),c=t.get(l)??l;return r.has(c)?(l!==c&&f(n,{code:"RENAMED_COLUMN",path:i,from:l,to:c}),c):(f(n,{code:"REMOVED_COLUMN",path:i,from:l}),null)}}function Ee(e){let n=Object.entries(e.columnTypes??{}),r=new Set(e.columns);if(n.length>b||n.some(([t,o])=>!r.has(t)||!["text","number","date","set",!1].includes(o)))throw new TypeError("[MachTable] Preference filter types must identify current columns and supported types.");return new Map(n)}function we(e,n){return n.match==="blank"||n.match==="notBlank"?!0:e==="number"?typeof n.value!="number"||!Number.isFinite(n.value)?!1:n.match!=="inRange"||typeof n.value2=="number"&&Number.isFinite(n.value2)&&n.value2>=n.value:typeof n.value!="string"?!1:e==="text"?!0:Number.isFinite(Date.parse(n.value))?n.match!=="inRange"||typeof n.value2=="string"&&Number.isFinite(Date.parse(n.value2))&&Date.parse(n.value2)>=Date.parse(n.value):!1}function Te(e,n){let r=typeof e=="string"?e.length:0;return r>1024||n.filterCharacters<r?!1:(n.filterCharacters-=r,!0)}function X(e,n){return n.filterItems<=0?!1:(n.filterItems--,e.every(r=>Te(r,n)))}function Ge(e){let n=g(e);return n?.operator!==void 0&&n.operator!=="and"&&n.operator!=="or"?null:E(n&&{type:n.type,operator:n.operator,values:Array.isArray(n.values)?n.values.slice(0,2e3):void 0,conditions:Array.isArray(n.conditions)?n.conditions.slice(0,20):void 0})}function W(e,n,r,t){let o=t.report;if(t.filterItems<=0)return f(o,{code:"LIMIT_EXCEEDED",path:r}),null;let i=Ge(e);if(!i)return f(o,{code:"INVALID_FILTER",path:r}),null;let l=t.types.get(n);if(l!==void 0&&l!==i.type)return f(o,{code:"TYPE_CHANGED",path:r,from:i.type,to:l===!1?"disabled":l}),null;if(i.type==="set"){let y=i.values.filter(M=>(M===null||typeof M=="string"||typeof M=="number")&&X([M],t)),h=g(e)?.values;return Array.isArray(h)&&h.length!==y.length&&f(o,{code:"NORMALIZED",path:r}),{type:"set",values:y}}let c=i.conditions.filter(y=>X(Object.values(y),t)&&we(i.type,y)),p=g(e)?.conditions;return Array.isArray(p)&&p.length!==c.length&&f(o,{code:"INVALID_FILTER",path:r}),c.length?{...i,conditions:c}:null}function ke(e,n,r){let t=r.resolve(e.colId,`${n}.colId`);if(!t)return null;let o=W(e.filter,t,`${n}.filter`,r);return o?{kind:"condition",colId:t,filter:o}:null}function Fe(e,n,r,t){if(!Array.isArray(e.children)||!["and","or"].includes(e.operator))return f(t.report,{code:"INVALID_FILTER",path:n}),null;let o=[];for(let i=0;i<Math.min(e.children.length,P);i++){let l=Q(e.children[i],`${n}.children[${i}]`,r+1,t);l&&o.push(l)}return e.children.length>P&&f(t.report,{code:"LIMIT_EXCEEDED",path:n}),o.length?{kind:"group",operator:e.operator,children:o,...e.not===!0?{not:!0}:{}}:null}function Q(e,n,r,t){let o=g(e);if(!o||r>16||t.nodes>=P||t.ancestors.has(o))return f(t.report,{code:"LIMIT_EXCEEDED",path:n}),null;t.nodes++,t.ancestors.add(o);let i=null;return o.kind==="condition"?i=ke(o,n,t):o.kind==="group"?i=Fe(o,n,r,t):f(t.report,{code:"INVALID_FILTER",path:n}),t.ancestors.delete(o),i}function H(e,n,r){let t=new Set;return e.flatMap((o,i)=>{let l=r.resolve(o.colId,`${n}[${i}]`);return l?t.has(l)?(f(r.report,{code:"DUPLICATE_COLUMN",path:n,from:o.colId,to:l}),[]):(t.add(l),[{...o,colId:l}]):[]})}function Ce(e,n){let r=g(e.filterModel),t=Object.create(null);if(!r)return t;let o=0;for(let i in r){if(!Object.prototype.hasOwnProperty.call(r,i))continue;if(o++>=b){f(n.report,{code:"LIMIT_EXCEEDED",path:"filterModel"});break}let l=`filterModel.${i.slice(0,512)}`,c=n.resolve(i,l);if(!c)continue;if(Object.prototype.hasOwnProperty.call(t,c)){f(n.report,{code:"DUPLICATE_COLUMN",path:"filterModel",from:i,to:c});continue}let p=W(r[i],c,l,n);p&&(t[c]=p)}return t}function Pe(e){let n=g(e.pagination);return g(e.filterModel)!==null&&n!==null&&typeof n.enabled=="boolean"&&typeof n.page=="number"&&typeof n.pageSize=="number"&&(e.quickFilterText===null||typeof e.quickFilterText=="string")&&[e.selectedRowIds,e.expandedRowIds,e.expandedGroupIds].every(Array.isArray)}function _e(e,n){if(e.version!==2||e.advancedFilterModel==null)return null;let r=g(e.advancedFilterModel);if(r?.version!==1)return f(n.report,{code:"INVALID_FILTER",path:"advancedFilterModel"}),null;let t=Q(r.root,"advancedFilterModel.root",0,n);return t?{version:1,root:t}:null}function K(e){return Array.isArray(e)?e.slice(0,b).filter(n=>{let r=g(n)?.colId;return typeof r!="string"||r.length<=512}):e}function v(e,n){let r=[],t=g(e),o=Re(n,r),i=Ee(n);if(!t||![1,2].includes(t.version))return f(r,{code:"UNSUPPORTED_VERSION",path:"version"}),{state:null,report:r};let l=V({version:2,columns:K(t.columns),sortModel:K(t.sortModel),filterModel:{},advancedFilterModel:null,quickFilterText:typeof t.quickFilterText=="string"?t.quickFilterText.slice(0,1e4):t.quickFilterText,pagination:t.pagination,selectedRowIds:t.selectedRowIds,expandedRowIds:t.expandedRowIds,expandedGroupIds:t.expandedGroupIds});if(!l||!Array.isArray(t.columns)||!Array.isArray(t.sortModel))return f(r,{code:"INVALID_STATE",path:"state"}),{state:null,report:r};if(t.version===1&&!Pe(t))return{state:null,report:[{code:"INVALID_STATE",path:"state"}]};t.version===1&&f(r,{code:"VERSION_MIGRATED",path:"version",from:"1",to:"2"});let c={report:r,resolve:o,types:i,ancestors:new WeakSet,nodes:0,filterItems:1e4,filterCharacters:64e3};for(let p of["columns","sortModel"])t[p].length!==l[p].length&&f(r,{code:"NORMALIZED",path:p});return l.columns=H(l.columns,"columns",c),l.sortModel=H(l.sortModel,"sortModel",c),l.filterModel=Ce(t,c),l.advancedFilterModel=_e(t,c),{state:l,report:r}}var Ne=64,xe=64;function I(){let e=new Error("[MachTable] Preference operation no longer belongs to the current identity.");return e.name="AbortError",e}function w(e){return typeof e=="string"&&e.length<=512&&e.trim().length>0}function Oe(e){if(e==null)return null;let{tenantId:n,userId:r,pageId:t,schemaId:o}=e;if(![n,r,t,o].every(w))throw new TypeError("[MachTable] Invalid preference identity.");return Object.freeze({tenantId:n,userId:r,pageId:t,schemaId:o})}function De(e){return e?JSON.stringify([e.tenantId,e.userId,e.pageId,e.schemaId]):""}function $(e,n){return new Promise((r,t)=>{let o=()=>t(I());if(e.then(r,t).finally(()=>n.removeEventListener("abort",o)),n.aborted){t(I());return}n.addEventListener("abort",o,{once:!0})})}function A(e){let n=Promise.reject(e instanceof Error?e:new Error(String(e)));return n.catch(()=>{}),n}function B(e){let n={columns:[...e.columns],renameColumns:{...e.renameColumns},columnTypes:{...e.columnTypes}};v(null,n);let r=null,t=!1,o=()=>{if(t)throw I();let s=Oe(e.identity()),d=De(s);if(r?.fingerprint===d)return r;if(r)throw t=!0,r.controller.abort(),r.keys.clear(),r=null,I();return r=s?{identity:s,fingerprint:d,controller:new AbortController,keys:new Map}:null,r},i=s=>{if(t||s.controller.signal.aborted||o()!==s)throw I()},l=(s,d)=>{if(!w(d))throw new TypeError("[MachTable] Invalid preference table key.");let u=s.keys.get(d);if(u)return s.keys.delete(d),s.keys.set(d,u),u;if(s.keys.size>=Ne){let m=[...s.keys].find(([,G])=>G.pending===0);if(!m)throw new RangeError("[MachTable] Too many active preference keys (maximum 64).");s.keys.delete(m[0])}let a={tail:Promise.resolve(),pending:0,revision:void 0};return s.keys.set(d,a),a},c=(s,d,u)=>{let a;try{if(a=l(s,d),a.pending>=xe)throw new RangeError("[MachTable] Too many pending preference operations for one key (maximum 64).")}catch(G){return A(G)}a.pending++;let m=a.tail.then(()=>(i(s),u(a)));return a.tail=m.then(()=>{},()=>{}).finally(()=>{a.pending--}),m},p=(s,d)=>({identity:s.identity,key:d,signal:s.controller.signal}),y=async(s,d,u)=>{i(s);let a=await $(Promise.resolve().then(()=>(i(s),e.load(p(s,d)))),s.controller.signal);if(i(s),a!=null&&!w(a.revision))throw new TypeError("[MachTable] Preference transport returned an invalid revision.");return u.revision=a?.revision??null,a},h=(s,d,u)=>{let a=v(s,n);if(a.report.length)try{e.onMigration?.(a,p(d,u))}catch{}return a},M=async(s,d,u,a)=>{a.revision===void 0&&await y(s,d,a),i(s);let m=await $(Promise.resolve().then(()=>(i(s),e.save({...p(s,d),state:u,expectedRevision:a.revision??null}))),s.controller.signal);if(i(s),!m||!w(m.revision))throw new TypeError("[MachTable] Preference save must return its committed revision.");a.revision=m.revision};return o(),{load(s){try{let d=o();return d?c(d,s,async u=>{let a=await y(d,s,u),m=a?h(a.state,d,s).state:null;return i(d),m}).catch(u=>{if(u?.name==="AbortError")return null;throw u}):Promise.resolve(null)}catch(d){return A(d)}},save(s,d){try{let u=o();if(!u)return A(I());let a=h(d,u,s).state;return a?c(u,s,m=>M(u,s,a,m)):A(new TypeError("[MachTable] Cannot save invalid grid preferences."))}catch(u){return A(u)}},dispose(){t||(t=!0,r?.controller.abort(),r?.keys.clear(),r=null)}}}var T=class extends Error{constructor(n,r){super("[MachTable] Grid preference revision conflict; reload and review before saving again."),this.name="GridPreferenceConflictError",this.expectedRevision=n,this.actualRevision=r}};0&&(module.exports={GridPreferenceConflictError,createGridPreferenceStore,migrateGridState});
@@ -1,4 +1,4 @@
1
- import { f as GridState, g as GridStateStore, F as FilterType } from './api-pOhyuSQk.cjs';
1
+ import { f as GridState, g as GridStateStore, F as FilterType } from './api-CZkd8tYy.cjs';
2
2
 
3
3
  interface GridStateMigrationOptions {
4
4
  /** Current stable column IDs; removed IDs are not restored. */
@@ -1,4 +1,4 @@
1
- import { f as GridState, g as GridStateStore, F as FilterType } from './api-pOhyuSQk.js';
1
+ import { f as GridState, g as GridStateStore, F as FilterType } from './api-CZkd8tYy.js';
2
2
 
3
3
  interface GridStateMigrationOptions {
4
4
  /** Current stable column IDs; removed IDs are not restored. */
@@ -1 +1 @@
1
- var K=new Set(["contains","notContains","equals","notEquals","startsWith","endsWith","blank","notBlank"]),Q=new Set(["equals","notEquals","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","inRange","blank","notBlank"]),W=new Set(["equals","notEquals","lessThan","greaterThan","inRange","blank","notBlank"]);function $(e){return e==null||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function B(e){return e==="text"?K:e==="number"?Q:W}function Y(e,n,t){if(e==null||typeof e!="object")return null;let r=e;return typeof r.match!="string"||!t.has(r.match)?null:{match:r.match,...Z(r,n)}}function Z(e,n){let t=n==="number"?C(e.value):typeof e.value=="string"?e.value:void 0,r=n==="number"?C(e.value2):typeof e.value2=="string"?e.value2:void 0;return{...t!==void 0?{value:t}:{},...r!==void 0?{value2:r}:{}}}function C(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function J(e,n){let t=[],r=B(n);for(let o of e.slice(0,20)){let i=Y(o,n,r);i&&t.push(i)}return t}function v(e){if(e==null||typeof e!="object")return null;let n=e;return n.type==="set"?Array.isArray(n.values)?{type:"set",values:n.values.filter($).slice(0,2e3)}:null:n.type!=="text"&&n.type!=="number"&&n.type!=="date"||!Array.isArray(n.conditions)?null:{type:n.type,...n.operator==="or"||n.operator==="and"?{operator:n.operator}:{},conditions:J(n.conditions,n.type)}}function ee(e,n){if(typeof e.colId!="string"||!e.colId.trim())return null;let t=e.colId.trim();if(n.validColumnIds?.has(t)===!1)return null;let r=v(e.filter);return r?{kind:"condition",colId:t,filter:r}:null}function ne(e,n,t){if(!Array.isArray(e.children))return null;let r=[];for(let o of e.children){let i=N(o,n+1,t);i&&r.push(i)}return r.length===0?null:{kind:"group",operator:e.operator==="or"?"or":"and",children:r,...e.not===!0?{not:!0}:{}}}function te(e,n,t){return n<=16&&t.nodes<512&&e!=null&&typeof e=="object"}function N(e,n,t){if(!te(e,n,t)||t.ancestors.has(e))return null;t.ancestors.add(e),t.nodes++;let r=e,o=r.kind==="condition"?ee(r,t):r.kind==="group"?ne(r,n,t):null;return t.ancestors.delete(e),o}function P(e,n){if(e==null||typeof e!="object")return null;let t=e;if(t.version!==1||t.root==null)return null;let r=N(t.root,0,{ancestors:new WeakSet,nodes:0,validColumnIds:n});return r?{version:1,root:r}:null}function _(e,n){if(e==null||typeof e!="object"||Array.isArray(e))return{};let t={};for(let[r,o]of Object.entries(e).slice(0,2e3)){let i=r.trim();if(!i||n?.has(i)===!1)continue;let s=v(o);s&&(t[i]=s)}return t}var D=2e3,re=1e5,w=512,oe=1e4;function R(e){return Array.isArray(e)?[...new Set(e.slice(0,re).filter(n=>typeof n=="string"&&n.length>0&&n.length<=w))]:[]}function O(e,n){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):n}function x(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function ie(e,n){let t=x(n.flex);for(let r of["width","contentWidth"]){let o=x(n[r]);o!==void 0&&(e[r]=o)}n.flex===null?e.flex=null:t!==void 0&&(e.flex=t),(n.widthMode==="auto"||n.widthMode==="manual")&&(e.widthMode=n.widthMode)}function le(e,n){typeof n.hide=="boolean"&&(e.hide=n.hide),(n.pinned===null||n.pinned==="left"||n.pinned==="right")&&(e.pinned=n.pinned)}function se(e,n){if(e==null||typeof e!="object")return null;let t=e,r=typeof t.colId=="string"?t.colId.trim():"";if(!r||r.length>w||n.has(r))return null;n.add(r);let o={colId:r};return le(o,t),ie(o,t),o}function ae(e){if(!Array.isArray(e))return[];let n=[],t=new Set;for(let r of e.slice(0,D)){let o=se(r,t);o&&n.push(o)}return n}function de(e){if(!Array.isArray(e))return[];let n=[],t=new Set;for(let r of e.slice(0,D)){if(r==null||typeof r!="object")continue;let o=r,i=typeof o.colId=="string"?o.colId.trim():"";!i||i.length>w||t.has(i)||o.direction!=="asc"&&o.direction!=="desc"||(t.add(i),n.push({colId:i,direction:o.direction}))}return n}function L(e){if(e==null||typeof e!="object")return null;let n=e;if(n.version!==2||!Array.isArray(n.columns)||!Array.isArray(n.sortModel))return null;let t=n.pagination!=null&&typeof n.pagination=="object"?n.pagination:{};return{version:2,columns:ae(n.columns),sortModel:de(n.sortModel),filterModel:_(n.filterModel),advancedFilterModel:P(n.advancedFilterModel),quickFilterText:typeof n.quickFilterText=="string"&&n.quickFilterText.trim()?n.quickFilterText.slice(0,oe):null,pagination:{enabled:t.enabled===!0,page:O(t.page,1),pageSize:O(t.pageSize,20)},selectedRowIds:R(n.selectedRowIds),expandedRowIds:R(n.expandedRowIds),expandedGroupIds:R(n.expandedGroupIds)}}var S=2e3,q=256,k=512;function g(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:null}function G(e){return typeof e=="string"&&e.length<=512&&e.trim().length>0&&!["__proto__","prototype","constructor"].includes(e)}function f(e,n){e.length<q-1?e.push(n):e.length===q-1&&e.push({code:"LIMIT_EXCEEDED",path:"report"})}function ue(e,n){if(e.columns.length>S||e.columns.some(o=>!G(o)||o!==o.trim()))throw new TypeError("[MachTable] Preference columns must contain at most 2000 valid stable IDs.");let t=new Set(e.columns);if(t.size!==e.columns.length)throw new TypeError("[MachTable] Preference column IDs must be unique.");let r=new Map(Object.entries(e.renameColumns??{}));if(r.size>S||[...r].some(([o,i])=>!G(o)||!t.has(i)))throw new TypeError("[MachTable] Preference rename targets must identify current columns.");return(o,i)=>{if(!G(o))return f(n,{code:"REMOVED_COLUMN",path:i}),null;let s=o.trim(),c=r.get(s)??s;return t.has(c)?(s!==c&&f(n,{code:"RENAMED_COLUMN",path:i,from:s,to:c}),c):(f(n,{code:"REMOVED_COLUMN",path:i,from:s}),null)}}function ce(e){let n=Object.entries(e.columnTypes??{}),t=new Set(e.columns);if(n.length>S||n.some(([r,o])=>!t.has(r)||!["text","number","date","set",!1].includes(o)))throw new TypeError("[MachTable] Preference filter types must identify current columns and supported types.");return new Map(n)}function fe(e,n){return n.match==="blank"||n.match==="notBlank"?!0:e==="number"?typeof n.value!="number"||!Number.isFinite(n.value)?!1:n.match!=="inRange"||typeof n.value2=="number"&&Number.isFinite(n.value2)&&n.value2>=n.value:typeof n.value!="string"?!1:e==="text"?!0:Number.isFinite(Date.parse(n.value))?n.match!=="inRange"||typeof n.value2=="string"&&Number.isFinite(Date.parse(n.value2))&&Date.parse(n.value2)>=Date.parse(n.value):!1}function pe(e,n){let t=typeof e=="string"?e.length:0;return t>1024||n.filterCharacters<t?!1:(n.filterCharacters-=t,!0)}function z(e,n){return n.filterItems<=0?!1:(n.filterItems--,e.every(t=>pe(t,n)))}function me(e){let n=g(e);return n?.operator!==void 0&&n.operator!=="and"&&n.operator!=="or"?null:v(n&&{type:n.type,operator:n.operator,values:Array.isArray(n.values)?n.values.slice(0,2e3):void 0,conditions:Array.isArray(n.conditions)?n.conditions.slice(0,20):void 0})}function X(e,n,t,r){let o=r.report;if(r.filterItems<=0)return f(o,{code:"LIMIT_EXCEEDED",path:t}),null;let i=me(e);if(!i)return f(o,{code:"INVALID_FILTER",path:t}),null;let s=r.types.get(n);if(s!==void 0&&s!==i.type)return f(o,{code:"TYPE_CHANGED",path:t,from:i.type,to:s===!1?"disabled":s}),null;if(i.type==="set"){let y=i.values.filter(M=>(M===null||typeof M=="string"||typeof M=="number")&&z([M],r)),h=g(e)?.values;return Array.isArray(h)&&h.length!==y.length&&f(o,{code:"NORMALIZED",path:t}),{type:"set",values:y}}let c=i.conditions.filter(y=>z(Object.values(y),r)&&fe(i.type,y)),p=g(e)?.conditions;return Array.isArray(p)&&p.length!==c.length&&f(o,{code:"INVALID_FILTER",path:t}),c.length?{...i,conditions:c}:null}function ge(e,n,t){let r=t.resolve(e.colId,`${n}.colId`);if(!r)return null;let o=X(e.filter,r,`${n}.filter`,t);return o?{kind:"condition",colId:r,filter:o}:null}function ye(e,n,t,r){if(!Array.isArray(e.children)||!["and","or"].includes(e.operator))return f(r.report,{code:"INVALID_FILTER",path:n}),null;let o=[];for(let i=0;i<Math.min(e.children.length,k);i++){let s=U(e.children[i],`${n}.children[${i}]`,t+1,r);s&&o.push(s)}return e.children.length>k&&f(r.report,{code:"LIMIT_EXCEEDED",path:n}),o.length?{kind:"group",operator:e.operator,children:o,...e.not===!0?{not:!0}:{}}:null}function U(e,n,t,r){let o=g(e);if(!o||t>16||r.nodes>=k||r.ancestors.has(o))return f(r.report,{code:"LIMIT_EXCEEDED",path:n}),null;r.nodes++,r.ancestors.add(o);let i=null;return o.kind==="condition"?i=ge(o,n,r):o.kind==="group"?i=ye(o,n,t,r):f(r.report,{code:"INVALID_FILTER",path:n}),r.ancestors.delete(o),i}function j(e,n,t){let r=new Set;return e.flatMap((o,i)=>{let s=t.resolve(o.colId,`${n}[${i}]`);return s?r.has(s)?(f(t.report,{code:"DUPLICATE_COLUMN",path:n,from:o.colId,to:s}),[]):(r.add(s),[{...o,colId:s}]):[]})}function Me(e,n){let t=g(e.filterModel),r=Object.create(null);if(!t)return r;let o=0;for(let i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;if(o++>=S){f(n.report,{code:"LIMIT_EXCEEDED",path:"filterModel"});break}let s=`filterModel.${i.slice(0,512)}`,c=n.resolve(i,s);if(!c)continue;if(Object.prototype.hasOwnProperty.call(r,c)){f(n.report,{code:"DUPLICATE_COLUMN",path:"filterModel",from:i,to:c});continue}let p=X(t[i],c,s,n);p&&(r[c]=p)}return r}function Ie(e){let n=g(e.pagination);return g(e.filterModel)!==null&&n!==null&&typeof n.enabled=="boolean"&&typeof n.page=="number"&&typeof n.pageSize=="number"&&(e.quickFilterText===null||typeof e.quickFilterText=="string")&&[e.selectedRowIds,e.expandedRowIds,e.expandedGroupIds].every(Array.isArray)}function he(e,n){if(e.version!==2||e.advancedFilterModel==null)return null;let t=g(e.advancedFilterModel);if(t?.version!==1)return f(n.report,{code:"INVALID_FILTER",path:"advancedFilterModel"}),null;let r=U(t.root,"advancedFilterModel.root",0,n);return r?{version:1,root:r}:null}function V(e){return Array.isArray(e)?e.slice(0,S).filter(n=>{let t=g(n)?.colId;return typeof t!="string"||t.length<=512}):e}function A(e,n){let t=[],r=g(e),o=ue(n,t),i=ce(n);if(!r||![1,2].includes(r.version))return f(t,{code:"UNSUPPORTED_VERSION",path:"version"}),{state:null,report:t};let s=L({version:2,columns:V(r.columns),sortModel:V(r.sortModel),filterModel:{},advancedFilterModel:null,quickFilterText:typeof r.quickFilterText=="string"?r.quickFilterText.slice(0,1e4):r.quickFilterText,pagination:r.pagination,selectedRowIds:r.selectedRowIds,expandedRowIds:r.expandedRowIds,expandedGroupIds:r.expandedGroupIds});if(!s||!Array.isArray(r.columns)||!Array.isArray(r.sortModel))return f(t,{code:"INVALID_STATE",path:"state"}),{state:null,report:t};if(r.version===1&&!Ie(r))return{state:null,report:[{code:"INVALID_STATE",path:"state"}]};r.version===1&&f(t,{code:"VERSION_MIGRATED",path:"version",from:"1",to:"2"});let c={report:t,resolve:o,types:i,ancestors:new WeakSet,nodes:0,filterItems:1e4,filterCharacters:64e3};for(let p of["columns","sortModel"])r[p].length!==s[p].length&&f(t,{code:"NORMALIZED",path:p});return s.columns=j(s.columns,"columns",c),s.sortModel=j(s.sortModel,"sortModel",c),s.filterModel=Me(r,c),s.advancedFilterModel=he(r,c),{state:s,report:t}}var Se=64,be=64;function I(){let e=new Error("[MachTable] Preference operation no longer belongs to the current identity.");return e.name="AbortError",e}function E(e){return typeof e=="string"&&e.length<=512&&e.trim().length>0}function ve(e){if(e==null)return null;let{tenantId:n,userId:t,pageId:r,schemaId:o}=e;if(![n,t,r,o].every(E))throw new TypeError("[MachTable] Invalid preference identity.");return Object.freeze({tenantId:n,userId:t,pageId:r,schemaId:o})}function Ae(e){return e?JSON.stringify([e.tenantId,e.userId,e.pageId,e.schemaId]):""}function H(e,n){return new Promise((t,r)=>{let o=()=>r(I());if(e.then(t,r).finally(()=>n.removeEventListener("abort",o)),n.aborted){r(I());return}n.addEventListener("abort",o,{once:!0})})}function b(e){let n=Promise.reject(e instanceof Error?e:new Error(String(e)));return n.catch(()=>{}),n}function Ee(e){let n={columns:[...e.columns],renameColumns:{...e.renameColumns},columnTypes:{...e.columnTypes}};A(null,n);let t=null,r=!1,o=()=>{if(r)throw I();let l=ve(e.identity()),d=Ae(l);if(t?.fingerprint===d)return t;if(t)throw r=!0,t.controller.abort(),t.keys.clear(),t=null,I();return t=l?{identity:l,fingerprint:d,controller:new AbortController,keys:new Map}:null,t},i=l=>{if(r||l.controller.signal.aborted||o()!==l)throw I()},s=(l,d)=>{if(!E(d))throw new TypeError("[MachTable] Invalid preference table key.");let u=l.keys.get(d);if(u)return l.keys.delete(d),l.keys.set(d,u),u;if(l.keys.size>=Se){let m=[...l.keys].find(([,T])=>T.pending===0);if(!m)throw new RangeError("[MachTable] Too many active preference keys (maximum 64).");l.keys.delete(m[0])}let a={tail:Promise.resolve(),pending:0,revision:void 0};return l.keys.set(d,a),a},c=(l,d,u)=>{let a;try{if(a=s(l,d),a.pending>=be)throw new RangeError("[MachTable] Too many pending preference operations for one key (maximum 64).")}catch(T){return b(T)}a.pending++;let m=a.tail.then(()=>(i(l),u(a)));return a.tail=m.then(()=>{},()=>{}).finally(()=>{a.pending--}),m},p=(l,d)=>({identity:l.identity,key:d,signal:l.controller.signal}),y=async(l,d,u)=>{i(l);let a=await H(Promise.resolve().then(()=>(i(l),e.load(p(l,d)))),l.controller.signal);if(i(l),a!=null&&!E(a.revision))throw new TypeError("[MachTable] Preference transport returned an invalid revision.");return u.revision=a?.revision??null,a},h=(l,d,u)=>{let a=A(l,n);if(a.report.length)try{e.onMigration?.(a,p(d,u))}catch{}return a},M=async(l,d,u,a)=>{a.revision===void 0&&await y(l,d,a),i(l);let m=await H(Promise.resolve().then(()=>(i(l),e.save({...p(l,d),state:u,expectedRevision:a.revision??null}))),l.controller.signal);if(i(l),!m||!E(m.revision))throw new TypeError("[MachTable] Preference save must return its committed revision.");a.revision=m.revision};return o(),{load(l){try{let d=o();return d?c(d,l,async u=>{let a=await y(d,l,u),m=a?h(a.state,d,l).state:null;return i(d),m}).catch(u=>{if(u?.name==="AbortError")return null;throw u}):Promise.resolve(null)}catch(d){return b(d)}},save(l,d){try{let u=o();if(!u)return b(I());let a=h(d,u,l).state;return a?c(u,l,m=>M(u,l,a,m)):b(new TypeError("[MachTable] Cannot save invalid grid preferences."))}catch(u){return b(u)}},dispose(){r||(r=!0,t?.controller.abort(),t?.keys.clear(),t=null)}}}var F=class extends Error{constructor(n,t){super("[MachTable] Grid preference revision conflict; reload and review before saving again."),this.name="GridPreferenceConflictError",this.expectedRevision=n,this.actualRevision=t}};export{F as GridPreferenceConflictError,Ee as createGridPreferenceStore,A as migrateGridState};
1
+ var A={text:["contains","notContains","equals","notEquals","startsWith","endsWith","blank","notBlank"],number:["equals","notEquals","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","inRange","blank","notBlank"],date:["equals","notEquals","lessThan","greaterThan","inRange","blank","notBlank"]};var $=16,B=512,Y=20,Z=2e3,J=2e3,ee={text:new Set(A.text),number:new Set(A.number),date:new Set(A.date)};function ne(e){return e==null||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function te(e,n,r){if(e==null||typeof e!="object")return null;let t=e;return typeof t.match!="string"||!r.has(t.match)?null:{match:t.match,...re(t,n)}}function re(e,n){let r=n==="number"?P(e.value):typeof e.value=="string"?e.value:void 0,t=n==="number"?P(e.value2):typeof e.value2=="string"?e.value2:void 0;return{...r!==void 0?{value:r}:{},...t!==void 0?{value2:t}:{}}}function P(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function oe(e,n){let r=[],t=ee[n];for(let o of e.slice(0,Y)){let i=te(o,n,t);i&&r.push(i)}return r}function R(e){if(e==null||typeof e!="object")return null;let n=e;return n.type==="set"?Array.isArray(n.values)?{type:"set",values:n.values.filter(ne).slice(0,Z)}:null:n.type!=="text"&&n.type!=="number"&&n.type!=="date"||!Array.isArray(n.conditions)?null:{type:n.type,...n.operator==="or"||n.operator==="and"?{operator:n.operator}:{},conditions:oe(n.conditions,n.type)}}function ie(e,n){if(typeof e.colId!="string"||!e.colId.trim())return null;let r=e.colId.trim();if(n.validColumnIds?.has(r)===!1)return null;let t=R(e.filter);return t?{kind:"condition",colId:r,filter:t}:null}function se(e,n,r){if(!Array.isArray(e.children))return null;let t=[];for(let o of e.children){let i=_(o,n+1,r);i&&t.push(i)}return t.length===0?null:{kind:"group",operator:e.operator==="or"?"or":"and",children:t,...e.not===!0?{not:!0}:{}}}function le(e,n,r){return n<=$&&r.nodes<B&&e!=null&&typeof e=="object"}function _(e,n,r){if(!le(e,n,r)||r.ancestors.has(e))return null;r.ancestors.add(e),r.nodes++;let t=e,o=t.kind==="condition"?ie(t,r):t.kind==="group"?se(t,n,r):null;return r.ancestors.delete(e),o}function N(e,n){if(e==null||typeof e!="object")return null;let r=e;if(r.version!==1||r.root==null)return null;let t=_(r.root,0,{ancestors:new WeakSet,nodes:0,validColumnIds:n});return t?{version:1,root:t}:null}function x(e,n){if(e==null||typeof e!="object"||Array.isArray(e))return{};let r={};for(let[t,o]of Object.entries(e).slice(0,J)){let i=t.trim();if(!i||n?.has(i)===!1)continue;let l=R(o);l&&(r[i]=l)}return r}var O="group:";var z=2e3,G=1e5,S=512,de=1e4;function D(e){return Array.isArray(e)?[...new Set(e.slice(0,G).filter(n=>typeof n=="string"&&n.length>0&&n.length<=S))]:[]}function ue(e){if(!Array.isArray(e))return[];let n=new Set,r=G*S;for(let t of e.slice(0,G)){if(typeof t!="string"||!t.length||n.has(t))continue;let o=t.startsWith(O)?65536:S;t.length>o||t.length>r||(n.add(t),r-=t.length)}return[...n]}function L(e,n){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):n}function q(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function ce(e,n){let r=q(n.flex);for(let t of["width","contentWidth"]){let o=q(n[t]);o!==void 0&&(e[t]=o)}n.flex===null?e.flex=null:r!==void 0&&(e.flex=r),(n.widthMode==="auto"||n.widthMode==="manual")&&(e.widthMode=n.widthMode)}function fe(e,n){typeof n.hide=="boolean"&&(e.hide=n.hide),(n.pinned===null||n.pinned==="left"||n.pinned==="right")&&(e.pinned=n.pinned)}function pe(e,n){if(e==null||typeof e!="object")return null;let r=e,t=typeof r.colId=="string"?r.colId.trim():"";if(!t||t.length>S||n.has(t))return null;n.add(t);let o={colId:t};return fe(o,r),ce(o,r),o}function me(e){if(!Array.isArray(e))return[];let n=[],r=new Set;for(let t of e.slice(0,z)){let o=pe(t,r);o&&n.push(o)}return n}function ge(e){if(!Array.isArray(e))return[];let n=[],r=new Set;for(let t of e.slice(0,z)){if(t==null||typeof t!="object")continue;let o=t,i=typeof o.colId=="string"?o.colId.trim():"";!i||i.length>S||r.has(i)||o.direction!=="asc"&&o.direction!=="desc"||(r.add(i),n.push({colId:i,direction:o.direction}))}return n}function j(e){if(e==null||typeof e!="object")return null;let n=e;if(n.version!==2||!Array.isArray(n.columns)||!Array.isArray(n.sortModel))return null;let r=n.pagination!=null&&typeof n.pagination=="object"?n.pagination:{};return{version:2,columns:me(n.columns),sortModel:ge(n.sortModel),filterModel:x(n.filterModel),advancedFilterModel:N(n.advancedFilterModel),quickFilterText:typeof n.quickFilterText=="string"&&n.quickFilterText.trim()?n.quickFilterText.slice(0,de):null,pagination:{enabled:r.enabled===!0,page:L(r.page,1),pageSize:L(r.pageSize,20)},selectedRowIds:D(n.selectedRowIds),expandedRowIds:D(n.expandedRowIds),expandedGroupIds:ue(n.expandedGroupIds)}}var b=2e3,V=256,F=512;function g(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:null}function k(e){return typeof e=="string"&&e.length<=512&&e.trim().length>0&&!["__proto__","prototype","constructor"].includes(e)}function f(e,n){e.length<V-1?e.push(n):e.length===V-1&&e.push({code:"LIMIT_EXCEEDED",path:"report"})}function ye(e,n){if(e.columns.length>b||e.columns.some(o=>!k(o)||o!==o.trim()))throw new TypeError("[MachTable] Preference columns must contain at most 2000 valid stable IDs.");let r=new Set(e.columns);if(r.size!==e.columns.length)throw new TypeError("[MachTable] Preference column IDs must be unique.");let t=new Map(Object.entries(e.renameColumns??{}));if(t.size>b||[...t].some(([o,i])=>!k(o)||!r.has(i)))throw new TypeError("[MachTable] Preference rename targets must identify current columns.");return(o,i)=>{if(!k(o))return f(n,{code:"REMOVED_COLUMN",path:i}),null;let l=o.trim(),c=t.get(l)??l;return r.has(c)?(l!==c&&f(n,{code:"RENAMED_COLUMN",path:i,from:l,to:c}),c):(f(n,{code:"REMOVED_COLUMN",path:i,from:l}),null)}}function Me(e){let n=Object.entries(e.columnTypes??{}),r=new Set(e.columns);if(n.length>b||n.some(([t,o])=>!r.has(t)||!["text","number","date","set",!1].includes(o)))throw new TypeError("[MachTable] Preference filter types must identify current columns and supported types.");return new Map(n)}function Ie(e,n){return n.match==="blank"||n.match==="notBlank"?!0:e==="number"?typeof n.value!="number"||!Number.isFinite(n.value)?!1:n.match!=="inRange"||typeof n.value2=="number"&&Number.isFinite(n.value2)&&n.value2>=n.value:typeof n.value!="string"?!1:e==="text"?!0:Number.isFinite(Date.parse(n.value))?n.match!=="inRange"||typeof n.value2=="string"&&Number.isFinite(Date.parse(n.value2))&&Date.parse(n.value2)>=Date.parse(n.value):!1}function he(e,n){let r=typeof e=="string"?e.length:0;return r>1024||n.filterCharacters<r?!1:(n.filterCharacters-=r,!0)}function U(e,n){return n.filterItems<=0?!1:(n.filterItems--,e.every(r=>he(r,n)))}function Se(e){let n=g(e);return n?.operator!==void 0&&n.operator!=="and"&&n.operator!=="or"?null:R(n&&{type:n.type,operator:n.operator,values:Array.isArray(n.values)?n.values.slice(0,2e3):void 0,conditions:Array.isArray(n.conditions)?n.conditions.slice(0,20):void 0})}function K(e,n,r,t){let o=t.report;if(t.filterItems<=0)return f(o,{code:"LIMIT_EXCEEDED",path:r}),null;let i=Se(e);if(!i)return f(o,{code:"INVALID_FILTER",path:r}),null;let l=t.types.get(n);if(l!==void 0&&l!==i.type)return f(o,{code:"TYPE_CHANGED",path:r,from:i.type,to:l===!1?"disabled":l}),null;if(i.type==="set"){let y=i.values.filter(M=>(M===null||typeof M=="string"||typeof M=="number")&&U([M],t)),h=g(e)?.values;return Array.isArray(h)&&h.length!==y.length&&f(o,{code:"NORMALIZED",path:r}),{type:"set",values:y}}let c=i.conditions.filter(y=>U(Object.values(y),t)&&Ie(i.type,y)),p=g(e)?.conditions;return Array.isArray(p)&&p.length!==c.length&&f(o,{code:"INVALID_FILTER",path:r}),c.length?{...i,conditions:c}:null}function be(e,n,r){let t=r.resolve(e.colId,`${n}.colId`);if(!t)return null;let o=K(e.filter,t,`${n}.filter`,r);return o?{kind:"condition",colId:t,filter:o}:null}function ve(e,n,r,t){if(!Array.isArray(e.children)||!["and","or"].includes(e.operator))return f(t.report,{code:"INVALID_FILTER",path:n}),null;let o=[];for(let i=0;i<Math.min(e.children.length,F);i++){let l=W(e.children[i],`${n}.children[${i}]`,r+1,t);l&&o.push(l)}return e.children.length>F&&f(t.report,{code:"LIMIT_EXCEEDED",path:n}),o.length?{kind:"group",operator:e.operator,children:o,...e.not===!0?{not:!0}:{}}:null}function W(e,n,r,t){let o=g(e);if(!o||r>16||t.nodes>=F||t.ancestors.has(o))return f(t.report,{code:"LIMIT_EXCEEDED",path:n}),null;t.nodes++,t.ancestors.add(o);let i=null;return o.kind==="condition"?i=be(o,n,t):o.kind==="group"?i=ve(o,n,r,t):f(t.report,{code:"INVALID_FILTER",path:n}),t.ancestors.delete(o),i}function X(e,n,r){let t=new Set;return e.flatMap((o,i)=>{let l=r.resolve(o.colId,`${n}[${i}]`);return l?t.has(l)?(f(r.report,{code:"DUPLICATE_COLUMN",path:n,from:o.colId,to:l}),[]):(t.add(l),[{...o,colId:l}]):[]})}function Ae(e,n){let r=g(e.filterModel),t=Object.create(null);if(!r)return t;let o=0;for(let i in r){if(!Object.prototype.hasOwnProperty.call(r,i))continue;if(o++>=b){f(n.report,{code:"LIMIT_EXCEEDED",path:"filterModel"});break}let l=`filterModel.${i.slice(0,512)}`,c=n.resolve(i,l);if(!c)continue;if(Object.prototype.hasOwnProperty.call(t,c)){f(n.report,{code:"DUPLICATE_COLUMN",path:"filterModel",from:i,to:c});continue}let p=K(r[i],c,l,n);p&&(t[c]=p)}return t}function Re(e){let n=g(e.pagination);return g(e.filterModel)!==null&&n!==null&&typeof n.enabled=="boolean"&&typeof n.page=="number"&&typeof n.pageSize=="number"&&(e.quickFilterText===null||typeof e.quickFilterText=="string")&&[e.selectedRowIds,e.expandedRowIds,e.expandedGroupIds].every(Array.isArray)}function Ee(e,n){if(e.version!==2||e.advancedFilterModel==null)return null;let r=g(e.advancedFilterModel);if(r?.version!==1)return f(n.report,{code:"INVALID_FILTER",path:"advancedFilterModel"}),null;let t=W(r.root,"advancedFilterModel.root",0,n);return t?{version:1,root:t}:null}function H(e){return Array.isArray(e)?e.slice(0,b).filter(n=>{let r=g(n)?.colId;return typeof r!="string"||r.length<=512}):e}function E(e,n){let r=[],t=g(e),o=ye(n,r),i=Me(n);if(!t||![1,2].includes(t.version))return f(r,{code:"UNSUPPORTED_VERSION",path:"version"}),{state:null,report:r};let l=j({version:2,columns:H(t.columns),sortModel:H(t.sortModel),filterModel:{},advancedFilterModel:null,quickFilterText:typeof t.quickFilterText=="string"?t.quickFilterText.slice(0,1e4):t.quickFilterText,pagination:t.pagination,selectedRowIds:t.selectedRowIds,expandedRowIds:t.expandedRowIds,expandedGroupIds:t.expandedGroupIds});if(!l||!Array.isArray(t.columns)||!Array.isArray(t.sortModel))return f(r,{code:"INVALID_STATE",path:"state"}),{state:null,report:r};if(t.version===1&&!Re(t))return{state:null,report:[{code:"INVALID_STATE",path:"state"}]};t.version===1&&f(r,{code:"VERSION_MIGRATED",path:"version",from:"1",to:"2"});let c={report:r,resolve:o,types:i,ancestors:new WeakSet,nodes:0,filterItems:1e4,filterCharacters:64e3};for(let p of["columns","sortModel"])t[p].length!==l[p].length&&f(r,{code:"NORMALIZED",path:p});return l.columns=X(l.columns,"columns",c),l.sortModel=X(l.sortModel,"sortModel",c),l.filterModel=Ae(t,c),l.advancedFilterModel=Ee(t,c),{state:l,report:r}}var we=64,Te=64;function I(){let e=new Error("[MachTable] Preference operation no longer belongs to the current identity.");return e.name="AbortError",e}function w(e){return typeof e=="string"&&e.length<=512&&e.trim().length>0}function Ge(e){if(e==null)return null;let{tenantId:n,userId:r,pageId:t,schemaId:o}=e;if(![n,r,t,o].every(w))throw new TypeError("[MachTable] Invalid preference identity.");return Object.freeze({tenantId:n,userId:r,pageId:t,schemaId:o})}function ke(e){return e?JSON.stringify([e.tenantId,e.userId,e.pageId,e.schemaId]):""}function Q(e,n){return new Promise((r,t)=>{let o=()=>t(I());if(e.then(r,t).finally(()=>n.removeEventListener("abort",o)),n.aborted){t(I());return}n.addEventListener("abort",o,{once:!0})})}function v(e){let n=Promise.reject(e instanceof Error?e:new Error(String(e)));return n.catch(()=>{}),n}function Fe(e){let n={columns:[...e.columns],renameColumns:{...e.renameColumns},columnTypes:{...e.columnTypes}};E(null,n);let r=null,t=!1,o=()=>{if(t)throw I();let s=Ge(e.identity()),d=ke(s);if(r?.fingerprint===d)return r;if(r)throw t=!0,r.controller.abort(),r.keys.clear(),r=null,I();return r=s?{identity:s,fingerprint:d,controller:new AbortController,keys:new Map}:null,r},i=s=>{if(t||s.controller.signal.aborted||o()!==s)throw I()},l=(s,d)=>{if(!w(d))throw new TypeError("[MachTable] Invalid preference table key.");let u=s.keys.get(d);if(u)return s.keys.delete(d),s.keys.set(d,u),u;if(s.keys.size>=we){let m=[...s.keys].find(([,T])=>T.pending===0);if(!m)throw new RangeError("[MachTable] Too many active preference keys (maximum 64).");s.keys.delete(m[0])}let a={tail:Promise.resolve(),pending:0,revision:void 0};return s.keys.set(d,a),a},c=(s,d,u)=>{let a;try{if(a=l(s,d),a.pending>=Te)throw new RangeError("[MachTable] Too many pending preference operations for one key (maximum 64).")}catch(T){return v(T)}a.pending++;let m=a.tail.then(()=>(i(s),u(a)));return a.tail=m.then(()=>{},()=>{}).finally(()=>{a.pending--}),m},p=(s,d)=>({identity:s.identity,key:d,signal:s.controller.signal}),y=async(s,d,u)=>{i(s);let a=await Q(Promise.resolve().then(()=>(i(s),e.load(p(s,d)))),s.controller.signal);if(i(s),a!=null&&!w(a.revision))throw new TypeError("[MachTable] Preference transport returned an invalid revision.");return u.revision=a?.revision??null,a},h=(s,d,u)=>{let a=E(s,n);if(a.report.length)try{e.onMigration?.(a,p(d,u))}catch{}return a},M=async(s,d,u,a)=>{a.revision===void 0&&await y(s,d,a),i(s);let m=await Q(Promise.resolve().then(()=>(i(s),e.save({...p(s,d),state:u,expectedRevision:a.revision??null}))),s.controller.signal);if(i(s),!m||!w(m.revision))throw new TypeError("[MachTable] Preference save must return its committed revision.");a.revision=m.revision};return o(),{load(s){try{let d=o();return d?c(d,s,async u=>{let a=await y(d,s,u),m=a?h(a.state,d,s).state:null;return i(d),m}).catch(u=>{if(u?.name==="AbortError")return null;throw u}):Promise.resolve(null)}catch(d){return v(d)}},save(s,d){try{let u=o();if(!u)return v(I());let a=h(d,u,s).state;return a?c(u,s,m=>M(u,s,a,m)):v(new TypeError("[MachTable] Cannot save invalid grid preferences."))}catch(u){return v(u)}},dispose(){t||(t=!0,r?.controller.abort(),r?.keys.clear(),r=null)}}}var C=class extends Error{constructor(n,r){super("[MachTable] Grid preference revision conflict; reload and review before saving again."),this.name="GridPreferenceConflictError",this.expectedRevision=n,this.actualRevision=r}};export{C as GridPreferenceConflictError,Fe as createGridPreferenceStore,E as migrateGridState};