@agile-team/mach-table 0.32.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -2
- package/dist/adapter.cjs +1 -1
- package/dist/adapter.d.cts +28 -26
- package/dist/adapter.d.ts +28 -26
- package/dist/adapter.js +1 -1
- package/dist/analysis.cjs +2 -2
- package/dist/analysis.d.cts +2 -2
- package/dist/analysis.d.ts +2 -2
- package/dist/analysis.js +2 -2
- package/dist/{api-pOhyuSQk.d.cts → api-CZkd8tYy.d.cts} +39 -4
- package/dist/{api-pOhyuSQk.d.ts → api-CZkd8tYy.d.ts} +39 -4
- package/dist/{configuration-SYWVjGft.d.ts → configuration-D10N9PqG.d.ts} +5 -2
- package/dist/{configuration-gAE1eZuB.d.cts → configuration-XdxYEMiS.d.cts} +5 -2
- package/dist/import.cjs +1 -0
- package/dist/import.d.cts +47 -0
- package/dist/import.d.ts +47 -0
- package/dist/import.js +1 -0
- package/dist/index.cjs +6 -6
- package/dist/index.d.cts +8 -4
- package/dist/index.d.ts +8 -4
- package/dist/index.js +6 -6
- package/dist/multi-range.cjs +2 -2
- package/dist/multi-range.d.cts +1 -1
- package/dist/multi-range.d.ts +1 -1
- package/dist/multi-range.js +3 -3
- package/dist/ordering.cjs +1 -1
- package/dist/ordering.d.cts +1 -1
- package/dist/ordering.d.ts +1 -1
- package/dist/ordering.js +1 -1
- package/dist/preferences.cjs +1 -1
- package/dist/preferences.d.cts +1 -1
- package/dist/preferences.d.ts +1 -1
- package/dist/preferences.js +1 -1
- package/dist/server-side.cjs +1 -1
- package/dist/server-side.d.cts +1 -1
- package/dist/server-side.d.ts +1 -1
- package/dist/server-side.js +1 -1
- package/dist/{shared-Bi8hAuzn.d.cts → shared-BS_wes40.d.cts} +1 -1
- package/dist/{shared-Bn77TiBm.d.ts → shared-ujm7RteA.d.ts} +1 -1
- package/dist/workbench.cjs +1 -1
- package/dist/workbench.d.cts +3 -3
- package/dist/workbench.d.ts +3 -3
- package/dist/workbench.js +1 -1
- package/dist/worker.cjs +1 -1
- package/dist/worker.d.cts +4 -2
- package/dist/worker.d.ts +4 -2
- package/dist/worker.js +1 -1
- package/package.json +12 -2
package/dist/analysis.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var J=new Set(["__proto__","prototype","constructor"]);function E(n){return typeof n!="string"||n.length===0?!1:n.split(".").every(t=>t.length>0&&!J.has(t))}function x(n,e){if(n==null||!E(e))return;if(e.indexOf(".")<0)return n[e];let r=n,i=0;for(;i<e.length;){if(r==null)return;let o=e.indexOf(".",i);if(o<0){r=r[e.slice(i)];break}r=r[e.slice(i,o)],i=o+1}return r}var Z=new Set(["sum","count","avg","min","max"]);function V(n){return JSON.stringify(n.map(e=>[e===null?"null":typeof e,e]))}function H(n){if(n==null)return null;if(typeof n=="number")return Number.isFinite(n)?n:null;if(typeof n=="string"||typeof n=="boolean")return n;if(n instanceof Date&&!Number.isNaN(n.getTime()))return n.toISOString();throw new TypeError("Pivot dimensions must be primitive values or valid Dates")}function Q(n,e){if(n.length>1e4)throw new RangeError("Pivot supports at most 10000 input rows; aggregate remotely for larger datasets");let t=[...e.rowFields,...e.columnFields??[]];if(t.length>12||e.values.length>16||!e.values.length)throw new RangeError("Pivot supports 12 dimensions and 1\u201316 measures");for(let i of t)if(!E(i))throw new TypeError(`Invalid pivot field: ${i}`);let r=new Set;for(let i of e.values){ee(i);let o=JSON.stringify([i.field??null,i.aggregate]);if(r.has(o))throw new TypeError("Duplicate pivot measure");r.add(o)}}function ee(n){if(!Z.has(n.aggregate))throw new TypeError(`Unknown pivot aggregate: ${String(n.aggregate)}`);if(n.field!=null&&!E(n.field))throw new TypeError(`Invalid pivot field: ${n.field}`);if(!n.field&&n.aggregate!=="count")throw new TypeError("Numeric pivot measures require a field")}function j(n,e,t){let r=n.get(e);r||(r={count:0,numeric:0,sum:0,min:1/0,max:-1/0},n.set(e,r)),r.count++,!(typeof t!="number"||!Number.isFinite(t))&&(r.numeric++,r.sum+=t,r.min=Math.min(r.min,t),r.max=Math.max(r.max,t))}function te(n,e){return e==="count"?n?.count??0:n?.numeric?e==="avg"?Number.isFinite(n.sum)?n.sum/n.numeric:null:e==="sum"?Number.isFinite(n.sum)?n.sum:null:e==="min"?n.min:n.max:null}function ne(n,e){return JSON.stringify([n===null?"total":V(n),e.field??null,e.aggregate])}function N(n,e){Q(n,e);let t=new Map,r=new Map,i=new Map,o=e.columnFields??[];for(let s of n){let u=e.rowFields.map(p=>H(x(s,p))),m=V(u),d=t.get(m);if(d||(d={dimensions:u,cells:new Map},t.set(m,d)),t.size>2e3)throw new RangeError("Pivot supports at most 2000 result row groups");let h=o.map(p=>H(x(s,p)));for(let p of e.values){let g=p.field?x(s,p.field):void 0;G(d,r,i,h,p,g),o.length&&G(d,r,i,null,p,g)}if(r.size>128)throw new RangeError("Pivot supports at most 128 result columns")}if(!n.length&&!o.length)for(let s of e.values)z(r,[],s);let a=[...r.values()].sort((s,u)=>Number(s.total)-Number(u.total)||s.id.localeCompare(u.id)),l=[...t.entries()].sort(([s],[u])=>s.localeCompare(u)).map(([s,u])=>({id:s,dimensions:u.dimensions,values:U(a,u.cells)}));return{columns:a,rows:l,totals:U(a,i),inputCount:n.length}}function z(n,e,t){let r=ne(e,t);if(!n.has(r)){let i=t.label??`${t.field??"\u8BB0\u5F55"} \xB7 ${t.aggregate}`,o=e===null?"\u5408\u8BA1":e.map(a=>a==null?"\u7A7A\u503C":String(a)).join(" / ");n.set(r,{id:r,label:o?`${o} / ${i}`:i,dimensions:e??[],total:e===null,measure:{...t}})}return r}function G(n,e,t,r,i,o){let a=z(e,r,i);j(n.cells,a,o),j(t,a,o)}function U(n,e){let t=Object.create(null);for(let r of n)t[r.id]=te(e.get(r.id),r.measure.aggregate);return t}var f=class extends Error{constructor(t,r){super(r);this.code=t}},W={"+":1,"-":1,"*":2,"/":2,"%":2,"^":3},re=new Set(["SUM","MIN","MAX","AVG"]);function ie(n){if(n.length>4096)throw new f("LIMIT","Formula exceeds 4096 characters");let e=[],t=n.startsWith("=")?1:0;for(;t<n.length;){if(/\s/.test(n[t])){t++;continue}let r=oe(n.slice(t));if(e.push(r),t+=r.kind==="field"?r.value.length+2:r.value.length,e.length>256)throw new f("LIMIT","Formula exceeds 256 tokens")}return e}function oe(n){let e=/^(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?/i.exec(n);if(e)return{kind:"number",value:e[0]};let t=/^\[([^\]\r\n]+)\]/.exec(n);if(t)return{kind:"field",value:t[1]};let r=/^[A-Za-z_\u4e00-\u9fff][\w.\u4e00-\u9fff]*/.exec(n);if(r)return{kind:"name",value:r[0]};if("+-*/%^(),".includes(n[0]))return{kind:"symbol",value:n[0]};throw new f("SYNTAX",`Unexpected token: ${n.slice(0,12)}`)}function B(n){let e=ie(n),t=0,r=s=>{if(e[t++]?.value!==s)throw new f("SYNTAX",`Expected ${s}`)},i=(s,u)=>{if(u>32)throw new f("LIMIT","Formula exceeds 32 nesting levels");let m=a(u);for(;t<e.length;){let d=e[t].value,h=Object.prototype.hasOwnProperty.call(W,d)?W[d]:void 0;if(h==null||h<s)break;t++;let p=i(h+(d==="^"?0:1),u+1);m={kind:"binary",operator:d,left:m,right:p}}return m},o=(s,u)=>{let m=s.toUpperCase();if(!re.has(m))throw new f("SYNTAX",`Unsupported function: ${s}`);r("(");let d=[];if(e[t]?.value!==")")do d.push(i(0,u+1));while(e[t]?.value===","&&++t);if(r(")"),!d.length&&m!=="SUM")throw new f("SYNTAX",`${m} requires arguments`);return{kind:"call",name:m,args:d}},a=s=>{let u=e[t++];if(!u)throw new f("SYNTAX","Expected a value");if(u.kind==="number")return{kind:"number",value:Number(u.value)};if(u.kind==="field")return{kind:"field",name:u.value};if(u.kind==="name")return e[t]?.value==="("?o(u.value,s):{kind:"field",name:u.value};if(u.value==="+"||u.value==="-")return{kind:"unary",operator:u.value,operand:i(3,s+1)};if(u.value==="("){let m=i(0,s+1);return r(")"),m}throw new f("SYNTAX",`Unexpected token: ${u.value}`)},l=i(0,0);if(t!==e.length)throw new f("SYNTAX","Unexpected trailing tokens");return l}function k(n){if(!Number.isFinite(n))throw new f("NON_FINITE","Formula result is not a finite number");return n}function se(n,e,t){if((n==="/"||n==="%")&&t===0)throw new f("DIV_ZERO","Division by zero");return n==="+"?e+t:n==="-"?e-t:n==="*"?e*t:n==="/"?e/t:n==="%"?e%t:e**t}function T(n,e){if(n.kind==="number")return k(n.value);if(n.kind==="field")return e(n.name);if(n.kind==="unary")return k((n.operator==="-"?-1:1)*T(n.operand,e));if(n.kind==="binary")return k(se(n.operator,T(n.left,e),T(n.right,e)));let t=n.args.map(i=>T(i,e));if(n.name==="MIN")return Math.min(...t);if(n.name==="MAX")return Math.max(...t);let r=t.reduce((i,o)=>i+o,0);return k(n.name==="AVG"?r/t.length:r)}function S(n,e){let t=Object.entries(e);if(t.length>32||n.length>1e4||t.length*n.length>1e5)throw new f("LIMIT","Formulas support 32 columns, 10000 rows and 100000 result cells");let r=new Map;for(let[a,l]of t){if(!E(a)||/[.\[\]]/.test(a))throw new f("SYNTAX",`Invalid formula column: ${a}; use a single-level ID without dots or brackets`);try{r.set(a,B(l))}catch(s){r.set(a,X(s))}}let i=[];return{rows:n.map((a,l)=>{let s={...a},u=le(a,r);for(let[m,d]of u)d instanceof f&&i.push({rowIndex:l,colId:m,code:d.code,message:d.message}),Object.defineProperty(s,m,{value:d instanceof f?null:d,enumerable:!0,configurable:!0,writable:!0});return s}),errors:i}}function X(n){return n instanceof f?n:new f("SYNTAX",n instanceof Error?n.message:String(n))}function ae(n,e){if(!E(e))throw new f("UNKNOWN_FIELD",`Unknown field: ${e}`);let t=x(n,e);if(t===void 0)throw new f("UNKNOWN_FIELD",`Unknown field: ${e}`);if(typeof t!="number")throw new f("NON_NUMERIC",`Field is not numeric: ${e}`);return k(t)}function le(n,e){let t=new Map,r=new Set,i=o=>{if(!e.has(o))return ae(n,o);let a=t.get(o);if(a instanceof f)throw a;if(a!=null)return a;if(r.has(o))throw new f("CYCLE",`Cyclic formula: ${[...r,o].join(" \u2192 ")}`);r.add(o);try{let l=e.get(o);if(l instanceof f)throw l;let s=k(T(l,i));return t.set(o,s),s}catch(l){let s=X(l);throw t.set(o,s),s}finally{r.delete(o)}};for(let o of e.keys())try{i(o)}catch{}return t}var ue=["--mach-font-family","--mach-font-size","--mach-font-size-sm","--mach-header-font-weight","--mach-cell-padding","--mach-header-h","--mach-primary","--mach-primary-weak","--mach-success","--mach-warning","--mach-danger","--mach-info","--mach-border-color","--mach-border-width","--mach-header-bg","--mach-header-fg","--mach-body-bg","--mach-body-fg","--mach-row-hover-bg","--mach-radius-sm","--mach-radius","--mach-radius-lg","--mach-shadow-sm","--mach-shadow","--mach-transition","--mach-z-popup","--mach-z-menu"];function Y(n,e){if(n.classList.add("mach-portal"),!e)return;let t=window.getComputedStyle(e);for(let r of ue){let i=t.getPropertyValue(r).trim();i&&n.style.setProperty(r,i)}n.style.colorScheme=t.colorScheme}function c(n,e,t){let r=document.createElement(n);return e&&(r.className=e),t!=null&&(r.textContent=t),r}function y(n,e,t=""){let r=c("button",`mach-workbench__button ${t}`.trim(),n);return r.type="button",r.addEventListener("click",e),r}function P(n,e,t,r){let i=c("select","mach-workbench__input");i.setAttribute("aria-label",n);for(let o of e){let a=c("option",void 0,o.label);a.value=o.value,i.append(a)}return i.value=t,i.addEventListener("change",()=>r(i.value)),i}function _(n,e){let t=[...n.querySelectorAll("button,select,input")].filter(i=>!i.disabled);(t.find(i=>i.getAttribute("aria-label")===e||i.textContent===e)??t[0])?.focus()}function K(n,e,t,r){let i=document.activeElement,o=c("section","mach-workbench");o.setAttribute("aria-label",e),o.tabIndex=-1;let a=c("header","mach-workbench__header");a.append(c("h2","mach-workbench__title",e),y("\u5173\u95ED",t));let l=c("div","mach-workbench__body"),s=c("p","mach-workbench__status");s.setAttribute("role","status"),s.setAttribute("aria-live","polite");let u=c("footer","mach-workbench__footer");o.append(a,l,s,u);let m=v=>{v.key!=="Escape"||v.isComposing||(v.preventDefault(),v.stopPropagation(),t())};o.addEventListener("keydown",m);let d=!1,h=r.view.getRoot(),p=()=>{d||(o.dataset.theme=h?.classList.contains("mach-theme-dark")?"dark":"light",Y(o,h))},g=null;try{p(),h&&(g=new MutationObserver(p),g.observe(h,{attributes:!0,attributeFilter:["class","style"]})),n.append(o)}catch(v){throw g?.disconnect(),o.remove(),v}return{root:o,body:l,status:s,footer:u,syncTheme:p,destroy(){if(d)return;d=!0,g?.disconnect();let v=o.contains(document.activeElement);o.removeEventListener("keydown",m),o.remove(),v&&i?.isConnected&&i.focus()}}}function w(n,e,t){let r=document.createElementNS("http://www.w3.org/2000/svg",n);for(let[i,o]of Object.entries(e))r.setAttribute(i,String(o));return t!=null&&(r.textContent=t),r}function q(n,e,t){let r=c("figure","mach-analysis__chart"),i=n.columns.find(b=>b.id===e);if(!i)return r.append(c("p",void 0,"\u5C1A\u65E0\u53EF\u7ED8\u5236\u7684\u6307\u6807")),r;let o=n.rows.slice(0,40),a=`${i.label} \xB7 ${t==="bar"?"\u67F1\u72B6\u56FE":"\u6298\u7EBF\u56FE"}\uFF0C${o.length} \u7EC4`,l=w("svg",{viewBox:"0 0 680 260",role:"img","aria-label":a});l.append(w("title",{},a));let s=o.map(b=>b.values[e]).filter(b=>b!=null&&Number.isFinite(b)),u=Math.min(0,...s),m=Math.max(0,...s),d=Math.max(Math.abs(m),Math.abs(u))||1,h=m/d-u/d||1,p=b=>210-(b/d-u/d)/h*180,g=p(0);l.append(w("line",{x1:50,x2:660,y1:g,y2:g,stroke:"currentColor",opacity:".4"})),l.append(w("text",{x:2,y:25,"font-size":11},String(m)),w("text",{x:2,y:212,"font-size":11},String(u)));let v=600/Math.max(o.length,1),M=[],D=()=>{M.length&&l.append(w("polyline",{points:M.join(" "),fill:"none",stroke:"currentColor","stroke-width":2})),M=[]};return o.forEach((b,O)=>{let C=b.values[e];if(C==null){D();return}let F=55+v*(O+.5),A=p(C),L=b.dimensions.map($=>$==null?"\u7A7A\u503C":String($)).join(" / ")||"\u5168\u90E8",I=t==="bar"?w("rect",{x:F-v*.35,y:Math.min(g,A),width:Math.max(1,v*.7),height:Math.max(1,Math.abs(A-g)),fill:"currentColor",rx:2}):w("circle",{cx:F,cy:A,r:3,fill:"currentColor"});I.append(w("title",{},`${L}: ${C}`)),l.append(I),t==="line"&&M.push(`${F},${A}`),(o.length<=10||O%Math.ceil(o.length/10)===0)&&l.append(w("text",{x:F,y:238,"text-anchor":"middle","font-size":10},L.slice(0,12)))}),D(),r.append(l,c("figcaption","mach-workbench__hint",`${a}\u3002${n.rows.length>40?"\u56FE\u8868\u4EC5\u5C55\u793A\u524D 40 \u7EC4\uFF0C":""}\u5B8C\u6574\u6570\u503C\u89C1\u4E0B\u65B9\u6570\u636E\u8868\u3002`)),r}var ce={sum:"\u6C42\u548C",count:"\u8BB0\u5F55\u6570",avg:"\u5E73\u5747\u503C",min:"\u6700\u5C0F\u503C",max:"\u6700\u5927\u503C"};function de(n,e){return new R(n,e)}var R=class{constructor(e,t){this.options=t;this.fields=[];this.result=null;this.results=c("div","mach-analysis__results");this.page=0;this.i="bar";this.t="";this.destroyed=!1;if(t.api.isDestroyed())throw new Error("Cannot mount analysis on a destroyed grid");this.config={rowFields:[...t.pivot?.rowFields??[]],columnFields:[...t.pivot?.columnFields??[]],values:t.pivot?.values.map(r=>({...r}))??[{aggregate:"count"}]},this.formulas=Object.entries(t.formulas??{}).map(([r,i])=>({field:r,expression:i})),this.e=K(e,"\u6570\u636E\u5206\u6790",()=>{this.destroy(),t.onClose?.()},t.api),this.e.footer.append(y("\u8FD0\u884C\u5206\u6790",()=>this.s(),"mach-workbench__button--primary")),this.o=[t.api.on("gridDestroyed",()=>this.destroy()),t.api.on("modelUpdated",()=>{!this.destroyed&&this.result&&(this.e.status.textContent="\u8868\u683C\u6570\u636E\u5DF2\u66F4\u65B0\uFF1B\u91CD\u65B0\u8FD0\u884C\u5206\u6790\u4EE5\u5237\u65B0\u7ED3\u679C\u3002")})],this.refresh(),this.s(),this.e.root.focus()}refresh(){this.a()&&(this.fields=this.l(),this.e.syncTheme(),this.e.body.replaceChildren(),this.c(),this.e.body.append(this.results),this.n())}destroy(){this.destroyed||(this.destroyed=!0,this.o.splice(0).forEach(e=>e()),this.e.destroy())}a(){return!this.destroyed&&!this.options.api.isDestroyed()}l(){let e=[],t=r=>{for(let i of r){if("children"in i){t(i.children);continue}if(!i.field)continue;let o=x(this.options.api.rows.getAt(0)?.data,i.field);e.push({field:i.field,label:i.headerName??i.field,numeric:typeof o=="number"||i.cellEditor==="number"||i.filter==="number"})}};t(this.options.api.columns.getDefinitions()??[]);for(let r of this.formulas)r.field&&!e.some(i=>i.field===r.field)&&e.push({field:r.field,label:`${r.field}\uFF08\u516C\u5F0F\uFF09`,numeric:!0});return e}c(){let e=c("div","mach-analysis__settings");e.append(this.dimensions("\u884C\u7EF4\u5EA6",this.config.rowFields,i=>{this.config.rowFields=i}),this.dimensions("\u5217\u7EF4\u5EA6",this.config.columnFields??[],i=>{this.config.columnFields=i}));let t=c("fieldset","mach-workbench__group");t.append(c("legend",void 0,"\u805A\u5408\u6307\u6807")),this.config.values.forEach((i,o)=>t.append(this.measure(i,o)));let r=y("\u6DFB\u52A0\u6307\u6807",()=>{this.config.values=[...this.config.values,{aggregate:"count"}],this.refresh()});r.disabled=this.config.values.length>=16,t.append(r),e.append(t,this.d()),this.e.body.append(e)}dimensions(e,t,r){let i=c("label","mach-analysis__dimension",e),o=c("select","mach-workbench__input");o.multiple=!0,o.setAttribute("aria-label",e);let a=[...this.fields];for(let l of t)a.some(s=>s.field===l)||a.push({field:l,label:`${l}\uFF08\u5DF2\u79FB\u9664\uFF09`,numeric:!1});for(let l of a){let s=c("option",void 0,l.label);s.value=l.field,s.selected=t.includes(l.field),o.append(s)}return o.addEventListener("change",()=>r([...o.selectedOptions].map(l=>l.value))),i.append(o,c("small","mach-workbench__hint","\u652F\u6301\u591A\u9009\uFF1B\u4E0D\u9009\u62E9\u8868\u793A\u5168\u90E8\u8BB0\u5F55\u3002")),i}measure(e,t){let r=c("div","mach-workbench__values"),i=[{value:"",label:"\u5168\u90E8\u8BB0\u5F55"},...this.fields.map(o=>({value:o.field,label:o.label}))];return e.field&&!i.some(o=>o.value===e.field)&&i.push({value:e.field,label:`${e.field}\uFF08\u5DF2\u79FB\u9664\uFF09`}),r.append(P("\u6307\u6807\u5B57\u6BB5",i,e.field??"",o=>{e.field=o||void 0}),P("\u805A\u5408\u65B9\u5F0F",Object.entries(ce).map(([o,a])=>({value:o,label:a})),e.aggregate,o=>{e.aggregate=o}),y("\u5220\u9664\u6307\u6807",()=>{this.config.values=this.config.values.filter((o,a)=>a!==t),this.refresh()})),r}d(){let e=c("fieldset","mach-workbench__group");e.append(c("legend",void 0,"\u516C\u5F0F\u5217"),c("p","mach-workbench__hint","\u4F7F\u7528 [\u5B57\u6BB5]\u3001+ - * / % ^\u3001\u62EC\u53F7\u548C SUM / MIN / MAX / AVG\u3002\u7ED3\u679C\u5217\u4F7F\u7528\u5355\u5C42 ID\uFF0C\u4E0D\u542B . \u6216 []\uFF1B\u5D4C\u5957\u8F93\u5165\u53EF\u5F15\u7528 [tax.total]\u3002\u53EA\u8BA1\u7B97\u5F53\u524D\u8BB0\u5F55\uFF0C\u4E0D\u652F\u6301\u811A\u672C\u6216\u8DE8\u884C\u5F15\u7528\u3002")),this.formulas.forEach((r,i)=>{let o=c("div","mach-workbench__values"),a=c("input","mach-workbench__input");a.setAttribute("aria-label","\u516C\u5F0F\u7ED3\u679C\u5217"),a.placeholder="\u5982 total",a.value=r.field,a.addEventListener("input",()=>{r.field=a.value.trim()});let l=c("input","mach-workbench__input");l.setAttribute("aria-label","\u516C\u5F0F\u8868\u8FBE\u5F0F"),l.placeholder="\u5982 [quantity] * [price]",l.value=r.expression,l.addEventListener("input",()=>{r.expression=l.value}),o.append(a,l,y("\u5220\u9664\u516C\u5F0F",()=>{this.formulas.splice(i,1),this.refresh()})),e.append(o)});let t=y("\u6DFB\u52A0\u516C\u5F0F",()=>{this.formulas.push({field:"",expression:""}),this.refresh()});return t.disabled=this.formulas.length>=32,e.append(t),e}s(){if(!this.a())return;let e=[],t=0;this.options.api.rows.forEach(r=>{r.data==null||r.isGroup||r.isDetail||(t++,e.length<1e4&&e.push(r.data))});try{let r=this.f(),i=S(e,r);if(i.errors.length){let l=i.errors.slice(0,20).map(s=>`\u7B2C ${s.rowIndex+1} \u884C / ${s.colId}\uFF1A${s.code} ${s.message}`);throw new Error(`\u516C\u5F0F\u9519\u8BEF ${i.errors.length} \u9879${i.errors.length>20?"\uFF08\u663E\u793A\u524D 20 \u9879\uFF09":""}\uFF1A
|
|
1
|
+
var ne=new Set(["__proto__","prototype","constructor"]),M=new Map;function j(t){if(typeof t!="string"||t.length===0)return null;let e=M.get(t);if(e!==void 0)return e;let n=t.split("."),r=n.every(o=>o.length>0&&!ne.has(o))?n:null;return t.length<=1024&&(M.size>=256&&M.delete(M.keys().next().value),M.set(t,r)),r}function E(t){return j(t)!==null}function x(t,e){if(t==null)return;let n=j(e);if(!n)return;let r=t;for(let o of n){if(r==null)return;r=r[o]}return r}function G(){return{count:0,numeric:0,sum:0,min:1/0,max:-1/0}}function U(t,e){t.count++,!(typeof e!="number"||!Number.isFinite(e))&&(t.numeric++,t.sum+=e,t.min=Math.min(t.min,e),t.max=Math.max(t.max,e))}function V(t,e){return e==="count"?t?.count??0:t?.numeric?e==="min"?t.min:e==="max"?t.max:Number.isFinite(t.sum)?e==="avg"?t.sum/t.numeric:t.sum:null:null}var re=new Set(["sum","count","avg","min","max"]);function X(t){return JSON.stringify(t.map(e=>[e===null?"null":typeof e,e]))}function B(t){if(t==null)return null;if(typeof t=="number")return Number.isFinite(t)?t:null;if(typeof t=="string"||typeof t=="boolean")return t;if(t instanceof Date&&!Number.isNaN(t.getTime()))return t.toISOString();throw new TypeError("Pivot dimensions must be primitive values or valid Dates")}function oe(t,e){if(t.length>1e4)throw new RangeError("Pivot supports at most 10000 input rows; aggregate remotely for larger datasets");let n=[...e.rowFields,...e.columnFields??[]];if(n.length>12||e.values.length>16||!e.values.length)throw new RangeError("Pivot supports 12 dimensions and 1\u201316 measures");for(let o of n)if(!E(o))throw new TypeError(`Invalid pivot field: ${o}`);let r=new Set;for(let o of e.values){ie(o);let i=JSON.stringify([o.field??null,o.aggregate]);if(r.has(i))throw new TypeError("Duplicate pivot measure");r.add(i)}}function ie(t){if(!re.has(t.aggregate))throw new TypeError(`Unknown pivot aggregate: ${String(t.aggregate)}`);if(t.field!=null&&!E(t.field))throw new TypeError(`Invalid pivot field: ${t.field}`);if(!t.field&&t.aggregate!=="count")throw new TypeError("Numeric pivot measures require a field")}function W(t,e,n){let r=t.get(e);r||(r=G(),t.set(e,r)),U(r,n)}function se(t,e){return JSON.stringify([t===null?"total":X(t),e.field??null,e.aggregate])}function S(t,e){oe(t,e);let n=new Map,r=new Map,o=new Map,i=e.columnFields??[];for(let s of t){let u=e.rowFields.map(p=>B(x(s,p))),f=X(u),d=n.get(f);if(d||(d={dimensions:u,cells:new Map},n.set(f,d)),n.size>2e3)throw new RangeError("Pivot supports at most 2000 result row groups");let h=i.map(p=>B(x(s,p)));for(let p of e.values){let g=p.field?x(s,p.field):void 0;z(d,r,o,h,p,g),i.length&&z(d,r,o,null,p,g)}if(r.size>128)throw new RangeError("Pivot supports at most 128 result columns")}if(!t.length&&!i.length)for(let s of e.values)Y(r,[],s);let a=[...r.values()].sort((s,u)=>Number(s.total)-Number(u.total)||s.id.localeCompare(u.id)),l=[...n.entries()].sort(([s],[u])=>s.localeCompare(u)).map(([s,u])=>({id:s,dimensions:u.dimensions,values:K(a,u.cells)}));return{columns:a,rows:l,totals:K(a,o),inputCount:t.length}}function Y(t,e,n){let r=se(e,n);if(!t.has(r)){let o=n.label??`${n.field??"\u8BB0\u5F55"} \xB7 ${n.aggregate}`,i=e===null?"\u5408\u8BA1":e.map(a=>a==null?"\u7A7A\u503C":String(a)).join(" / ");t.set(r,{id:r,label:i?`${i} / ${o}`:o,dimensions:e??[],total:e===null,measure:{...n}})}return r}function z(t,e,n,r,o,i){let a=Y(e,r,o);W(t.cells,a,i),W(n,a,i)}function K(t,e){let n=Object.create(null);for(let r of t)n[r.id]=V(e.get(r.id),r.measure.aggregate);return n}var m=class extends Error{constructor(n,r){super(r);this.code=n}},q={"+":1,"-":1,"*":2,"/":2,"%":2,"^":3},ae=new Set(["SUM","MIN","MAX","AVG"]);function le(t){if(t.length>4096)throw new m("LIMIT","Formula exceeds 4096 characters");let e=[],n=t.startsWith("=")?1:0;for(;n<t.length;){if(/\s/.test(t[n])){n++;continue}let r=ue(t.slice(n));if(e.push(r),n+=r.kind==="field"?r.value.length+2:r.value.length,e.length>256)throw new m("LIMIT","Formula exceeds 256 tokens")}return e}function ue(t){let e=/^(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?/i.exec(t);if(e)return{kind:"number",value:e[0]};let n=/^\[([^\]\r\n]+)\]/.exec(t);if(n)return{kind:"field",value:n[1]};let r=/^[A-Za-z_\u4e00-\u9fff][\w.\u4e00-\u9fff]*/.exec(t);if(r)return{kind:"name",value:r[0]};if("+-*/%^(),".includes(t[0]))return{kind:"symbol",value:t[0]};throw new m("SYNTAX",`Unexpected token: ${t.slice(0,12)}`)}function J(t){let e=le(t),n=0,r=s=>{if(e[n++]?.value!==s)throw new m("SYNTAX",`Expected ${s}`)},o=(s,u)=>{if(u>32)throw new m("LIMIT","Formula exceeds 32 nesting levels");let f=a(u);for(;n<e.length;){let d=e[n].value,h=Object.prototype.hasOwnProperty.call(q,d)?q[d]:void 0;if(h==null||h<s)break;n++;let p=o(h+(d==="^"?0:1),u+1);f={kind:"binary",operator:d,left:f,right:p}}return f},i=(s,u)=>{let f=s.toUpperCase();if(!ae.has(f))throw new m("SYNTAX",`Unsupported function: ${s}`);r("(");let d=[];if(e[n]?.value!==")")do d.push(o(0,u+1));while(e[n]?.value===","&&++n);if(r(")"),!d.length&&f!=="SUM")throw new m("SYNTAX",`${f} requires arguments`);return{kind:"call",name:f,args:d}},a=s=>{let u=e[n++];if(!u)throw new m("SYNTAX","Expected a value");if(u.kind==="number")return{kind:"number",value:Number(u.value)};if(u.kind==="field")return{kind:"field",name:u.value};if(u.kind==="name")return e[n]?.value==="("?i(u.value,s):{kind:"field",name:u.value};if(u.value==="+"||u.value==="-")return{kind:"unary",operator:u.value,operand:o(3,s+1)};if(u.value==="("){let f=o(0,s+1);return r(")"),f}throw new m("SYNTAX",`Unexpected token: ${u.value}`)},l=o(0,0);if(n!==e.length)throw new m("SYNTAX","Unexpected trailing tokens");return l}function k(t){if(!Number.isFinite(t))throw new m("NON_FINITE","Formula result is not a finite number");return t}function ce(t,e,n){if((t==="/"||t==="%")&&n===0)throw new m("DIV_ZERO","Division by zero");return t==="+"?e+n:t==="-"?e-n:t==="*"?e*n:t==="/"?e/n:t==="%"?e%n:e**n}function T(t,e){if(t.kind==="number")return k(t.value);if(t.kind==="field")return e(t.name);if(t.kind==="unary")return k((t.operator==="-"?-1:1)*T(t.operand,e));if(t.kind==="binary")return k(ce(t.operator,T(t.left,e),T(t.right,e)));let n=t.args.map(o=>T(o,e));if(t.name==="MIN")return Math.min(...n);if(t.name==="MAX")return Math.max(...n);let r=n.reduce((o,i)=>o+i,0);return k(t.name==="AVG"?r/n.length:r)}function R(t,e){let n=Object.entries(e);if(n.length>32||t.length>1e4||n.length*t.length>1e5)throw new m("LIMIT","Formulas support 32 columns, 10000 rows and 100000 result cells");let r=new Map;for(let[a,l]of n){if(!E(a)||/[.\[\]]/.test(a))throw new m("SYNTAX",`Invalid formula column: ${a}; use a single-level ID without dots or brackets`);try{r.set(a,J(l))}catch(s){r.set(a,Z(s))}}let o=[];return{rows:t.map((a,l)=>{let s={...a},u=me(a,r);for(let[f,d]of u)d instanceof m&&o.push({rowIndex:l,colId:f,code:d.code,message:d.message}),Object.defineProperty(s,f,{value:d instanceof m?null:d,enumerable:!0,configurable:!0,writable:!0});return s}),errors:o}}function Z(t){return t instanceof m?t:new m("SYNTAX",t instanceof Error?t.message:String(t))}function de(t,e){if(!E(e))throw new m("UNKNOWN_FIELD",`Unknown field: ${e}`);let n=x(t,e);if(n===void 0)throw new m("UNKNOWN_FIELD",`Unknown field: ${e}`);if(typeof n!="number")throw new m("NON_NUMERIC",`Field is not numeric: ${e}`);return k(n)}function me(t,e){let n=new Map,r=new Set,o=i=>{if(!e.has(i))return de(t,i);let a=n.get(i);if(a instanceof m)throw a;if(a!=null)return a;if(r.has(i))throw new m("CYCLE",`Cyclic formula: ${[...r,i].join(" \u2192 ")}`);r.add(i);try{let l=e.get(i);if(l instanceof m)throw l;let s=k(T(l,o));return n.set(i,s),s}catch(l){let s=Z(l);throw n.set(i,s),s}finally{r.delete(i)}};for(let i of e.keys())try{o(i)}catch{}return n}function Q(t,e){if(t.classList.add("mach-portal"),!e)return;let n=window.getComputedStyle(e);for(let r=0;r<n.length;r++){let o=n.item(r);if(!o.startsWith("--mach-"))continue;let i=n.getPropertyValue(o).trim();i&&t.style.setProperty(o,i)}t.style.colorScheme=n.colorScheme}function c(t,e,n){let r=document.createElement(t);return e&&(r.className=e),n!=null&&(r.textContent=n),r}function w(t,e,n=""){let r=c("button",`mach-workbench__button ${n}`.trim(),t);return r.type="button",r.addEventListener("click",e),r}function A(t,e,n,r){let o=c("select","mach-workbench__input");o.setAttribute("aria-label",t);for(let i of e){let a=c("option",void 0,i.label);a.value=i.value,o.append(a)}return o.value=n,o.addEventListener("change",()=>r(o.value)),o}function _(t,e){let n=[...t.querySelectorAll("button,select,input")].filter(o=>!o.disabled);(n.find(o=>o.getAttribute("aria-label")===e||o.textContent===e)??n[0])?.focus()}function ee(t,e,n,r){let o=document.activeElement,i=c("section","mach-workbench");i.setAttribute("aria-label",e),i.tabIndex=-1;let a=c("header","mach-workbench__header");a.append(c("h2","mach-workbench__title",e),w("\u5173\u95ED",n));let l=c("div","mach-workbench__body"),s=c("p","mach-workbench__status");s.setAttribute("role","status"),s.setAttribute("aria-live","polite");let u=c("footer","mach-workbench__footer");i.append(a,l,s,u);let f=v=>{v.key!=="Escape"||v.isComposing||(v.preventDefault(),v.stopPropagation(),n())};i.addEventListener("keydown",f);let d=!1,h=r.view.getRoot(),p=()=>{d||(i.dataset.theme=h?.classList.contains("mach-theme-dark")?"dark":"light",Q(i,h))},g=null;try{p(),h&&(g=new MutationObserver(p),g.observe(h,{attributes:!0,attributeFilter:["class","style"]})),t.append(i)}catch(v){throw g?.disconnect(),i.remove(),v}return{root:i,body:l,status:s,footer:u,syncTheme:p,destroy(){if(d)return;d=!0,g?.disconnect();let v=i.contains(document.activeElement);i.removeEventListener("keydown",f),i.remove(),v&&o?.isConnected&&o.focus()}}}function y(t,e,n){let r=document.createElementNS("http://www.w3.org/2000/svg",t);for(let[o,i]of Object.entries(e))r.setAttribute(o,String(i));return n!=null&&(r.textContent=n),r}function te(t,e,n){let r=c("figure","mach-analysis__chart"),o=t.columns.find(b=>b.id===e);if(!o)return r.append(c("p",void 0,"\u5C1A\u65E0\u53EF\u7ED8\u5236\u7684\u6307\u6807")),r;let i=t.rows.slice(0,40),a=`${o.label} \xB7 ${n==="bar"?"\u67F1\u72B6\u56FE":"\u6298\u7EBF\u56FE"}\uFF0C${i.length} \u7EC4`,l=y("svg",{viewBox:"0 0 680 260",role:"img","aria-label":a});l.append(y("title",{},a));let s=i.map(b=>b.values[e]).filter(b=>b!=null&&Number.isFinite(b)),u=Math.min(0,...s),f=Math.max(0,...s),d=Math.max(Math.abs(f),Math.abs(u))||1,h=f/d-u/d||1,p=b=>210-(b/d-u/d)/h*180,g=p(0);l.append(y("line",{x1:50,x2:660,y1:g,y2:g,stroke:"currentColor",opacity:".4"})),l.append(y("text",{x:2,y:25,"font-size":11},String(f)),y("text",{x:2,y:212,"font-size":11},String(u)));let v=600/Math.max(i.length,1),P=[],L=()=>{P.length&&l.append(y("polyline",{points:P.join(" "),fill:"none",stroke:"currentColor","stroke-width":2})),P=[]};return i.forEach((b,O)=>{let C=b.values[e];if(C==null){L();return}let N=55+v*(O+.5),F=p(C),I=b.dimensions.map(H=>H==null?"\u7A7A\u503C":String(H)).join(" / ")||"\u5168\u90E8",$=n==="bar"?y("rect",{x:N-v*.35,y:Math.min(g,F),width:Math.max(1,v*.7),height:Math.max(1,Math.abs(F-g)),fill:"currentColor",rx:2}):y("circle",{cx:N,cy:F,r:3,fill:"currentColor"});$.append(y("title",{},`${I}: ${C}`)),l.append($),n==="line"&&P.push(`${N},${F}`),(i.length<=10||O%Math.ceil(i.length/10)===0)&&l.append(y("text",{x:N,y:238,"text-anchor":"middle","font-size":10},I.slice(0,12)))}),L(),r.append(l,c("figcaption","mach-workbench__hint",`${a}\u3002${t.rows.length>40?"\u56FE\u8868\u4EC5\u5C55\u793A\u524D 40 \u7EC4\uFF0C":""}\u5B8C\u6574\u6570\u503C\u89C1\u4E0B\u65B9\u6570\u636E\u8868\u3002`)),r}var fe={sum:"\u6C42\u548C",count:"\u8BB0\u5F55\u6570",avg:"\u5E73\u5747\u503C",min:"\u6700\u5C0F\u503C",max:"\u6700\u5927\u503C"};function pe(t,e){return new D(t,e)}var D=class{constructor(e,n){this.options=n;this.fields=[];this.result=null;this.results=c("div","mach-analysis__results");this.page=0;this.o="bar";this.t="";this.destroyed=!1;if(n.api.isDestroyed())throw new Error("Cannot mount analysis on a destroyed grid");this.config={rowFields:[...n.pivot?.rowFields??[]],columnFields:[...n.pivot?.columnFields??[]],values:n.pivot?.values.map(r=>({...r}))??[{aggregate:"count"}]},this.formulas=Object.entries(n.formulas??{}).map(([r,o])=>({field:r,expression:o})),this.e=ee(e,"\u6570\u636E\u5206\u6790",()=>{this.destroy(),n.onClose?.()},n.api),this.e.footer.append(w("\u8FD0\u884C\u5206\u6790",()=>this.s(),"mach-workbench__button--primary")),this.i=[n.api.on("gridDestroyed",()=>this.destroy()),n.api.on("modelUpdated",()=>{!this.destroyed&&this.result&&(this.e.status.textContent="\u8868\u683C\u6570\u636E\u5DF2\u66F4\u65B0\uFF1B\u91CD\u65B0\u8FD0\u884C\u5206\u6790\u4EE5\u5237\u65B0\u7ED3\u679C\u3002")})],this.refresh(),this.s(),this.e.root.focus()}refresh(){this.a()&&(this.fields=this.l(),this.e.syncTheme(),this.e.body.replaceChildren(),this.c(),this.e.body.append(this.results),this.n())}destroy(){this.destroyed||(this.destroyed=!0,this.i.splice(0).forEach(e=>e()),this.e.destroy())}a(){return!this.destroyed&&!this.options.api.isDestroyed()}l(){let e=[],n=r=>{for(let o of r){if("children"in o){n(o.children);continue}if(!o.field)continue;let i=x(this.options.api.rows.getAt(0)?.data,o.field);e.push({field:o.field,label:o.headerName??o.field,numeric:typeof i=="number"||o.cellEditor==="number"||o.filter==="number"})}};n(this.options.api.columns.getDefinitions()??[]);for(let r of this.formulas)r.field&&!e.some(o=>o.field===r.field)&&e.push({field:r.field,label:`${r.field}\uFF08\u516C\u5F0F\uFF09`,numeric:!0});return e}c(){let e=c("div","mach-analysis__settings");e.append(this.dimensions("\u884C\u7EF4\u5EA6",this.config.rowFields,o=>{this.config.rowFields=o}),this.dimensions("\u5217\u7EF4\u5EA6",this.config.columnFields??[],o=>{this.config.columnFields=o}));let n=c("fieldset","mach-workbench__group");n.append(c("legend",void 0,"\u805A\u5408\u6307\u6807")),this.config.values.forEach((o,i)=>n.append(this.measure(o,i)));let r=w("\u6DFB\u52A0\u6307\u6807",()=>{this.config.values=[...this.config.values,{aggregate:"count"}],this.refresh()});r.disabled=this.config.values.length>=16,n.append(r),e.append(n,this.d()),this.e.body.append(e)}dimensions(e,n,r){let o=c("label","mach-analysis__dimension",e),i=c("select","mach-workbench__input");i.multiple=!0,i.setAttribute("aria-label",e);let a=[...this.fields];for(let l of n)a.some(s=>s.field===l)||a.push({field:l,label:`${l}\uFF08\u5DF2\u79FB\u9664\uFF09`,numeric:!1});for(let l of a){let s=c("option",void 0,l.label);s.value=l.field,s.selected=n.includes(l.field),i.append(s)}return i.addEventListener("change",()=>r([...i.selectedOptions].map(l=>l.value))),o.append(i,c("small","mach-workbench__hint","\u652F\u6301\u591A\u9009\uFF1B\u4E0D\u9009\u62E9\u8868\u793A\u5168\u90E8\u8BB0\u5F55\u3002")),o}measure(e,n){let r=c("div","mach-workbench__values"),o=[{value:"",label:"\u5168\u90E8\u8BB0\u5F55"},...this.fields.map(i=>({value:i.field,label:i.label}))];return e.field&&!o.some(i=>i.value===e.field)&&o.push({value:e.field,label:`${e.field}\uFF08\u5DF2\u79FB\u9664\uFF09`}),r.append(A("\u6307\u6807\u5B57\u6BB5",o,e.field??"",i=>{e.field=i||void 0}),A("\u805A\u5408\u65B9\u5F0F",Object.entries(fe).map(([i,a])=>({value:i,label:a})),e.aggregate,i=>{e.aggregate=i}),w("\u5220\u9664\u6307\u6807",()=>{this.config.values=this.config.values.filter((i,a)=>a!==n),this.refresh()})),r}d(){let e=c("fieldset","mach-workbench__group");e.append(c("legend",void 0,"\u516C\u5F0F\u5217"),c("p","mach-workbench__hint","\u4F7F\u7528 [\u5B57\u6BB5]\u3001+ - * / % ^\u3001\u62EC\u53F7\u548C SUM / MIN / MAX / AVG\u3002\u7ED3\u679C\u5217\u4F7F\u7528\u5355\u5C42 ID\uFF0C\u4E0D\u542B . \u6216 []\uFF1B\u5D4C\u5957\u8F93\u5165\u53EF\u5F15\u7528 [tax.total]\u3002\u53EA\u8BA1\u7B97\u5F53\u524D\u8BB0\u5F55\uFF0C\u4E0D\u652F\u6301\u811A\u672C\u6216\u8DE8\u884C\u5F15\u7528\u3002")),this.formulas.forEach((r,o)=>{let i=c("div","mach-workbench__values"),a=c("input","mach-workbench__input");a.setAttribute("aria-label","\u516C\u5F0F\u7ED3\u679C\u5217"),a.placeholder="\u5982 total",a.value=r.field,a.addEventListener("input",()=>{r.field=a.value.trim()});let l=c("input","mach-workbench__input");l.setAttribute("aria-label","\u516C\u5F0F\u8868\u8FBE\u5F0F"),l.placeholder="\u5982 [quantity] * [price]",l.value=r.expression,l.addEventListener("input",()=>{r.expression=l.value}),i.append(a,l,w("\u5220\u9664\u516C\u5F0F",()=>{this.formulas.splice(o,1),this.refresh()})),e.append(i)});let n=w("\u6DFB\u52A0\u516C\u5F0F",()=>{this.formulas.push({field:"",expression:""}),this.refresh()});return n.disabled=this.formulas.length>=32,e.append(n),e}s(){if(!this.a())return;let e=[],n=0;this.options.api.rows.forEach(r=>{r.data==null||r.isGroup||r.isDetail||(n++,e.length<1e4&&e.push(r.data))});try{let r=this.m(),o=R(e,r);if(o.errors.length){let l=o.errors.slice(0,20).map(s=>`\u7B2C ${s.rowIndex+1} \u884C / ${s.colId}\uFF1A${s.code} ${s.message}`);throw new Error(`\u516C\u5F0F\u9519\u8BEF ${o.errors.length} \u9879${o.errors.length>20?"\uFF08\u663E\u793A\u524D 20 \u9879\uFF09":""}\uFF1A
|
|
2
2
|
${l.join(`
|
|
3
|
-
`)}`)}this.
|
|
3
|
+
`)}`)}this.f(r),this.result=S(o.rows,this.config),this.page=0,this.refresh();let i=this.options.api.rows.isRemote()?"\u8FDC\u7A0B\u6A21\u5F0F\u4EC5\u5305\u542B\u5DF2\u52A0\u8F7D\u884C\uFF0C\u4E0D\u4EE3\u8868\u670D\u52A1\u7AEF\u5168\u91CF\u3002":"",a=n>e.length?`\u5DF2\u52A0\u8F7D ${n} \u884C\uFF0C\u672C\u6B21\u4EC5\u5206\u6790\u524D ${e.length} \u884C\u3002`:`\u5206\u6790\u5DF2\u52A0\u8F7D\u7684 ${e.length} \u884C\u3002`;this.e.status.textContent=`${a}${i} \u751F\u6210 ${this.result.rows.length} \u4E2A\u884C\u7EC4\u3001${this.result.columns.length} \u4E2A\u7ED3\u679C\u5217\u3002`,this.e.status.classList.remove("mach-workbench__status--error"),this.e.status.setAttribute("role","status")}catch(r){this.result=null,this.results.replaceChildren(),this.e.status.textContent=r instanceof Error?r.message:String(r),this.e.status.classList.add("mach-workbench__status--error"),this.e.status.setAttribute("role","alert")}}m(){let e=Object.create(null);for(let n of this.formulas){if(!n.field||Object.prototype.hasOwnProperty.call(e,n.field))throw new Error("\u516C\u5F0F\u7ED3\u679C\u5217\u4E0D\u80FD\u4E3A\u7A7A\u6216\u91CD\u590D");e[n.field]=n.expression}return e}f(e){let n=new Set([...this.l().map(o=>o.field),...Object.keys(e)]),r=[...this.config.rowFields,...this.config.columnFields??[],...this.config.values.flatMap(o=>o.field?[o.field]:[])];for(let o of r)if(!n.has(o))throw new Error(`\u5B57\u6BB5\u5DF2\u79FB\u9664\u6216\u4E0D\u53EF\u5206\u6790\uFF1A${o}`)}n(){if(this.results.replaceChildren(),!this.result)return;let e=this.result;e.columns.some(l=>l.id===this.t)||(this.t=e.columns[0]?.id??"");let n=c("div","mach-workbench__tools");n.append(A("\u56FE\u8868\u7C7B\u578B",[{value:"bar",label:"\u67F1\u72B6\u56FE"},{value:"line",label:"\u6298\u7EBF\u56FE"}],this.o,l=>{this.o=l,this.n(),_(this.results,"\u56FE\u8868\u7C7B\u578B")}),A("\u56FE\u8868\u6307\u6807",e.columns.map(l=>({value:l.id,label:l.label})),this.t,l=>{this.t=l,this.n(),_(this.results,"\u56FE\u8868\u6307\u6807")})),this.results.append(n,te(e,this.t,this.o),this.table(e));let r=Math.max(1,Math.ceil(e.rows.length/50)),o=c("nav","mach-workbench__tools");o.setAttribute("aria-label","\u5206\u6790\u7ED3\u679C\u5206\u9875");let i=w("\u4E0A\u4E00\u9875",()=>{this.page--,this.n(),_(this.results.querySelector("nav"),"\u4E0A\u4E00\u9875")}),a=w("\u4E0B\u4E00\u9875",()=>{this.page++,this.n(),_(this.results.querySelector("nav"),"\u4E0B\u4E00\u9875")});i.disabled=this.page<=0,a.disabled=this.page>=r-1,o.append(i,c("span",void 0,`\u7B2C ${this.page+1} / ${r} \u9875 \xB7 \u6BCF\u9875 50 \u7EC4`),a),this.results.append(o)}table(e){let n=c("div","mach-analysis__table-wrap"),r=c("table","mach-analysis__table");r.append(c("caption",void 0,"\u900F\u89C6\u7ED3\u679C\u6570\u636E\u8868\uFF08\u5B8C\u6574\u7ED3\u679C\u53EF\u5206\u9875\u67E5\u770B\uFF09"));let o=c("thead"),i=c("tr");for(let s of["\u884C\u7EF4\u5EA6",...e.columns.map(u=>u.label)]){let u=c("th",void 0,s);u.scope="col",i.append(u)}o.append(i);let a=c("tbody");for(let s of e.rows.slice(this.page*50,(this.page+1)*50))a.append(this.u(s.dimensions.map(u=>u==null?"\u7A7A\u503C":String(u)).join(" / ")||"\u5168\u90E8",e,s.values));let l=c("tfoot");return l.append(this.u("\u5408\u8BA1",e,e.totals)),r.append(o,a,l),n.append(r),n}u(e,n,r){let o=c("tr"),i=c("th",void 0,e);i.scope="row",o.append(i);for(let a of n.columns){let l=r[a.id],s=c("td",void 0,l==null?"\u2014":l.toLocaleString("zh-CN",{maximumFractionDigits:6}));s.title=l==null?"\u65E0\u6570\u503C":String(l),o.append(s)}return o}};export{S as createPivot,R as evaluateFormulas,pe as mountAnalysis};
|
|
@@ -147,6 +147,16 @@ type SortDirection = "asc" | "desc";
|
|
|
147
147
|
type PinnedDirection = "left" | "right";
|
|
148
148
|
type FilterType = "text" | "number" | "date" | "set";
|
|
149
149
|
type CellAlign = "left" | "center" | "right";
|
|
150
|
+
type ValueInputSource = "editor" | "clipboard" | "import";
|
|
151
|
+
type ValueOutputTarget = "clipboard" | "csv" | "xlsx";
|
|
152
|
+
interface ValueParserParams<TData = any, TValue = any> extends ValueGetterParams<TData, TValue> {
|
|
153
|
+
value: unknown;
|
|
154
|
+
oldValue: TValue | undefined;
|
|
155
|
+
source: ValueInputSource;
|
|
156
|
+
}
|
|
157
|
+
interface ValueSerializerParams<TData = any, TValue = any> extends ValueFormatterParams<TData, TValue> {
|
|
158
|
+
target: ValueOutputTarget;
|
|
159
|
+
}
|
|
150
160
|
type TextFilterMatch = "contains" | "notContains" | "equals" | "notEquals" | "startsWith" | "endsWith" | "blank" | "notBlank";
|
|
151
161
|
type NumberFilterMatch = "equals" | "notEquals" | "lessThan" | "lessThanOrEqual" | "greaterThan" | "greaterThanOrEqual" | "inRange" | "blank" | "notBlank";
|
|
152
162
|
type DateFilterMatch = "equals" | "notEquals" | "lessThan" | "greaterThan" | "inRange" | "blank" | "notBlank";
|
|
@@ -255,6 +265,10 @@ interface ColDef<TData = any, TValue = any> {
|
|
|
255
265
|
rowDrag?: boolean;
|
|
256
266
|
valueGetter?: (params: ValueGetterParams<TData, TValue>) => TValue;
|
|
257
267
|
valueSetter?: (params: ValueSetterParams<TData, TValue>) => boolean;
|
|
268
|
+
/** Synchronous user-input normalization. Not called by trusted transactions or undo replay. */
|
|
269
|
+
valueParser?: (params: ValueParserParams<TData, TValue>) => TValue;
|
|
270
|
+
/** Clipboard/file output; display formatting and sort/filter continue to use stored values. */
|
|
271
|
+
valueSerializer?: (params: ValueSerializerParams<TData, TValue>) => unknown;
|
|
258
272
|
valueFormatter?: (params: ValueFormatterParams<TData, TValue>) => any;
|
|
259
273
|
cellRenderer?: CellRendererFn | string;
|
|
260
274
|
cellRendererParams?: Record<string, any>;
|
|
@@ -740,7 +754,7 @@ interface GridDataProcessorResult {
|
|
|
740
754
|
/** Filtered and sorted stable row IDs, in final display order. */
|
|
741
755
|
rowIds: readonly string[];
|
|
742
756
|
}
|
|
743
|
-
/** Optional async/Worker boundary
|
|
757
|
+
/** Optional async/Worker boundary. Each instance is owned and destroyed by exactly one grid. */
|
|
744
758
|
interface GridDataProcessor<TData = any> {
|
|
745
759
|
process(request: GridDataProcessorRequest<TData>): Promise<GridDataProcessorResult>;
|
|
746
760
|
destroy?(): void;
|
|
@@ -941,8 +955,8 @@ interface GridOptions<TData = any> extends EventHandlers<TData> {
|
|
|
941
955
|
blockPrefetch?: number;
|
|
942
956
|
/** Optional initial total enables immediate scrollbar range before the first response. */
|
|
943
957
|
datasourceRowCount?: number;
|
|
944
|
-
/**
|
|
945
|
-
dataProcessor?: GridDataProcessor<TData
|
|
958
|
+
/** Per-grid processor or factory. Reusable application defaults must use a factory returning a fresh instance. */
|
|
959
|
+
dataProcessor?: GridDataProcessor<TData> | (() => GridDataProcessor<TData>);
|
|
946
960
|
/** Minimum local row count before dataProcessor is used. Defaults to 5,000. */
|
|
947
961
|
dataProcessorMinRows?: number;
|
|
948
962
|
/** Number of automatic retries after an infinite datasource request fails. */
|
|
@@ -1104,6 +1118,24 @@ interface ImportCsvOptions {
|
|
|
1104
1118
|
columnIndex: number;
|
|
1105
1119
|
}) => any;
|
|
1106
1120
|
}
|
|
1121
|
+
interface ImportMatrixOptions {
|
|
1122
|
+
mode?: "replace" | "append" | "paste";
|
|
1123
|
+
/** -1 means no header. Explicit columns default to -1; otherwise the first row is a header. */
|
|
1124
|
+
headerRowIndex?: number;
|
|
1125
|
+
/** Explicit destination column IDs/fields, in matrix order. */
|
|
1126
|
+
columns?: readonly string[];
|
|
1127
|
+
coerceNumbers?: boolean;
|
|
1128
|
+
/** Per-operation override; takes priority over the column parser. */
|
|
1129
|
+
parseValue?: (params: {
|
|
1130
|
+
value: unknown;
|
|
1131
|
+
field: string;
|
|
1132
|
+
rowIndex: number;
|
|
1133
|
+
columnIndex: number;
|
|
1134
|
+
}) => any;
|
|
1135
|
+
}
|
|
1136
|
+
interface MatrixExportParams extends CsvExportParams {
|
|
1137
|
+
target?: "csv" | "xlsx";
|
|
1138
|
+
}
|
|
1107
1139
|
interface PrintOptions {
|
|
1108
1140
|
title?: string;
|
|
1109
1141
|
includeHeader?: boolean;
|
|
@@ -1336,6 +1368,9 @@ interface GridViewApi<TData = any> {
|
|
|
1336
1368
|
interface GridIoApi {
|
|
1337
1369
|
exportCsv(params?: CsvExportParams): string;
|
|
1338
1370
|
importCsv(text: string, options?: ImportCsvOptions): boolean;
|
|
1371
|
+
exportMatrix(params?: MatrixExportParams): unknown[][];
|
|
1372
|
+
/** Synchronous result: replace/append load parser-normalized records; paste starts interactive validation, which may finish later. */
|
|
1373
|
+
importMatrix(rows: readonly (readonly unknown[])[], options?: ImportMatrixOptions): boolean;
|
|
1339
1374
|
print(options?: PrintOptions): boolean;
|
|
1340
1375
|
copyRange(): Promise<boolean>;
|
|
1341
1376
|
}
|
|
@@ -1388,4 +1423,4 @@ interface GridApi<TData = any> {
|
|
|
1388
1423
|
isDestroyed(): boolean;
|
|
1389
1424
|
}
|
|
1390
1425
|
|
|
1391
|
-
export {
|
|
1426
|
+
export { type ContextMenuParams as $, type AdvancedFilterModel as A, type ApplyGridStateOptions as B, type ColDef as C, type CellAlign as D, type CellClassParams as E, type FilterType as F, type GridFeature as G, type CellClassRule as H, type ImportMatrixOptions as I, type CellClickEvent as J, type CellContextMenuEvent as K, type CellDoubleClickEvent as L, type CellEditingStartedEvent as M, type CellEditingStoppedEvent as N, type CellEditorFactory as O, type CellEditorParams as P, type CellRendererOutput as Q, type CellStyleRule as R, type SortModel as S, type CellValueChangedEvent as T, type ColDefOrGroup as U, type ColumnLayoutMode as V, type ColumnMovedEvent as W, type ColumnResizedEvent as X, type ColumnVisibilityChangedEvent as Y, type ColumnWorkbenchItem as Z, type ContextMenuItem as _, type GridCellRange as a, type PaginationConfig as a$, type CsvExportParams as a0, DEFAULT_LOCALE as a1, type DatasourceMode as a2, type DateFilterCondition as a3, type DateFilterMatch as a4, type DetailRowRendererParams as a5, type DetailToggledEvent as a6, type DirtyStateChangedEvent as a7, type DomLayoutMode as a8, EVENT_TYPES as a9, type GridIoApi as aA, type GridPaginationApi as aB, type GridPerformanceSnapshot as aC, type GridPersistenceOptions as aD, type GridReadyEvent as aE, type GridRowsApi as aF, type GridSelectionApi as aG, type GridSortingApi as aH, type GridStateApi as aI, type GridStateSection as aJ, type GridUpdateSchedulerSnapshot as aK, type GridViewApi as aL, type HeaderComponentParams as aM, type ICellEditor as aN, type ICellRendererResult as aO, type ImportCsvOptions as aP, type InfiniteGetRowsParams as aQ, LOCALE_EN as aR, type MachTableLocale as aS, type MachTableLocaleKey as aT, type MatrixExportParams as aU, type ModelUpdatedEvent as aV, type NumberFilterCondition as aW, type NumberFilterMatch as aX, type OverlayContent as aY, type OverlayTemplate as aZ, type PaginationChangedEvent as a_, type EditableIndicator as aa, type EditableParams as ab, type EventHandlers as ac, type FilterChangedEvent as ad, type GetRowHeightParams as ae, type GridAsyncOptions as af, type GridBatchSaveResult as ag, type GridCellChange as ah, type GridColumnsApi as ai, type GridDataProcessorColumn as aj, type GridDataProcessorRequest as ak, type GridDataProcessorResult as al, type GridDataProcessorRow as am, type GridDatasource as an, type GridDiagnosticError as ao, type GridDiagnostics as ap, type GridDiagnosticsApi as aq, type GridEditType as ar, type GridEditingApi as as, type GridErrorCode as at, type GridErrorEvent as au, type GridEventBase as av, type GridEventMap as aw, type GridFeatureContext as ax, type GridFilteringApi as ay, type GridHierarchyApi as az, type GridApi as b, type PinnedDirection as b0, type PrintOptions as b1, type RangeSelectionChangedEvent as b2, type RefreshCellsParams as b3, type RemoteBlockCacheSnapshot as b4, type ResolvedGridOptions as b5, type RowClickEvent as b6, type RowDragEndEvent as b7, type RowDragIntent as b8, type RowDragPolicy as b9, type TooltipParams as bA, type TreeChildrenLoadFailedEvent as bB, type TreeChildrenLoadedEvent as bC, type TreeDataLoadParams as bD, type ValueFormatterParams as bE, type ValueGetterParams as bF, type ValueInputSource as bG, type ValueOutputTarget as bH, type ValueParserParams as bI, type ValueSerializerParams as bJ, type ValueSetterParams as bK, type WatermarkConfig as bL, formatText as bM, formatTwo as bN, isColDefGroup as bO, matchLocaleKey as bP, type RowEditChange as ba, type RowEditValidationParams as bb, type RowEditValidationResult as bc, type RowEditingStartedEvent as bd, type RowEditingStoppedEvent as be, type RowNode as bf, type RowSelectionMode as bg, type RowStyleParams as bh, type RowStyleRule as bi, type RowTone as bj, type RowTransaction as bk, type SaveChangeIssue as bl, type SaveChangesResult as bm, type SelectEditorOption as bn, type SelectEditorParams as bo, type SelectionChangedEvent as bp, type SetFilterCondition as bq, type SetFilterParams as br, type SortChangedEvent as bs, type SortDirection as bt, type SortModelItem as bu, type StatusBarConfig as bv, type StatusBarPanel as bw, type TextFilterCondition as bx, type TextFilterMatch as by, type ThemeMode as bz, type GridOptions as c, type GridDataProcessor as d, type GridComponents as e, type GridState as f, type GridStateStore as g, type FilterModel as h, type FieldPath as i, type GridEventType as j, type SaveChangesHandler as k, type ColumnFilter as l, type AdvancedFilterCondition as m, type AdvancedFilterNode as n, type AdvancedFilterGroup as o, type ColDefGroup as p, type GridStateInput as q, type GridSize as r, type CellRendererParams as s, type GridChange as t, type CellRendererFn as u, type FieldPathValue as v, type SaveChangeConflict as w, type ColumnState as x, type ActionPolicy as y, type ActionPolicyContext as z };
|
|
@@ -147,6 +147,16 @@ type SortDirection = "asc" | "desc";
|
|
|
147
147
|
type PinnedDirection = "left" | "right";
|
|
148
148
|
type FilterType = "text" | "number" | "date" | "set";
|
|
149
149
|
type CellAlign = "left" | "center" | "right";
|
|
150
|
+
type ValueInputSource = "editor" | "clipboard" | "import";
|
|
151
|
+
type ValueOutputTarget = "clipboard" | "csv" | "xlsx";
|
|
152
|
+
interface ValueParserParams<TData = any, TValue = any> extends ValueGetterParams<TData, TValue> {
|
|
153
|
+
value: unknown;
|
|
154
|
+
oldValue: TValue | undefined;
|
|
155
|
+
source: ValueInputSource;
|
|
156
|
+
}
|
|
157
|
+
interface ValueSerializerParams<TData = any, TValue = any> extends ValueFormatterParams<TData, TValue> {
|
|
158
|
+
target: ValueOutputTarget;
|
|
159
|
+
}
|
|
150
160
|
type TextFilterMatch = "contains" | "notContains" | "equals" | "notEquals" | "startsWith" | "endsWith" | "blank" | "notBlank";
|
|
151
161
|
type NumberFilterMatch = "equals" | "notEquals" | "lessThan" | "lessThanOrEqual" | "greaterThan" | "greaterThanOrEqual" | "inRange" | "blank" | "notBlank";
|
|
152
162
|
type DateFilterMatch = "equals" | "notEquals" | "lessThan" | "greaterThan" | "inRange" | "blank" | "notBlank";
|
|
@@ -255,6 +265,10 @@ interface ColDef<TData = any, TValue = any> {
|
|
|
255
265
|
rowDrag?: boolean;
|
|
256
266
|
valueGetter?: (params: ValueGetterParams<TData, TValue>) => TValue;
|
|
257
267
|
valueSetter?: (params: ValueSetterParams<TData, TValue>) => boolean;
|
|
268
|
+
/** Synchronous user-input normalization. Not called by trusted transactions or undo replay. */
|
|
269
|
+
valueParser?: (params: ValueParserParams<TData, TValue>) => TValue;
|
|
270
|
+
/** Clipboard/file output; display formatting and sort/filter continue to use stored values. */
|
|
271
|
+
valueSerializer?: (params: ValueSerializerParams<TData, TValue>) => unknown;
|
|
258
272
|
valueFormatter?: (params: ValueFormatterParams<TData, TValue>) => any;
|
|
259
273
|
cellRenderer?: CellRendererFn | string;
|
|
260
274
|
cellRendererParams?: Record<string, any>;
|
|
@@ -740,7 +754,7 @@ interface GridDataProcessorResult {
|
|
|
740
754
|
/** Filtered and sorted stable row IDs, in final display order. */
|
|
741
755
|
rowIds: readonly string[];
|
|
742
756
|
}
|
|
743
|
-
/** Optional async/Worker boundary
|
|
757
|
+
/** Optional async/Worker boundary. Each instance is owned and destroyed by exactly one grid. */
|
|
744
758
|
interface GridDataProcessor<TData = any> {
|
|
745
759
|
process(request: GridDataProcessorRequest<TData>): Promise<GridDataProcessorResult>;
|
|
746
760
|
destroy?(): void;
|
|
@@ -941,8 +955,8 @@ interface GridOptions<TData = any> extends EventHandlers<TData> {
|
|
|
941
955
|
blockPrefetch?: number;
|
|
942
956
|
/** Optional initial total enables immediate scrollbar range before the first response. */
|
|
943
957
|
datasourceRowCount?: number;
|
|
944
|
-
/**
|
|
945
|
-
dataProcessor?: GridDataProcessor<TData
|
|
958
|
+
/** Per-grid processor or factory. Reusable application defaults must use a factory returning a fresh instance. */
|
|
959
|
+
dataProcessor?: GridDataProcessor<TData> | (() => GridDataProcessor<TData>);
|
|
946
960
|
/** Minimum local row count before dataProcessor is used. Defaults to 5,000. */
|
|
947
961
|
dataProcessorMinRows?: number;
|
|
948
962
|
/** Number of automatic retries after an infinite datasource request fails. */
|
|
@@ -1104,6 +1118,24 @@ interface ImportCsvOptions {
|
|
|
1104
1118
|
columnIndex: number;
|
|
1105
1119
|
}) => any;
|
|
1106
1120
|
}
|
|
1121
|
+
interface ImportMatrixOptions {
|
|
1122
|
+
mode?: "replace" | "append" | "paste";
|
|
1123
|
+
/** -1 means no header. Explicit columns default to -1; otherwise the first row is a header. */
|
|
1124
|
+
headerRowIndex?: number;
|
|
1125
|
+
/** Explicit destination column IDs/fields, in matrix order. */
|
|
1126
|
+
columns?: readonly string[];
|
|
1127
|
+
coerceNumbers?: boolean;
|
|
1128
|
+
/** Per-operation override; takes priority over the column parser. */
|
|
1129
|
+
parseValue?: (params: {
|
|
1130
|
+
value: unknown;
|
|
1131
|
+
field: string;
|
|
1132
|
+
rowIndex: number;
|
|
1133
|
+
columnIndex: number;
|
|
1134
|
+
}) => any;
|
|
1135
|
+
}
|
|
1136
|
+
interface MatrixExportParams extends CsvExportParams {
|
|
1137
|
+
target?: "csv" | "xlsx";
|
|
1138
|
+
}
|
|
1107
1139
|
interface PrintOptions {
|
|
1108
1140
|
title?: string;
|
|
1109
1141
|
includeHeader?: boolean;
|
|
@@ -1336,6 +1368,9 @@ interface GridViewApi<TData = any> {
|
|
|
1336
1368
|
interface GridIoApi {
|
|
1337
1369
|
exportCsv(params?: CsvExportParams): string;
|
|
1338
1370
|
importCsv(text: string, options?: ImportCsvOptions): boolean;
|
|
1371
|
+
exportMatrix(params?: MatrixExportParams): unknown[][];
|
|
1372
|
+
/** Synchronous result: replace/append load parser-normalized records; paste starts interactive validation, which may finish later. */
|
|
1373
|
+
importMatrix(rows: readonly (readonly unknown[])[], options?: ImportMatrixOptions): boolean;
|
|
1339
1374
|
print(options?: PrintOptions): boolean;
|
|
1340
1375
|
copyRange(): Promise<boolean>;
|
|
1341
1376
|
}
|
|
@@ -1388,4 +1423,4 @@ interface GridApi<TData = any> {
|
|
|
1388
1423
|
isDestroyed(): boolean;
|
|
1389
1424
|
}
|
|
1390
1425
|
|
|
1391
|
-
export {
|
|
1426
|
+
export { type ContextMenuParams as $, type AdvancedFilterModel as A, type ApplyGridStateOptions as B, type ColDef as C, type CellAlign as D, type CellClassParams as E, type FilterType as F, type GridFeature as G, type CellClassRule as H, type ImportMatrixOptions as I, type CellClickEvent as J, type CellContextMenuEvent as K, type CellDoubleClickEvent as L, type CellEditingStartedEvent as M, type CellEditingStoppedEvent as N, type CellEditorFactory as O, type CellEditorParams as P, type CellRendererOutput as Q, type CellStyleRule as R, type SortModel as S, type CellValueChangedEvent as T, type ColDefOrGroup as U, type ColumnLayoutMode as V, type ColumnMovedEvent as W, type ColumnResizedEvent as X, type ColumnVisibilityChangedEvent as Y, type ColumnWorkbenchItem as Z, type ContextMenuItem as _, type GridCellRange as a, type PaginationConfig as a$, type CsvExportParams as a0, DEFAULT_LOCALE as a1, type DatasourceMode as a2, type DateFilterCondition as a3, type DateFilterMatch as a4, type DetailRowRendererParams as a5, type DetailToggledEvent as a6, type DirtyStateChangedEvent as a7, type DomLayoutMode as a8, EVENT_TYPES as a9, type GridIoApi as aA, type GridPaginationApi as aB, type GridPerformanceSnapshot as aC, type GridPersistenceOptions as aD, type GridReadyEvent as aE, type GridRowsApi as aF, type GridSelectionApi as aG, type GridSortingApi as aH, type GridStateApi as aI, type GridStateSection as aJ, type GridUpdateSchedulerSnapshot as aK, type GridViewApi as aL, type HeaderComponentParams as aM, type ICellEditor as aN, type ICellRendererResult as aO, type ImportCsvOptions as aP, type InfiniteGetRowsParams as aQ, LOCALE_EN as aR, type MachTableLocale as aS, type MachTableLocaleKey as aT, type MatrixExportParams as aU, type ModelUpdatedEvent as aV, type NumberFilterCondition as aW, type NumberFilterMatch as aX, type OverlayContent as aY, type OverlayTemplate as aZ, type PaginationChangedEvent as a_, type EditableIndicator as aa, type EditableParams as ab, type EventHandlers as ac, type FilterChangedEvent as ad, type GetRowHeightParams as ae, type GridAsyncOptions as af, type GridBatchSaveResult as ag, type GridCellChange as ah, type GridColumnsApi as ai, type GridDataProcessorColumn as aj, type GridDataProcessorRequest as ak, type GridDataProcessorResult as al, type GridDataProcessorRow as am, type GridDatasource as an, type GridDiagnosticError as ao, type GridDiagnostics as ap, type GridDiagnosticsApi as aq, type GridEditType as ar, type GridEditingApi as as, type GridErrorCode as at, type GridErrorEvent as au, type GridEventBase as av, type GridEventMap as aw, type GridFeatureContext as ax, type GridFilteringApi as ay, type GridHierarchyApi as az, type GridApi as b, type PinnedDirection as b0, type PrintOptions as b1, type RangeSelectionChangedEvent as b2, type RefreshCellsParams as b3, type RemoteBlockCacheSnapshot as b4, type ResolvedGridOptions as b5, type RowClickEvent as b6, type RowDragEndEvent as b7, type RowDragIntent as b8, type RowDragPolicy as b9, type TooltipParams as bA, type TreeChildrenLoadFailedEvent as bB, type TreeChildrenLoadedEvent as bC, type TreeDataLoadParams as bD, type ValueFormatterParams as bE, type ValueGetterParams as bF, type ValueInputSource as bG, type ValueOutputTarget as bH, type ValueParserParams as bI, type ValueSerializerParams as bJ, type ValueSetterParams as bK, type WatermarkConfig as bL, formatText as bM, formatTwo as bN, isColDefGroup as bO, matchLocaleKey as bP, type RowEditChange as ba, type RowEditValidationParams as bb, type RowEditValidationResult as bc, type RowEditingStartedEvent as bd, type RowEditingStoppedEvent as be, type RowNode as bf, type RowSelectionMode as bg, type RowStyleParams as bh, type RowStyleRule as bi, type RowTone as bj, type RowTransaction as bk, type SaveChangeIssue as bl, type SaveChangesResult as bm, type SelectEditorOption as bn, type SelectEditorParams as bo, type SelectionChangedEvent as bp, type SetFilterCondition as bq, type SetFilterParams as br, type SortChangedEvent as bs, type SortDirection as bt, type SortModelItem as bu, type StatusBarConfig as bv, type StatusBarPanel as bw, type TextFilterCondition as bx, type TextFilterMatch as by, type ThemeMode as bz, type GridOptions as c, type GridDataProcessor as d, type GridComponents as e, type GridState as f, type GridStateStore as g, type FilterModel as h, type FieldPath as i, type GridEventType as j, type SaveChangesHandler as k, type ColumnFilter as l, type AdvancedFilterCondition as m, type AdvancedFilterNode as n, type AdvancedFilterGroup as o, type ColDefGroup as p, type GridStateInput as q, type GridSize as r, type CellRendererParams as s, type GridChange as t, type CellRendererFn as u, type FieldPathValue as v, type SaveChangeConflict as w, type ColumnState as x, type ActionPolicy as y, type ActionPolicyContext as z };
|
|
@@ -1,9 +1,12 @@
|
|
|
1
|
-
import { c as GridOptions, C as ColDef,
|
|
1
|
+
import { c as GridOptions, d as GridDataProcessor, C as ColDef, e as GridComponents } from './api-CZkd8tYy.js';
|
|
2
2
|
|
|
3
3
|
type MachTablePresetSelection = string | readonly string[] | false;
|
|
4
4
|
type MachTableInstanceOptionKey = "rowData" | "columnDefs" | "datasource" | "loading" | "error" | "initialState" | "persistence" | "components" | "columnTypes";
|
|
5
5
|
/** Safe application/preset defaults. Data, request state and persistence identity stay per table. */
|
|
6
|
-
type MachTableDefaults = Omit<Partial<GridOptions<any>>, MachTableInstanceOptionKey
|
|
6
|
+
type MachTableDefaults = Omit<Partial<GridOptions<any>>, MachTableInstanceOptionKey | "dataProcessor"> & {
|
|
7
|
+
/** Called once for each grid; a processor instance belongs to only that grid. */
|
|
8
|
+
dataProcessor?: () => GridDataProcessor<any>;
|
|
9
|
+
};
|
|
7
10
|
type MachTablePreset = MachTableDefaults;
|
|
8
11
|
interface MachTableConfigWarning {
|
|
9
12
|
code: "UNKNOWN_PRESET" | "INVALID_DEFAULT_OPTION" | "INVALID_PRESET_OPTION";
|
|
@@ -1,9 +1,12 @@
|
|
|
1
|
-
import { c as GridOptions, C as ColDef,
|
|
1
|
+
import { c as GridOptions, d as GridDataProcessor, C as ColDef, e as GridComponents } from './api-CZkd8tYy.cjs';
|
|
2
2
|
|
|
3
3
|
type MachTablePresetSelection = string | readonly string[] | false;
|
|
4
4
|
type MachTableInstanceOptionKey = "rowData" | "columnDefs" | "datasource" | "loading" | "error" | "initialState" | "persistence" | "components" | "columnTypes";
|
|
5
5
|
/** Safe application/preset defaults. Data, request state and persistence identity stay per table. */
|
|
6
|
-
type MachTableDefaults = Omit<Partial<GridOptions<any>>, MachTableInstanceOptionKey
|
|
6
|
+
type MachTableDefaults = Omit<Partial<GridOptions<any>>, MachTableInstanceOptionKey | "dataProcessor"> & {
|
|
7
|
+
/** Called once for each grid; a processor instance belongs to only that grid. */
|
|
8
|
+
dataProcessor?: () => GridDataProcessor<any>;
|
|
9
|
+
};
|
|
7
10
|
type MachTablePreset = MachTableDefaults;
|
|
8
11
|
interface MachTableConfigWarning {
|
|
9
12
|
code: "UNKNOWN_PRESET" | "INVALID_DEFAULT_OPTION" | "INVALID_PRESET_OPTION";
|
package/dist/import.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var M=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var ee=Object.prototype.hasOwnProperty;var re=(e,r)=>{for(var o in r)M(e,o,{get:r[o],enumerable:!0})},te=(e,r,o,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let t of Z(r))!ee.call(e,t)&&t!==o&&M(e,t,{get:()=>r[t],enumerable:!(n=Y(r,t))||n.enumerable});return e};var oe=e=>te(M({},"__esModule",{value:!0}),e);var we={};re(we,{createImportPlan:()=>K});module.exports=oe(we);var ne=new Set(["__proto__","prototype","constructor"]),A=new Map;function _(e){if(typeof e!="string"||e.length===0)return null;let r=A.get(e);if(r!==void 0)return r;let o=e.split("."),n=o.every(t=>t.length>0&&!ne.has(t))?o:null;return e.length<=1024&&(A.size>=256&&A.delete(A.keys().next().value),A.set(e,n)),n}function B(e,r){if(e==null)return;let o=_(r);if(!o)return;let n=e;for(let t of o){if(n==null)return;n=n[t]}return n}function U(e,r,o){if(e==null)return!1;let n=_(r);if(!n)return!1;let t=e;for(let s=0;s<n.length-1;s++){if(typeof t!="object"&&typeof t!="function"||t===null)return!1;t[n[s]]==null&&(t[n[s]]={}),t=t[n[s]]}return typeof t!="object"&&typeof t!="function"||t===null?!1:(t[n[n.length-1]]=o,!0)}var se=Symbol.for("mach-table.import.v1");function j(e){let r=e[se];if(!r)throw new TypeError("Import plans require a MachTable GridApi");return r}function ie(e){return Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([r,o])=>{if(r==="length"&&Array.isArray(e)||!o.enumerable)return!1;if(o.get||o.set||["__proto__","prototype","constructor"].includes(r))throw new TypeError("Unsafe import property");return!0})}function N(e){let r=new Set,o=0,n=(t,s)=>{if(++o>2e5||s>32)throw new RangeError("Import snapshot exceeds its value/depth limit");if(t==null||["string","number","boolean","bigint","undefined"].includes(typeof t))return t;if(t instanceof Date)return new Date(t.getTime());if(typeof t!="object"||r.has(t))throw new TypeError("Import values must be acyclic data");let i=Object.getPrototypeOf(t);if(!Array.isArray(t)&&i!==Object.prototype&&i!==null)throw new TypeError("Import records must contain plain data");r.add(t);let m=Array.isArray(t)?[]:{};for(let[l,d]of ie(t))m[l]=n(d.value,s+1);return r.delete(t),m};return n(e,0)}var ae=/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/;function L(e,r=!0){if(e==="")return null;if(!r||typeof e!="string"||!ae.test(e)||/^[+-]?0\d/.test(e))return e;let o=Number(e);return Number.isFinite(o)&&(!Number.isInteger(o)||Number.isSafeInteger(o))?o:e}function pe(e,r,o,n){let t=e.columns().filter(a=>a.colDef.field),s=o.columns??r,i=new Map(t.map(a=>[a.id,a])),m=new Map,l=new Map;for(let a of t){let u=a.colDef.field;m.set(u,m.has(u)?null:a);let f=a.colDef.headerName;f&&l.set(f,l.has(f)?null:a)}let d=[],c=new Set;return s.forEach((a,u)=>{let f=(typeof a=="string"||typeof a=="number"?String(a):"").replace(/^\uFEFF/,"").trim(),P=i.get(f)??(m.has(f)?m.get(f):l.get(f));if(!P){if(n||o.columns||m.has(f)||l.has(f))throw new TypeError(`Unknown or ambiguous import column: ${f}`);return}if(c.has(P.colDef.field))throw new TypeError(`Duplicate import column: ${P.id}`);c.add(P.colDef.field),d.push({column:P,index:u})}),d.length?d:e.visibleColumns().filter(a=>a.colDef.field).map((a,u)=>({column:a,index:u}))}function ue(e,r){if(!Array.isArray(e)||e.some(o=>!Array.isArray(o)))throw new TypeError("Import requires an array of rows");if(!Number.isInteger(r)||r<-1||r>=e.length)throw new RangeError("Invalid import header row");if(e.length-r-1>1e4||e.reduce((o,n)=>o+n.length,0)>1e5)throw new RangeError("Import supports 10000 data rows and 100000 cells")}function le(e,r,o,n,t,s){let i=o.colDef.field,m=e.read(r.node,o),l=s.parseValue?s.parseValue({value:t,field:i,rowIndex:r.rowIndex,columnIndex:n}):o.colDef.valueParser?e.parse(r.node,o,t,m):L(t,s.coerceNumbers!==!1);if(l!=null&&typeof l.then=="function")throw new TypeError("Import parsers must return synchronous values");if(!U(r.data,i,l))throw new TypeError(`Unsafe import field: ${i}`);r.changes.push({node:r.node,column:o,oldValue:m,newValue:l})}function de(e,r,o,n,t,s,i,m){let l=m?.[o]??{},d=i?.[o]??{id:`import:${o}`,rowIndex:o,data:l,selected:!1},c={data:l,node:d,changes:[],rowIndex:o};for(let{column:a,index:u}of n)if(!(r[u]===void 0||i&&!e.editable(d,a)))try{le(e,c,a,u,r[u],t)}catch(f){s.issues.push({rowIndex:o,columnIndex:u,colId:a.id,code:"PARSE",message:f instanceof Error?f.message:String(f)})}s.rows.push(c)}function q(e,r,o={},n,t=!1,s){let i=o.headerRowIndex??(o.columns?-1:0);ue(r,i);let m=pe(e,i<0?[]:r[i],o,t);if(!m.length)throw new TypeError("Import requires a writable field column");let l={rows:[],issues:[]};for(let d=i+1;d<r.length;d++){let c=r[d];c.some(a=>a!==""&&a!==void 0)&&de(e,c,d-i-1,m,o,l,n,s)}return l}function F(e,r,o,n){if(e.rows.isRemote())throw new TypeError("Import plans require local records");if(n.mode!=="paste"&&e.getOption("treeData"))throw new TypeError("Import plans require a flat-record model for replace/append");if(r.isEditing())throw new TypeError("Finish active editing before importing");if(n.mode!=="paste"&&e.editing.getDirtyRowIds().length)throw new TypeError("Save or roll back pending changes before loading records");let t=N(o),s=n.mode==="paste"?r.pasteRows(t.rows.length):void 0,i,m;if(t.kind==="rows"){m=t.rows;let d=n.columns??r.columns().filter(u=>u.colDef.field).map(u=>u.id),c=new Map(r.columns().map(u=>[u.id,u.colDef.field])),a=d.map(u=>c.get(u)??u);i=t.rows.map(u=>a.map(f=>B(u,f))),n={...n,columns:d,headerRowIndex:-1}}else i=t.rows;let l=q(r,i,n,s,!0,m);if(!s&&l.rows.some(d=>d.changes.some(c=>c.column.colDef.valueGetter||c.column.colDef.valueSetter)))throw new TypeError("New records require ordinary field columns; custom getters/setters are ambiguous");return l}var b=(e,r="UNSUPPORTED",o=-1)=>({rowIndex:o,code:r,message:e}),z=e=>e instanceof Error?e.message:String(e);function me(e,r,o,n){let t=new Set;for(let s of o.rows){if(n==="paste"){e.rows.getById(s.node.id)!==s.node&&o.issues.push(b("Paste target is not loaded","MAPPING",s.rowIndex));continue}try{let i=r.resolveId(s.data,s.rowIndex);if(i===void 0)continue;(!i||t.has(i)||n==="append"&&e.rows.getById(i))&&o.issues.push(b(`Missing or duplicate row key: ${i}`,"MAPPING",s.rowIndex)),t.add(i),s.node.id=i}catch(i){o.issues.push(b(z(i),"MAPPING",s.rowIndex))}}}function ce(e,r,o,n){let t=F(e,r,o,n);if(n.mode==="paste")for(let s of t.rows)s.changes.length||t.issues.push(b("Paste row has no editable destination cells","VALIDATION",s.rowIndex)),s.changes=s.changes.filter(i=>i.newValue!==void 0&&!Object.is(i.oldValue,i.newValue));return t.rows.length||t.issues.push(b("Import contains no data rows","MAPPING")),me(e,r,t,n.mode),t}function $(e,r){return r.map(o=>({rowIndex:e.rowIndex,colId:o.colId,code:"VALIDATION",message:o.message}))}function fe(e){let r=e.rows.flatMap(n=>n.changes.map(t=>({rowIndex:n.rowIndex,colId:t.column.id,value:t.newValue}))),o=N(r.map(n=>n.value));return r.map((n,t)=>({...n,value:o[t]}))}function Ie(e){let r=new Map;for(let o of e){let n=r.get(o.rowIndex)??[];n.push(o),r.set(o.rowIndex,n)}return r}function K(e,r,o={}){let n=j(e),t={...o,columns:o.columns?[...o.columns]:void 0},s=!1,i=0,m=0,l=!1,d,c,a,u,f=[e.on("modelUpdated",()=>i++),e.on("cellValueChanged",()=>i++)],P=()=>s||e.isDestroyed()?"destroyed":"stale",T=(p,y=[])=>({status:p,rowCount:0,cells:[],issues:y}),k=()=>{s||(s=!0,m++,d=void 0,f.forEach(p=>p()))};f.push(e.on("gridDestroyed",k));async function H(){let p=++m;if(d=void 0,s||e.isDestroyed())return T("destroyed");if(l)return T("stale",[b("This import plan has already committed","STALE")]);let y=n.begin(),x=n.revision(),v=n.columns(),D=i,E=e.getOption("rowEditValidator"),R=e.getOption("rowKey"),O=()=>!s&&p===m&&y()&&n.revision()===x&&n.columns()===v&&e.getOption("rowEditValidator")===E&&e.getOption("rowKey")===R,w=()=>O()&&i===D;try{let I=ce(e,n,r,t),h=I.rows.map(g=>t.mode==="paste"&&g.changes.length?n.guard(g.changes):()=>!0),S=I.rows.map((g,V)=>({changes:g.changes,current:()=>w()&&h[V]()})),C=await Promise.all(S.map(g=>Promise.resolve(g.changes.length?n.validate(g.changes,g.current):[])));if(!w())return T(P(),[b("Grid, columns or input changed during validation","STALE")]);I.rows.forEach((g,V)=>I.issues.push(...$(g,C[V])));let W=fe(I);return d={prepared:I,rows:S,guards:h,errors:C,current:w,intent:O},{status:I.issues.length?"invalid":"ready",rowCount:I.rows.length,cells:W,issues:I.issues.map(g=>({...g}))}}catch(I){return T(w()?"invalid":P(),[b(z(I))])}}async function X(){c?await c:!d&&!a&&await G()}async function J(){if(await X(),s||e.isDestroyed())return{status:"destroyed",importedRowCount:0,issues:[]};let p=d;if(!p&&a?.status==="invalid")return{status:"invalid",importedRowCount:0,issues:a.issues.map(v=>({...v}))};if(!p?.current()||l)return{status:"stale",importedRowCount:0,issues:[b("Import preview is no longer current","STALE")]};let{prepared:y}=p;if(y.issues.length&&t.mode!=="paste")return{status:"invalid",importedRowCount:0,issues:y.issues.map(v=>({...v}))};if(l=!0,t.mode==="paste")return Q(p);let x=y.rows.map(v=>v.data);return t.mode==="append"?e.rows.transact({add:x}):e.rows.setData(x),{status:"applied",importedRowCount:x.length,issues:[]}}function Q(p){let y=Ie(p.prepared.issues),x=p.errors.map((w,I)=>[...w,...(y.get(p.prepared.rows[I].rowIndex)??[]).filter(h=>h.code!=="VALIDATION").map(h=>({colId:h.colId??"",message:h.message}))]),v=p.rows.map((w,I)=>({...w,current:()=>p.intent()&&p.guards[I]()})),D=n.commitRows(v,x,p.intent),E=[...p.prepared.issues,...D.flatMap((w,I)=>{let h=p.prepared.rows[I],S=new Set((y.get(h.rowIndex)??[]).map(C=>C.message));return $(h,w.errors).filter(C=>!S.has(C.message))})],R=D.filter(w=>w.applied).length;return p.intent()?{status:E.length>0||R<p.rows.filter(w=>w.changes.length).length?R?"partial":"invalid":"applied",importedRowCount:R,issues:E}:{status:P(),importedRowCount:R,issues:[...E,b("Input scope changed during commit","STALE")]}}function G(){let p=H();return c=p,a=void 0,p.then(y=>{c===p&&(a=y)}),p.finally(()=>{c===p&&(c=void 0)}),p}return{preview:G,commit:()=>u??(u=J().finally(()=>{u=void 0})),destroy:k}}0&&(module.exports={createImportPlan});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { I as ImportMatrixOptions, b as GridApi } from './api-CZkd8tYy.cjs';
|
|
2
|
+
|
|
3
|
+
interface ImportIssue {
|
|
4
|
+
/** Zero-based data-row index, excluding the header. -1 denotes the complete plan. */
|
|
5
|
+
rowIndex: number;
|
|
6
|
+
columnIndex?: number;
|
|
7
|
+
colId?: string;
|
|
8
|
+
code: "MAPPING" | "PARSE" | "VALIDATION" | "STALE" | "UNSUPPORTED";
|
|
9
|
+
message: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
type ImportSource<TData = Record<string, unknown>> = {
|
|
13
|
+
kind: "matrix";
|
|
14
|
+
rows: readonly (readonly unknown[])[];
|
|
15
|
+
} | {
|
|
16
|
+
kind: "rows";
|
|
17
|
+
rows: readonly TData[];
|
|
18
|
+
};
|
|
19
|
+
type ImportPlanOptions = ImportMatrixOptions;
|
|
20
|
+
interface ImportPreviewCell {
|
|
21
|
+
rowIndex: number;
|
|
22
|
+
colId: string;
|
|
23
|
+
value: unknown;
|
|
24
|
+
}
|
|
25
|
+
interface ImportPreview {
|
|
26
|
+
status: "ready" | "invalid" | "stale" | "destroyed";
|
|
27
|
+
rowCount: number;
|
|
28
|
+
cells: readonly ImportPreviewCell[];
|
|
29
|
+
issues: readonly ImportIssue[];
|
|
30
|
+
}
|
|
31
|
+
interface ImportResult {
|
|
32
|
+
status: "applied" | "partial" | "invalid" | "stale" | "destroyed";
|
|
33
|
+
importedRowCount: number;
|
|
34
|
+
issues: readonly ImportIssue[];
|
|
35
|
+
}
|
|
36
|
+
interface ImportPlan {
|
|
37
|
+
/** Re-parse and validate the bounded input snapshot; a newer preview cancels the older one. */
|
|
38
|
+
preview(): Promise<ImportPreview>;
|
|
39
|
+
/** Uses the last successful preview, or previews once if none exists. A plan commits at most once. */
|
|
40
|
+
commit(): Promise<ImportResult>;
|
|
41
|
+
destroy(): void;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** An explicit, bounded transaction preview. No worker, workbook state or second value-writing engine. */
|
|
45
|
+
declare function createImportPlan<TData>(api: GridApi<TData>, source: ImportSource<TData>, options?: ImportPlanOptions): ImportPlan;
|
|
46
|
+
|
|
47
|
+
export { type ImportIssue, type ImportPlan, type ImportPlanOptions, type ImportPreview, type ImportPreviewCell, type ImportResult, type ImportSource, createImportPlan };
|
package/dist/import.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { I as ImportMatrixOptions, b as GridApi } from './api-CZkd8tYy.js';
|
|
2
|
+
|
|
3
|
+
interface ImportIssue {
|
|
4
|
+
/** Zero-based data-row index, excluding the header. -1 denotes the complete plan. */
|
|
5
|
+
rowIndex: number;
|
|
6
|
+
columnIndex?: number;
|
|
7
|
+
colId?: string;
|
|
8
|
+
code: "MAPPING" | "PARSE" | "VALIDATION" | "STALE" | "UNSUPPORTED";
|
|
9
|
+
message: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
type ImportSource<TData = Record<string, unknown>> = {
|
|
13
|
+
kind: "matrix";
|
|
14
|
+
rows: readonly (readonly unknown[])[];
|
|
15
|
+
} | {
|
|
16
|
+
kind: "rows";
|
|
17
|
+
rows: readonly TData[];
|
|
18
|
+
};
|
|
19
|
+
type ImportPlanOptions = ImportMatrixOptions;
|
|
20
|
+
interface ImportPreviewCell {
|
|
21
|
+
rowIndex: number;
|
|
22
|
+
colId: string;
|
|
23
|
+
value: unknown;
|
|
24
|
+
}
|
|
25
|
+
interface ImportPreview {
|
|
26
|
+
status: "ready" | "invalid" | "stale" | "destroyed";
|
|
27
|
+
rowCount: number;
|
|
28
|
+
cells: readonly ImportPreviewCell[];
|
|
29
|
+
issues: readonly ImportIssue[];
|
|
30
|
+
}
|
|
31
|
+
interface ImportResult {
|
|
32
|
+
status: "applied" | "partial" | "invalid" | "stale" | "destroyed";
|
|
33
|
+
importedRowCount: number;
|
|
34
|
+
issues: readonly ImportIssue[];
|
|
35
|
+
}
|
|
36
|
+
interface ImportPlan {
|
|
37
|
+
/** Re-parse and validate the bounded input snapshot; a newer preview cancels the older one. */
|
|
38
|
+
preview(): Promise<ImportPreview>;
|
|
39
|
+
/** Uses the last successful preview, or previews once if none exists. A plan commits at most once. */
|
|
40
|
+
commit(): Promise<ImportResult>;
|
|
41
|
+
destroy(): void;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** An explicit, bounded transaction preview. No worker, workbook state or second value-writing engine. */
|
|
45
|
+
declare function createImportPlan<TData>(api: GridApi<TData>, source: ImportSource<TData>, options?: ImportPlanOptions): ImportPlan;
|
|
46
|
+
|
|
47
|
+
export { type ImportIssue, type ImportPlan, type ImportPlanOptions, type ImportPreview, type ImportPreviewCell, type ImportResult, type ImportSource, createImportPlan };
|
package/dist/import.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var Q=new Set(["__proto__","prototype","constructor"]),A=new Map;function G(e){if(typeof e!="string"||e.length===0)return null;let o=A.get(e);if(o!==void 0)return o;let t=e.split("."),n=t.every(r=>r.length>0&&!Q.has(r))?t:null;return e.length<=1024&&(A.size>=256&&A.delete(A.keys().next().value),A.set(e,n)),n}function _(e,o){if(e==null)return;let t=G(o);if(!t)return;let n=e;for(let r of t){if(n==null)return;n=n[r]}return n}function B(e,o,t){if(e==null)return!1;let n=G(o);if(!n)return!1;let r=e;for(let s=0;s<n.length-1;s++){if(typeof r!="object"&&typeof r!="function"||r===null)return!1;r[n[s]]==null&&(r[n[s]]={}),r=r[n[s]]}return typeof r!="object"&&typeof r!="function"||r===null?!1:(r[n[n.length-1]]=t,!0)}var W=Symbol.for("mach-table.import.v1");function U(e){let o=e[W];if(!o)throw new TypeError("Import plans require a MachTable GridApi");return o}function Y(e){return Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([o,t])=>{if(o==="length"&&Array.isArray(e)||!t.enumerable)return!1;if(t.get||t.set||["__proto__","prototype","constructor"].includes(o))throw new TypeError("Unsafe import property");return!0})}function N(e){let o=new Set,t=0,n=(r,s)=>{if(++t>2e5||s>32)throw new RangeError("Import snapshot exceeds its value/depth limit");if(r==null||["string","number","boolean","bigint","undefined"].includes(typeof r))return r;if(r instanceof Date)return new Date(r.getTime());if(typeof r!="object"||o.has(r))throw new TypeError("Import values must be acyclic data");let i=Object.getPrototypeOf(r);if(!Array.isArray(r)&&i!==Object.prototype&&i!==null)throw new TypeError("Import records must contain plain data");o.add(r);let m=Array.isArray(r)?[]:{};for(let[l,d]of Y(r))m[l]=n(d.value,s+1);return o.delete(r),m};return n(e,0)}var Z=/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/;function j(e,o=!0){if(e==="")return null;if(!o||typeof e!="string"||!Z.test(e)||/^[+-]?0\d/.test(e))return e;let t=Number(e);return Number.isFinite(t)&&(!Number.isInteger(t)||Number.isSafeInteger(t))?t:e}function ee(e,o,t,n){let r=e.columns().filter(a=>a.colDef.field),s=t.columns??o,i=new Map(r.map(a=>[a.id,a])),m=new Map,l=new Map;for(let a of r){let u=a.colDef.field;m.set(u,m.has(u)?null:a);let f=a.colDef.headerName;f&&l.set(f,l.has(f)?null:a)}let d=[],c=new Set;return s.forEach((a,u)=>{let f=(typeof a=="string"||typeof a=="number"?String(a):"").replace(/^\uFEFF/,"").trim(),P=i.get(f)??(m.has(f)?m.get(f):l.get(f));if(!P){if(n||t.columns||m.has(f)||l.has(f))throw new TypeError(`Unknown or ambiguous import column: ${f}`);return}if(c.has(P.colDef.field))throw new TypeError(`Duplicate import column: ${P.id}`);c.add(P.colDef.field),d.push({column:P,index:u})}),d.length?d:e.visibleColumns().filter(a=>a.colDef.field).map((a,u)=>({column:a,index:u}))}function re(e,o){if(!Array.isArray(e)||e.some(t=>!Array.isArray(t)))throw new TypeError("Import requires an array of rows");if(!Number.isInteger(o)||o<-1||o>=e.length)throw new RangeError("Invalid import header row");if(e.length-o-1>1e4||e.reduce((t,n)=>t+n.length,0)>1e5)throw new RangeError("Import supports 10000 data rows and 100000 cells")}function te(e,o,t,n,r,s){let i=t.colDef.field,m=e.read(o.node,t),l=s.parseValue?s.parseValue({value:r,field:i,rowIndex:o.rowIndex,columnIndex:n}):t.colDef.valueParser?e.parse(o.node,t,r,m):j(r,s.coerceNumbers!==!1);if(l!=null&&typeof l.then=="function")throw new TypeError("Import parsers must return synchronous values");if(!B(o.data,i,l))throw new TypeError(`Unsafe import field: ${i}`);o.changes.push({node:o.node,column:t,oldValue:m,newValue:l})}function oe(e,o,t,n,r,s,i,m){let l=m?.[t]??{},d=i?.[t]??{id:`import:${t}`,rowIndex:t,data:l,selected:!1},c={data:l,node:d,changes:[],rowIndex:t};for(let{column:a,index:u}of n)if(!(o[u]===void 0||i&&!e.editable(d,a)))try{te(e,c,a,u,o[u],r)}catch(f){s.issues.push({rowIndex:t,columnIndex:u,colId:a.id,code:"PARSE",message:f instanceof Error?f.message:String(f)})}s.rows.push(c)}function L(e,o,t={},n,r=!1,s){let i=t.headerRowIndex??(t.columns?-1:0);re(o,i);let m=ee(e,i<0?[]:o[i],t,r);if(!m.length)throw new TypeError("Import requires a writable field column");let l={rows:[],issues:[]};for(let d=i+1;d<o.length;d++){let c=o[d];c.some(a=>a!==""&&a!==void 0)&&oe(e,c,d-i-1,m,t,l,n,s)}return l}function q(e,o,t,n){if(e.rows.isRemote())throw new TypeError("Import plans require local records");if(n.mode!=="paste"&&e.getOption("treeData"))throw new TypeError("Import plans require a flat-record model for replace/append");if(o.isEditing())throw new TypeError("Finish active editing before importing");if(n.mode!=="paste"&&e.editing.getDirtyRowIds().length)throw new TypeError("Save or roll back pending changes before loading records");let r=N(t),s=n.mode==="paste"?o.pasteRows(r.rows.length):void 0,i,m;if(r.kind==="rows"){m=r.rows;let d=n.columns??o.columns().filter(u=>u.colDef.field).map(u=>u.id),c=new Map(o.columns().map(u=>[u.id,u.colDef.field])),a=d.map(u=>c.get(u)??u);i=r.rows.map(u=>a.map(f=>_(u,f))),n={...n,columns:d,headerRowIndex:-1}}else i=r.rows;let l=L(o,i,n,s,!0,m);if(!s&&l.rows.some(d=>d.changes.some(c=>c.column.colDef.valueGetter||c.column.colDef.valueSetter)))throw new TypeError("New records require ordinary field columns; custom getters/setters are ambiguous");return l}var b=(e,o="UNSUPPORTED",t=-1)=>({rowIndex:t,code:o,message:e}),$=e=>e instanceof Error?e.message:String(e);function ne(e,o,t,n){let r=new Set;for(let s of t.rows){if(n==="paste"){e.rows.getById(s.node.id)!==s.node&&t.issues.push(b("Paste target is not loaded","MAPPING",s.rowIndex));continue}try{let i=o.resolveId(s.data,s.rowIndex);if(i===void 0)continue;(!i||r.has(i)||n==="append"&&e.rows.getById(i))&&t.issues.push(b(`Missing or duplicate row key: ${i}`,"MAPPING",s.rowIndex)),r.add(i),s.node.id=i}catch(i){t.issues.push(b($(i),"MAPPING",s.rowIndex))}}}function se(e,o,t,n){let r=q(e,o,t,n);if(n.mode==="paste")for(let s of r.rows)s.changes.length||r.issues.push(b("Paste row has no editable destination cells","VALIDATION",s.rowIndex)),s.changes=s.changes.filter(i=>i.newValue!==void 0&&!Object.is(i.oldValue,i.newValue));return r.rows.length||r.issues.push(b("Import contains no data rows","MAPPING")),ne(e,o,r,n.mode),r}function F(e,o){return o.map(t=>({rowIndex:e.rowIndex,colId:t.colId,code:"VALIDATION",message:t.message}))}function ie(e){let o=e.rows.flatMap(n=>n.changes.map(r=>({rowIndex:n.rowIndex,colId:r.column.id,value:r.newValue}))),t=N(o.map(n=>n.value));return o.map((n,r)=>({...n,value:t[r]}))}function ae(e){let o=new Map;for(let t of e){let n=o.get(t.rowIndex)??[];n.push(t),o.set(t.rowIndex,n)}return o}function pe(e,o,t={}){let n=U(e),r={...t,columns:t.columns?[...t.columns]:void 0},s=!1,i=0,m=0,l=!1,d,c,a,u,f=[e.on("modelUpdated",()=>i++),e.on("cellValueChanged",()=>i++)],P=()=>s||e.isDestroyed()?"destroyed":"stale",T=(p,y=[])=>({status:p,rowCount:0,cells:[],issues:y}),M=()=>{s||(s=!0,m++,d=void 0,f.forEach(p=>p()))};f.push(e.on("gridDestroyed",M));async function z(){let p=++m;if(d=void 0,s||e.isDestroyed())return T("destroyed");if(l)return T("stale",[b("This import plan has already committed","STALE")]);let y=n.begin(),x=n.revision(),v=n.columns(),D=i,E=e.getOption("rowEditValidator"),R=e.getOption("rowKey"),O=()=>!s&&p===m&&y()&&n.revision()===x&&n.columns()===v&&e.getOption("rowEditValidator")===E&&e.getOption("rowKey")===R,w=()=>O()&&i===D;try{let I=se(e,n,o,r),h=I.rows.map(g=>r.mode==="paste"&&g.changes.length?n.guard(g.changes):()=>!0),S=I.rows.map((g,V)=>({changes:g.changes,current:()=>w()&&h[V]()})),C=await Promise.all(S.map(g=>Promise.resolve(g.changes.length?n.validate(g.changes,g.current):[])));if(!w())return T(P(),[b("Grid, columns or input changed during validation","STALE")]);I.rows.forEach((g,V)=>I.issues.push(...F(g,C[V])));let J=ie(I);return d={prepared:I,rows:S,guards:h,errors:C,current:w,intent:O},{status:I.issues.length?"invalid":"ready",rowCount:I.rows.length,cells:J,issues:I.issues.map(g=>({...g}))}}catch(I){return T(w()?"invalid":P(),[b($(I))])}}async function K(){c?await c:!d&&!a&&await k()}async function H(){if(await K(),s||e.isDestroyed())return{status:"destroyed",importedRowCount:0,issues:[]};let p=d;if(!p&&a?.status==="invalid")return{status:"invalid",importedRowCount:0,issues:a.issues.map(v=>({...v}))};if(!p?.current()||l)return{status:"stale",importedRowCount:0,issues:[b("Import preview is no longer current","STALE")]};let{prepared:y}=p;if(y.issues.length&&r.mode!=="paste")return{status:"invalid",importedRowCount:0,issues:y.issues.map(v=>({...v}))};if(l=!0,r.mode==="paste")return X(p);let x=y.rows.map(v=>v.data);return r.mode==="append"?e.rows.transact({add:x}):e.rows.setData(x),{status:"applied",importedRowCount:x.length,issues:[]}}function X(p){let y=ae(p.prepared.issues),x=p.errors.map((w,I)=>[...w,...(y.get(p.prepared.rows[I].rowIndex)??[]).filter(h=>h.code!=="VALIDATION").map(h=>({colId:h.colId??"",message:h.message}))]),v=p.rows.map((w,I)=>({...w,current:()=>p.intent()&&p.guards[I]()})),D=n.commitRows(v,x,p.intent),E=[...p.prepared.issues,...D.flatMap((w,I)=>{let h=p.prepared.rows[I],S=new Set((y.get(h.rowIndex)??[]).map(C=>C.message));return F(h,w.errors).filter(C=>!S.has(C.message))})],R=D.filter(w=>w.applied).length;return p.intent()?{status:E.length>0||R<p.rows.filter(w=>w.changes.length).length?R?"partial":"invalid":"applied",importedRowCount:R,issues:E}:{status:P(),importedRowCount:R,issues:[...E,b("Input scope changed during commit","STALE")]}}function k(){let p=z();return c=p,a=void 0,p.then(y=>{c===p&&(a=y)}),p.finally(()=>{c===p&&(c=void 0)}),p}return{preview:k,commit:()=>u??(u=H().finally(()=>{u=void 0})),destroy:M}}export{pe as createImportPlan};
|