@agile-team/mach-table 0.34.2 → 0.35.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.
@@ -1,4 +1,4 @@
1
- import { G as GridFeature, a as GridCellRange } from './api-CUQtfQR4.cjs';
1
+ import { G as GridFeature, a as GridCellRange } from './api-QsIvYp7X.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-CUQtfQR4.js';
1
+ import { G as GridFeature, a as GridCellRange } from './api-QsIvYp7X.js';
2
2
 
3
3
  interface MultiRangeSelection extends GridFeature {
4
4
  getRanges(): GridCellRange[];
package/dist/ordering.cjs CHANGED
@@ -1 +1 @@
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
+ "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 d=n?We(a.row,s):[],w={...a,id:c,children:d};o.entries.push(w),o.byId.set(c,w),o.byRow.set(w.row,w),o.children.set(c,d);for(let f=d.length-1;f>=0;f--)i.push({row:d[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 le(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,d=n.canMove({row:a.row,previousParent:c,parent:s,target:o.row,intent:t});if(d===!1||typeof d=="string")throw new Error(typeof d=="string"?d:"[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=le(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(d=>d.id)),i=new Map;for(let d of e)i.has(d.parentId)||i.set(d.parentId,r.children.get(d.parentId).filter(w=>!o.has(r.byRow.get(w).id)));let s=i.get(t)??r.children.get(t),a=s.findIndex(d=>d===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(d=>d.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 le(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 d=s[a-1];if(!d)throw new Error("[MachTable] Row ordering cannot restore an isolated root.");return{rowIds:[i.id],targetId:n.byRow.get(d).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 d=i.byId.get(c),w=s.byId.get(c),f=w.parentId===null?null:i.byId.get(w.parentId).row,O=d.parentId===null?null:i.byId.get(d.parentId).row,S=n.canMove({row:d.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}=le(i,o.rowIds),c=Re(i,{moved:s,selected:a},o,t),d=je(i,s,c,o),w=Xe(r,i,d,t),f=Ve(o,s,d.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 de(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(),d=String(typeof e.rowKey=="function"?e.rowKey(s):V(s,e.rowKey));if(n.depths.has(d))throw new Error("[MachTable] Row ordering requires unique, acyclic row keys.");n.depths.set(d,c),n.siblings.get(a).push(d),n.siblings.set(d,[]),a!==null&&n.parents.set(d,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:d,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]),d=[...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:d,isSource:w,validate:()=>{for(let u of d){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:d,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,d.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.e=null;this.n=0;this.o=0;this.l=e=>{let t=this.e;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.u()}};this.m=()=>{if(this.n=0,!!this.e?.active){if(!this.current()){this.destroy();return}this.p(),this.y()&&this.u()}};this.d=e=>{let t=this.e;if(!(!t||e.pointerId!==t.pointerId)){t.clientX=e.clientX,t.clientY=e.clientY,t.active&&this.current()&&this.p(),this.h();try{t.active&&t.drop?.valid&&this.s(e.clientX,e.clientY)&&this.current()&&this.commitDrop(t.drop)}finally{this.release()}}};this.c=e=>{e.key==="Escape"&&(e.preventDefault(),this.destroy())};this.i=e=>{e.type==="pointercancel"&&e.pointerId!==this.e?.pointerId||this.destroy()}}begin(e){let t=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.e={startY:e.clientY,clientX:e.clientX,clientY:e.clientY,pointerId:e.pointerId,indicators:t,preview:n,drop:null,active:!1},window.addEventListener("pointermove",this.l),window.addEventListener("pointerup",this.d),window.addEventListener("pointercancel",this.i),window.addEventListener("keydown",this.c),window.addEventListener("blur",this.i)}g(e){return this.e?.active===!0&&this.sourceContains(e)}f(e,t=()=>!0){this.o=requestAnimationFrame(()=>{this.o=0,t()&&[...this.host.root.querySelectorAll(".mach-row-drag-handle")].find(n=>n.closest(".mach-row")?.dataset.id===e)?.focus()})}u(){this.n||(this.n=requestAnimationFrame(this.m))}s(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}y(){let e=this.e;if(!e||!this.s(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}p(){let e=this.e;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.s(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)`}h(){let e=this.e;this.e=null,window.removeEventListener("pointermove",this.l),window.removeEventListener("pointerup",this.d),window.removeEventListener("pointercancel",this.i),window.removeEventListener("keydown",this.c),window.removeEventListener("blur",this.i),cancelAnimationFrame(this.n),this.n=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.h(),this.release(),cancelAnimationFrame(this.o),this.o=0}};var te=class extends ee{constructor(t,n,o){super(t);this.t=t;this.prepare=n;this.v=o;this.scope=null;this.a=!1}r(t,n,o){try{return n()}catch(i){return this.scope&&(this.scope.failed=!0),this.t.report(i,t),o}}w(t){return this.r("prepare",()=>{let n=this.t.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.w(n)&&this.current()&&this.begin(t)}moveWithKeyboard(t,n){this.destroy();let o=this.w(n);if(!(!o||!this.current())){this.a=!0;try{let i=t.key==="ArrowUp"?-1:1,s=this.r("keyboardTarget",()=>o.session.keyboardTarget(i),void 0);s&&this.commitDrop(this.destination(s,i<0?0:1))}finally{this.a=!1,this.release()}}}isSource(t){return this.g(t.id)}current(){return!!(this.scope&&!this.scope.failed&&this.scope.guard.current()&&this.t.api.rows.getById(this.scope.node.id)===this.scope.node)}sourceContains(t){return this.r("isSource",()=>this.scope?.session.isSource(t)??!1,!1)}release(){this.scope=null}outsideText(){return this.t.api.getOption("locale")?.rowDragOutside??"\u79FB\u56DE\u8868\u683C\u5185\u653E\u7F6E \xB7 Esc \u53D6\u6D88"}describe(t){let n=this.t.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.r("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",d={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 d;d.intent=a.intent,d.position=a.intent.position,d.toIndex=a.toIndex,d.targetIndex=a.targetIndex,d.boundary=a.indicatorIndex??t.rowIndex+ +(a.intent.position==="after"),d.style=a.indicatorStyle,d.text=a.text??c;let w=this.r("canDrop",()=>this.t.api.getOption("rowDragPolicy")?.canDrop?.({node:o.node,api:this.t.api,targetNode:t,intent:a.intent})??!0,!1);return d.valid=w===!0,typeof w=="string"&&(d.text=w),d}commitDrop(t){let n=this.scope;if(!n||!this.current()||this.r("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.a&&this.v(o.intent,i=>this.f(n.node.id,i)),this.t.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=()=>{},d=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 l=o;return t++,o=null,i=null,l.abort(),!0},u=(l=e.status)=>({canUndo:!n&&l!=="saving"&&f.canUndo,canRedo:!n&&l!=="saving"&&f.canRedo}),g=l=>{e=Object.freeze({...l,...u(l.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=(l=w)=>{l?.release(),w===l&&(w=null)},T=()=>{!i||i()||(q(),E(),m(),g({...e,status:"idle",plan:null,error:null}))},k=l=>new te(l,p=>Se(l.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:l.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 l=u();(e.canUndo!==l.canUndo||e.canRedo!==l.canRedo)&&(e=Object.freeze({...e,...l}))},B=l=>{if(l===s){T(),ue(l,k)||(c(),c=pe(l,k));return}let p=q();a(),c(),m(),E(),s=l,c=pe(l,k),a=l.on("cellValueChanged",()=>{d++;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=l=>{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&&l.expectedRevision!==void 0&&l.expectedRevision!==p)throw new L;let h={...l,expectedRevision:l.expectedRevision??p};return(r.treeData?Q:J)(r.getRows(),h,r)},z=async(l,p,h,v,R)=>{if(!l.changed)return l;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=d,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:l});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(l.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(),$(l.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(l.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:l}),!ie())return l;let U=rt(await xe(Promise.resolve(r.save?.(l.intent,{signal:j.signal,plan:l,operation:p,operations:h})),j.signal));return ie()&&(me=!0,oe=U??X,d===ke?f.commit(p,v):E(),g({...e,status:"saved",revision:oe})),l}catch(I){throw Ne(I),I}finally{Ge()}},ge=async(l,p)=>{p!==w&&(p=void 0),w!==p&&m();let h=N(l);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=l=>ge(l),fe=async l=>{if(m(),M(),n||o)throw new Error("[MachTable] Row ordering is unavailable while disposed or saving.");let p=f.peek(l);if(!p)throw new Error(`[MachTable] Nothing to ${l}.`);let h=(l==="undo"?p.inverse:[p.plan.intent]).map(G=>({...G,expectedRevision:y()})),v=r.getRows(),R=l==="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,l,h,p)},Le=l=>{try{if(n||o)return!1;let p=r.getRows(),h=y();if(h!==void 0&&l.expectedRevision!==void 0&&l.expectedRevision!==h)return!1;let v=x?.rowIds===l.rowIds?x.sources:JSON.stringify(l.rowIds.map(String));return(!x||x.rows!==p||x.revision!==h||x.sources!==v)&&(x={rows:p,revision:h,sources:v,rowIds:l.rowIds,validate:Te(p,l.rowIds,r,r.treeData===!0)}),x.rowIds=l.rowIds,x.validate(l),!0}catch(p){return p instanceof Error?p.message:!1}},Pe=l=>{let p=l.intent;if(l.applied||!p)return;B(l.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=l=>n?!1:(B(l),o?"Wait for the current row order to finish saving.":Z(l)||"Save or discard edited rows before changing their order.");return{get state(){return M(),e},bindings:{applyRowDrag:!1,rowDragPolicy:{canDrag:({api:l})=>ye(l),canDrop:({intent:l,api:p})=>{let h=ye(p);if(h!==!0)return h;try{return Le(Ae(l))}catch(v){return v instanceof Error?v.message:!1}},getRevision:y},onRowDragEnd:Pe},preview:N,move:Ce,undo:()=>fe("undo"),redo:()=>fe("redo"),subscribe(l){return n?()=>{}:(S.add(l),()=>{S.delete(l)})},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-CUQtfQR4.cjs';
1
+ import { c as GridOptions } from './api-QsIvYp7X.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-CUQtfQR4.js';
1
+ import { c as GridOptions } from './api-QsIvYp7X.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 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
+ 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 d=n?He(a.row,s):[],w={...a,id:c,children:d};o.entries.push(w),o.byId.set(c,w),o.byRow.set(w.row,w),o.children.set(c,d);for(let f=d.length-1;f>=0;f--)i.push({row:d[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,d=n.canMove({row:a.row,previousParent:c,parent:s,target:o.row,intent:e});if(d===!1||typeof d=="string")throw new Error(typeof d=="string"?d:"[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(d=>d.id)),i=new Map;for(let d of t)i.has(d.parentId)||i.set(d.parentId,r.children.get(d.parentId).filter(w=>!o.has(r.byRow.get(w).id)));let s=i.get(e)??r.children.get(e),a=s.findIndex(d=>d===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(d=>d.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 d=s[a-1];if(!d)throw new Error("[MachTable] Row ordering cannot restore an isolated root.");return{rowIds:[i.id],targetId:n.byRow.get(d).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 d=i.byId.get(c),w=s.byId.get(c),f=w.parentId===null?null:i.byId.get(w.parentId).row,O=d.parentId===null?null:i.byId.get(d.parentId).row,S=n.canMove({row:d.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),d=Be(i,s,c,o),w=Ke(r,i,d,e),f=Ue(o,s,d.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 le(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 de=Symbol.for("mach-table.adapter.lifecycle.v1");function J(r){return!r.isDestroyed()&&(r[de]?.canReplaceData()??!1)}function ce(r,t){let e=r[de]?.rowDrag;return e?.original===t&&e.policy===r.getOption("rowDragPolicy")}function ue(r,t){let e=r[de];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(),d=String(typeof t.rowKey=="function"?t.rowKey(s):V(s,t.rowKey));if(n.depths.has(d))throw new Error("[MachTable] Row ordering requires unique, acyclic row keys.");n.depths.set(d,c),n.siblings.get(a).push(d),n.siblings.set(d,[]),a!==null&&n.parents.set(d,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:d,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]),d=[...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:d,isSource:w,validate:()=>{for(let u of d){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:d,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,d.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.e=null;this.n=0;this.o=0;this.l=t=>{let e=this.e;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.u()}};this.m=()=>{if(this.n=0,!!this.e?.active){if(!this.current()){this.destroy();return}this.p(),this.y()&&this.u()}};this.d=t=>{let e=this.e;if(!(!e||t.pointerId!==e.pointerId)){e.clientX=t.clientX,e.clientY=t.clientY,e.active&&this.current()&&this.p(),this.h();try{e.active&&e.drop?.valid&&this.s(t.clientX,t.clientY)&&this.current()&&this.commitDrop(e.drop)}finally{this.release()}}};this.c=t=>{t.key==="Escape"&&(t.preventDefault(),this.destroy())};this.i=t=>{t.type==="pointercancel"&&t.pointerId!==this.e?.pointerId||this.destroy()}}begin(t){let e=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.e={startY:t.clientY,clientX:t.clientX,clientY:t.clientY,pointerId:t.pointerId,indicators:e,preview:n,drop:null,active:!1},window.addEventListener("pointermove",this.l),window.addEventListener("pointerup",this.d),window.addEventListener("pointercancel",this.i),window.addEventListener("keydown",this.c),window.addEventListener("blur",this.i)}g(t){return this.e?.active===!0&&this.sourceContains(t)}f(t,e=()=>!0){this.o=requestAnimationFrame(()=>{this.o=0,e()&&[...this.host.root.querySelectorAll(".mach-row-drag-handle")].find(n=>n.closest(".mach-row")?.dataset.id===t)?.focus()})}u(){this.n||(this.n=requestAnimationFrame(this.m))}s(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}y(){let t=this.e;if(!t||!this.s(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}p(){let t=this.e;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.s(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)`}h(){let t=this.e;this.e=null,window.removeEventListener("pointermove",this.l),window.removeEventListener("pointerup",this.d),window.removeEventListener("pointercancel",this.i),window.removeEventListener("keydown",this.c),window.removeEventListener("blur",this.i),cancelAnimationFrame(this.n),this.n=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.h(),this.release(),cancelAnimationFrame(this.o),this.o=0}};var Z=class extends Q{constructor(e,n,o){super(e);this.t=e;this.prepare=n;this.v=o;this.scope=null;this.a=!1}r(e,n,o){try{return n()}catch(i){return this.scope&&(this.scope.failed=!0),this.t.report(i,e),o}}w(e){return this.r("prepare",()=>{let n=this.t.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.w(n)&&this.current()&&this.begin(e)}moveWithKeyboard(e,n){this.destroy();let o=this.w(n);if(!(!o||!this.current())){this.a=!0;try{let i=e.key==="ArrowUp"?-1:1,s=this.r("keyboardTarget",()=>o.session.keyboardTarget(i),void 0);s&&this.commitDrop(this.destination(s,i<0?0:1))}finally{this.a=!1,this.release()}}}isSource(e){return this.g(e.id)}current(){return!!(this.scope&&!this.scope.failed&&this.scope.guard.current()&&this.t.api.rows.getById(this.scope.node.id)===this.scope.node)}sourceContains(e){return this.r("isSource",()=>this.scope?.session.isSource(e)??!1,!1)}release(){this.scope=null}outsideText(){return this.t.api.getOption("locale")?.rowDragOutside??"\u79FB\u56DE\u8868\u683C\u5185\u653E\u7F6E \xB7 Esc \u53D6\u6D88"}describe(e){let n=this.t.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.r("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",d={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 d;d.intent=a.intent,d.position=a.intent.position,d.toIndex=a.toIndex,d.targetIndex=a.targetIndex,d.boundary=a.indicatorIndex??e.rowIndex+ +(a.intent.position==="after"),d.style=a.indicatorStyle,d.text=a.text??c;let w=this.r("canDrop",()=>this.t.api.getOption("rowDragPolicy")?.canDrop?.({node:o.node,api:this.t.api,targetNode:e,intent:a.intent})??!0,!1);return d.valid=w===!0,typeof w=="string"&&(d.text=w),d}commitDrop(e){let n=this.scope;if(!n||!this.current()||this.r("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.a&&this.v(o.intent,i=>this.f(n.node.id,i)),this.t.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=()=>{},d=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 l=o;return e++,o=null,i=null,l.abort(),!0},u=(l=t.status)=>({canUndo:!n&&l!=="saving"&&f.canUndo,canRedo:!n&&l!=="saving"&&f.canRedo}),g=l=>{t=Object.freeze({...l,...u(l.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=(l=w)=>{l?.release(),w===l&&(w=null)},T=()=>{!i||i()||(q(),E(),m(),g({...t,status:"idle",plan:null,error:null}))},k=l=>new Z(l,p=>Ee(l.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:l.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 l=u();(t.canUndo!==l.canUndo||t.canRedo!==l.canRedo)&&(t=Object.freeze({...t,...l}))},B=l=>{if(l===s){T(),ce(l,k)||(c(),c=ue(l,k));return}let p=q();a(),c(),m(),E(),s=l,c=ue(l,k),a=l.on("cellValueChanged",()=>{d++;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=l=>{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&&l.expectedRevision!==void 0&&l.expectedRevision!==p)throw new P;let h={...l,expectedRevision:l.expectedRevision??p};return(r.treeData?ae:se)(r.getRows(),h,r)},z=async(l,p,h,v,R)=>{if(!l.changed)return l;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=d,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:l});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(l.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(),$(l.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(l.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:l}),!ne())return l;let U=je(await Oe(Promise.resolve(r.save?.(l.intent,{signal:j.signal,plan:l,operation:p,operations:h})),j.signal));return ne()&&(ye=!0,re=U??X,d===Le?f.commit(p,v):E(),g({...t,status:"saved",revision:re})),l}catch(I){throw Pe(I),I}finally{ke()}},he=async(l,p)=>{p!==w&&(p=void 0),w!==p&&m();let h=N(l);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=l=>he(l),ge=async l=>{if(m(),M(),n||o)throw new Error("[MachTable] Row ordering is unavailable while disposed or saving.");let p=f.peek(l);if(!p)throw new Error(`[MachTable] Nothing to ${l}.`);let h=(l==="undo"?p.inverse:[p.plan.intent]).map(G=>({...G,expectedRevision:y()})),v=r.getRows(),R=l==="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,l,h,p)},Me=l=>{try{if(n||o)return!1;let p=r.getRows(),h=y();if(h!==void 0&&l.expectedRevision!==void 0&&l.expectedRevision!==h)return!1;let v=x?.rowIds===l.rowIds?x.sources:JSON.stringify(l.rowIds.map(String));return(!x||x.rows!==p||x.revision!==h||x.sources!==v)&&(x={rows:p,revision:h,sources:v,rowIds:l.rowIds,validate:Re(p,l.rowIds,r,r.treeData===!0)}),x.rowIds=l.rowIds,x.validate(l),!0}catch(p){return p instanceof Error?p.message:!1}},Ce=l=>{let p=l.intent;if(l.applied||!p)return;B(l.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=l=>n?!1:(B(l),o?"Wait for the current row order to finish saving.":J(l)||"Save or discard edited rows before changing their order.");return{get state(){return M(),t},bindings:{applyRowDrag:!1,rowDragPolicy:{canDrag:({api:l})=>fe(l),canDrop:({intent:l,api:p})=>{let h=fe(p);if(h!==!0)return h;try{return Me(Se(l))}catch(v){return v instanceof Error?v.message:!1}},getRevision:y},onRowDragEnd:Ce},preview:N,move:Ae,undo:()=>ge("undo"),redo:()=>ge("redo"),subscribe(l){return n?()=>{}:(S.add(l),()=>{S.delete(l)})},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,4 +1,4 @@
1
- import { f as GridState, g as GridStateStore, F as FilterType } from './api-CUQtfQR4.cjs';
1
+ import { f as GridState, g as GridStateStore, F as FilterType } from './api-QsIvYp7X.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-CUQtfQR4.js';
1
+ import { f as GridState, g as GridStateStore, F as FilterType } from './api-QsIvYp7X.js';
2
2
 
3
3
  interface GridStateMigrationOptions {
4
4
  /** Current stable column IDs; removed IDs are not restored. */
@@ -1 +1 @@
1
- "use strict";var E=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var ee=(n,e)=>{for(var t in e)E(n,t,{get:e[t],enumerable:!0})},te=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Y(e))!Z.call(n,o)&&o!==t&&E(n,o,{get:()=>e[o],enumerable:!(r=U(e,o))||r.enumerable});return n};var re=n=>te(E({},"__esModule",{value:!0}),n);var xe={};ee(xe,{ServerSideVersionConflictError:()=>m,bindServerSideGrid:()=>J,createServerSideGroupColumn:()=>W,createServerSideStore:()=>_,serverSideDataColumn:()=>$});module.exports=re(xe);function S(n,e){if(n instanceof Error)return n;let t=new Error(typeof n=="string"?n:e);return t.name="AbortError",t}var ne=()=>S(void 0,"[MachTable] Operation cancelled.");function R(n,e,t=ne){return e?new Promise((r,o)=>{let s=()=>{e.removeEventListener("abort",s),o(t())};if(n.then(r,o).finally(()=>e.removeEventListener("abort",s)),e.aborted){s();return}e.addEventListener("abort",s,{once:!0})}):n}function g(n){return S(n.reason,"Block request aborted")}function x(n){return Number.isFinite(n)?Math.max(1,Math.trunc(n)):1}var T=class{constructor(e,t,r=4){this.maxBlocks=e;this.n=t;this.maxConcurrentRequests=r;this.e=new Map;this.t=new Map;this.m=0;this.generation=0;this.hitCount=0;this.missCount=0;this.evictionCount=0;this.s=0;this.a=new Set;this.maxBlocks=x(e),this.maxConcurrentRequests=x(r)}configure(e,t=this.maxConcurrentRequests){this.maxBlocks=x(e),this.maxConcurrentRequests=x(t),this.u(),this.l()}b(e){this.a=e,this.u()}peek(e){let t=this.e.get(e);if(t)return t.touchedAt=++this.m,t}has(e){return this.e.has(e)}invalidate(e){let t=this.t.get(e);t&&(this.t.delete(e),t.controller.abort(),t.state==="queued"&&t.reject(g(t.controller.signal)));let r=this.e.get(e);r&&(this.e.delete(e),this.n?.(e,r))}load(e,t,r,o=0){if(r?.aborted)return Promise.reject(g(r));let s=this.peek(e);if(s)return this.hitCount++,Promise.resolve(s);let i=this.t.get(e);if(i)return this.hitCount++,i.priority=Math.max(i.priority,o),this.l(),this.g(e,i,r);this.missCount++;let a=new AbortController,d,u,l=new Promise((M,X)=>{d=M,u=X}),h={controller:a,promise:l,consumers:0,loader:t,priority:o,state:"queued",resolve:d,reject:u};this.t.set(e,h);let p=this.g(e,h,r);return this.l(),p}y(){this.generation++,this.a.clear();for(let e of this.t.values())e.controller.abort(),e.state==="queued"&&e.reject(g(e.controller.signal));this.t.clear();for(let[e,t]of this.e)this.n?.(e,t);this.e.clear()}snapshot(){let e=0,t=0;for(let r of this.e.values())e+=r.rows.length;for(let r of this.t.values())r.state==="active"&&t++;return{cachedBlockCount:this.e.size,loadingBlockCount:this.t.size,activeRequestCount:t,queuedRequestCount:Math.max(0,this.t.size-t),cachedRowCount:e,hitCount:this.hitCount,missCount:this.missCount,evictionCount:this.evictionCount}}l(){for(;this.s<this.maxConcurrentRequests;){let e,t;for(let[r,o]of this.t)o.state!=="queued"||o.controller.signal.aborted||(!t||o.priority>t.priority)&&(e=r,t=o);if(e==null||!t)return;this.w(e,t)}}w(e,t){t.state="active",this.s++;let r=this.generation;this.x(t).then(o=>{r===this.generation&&!t.controller.signal.aborted&&(this.e.set(e,{rows:o.rows,...o.lastRow==null?{}:{lastRow:o.lastRow},touchedAt:++this.m}),this.u()),t.resolve(o)},t.reject).finally(()=>{this.s=Math.max(0,this.s-1),this.t.get(e)===t&&this.t.delete(e),this.l()})}x(e){let{signal:t}=e.controller;return R(Promise.resolve().then(()=>{if(t.aborted)throw g(t);return e.loader(t)}),t,()=>g(t))}g(e,t,r){return t.consumers++,new Promise((o,s)=>{let i=!1,a=u=>{i||(i=!0,r?.removeEventListener("abort",d),t.consumers=Math.max(0,t.consumers-1),u())},d=()=>a(()=>{t.consumers===0&&this.t.get(e)===t&&(this.t.delete(e),t.controller.abort(r?.reason),t.state==="queued"&&t.reject(g(t.controller.signal))),s(g(r))});r?.addEventListener("abort",d,{once:!0}),t.promise.then(u=>a(()=>o(u)),u=>a(()=>s(u instanceof Error?u:new Error(String(u??"Block request failed")))))})}u(){let e=Math.max(this.maxBlocks,this.a.size+1);for(;this.e.size>e;){let t=-1,r=Number.POSITIVE_INFINITY;for(let[s,i]of this.e)this.a.has(s)||i.touchedAt<r&&(t=s,r=i.touchedAt);if(t<0)return;let o=this.e.get(t);this.e.delete(t),this.evictionCount++,o&&this.n?.(t,o)}}};var k={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 oe=16,ie=512,se=20,ae=2e3,le=2e3,de={text:new Set(k.text),number:new Set(k.number),date:new Set(k.date)};function ue(n){return n==null||typeof n=="string"||typeof n=="number"&&Number.isFinite(n)}function ce(n,e,t){if(n==null||typeof n!="object")return null;let r=n;return typeof r.match!="string"||!t.has(r.match)?null:{match:r.match,...he(r,e)}}function he(n,e){let t=e==="number"?F(n.value):typeof n.value=="string"?n.value:void 0,r=e==="number"?F(n.value2):typeof n.value2=="string"?n.value2:void 0;return{...t!==void 0?{value:t}:{},...r!==void 0?{value2:r}:{}}}function F(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function pe(n,e){let t=[],r=de[e];for(let o of n.slice(0,se)){let s=ce(o,e,r);s&&t.push(s)}return t}function I(n){if(n==null||typeof n!="object")return null;let e=n;return e.type==="set"?Array.isArray(e.values)?{type:"set",values:e.values.filter(ue).slice(0,ae)}:null:e.type!=="text"&&e.type!=="number"&&e.type!=="date"||!Array.isArray(e.conditions)?null:{type:e.type,...e.operator==="or"||e.operator==="and"?{operator:e.operator}:{},conditions:pe(e.conditions,e.type)}}function fe(n,e){if(typeof n.colId!="string"||!n.colId.trim())return null;let t=n.colId.trim();if(e.validColumnIds?.has(t)===!1)return null;let r=I(n.filter);return r?{kind:"condition",colId:t,filter:r}:null}function ve(n,e,t){if(!Array.isArray(n.children))return null;let r=[];for(let o of n.children){let s=G(o,e+1,t);s&&r.push(s)}return r.length===0?null:{kind:"group",operator:n.operator==="or"?"or":"and",children:r,...n.not===!0?{not:!0}:{}}}function ge(n,e,t){return e<=oe&&t.nodes<ie&&n!=null&&typeof n=="object"}function G(n,e,t){if(!ge(n,e,t)||t.ancestors.has(n))return null;t.ancestors.add(n),t.nodes++;let r=n,o=r.kind==="condition"?fe(r,t):r.kind==="group"?ve(r,e,t):null;return t.ancestors.delete(n),o}function B(n,e){if(n==null||typeof n!="object")return null;let t=n;if(t.version!==1||t.root==null)return null;let r=G(t.root,0,{ancestors:new WeakSet,nodes:0,validColumnIds:e});return r?{version:1,root:r}:null}function N(n,e){if(n==null||typeof n!="object"||Array.isArray(n))return{};let t={};for(let[r,o]of Object.entries(n).slice(0,le)){let s=r.trim();if(!s||e?.has(s)===!1)continue;let i=I(o);i&&(t[s]=i)}return t}function f(){return S(void 0,"[MachTable] Server-side operation cancelled or replaced.")}function v(n,e,t,r=1){return n!=null&&Number.isFinite(n)?Math.max(r,Math.min(t,Math.floor(n))):e}function A(n){if(!Array.isArray(n)||n.length>16||n.some(e=>typeof e!="string"||e.length>512))throw new TypeError("[MachTable] Invalid server-side group route.");return[...n]}function C(n,e){let t={...e,...n},r=t.rowGroupCols??[],o=t.valueCols??[];if(r.length>16||o.length>128)throw new RangeError("[MachTable] Server-side query exceeds group/aggregate column limits.");if([...r,...o].some(i=>typeof i.colId!="string"||!i.colId||i.colId.length>512))throw new TypeError("[MachTable] Invalid server-side query column.");return{rowGroupCols:r.map(i=>({colId:i.colId,...i.field?{field:i.field}:{}})),valueCols:o.map(i=>({colId:i.colId,aggFunc:i.aggFunc,...i.field?{field:i.field}:{}})),sortModel:(t.sortModel??[]).slice(0,2e3).filter(i=>i.direction==="asc"||i.direction==="desc").map(i=>({...i})),filterModel:N(t.filterModel),advancedFilterModel:B(t.advancedFilterModel),quickFilterText:t.quickFilterText?.slice(0,1e4)||null}}function me(n,e,t){if(!n||!Array.isArray(n.rows)||n.rows.length>t||!Number.isInteger(n.rowCount)||n.rowCount<0||n.rows.length>0&&n.rowCount<e+n.rows.length||typeof n.revision!="string"||!n.revision||n.revision.length>512)throw new TypeError("[MachTable] Invalid server-side route response.")}function z(n,e,t){return e>0&&n>=e?Math.floor((e-1)/t)*t:null}function K(n,e,t,r){me(n,e,t);let o=new Set,s=new Set;for(let i of n.rows){if(typeof i.id!="string"||!i.id||i.id.length>512||o.has(i.id))throw new TypeError("[MachTable] Duplicate/invalid server-side row ID.");if(o.add(i.id),r){if(typeof i.groupKey!="string"||i.groupKey.length>512||s.has(i.groupKey))throw new TypeError("[MachTable] Duplicate/invalid group key.");s.add(i.groupKey)}else if(i.groupKey!==void 0)throw new TypeError("[MachTable] Leaf routes cannot return group rows.")}return{rows:n.rows.map(i=>({...i})),rowCount:n.rowCount,revision:n.revision}}function O(n,e){return new Promise((t,r)=>{if(e.aborted){r(f());return}let o=()=>{clearTimeout(s),r(f())},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);e.addEventListener("abort",o,{once:!0})})}function j(n,e){return R(n,e,f)}function c(n){return JSON.stringify(n)}function L(n,e){return JSON.stringify([n,e])}function b(n,e){return n.length>=e.length&&e.every((t,r)=>n[r]===t)}var D=class{constructor(){this.selected=new Map;this.r=new Map;this.routes=new Map;this.excludedRoutes=new Map}h(e){let t=!1;for(let r=0;r<=e.length;r++){let o=c(e.slice(0,r));this.routes.has(o)&&(t=!0),this.excludedRoutes.has(o)&&(t=!1)}return t}c(e,t,r=!1){return[...e.values()].some(o=>b(o,t)&&(!r||o.length>t.length))}get(e){if(e.groupKey===void 0)return this.selected.has(e.key)||!this.r.has(e.key)&&this.h(e.route)?"selected":"none";let t=[...e.route,e.groupKey];if(this.r.has(e.key))return this.h(t)?"partial":"none";let r=this.h(t)||this.selected.has(e.key);return(r?this.c(this.r,t)||this.c(this.excludedRoutes,t,!0):this.c(this.selected,t)||this.c(this.routes,t,!0))?"partial":r?"selected":"none"}R(e,t){for(let[r,o]of e)b(o,t)&&e.delete(r)}select(e,t,r){let o=c([...e.route,e.groupKey??e.id]);if(!(this.selected.has(e.key)||this.r.has(e.key)||this.routes.has(o)||this.excludedRoutes.has(o))&&this.selected.size+this.r.size+this.routes.size+this.excludedRoutes.size>=1e4)throw new RangeError("[MachTable] Server-side selection exceeds 10000 explicit rules; clear selection first.");if(e.groupKey!==void 0&&r==="descendants"){let i=[...e.route,e.groupKey];for(let a of[this.selected,this.r,this.routes,this.excludedRoutes])this.R(a,i);this.selected.delete(e.key),this.r.delete(e.key),t?this.routes.set(c(i),i):this.excludedRoutes.set(c(i),i);return}this.selected.delete(e.key),this.r.delete(e.key),t?this.selected.set(e.key,e.route):this.r.set(e.key,e.route)}clear(){this.selected.clear(),this.r.clear(),this.routes.clear(),this.excludedRoutes.clear()}snapshot(){return{selectedKeys:[...this.selected.keys()],excludedKeys:[...this.r.keys()],selectedRoutes:[...this.routes.values()].map(e=>[...e]),excludedRoutes:[...this.excludedRoutes.values()].map(e=>[...e])}}};var m=class extends Error{constructor(t,r){super("[MachTable] Server-side route revision changed; refresh before retrying the transaction.");this.expectedRevision=t;this.actualRevision=r;this.name="ServerSideVersionConflictError"}};var P=class{constructor(e){this.options=e;this.routes=new Map;this.e=new Map;this.indices=new Map;this.expanded=new Set;this.selection=new D;this.d=new Set;this.i=new Set;this.T=0;this.generation=0;this.revision=0;this.disposed=!1;this.p=0;this.snapshot=null;this.query=C(e.query??{}),this.blockSize=v(e.blockSize,100,1e3),this.cache=new T(v(e.maxBlocks,12,256),t=>this.n(t),v(e.maxConcurrentRequests,4,16))}o(){if(this.disposed)throw f()}k(){if(this.p>=256)throw new RangeError("[MachTable] Server-side load queue limit reached (256).")}emit(e=!1){if(!this.disposed){this.snapshot=null,e&&this.revision++;for(let t of this.d)try{t()}catch(r){this.report(r,[])}}}report(e,t){if(e?.name!=="AbortError")try{this.options.onError?.(e,t)}catch{}}state(e){let t=A(e);if(t.length>this.query.rowGroupCols.length)throw new RangeError("[MachTable] Route exceeds configured grouping depth.");let r=c(t),o=this.routes.get(r);if(o)return this.routes.delete(r),this.routes.set(r,o),o;if(this.routes.size>=256){let i=[...this.routes].find(([a,d])=>a!=="[]"&&d.pending===0&&!this.expanded.has(a));if(!i)throw new RangeError("[MachTable] Server-side route metadata limit reached (256).");this.f(i[0]),this.routes.delete(i[0])}let s={route:t,startRow:0,endRow:0,rowCount:null,revision:null,loading:!1,error:null,generation:0,active:null,pending:0,requestVersion:0};return this.routes.set(r,s),s}n(e){this.snapshot=null;let t=this.indices.get(e);if(!t)return;this.indices.delete(e),this.e.get(t.key)===t&&this.e.delete(t.key);let r=this.routes.get(t.route);r?.active===e&&(r.active=null)}f(e,t){for(let r of[...this.indices.values()])r.route!==e||r.index===t||(this.cache.invalidate(r.index),this.n(r.index))}v(){let e=new Set;for(let[t,r]of this.routes)r.active!=null&&(t==="[]"||this.expanded.has(t))&&e.add(r.active);this.cache.b(e)}block(e,t){let r=JSON.stringify([e,t]),o=this.e.get(r);if(o)return o;let s={index:++this.T,key:r,route:e,start:t};return this.e.set(r,s),this.indices.set(s.index,s),s}async fetch(e,t,r){let o=v(this.options.retryCount,1,5,0),s=this.query;for(let i=0;;i++){if(r.aborted)throw f();try{let a=await this.options.getRows({...s,route:[...e.route],startRow:t,endRow:t+this.blockSize,revision:e.revision,signal:r});if(r.aborted)throw f();return K(a,t,this.blockSize,e.route.length<s.rowGroupCols.length)}catch(a){if(r.aborted||i>=o)throw a;await O(Math.min(3e4,v(this.options.retryDelay,200,1e4,0)*2**i),r)}}}current(e,t,r,o){return!this.disposed&&r===this.generation&&e.generation===o&&this.cache.has(t.index)}async load(e=[],t=0,r){this.o(),this.k();let o=this.state(e),s=Math.floor(v(t,0,Number.MAX_SAFE_INTEGER,0)/this.blockSize)*this.blockSize,i=this.block(c(o.route),s),a=this.generation,d=o.generation,u=++o.requestVersion;this.p++,o.pending++,o.loading=!0,o.error=null,this.v(),this.emit();try{let l=await this.cache.load(i.index,async M=>({rows:[await this.fetch(o,s,M)]}),r,100);if(!this.current(o,i,a,d))throw f();if(u!==o.requestVersion)return;let h=l.rows[0];o.revision!=null&&o.revision!==h.revision&&(o.generation++,this.f(i.route,i.index)),o.revision=h.revision;let p=z(s,h.rowCount,this.blockSize);if(p!=null){await this.load(o.route,p,r);return}o.active=i.index,o.startRow=s,o.endRow=s+h.rows.length,o.rowCount=h.rowCount,o.revision=h.revision,this.v(),this.emit(!0),await this.S(o.route)}catch(l){throw this.C(o,a,d,u)&&(o.error=l?.name==="AbortError"?null:l,this.report(l,o.route)),l}finally{o.pending=Math.max(0,o.pending-1),this.p--,u===o.requestVersion&&(o.loading=!1),this.cache.has(i.index)||this.n(i.index),a===this.generation&&this.emit()}}C(e,t,r,o){return!this.disposed&&t===this.generation&&e.generation===r&&o===e.requestVersion}async expand(e){this.o();let t=A(e),r=this.state(t),o=c(t);if(!this.expanded.has(o)&&this.expanded.size>=128)throw new RangeError("[MachTable] Expanded group limit reached (128).");this.expanded.add(o),this.emit(!0),r.active==null?await this.load(t,r.startRow):await this.S(t)}collapse(e){let t=A(e);for(let r of this.expanded)b(JSON.parse(r),t)&&this.expanded.delete(r);this.v(),this.emit(!0)}A(e){for(let[t,r]of this.routes)b(r.route,e)&&(r.generation++,r.active=null,r.revision=null,r.error=null,this.f(t))}async S(e){let t=this.routes.get(c(e)),r=t?.active==null?void 0:this.cache.peek(t.active)?.rows[0];if(!r)return;let o=r.rows.flatMap(s=>s.groupKey!==void 0&&this.expanded.has(c([...e,s.groupKey]))?[[...e,s.groupKey]]:[]);await Promise.all(o.map(s=>this.expand(s)))}async refresh(e=[]){this.o();let t=this.state(e);this.A(t.route),this.emit(!0),await this.load(t.route,t.startRow)}async setQuery(e){this.o();let t=C(e,this.query);if(JSON.stringify(t)!==JSON.stringify(this.query)){this.generation++,this.cache.y(),this.e.clear(),this.indices.clear(),this.routes.clear(),this.expanded.clear();for(let r of this.i)r.abort();this.selection.clear(),this.query=t,this.emit(!0),await this.load()}}async transact(e){this.o();let t=this.state(e.route);if(t.revision!==e.expectedRevision)throw new m(e.expectedRevision,t.revision);if(!this.options.transact)throw new Error("[MachTable] A server-side transaction transport is required.");if(this.i.size>=v(this.options.maxConcurrentRequests,4,16))throw new RangeError("[MachTable] Too many active server-side transactions.");let r=new AbortController;this.i.add(r);let o=this.generation,s=t.generation;try{let i=await j(Promise.resolve().then(()=>{if(r.signal.aborted)throw f();return this.options.transact({...e,route:[...t.route],query:this.query,signal:r.signal})}),r.signal);if(r.signal.aborted||o!==this.generation||s!==t.generation)throw f();if(typeof i?.revision!="string"||!i.revision||i.revision.length>512)throw new TypeError("[MachTable] Transaction transport must return the committed revision.");await this.refresh([])}finally{this.i.delete(r)}}select(e,t,r="descendants"){this.o(),this.selection.select(e,t,r),this.emit()}getSelection(e){return this.selection.get(e)}clearSelection(){this.selection.clear(),this.emit()}getSnapshot(){if(this.snapshot)return this.snapshot;let e=[],t=r=>{let o=this.routes.get(c(r)),s=o?.active==null?void 0:this.cache.peek(o.active)?.rows[0];if(s)for(let i of s.rows){let a=i.groupKey!==void 0&&this.expanded.has(c([...r,i.groupKey]));e.push({...i,key:L(r,i.id),route:[...r],depth:r.length,expanded:a}),a&&t([...r,i.groupKey])}};return t([]),this.snapshot={rows:e,routes:[...this.routes.values()].map(({route:r,startRow:o,endRow:s,rowCount:i,revision:a,loading:d,error:u})=>({route:[...r],startRow:o,endRow:s,rowCount:i,revision:a,loading:d,error:u})),selection:this.selection.snapshot(),query:C(this.query),revision:this.revision,cachedBlockCount:this.cache.snapshot().cachedBlockCount},this.snapshot}subscribe(e){return this.o(),this.d.add(e),()=>this.d.delete(e)}dispose(){if(!this.disposed){this.disposed=!0,this.generation++,this.cache.y();for(let e of this.i)e.abort();this.i.clear(),this.routes.clear(),this.e.clear(),this.indices.clear(),this.expanded.clear(),this.selection.clear(),this.d.clear(),this.snapshot=null}}};function _(n){return new P(n)}var ye=new Set(["__proto__","prototype","constructor"]),w=new Map;function Se(n){if(typeof n!="string"||n.length===0)return null;let e=w.get(n);if(e!==void 0)return e;let t=n.split("."),r=t.every(o=>o.length>0&&!ye.has(o))?t:null;return n.length<=1024&&(w.size>=256&&w.delete(w.keys().next().value),w.set(n,r)),r}function Q(n,e){if(n==null)return;let t=Se(e);if(!t)return;let r=n;for(let o of t){if(r==null)return;r=r[o]}return r}var be=Symbol.for("mach-table.adapter.lifecycle.v1");function q(n){return!n.isDestroyed()&&(n[be]?.canReplaceData()??!1)}function y(n,e,t=!1){let r=document.createElement("button");return r.type="button",r.className="mach-server-button",r.textContent=n,r.disabled=t,r.addEventListener("click",o=>{o.stopPropagation();try{Promise.resolve(e()).catch(()=>{})}catch{}}),r}function we(n){return n?n.loading?"\u52A0\u8F7D\u4E2D\u2026":n.error?"\u52A0\u8F7D\u5931\u8D25":`${n.endRow>n.startRow?n.startRow+1:0}\u2013${n.endRow} / ${n.rowCount??"?"}`:"\u5C1A\u672A\u52A0\u8F7D"}function V(n,e){let t=n.getSnapshot().routes.find(s=>c(s.route)===c(e)),r=document.createElement("span");r.className="mach-server-paging";let o=document.createElement("span");return o.className="mach-server-range",o.textContent=we(t),o.setAttribute("aria-live","polite"),r.append(o),r.append(y("\u4E0A\u4E00\u9875",()=>n.load(e,Math.max(0,(t?.startRow??0)-1)),!t||t.loading||t.startRow===0)),r.append(y("\u4E0B\u4E00\u9875",()=>n.load(e,t?.endRow??0),!t||t.loading||t.rowCount===null||t.endRow>=t.rowCount)),t?.error&&r.append(y("\u91CD\u8BD5",()=>n.refresh(e))),r}function W(n,e={}){return{colId:"__server_group",headerName:e.headerName??"\u670D\u52A1\u7AEF\u5206\u7EC4",width:e.width??420,minWidth:260,pinned:"left",sortable:!1,filter:!1,editable:!1,headerComponent:()=>{let t=document.createElement("div");t.className="mach-server-header";let r=()=>{t.replaceChildren(V(n,[]),y("\u5237\u65B0",()=>n.refresh()),y("\u6E05\u9664\u9009\u62E9",()=>n.clearSelection()))};return r(),{el:t,destroy:n.subscribe(r)}},cellRenderer:({data:t})=>{if(!t)return"";let r=document.createElement("div");r.className="mach-server-cell",r.style.paddingInlineStart=`${t.depth*16}px`;let o=document.createElement("input");o.type="checkbox";let s=n.getSelection(t);if(o.checked=s==="selected",o.indeterminate=s==="partial",o.setAttribute("aria-label",`\u9009\u62E9 ${t.groupKey??t.id}`),o.addEventListener("click",a=>{a.stopPropagation(),n.select(t,o.checked)}),r.append(o),t.groupKey!==void 0){let a=[...t.route,t.groupKey],d=y(t.expanded?"\u25BE":"\u25B8",()=>t.expanded?n.collapse(a):n.expand(a));d.setAttribute("aria-expanded",String(t.expanded)),d.setAttribute("aria-label",`${t.expanded?"\u6536\u8D77":"\u5C55\u5F00"} ${t.groupKey||"\u7A7A\u767D\u5206\u7EC4"}`),r.append(d)}let i=document.createElement("span");return i.className="mach-server-label",i.textContent=e.label?.(t)??t.groupKey??t.id,r.append(i),t.expanded&&t.groupKey!==void 0&&r.append(V(n,[...t.route,t.groupKey])),r}}}function $(n,e={}){let t=e.colId??n;return{...e,colId:t,headerName:e.headerName??n,editable:!1,valueGetter:({data:r})=>r?.groupKey!==void 0&&r.aggValues&&Object.prototype.hasOwnProperty.call(r.aggValues,t)?r.aggValues[t]:Q(r?.data,n)}}function Re(n,e){var r;let t=n.querySelectorAll(".mach-server-header button,.mach-server-cell button,.mach-server-cell input");for(let o of t)e?((r=o.dataset).serverWasDisabled??(r.serverWasDisabled=String(o.disabled)),o.disabled=!0):o.dataset.serverWasDisabled!==void 0&&(o.disabled=o.dataset.serverWasDisabled==="true",delete o.dataset.serverWasDisabled)}function H(n,e){let t=n.view.getRoot();if(!t)return;Re(t,e);let r=t.querySelector(".mach-server-sync-notice");if(!e){r?.remove(),delete t.dataset.serverPending;return}if(t.dataset.serverPending="true",r)return;let o=document.createElement("div");o.className="mach-server-sync-notice",o.setAttribute("role","status"),o.textContent="\u65B0\u6570\u636E\u7B49\u5F85\u663E\u793A\uFF1A\u8BF7\u5148\u4FDD\u5B58\u3001\u53D6\u6D88\u7F16\u8F91\u6216\u56DE\u6EDA\u4FEE\u6539",t.append(o)}function J(n,e){if(!q(n))throw new Error("[MachTable] Save or cancel grid edits before binding server-side data.");let t=!1,r=-1,o=!1,s=()=>{if(t||o||n.isDestroyed())return;let l=e.getSnapshot(),h=l.revision!==r&&!q(n);if(H(n,h),!h){t=!0;try{l.revision!==r&&(r=l.revision,n.rows.setData([...l.rows])),n.selection.setRows(l.rows.filter(p=>e.getSelection(p)==="selected"),!0),n.view.refreshCells()}finally{t=!1}}},i=()=>{t||o||e.setQuery({sortModel:n.sorting.getModel(),filterModel:n.filtering.getModel(),advancedFilterModel:n.filtering.getAdvancedModel(),quickFilterText:n.filtering.getQuickText()}).catch(()=>{})},a=()=>{e.getSnapshot().revision!==r&&s()};n.updateOptions({rowKey:l=>l.key,rowSelection:"multiple",manualFiltering:!0,manualSorting:!0,pagination:!1});let d=[e.subscribe(s),n.on("sortChanged",i),n.on("filterChanged",i),n.on("dirtyStateChanged",a),n.on("cellEditingStopped",a),n.on("rowEditingStopped",a),n.on("selectionChanged",()=>{if(t||o||e.getSnapshot().revision!==r)return;let l=new Set(n.selection.getIds()),h=e.getSnapshot().rows.filter(p=>l.has(p.key)!==(e.getSelection(p)==="selected"));for(let p of h)e.select(p,l.has(p.key))})],u=()=>{if(!o){o=!0;for(let l of d)l();H(n,!1),e.dispose()}};return d.push(n.on("gridDestroyed",u)),s(),e.setQuery({sortModel:n.sorting.getModel(),filterModel:n.filtering.getModel(),advancedFilterModel:n.filtering.getAdvancedModel(),quickFilterText:n.filtering.getQuickText()}).then(()=>e.getSnapshot().routes.length===0?e.load():void 0).catch(()=>{}),u}0&&(module.exports={ServerSideVersionConflictError,bindServerSideGrid,createServerSideGroupColumn,createServerSideStore,serverSideDataColumn});
1
+ "use strict";var E=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var ee=(n,e)=>{for(var t in e)E(n,t,{get:e[t],enumerable:!0})},te=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Y(e))!Z.call(n,o)&&o!==t&&E(n,o,{get:()=>e[o],enumerable:!(r=U(e,o))||r.enumerable});return n};var re=n=>te(E({},"__esModule",{value:!0}),n);var xe={};ee(xe,{ServerSideVersionConflictError:()=>m,bindServerSideGrid:()=>J,createServerSideGroupColumn:()=>W,createServerSideStore:()=>_,serverSideDataColumn:()=>$});module.exports=re(xe);function S(n,e){if(n instanceof Error)return n;let t=new Error(typeof n=="string"?n:e);return t.name="AbortError",t}var ne=()=>S(void 0,"[MachTable] Operation cancelled.");function R(n,e,t=ne){return e?new Promise((r,o)=>{let s=()=>{e.removeEventListener("abort",s),o(t())};if(n.then(r,o).finally(()=>e.removeEventListener("abort",s)),e.aborted){s();return}e.addEventListener("abort",s,{once:!0})}):n}function g(n){return S(n.reason,"Block request aborted")}function x(n){return Number.isFinite(n)?Math.max(1,Math.trunc(n)):1}var T=class{constructor(e,t,r=4){this.maxBlocks=e;this.n=t;this.maxConcurrentRequests=r;this.e=new Map;this.t=new Map;this.y=0;this.u=0;this.h=0;this.S=0;this.b=0;this.s=0;this.a=new Set;this.maxBlocks=x(e),this.maxConcurrentRequests=x(r)}configure(e,t=this.maxConcurrentRequests){this.maxBlocks=x(e),this.maxConcurrentRequests=x(t),this.p(),this.l()}T(e){this.a=e,this.p()}peek(e){let t=this.e.get(e);if(t)return t.touchedAt=++this.y,t}has(e){return this.e.has(e)}invalidate(e){let t=this.t.get(e);t&&(this.t.delete(e),t.controller.abort(),t.state==="queued"&&t.reject(g(t.controller.signal)));let r=this.e.get(e);r&&(this.e.delete(e),this.n?.(e,r))}load(e,t,r,o=0){if(r?.aborted)return Promise.reject(g(r));let s=this.peek(e);if(s)return this.h++,Promise.resolve(s);let i=this.t.get(e);if(i)return this.h++,i.priority=Math.max(i.priority,o),this.l(),this.w(e,i,r);this.S++;let a=new AbortController,d,u,l=new Promise((M,X)=>{d=M,u=X}),h={controller:a,promise:l,consumers:0,loader:t,priority:o,state:"queued",resolve:d,reject:u};this.t.set(e,h);let p=this.w(e,h,r);return this.l(),p}x(){this.u++,this.a.clear();for(let e of this.t.values())e.controller.abort(),e.state==="queued"&&e.reject(g(e.controller.signal));this.t.clear();for(let[e,t]of this.e)this.n?.(e,t);this.e.clear()}snapshot(){let e=0,t=0;for(let r of this.e.values())e+=r.rows.length;for(let r of this.t.values())r.state==="active"&&t++;return{cachedBlockCount:this.e.size,loadingBlockCount:this.t.size,activeRequestCount:t,queuedRequestCount:Math.max(0,this.t.size-t),cachedRowCount:e,hitCount:this.h,missCount:this.S,evictionCount:this.b}}l(){for(;this.s<this.maxConcurrentRequests;){let e,t;for(let[r,o]of this.t)o.state!=="queued"||o.controller.signal.aborted||(!t||o.priority>t.priority)&&(e=r,t=o);if(e==null||!t)return;this.k(e,t)}}k(e,t){t.state="active",this.s++;let r=this.u;this.C(t).then(o=>{r===this.u&&!t.controller.signal.aborted&&(this.e.set(e,{rows:o.rows,...o.lastRow==null?{}:{lastRow:o.lastRow},touchedAt:++this.y}),this.p()),t.resolve(o)},t.reject).finally(()=>{this.s=Math.max(0,this.s-1),this.t.get(e)===t&&this.t.delete(e),this.l()})}C(e){let{signal:t}=e.controller;return R(Promise.resolve().then(()=>{if(t.aborted)throw g(t);return e.loader(t)}),t,()=>g(t))}w(e,t,r){return t.consumers++,new Promise((o,s)=>{let i=!1,a=u=>{i||(i=!0,r?.removeEventListener("abort",d),t.consumers=Math.max(0,t.consumers-1),u())},d=()=>a(()=>{t.consumers===0&&this.t.get(e)===t&&(this.t.delete(e),t.controller.abort(r?.reason),t.state==="queued"&&t.reject(g(t.controller.signal))),s(g(r))});r?.addEventListener("abort",d,{once:!0}),t.promise.then(u=>a(()=>o(u)),u=>a(()=>s(u instanceof Error?u:new Error(String(u??"Block request failed")))))})}p(){let e=Math.max(this.maxBlocks,this.a.size+1);for(;this.e.size>e;){let t=-1,r=Number.POSITIVE_INFINITY;for(let[s,i]of this.e)this.a.has(s)||i.touchedAt<r&&(t=s,r=i.touchedAt);if(t<0)return;let o=this.e.get(t);this.e.delete(t),this.b++,o&&this.n?.(t,o)}}};var k={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 oe=16,ie=512,se=20,ae=2e3,le=2e3,de={text:new Set(k.text),number:new Set(k.number),date:new Set(k.date)};function ue(n){return n==null||typeof n=="string"||typeof n=="number"&&Number.isFinite(n)}function ce(n,e,t){if(n==null||typeof n!="object")return null;let r=n;return typeof r.match!="string"||!t.has(r.match)?null:{match:r.match,...he(r,e)}}function he(n,e){let t=e==="number"?F(n.value):typeof n.value=="string"?n.value:void 0,r=e==="number"?F(n.value2):typeof n.value2=="string"?n.value2:void 0;return{...t!==void 0?{value:t}:{},...r!==void 0?{value2:r}:{}}}function F(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function pe(n,e){let t=[],r=de[e];for(let o of n.slice(0,se)){let s=ce(o,e,r);s&&t.push(s)}return t}function I(n){if(n==null||typeof n!="object")return null;let e=n;return e.type==="set"?Array.isArray(e.values)?{type:"set",values:e.values.filter(ue).slice(0,ae)}:null:e.type!=="text"&&e.type!=="number"&&e.type!=="date"||!Array.isArray(e.conditions)?null:{type:e.type,...e.operator==="or"||e.operator==="and"?{operator:e.operator}:{},conditions:pe(e.conditions,e.type)}}function fe(n,e){if(typeof n.colId!="string"||!n.colId.trim())return null;let t=n.colId.trim();if(e.validColumnIds?.has(t)===!1)return null;let r=I(n.filter);return r?{kind:"condition",colId:t,filter:r}:null}function ve(n,e,t){if(!Array.isArray(n.children))return null;let r=[];for(let o of n.children){let s=G(o,e+1,t);s&&r.push(s)}return r.length===0?null:{kind:"group",operator:n.operator==="or"?"or":"and",children:r,...n.not===!0?{not:!0}:{}}}function ge(n,e,t){return e<=oe&&t.nodes<ie&&n!=null&&typeof n=="object"}function G(n,e,t){if(!ge(n,e,t)||t.ancestors.has(n))return null;t.ancestors.add(n),t.nodes++;let r=n,o=r.kind==="condition"?fe(r,t):r.kind==="group"?ve(r,e,t):null;return t.ancestors.delete(n),o}function B(n,e){if(n==null||typeof n!="object")return null;let t=n;if(t.version!==1||t.root==null)return null;let r=G(t.root,0,{ancestors:new WeakSet,nodes:0,validColumnIds:e});return r?{version:1,root:r}:null}function N(n,e){if(n==null||typeof n!="object"||Array.isArray(n))return{};let t={};for(let[r,o]of Object.entries(n).slice(0,le)){let s=r.trim();if(!s||e?.has(s)===!1)continue;let i=I(o);i&&(t[s]=i)}return t}function f(){return S(void 0,"[MachTable] Server-side operation cancelled or replaced.")}function v(n,e,t,r=1){return n!=null&&Number.isFinite(n)?Math.max(r,Math.min(t,Math.floor(n))):e}function A(n){if(!Array.isArray(n)||n.length>16||n.some(e=>typeof e!="string"||e.length>512))throw new TypeError("[MachTable] Invalid server-side group route.");return[...n]}function D(n,e){let t={...e,...n},r=t.rowGroupCols??[],o=t.valueCols??[];if(r.length>16||o.length>128)throw new RangeError("[MachTable] Server-side query exceeds group/aggregate column limits.");if([...r,...o].some(i=>typeof i.colId!="string"||!i.colId||i.colId.length>512))throw new TypeError("[MachTable] Invalid server-side query column.");return{rowGroupCols:r.map(i=>({colId:i.colId,...i.field?{field:i.field}:{}})),valueCols:o.map(i=>({colId:i.colId,aggFunc:i.aggFunc,...i.field?{field:i.field}:{}})),sortModel:(t.sortModel??[]).slice(0,2e3).filter(i=>i.direction==="asc"||i.direction==="desc").map(i=>({...i})),filterModel:N(t.filterModel),advancedFilterModel:B(t.advancedFilterModel),quickFilterText:t.quickFilterText?.slice(0,1e4)||null}}function me(n,e,t){if(!n||!Array.isArray(n.rows)||n.rows.length>t||!Number.isInteger(n.rowCount)||n.rowCount<0||n.rows.length>0&&n.rowCount<e+n.rows.length||typeof n.revision!="string"||!n.revision||n.revision.length>512)throw new TypeError("[MachTable] Invalid server-side route response.")}function z(n,e,t){return e>0&&n>=e?Math.floor((e-1)/t)*t:null}function K(n,e,t,r){me(n,e,t);let o=new Set,s=new Set;for(let i of n.rows){if(typeof i.id!="string"||!i.id||i.id.length>512||o.has(i.id))throw new TypeError("[MachTable] Duplicate/invalid server-side row ID.");if(o.add(i.id),r){if(typeof i.groupKey!="string"||i.groupKey.length>512||s.has(i.groupKey))throw new TypeError("[MachTable] Duplicate/invalid group key.");s.add(i.groupKey)}else if(i.groupKey!==void 0)throw new TypeError("[MachTable] Leaf routes cannot return group rows.")}return{rows:n.rows.map(i=>({...i})),rowCount:n.rowCount,revision:n.revision}}function O(n,e){return new Promise((t,r)=>{if(e.aborted){r(f());return}let o=()=>{clearTimeout(s),r(f())},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);e.addEventListener("abort",o,{once:!0})})}function j(n,e){return R(n,e,f)}function c(n){return JSON.stringify(n)}function L(n,e){return JSON.stringify([n,e])}function b(n,e){return n.length>=e.length&&e.every((t,r)=>n[r]===t)}var C=class{constructor(){this.selected=new Map;this.r=new Map;this.routes=new Map;this.excludedRoutes=new Map}f(e){let t=!1;for(let r=0;r<=e.length;r++){let o=c(e.slice(0,r));this.routes.has(o)&&(t=!0),this.excludedRoutes.has(o)&&(t=!1)}return t}d(e,t,r=!1){return[...e.values()].some(o=>b(o,t)&&(!r||o.length>t.length))}get(e){if(e.groupKey===void 0)return this.selected.has(e.key)||!this.r.has(e.key)&&this.f(e.route)?"selected":"none";let t=[...e.route,e.groupKey];if(this.r.has(e.key))return this.f(t)?"partial":"none";let r=this.f(t)||this.selected.has(e.key);return(r?this.d(this.r,t)||this.d(this.excludedRoutes,t,!0):this.d(this.selected,t)||this.d(this.routes,t,!0))?"partial":r?"selected":"none"}A(e,t){for(let[r,o]of e)b(o,t)&&e.delete(r)}select(e,t,r){let o=c([...e.route,e.groupKey??e.id]);if(!(this.selected.has(e.key)||this.r.has(e.key)||this.routes.has(o)||this.excludedRoutes.has(o))&&this.selected.size+this.r.size+this.routes.size+this.excludedRoutes.size>=1e4)throw new RangeError("[MachTable] Server-side selection exceeds 10000 explicit rules; clear selection first.");if(e.groupKey!==void 0&&r==="descendants"){let i=[...e.route,e.groupKey];for(let a of[this.selected,this.r,this.routes,this.excludedRoutes])this.A(a,i);this.selected.delete(e.key),this.r.delete(e.key),t?this.routes.set(c(i),i):this.excludedRoutes.set(c(i),i);return}this.selected.delete(e.key),this.r.delete(e.key),t?this.selected.set(e.key,e.route):this.r.set(e.key,e.route)}clear(){this.selected.clear(),this.r.clear(),this.routes.clear(),this.excludedRoutes.clear()}snapshot(){return{selectedKeys:[...this.selected.keys()],excludedKeys:[...this.r.keys()],selectedRoutes:[...this.routes.values()].map(e=>[...e]),excludedRoutes:[...this.excludedRoutes.values()].map(e=>[...e])}}};var m=class extends Error{constructor(t,r){super("[MachTable] Server-side route revision changed; refresh before retrying the transaction.");this.expectedRevision=t;this.actualRevision=r;this.name="ServerSideVersionConflictError"}};var P=class{constructor(e){this.options=e;this.routes=new Map;this.e=new Map;this.indices=new Map;this.expanded=new Set;this.selection=new C;this.c=new Set;this.i=new Set;this.E=0;this.generation=0;this.revision=0;this.disposed=!1;this.v=0;this.snapshot=null;this.query=D(e.query??{}),this.blockSize=v(e.blockSize,100,1e3),this.cache=new T(v(e.maxBlocks,12,256),t=>this.n(t),v(e.maxConcurrentRequests,4,16))}o(){if(this.disposed)throw f()}M(){if(this.v>=256)throw new RangeError("[MachTable] Server-side load queue limit reached (256).")}emit(e=!1){if(!this.disposed){this.snapshot=null,e&&this.revision++;for(let t of this.c)try{t()}catch(r){this.report(r,[])}}}report(e,t){if(e?.name!=="AbortError")try{this.options.onError?.(e,t)}catch{}}state(e){let t=A(e);if(t.length>this.query.rowGroupCols.length)throw new RangeError("[MachTable] Route exceeds configured grouping depth.");let r=c(t),o=this.routes.get(r);if(o)return this.routes.delete(r),this.routes.set(r,o),o;if(this.routes.size>=256){let i=[...this.routes].find(([a,d])=>a!=="[]"&&d.pending===0&&!this.expanded.has(a));if(!i)throw new RangeError("[MachTable] Server-side route metadata limit reached (256).");this.m(i[0]),this.routes.delete(i[0])}let s={route:t,startRow:0,endRow:0,rowCount:null,revision:null,loading:!1,error:null,generation:0,active:null,pending:0,requestVersion:0};return this.routes.set(r,s),s}n(e){this.snapshot=null;let t=this.indices.get(e);if(!t)return;this.indices.delete(e),this.e.get(t.key)===t&&this.e.delete(t.key);let r=this.routes.get(t.route);r?.active===e&&(r.active=null)}m(e,t){for(let r of[...this.indices.values()])r.route!==e||r.index===t||(this.cache.invalidate(r.index),this.n(r.index))}g(){let e=new Set;for(let[t,r]of this.routes)r.active!=null&&(t==="[]"||this.expanded.has(t))&&e.add(r.active);this.cache.T(e)}block(e,t){let r=JSON.stringify([e,t]),o=this.e.get(r);if(o)return o;let s={index:++this.E,key:r,route:e,start:t};return this.e.set(r,s),this.indices.set(s.index,s),s}async fetch(e,t,r){let o=v(this.options.retryCount,1,5,0),s=this.query;for(let i=0;;i++){if(r.aborted)throw f();try{let a=await this.options.getRows({...s,route:[...e.route],startRow:t,endRow:t+this.blockSize,revision:e.revision,signal:r});if(r.aborted)throw f();return K(a,t,this.blockSize,e.route.length<s.rowGroupCols.length)}catch(a){if(r.aborted||i>=o)throw a;await O(Math.min(3e4,v(this.options.retryDelay,200,1e4,0)*2**i),r)}}}current(e,t,r,o){return!this.disposed&&r===this.generation&&e.generation===o&&this.cache.has(t.index)}async load(e=[],t=0,r){this.o(),this.M();let o=this.state(e),s=Math.floor(v(t,0,Number.MAX_SAFE_INTEGER,0)/this.blockSize)*this.blockSize,i=this.block(c(o.route),s),a=this.generation,d=o.generation,u=++o.requestVersion;this.v++,o.pending++,o.loading=!0,o.error=null,this.g(),this.emit();try{let l=await this.cache.load(i.index,async M=>({rows:[await this.fetch(o,s,M)]}),r,100);if(!this.current(o,i,a,d))throw f();if(u!==o.requestVersion)return;let h=l.rows[0];o.revision!=null&&o.revision!==h.revision&&(o.generation++,this.m(i.route,i.index)),o.revision=h.revision;let p=z(s,h.rowCount,this.blockSize);if(p!=null){await this.load(o.route,p,r);return}o.active=i.index,o.startRow=s,o.endRow=s+h.rows.length,o.rowCount=h.rowCount,o.revision=h.revision,this.g(),this.emit(!0),await this.R(o.route)}catch(l){throw this.D(o,a,d,u)&&(o.error=l?.name==="AbortError"?null:l,this.report(l,o.route)),l}finally{o.pending=Math.max(0,o.pending-1),this.v--,u===o.requestVersion&&(o.loading=!1),this.cache.has(i.index)||this.n(i.index),a===this.generation&&this.emit()}}D(e,t,r,o){return!this.disposed&&t===this.generation&&e.generation===r&&o===e.requestVersion}async expand(e){this.o();let t=A(e),r=this.state(t),o=c(t);if(!this.expanded.has(o)&&this.expanded.size>=128)throw new RangeError("[MachTable] Expanded group limit reached (128).");this.expanded.add(o),this.emit(!0),r.active==null?await this.load(t,r.startRow):await this.R(t)}collapse(e){let t=A(e);for(let r of this.expanded)b(JSON.parse(r),t)&&this.expanded.delete(r);this.g(),this.emit(!0)}P(e){for(let[t,r]of this.routes)b(r.route,e)&&(r.generation++,r.active=null,r.revision=null,r.error=null,this.m(t))}async R(e){let t=this.routes.get(c(e)),r=t?.active==null?void 0:this.cache.peek(t.active)?.rows[0];if(!r)return;let o=r.rows.flatMap(s=>s.groupKey!==void 0&&this.expanded.has(c([...e,s.groupKey]))?[[...e,s.groupKey]]:[]);await Promise.all(o.map(s=>this.expand(s)))}async refresh(e=[]){this.o();let t=this.state(e);this.P(t.route),this.emit(!0),await this.load(t.route,t.startRow)}async setQuery(e){this.o();let t=D(e,this.query);if(JSON.stringify(t)!==JSON.stringify(this.query)){this.generation++,this.cache.x(),this.e.clear(),this.indices.clear(),this.routes.clear(),this.expanded.clear();for(let r of this.i)r.abort();this.selection.clear(),this.query=t,this.emit(!0),await this.load()}}async transact(e){this.o();let t=this.state(e.route);if(t.revision!==e.expectedRevision)throw new m(e.expectedRevision,t.revision);if(!this.options.transact)throw new Error("[MachTable] A server-side transaction transport is required.");if(this.i.size>=v(this.options.maxConcurrentRequests,4,16))throw new RangeError("[MachTable] Too many active server-side transactions.");let r=new AbortController;this.i.add(r);let o=this.generation,s=t.generation;try{let i=await j(Promise.resolve().then(()=>{if(r.signal.aborted)throw f();return this.options.transact({...e,route:[...t.route],query:this.query,signal:r.signal})}),r.signal);if(r.signal.aborted||o!==this.generation||s!==t.generation)throw f();if(typeof i?.revision!="string"||!i.revision||i.revision.length>512)throw new TypeError("[MachTable] Transaction transport must return the committed revision.");await this.refresh([])}finally{this.i.delete(r)}}select(e,t,r="descendants"){this.o(),this.selection.select(e,t,r),this.emit()}getSelection(e){return this.selection.get(e)}clearSelection(){this.selection.clear(),this.emit()}getSnapshot(){if(this.snapshot)return this.snapshot;let e=[],t=r=>{let o=this.routes.get(c(r)),s=o?.active==null?void 0:this.cache.peek(o.active)?.rows[0];if(s)for(let i of s.rows){let a=i.groupKey!==void 0&&this.expanded.has(c([...r,i.groupKey]));e.push({...i,key:L(r,i.id),route:[...r],depth:r.length,expanded:a}),a&&t([...r,i.groupKey])}};return t([]),this.snapshot={rows:e,routes:[...this.routes.values()].map(({route:r,startRow:o,endRow:s,rowCount:i,revision:a,loading:d,error:u})=>({route:[...r],startRow:o,endRow:s,rowCount:i,revision:a,loading:d,error:u})),selection:this.selection.snapshot(),query:D(this.query),revision:this.revision,cachedBlockCount:this.cache.snapshot().cachedBlockCount},this.snapshot}subscribe(e){return this.o(),this.c.add(e),()=>this.c.delete(e)}dispose(){if(!this.disposed){this.disposed=!0,this.generation++,this.cache.x();for(let e of this.i)e.abort();this.i.clear(),this.routes.clear(),this.e.clear(),this.indices.clear(),this.expanded.clear(),this.selection.clear(),this.c.clear(),this.snapshot=null}}};function _(n){return new P(n)}var ye=new Set(["__proto__","prototype","constructor"]),w=new Map;function Se(n){if(typeof n!="string"||n.length===0)return null;let e=w.get(n);if(e!==void 0)return e;let t=n.split("."),r=t.every(o=>o.length>0&&!ye.has(o))?t:null;return n.length<=1024&&(w.size>=256&&w.delete(w.keys().next().value),w.set(n,r)),r}function Q(n,e){if(n==null)return;let t=Se(e);if(!t)return;let r=n;for(let o of t){if(r==null)return;r=r[o]}return r}var be=Symbol.for("mach-table.adapter.lifecycle.v1");function q(n){return!n.isDestroyed()&&(n[be]?.canReplaceData()??!1)}function y(n,e,t=!1){let r=document.createElement("button");return r.type="button",r.className="mach-server-button",r.textContent=n,r.disabled=t,r.addEventListener("click",o=>{o.stopPropagation();try{Promise.resolve(e()).catch(()=>{})}catch{}}),r}function we(n){return n?n.loading?"\u52A0\u8F7D\u4E2D\u2026":n.error?"\u52A0\u8F7D\u5931\u8D25":`${n.endRow>n.startRow?n.startRow+1:0}\u2013${n.endRow} / ${n.rowCount??"?"}`:"\u5C1A\u672A\u52A0\u8F7D"}function V(n,e){let t=n.getSnapshot().routes.find(s=>c(s.route)===c(e)),r=document.createElement("span");r.className="mach-server-paging";let o=document.createElement("span");return o.className="mach-server-range",o.textContent=we(t),o.setAttribute("aria-live","polite"),r.append(o),r.append(y("\u4E0A\u4E00\u9875",()=>n.load(e,Math.max(0,(t?.startRow??0)-1)),!t||t.loading||t.startRow===0)),r.append(y("\u4E0B\u4E00\u9875",()=>n.load(e,t?.endRow??0),!t||t.loading||t.rowCount===null||t.endRow>=t.rowCount)),t?.error&&r.append(y("\u91CD\u8BD5",()=>n.refresh(e))),r}function W(n,e={}){return{colId:"__server_group",headerName:e.headerName??"\u670D\u52A1\u7AEF\u5206\u7EC4",width:e.width??420,minWidth:260,pinned:"left",sortable:!1,filter:!1,editable:!1,headerComponent:()=>{let t=document.createElement("div");t.className="mach-server-header";let r=()=>{t.replaceChildren(V(n,[]),y("\u5237\u65B0",()=>n.refresh()),y("\u6E05\u9664\u9009\u62E9",()=>n.clearSelection()))};return r(),{el:t,destroy:n.subscribe(r)}},cellRenderer:({data:t})=>{if(!t)return"";let r=document.createElement("div");r.className="mach-server-cell",r.style.paddingInlineStart=`${t.depth*16}px`;let o=document.createElement("input");o.type="checkbox";let s=n.getSelection(t);if(o.checked=s==="selected",o.indeterminate=s==="partial",o.setAttribute("aria-label",`\u9009\u62E9 ${t.groupKey??t.id}`),o.addEventListener("click",a=>{a.stopPropagation(),n.select(t,o.checked)}),r.append(o),t.groupKey!==void 0){let a=[...t.route,t.groupKey],d=y(t.expanded?"\u25BE":"\u25B8",()=>t.expanded?n.collapse(a):n.expand(a));d.setAttribute("aria-expanded",String(t.expanded)),d.setAttribute("aria-label",`${t.expanded?"\u6536\u8D77":"\u5C55\u5F00"} ${t.groupKey||"\u7A7A\u767D\u5206\u7EC4"}`),r.append(d)}let i=document.createElement("span");return i.className="mach-server-label",i.textContent=e.label?.(t)??t.groupKey??t.id,r.append(i),t.expanded&&t.groupKey!==void 0&&r.append(V(n,[...t.route,t.groupKey])),r}}}function $(n,e={}){let t=e.colId??n;return{...e,colId:t,headerName:e.headerName??n,editable:!1,valueGetter:({data:r})=>r?.groupKey!==void 0&&r.aggValues&&Object.prototype.hasOwnProperty.call(r.aggValues,t)?r.aggValues[t]:Q(r?.data,n)}}function Re(n,e){var r;let t=n.querySelectorAll(".mach-server-header button,.mach-server-cell button,.mach-server-cell input");for(let o of t)e?((r=o.dataset).serverWasDisabled??(r.serverWasDisabled=String(o.disabled)),o.disabled=!0):o.dataset.serverWasDisabled!==void 0&&(o.disabled=o.dataset.serverWasDisabled==="true",delete o.dataset.serverWasDisabled)}function H(n,e){let t=n.view.getRoot();if(!t)return;Re(t,e);let r=t.querySelector(".mach-server-sync-notice");if(!e){r?.remove(),delete t.dataset.serverPending;return}if(t.dataset.serverPending="true",r)return;let o=document.createElement("div");o.className="mach-server-sync-notice",o.setAttribute("role","status"),o.textContent="\u65B0\u6570\u636E\u7B49\u5F85\u663E\u793A\uFF1A\u8BF7\u5148\u4FDD\u5B58\u3001\u53D6\u6D88\u7F16\u8F91\u6216\u56DE\u6EDA\u4FEE\u6539",t.append(o)}function J(n,e){if(!q(n))throw new Error("[MachTable] Save or cancel grid edits before binding server-side data.");let t=!1,r=-1,o=!1,s=()=>{if(t||o||n.isDestroyed())return;let l=e.getSnapshot(),h=l.revision!==r&&!q(n);if(H(n,h),!h){t=!0;try{l.revision!==r&&(r=l.revision,n.rows.setData([...l.rows])),n.selection.setRows(l.rows.filter(p=>e.getSelection(p)==="selected"),!0),n.view.refreshCells()}finally{t=!1}}},i=()=>{t||o||e.setQuery({sortModel:n.sorting.getModel(),filterModel:n.filtering.getModel(),advancedFilterModel:n.filtering.getAdvancedModel(),quickFilterText:n.filtering.getQuickText()}).catch(()=>{})},a=()=>{e.getSnapshot().revision!==r&&s()};n.updateOptions({rowKey:l=>l.key,rowSelection:"multiple",manualFiltering:!0,manualSorting:!0,pagination:!1});let d=[e.subscribe(s),n.on("sortChanged",i),n.on("filterChanged",i),n.on("dirtyStateChanged",a),n.on("cellEditingStopped",a),n.on("rowEditingStopped",a),n.on("selectionChanged",()=>{if(t||o||e.getSnapshot().revision!==r)return;let l=new Set(n.selection.getIds()),h=e.getSnapshot().rows.filter(p=>l.has(p.key)!==(e.getSelection(p)==="selected"));for(let p of h)e.select(p,l.has(p.key))})],u=()=>{if(!o){o=!0;for(let l of d)l();H(n,!1),e.dispose()}};return d.push(n.on("gridDestroyed",u)),s(),e.setQuery({sortModel:n.sorting.getModel(),filterModel:n.filtering.getModel(),advancedFilterModel:n.filtering.getAdvancedModel(),quickFilterText:n.filtering.getQuickText()}).then(()=>e.getSnapshot().routes.length===0?e.load():void 0).catch(()=>{}),u}0&&(module.exports={ServerSideVersionConflictError,bindServerSideGrid,createServerSideGroupColumn,createServerSideStore,serverSideDataColumn});
@@ -1,4 +1,4 @@
1
- import { S as SortModel, h as FilterModel, A as AdvancedFilterModel, b as GridApi, C as ColDef, i as FieldPath } from './api-CUQtfQR4.cjs';
1
+ import { S as SortModel, h as FilterModel, A as AdvancedFilterModel, b as GridApi, C as ColDef, i as FieldPath } from './api-QsIvYp7X.cjs';
2
2
 
3
3
  interface ServerSideGroupColumn {
4
4
  colId: string;
@@ -1,4 +1,4 @@
1
- import { S as SortModel, h as FilterModel, A as AdvancedFilterModel, b as GridApi, C as ColDef, i as FieldPath } from './api-CUQtfQR4.js';
1
+ import { S as SortModel, h as FilterModel, A as AdvancedFilterModel, b as GridApi, C as ColDef, i as FieldPath } from './api-QsIvYp7X.js';
2
2
 
3
3
  interface ServerSideGroupColumn {
4
4
  colId: string;
@@ -1 +1 @@
1
- function y(n,e){if(n instanceof Error)return n;let t=new Error(typeof n=="string"?n:e);return t.name="AbortError",t}var H=()=>y(void 0,"[MachTable] Operation cancelled.");function R(n,e,t=H){return e?new Promise((r,o)=>{let s=()=>{e.removeEventListener("abort",s),o(t())};if(n.then(r,o).finally(()=>e.removeEventListener("abort",s)),e.aborted){s();return}e.addEventListener("abort",s,{once:!0})}):n}function g(n){return y(n.reason,"Block request aborted")}function x(n){return Number.isFinite(n)?Math.max(1,Math.trunc(n)):1}var T=class{constructor(e,t,r=4){this.maxBlocks=e;this.n=t;this.maxConcurrentRequests=r;this.e=new Map;this.t=new Map;this.m=0;this.generation=0;this.hitCount=0;this.missCount=0;this.evictionCount=0;this.s=0;this.a=new Set;this.maxBlocks=x(e),this.maxConcurrentRequests=x(r)}configure(e,t=this.maxConcurrentRequests){this.maxBlocks=x(e),this.maxConcurrentRequests=x(t),this.u(),this.l()}b(e){this.a=e,this.u()}peek(e){let t=this.e.get(e);if(t)return t.touchedAt=++this.m,t}has(e){return this.e.has(e)}invalidate(e){let t=this.t.get(e);t&&(this.t.delete(e),t.controller.abort(),t.state==="queued"&&t.reject(g(t.controller.signal)));let r=this.e.get(e);r&&(this.e.delete(e),this.n?.(e,r))}load(e,t,r,o=0){if(r?.aborted)return Promise.reject(g(r));let s=this.peek(e);if(s)return this.hitCount++,Promise.resolve(s);let i=this.t.get(e);if(i)return this.hitCount++,i.priority=Math.max(i.priority,o),this.l(),this.g(e,i,r);this.missCount++;let a=new AbortController,d,u,l=new Promise((M,V)=>{d=M,u=V}),h={controller:a,promise:l,consumers:0,loader:t,priority:o,state:"queued",resolve:d,reject:u};this.t.set(e,h);let p=this.g(e,h,r);return this.l(),p}y(){this.generation++,this.a.clear();for(let e of this.t.values())e.controller.abort(),e.state==="queued"&&e.reject(g(e.controller.signal));this.t.clear();for(let[e,t]of this.e)this.n?.(e,t);this.e.clear()}snapshot(){let e=0,t=0;for(let r of this.e.values())e+=r.rows.length;for(let r of this.t.values())r.state==="active"&&t++;return{cachedBlockCount:this.e.size,loadingBlockCount:this.t.size,activeRequestCount:t,queuedRequestCount:Math.max(0,this.t.size-t),cachedRowCount:e,hitCount:this.hitCount,missCount:this.missCount,evictionCount:this.evictionCount}}l(){for(;this.s<this.maxConcurrentRequests;){let e,t;for(let[r,o]of this.t)o.state!=="queued"||o.controller.signal.aborted||(!t||o.priority>t.priority)&&(e=r,t=o);if(e==null||!t)return;this.w(e,t)}}w(e,t){t.state="active",this.s++;let r=this.generation;this.x(t).then(o=>{r===this.generation&&!t.controller.signal.aborted&&(this.e.set(e,{rows:o.rows,...o.lastRow==null?{}:{lastRow:o.lastRow},touchedAt:++this.m}),this.u()),t.resolve(o)},t.reject).finally(()=>{this.s=Math.max(0,this.s-1),this.t.get(e)===t&&this.t.delete(e),this.l()})}x(e){let{signal:t}=e.controller;return R(Promise.resolve().then(()=>{if(t.aborted)throw g(t);return e.loader(t)}),t,()=>g(t))}g(e,t,r){return t.consumers++,new Promise((o,s)=>{let i=!1,a=u=>{i||(i=!0,r?.removeEventListener("abort",d),t.consumers=Math.max(0,t.consumers-1),u())},d=()=>a(()=>{t.consumers===0&&this.t.get(e)===t&&(this.t.delete(e),t.controller.abort(r?.reason),t.state==="queued"&&t.reject(g(t.controller.signal))),s(g(r))});r?.addEventListener("abort",d,{once:!0}),t.promise.then(u=>a(()=>o(u)),u=>a(()=>s(u instanceof Error?u:new Error(String(u??"Block request failed")))))})}u(){let e=Math.max(this.maxBlocks,this.a.size+1);for(;this.e.size>e;){let t=-1,r=Number.POSITIVE_INFINITY;for(let[s,i]of this.e)this.a.has(s)||i.touchedAt<r&&(t=s,r=i.touchedAt);if(t<0)return;let o=this.e.get(t);this.e.delete(t),this.evictionCount++,o&&this.n?.(t,o)}}};var k={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 W=16,$=512,J=20,X=2e3,U=2e3,Y={text:new Set(k.text),number:new Set(k.number),date:new Set(k.date)};function Z(n){return n==null||typeof n=="string"||typeof n=="number"&&Number.isFinite(n)}function ee(n,e,t){if(n==null||typeof n!="object")return null;let r=n;return typeof r.match!="string"||!t.has(r.match)?null:{match:r.match,...te(r,e)}}function te(n,e){let t=e==="number"?q(n.value):typeof n.value=="string"?n.value:void 0,r=e==="number"?q(n.value2):typeof n.value2=="string"?n.value2:void 0;return{...t!==void 0?{value:t}:{},...r!==void 0?{value2:r}:{}}}function q(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function re(n,e){let t=[],r=Y[e];for(let o of n.slice(0,J)){let s=ee(o,e,r);s&&t.push(s)}return t}function F(n){if(n==null||typeof n!="object")return null;let e=n;return e.type==="set"?Array.isArray(e.values)?{type:"set",values:e.values.filter(Z).slice(0,X)}:null:e.type!=="text"&&e.type!=="number"&&e.type!=="date"||!Array.isArray(e.conditions)?null:{type:e.type,...e.operator==="or"||e.operator==="and"?{operator:e.operator}:{},conditions:re(e.conditions,e.type)}}function ne(n,e){if(typeof n.colId!="string"||!n.colId.trim())return null;let t=n.colId.trim();if(e.validColumnIds?.has(t)===!1)return null;let r=F(n.filter);return r?{kind:"condition",colId:t,filter:r}:null}function oe(n,e,t){if(!Array.isArray(n.children))return null;let r=[];for(let o of n.children){let s=I(o,e+1,t);s&&r.push(s)}return r.length===0?null:{kind:"group",operator:n.operator==="or"?"or":"and",children:r,...n.not===!0?{not:!0}:{}}}function ie(n,e,t){return e<=W&&t.nodes<$&&n!=null&&typeof n=="object"}function I(n,e,t){if(!ie(n,e,t)||t.ancestors.has(n))return null;t.ancestors.add(n),t.nodes++;let r=n,o=r.kind==="condition"?ne(r,t):r.kind==="group"?oe(r,e,t):null;return t.ancestors.delete(n),o}function G(n,e){if(n==null||typeof n!="object")return null;let t=n;if(t.version!==1||t.root==null)return null;let r=I(t.root,0,{ancestors:new WeakSet,nodes:0,validColumnIds:e});return r?{version:1,root:r}:null}function B(n,e){if(n==null||typeof n!="object"||Array.isArray(n))return{};let t={};for(let[r,o]of Object.entries(n).slice(0,U)){let s=r.trim();if(!s||e?.has(s)===!1)continue;let i=F(o);i&&(t[s]=i)}return t}function f(){return y(void 0,"[MachTable] Server-side operation cancelled or replaced.")}function v(n,e,t,r=1){return n!=null&&Number.isFinite(n)?Math.max(r,Math.min(t,Math.floor(n))):e}function A(n){if(!Array.isArray(n)||n.length>16||n.some(e=>typeof e!="string"||e.length>512))throw new TypeError("[MachTable] Invalid server-side group route.");return[...n]}function C(n,e){let t={...e,...n},r=t.rowGroupCols??[],o=t.valueCols??[];if(r.length>16||o.length>128)throw new RangeError("[MachTable] Server-side query exceeds group/aggregate column limits.");if([...r,...o].some(i=>typeof i.colId!="string"||!i.colId||i.colId.length>512))throw new TypeError("[MachTable] Invalid server-side query column.");return{rowGroupCols:r.map(i=>({colId:i.colId,...i.field?{field:i.field}:{}})),valueCols:o.map(i=>({colId:i.colId,aggFunc:i.aggFunc,...i.field?{field:i.field}:{}})),sortModel:(t.sortModel??[]).slice(0,2e3).filter(i=>i.direction==="asc"||i.direction==="desc").map(i=>({...i})),filterModel:B(t.filterModel),advancedFilterModel:G(t.advancedFilterModel),quickFilterText:t.quickFilterText?.slice(0,1e4)||null}}function se(n,e,t){if(!n||!Array.isArray(n.rows)||n.rows.length>t||!Number.isInteger(n.rowCount)||n.rowCount<0||n.rows.length>0&&n.rowCount<e+n.rows.length||typeof n.revision!="string"||!n.revision||n.revision.length>512)throw new TypeError("[MachTable] Invalid server-side route response.")}function N(n,e,t){return e>0&&n>=e?Math.floor((e-1)/t)*t:null}function z(n,e,t,r){se(n,e,t);let o=new Set,s=new Set;for(let i of n.rows){if(typeof i.id!="string"||!i.id||i.id.length>512||o.has(i.id))throw new TypeError("[MachTable] Duplicate/invalid server-side row ID.");if(o.add(i.id),r){if(typeof i.groupKey!="string"||i.groupKey.length>512||s.has(i.groupKey))throw new TypeError("[MachTable] Duplicate/invalid group key.");s.add(i.groupKey)}else if(i.groupKey!==void 0)throw new TypeError("[MachTable] Leaf routes cannot return group rows.")}return{rows:n.rows.map(i=>({...i})),rowCount:n.rowCount,revision:n.revision}}function K(n,e){return new Promise((t,r)=>{if(e.aborted){r(f());return}let o=()=>{clearTimeout(s),r(f())},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);e.addEventListener("abort",o,{once:!0})})}function O(n,e){return R(n,e,f)}function c(n){return JSON.stringify(n)}function j(n,e){return JSON.stringify([n,e])}function S(n,e){return n.length>=e.length&&e.every((t,r)=>n[r]===t)}var D=class{constructor(){this.selected=new Map;this.r=new Map;this.routes=new Map;this.excludedRoutes=new Map}h(e){let t=!1;for(let r=0;r<=e.length;r++){let o=c(e.slice(0,r));this.routes.has(o)&&(t=!0),this.excludedRoutes.has(o)&&(t=!1)}return t}c(e,t,r=!1){return[...e.values()].some(o=>S(o,t)&&(!r||o.length>t.length))}get(e){if(e.groupKey===void 0)return this.selected.has(e.key)||!this.r.has(e.key)&&this.h(e.route)?"selected":"none";let t=[...e.route,e.groupKey];if(this.r.has(e.key))return this.h(t)?"partial":"none";let r=this.h(t)||this.selected.has(e.key);return(r?this.c(this.r,t)||this.c(this.excludedRoutes,t,!0):this.c(this.selected,t)||this.c(this.routes,t,!0))?"partial":r?"selected":"none"}R(e,t){for(let[r,o]of e)S(o,t)&&e.delete(r)}select(e,t,r){let o=c([...e.route,e.groupKey??e.id]);if(!(this.selected.has(e.key)||this.r.has(e.key)||this.routes.has(o)||this.excludedRoutes.has(o))&&this.selected.size+this.r.size+this.routes.size+this.excludedRoutes.size>=1e4)throw new RangeError("[MachTable] Server-side selection exceeds 10000 explicit rules; clear selection first.");if(e.groupKey!==void 0&&r==="descendants"){let i=[...e.route,e.groupKey];for(let a of[this.selected,this.r,this.routes,this.excludedRoutes])this.R(a,i);this.selected.delete(e.key),this.r.delete(e.key),t?this.routes.set(c(i),i):this.excludedRoutes.set(c(i),i);return}this.selected.delete(e.key),this.r.delete(e.key),t?this.selected.set(e.key,e.route):this.r.set(e.key,e.route)}clear(){this.selected.clear(),this.r.clear(),this.routes.clear(),this.excludedRoutes.clear()}snapshot(){return{selectedKeys:[...this.selected.keys()],excludedKeys:[...this.r.keys()],selectedRoutes:[...this.routes.values()].map(e=>[...e]),excludedRoutes:[...this.excludedRoutes.values()].map(e=>[...e])}}};var b=class extends Error{constructor(t,r){super("[MachTable] Server-side route revision changed; refresh before retrying the transaction.");this.expectedRevision=t;this.actualRevision=r;this.name="ServerSideVersionConflictError"}};var E=class{constructor(e){this.options=e;this.routes=new Map;this.e=new Map;this.indices=new Map;this.expanded=new Set;this.selection=new D;this.d=new Set;this.i=new Set;this.T=0;this.generation=0;this.revision=0;this.disposed=!1;this.p=0;this.snapshot=null;this.query=C(e.query??{}),this.blockSize=v(e.blockSize,100,1e3),this.cache=new T(v(e.maxBlocks,12,256),t=>this.n(t),v(e.maxConcurrentRequests,4,16))}o(){if(this.disposed)throw f()}k(){if(this.p>=256)throw new RangeError("[MachTable] Server-side load queue limit reached (256).")}emit(e=!1){if(!this.disposed){this.snapshot=null,e&&this.revision++;for(let t of this.d)try{t()}catch(r){this.report(r,[])}}}report(e,t){if(e?.name!=="AbortError")try{this.options.onError?.(e,t)}catch{}}state(e){let t=A(e);if(t.length>this.query.rowGroupCols.length)throw new RangeError("[MachTable] Route exceeds configured grouping depth.");let r=c(t),o=this.routes.get(r);if(o)return this.routes.delete(r),this.routes.set(r,o),o;if(this.routes.size>=256){let i=[...this.routes].find(([a,d])=>a!=="[]"&&d.pending===0&&!this.expanded.has(a));if(!i)throw new RangeError("[MachTable] Server-side route metadata limit reached (256).");this.f(i[0]),this.routes.delete(i[0])}let s={route:t,startRow:0,endRow:0,rowCount:null,revision:null,loading:!1,error:null,generation:0,active:null,pending:0,requestVersion:0};return this.routes.set(r,s),s}n(e){this.snapshot=null;let t=this.indices.get(e);if(!t)return;this.indices.delete(e),this.e.get(t.key)===t&&this.e.delete(t.key);let r=this.routes.get(t.route);r?.active===e&&(r.active=null)}f(e,t){for(let r of[...this.indices.values()])r.route!==e||r.index===t||(this.cache.invalidate(r.index),this.n(r.index))}v(){let e=new Set;for(let[t,r]of this.routes)r.active!=null&&(t==="[]"||this.expanded.has(t))&&e.add(r.active);this.cache.b(e)}block(e,t){let r=JSON.stringify([e,t]),o=this.e.get(r);if(o)return o;let s={index:++this.T,key:r,route:e,start:t};return this.e.set(r,s),this.indices.set(s.index,s),s}async fetch(e,t,r){let o=v(this.options.retryCount,1,5,0),s=this.query;for(let i=0;;i++){if(r.aborted)throw f();try{let a=await this.options.getRows({...s,route:[...e.route],startRow:t,endRow:t+this.blockSize,revision:e.revision,signal:r});if(r.aborted)throw f();return z(a,t,this.blockSize,e.route.length<s.rowGroupCols.length)}catch(a){if(r.aborted||i>=o)throw a;await K(Math.min(3e4,v(this.options.retryDelay,200,1e4,0)*2**i),r)}}}current(e,t,r,o){return!this.disposed&&r===this.generation&&e.generation===o&&this.cache.has(t.index)}async load(e=[],t=0,r){this.o(),this.k();let o=this.state(e),s=Math.floor(v(t,0,Number.MAX_SAFE_INTEGER,0)/this.blockSize)*this.blockSize,i=this.block(c(o.route),s),a=this.generation,d=o.generation,u=++o.requestVersion;this.p++,o.pending++,o.loading=!0,o.error=null,this.v(),this.emit();try{let l=await this.cache.load(i.index,async M=>({rows:[await this.fetch(o,s,M)]}),r,100);if(!this.current(o,i,a,d))throw f();if(u!==o.requestVersion)return;let h=l.rows[0];o.revision!=null&&o.revision!==h.revision&&(o.generation++,this.f(i.route,i.index)),o.revision=h.revision;let p=N(s,h.rowCount,this.blockSize);if(p!=null){await this.load(o.route,p,r);return}o.active=i.index,o.startRow=s,o.endRow=s+h.rows.length,o.rowCount=h.rowCount,o.revision=h.revision,this.v(),this.emit(!0),await this.S(o.route)}catch(l){throw this.C(o,a,d,u)&&(o.error=l?.name==="AbortError"?null:l,this.report(l,o.route)),l}finally{o.pending=Math.max(0,o.pending-1),this.p--,u===o.requestVersion&&(o.loading=!1),this.cache.has(i.index)||this.n(i.index),a===this.generation&&this.emit()}}C(e,t,r,o){return!this.disposed&&t===this.generation&&e.generation===r&&o===e.requestVersion}async expand(e){this.o();let t=A(e),r=this.state(t),o=c(t);if(!this.expanded.has(o)&&this.expanded.size>=128)throw new RangeError("[MachTable] Expanded group limit reached (128).");this.expanded.add(o),this.emit(!0),r.active==null?await this.load(t,r.startRow):await this.S(t)}collapse(e){let t=A(e);for(let r of this.expanded)S(JSON.parse(r),t)&&this.expanded.delete(r);this.v(),this.emit(!0)}A(e){for(let[t,r]of this.routes)S(r.route,e)&&(r.generation++,r.active=null,r.revision=null,r.error=null,this.f(t))}async S(e){let t=this.routes.get(c(e)),r=t?.active==null?void 0:this.cache.peek(t.active)?.rows[0];if(!r)return;let o=r.rows.flatMap(s=>s.groupKey!==void 0&&this.expanded.has(c([...e,s.groupKey]))?[[...e,s.groupKey]]:[]);await Promise.all(o.map(s=>this.expand(s)))}async refresh(e=[]){this.o();let t=this.state(e);this.A(t.route),this.emit(!0),await this.load(t.route,t.startRow)}async setQuery(e){this.o();let t=C(e,this.query);if(JSON.stringify(t)!==JSON.stringify(this.query)){this.generation++,this.cache.y(),this.e.clear(),this.indices.clear(),this.routes.clear(),this.expanded.clear();for(let r of this.i)r.abort();this.selection.clear(),this.query=t,this.emit(!0),await this.load()}}async transact(e){this.o();let t=this.state(e.route);if(t.revision!==e.expectedRevision)throw new b(e.expectedRevision,t.revision);if(!this.options.transact)throw new Error("[MachTable] A server-side transaction transport is required.");if(this.i.size>=v(this.options.maxConcurrentRequests,4,16))throw new RangeError("[MachTable] Too many active server-side transactions.");let r=new AbortController;this.i.add(r);let o=this.generation,s=t.generation;try{let i=await O(Promise.resolve().then(()=>{if(r.signal.aborted)throw f();return this.options.transact({...e,route:[...t.route],query:this.query,signal:r.signal})}),r.signal);if(r.signal.aborted||o!==this.generation||s!==t.generation)throw f();if(typeof i?.revision!="string"||!i.revision||i.revision.length>512)throw new TypeError("[MachTable] Transaction transport must return the committed revision.");await this.refresh([])}finally{this.i.delete(r)}}select(e,t,r="descendants"){this.o(),this.selection.select(e,t,r),this.emit()}getSelection(e){return this.selection.get(e)}clearSelection(){this.selection.clear(),this.emit()}getSnapshot(){if(this.snapshot)return this.snapshot;let e=[],t=r=>{let o=this.routes.get(c(r)),s=o?.active==null?void 0:this.cache.peek(o.active)?.rows[0];if(s)for(let i of s.rows){let a=i.groupKey!==void 0&&this.expanded.has(c([...r,i.groupKey]));e.push({...i,key:j(r,i.id),route:[...r],depth:r.length,expanded:a}),a&&t([...r,i.groupKey])}};return t([]),this.snapshot={rows:e,routes:[...this.routes.values()].map(({route:r,startRow:o,endRow:s,rowCount:i,revision:a,loading:d,error:u})=>({route:[...r],startRow:o,endRow:s,rowCount:i,revision:a,loading:d,error:u})),selection:this.selection.snapshot(),query:C(this.query),revision:this.revision,cachedBlockCount:this.cache.snapshot().cachedBlockCount},this.snapshot}subscribe(e){return this.o(),this.d.add(e),()=>this.d.delete(e)}dispose(){if(!this.disposed){this.disposed=!0,this.generation++,this.cache.y();for(let e of this.i)e.abort();this.i.clear(),this.routes.clear(),this.e.clear(),this.indices.clear(),this.expanded.clear(),this.selection.clear(),this.d.clear(),this.snapshot=null}}};function ae(n){return new E(n)}var le=new Set(["__proto__","prototype","constructor"]),w=new Map;function de(n){if(typeof n!="string"||n.length===0)return null;let e=w.get(n);if(e!==void 0)return e;let t=n.split("."),r=t.every(o=>o.length>0&&!le.has(o))?t:null;return n.length<=1024&&(w.size>=256&&w.delete(w.keys().next().value),w.set(n,r)),r}function L(n,e){if(n==null)return;let t=de(e);if(!t)return;let r=n;for(let o of t){if(r==null)return;r=r[o]}return r}var ue=Symbol.for("mach-table.adapter.lifecycle.v1");function P(n){return!n.isDestroyed()&&(n[ue]?.canReplaceData()??!1)}function m(n,e,t=!1){let r=document.createElement("button");return r.type="button",r.className="mach-server-button",r.textContent=n,r.disabled=t,r.addEventListener("click",o=>{o.stopPropagation();try{Promise.resolve(e()).catch(()=>{})}catch{}}),r}function ce(n){return n?n.loading?"\u52A0\u8F7D\u4E2D\u2026":n.error?"\u52A0\u8F7D\u5931\u8D25":`${n.endRow>n.startRow?n.startRow+1:0}\u2013${n.endRow} / ${n.rowCount??"?"}`:"\u5C1A\u672A\u52A0\u8F7D"}function _(n,e){let t=n.getSnapshot().routes.find(s=>c(s.route)===c(e)),r=document.createElement("span");r.className="mach-server-paging";let o=document.createElement("span");return o.className="mach-server-range",o.textContent=ce(t),o.setAttribute("aria-live","polite"),r.append(o),r.append(m("\u4E0A\u4E00\u9875",()=>n.load(e,Math.max(0,(t?.startRow??0)-1)),!t||t.loading||t.startRow===0)),r.append(m("\u4E0B\u4E00\u9875",()=>n.load(e,t?.endRow??0),!t||t.loading||t.rowCount===null||t.endRow>=t.rowCount)),t?.error&&r.append(m("\u91CD\u8BD5",()=>n.refresh(e))),r}function he(n,e={}){return{colId:"__server_group",headerName:e.headerName??"\u670D\u52A1\u7AEF\u5206\u7EC4",width:e.width??420,minWidth:260,pinned:"left",sortable:!1,filter:!1,editable:!1,headerComponent:()=>{let t=document.createElement("div");t.className="mach-server-header";let r=()=>{t.replaceChildren(_(n,[]),m("\u5237\u65B0",()=>n.refresh()),m("\u6E05\u9664\u9009\u62E9",()=>n.clearSelection()))};return r(),{el:t,destroy:n.subscribe(r)}},cellRenderer:({data:t})=>{if(!t)return"";let r=document.createElement("div");r.className="mach-server-cell",r.style.paddingInlineStart=`${t.depth*16}px`;let o=document.createElement("input");o.type="checkbox";let s=n.getSelection(t);if(o.checked=s==="selected",o.indeterminate=s==="partial",o.setAttribute("aria-label",`\u9009\u62E9 ${t.groupKey??t.id}`),o.addEventListener("click",a=>{a.stopPropagation(),n.select(t,o.checked)}),r.append(o),t.groupKey!==void 0){let a=[...t.route,t.groupKey],d=m(t.expanded?"\u25BE":"\u25B8",()=>t.expanded?n.collapse(a):n.expand(a));d.setAttribute("aria-expanded",String(t.expanded)),d.setAttribute("aria-label",`${t.expanded?"\u6536\u8D77":"\u5C55\u5F00"} ${t.groupKey||"\u7A7A\u767D\u5206\u7EC4"}`),r.append(d)}let i=document.createElement("span");return i.className="mach-server-label",i.textContent=e.label?.(t)??t.groupKey??t.id,r.append(i),t.expanded&&t.groupKey!==void 0&&r.append(_(n,[...t.route,t.groupKey])),r}}}function pe(n,e={}){let t=e.colId??n;return{...e,colId:t,headerName:e.headerName??n,editable:!1,valueGetter:({data:r})=>r?.groupKey!==void 0&&r.aggValues&&Object.prototype.hasOwnProperty.call(r.aggValues,t)?r.aggValues[t]:L(r?.data,n)}}function fe(n,e){var r;let t=n.querySelectorAll(".mach-server-header button,.mach-server-cell button,.mach-server-cell input");for(let o of t)e?((r=o.dataset).serverWasDisabled??(r.serverWasDisabled=String(o.disabled)),o.disabled=!0):o.dataset.serverWasDisabled!==void 0&&(o.disabled=o.dataset.serverWasDisabled==="true",delete o.dataset.serverWasDisabled)}function Q(n,e){let t=n.view.getRoot();if(!t)return;fe(t,e);let r=t.querySelector(".mach-server-sync-notice");if(!e){r?.remove(),delete t.dataset.serverPending;return}if(t.dataset.serverPending="true",r)return;let o=document.createElement("div");o.className="mach-server-sync-notice",o.setAttribute("role","status"),o.textContent="\u65B0\u6570\u636E\u7B49\u5F85\u663E\u793A\uFF1A\u8BF7\u5148\u4FDD\u5B58\u3001\u53D6\u6D88\u7F16\u8F91\u6216\u56DE\u6EDA\u4FEE\u6539",t.append(o)}function ve(n,e){if(!P(n))throw new Error("[MachTable] Save or cancel grid edits before binding server-side data.");let t=!1,r=-1,o=!1,s=()=>{if(t||o||n.isDestroyed())return;let l=e.getSnapshot(),h=l.revision!==r&&!P(n);if(Q(n,h),!h){t=!0;try{l.revision!==r&&(r=l.revision,n.rows.setData([...l.rows])),n.selection.setRows(l.rows.filter(p=>e.getSelection(p)==="selected"),!0),n.view.refreshCells()}finally{t=!1}}},i=()=>{t||o||e.setQuery({sortModel:n.sorting.getModel(),filterModel:n.filtering.getModel(),advancedFilterModel:n.filtering.getAdvancedModel(),quickFilterText:n.filtering.getQuickText()}).catch(()=>{})},a=()=>{e.getSnapshot().revision!==r&&s()};n.updateOptions({rowKey:l=>l.key,rowSelection:"multiple",manualFiltering:!0,manualSorting:!0,pagination:!1});let d=[e.subscribe(s),n.on("sortChanged",i),n.on("filterChanged",i),n.on("dirtyStateChanged",a),n.on("cellEditingStopped",a),n.on("rowEditingStopped",a),n.on("selectionChanged",()=>{if(t||o||e.getSnapshot().revision!==r)return;let l=new Set(n.selection.getIds()),h=e.getSnapshot().rows.filter(p=>l.has(p.key)!==(e.getSelection(p)==="selected"));for(let p of h)e.select(p,l.has(p.key))})],u=()=>{if(!o){o=!0;for(let l of d)l();Q(n,!1),e.dispose()}};return d.push(n.on("gridDestroyed",u)),s(),e.setQuery({sortModel:n.sorting.getModel(),filterModel:n.filtering.getModel(),advancedFilterModel:n.filtering.getAdvancedModel(),quickFilterText:n.filtering.getQuickText()}).then(()=>e.getSnapshot().routes.length===0?e.load():void 0).catch(()=>{}),u}export{b as ServerSideVersionConflictError,ve as bindServerSideGrid,he as createServerSideGroupColumn,ae as createServerSideStore,pe as serverSideDataColumn};
1
+ function y(n,e){if(n instanceof Error)return n;let t=new Error(typeof n=="string"?n:e);return t.name="AbortError",t}var H=()=>y(void 0,"[MachTable] Operation cancelled.");function R(n,e,t=H){return e?new Promise((r,o)=>{let s=()=>{e.removeEventListener("abort",s),o(t())};if(n.then(r,o).finally(()=>e.removeEventListener("abort",s)),e.aborted){s();return}e.addEventListener("abort",s,{once:!0})}):n}function g(n){return y(n.reason,"Block request aborted")}function x(n){return Number.isFinite(n)?Math.max(1,Math.trunc(n)):1}var T=class{constructor(e,t,r=4){this.maxBlocks=e;this.n=t;this.maxConcurrentRequests=r;this.e=new Map;this.t=new Map;this.y=0;this.u=0;this.h=0;this.S=0;this.b=0;this.s=0;this.a=new Set;this.maxBlocks=x(e),this.maxConcurrentRequests=x(r)}configure(e,t=this.maxConcurrentRequests){this.maxBlocks=x(e),this.maxConcurrentRequests=x(t),this.p(),this.l()}T(e){this.a=e,this.p()}peek(e){let t=this.e.get(e);if(t)return t.touchedAt=++this.y,t}has(e){return this.e.has(e)}invalidate(e){let t=this.t.get(e);t&&(this.t.delete(e),t.controller.abort(),t.state==="queued"&&t.reject(g(t.controller.signal)));let r=this.e.get(e);r&&(this.e.delete(e),this.n?.(e,r))}load(e,t,r,o=0){if(r?.aborted)return Promise.reject(g(r));let s=this.peek(e);if(s)return this.h++,Promise.resolve(s);let i=this.t.get(e);if(i)return this.h++,i.priority=Math.max(i.priority,o),this.l(),this.w(e,i,r);this.S++;let a=new AbortController,d,u,l=new Promise((M,V)=>{d=M,u=V}),h={controller:a,promise:l,consumers:0,loader:t,priority:o,state:"queued",resolve:d,reject:u};this.t.set(e,h);let p=this.w(e,h,r);return this.l(),p}x(){this.u++,this.a.clear();for(let e of this.t.values())e.controller.abort(),e.state==="queued"&&e.reject(g(e.controller.signal));this.t.clear();for(let[e,t]of this.e)this.n?.(e,t);this.e.clear()}snapshot(){let e=0,t=0;for(let r of this.e.values())e+=r.rows.length;for(let r of this.t.values())r.state==="active"&&t++;return{cachedBlockCount:this.e.size,loadingBlockCount:this.t.size,activeRequestCount:t,queuedRequestCount:Math.max(0,this.t.size-t),cachedRowCount:e,hitCount:this.h,missCount:this.S,evictionCount:this.b}}l(){for(;this.s<this.maxConcurrentRequests;){let e,t;for(let[r,o]of this.t)o.state!=="queued"||o.controller.signal.aborted||(!t||o.priority>t.priority)&&(e=r,t=o);if(e==null||!t)return;this.k(e,t)}}k(e,t){t.state="active",this.s++;let r=this.u;this.C(t).then(o=>{r===this.u&&!t.controller.signal.aborted&&(this.e.set(e,{rows:o.rows,...o.lastRow==null?{}:{lastRow:o.lastRow},touchedAt:++this.y}),this.p()),t.resolve(o)},t.reject).finally(()=>{this.s=Math.max(0,this.s-1),this.t.get(e)===t&&this.t.delete(e),this.l()})}C(e){let{signal:t}=e.controller;return R(Promise.resolve().then(()=>{if(t.aborted)throw g(t);return e.loader(t)}),t,()=>g(t))}w(e,t,r){return t.consumers++,new Promise((o,s)=>{let i=!1,a=u=>{i||(i=!0,r?.removeEventListener("abort",d),t.consumers=Math.max(0,t.consumers-1),u())},d=()=>a(()=>{t.consumers===0&&this.t.get(e)===t&&(this.t.delete(e),t.controller.abort(r?.reason),t.state==="queued"&&t.reject(g(t.controller.signal))),s(g(r))});r?.addEventListener("abort",d,{once:!0}),t.promise.then(u=>a(()=>o(u)),u=>a(()=>s(u instanceof Error?u:new Error(String(u??"Block request failed")))))})}p(){let e=Math.max(this.maxBlocks,this.a.size+1);for(;this.e.size>e;){let t=-1,r=Number.POSITIVE_INFINITY;for(let[s,i]of this.e)this.a.has(s)||i.touchedAt<r&&(t=s,r=i.touchedAt);if(t<0)return;let o=this.e.get(t);this.e.delete(t),this.b++,o&&this.n?.(t,o)}}};var k={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 W=16,$=512,J=20,X=2e3,U=2e3,Y={text:new Set(k.text),number:new Set(k.number),date:new Set(k.date)};function Z(n){return n==null||typeof n=="string"||typeof n=="number"&&Number.isFinite(n)}function ee(n,e,t){if(n==null||typeof n!="object")return null;let r=n;return typeof r.match!="string"||!t.has(r.match)?null:{match:r.match,...te(r,e)}}function te(n,e){let t=e==="number"?q(n.value):typeof n.value=="string"?n.value:void 0,r=e==="number"?q(n.value2):typeof n.value2=="string"?n.value2:void 0;return{...t!==void 0?{value:t}:{},...r!==void 0?{value2:r}:{}}}function q(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function re(n,e){let t=[],r=Y[e];for(let o of n.slice(0,J)){let s=ee(o,e,r);s&&t.push(s)}return t}function F(n){if(n==null||typeof n!="object")return null;let e=n;return e.type==="set"?Array.isArray(e.values)?{type:"set",values:e.values.filter(Z).slice(0,X)}:null:e.type!=="text"&&e.type!=="number"&&e.type!=="date"||!Array.isArray(e.conditions)?null:{type:e.type,...e.operator==="or"||e.operator==="and"?{operator:e.operator}:{},conditions:re(e.conditions,e.type)}}function ne(n,e){if(typeof n.colId!="string"||!n.colId.trim())return null;let t=n.colId.trim();if(e.validColumnIds?.has(t)===!1)return null;let r=F(n.filter);return r?{kind:"condition",colId:t,filter:r}:null}function oe(n,e,t){if(!Array.isArray(n.children))return null;let r=[];for(let o of n.children){let s=I(o,e+1,t);s&&r.push(s)}return r.length===0?null:{kind:"group",operator:n.operator==="or"?"or":"and",children:r,...n.not===!0?{not:!0}:{}}}function ie(n,e,t){return e<=W&&t.nodes<$&&n!=null&&typeof n=="object"}function I(n,e,t){if(!ie(n,e,t)||t.ancestors.has(n))return null;t.ancestors.add(n),t.nodes++;let r=n,o=r.kind==="condition"?ne(r,t):r.kind==="group"?oe(r,e,t):null;return t.ancestors.delete(n),o}function G(n,e){if(n==null||typeof n!="object")return null;let t=n;if(t.version!==1||t.root==null)return null;let r=I(t.root,0,{ancestors:new WeakSet,nodes:0,validColumnIds:e});return r?{version:1,root:r}:null}function B(n,e){if(n==null||typeof n!="object"||Array.isArray(n))return{};let t={};for(let[r,o]of Object.entries(n).slice(0,U)){let s=r.trim();if(!s||e?.has(s)===!1)continue;let i=F(o);i&&(t[s]=i)}return t}function f(){return y(void 0,"[MachTable] Server-side operation cancelled or replaced.")}function v(n,e,t,r=1){return n!=null&&Number.isFinite(n)?Math.max(r,Math.min(t,Math.floor(n))):e}function A(n){if(!Array.isArray(n)||n.length>16||n.some(e=>typeof e!="string"||e.length>512))throw new TypeError("[MachTable] Invalid server-side group route.");return[...n]}function D(n,e){let t={...e,...n},r=t.rowGroupCols??[],o=t.valueCols??[];if(r.length>16||o.length>128)throw new RangeError("[MachTable] Server-side query exceeds group/aggregate column limits.");if([...r,...o].some(i=>typeof i.colId!="string"||!i.colId||i.colId.length>512))throw new TypeError("[MachTable] Invalid server-side query column.");return{rowGroupCols:r.map(i=>({colId:i.colId,...i.field?{field:i.field}:{}})),valueCols:o.map(i=>({colId:i.colId,aggFunc:i.aggFunc,...i.field?{field:i.field}:{}})),sortModel:(t.sortModel??[]).slice(0,2e3).filter(i=>i.direction==="asc"||i.direction==="desc").map(i=>({...i})),filterModel:B(t.filterModel),advancedFilterModel:G(t.advancedFilterModel),quickFilterText:t.quickFilterText?.slice(0,1e4)||null}}function se(n,e,t){if(!n||!Array.isArray(n.rows)||n.rows.length>t||!Number.isInteger(n.rowCount)||n.rowCount<0||n.rows.length>0&&n.rowCount<e+n.rows.length||typeof n.revision!="string"||!n.revision||n.revision.length>512)throw new TypeError("[MachTable] Invalid server-side route response.")}function N(n,e,t){return e>0&&n>=e?Math.floor((e-1)/t)*t:null}function z(n,e,t,r){se(n,e,t);let o=new Set,s=new Set;for(let i of n.rows){if(typeof i.id!="string"||!i.id||i.id.length>512||o.has(i.id))throw new TypeError("[MachTable] Duplicate/invalid server-side row ID.");if(o.add(i.id),r){if(typeof i.groupKey!="string"||i.groupKey.length>512||s.has(i.groupKey))throw new TypeError("[MachTable] Duplicate/invalid group key.");s.add(i.groupKey)}else if(i.groupKey!==void 0)throw new TypeError("[MachTable] Leaf routes cannot return group rows.")}return{rows:n.rows.map(i=>({...i})),rowCount:n.rowCount,revision:n.revision}}function K(n,e){return new Promise((t,r)=>{if(e.aborted){r(f());return}let o=()=>{clearTimeout(s),r(f())},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);e.addEventListener("abort",o,{once:!0})})}function O(n,e){return R(n,e,f)}function c(n){return JSON.stringify(n)}function j(n,e){return JSON.stringify([n,e])}function S(n,e){return n.length>=e.length&&e.every((t,r)=>n[r]===t)}var C=class{constructor(){this.selected=new Map;this.r=new Map;this.routes=new Map;this.excludedRoutes=new Map}f(e){let t=!1;for(let r=0;r<=e.length;r++){let o=c(e.slice(0,r));this.routes.has(o)&&(t=!0),this.excludedRoutes.has(o)&&(t=!1)}return t}d(e,t,r=!1){return[...e.values()].some(o=>S(o,t)&&(!r||o.length>t.length))}get(e){if(e.groupKey===void 0)return this.selected.has(e.key)||!this.r.has(e.key)&&this.f(e.route)?"selected":"none";let t=[...e.route,e.groupKey];if(this.r.has(e.key))return this.f(t)?"partial":"none";let r=this.f(t)||this.selected.has(e.key);return(r?this.d(this.r,t)||this.d(this.excludedRoutes,t,!0):this.d(this.selected,t)||this.d(this.routes,t,!0))?"partial":r?"selected":"none"}A(e,t){for(let[r,o]of e)S(o,t)&&e.delete(r)}select(e,t,r){let o=c([...e.route,e.groupKey??e.id]);if(!(this.selected.has(e.key)||this.r.has(e.key)||this.routes.has(o)||this.excludedRoutes.has(o))&&this.selected.size+this.r.size+this.routes.size+this.excludedRoutes.size>=1e4)throw new RangeError("[MachTable] Server-side selection exceeds 10000 explicit rules; clear selection first.");if(e.groupKey!==void 0&&r==="descendants"){let i=[...e.route,e.groupKey];for(let a of[this.selected,this.r,this.routes,this.excludedRoutes])this.A(a,i);this.selected.delete(e.key),this.r.delete(e.key),t?this.routes.set(c(i),i):this.excludedRoutes.set(c(i),i);return}this.selected.delete(e.key),this.r.delete(e.key),t?this.selected.set(e.key,e.route):this.r.set(e.key,e.route)}clear(){this.selected.clear(),this.r.clear(),this.routes.clear(),this.excludedRoutes.clear()}snapshot(){return{selectedKeys:[...this.selected.keys()],excludedKeys:[...this.r.keys()],selectedRoutes:[...this.routes.values()].map(e=>[...e]),excludedRoutes:[...this.excludedRoutes.values()].map(e=>[...e])}}};var b=class extends Error{constructor(t,r){super("[MachTable] Server-side route revision changed; refresh before retrying the transaction.");this.expectedRevision=t;this.actualRevision=r;this.name="ServerSideVersionConflictError"}};var E=class{constructor(e){this.options=e;this.routes=new Map;this.e=new Map;this.indices=new Map;this.expanded=new Set;this.selection=new C;this.c=new Set;this.i=new Set;this.E=0;this.generation=0;this.revision=0;this.disposed=!1;this.v=0;this.snapshot=null;this.query=D(e.query??{}),this.blockSize=v(e.blockSize,100,1e3),this.cache=new T(v(e.maxBlocks,12,256),t=>this.n(t),v(e.maxConcurrentRequests,4,16))}o(){if(this.disposed)throw f()}M(){if(this.v>=256)throw new RangeError("[MachTable] Server-side load queue limit reached (256).")}emit(e=!1){if(!this.disposed){this.snapshot=null,e&&this.revision++;for(let t of this.c)try{t()}catch(r){this.report(r,[])}}}report(e,t){if(e?.name!=="AbortError")try{this.options.onError?.(e,t)}catch{}}state(e){let t=A(e);if(t.length>this.query.rowGroupCols.length)throw new RangeError("[MachTable] Route exceeds configured grouping depth.");let r=c(t),o=this.routes.get(r);if(o)return this.routes.delete(r),this.routes.set(r,o),o;if(this.routes.size>=256){let i=[...this.routes].find(([a,d])=>a!=="[]"&&d.pending===0&&!this.expanded.has(a));if(!i)throw new RangeError("[MachTable] Server-side route metadata limit reached (256).");this.m(i[0]),this.routes.delete(i[0])}let s={route:t,startRow:0,endRow:0,rowCount:null,revision:null,loading:!1,error:null,generation:0,active:null,pending:0,requestVersion:0};return this.routes.set(r,s),s}n(e){this.snapshot=null;let t=this.indices.get(e);if(!t)return;this.indices.delete(e),this.e.get(t.key)===t&&this.e.delete(t.key);let r=this.routes.get(t.route);r?.active===e&&(r.active=null)}m(e,t){for(let r of[...this.indices.values()])r.route!==e||r.index===t||(this.cache.invalidate(r.index),this.n(r.index))}g(){let e=new Set;for(let[t,r]of this.routes)r.active!=null&&(t==="[]"||this.expanded.has(t))&&e.add(r.active);this.cache.T(e)}block(e,t){let r=JSON.stringify([e,t]),o=this.e.get(r);if(o)return o;let s={index:++this.E,key:r,route:e,start:t};return this.e.set(r,s),this.indices.set(s.index,s),s}async fetch(e,t,r){let o=v(this.options.retryCount,1,5,0),s=this.query;for(let i=0;;i++){if(r.aborted)throw f();try{let a=await this.options.getRows({...s,route:[...e.route],startRow:t,endRow:t+this.blockSize,revision:e.revision,signal:r});if(r.aborted)throw f();return z(a,t,this.blockSize,e.route.length<s.rowGroupCols.length)}catch(a){if(r.aborted||i>=o)throw a;await K(Math.min(3e4,v(this.options.retryDelay,200,1e4,0)*2**i),r)}}}current(e,t,r,o){return!this.disposed&&r===this.generation&&e.generation===o&&this.cache.has(t.index)}async load(e=[],t=0,r){this.o(),this.M();let o=this.state(e),s=Math.floor(v(t,0,Number.MAX_SAFE_INTEGER,0)/this.blockSize)*this.blockSize,i=this.block(c(o.route),s),a=this.generation,d=o.generation,u=++o.requestVersion;this.v++,o.pending++,o.loading=!0,o.error=null,this.g(),this.emit();try{let l=await this.cache.load(i.index,async M=>({rows:[await this.fetch(o,s,M)]}),r,100);if(!this.current(o,i,a,d))throw f();if(u!==o.requestVersion)return;let h=l.rows[0];o.revision!=null&&o.revision!==h.revision&&(o.generation++,this.m(i.route,i.index)),o.revision=h.revision;let p=N(s,h.rowCount,this.blockSize);if(p!=null){await this.load(o.route,p,r);return}o.active=i.index,o.startRow=s,o.endRow=s+h.rows.length,o.rowCount=h.rowCount,o.revision=h.revision,this.g(),this.emit(!0),await this.R(o.route)}catch(l){throw this.D(o,a,d,u)&&(o.error=l?.name==="AbortError"?null:l,this.report(l,o.route)),l}finally{o.pending=Math.max(0,o.pending-1),this.v--,u===o.requestVersion&&(o.loading=!1),this.cache.has(i.index)||this.n(i.index),a===this.generation&&this.emit()}}D(e,t,r,o){return!this.disposed&&t===this.generation&&e.generation===r&&o===e.requestVersion}async expand(e){this.o();let t=A(e),r=this.state(t),o=c(t);if(!this.expanded.has(o)&&this.expanded.size>=128)throw new RangeError("[MachTable] Expanded group limit reached (128).");this.expanded.add(o),this.emit(!0),r.active==null?await this.load(t,r.startRow):await this.R(t)}collapse(e){let t=A(e);for(let r of this.expanded)S(JSON.parse(r),t)&&this.expanded.delete(r);this.g(),this.emit(!0)}P(e){for(let[t,r]of this.routes)S(r.route,e)&&(r.generation++,r.active=null,r.revision=null,r.error=null,this.m(t))}async R(e){let t=this.routes.get(c(e)),r=t?.active==null?void 0:this.cache.peek(t.active)?.rows[0];if(!r)return;let o=r.rows.flatMap(s=>s.groupKey!==void 0&&this.expanded.has(c([...e,s.groupKey]))?[[...e,s.groupKey]]:[]);await Promise.all(o.map(s=>this.expand(s)))}async refresh(e=[]){this.o();let t=this.state(e);this.P(t.route),this.emit(!0),await this.load(t.route,t.startRow)}async setQuery(e){this.o();let t=D(e,this.query);if(JSON.stringify(t)!==JSON.stringify(this.query)){this.generation++,this.cache.x(),this.e.clear(),this.indices.clear(),this.routes.clear(),this.expanded.clear();for(let r of this.i)r.abort();this.selection.clear(),this.query=t,this.emit(!0),await this.load()}}async transact(e){this.o();let t=this.state(e.route);if(t.revision!==e.expectedRevision)throw new b(e.expectedRevision,t.revision);if(!this.options.transact)throw new Error("[MachTable] A server-side transaction transport is required.");if(this.i.size>=v(this.options.maxConcurrentRequests,4,16))throw new RangeError("[MachTable] Too many active server-side transactions.");let r=new AbortController;this.i.add(r);let o=this.generation,s=t.generation;try{let i=await O(Promise.resolve().then(()=>{if(r.signal.aborted)throw f();return this.options.transact({...e,route:[...t.route],query:this.query,signal:r.signal})}),r.signal);if(r.signal.aborted||o!==this.generation||s!==t.generation)throw f();if(typeof i?.revision!="string"||!i.revision||i.revision.length>512)throw new TypeError("[MachTable] Transaction transport must return the committed revision.");await this.refresh([])}finally{this.i.delete(r)}}select(e,t,r="descendants"){this.o(),this.selection.select(e,t,r),this.emit()}getSelection(e){return this.selection.get(e)}clearSelection(){this.selection.clear(),this.emit()}getSnapshot(){if(this.snapshot)return this.snapshot;let e=[],t=r=>{let o=this.routes.get(c(r)),s=o?.active==null?void 0:this.cache.peek(o.active)?.rows[0];if(s)for(let i of s.rows){let a=i.groupKey!==void 0&&this.expanded.has(c([...r,i.groupKey]));e.push({...i,key:j(r,i.id),route:[...r],depth:r.length,expanded:a}),a&&t([...r,i.groupKey])}};return t([]),this.snapshot={rows:e,routes:[...this.routes.values()].map(({route:r,startRow:o,endRow:s,rowCount:i,revision:a,loading:d,error:u})=>({route:[...r],startRow:o,endRow:s,rowCount:i,revision:a,loading:d,error:u})),selection:this.selection.snapshot(),query:D(this.query),revision:this.revision,cachedBlockCount:this.cache.snapshot().cachedBlockCount},this.snapshot}subscribe(e){return this.o(),this.c.add(e),()=>this.c.delete(e)}dispose(){if(!this.disposed){this.disposed=!0,this.generation++,this.cache.x();for(let e of this.i)e.abort();this.i.clear(),this.routes.clear(),this.e.clear(),this.indices.clear(),this.expanded.clear(),this.selection.clear(),this.c.clear(),this.snapshot=null}}};function ae(n){return new E(n)}var le=new Set(["__proto__","prototype","constructor"]),w=new Map;function de(n){if(typeof n!="string"||n.length===0)return null;let e=w.get(n);if(e!==void 0)return e;let t=n.split("."),r=t.every(o=>o.length>0&&!le.has(o))?t:null;return n.length<=1024&&(w.size>=256&&w.delete(w.keys().next().value),w.set(n,r)),r}function L(n,e){if(n==null)return;let t=de(e);if(!t)return;let r=n;for(let o of t){if(r==null)return;r=r[o]}return r}var ue=Symbol.for("mach-table.adapter.lifecycle.v1");function P(n){return!n.isDestroyed()&&(n[ue]?.canReplaceData()??!1)}function m(n,e,t=!1){let r=document.createElement("button");return r.type="button",r.className="mach-server-button",r.textContent=n,r.disabled=t,r.addEventListener("click",o=>{o.stopPropagation();try{Promise.resolve(e()).catch(()=>{})}catch{}}),r}function ce(n){return n?n.loading?"\u52A0\u8F7D\u4E2D\u2026":n.error?"\u52A0\u8F7D\u5931\u8D25":`${n.endRow>n.startRow?n.startRow+1:0}\u2013${n.endRow} / ${n.rowCount??"?"}`:"\u5C1A\u672A\u52A0\u8F7D"}function _(n,e){let t=n.getSnapshot().routes.find(s=>c(s.route)===c(e)),r=document.createElement("span");r.className="mach-server-paging";let o=document.createElement("span");return o.className="mach-server-range",o.textContent=ce(t),o.setAttribute("aria-live","polite"),r.append(o),r.append(m("\u4E0A\u4E00\u9875",()=>n.load(e,Math.max(0,(t?.startRow??0)-1)),!t||t.loading||t.startRow===0)),r.append(m("\u4E0B\u4E00\u9875",()=>n.load(e,t?.endRow??0),!t||t.loading||t.rowCount===null||t.endRow>=t.rowCount)),t?.error&&r.append(m("\u91CD\u8BD5",()=>n.refresh(e))),r}function he(n,e={}){return{colId:"__server_group",headerName:e.headerName??"\u670D\u52A1\u7AEF\u5206\u7EC4",width:e.width??420,minWidth:260,pinned:"left",sortable:!1,filter:!1,editable:!1,headerComponent:()=>{let t=document.createElement("div");t.className="mach-server-header";let r=()=>{t.replaceChildren(_(n,[]),m("\u5237\u65B0",()=>n.refresh()),m("\u6E05\u9664\u9009\u62E9",()=>n.clearSelection()))};return r(),{el:t,destroy:n.subscribe(r)}},cellRenderer:({data:t})=>{if(!t)return"";let r=document.createElement("div");r.className="mach-server-cell",r.style.paddingInlineStart=`${t.depth*16}px`;let o=document.createElement("input");o.type="checkbox";let s=n.getSelection(t);if(o.checked=s==="selected",o.indeterminate=s==="partial",o.setAttribute("aria-label",`\u9009\u62E9 ${t.groupKey??t.id}`),o.addEventListener("click",a=>{a.stopPropagation(),n.select(t,o.checked)}),r.append(o),t.groupKey!==void 0){let a=[...t.route,t.groupKey],d=m(t.expanded?"\u25BE":"\u25B8",()=>t.expanded?n.collapse(a):n.expand(a));d.setAttribute("aria-expanded",String(t.expanded)),d.setAttribute("aria-label",`${t.expanded?"\u6536\u8D77":"\u5C55\u5F00"} ${t.groupKey||"\u7A7A\u767D\u5206\u7EC4"}`),r.append(d)}let i=document.createElement("span");return i.className="mach-server-label",i.textContent=e.label?.(t)??t.groupKey??t.id,r.append(i),t.expanded&&t.groupKey!==void 0&&r.append(_(n,[...t.route,t.groupKey])),r}}}function pe(n,e={}){let t=e.colId??n;return{...e,colId:t,headerName:e.headerName??n,editable:!1,valueGetter:({data:r})=>r?.groupKey!==void 0&&r.aggValues&&Object.prototype.hasOwnProperty.call(r.aggValues,t)?r.aggValues[t]:L(r?.data,n)}}function fe(n,e){var r;let t=n.querySelectorAll(".mach-server-header button,.mach-server-cell button,.mach-server-cell input");for(let o of t)e?((r=o.dataset).serverWasDisabled??(r.serverWasDisabled=String(o.disabled)),o.disabled=!0):o.dataset.serverWasDisabled!==void 0&&(o.disabled=o.dataset.serverWasDisabled==="true",delete o.dataset.serverWasDisabled)}function Q(n,e){let t=n.view.getRoot();if(!t)return;fe(t,e);let r=t.querySelector(".mach-server-sync-notice");if(!e){r?.remove(),delete t.dataset.serverPending;return}if(t.dataset.serverPending="true",r)return;let o=document.createElement("div");o.className="mach-server-sync-notice",o.setAttribute("role","status"),o.textContent="\u65B0\u6570\u636E\u7B49\u5F85\u663E\u793A\uFF1A\u8BF7\u5148\u4FDD\u5B58\u3001\u53D6\u6D88\u7F16\u8F91\u6216\u56DE\u6EDA\u4FEE\u6539",t.append(o)}function ve(n,e){if(!P(n))throw new Error("[MachTable] Save or cancel grid edits before binding server-side data.");let t=!1,r=-1,o=!1,s=()=>{if(t||o||n.isDestroyed())return;let l=e.getSnapshot(),h=l.revision!==r&&!P(n);if(Q(n,h),!h){t=!0;try{l.revision!==r&&(r=l.revision,n.rows.setData([...l.rows])),n.selection.setRows(l.rows.filter(p=>e.getSelection(p)==="selected"),!0),n.view.refreshCells()}finally{t=!1}}},i=()=>{t||o||e.setQuery({sortModel:n.sorting.getModel(),filterModel:n.filtering.getModel(),advancedFilterModel:n.filtering.getAdvancedModel(),quickFilterText:n.filtering.getQuickText()}).catch(()=>{})},a=()=>{e.getSnapshot().revision!==r&&s()};n.updateOptions({rowKey:l=>l.key,rowSelection:"multiple",manualFiltering:!0,manualSorting:!0,pagination:!1});let d=[e.subscribe(s),n.on("sortChanged",i),n.on("filterChanged",i),n.on("dirtyStateChanged",a),n.on("cellEditingStopped",a),n.on("rowEditingStopped",a),n.on("selectionChanged",()=>{if(t||o||e.getSnapshot().revision!==r)return;let l=new Set(n.selection.getIds()),h=e.getSnapshot().rows.filter(p=>l.has(p.key)!==(e.getSelection(p)==="selected"));for(let p of h)e.select(p,l.has(p.key))})],u=()=>{if(!o){o=!0;for(let l of d)l();Q(n,!1),e.dispose()}};return d.push(n.on("gridDestroyed",u)),s(),e.setQuery({sortModel:n.sorting.getModel(),filterModel:n.filtering.getModel(),advancedFilterModel:n.filtering.getAdvancedModel(),quickFilterText:n.filtering.getQuickText()}).then(()=>e.getSnapshot().routes.length===0?e.load():void 0).catch(()=>{}),u}export{b as ServerSideVersionConflictError,ve as bindServerSideGrid,he as createServerSideGroupColumn,ae as createServerSideStore,pe as serverSideDataColumn};
@@ -1,4 +1,4 @@
1
- import { b as GridApi } from './api-CUQtfQR4.cjs';
1
+ import { b as GridApi } from './api-QsIvYp7X.cjs';
2
2
 
3
3
  interface WorkbenchHandle {
4
4
  refresh(): void;
@@ -1,4 +1,4 @@
1
- import { b as GridApi } from './api-CUQtfQR4.js';
1
+ import { b as GridApi } from './api-QsIvYp7X.js';
2
2
 
3
3
  interface WorkbenchHandle {
4
4
  refresh(): void;
@@ -1,6 +1,6 @@
1
- import { F as FilterType, A as AdvancedFilterModel, k as SaveChangesHandler, c as GridOptions, b as GridApi } from './api-CUQtfQR4.cjs';
2
- import { a as WorkbenchHandle, W as WorkbenchOptions } from './shared-BgBZ4-2C.cjs';
3
- import { M as MachTableOptionExplanation } from './configuration-BNK9jzn2.cjs';
1
+ import { F as FilterType, A as AdvancedFilterModel, k as SaveChangesHandler, c as GridOptions, b as GridApi } from './api-QsIvYp7X.cjs';
2
+ import { a as WorkbenchHandle, W as WorkbenchOptions } from './shared-BQc49rXR.cjs';
3
+ import { M as MachTableOptionExplanation } from './configuration-BwrRF3G0.cjs';
4
4
 
5
5
  interface FilterField {
6
6
  colId: string;