cenitu-table 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +137 -3
  3. package/README.tr.md +126 -0
  4. package/dist/cenitu-table.cjs +1 -0
  5. package/dist/cenitu-table.js +52 -0
  6. package/dist/index-BJIaMXd1.cjs +164 -0
  7. package/dist/index-DG98ykBX.js +5230 -0
  8. package/dist/react.cjs +1 -0
  9. package/dist/react.js +70 -0
  10. package/dist/types/export/csv.d.ts +26 -0
  11. package/dist/types/export/download.d.ts +3 -0
  12. package/dist/types/export/index.d.ts +6 -0
  13. package/dist/types/export/numberFormat.d.ts +12 -0
  14. package/dist/types/export/styles.d.ts +14 -0
  15. package/dist/types/export/types.d.ts +48 -0
  16. package/dist/types/export/xlsx.d.ts +24 -0
  17. package/dist/types/export/xml.d.ts +5 -0
  18. package/dist/types/export/zip.d.ts +20 -0
  19. package/dist/types/formula/address.d.ts +25 -0
  20. package/dist/types/formula/array-functions.d.ts +1 -0
  21. package/dist/types/formula/arrays.d.ts +13 -0
  22. package/dist/types/formula/ast.d.ts +82 -0
  23. package/dist/types/formula/coerce.d.ts +12 -0
  24. package/dist/types/formula/criteria-functions.d.ts +1 -0
  25. package/dist/types/formula/date-functions.d.ts +1 -0
  26. package/dist/types/formula/dates.d.ts +23 -0
  27. package/dist/types/formula/engine.d.ts +225 -0
  28. package/dist/types/formula/environment.d.ts +9 -0
  29. package/dist/types/formula/functions.d.ts +63 -0
  30. package/dist/types/formula/index.d.ts +10 -0
  31. package/dist/types/formula/interpreter.d.ts +23 -0
  32. package/dist/types/formula/lexer.d.ts +46 -0
  33. package/dist/types/formula/logic-functions.d.ts +1 -0
  34. package/dist/types/formula/lookup-functions.d.ts +1 -0
  35. package/dist/types/formula/math-functions.d.ts +1 -0
  36. package/dist/types/formula/parser.d.ts +12 -0
  37. package/dist/types/formula/restructure.d.ts +98 -0
  38. package/dist/types/formula/stat-functions.d.ts +1 -0
  39. package/dist/types/formula/text-format.d.ts +14 -0
  40. package/dist/types/formula/text-functions.d.ts +2 -0
  41. package/dist/types/formula/values.d.ts +41 -0
  42. package/dist/types/grid/autofill.d.ts +11 -0
  43. package/dist/types/grid/axis.d.ts +21 -0
  44. package/dist/types/grid/binding.d.ts +35 -0
  45. package/dist/types/grid/cellTypes.d.ts +82 -0
  46. package/dist/types/grid/columnMenu.d.ts +17 -0
  47. package/dist/types/grid/contextMenu.d.ts +15 -0
  48. package/dist/types/grid/filters.d.ts +14 -0
  49. package/dist/types/grid/grid.d.ts +380 -0
  50. package/dist/types/grid/merges.d.ts +24 -0
  51. package/dist/types/grid/messages.d.ts +47 -0
  52. package/dist/types/grid/rowMapper.d.ts +44 -0
  53. package/dist/types/grid/styles.d.ts +1 -0
  54. package/dist/types/grid/tsv.d.ts +3 -0
  55. package/dist/types/index.d.ts +9 -0
  56. package/dist/types/react/index.d.ts +19 -0
  57. package/package.json +76 -4
@@ -0,0 +1,164 @@
1
+ "use strict";var bn=Object.defineProperty;var An=(s,t,e)=>t in s?bn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var v=(s,t,e)=>An(s,typeof t!="symbol"?t+"":t,e);const N=(s,t,e=0)=>e*17179869184+s*16384+t,me=s=>{const t=Math.floor(s/17179869184),e=s-t*17179869184;return{row:Math.floor(e/16384),col:e%16384,sheet:t}};function Rt(s){let t="",e=s+1;for(;e>0;){const n=(e-1)%26;t=String.fromCharCode(65+n)+t,e=Math.floor((e-1)/26)}return t}function Me(s){let t=0;for(const e of s.toUpperCase()){const n=e.charCodeAt(0);if(n<65||n>90)return-1;t=t*26+(n-64)}return t-1}const Cn=/^\$?([A-Za-z]{1,3})\$?(\d+)$/;function Re(s){const t=Cn.exec(s.trim());if(!t)return;const e=Me(t[1]),n=Number(t[2])-1;if(!(e<0||e>=16384||n<0||n>=1048576))return{row:n,col:e}}const As=({row:s,col:t})=>`${Rt(t)}${s+1}`;function Cs(s,t){return{start:{row:Math.min(s.row,t.row),col:Math.min(s.col,t.col)},end:{row:Math.max(s.row,t.row),col:Math.max(s.col,t.col)}}}const Sn=(s,t,e)=>t>=s.start.row&&t<=s.end.row&&e>=s.start.col&&e<=s.end.col,En=/^[\p{L}_][\p{L}\p{N}_.]*$/u;function Ss(s){return En.test(s)&&!Re(s)&&!/^(TRUE|FALSE)$/i.test(s)?s:`'${s.replace(/'/g,"''")}'`}function ne(s,t={}){var r,i;const e=s.rowAbs?s.row:s.row+(((r=t.base)==null?void 0:r.row)??0),n=s.colAbs?s.col:s.col+(((i=t.base)==null?void 0:i.col)??0);return e<0||n<0?"#REF!":`${s.colAbs?"$":""}${Rt(n)}${s.rowAbs?"$":""}${e+1}`}function We(s,t){var e;return s.sheet===void 0?"":Ss(((e=t.sheetName)==null?void 0:e.call(t,s.sheet))??`Sheet${s.sheet+1}`)+"!"}function jt(s,t={}){const e=n=>jt(n,t);switch(s.type){case"number":return String(s.value);case"string":return`"${s.value.replace(/"/g,'""')}"`;case"bool":return s.value?"TRUE":"FALSE";case"error":return s.code;case"ref":{const n=ne(s,t);return n==="#REF!"?n:We(s,t)+n}case"range":{const n=ne(s.start,t),r=ne(s.end,t);return n==="#REF!"||r==="#REF!"?"#REF!":`${We(s.start,t)}${n}:${r}`}case"name":return s.name;case"unary":return s.op+e(s.arg);case"percent":return e(s.arg)+"%";case"binary":return e(s.left)+s.op+e(s.right);case"paren":return`(${e(s.expr)})`;case"call":return`${s.name}(${s.args.map(e).join(",")})`}}function Z(s,t){switch(s.type){case"ref":case"range":case"name":return t(s);case"unary":case"percent":return Z(s.arg,t);case"binary":return Z(s.left,t),Z(s.right,t);case"paren":return Z(s.expr,t);case"call":for(const e of s.args)Z(e,t)}}function St(s,t){switch(s.type){case"unary":case"percent":return St(s.arg,t);case"binary":return St(s.left,t),St(s.right,t);case"paren":return St(s.expr,t);case"call":t(s.name);for(const e of s.args)St(e,t)}}function Et(s,t){switch(s.type){case"ref":case"range":case"name":return t(s);case"unary":case"percent":return s.arg=Et(s.arg,t),s;case"binary":return s.left=Et(s.left,t),s.right=Et(s.right,t),s;case"paren":return s.expr=Et(s.expr,t),s;case"call":for(let e=0;e<s.args.length;e++)s.args[e]=Et(s.args[e],t);return s;default:return s}}const Mn=["#DIV/0!","#VALUE!","#REF!","#NAME?","#N/A","#NUM!","#NULL!","#ERROR!","#CYCLE!","#SPILL!","#CALC!"];class rt{constructor(t,e){this.code=t,this.message=e}toString(){return this.code}}class R{constructor(t,e){this.values=t,this.origin=e}get height(){return this.values.length}get width(){var t;return((t=this.values[0])==null?void 0:t.length)??0}*flat(){for(const t of this.values)yield*t}}const m=s=>s instanceof rt,A=(s,t)=>new rt(s,t);function F(s){return typeof s=="string"&&s.length>1&&s[0]==="="}function et(s){if(s==null||s==="")return null;if(typeof s!="string")return s;if(s[0]==="'")return s.slice(1);const t=wt(s);if(t!==void 0)return t;const e=s.toUpperCase();return e==="TRUE"?!0:e==="FALSE"?!1:s}const Rn=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?%?$/;function wt(s){const t=s.trim();if(Rn.test(t))return t.endsWith("%")?Number(t.slice(0,-1))/100:Number(t)}function T(s){return!Number.isFinite(s)||Number.isInteger(s)?s:Number(s.toPrecision(15))}function H(s){if(m(s))return s;if(s===null)return 0;if(typeof s=="number")return s;if(typeof s=="boolean")return s?1:0;const t=wt(s);return t===void 0?A("#VALUE!",`"${s}" is not a number`):t}function K(s){return m(s)?s:s===null?"":typeof s=="boolean"?s?"TRUE":"FALSE":typeof s=="number"?ke(s):s}function st(s){if(m(s))return s;if(s===null)return!1;if(typeof s=="boolean")return s;if(typeof s=="number")return s!==0;const t=s.toUpperCase();return t==="TRUE"?!0:t==="FALSE"?!1:A("#VALUE!",`"${s}" is not a boolean`)}function ke(s){return String(T(s))}function k(s){return s instanceof R?s.height===1&&s.width===1?s.values[0][0]:A("#VALUE!","Range used where a single value is expected"):s}const je=s=>typeof s=="number"?0:typeof s=="string"?1:2;function L(s,t){s===null&&(s=t===null?0:typeof t=="string"?"":typeof t=="boolean"?!1:0),t===null&&(t=typeof s=="string"?"":typeof s=="boolean"?!1:0);const e=je(s),n=je(t);if(e!==n)return e-n;if(typeof s=="string"){const o=s.toLowerCase(),l=t.toLowerCase();return o<l?-1:o>l?1:0}const r=Number(s),i=Number(t);return r<i?-1:r>i?1:0}const Es=s=>s instanceof R&&(s.height!==1||s.width!==1),B=s=>s instanceof R?s:new R([[s]]);function mt(s,t){let e=0,n=0;for(const i of s)Es(i)&&(e=Math.max(e,i.height),n=Math.max(n,i.width));if(e===0)return t(...s.map(k));const r=[];for(let i=0;i<e;i++){const o=[];for(let l=0;l<n;l++)o.push(t(...s.map(a=>kn(a,i,l))));r.push(o)}return new R(r)}function kn(s,t,e){if(!(s instanceof R))return s;const n=s.height===1?0:t,r=s.width===1?0:e;return n<s.height&&r<s.width?s.values[n][r]:A("#N/A")}const Ms=(s,t)=>s.values.map(e=>e[t]);function ge(s){return new R(Array.from({length:s.width},(t,e)=>Ms(s,e)))}const Gt=new Map;function w(s,t){const e=typeof t=="function"?{impl:t}:t;Gt.set(s.toUpperCase(),$n(s.toUpperCase(),e))}function Dn(s){Gt.delete(s.toUpperCase())}const we=s=>Gt.get(s.toUpperCase()),Nn=()=>[...Gt.keys()].sort();function $n(s,t){const{minArgs:e=0,maxArgs:n=1/0}=t,r=i=>i<e||i>n?A("#VALUE!",`Wrong number of arguments to ${s}`):void 0;return{...t,impl:t.impl&&((i,o)=>r(i.length)??t.impl(i,o)),lazy:t.lazy&&((i,o)=>r(i.length)??t.lazy(i,o))}}const V=s=>H(k(s));function ct(s){const t=[];for(const e of s)if(e instanceof R)for(const n of e.flat()){if(m(n))return n;typeof n=="number"&&t.push(n)}else{if(e===null)continue;const n=H(e);if(m(n))return n;t.push(n)}return t}function P(s){return t=>mt(t,(...e)=>{const n=[];for(const i of e){const o=H(i);if(m(o))return o;n.push(o)}const r=s(...n);return m(r)?r:Number.isFinite(r)?T(r):A("#NUM!")})}function Ut(s){return t=>mt(t,(...e)=>{const n=[];for(const r of e){const i=K(r);if(m(i))return i;n.push(i)}return s(...n)})}const lt=s=>s instanceof R?s:new R([[s]]);class Zt{constructor(){v(this,"sum",0);v(this,"comp",0)}add(t){const e=this.sum+t;this.comp+=Math.abs(this.sum)>=Math.abs(t)?this.sum-e+t:t-e+this.sum,this.sum=e}get value(){return this.sum+this.comp}}const Yt=s=>{const t=new Zt;return s.forEach(e=>t.add(e)),t.value};function zn(s,t){const e=Math.pow(10,Math.trunc(t));return T(Math.sign(s)*Math.round(Math.abs(s)*e+1e-9)/e)}function De(s,t=!0){let e="";for(let n=0;n<s.length;n++){const r=s[n];r==="~"&&n+1<s.length?e+=Ye(s[++n]):r==="*"?e+="[\\s\\S]*":r==="?"?e+="[\\s\\S]":e+=Ye(r)}return new RegExp(t?`^${e}$`:e,"i")}const Ye=s=>s.replace(/[.*+?^${}()|[\]\\/-]/g,"\\$&"),Rs=s=>/[*?~]/.test(s);function Ne(s){if(typeof s!="string")return r=>r!==null&&!m(r)&&L(r,s)===0;const t=/^(<=|>=|<>|=|<|>)?(.*)$/s.exec(s),e=t[1]??"=",n=et(t[2]);if(n===null)return e==="<>"?r=>r!==null&&r!=="":r=>r===null||r==="";if(typeof n=="string"&&(e==="="||e==="<>")&&Rs(n)){const r=De(n);return e==="="?i=>typeof i=="string"&&r.test(i):i=>!(typeof i=="string"&&r.test(i))}return r=>{if(m(r)||e!=="="&&e!=="<>"&&(r===null||typeof r!=typeof n)||e==="="&&r===null)return!1;const i=L(r,n);switch(e){case"=":return i===0;case"<>":return i!==0;case"<":return i<0;case"<=":return i<=0;case">":return i>0;default:return i>=0}}}function ks(s,t){let e=0,n=s.length-1,r=-1;for(;e<=n;){const i=e+n>>1,o=s[i];o===null||L(o,t)<=0?(o!==null&&typeof o==typeof t&&(r=i),e=i+1):n=i-1}return r}function Ds(s,t){const e=typeof t=="string"?Ne("="+t):void 0;return s.findIndex(n=>e?e(n):n!==null&&!m(n)&&L(n,t)===0)}function Ns(s,t){const e=k(s[0]);if(m(e))return e;const n=lt(s[1]),r=V(s[2]);if(m(r))return r;const i=s.length>3?st(k(s[3])):!0;if(m(i))return i;const o=t?n.width:n.height,l=Math.trunc(r);if(l<1)return A("#VALUE!");if(l>o)return A("#REF!");const a=t?n.values.map(h=>h[0]):n.values[0],c=i?ks(a,e):Ds(a,e);return c<0?A("#N/A"):t?n.values[c][l-1]:n.values[l-1][c]}function $e(s,t){var a;const e=lt(s[0]),n=k(s[1]);if(m(n))return n;const r=s[2]!==void 0?lt(s[2]):e,i=Ne(n),o=new Zt;let l=0;for(let c=0;c<e.height;c++)for(let h=0;h<e.width;h++){if(!i(e.values[c][h]))continue;if(t==="count"){l++;continue}const u=((a=r.values[c])==null?void 0:a[h])??null;if(m(u))return u;typeof u=="number"&&(o.add(u),l++)}return t==="count"?l:t==="sum"?T(o.value):l===0?A("#DIV/0!"):T(o.value/l)}w("SUM",{aggregate:!0,impl:s=>{const t=ct(s);return m(t)?t:T(Yt(t))}});w("AVERAGE",{minArgs:1,aggregate:!0,impl:s=>{const t=ct(s);return m(t)?t:t.length===0?A("#DIV/0!"):T(Yt(t)/t.length)}});w("MIN",{aggregate:!0,impl:s=>{const t=ct(s);return m(t)?t:t.length?Math.min(...t):0}});w("MAX",{aggregate:!0,impl:s=>{const t=ct(s);return m(t)?t:t.length?Math.max(...t):0}});w("COUNT",{aggregate:!0,impl:s=>{let t=0;for(const e of s)if(e instanceof R)for(const n of e.flat())typeof n=="number"&&t++;else e!==null&&!m(H(e))&&t++;return t}});w("COUNTA",{aggregate:!0,impl:s=>{let t=0;for(const e of s)if(e instanceof R)for(const n of e.flat())n!==null&&t++;else e!==null&&t++;return t}});w("COUNTBLANK",{minArgs:1,maxArgs:1,impl:([s])=>{let t=0;for(const e of lt(s).flat())(e===null||e==="")&&t++;return t}});w("IF",{minArgs:2,maxArgs:3,lazy:(s,t)=>{const e=t.evaluate(s[0]);if(Es(e)){const r=t.evaluate(s[1]),i=s.length>2?t.evaluate(s[2]):!1;return mt([e,r,i],(o,l,a)=>{const c=st(o);return m(c)?c:c?l:a})}const n=st(k(e));return m(n)?n:n?t.evaluate(s[1]):s.length>2?t.evaluate(s[2]):!1}});w("IFERROR",{minArgs:2,maxArgs:2,lazy:(s,t)=>{const e=t.evaluate(s[0]);return m(e)?t.evaluate(s[1]):e}});w("IFNA",{minArgs:2,maxArgs:2,lazy:(s,t)=>{const e=t.evaluate(s[0]);return m(e)&&e.code==="#N/A"?t.evaluate(s[1]):e}});function ze(s,t,e){let n=e,r=!1;for(const i of s){const o=i instanceof R?[...i.flat()].filter(l=>typeof l!="string"&&l!==null):[i];for(const l of o){const a=st(l);if(m(a))return a;n=t(n,a),r=!0}}return r?n:A("#VALUE!")}w("AND",{minArgs:1,aggregate:!0,impl:s=>ze(s,(t,e)=>t&&e,!0)});w("OR",{minArgs:1,aggregate:!0,impl:s=>ze(s,(t,e)=>t||e,!1)});w("NOT",{minArgs:1,maxArgs:1,impl:([s])=>{const t=st(k(s));return m(t)?t:!t}});w("ABS",{minArgs:1,maxArgs:1,impl:P(Math.abs)});w("INT",{minArgs:1,maxArgs:1,impl:P(Math.floor)});w("SQRT",{minArgs:1,maxArgs:1,impl:P(Math.sqrt)});w("POWER",{minArgs:2,maxArgs:2,impl:P(Math.pow)});w("PI",{maxArgs:0,impl:()=>Math.PI});w("MOD",{minArgs:2,maxArgs:2,impl:s=>{const[t,e]=s.map(V);return m(t)?t:m(e)?e:e===0?A("#DIV/0!"):T(t-e*Math.floor(t/e))}});w("ROUND",{minArgs:1,maxArgs:2,impl:P((s,t=0)=>zn(s,t))});w("ROUNDUP",{minArgs:1,maxArgs:2,impl:P((s,t=0)=>{const e=Math.pow(10,Math.trunc(t));return Math.sign(s)*Math.ceil(Math.abs(s)*e-1e-9)/e})});w("ROUNDDOWN",{minArgs:1,maxArgs:2,impl:P((s,t=0)=>{const e=Math.pow(10,Math.trunc(t));return Math.sign(s)*Math.floor(Math.abs(s)*e+1e-9)/e})});w("CONCATENATE",{minArgs:1,impl:Ut((...s)=>s.join(""))});w("CONCAT",{minArgs:1,impl:s=>{let t="";for(const e of s)for(const n of lt(e).flat()){const r=K(n);if(m(r))return r;t+=r}return t}});w("LEN",{minArgs:1,maxArgs:1,impl:Ut(s=>s.length)});w("UPPER",{minArgs:1,maxArgs:1,impl:Ut(s=>s.toUpperCase())});w("LOWER",{minArgs:1,maxArgs:1,impl:Ut(s=>s.toLowerCase())});w("TRIM",{minArgs:1,maxArgs:1,impl:Ut(s=>s.trim().replace(/ {2,}/g," "))});w("LEFT",{minArgs:1,maxArgs:2,impl:s=>{const t=K(k(s[0])),e=s.length>1?V(s[1]):1;return m(t)?t:m(e)?e:e<0?A("#VALUE!"):t.slice(0,e)}});w("RIGHT",{minArgs:1,maxArgs:2,impl:s=>{const t=K(k(s[0])),e=s.length>1?V(s[1]):1;return m(t)?t:m(e)?e:e<0?A("#VALUE!"):e===0?"":t.slice(-e)}});w("MID",{minArgs:3,maxArgs:3,impl:s=>{const t=K(k(s[0])),e=V(s[1]),n=V(s[2]);return m(t)?t:m(e)?e:m(n)?n:e<1||n<0?A("#VALUE!"):t.substr(e-1,n)}});w("ISBLANK",{minArgs:1,maxArgs:1,impl:([s])=>k(s)===null});w("ISNUMBER",{minArgs:1,maxArgs:1,impl:([s])=>typeof k(s)=="number"});w("ISTEXT",{minArgs:1,maxArgs:1,impl:([s])=>typeof k(s)=="string"});w("ISERROR",{minArgs:1,maxArgs:1,impl:([s])=>m(k(s))});w("NA",{maxArgs:0,impl:()=>A("#N/A")});w("VLOOKUP",{minArgs:3,maxArgs:4,impl:s=>Ns(s,!0)});w("HLOOKUP",{minArgs:3,maxArgs:4,impl:s=>Ns(s,!1)});w("INDEX",{minArgs:2,maxArgs:3,impl:s=>{const t=lt(s[0]),e=V(s[1]),n=s.length>2?V(s[2]):1;if(m(e))return e;if(m(n))return n;const[r,i]=t.height===1&&s.length===2?[1,e]:[e,n];return r<1||i<1||r>t.height||i>t.width?A("#REF!"):t.values[r-1][i-1]}});w("MATCH",{minArgs:2,maxArgs:3,impl:s=>{const t=k(s[0]);if(m(t))return t;const e=lt(s[1]);if(e.height>1&&e.width>1)return A("#N/A");const n=[...e.flat()],r=s.length>2?V(s[2]):1;if(m(r))return r;let i;if(r===0)i=Ds(n,t);else if(r>0)i=ks(n,t);else{i=-1;for(let o=0;o<n.length&&(n[o]!==null&&L(n[o],t)>=0);o++)i=o}return i<0?A("#N/A"):i+1}});w("SUMIF",{minArgs:2,maxArgs:3,impl:s=>$e(s,"sum")});w("COUNTIF",{minArgs:2,maxArgs:2,impl:s=>$e(s,"count")});w("AVERAGEIF",{minArgs:2,maxArgs:3,impl:s=>$e(s,"average")});w("SUMPRODUCT",{minArgs:1,impl:s=>{const t=s.map(lt),{height:e,width:n}=t[0];if(t.some(i=>i.height!==e||i.width!==n))return A("#VALUE!");const r=new Zt;for(let i=0;i<e;i++)for(let o=0;o<n;o++){let l=1;for(const a of t){const c=a.values[i][o];if(m(c))return c;l*=typeof c=="number"?c:0}r.add(l)}return T(r.value)}});const Le=864e5,$s=25569,Kt=60;function zs(s,t,e){const n=new Date(0);return n.setUTCFullYear(s,t-1,e),n}function Ls(s,t){return zs(s,t+1,0).getUTCDate()}function kt(s,t,e){if(s===1900&&t===2&&e===29)return Kt;const n=Math.round(zs(s,t,e).getTime()/Le)+$s;return n<=Kt?n-1:n}function at(s){const t=Math.floor(s);if(t===Kt)return{year:1900,month:2,day:29};const e=new Date(((t<Kt?t+1:t)-$s)*Le);return{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate()}}const Ln=/^(\d{4})-(\d{1,2})-(\d{1,2})$/,Tn=/^(\d{1,2})([./])(\d{1,2})\2(\d{4})$/;function Qt(s){const t=s.trim();let e=Ln.exec(t),n;if(e?n=[Number(e[1]),Number(e[2]),Number(e[3])]:(e=Tn.exec(t))&&(n=[Number(e[4]),Number(e[3]),Number(e[1])]),!n)return;const[r,i,o]=n;if(!(r<1900||i<1||i>12||o<1||o>Ls(r,i)))return kt(r,i,o)}const dt=(s,t=2)=>String(s).padStart(t,"0");function Te(s,t="YYYY-MM-DD"){const{year:e,month:n,day:r}=at(s),i=Math.round((s-Math.floor(s))*86400),o={YYYY:dt(e,4),YY:dt(e%100),MM:dt(n),M:String(n),DD:dt(r),D:String(r),HH:dt(Math.floor(i/3600)%24),mm:dt(Math.floor(i/60)%60),ss:dt(i%60)};return t.replace(/YYYY|YY|MM|M|DD|D|HH|mm|ss/g,l=>o[l])}function Ts(s,t=new Date){const e=kt(t.getFullYear(),t.getMonth()+1,t.getDate());if(!s)return e;const n=((t.getHours()*60+t.getMinutes())*60+t.getSeconds())*1e3+t.getMilliseconds();return e+n/Le}let Fs=()=>new Date,Is=Math.random;function Fn(s){Fs=s??(()=>new Date)}function In(s){Is=s??Math.random}const Os=()=>Fs(),Us=()=>Is();function yt(s){const t=k(s);if(typeof t=="string"){const n=Qt(t);if(n!==void 0)return n}const e=H(t);return m(e)?e:e<0?A("#NUM!","Negative date"):Math.floor(e)}function Jt(s){const t=H(k(s));return m(t)?t:Math.trunc(t)}function On(s,t){const e=[];for(const n of s){const r=t(n);if(m(r))return r;e.push(r)}return e}const Fe=s=>t=>{const e=yt(t[0]);return m(e)?e:s(at(e))};function Hs(s,t,e){const{year:n,month:r,day:i}=at(s),o=n*12+(r-1)+t,l=Math.floor(o/12),a=o-l*12+1,c=Ls(l,a),h=kt(l,a,e?c:Math.min(i,c));return h<1?A("#NUM!"):h}w("DATE",{minArgs:3,maxArgs:3,impl:s=>{const t=On(s,Jt);if(m(t))return t;let[e]=t;if(e<0||e>9999)return A("#NUM!");e<1900&&(e+=1900);const n=kt(e,t[1],t[2]);return n<0?A("#NUM!"):n}});w("YEAR",{minArgs:1,maxArgs:1,impl:Fe(s=>s.year)});w("MONTH",{minArgs:1,maxArgs:1,impl:Fe(s=>s.month)});w("DAY",{minArgs:1,maxArgs:1,impl:Fe(s=>s.day)});w("TODAY",{maxArgs:0,volatile:!0,impl:()=>Ts(!1,Os())});w("NOW",{maxArgs:0,volatile:!0,impl:()=>Ts(!0,Os())});w("WEEKDAY",{minArgs:1,maxArgs:2,impl:s=>{const t=yt(s[0]),e=s.length>1?Jt(s[1]):1;if(m(t))return t;if(m(e))return e;const n=((t-1)%7+7)%7;switch(e){case 1:return n+1;case 2:return(n+6)%7+1;case 3:return(n+6)%7;default:return A("#NUM!")}}});w("EDATE",{minArgs:2,maxArgs:2,impl:s=>{const t=yt(s[0]),e=Jt(s[1]);return m(t)?t:m(e)?e:Hs(t,e,!1)}});w("EOMONTH",{minArgs:2,maxArgs:2,impl:s=>{const t=yt(s[0]),e=Jt(s[1]);return m(t)?t:m(e)?e:Hs(t,e,!0)}});w("DAYS",{minArgs:2,maxArgs:2,impl:s=>{const[t,e]=s.map(yt);return m(t)?t:m(e)?e:t-e}});w("DATEDIF",{minArgs:3,maxArgs:3,impl:s=>{const t=yt(s[0]),e=yt(s[1]),n=K(k(s[2]));if(m(t))return t;if(m(e))return e;if(m(n))return n;if(t>e)return A("#NUM!","Start date is after end date");const r=at(t),i=at(e),o=(i.year-r.year)*12+(i.month-r.month)-(i.day<r.day?1:0);switch(n.toUpperCase()){case"D":return e-t;case"M":return o;case"Y":return Math.floor(o/12);case"YM":return o%12;default:return A("#NUM!",`Unknown DATEDIF unit "${n}"`)}}});const nt=(s,t)=>T(s/t);w("CEILING",{minArgs:1,maxArgs:2,impl:P((s,t=1)=>t===0?0:s>0&&t<0?A("#NUM!"):t<0?-Math.ceil(nt(-s,-t))*-t:Math.ceil(nt(s,t))*t)});w("FLOOR",{minArgs:1,maxArgs:2,impl:P((s,t=1)=>t===0?s===0?0:A("#DIV/0!"):s>0&&t<0?A("#NUM!"):t<0?-Math.floor(nt(-s,-t))*-t:Math.floor(nt(s,t))*t)});w("CEILING.MATH",{minArgs:1,maxArgs:3,impl:P((s,t=1,e=0)=>{const n=Math.abs(t);return n===0?0:s<0&&e!==0?-Math.ceil(nt(-s,n))*n:Math.ceil(nt(s,n))*n})});w("FLOOR.MATH",{minArgs:1,maxArgs:3,impl:P((s,t=1,e=0)=>{const n=Math.abs(t);return n===0?0:s<0&&e!==0?-Math.floor(nt(-s,n))*n:Math.floor(nt(s,n))*n})});w("MROUND",{minArgs:2,maxArgs:2,impl:P((s,t)=>{if(t===0)return 0;if(s*t<0)return A("#NUM!");const e=nt(s,t);return Math.sign(e)*Math.round(Math.abs(e))*t})});w("TRUNC",{minArgs:1,maxArgs:2,impl:P((s,t=0)=>{const e=Math.pow(10,Math.trunc(t));return Math.trunc(T(s*e))/e})});w("SIGN",{minArgs:1,maxArgs:1,impl:P(s=>Math.sign(s))});w("PRODUCT",{minArgs:1,aggregate:!0,impl:s=>{const t=ct(s);if(m(t))return t;if(t.length===0)return 0;const e=t.reduce((n,r)=>n*r,1);return Number.isFinite(e)?T(e):A("#NUM!")}});w("RAND",{maxArgs:0,volatile:!0,impl:()=>Us()});w("RANDBETWEEN",{minArgs:2,maxArgs:2,volatile:!0,impl:P((s,t)=>{const e=Math.ceil(s),n=Math.floor(t);return e>n?A("#NUM!"):e+Math.floor(Us()*(n-e+1))})});function it(s,t){return{minArgs:s,aggregate:!0,impl:e=>{const n=ct(e);if(m(n))return n;const r=t(n);return m(r)?r:Number.isFinite(r)?T(r):A("#NUM!")}}}function Un(s){if(s.length===0)return A("#NUM!");const t=[...s].sort((n,r)=>n-r),e=t.length>>1;return t.length%2?t[e]:(t[e-1]+t[e])/2}function _s(s){const t=new Map;for(const r of s)t.set(r,(t.get(r)??0)+1);let e,n=1;for(const[r,i]of t)i>n&&(e=r,n=i);return e===void 0?A("#N/A"):e}function Dt(s,t){const e=s.length;if(e<(t?2:1))return A("#DIV/0!");const n=Yt(s)/e;return Yt(s.map(r=>(r-n)*(r-n)))/(t?e-1:e)}const Ie=s=>m(s)?s:Math.sqrt(s);w("MEDIAN",it(1,Un));w("MODE.SNGL",it(1,_s));w("MODE",it(1,_s));w("VAR.S",it(1,s=>Dt(s,!0)));w("VAR",it(1,s=>Dt(s,!0)));w("VAR.P",it(1,s=>Dt(s,!1)));w("STDEV.S",it(1,s=>Ie(Dt(s,!0))));w("STDEV",it(1,s=>Ie(Dt(s,!0))));w("STDEV.P",it(1,s=>Ie(Dt(s,!1))));function Ps(s,t){const e=ct([s[0]]);if(m(e))return e;const n=V(s[1]);if(m(n))return n;const r=Math.ceil(n);return r<1||r>e.length?A("#NUM!"):[...e].sort((o,l)=>t?l-o:o-l)[r-1]}w("LARGE",{minArgs:2,maxArgs:2,aggregate:!0,impl:s=>Ps(s,!0)});w("SMALL",{minArgs:2,maxArgs:2,aggregate:!0,impl:s=>Ps(s,!1)});function Vs(s){const t=H(k(s[0]));if(m(t))return t;const e=ct([s[1]]);if(m(e))return e;const n=s.length>2?V(s[2]):0;return m(n)?n:e.includes(t)?1+e.filter(r=>n===0?r>t:r<t).length:A("#N/A")}w("RANK.EQ",{minArgs:2,maxArgs:3,aggregate:!0,impl:Vs});w("RANK",{minArgs:2,maxArgs:3,aggregate:!0,impl:Vs});function Hn(s,t){const e=Xs(t);let n=e[0],r=s<0;s<0&&e.length>1&&e[1]!==""?(n=e[1],r=!1):s===0&&e.length>2&&e[2]!==""&&(n=e[2]);const i=Oe(n);if(i.some(a=>a.kind==="date"))return Bn(s<0&&!r?-s:s,i);const o=Math.abs(s);if(i.length===0||/^general$/i.test(n.trim()))return(r?"-":"")+ke(o);const l=Xn(o,i);return r&&/[1-9]/.test(l)?"-"+l:l}function _n(s,t){const e=Xs(t),n=e.length>3?e[3]:e.length===1&&Pn(e[0])?e[0]:void 0;if(n!==void 0)return Oe(n).map(r=>r.kind==="lit"?r.text:r.kind==="ph"&&r.ch==="@"?s:"").join("")}const Pn=s=>Oe(s).some(t=>t.kind==="ph"&&t.ch==="@");function Xs(s){const t=[];let e="";for(let n=0;n<s.length;n++){const r=s[n];if(r==='"'){const i=s.indexOf('"',n+1),o=i<0?s.length:i;e+=s.slice(n,o+1),n=o}else r==="\\"&&n+1<s.length?e+=r+s[++n]:r===";"?(t.push(e),e=""):e+=r}return t.push(e),t}const Vn=/^(am\/pm|a\/p|y+|m+|d+|h+|s+)/i;function Oe(s){const t=[];for(let e=0;e<s.length;e++){const n=s[e],r=s.slice(e);if(n==='"'){const i=s.indexOf('"',e+1),o=i<0?s.length:i;t.push({kind:"lit",text:s.slice(e+1,o)}),e=o}else if(n==="\\")e+1<s.length&&t.push({kind:"lit",text:s[++e]});else if(n==="_")e++,t.push({kind:"lit",text:" "});else if(n==="*")e++;else if(n==="["){const i=s.indexOf("]",e);e=i<0?s.length:i}else if("0#?.,%@".includes(n))t.push({kind:"ph",ch:n});else if((n==="E"||n==="e")&&/^[eE][+-]0/.test(r))t.push({kind:"ph",ch:"E"+r[1]}),e++;else{const i=Vn.exec(r);i?(t.push({kind:"date",text:i[0]}),e+=i[0].length-1):t.push({kind:"lit",text:n})}}return t}const Ke=s=>s.kind==="ph"&&(s.ch==="0"||s.ch==="#"||s.ch==="?");function Xn(s,t){var S;const e=t.findIndex(Ke);if(e<0)return t.map(x=>x.kind==="lit"?x.text:x.kind==="ph"&&x.ch==="%"?"%":"").join("");let n=t.length-1;for(;!Ke(t[n]);)n--;for(;n+1<t.length&&t[n+1].kind==="ph"&&",.".includes(t[n+1].ch);)n++;let r=s;for(const x of t)x.kind==="ph"&&x.ch==="%"&&(r*=100);const i=t.slice(e,n+1).filter(x=>x.kind==="ph"),o=i.findIndex(x=>x.ch.startsWith("E")),l=o<0?i:i.slice(0,o),a=l.findIndex(x=>x.ch==="."),c=(a<0?l:l.slice(0,a)).map(x=>x.ch).join(""),h=a<0?"":l.slice(a+1).map(x=>x.ch).join("").replace(/[^0#?]/g,""),u=c.replace(/[^0#?]/g,""),d=/[0#?],+[0#?]/.test(c);r/=Math.pow(1e3,((S=/,+$/.exec(c))==null?void 0:S[0].length)??0);let f;if(o>=0){const x=i.slice(o),g=Math.max(x.slice(1).filter(z=>z.ch==="0").length,1),p=x[0].ch[1];let b=r===0?0:Math.floor(Math.log10(r))-Math.max(u.length-1,0),C=r/Math.pow(10,b);const M=re(C,u,h,!1,a>=0);Number(M.replace(/,/g,""))>=Math.pow(10,Math.max(u.length,1))&&(b++,C=r/Math.pow(10,b));const E=String(Math.abs(b)).padStart(g,"0");f=re(C,u,h,!1,a>=0)+"E"+(b<0?"-":p==="+"?"+":"")+E}else f=re(r,u,h,d,a>=0);const y=x=>x.kind==="lit"?x.text:x.kind==="ph"&&",.%".includes(x.ch)?x.ch:"";return t.slice(0,e).map(y).join("")+f+t.slice(n+1).map(y).join("")}function re(s,t,e,n,r){const i=e.length,o=e.lastIndexOf("0")+1,l=(t.match(/0/g)??[]).length,a=Math.pow(10,i),c=T(Math.round(s*a+1e-9*Math.sign(s))/a);let[h,u=""]=c.toFixed(i).split(".");for(;u.length>o&&u.endsWith("0");)u=u.slice(0,-1);return h==="0"&&l===0&&(h=""),h=h.padStart(l,"0"),n&&(h=h.replace(/\B(?=(\d{3})+(?!\d))/g,",")),h+(r?"."+u:"")}const ie=["January","February","March","April","May","June","July","August","September","October","November","December"],qe=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],vt=s=>String(s).padStart(2,"0");function Bn(s,t){if(s<0)return;const e=Math.round(s*86400),n=Math.floor(e/86400),r=e-n*86400,{year:i,month:o,day:l}=at(n),a=Math.floor(r/3600),c=Math.floor(r/60)%60,h=r%60,u=t.some(y=>y.kind==="date"&&/^a/i.test(y.text)),d=((n-1)%7+7)%7,f=(y,S)=>{for(let x=y+S;x>=0&&x<t.length;x+=S){const g=t[x];if(g.kind==="date")return g.text[0].toLowerCase()}};return t.map((y,S)=>{if(y.kind==="lit")return y.text;if(y.kind==="ph")return y.ch==="@"?"":y.ch;const x=y.text,g=x.toLowerCase(),p=x.length;switch(g[0]){case"y":return p<=2?vt(i%100):String(i).padStart(4,"0");case"m":return p<=2&&(f(S,-1)==="h"||f(S,1)==="s")?p===2?vt(c):String(c):p===1?String(o):p===2?vt(o):p===3?ie[o-1].slice(0,3):p===5?ie[o-1][0]:ie[o-1];case"d":return p===1?String(l):p===2?vt(l):p===3?qe[d].slice(0,3):qe[d];case"h":{const b=u?(a+11)%12+1:a;return p>=2?vt(b):String(b)}case"s":return p>=2?vt(h):String(h);default:{const b=a>=12;if(g==="a/p")return b?x[2]==="P"?"P":"p":x[0];const C=x.slice(0,2),M=x.slice(3,5);return b?M:C}}}).join("")}const Bs=32767;function ht(s){return t=>mt(t,(...e)=>e.find(m)??s(...e))}function X(s){return K(s)}function It(s){const t=H(s);return m(t)?t:Math.trunc(t)}function Ws(s){const t=s.trim(),e=wt(t);if(e!==void 0)return e;if(/^[+-]?\d{1,3}(,\d{3})+(\.\d*)?%?$/.test(t))return wt(t.replace(/,/g,""));const n=Qt(t);if(n!==void 0)return n;const r=/^(\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(t);if(r&&Number(r[2])<60&&Number(r[3]??0)<60)return(Number(r[1])*3600+Number(r[2])*60+Number(r[3]??0))/86400}w("TEXT",{minArgs:2,maxArgs:2,impl:ht((s,t)=>{const e=X(t);if(m(e))return e;if(typeof s=="boolean")return s?"TRUE":"FALSE";let n;if(typeof s=="string"){const r=Ws(s);if(r===void 0)return _n(s,e)??s;n=r}else n=s??0;return Hn(n,e)??A("#VALUE!","Value cannot be formatted as a date")})});w("VALUE",{minArgs:1,maxArgs:1,impl:ht(s=>typeof s=="number"?s:s===null?0:typeof s=="boolean"?A("#VALUE!"):Ws(s)??A("#VALUE!",`"${s}" is not a number`))});function js(s){return ht((t,e,n=1)=>{const r=X(t),i=X(e),o=It(n);if(m(r))return r;if(m(i))return i;if(m(o))return o;if(o<1||o>Math.max(i.length,1))return A("#VALUE!");let l;if(s)l=i.indexOf(r,o-1);else if(Rs(r)){const a=De(r,!1).exec(i.slice(o-1));l=a?a.index+o-1:-1}else l=i.toLowerCase().indexOf(r.toLowerCase(),o-1);return l<0?A("#VALUE!","Text not found"):l+1})}w("FIND",{minArgs:2,maxArgs:3,impl:js(!0)});w("SEARCH",{minArgs:2,maxArgs:3,impl:js(!1)});w("SUBSTITUTE",{minArgs:3,maxArgs:4,impl:ht((s,t,e,n)=>{const r=X(s),i=X(t),o=X(e);if(m(r))return r;if(m(i))return i;if(m(o))return o;if(i==="")return r;if(n===void 0)return r.split(i).join(o);const l=It(n);if(m(l))return l;if(l<1)return A("#VALUE!");let a=-1;for(let c=0;c<l;c++)if(a=r.indexOf(i,a+(c===0?0:i.length)),a<0)return r;return r.slice(0,a)+o+r.slice(a+i.length)})});w("REPLACE",{minArgs:4,maxArgs:4,impl:ht((s,t,e,n)=>{const r=X(s),i=It(t),o=It(e),l=X(n);return m(r)?r:m(i)?i:m(o)?o:m(l)?l:i<1||o<0?A("#VALUE!"):r.slice(0,i-1)+l+r.slice(i-1+o)})});w("REPT",{minArgs:2,maxArgs:2,impl:ht((s,t)=>{const e=X(s),n=It(t);return m(e)?e:m(n)?n:n<0||e.length*n>Bs?A("#VALUE!"):e.repeat(n)})});w("PROPER",{minArgs:1,maxArgs:1,impl:ht(s=>{const t=X(s);if(m(t))return t;let e="",n=!1;for(const r of t){const i=new RegExp("\\p{L}","u").test(r);e+=i?n?r.toLowerCase():r.toUpperCase():r,n=i}return e})});w("EXACT",{minArgs:2,maxArgs:2,impl:ht((s,t)=>{const e=X(s),n=X(t);return m(e)?e:m(n)?n:e===n})});w("TEXTJOIN",{minArgs:3,impl:s=>{const t=[];for(const i of B(s[0]).flat()){const o=K(i);if(m(o))return o;t.push(o)}const e=st(k(s[1]));if(m(e))return e;const n=[];for(const i of s.slice(2))for(const o of B(i).flat()){if(m(o))return o;const l=K(o);e&&l===""||n.push(l)}let r=n[0]??"";for(let i=1;i<n.length;i++)r+=(t.length?t[(i-1)%t.length]:"")+n[i];return r.length>Bs?A("#VALUE!"):r}});function Ht(s,t){const e=t!=="count",n=s.slice(e?1:0);if(n.length===0||n.length%2)return A("#VALUE!","Criteria come in range/criterion pairs");const r=[];for(let u=0;u<n.length;u+=2){const d=k(n[u+1]);if(m(d))return d;r.push({range:B(n[u]),test:Ne(d)})}const i=e?B(s[0]):r[0].range,{height:o,width:l}=i;if(r.some(u=>u.range.height!==o||u.range.width!==l))return A("#VALUE!","Criteria ranges must have the same size");const a=new Zt;let c=0,h;for(let u=0;u<o;u++)for(let d=0;d<l;d++){if(!r.every(y=>y.test(y.range.values[u][d])))continue;if(!e){c++;continue}const f=i.values[u][d];if(m(f))return f;typeof f=="number"&&(a.add(f),c++,(h===void 0||(t==="max"?f>h:f<h))&&(h=f))}switch(t){case"count":return c;case"sum":return T(a.value);case"average":return c===0?A("#DIV/0!"):T(a.value/c);default:return h??0}}w("SUMIFS",{minArgs:3,impl:s=>Ht(s,"sum")});w("COUNTIFS",{minArgs:2,impl:s=>Ht(s,"count")});w("AVERAGEIFS",{minArgs:3,impl:s=>Ht(s,"average")});w("MAXIFS",{minArgs:3,impl:s=>Ht(s,"max")});w("MINIFS",{minArgs:3,impl:s=>Ht(s,"min")});w("ISNA",{minArgs:1,maxArgs:1,impl:([s])=>{const t=k(s);return m(t)&&t.code==="#N/A"}});w("ISLOGICAL",{minArgs:1,maxArgs:1,impl:([s])=>typeof k(s)=="boolean"});w("XOR",{minArgs:1,aggregate:!0,impl:s=>ze(s,(t,e)=>t!==e,!1)});w("IFS",{minArgs:2,lazy:(s,t)=>{if(s.length%2)return A("#VALUE!","IFS needs test/value pairs");for(let e=0;e<s.length;e+=2){const n=st(k(t.evaluate(s[e])));if(m(n))return n;if(n)return t.evaluate(s[e+1])}return A("#N/A","No test was true")}});function Wn(s,t){return s!==null&&t!==null&&typeof s!=typeof t?!1:L(s,t)===0}w("SWITCH",{minArgs:3,lazy:(s,t)=>{const e=k(t.evaluate(s[0]));if(m(e))return e;const n=Math.floor((s.length-1)/2);for(let r=0;r<n;r++){const i=1+2*r,o=k(t.evaluate(s[i]));if(m(o))return o;if(Wn(e,o))return t.evaluate(s[i+1])}return s.length%2===0?t.evaluate(s[s.length-1]):A("#N/A","No case matched")}});const jn=(s,t)=>s!==null&&!m(s)&&typeof s==typeof t;function Yn(s,t,e,n){const r=s.map((l,a)=>a);n<0&&r.reverse();const i=e===2&&typeof t=="string"?De(t):void 0;let o=-1;for(const l of r){const a=s[l];if(jn(a,t)){if(i?i.test(a):L(a,t)===0)return l;e===-1&&L(a,t)<0&&(o<0||L(a,s[o])>0)&&(o=l),e===1&&L(a,t)>0&&(o<0||L(a,s[o])<0)&&(o=l)}}return o}w("XLOOKUP",{minArgs:3,maxArgs:6,impl:s=>{const t=k(s[0]);if(m(t))return t;const e=B(s[1]),n=B(s[2]);if(e.width!==1&&e.height!==1)return A("#VALUE!","Lookup array must be one row or column");const r=e.width===1&&(e.height>1||n.height===1),i=r?e.height:e.width;if((r?n.height:n.width)!==i)return A("#VALUE!","Arrays must have the same length");const o=s.length>3&&s[3]!==null?s[3]:void 0,l=s.length>4&&s[4]!==null?V(s[4]):0,a=s.length>5&&s[5]!==null?V(s[5]):1;if(m(l))return l;if(m(a))return a;if(![0,-1,1,2].includes(l)||![1,-1,2,-2].includes(a))return A("#VALUE!");const c=r?Ms(e,0):e.values[0],h=Yn(c,t,l,a);return h<0?o??A("#N/A"):r?n.width===1?n.values[h][0]:new R([n.values[h]]):n.height===1?n.values[0][h]:new R(n.values.map(u=>[u[h]]))}});w("CHOOSE",{minArgs:2,lazy:(s,t)=>{const e=H(k(t.evaluate(s[0])));if(m(e))return e;const n=Math.trunc(e);return n<1||n>=s.length?A("#VALUE!","CHOOSE index out of range"):t.evaluate(s[n])}});w("ROW",{maxArgs:1,positional:!0,lazy:(s,t)=>{if(s.length===0)return t.row+1;const e=t.reference(s[0]);return e?e.height===1?e.row+1:new R(Array.from({length:e.height},(n,r)=>[e.row+r+1])):Ys(t.evaluate(s[0]))}});w("COLUMN",{maxArgs:1,positional:!0,lazy:(s,t)=>{if(s.length===0)return t.col+1;const e=t.reference(s[0]);return e?e.width===1?e.col+1:new R([Array.from({length:e.width},(n,r)=>e.col+r+1)]):Ys(t.evaluate(s[0]))}});const Ys=s=>m(s)?s:A("#VALUE!","Argument must be a reference");function Ks(s){return{minArgs:1,maxArgs:1,lazy:(t,e)=>{const n=e.reference(t[0]);if(n)return s(n);const r=e.evaluate(t[0]);return m(r)?r:s(r instanceof R?r:{height:1,width:1})}}}w("ROWS",Ks(s=>s.height));w("COLUMNS",Ks(s=>s.width));const Ue=()=>A("#CALC!","The result is an empty array");function Ot(s,t,e){if(s.length<=t||s[t]===null)return e;const n=H(k(s[t]));return m(n)?n:Math.trunc(n)}function ye(s,t){return s.length<=t||s[t]===null?!1:st(k(s[t]))}function te(s,t){return t?{rows:ge(s).values,rebuild:e=>ge(new R(e))}:{rows:s.values,rebuild:e=>new R(e)}}function Kn(s,t){const e=s??0,n=t??0,r=m(e),i=m(n);return r||i?r&&i?0:r?1:-1:L(e,n)}w("FILTER",{minArgs:2,maxArgs:3,impl:s=>{const t=B(s[0]),e=B(s[1]);let n;if(e.width===1&&e.height===t.height)n=!1;else if(e.height===1&&e.width===t.width)n=!0;else return A("#VALUE!","FILTER include must match the array height or width");const r=[...e.flat()],{rows:i,rebuild:o}=te(t,n),l=[];for(let a=0;a<i.length;a++){const c=r[a];if(typeof c=="string")return A("#VALUE!");const h=st(c);if(m(h))return h;h&&l.push(i[a])}return l.length===0?s.length>2?s[2]:Ue():o(l)}});function qs(s){return m(s)||s===1||s===-1?s:A("#VALUE!","Sort order must be 1 or -1")}function Gs(s,t){const e=s.map((n,r)=>r);return e.sort((n,r)=>{for(const i of t){const o=Kn(i.values[n],i.values[r]);if(o!==0)return o*i.order}return n-r}),e.map(n=>s[n])}w("SORT",{minArgs:1,maxArgs:4,impl:s=>{var l;const t=B(s[0]),e=Ot(s,1,1),n=qs(Ot(s,2,1)),r=ye(s,3);if(m(e))return e;if(m(n))return n;if(m(r))return r;const{rows:i,rebuild:o}=te(t,r);return e<1||e>(((l=i[0])==null?void 0:l.length)??0)?A("#VALUE!","Sort index out of range"):o(Gs(i,[{values:i.map(a=>a[e-1]),order:n}]))}});w("SORTBY",{minArgs:2,impl:s=>{const t=B(s[0]);let e;const n=[];for(let o=1;o<s.length;o+=2){const l=B(s[o]),a=l.height===1&&l.width===t.width&&!(l.width===1&&l.height===t.height);if(!(a||l.width===1&&l.height===t.height)||e!==void 0&&e!==a)return A("#VALUE!","SORTBY arrays must match the array");e=a;const h=qs(Ot(s,o+1,1));if(m(h))return h;n.push({values:[...l.flat()],order:h})}const{rows:r,rebuild:i}=te(t,e??!1);return i(Gs(r,n))}});function qn(s){return s===null?"n:0":m(s)?"e:"+s.code:typeof s=="string"?"s:"+s.toLowerCase():(typeof s=="number"?"n:":"b:")+String(s)}w("UNIQUE",{minArgs:1,maxArgs:3,impl:s=>{const t=ye(s,1),e=ye(s,2);if(m(t))return t;if(m(e))return e;const{rows:n,rebuild:r}=te(B(s[0]),t),i=new Map;for(const l of n){const a=l.map(qn).join("\0"),c=i.get(a);c?c.count++:i.set(a,{row:l,count:1})}const o=[...i.values()].filter(l=>!e||l.count===1).map(l=>l.row);return o.length?r(o):Ue()}});w("SEQUENCE",{minArgs:1,maxArgs:4,impl:s=>{const t=Ot(s,0,1),e=Ot(s,1,1);if(m(t))return t;if(m(e))return e;const n=s.length>2&&s[2]!==null?H(k(s[2])):1,r=s.length>3&&s[3]!==null?H(k(s[3])):1;return m(n)?n:m(r)?r:t<0||e<0||t>1048576||e>16384?A("#VALUE!"):t===0||e===0?Ue():t*e>1048576?A("#NUM!","SEQUENCE is too large"):new R(Array.from({length:t},(i,o)=>Array.from({length:e},(l,a)=>T(n+r*(o*e+a)))))}});w("TRANSPOSE",{minArgs:1,maxArgs:1,impl:([s])=>s instanceof R?ge(s):s});function ve(s,t,e,n,r,i){const o=[];for(let l=e;l<=r;l++){const a=[];for(let c=n;c<=i;c++)a.push(s.getCellValue(t,l,c));o.push(a)}return new R(o,{sheet:t,row:e,col:n})}const Ge=(s,t)=>t.getCellValue(s.sheet??t.sheet,s.rowAbs?s.row:s.row+t.row,s.colAbs?s.col:s.col+t.col);function Y(s,t){switch(s.type){case"number":return s.value;case"string":return s.value;case"bool":return s.value;case"error":return A(s.code);case"ref":return Ge(s,t);case"range":{const{start:e,end:n}=s,r=e.sheet??t.sheet,i=e.rowAbs?e.row:e.row+t.row,o=n.rowAbs?n.row:n.row+t.row,l=e.colAbs?e.col:e.col+t.col,a=n.colAbs?n.col:n.col+t.col,[c,h,u,d]=[Math.min(i,o),Math.max(i,o),Math.min(l,a),Math.max(l,a)];return t.getRange?t.getRange(r,c,u,h,d):ve(t,r,c,u,h,d)}case"name":return s.name===""?null:t.resolveName?t.resolveName(s.name):A("#NAME?",`Unknown name "${s.name}"`);case"paren":return Y(s.expr,t);case"unary":{const e=Y(s.arg,t);return e instanceof R?mt([e],n=>Ze(s.op,n)):Ze(s.op,e)}case"percent":{const e=Y(s.arg,t);return e instanceof R?mt([e],Qe):Qe(e)}case"binary":{const e=Y(s.left,t),n=Y(s.right,t);if(!(e instanceof R)&&!(n instanceof R))return Je(s.op,e,n);const r=s.op;return mt([e,n],(i,o)=>Je(r,i,o))}case"call":{const e=we(s.name);if(!e)return A("#NAME?",`Unknown function ${s.name}`);const n={evaluate:i=>Y(i,t),sheet:t.sheet,row:t.row,col:t.col,reference:i=>Zs(i,t)};if(e.lazy)return e.lazy(s.args,n);const r=s.args.map(i=>e.aggregate&&i.type==="ref"?new R([[Ge(i,t)]]):Y(i,t));return e.impl(r,n)}}}function Zs(s,t){if(s.type==="paren")return Zs(s.expr,t);if(s.type==="ref"){const e=s.rowAbs?s.row:s.row+t.row,n=s.colAbs?s.col:s.col+t.col;return{sheet:s.sheet??t.sheet,row:e,col:n,height:1,width:1}}if(s.type==="range"||s.type==="name"){const e=Y(s,t);if(e instanceof R&&e.origin)return{...e.origin,height:e.height,width:e.width}}}function Ze(s,t){const e=H(t);return m(e)||s==="+"?e:-e}function Qe(s){const t=H(s);return m(t)?t:t/100}function Je(s,t,e){if(m(t))return t;if(m(e))return e;switch(s){case"&":{const o=K(t),l=K(e);return m(o)?o:m(l)?l:o+l}case"=":return L(t,e)===0;case"<>":return L(t,e)!==0;case"<":return L(t,e)<0;case"<=":return L(t,e)<=0;case">":return L(t,e)>0;case">=":return L(t,e)>=0}const n=H(t),r=H(e);if(m(n))return n;if(m(r))return r;let i;switch(s){case"+":i=n+r;break;case"-":i=n-r;break;case"*":i=n*r;break;case"/":if(r===0)return A("#DIV/0!");i=n/r;break;case"^":if(n===0&&r===0)return A("#NUM!");i=Math.pow(n,r);break;default:return A("#ERROR!",`Unknown operator ${s}`)}return Number.isFinite(i)?T(i):A("#NUM!")}class I extends Error{constructor(t,e){super(t),this.pos=e}}const Gn=/(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/y,Zn=/[\p{L}_][\p{L}\p{N}_.]*/uy,Qn=/([\p{L}_][\p{L}\p{N}_.]*)!/uy,Jn=/[\p{L}_]/u,ts=/(\$?)([A-Za-z]{1,3})(\$?)(\d+)/y,tr=["<=",">=","<>"],er="+-*/^&=<>%(),;:";function sr(s){const t=[];let e=0;const n=i=>(i.lastIndex=e,i.exec(s));for(;e<s.length;){const i=s[e];if(i===" "||i===" "||i===`
2
+ `||i==="\r"){e++;continue}if(i>="0"&&i<="9"||i==="."&&/\d/.test(s[e+1]??"")){const l=n(Gn);t.push({type:"number",value:Number(l[0]),pos:e}),e+=l[0].length;continue}if(i==='"'){const l=e;let a="";for(e++;;){if(e>=s.length)throw new I("Unterminated string",l);if(s[e]==='"'){if(s[e+1]==='"'){a+='"',e+=2;continue}e++;break}a+=s[e++]}t.push({type:"string",value:a,pos:l});continue}if(i==="#"){const l=Mn.find(a=>s.startsWith(a,e)||s.toUpperCase().startsWith(a,e));if(!l)throw new I("Unknown error literal",e);t.push({type:"error",value:l,pos:e}),e+=l.length;continue}if(i==="'"){const l=e;let a="";for(e++;;){if(e>=s.length)throw new I("Unterminated sheet name",l);if(s[e]==="'"){if(s[e+1]==="'"){a+="'",e+=2;continue}e++;break}a+=s[e++]}if(s[e]!=="!")throw new I('Expected "!" after sheet name',e);e=r(a,l,e+1);continue}if(i==="$"||Jn.test(i)){const l=i==="$"?null:n(Qn);if(l){e=r(l[1],e,e+l[0].length);continue}const a=es(s,e),c=i==="$"?null:n(Zn);if(c&&nr(s,e+c[0].length)==="("){t.push({type:"func",value:c[0].toUpperCase(),pos:e}),e+=c[0].length;continue}if(a&&(!c||a.length>=c[0].length)){t.push({...a.token,pos:e}),e+=a.length;continue}if(!c)throw new I("Invalid reference",e);const h=c[0].toUpperCase();h==="TRUE"||h==="FALSE"?t.push({type:"bool",value:h==="TRUE",pos:e}):t.push({type:"name",value:c[0],pos:e}),e+=c[0].length;continue}const o=s.slice(e,e+2);if(tr.includes(o)){t.push({type:"op",value:o,pos:e}),e+=2;continue}if(er.includes(i)){t.push({type:"op",value:i===";"?",":i,pos:e}),e++;continue}throw new I(`Unexpected character "${i}"`,e)}return t.push({type:"eof",pos:s.length}),t;function r(i,o,l){const a=es(s,l);if(!a)throw new I('Expected cell reference after "!"',l);return t.push({...a.token,sheet:i,pos:o}),l+a.length}}function nr(s,t){for(;t<s.length&&s[t]===" ";)t++;return s[t]}function es(s,t){ts.lastIndex=t;const e=ts.exec(s);if(!e||/[\p{L}\p{N}_]/u.test(s[t+e[0].length]??""))return;const n=Me(e[2]),r=Number(e[4])-1;if(!(n<0||n>=16384||r<0||r>=1048576))return{length:e[0].length,token:{type:"ref",row:r,col:n,colAbs:e[1]==="$",rowAbs:e[3]==="$"}}}const rr={"=":1,"<>":1,"<":1,"<=":1,">":1,">=":1,"&":2,"+":3,"-":3,"*":4,"/":4,"^":5};function xe(s,t={}){var x,g;const e=sr(s),n=((x=t.base)==null?void 0:x.row)??0,r=((g=t.base)==null?void 0:g.col)??0;let i=0;const o=(p,b)=>({type:"ref",row:p.rowAbs?p.row:p.row-n,col:p.colAbs?p.col:p.col-r,rowAbs:p.rowAbs,colAbs:p.colAbs,...b===void 0?{}:{sheet:b}}),l=()=>e[i],a=()=>e[i++],c=(p,b)=>p.type==="op"&&p.value===b,h=p=>{const b=a();if(!c(b,p))throw new I(`Expected "${p}"`,b.pos)};function u(p){let b=d();for(;;){const C=l();if(C.type!=="op")break;const M=rr[C.value];if(M===void 0||M<p)break;a();const E=u(M+1);b={type:"binary",op:C.value,left:b,right:E}}return b}function d(){const p=l();if(c(p,"-")||c(p,"+"))return a(),{type:"unary",op:c(p,"-")?"-":"+",arg:d()};let b=f();for(;c(l(),"%");)a(),b={type:"percent",arg:b};return b}function f(){var b,C;const p=a();switch(p.type){case"number":return{type:"number",value:p.value};case"string":return{type:"string",value:p.value};case"bool":return{type:"bool",value:p.value};case"error":return{type:"error",code:p.value};case"name":return{type:"name",name:p.value};case"ref":{const M=p.sheet===void 0||(b=t.resolveSheet)==null?void 0:b.call(t,p.sheet),E=p.sheet!==void 0&&M===void 0,z=o(p,M);if(!c(l(),":"))return E?{type:"error",code:"#REF!"}:z;a();const D=a();if(D.type!=="ref")throw new I('Expected cell reference after ":"',D.pos);if(D.sheet!==void 0&&D.sheet.toUpperCase()!==((C=p.sheet)==null?void 0:C.toUpperCase()))throw new I("A range cannot span sheets",D.pos);return E?{type:"error",code:"#REF!"}:{type:"range",start:z,end:o(D,M)}}case"func":{h("(");const M=[];if(!c(l(),")"))for(;c(l(),",")||c(l(),")")?M.push({type:"name",name:""}):M.push(u(1)),!!c(l(),",");)a();return h(")"),{type:"call",name:p.value,args:M}}case"op":if(p.value==="("){const M=u(1);return h(")"),{type:"paren",expr:M}}throw new I(`Unexpected "${p.value}"`,p.pos);case"eof":throw new I("Unexpected end of formula",p.pos)}}const y=u(1),S=l();if(S.type!=="eof")throw new I("Unexpected token",S.pos);return y}const qt=-1;class ir{constructor(t){v(this,"sheet");v(this,"axis");this.ch=t,this.sheet=t.sheet,this.axis=t.axis}index(t){return be(this.ch,t)}span(t,e){return lr(this.ch,t,e)}}class or{constructor(t,e,n,r,i){this.sheet=t,this.axis=e,this.start=n,this.count=r,this.target=i}index(t){const{start:e,count:n,target:r}=this,i=e+n;return r>i?t<e||t>=r?t:t<i?t+r-i:t-n:t<r||t>=i?t:t>=e?t-(e-r):t+n}span(t,e){const n=this.index(t),r=this.index(e);return n<=r?[n,r]:[r,n]}}function Qs(s,t,e){return e>s+t?{start:e-t,count:t,target:s}:e<s?{start:e,count:t,target:s+t}:{start:s,count:t,target:e}}function Js(s,t,e,n){return n[0]-t!==n[1]-e||t!==e&&n[0]!==s.index(t)}function be(s,t){return t<s.index?t:s.remove?t<s.index+s.count?qt:t-s.count:t+s.count}function lr(s,t,e){if(!s.remove)return[be(s,t),be(s,e)];const n=s.index+s.count;if(!(t>=s.index&&e<n))return[t<s.index?t:t<n?s.index:t-s.count,e<s.index?e:e<n?s.index-1:e-s.count]}const Ae=()=>({type:"error",code:"#REF!"});class ar{constructor(t){v(this,"text",!1);v(this,"meaning",!1);v(this,"homeSheet",0);v(this,"homeBefore",0);v(this,"homeAfter",0);v(this,"isRow");this.map=t,this.isRow=t.axis==="row"}adjust(t,e,n,r){return this.text=this.meaning=!1,this.homeSheet=e,this.homeBefore=n,this.homeAfter=r,this.walk(t)}walk(t){switch(t.type){case"ref":return this.ref(t);case"range":return this.range(t);case"unary":case"percent":return t.arg=this.walk(t.arg),t;case"binary":return t.left=this.walk(t.left),t.right=this.walk(t.right),t;case"paren":return t.expr=this.walk(t.expr),t;case"call":for(let e=0;e<t.args.length;e++)t.args[e]=this.walk(t.args[e]);return t;default:return t}}absolute(t){return this.isRow?t.rowAbs?t.row:t.row+this.homeBefore:t.colAbs?t.col:t.col+this.homeBefore}store(t,e){this.isRow?t.row=t.rowAbs?e:e-this.homeAfter:t.col=t.colAbs?e:e-this.homeAfter}ref(t){const e=this.absolute(t),n=(t.sheet??this.homeSheet)===this.map.sheet?this.map.index(e):e;return n===qt?(this.text=this.meaning=!0,Ae()):(n!==e&&(this.text=!0),this.store(t,n),t)}range(t){const e=this.absolute(t.start),n=this.absolute(t.end);let r=e,i=n;if((t.start.sheet??this.homeSheet)===this.map.sheet){const o=e<=n?e:n,l=e<=n?n:e,a=this.map.span(o,l);if(!a)return this.text=this.meaning=!0,Ae();Js(this.map,o,l,a)&&(this.meaning=!0),(a[0]!==o||a[1]!==l)&&(this.text=!0),r=e<=n?a[0]:a[1],i=e<=n?a[1]:a[0]}return this.store(t.start,r),this.store(t.end,i),t}}function ss(s,t,e,n){const r=s.axis==="row",i=s.index+s.count,o=a=>r?a.rowAbs?a.row:a.row+n:a.colAbs?a.col:a.col+n;let l=!1;return Z(t,a=>{if(!(l||a.type==="name"||((a.type==="ref"?a:a.start).sheet??e)!==s.sheet))if(a.type==="ref"){const h=o(a);l=h>=s.index&&h<i}else{const h=o(a.start),u=o(a.end);l=Math.min(h,u)<i&&Math.max(h,u)>=s.index}}),l}function cr(s,t,e){let n=!1;return{ast:Et(s,i=>{const o=i.type==="ref"?i.sheet:i.type==="range"?i.start.sheet:void 0;return i.type==="name"||(o??e)!==t?i:(n=!0,Ae())}),changed:n}}const _=s=>Math.floor(s/17179869184),O=s=>Math.floor(s%17179869184/16384),U=s=>s%16384,ns=(s,t,e,n)=>`${s},${t}:${e},${n}`,hr=/^[\p{L}_][\p{L}\p{N}_.]*$/u,ur=64;class gt{constructor(){v(this,"sheetNames",[]);v(this,"sheetIds",new Map);v(this,"sheetData",[]);v(this,"rangeIndex",[]);v(this,"names",new Map);v(this,"unresolved",new Set);v(this,"evaluatingNames",new Set);v(this,"listeners",new Set);v(this,"batchDepth",0);v(this,"pendingKeys",new Set);v(this,"dirty",new Set);v(this,"volatiles",new Set);v(this,"anchors",new Set);v(this,"trace",null);v(this,"spillSeeds",new Set);v(this,"spillDirty",new Set);v(this,"ctx",{sheet:0,row:0,col:0,getCellValue:(t,e,n)=>{var r,i;return((i=(r=this.sheetData[t])==null?void 0:r.get(N(e,n,t)))==null?void 0:i.value)??null},resolveName:t=>this.nameValue(t),getRange:(t,e,n,r,i)=>{const o=this.rangeCache;if(!o)return ve(this.ctx,t,e,n,r,i);const l=`${t}!${e},${n}:${r},${i}`;let a=o.get(l);return a||o.set(l,a=ve(this.ctx,t,e,n,r,i)),a}});v(this,"rangeCache",null);this.createSheet("Sheet1")}static buildEmpty(){return new gt}static buildFromArray(t,e="Sheet1"){const n=new gt;return e!=="Sheet1"&&n.renameSheet(0,e),n.batch(()=>n.setCellContents({row:0,col:0},t)),n}static buildFromSheets(t){const e=new gt,n=Object.keys(t);return n.length===0?(e.removeSheet(0),e):(e.renameSheet(0,n[0]),n.slice(1).forEach(r=>e.addSheet(r)),e.batch(()=>n.forEach((r,i)=>e.setCellContents({row:0,col:0,sheet:i},t[r]))),e)}addSheet(t){const e=t??this.unusedSheetName();this.checkSheetName(e);const n=this.createSheet(e);return this.batch(()=>this.reresolve()),n}removeSheet(t){const e=this.requireSheet(t);return this.batch(()=>{var r,i;const n=new Set;for(const o of e.values())o.removed=!0,(r=o.dependents)==null||r.forEach(l=>n.add(l));(i=this.rangeIndex[t])==null||i.forEach(o=>o.dependents.forEach(l=>n.add(l)));for(const o of e.values())this.unlink(o),this.unresolved.delete(o),this.anchors.delete(o);this.sheetIds.delete(this.sheetNames[t].toUpperCase()),this.sheetNames[t]=void 0,this.sheetData[t]=void 0,this.rangeIndex[t]=void 0;for(const o of n){if(o.removed||!o.ast)continue;const{ast:l,changed:a}=cr(o.ast,t,this.homeSheet(o));a&&(this.unlink(o),o.ast=l,o.textDirty=!0,this.link(o),this.dirty.add(o))}})}renameSheet(t,e){this.requireSheet(t);const n=this.sheetNames[t];if(n!==e){n.toUpperCase()!==e.toUpperCase()&&this.checkSheetName(e),this.sheetIds.delete(n.toUpperCase()),this.sheetIds.set(e.toUpperCase(),t),this.sheetNames[t]=e;for(const r of this.formulaRecords())r.crossSheet&&!r.textDirty&&dr(r.ast,t)&&(r.textDirty=!0);this.batch(()=>this.reresolve())}}getSheetNames(){return this.sheetNames.filter(t=>t!==void 0)}getSheetId(t){return this.sheetIds.get(t.toUpperCase())}getSheetName(t){return this.sheetNames[t]}doesSheetExist(t){return this.getSheetId(t)!==void 0}countSheets(){return this.sheetIds.size}isItPossibleToAddNamedExpression(t){return hr.test(t)&&!Re(t)&&!/^(TRUE|FALSE)$/i.test(t)&&!we(t)&&!this.isNameDefined(t)}addNamedExpression(t,e){if(!this.isItPossibleToAddNamedExpression(t))throw new Error(`Cannot add named expression "${t}"`);return this.batch(()=>{const n=this.nameRecord(t);n.name=t,this.names.delete(t.toUpperCase()),this.names.set(t.toUpperCase(),n),this.setNameExpression(n,e)})}changeNamedExpression(t,e){const n=this.definedName(t);return this.batch(()=>this.setNameExpression(n,e))}removeNamedExpression(t){const e=this.definedName(t);return this.batch(()=>{this.unlink(e),this.unresolved.delete(e),e.raw=null,e.ast=void 0,e.value=null,this.dirty.add(e),this.collectPlaceholder(e)})}getNamedExpressionValue(t){if(!this.isNameDefined(t))return;const e=this.nameValue(t);return e instanceof R?e.values:this.finalize(e)}getNamedExpressionFormula(t){const e=this.names.get(t.toUpperCase());return e&&e.raw!==null?this.textOf(e):void 0}listNamedExpressions(){return[...this.names.values()].filter(t=>t.raw!==null).map(t=>t.name)}getCellValue({row:t,col:e,sheet:n=0}){var r;return((r=this.recordAt(N(t,e,n)))==null?void 0:r.value)??null}getCellSerialized({row:t,col:e,sheet:n=0}){const r=this.recordAt(N(t,e,n));return r?this.textOf(r):null}getCellFormula(t){const e=this.getCellSerialized(t);return F(e)?e:void 0}doesCellHaveFormula(t){return this.getCellFormula(t)!==void 0}getCellType({row:t,col:e,sheet:n=0}){const r=this.recordAt(N(t,e,n));return!r||r.raw===null?"EMPTY":F(r.raw)?"FORMULA":"VALUE"}getSpillRange({row:t,col:e,sheet:n=0}){var h;const r=this.recordAt(N(t,e,n)),i=(r==null?void 0:r.spillOwner)??r;if(!(i!=null&&i.spillArea)||!((h=i.spillCells)!=null&&h.length))return;const{r0:o,c0:l,r1:a,c1:c}=i.spillArea;return{start:At(n,o,l),end:At(n,a,c)}}getSheetDimensions(t=0){var r;let e=0,n=0;for(const i of((r=this.sheetData[t])==null?void 0:r.values())??[])i.raw===null&&!i.spillOwner||(n=Math.max(n,O(i.key)+1),e=Math.max(e,U(i.key)+1));return{width:e,height:n}}getSheetValues(t=0){return this.dump(t,e=>(e==null?void 0:e.value)??null)}getSheetSerialized(t=0){return this.dump(t,e=>e?this.textOf(e):null)}getCellPrecedents({row:t,col:e,sheet:n=0}){const r=this.recordAt(N(t,e,n));if(!(r!=null&&r.ast))return[];const i=[];return Z(r.ast,o=>{if(o.type==="ref")i.push(At(o.sheet??n,xt(o,t),bt(o,e)));else if(o.type==="range"){const l=o.start.sheet??n,[a,c]=Pt(xt(o.start,t),xt(o.end,t)),[h,u]=Pt(bt(o.start,e),bt(o.end,e));i.push({start:At(l,a,h),end:At(l,c,u)})}}),i}getCellDependents({row:t,col:e,sheet:n=0}){const r=N(t,e,n),i=new Set,o=l=>{var a;i.has(l)||(i.add(l),l.key<0&&((a=l.dependents)==null||a.forEach(o)))};return this.forEachDependent(this.recordAt(r),r,o),[...i].filter(l=>l.key>=0).map(l=>At(_(l.key),O(l.key),U(l.key)))}calculateFormula(t,e=0){try{const n=this.parse(oe(t),0,0);return this.finalize(Y(n,{...this.ctx,sheet:e,row:0,col:0}))}catch(n){if(n instanceof I)return A("#ERROR!",n.message);throw n}}validateFormula(t){try{return this.parse(oe(t),0,0),!0}catch{return!1}}setCellContents(t,e){const n=t.sheet??0;return this.requireSheet(n),this.batch(()=>{Array.isArray(e)?e.forEach((r,i)=>r.forEach((o,l)=>this.writeCell(n,t.row+i,t.col+l,o))):this.writeCell(n,t.row,t.col,e)})}setSheetContent(t,e=0){const n=this.requireSheet(e);return this.batch(()=>{for(const r of[...n.values()])r.raw!==null&&this.writeCell(e,O(r.key),U(r.key),null);this.setCellContents({row:0,col:0,sheet:e},t)})}batch(t){this.batchDepth++;try{t()}finally{this.batchDepth--}if(this.batchDepth>0)return[];const e=this.pendingKeys,n=this.dirty;this.pendingKeys=new Set,this.dirty=new Set;const r=this.recalculate(e,n);return r.length&&this.listeners.forEach(i=>i(r)),r}addRows(t,e,n=0){return this.restructure({sheet:n,axis:"row",index:t,count:e,remove:!1})}removeRows(t,e,n=0){return this.restructure({sheet:n,axis:"row",index:t,count:e,remove:!0})}addColumns(t,e,n=0){return this.restructure({sheet:n,axis:"col",index:t,count:e,remove:!1})}removeColumns(t,e,n=0){return this.restructure({sheet:n,axis:"col",index:t,count:e,remove:!0})}moveRows(t,e,n,r=0){return this.move("row",t,e,n,r)}moveColumns(t,e,n,r=0){return this.move("col",t,e,n,r)}inverseMove(t,e,n){return Qs(t,e,n)}recalculateVolatile(){return this.batch(()=>{})}captureRemoval(t,e,n,r=0){this.requireSheet(r);const i={sheet:r,axis:t,index:e,count:n},o=t==="row",l={sheet:r,axis:t,index:e,count:n,cells:[],names:[]};this.sheetData.forEach((a,c)=>{if(a)for(const h of a.values()){if(h.raw===null)continue;const u=o?O(h.key):U(h.key),d=c===r&&u>=e&&u<e+n,f=!!h.ast&&(c===r||!!h.crossSheet)&&ss(i,h.ast,c,u);(d||f)&&l.cells.push({address:{sheet:c,row:O(h.key),col:U(h.key)},raw:this.textOf(h)})}});for(const a of this.names.values())a.ast&&a.raw!==null&&ss(i,a.ast,-1,0)&&l.names.push({name:a.name,raw:this.textOf(a)});return l}restoreRemoval(t){return this.batch(()=>{t.axis==="row"?this.addRows(t.index,t.count,t.sheet):this.addColumns(t.index,t.count,t.sheet);for(const e of t.cells)this.setCellContents(e.address,e.raw);for(const e of t.names)this.changeNamedExpression(e.name,e.raw)})}shiftFormula(t,e,n){if(!F(t))return t;const r=[],i=this.sheetNames.length;let o;try{o=xe(oe(t),{resolveSheet:a=>this.getSheetId(a)??i+r.push(a)-1})}catch{return t}return"="+jt(o,{base:{row:e,col:n},sheetName:a=>a<i?this.sheetNames[a]:r[a-i]})}on(t,e){t==="valuesUpdated"&&this.listeners.add(e)}off(t,e){t==="valuesUpdated"&&this.listeners.delete(e)}destroy(){this.sheetData.forEach(t=>t==null?void 0:t.clear()),this.rangeIndex=[],this.names.clear(),this.unresolved.clear(),this.listeners.clear(),this.volatiles.clear(),this.anchors.clear()}createSheet(t){const e=this.sheetNames.length;return this.sheetNames.push(t),this.sheetIds.set(t.toUpperCase(),e),this.sheetData.push(new Map),this.rangeIndex.push(void 0),e}checkSheetName(t){if(t.trim()==="")throw new Error("Sheet name cannot be empty");if(this.doesSheetExist(t))throw new Error(`Sheet "${t}" already exists`)}unusedSheetName(){for(let t=this.countSheets()+1;;t++)if(!this.doesSheetExist(`Sheet${t}`))return`Sheet${t}`}requireSheet(t){const e=this.sheetData[t];if(!e)throw new Error(`There is no sheet with id ${t}`);return e}recordAt(t){var e;return(e=this.sheetData[_(t)])==null?void 0:e.get(t)}homeSheet(t){return t.key>=0?_(t.key):-1}*formulaRecords(){for(const t of this.sheetData)if(t)for(const e of t.values())e.ast&&(yield e);for(const t of this.names.values())t.ast&&(yield t)}textOf(t){if(t.textDirty&&t.ast){const e=t.key>=0?{row:O(t.key),col:U(t.key)}:void 0;t.raw="="+jt(t.ast,{base:e,sheetName:n=>this.sheetNames[n]}),t.textDirty=!1}return t.raw}dump(t,e){const n=this.sheetData[t],{width:r,height:i}=this.getSheetDimensions(t);return Array.from({length:i},(o,l)=>Array.from({length:r},(a,c)=>e(n==null?void 0:n.get(N(l,c,t)))))}parse(t,e,n,r){return xe(t,{base:{row:e,col:n},resolveSheet:i=>{const o=this.getSheetId(i);return r&&(r.crossSheet=!0,o===void 0&&(r.unresolved=!0,this.unresolved.add(r))),o}})}writeCell(t,e,n,r){var c;const i=this.requireSheet(t),o=N(e,n,t);let l=i.get(o);const a=r==null||r==="";a&&(l!=null&&l.spillOwner)||(l&&(l.spillOwner=void 0,l.spillArea&&this.dropSpill(l).forEach(h=>this.pendingKeys.add(h)),this.unlink(l),this.unresolved.delete(l),l.ast=void 0,l.textDirty=l.crossSheet=l.unresolved=!1),a?(c=l==null?void 0:l.dependents)!=null&&c.size?(l.raw=null,l.value=null):l&&(i.delete(o),l.removed=!0):(l||i.set(o,l={key:o,raw:r,value:null}),l.raw=r,F(r)?this.compile(l):l.value=et(r)),this.pendingKeys.add(o))}compile(t){t.value=null;try{t.ast=this.parse(t.raw.slice(1),O(t.key),U(t.key),t),this.link(t)}catch(e){if(!(e instanceof I))throw e;t.value=A("#ERROR!",e.message)}}setNameExpression(t,e){if(this.unlink(t),this.unresolved.delete(t),t.raw=e??null,t.ast=void 0,t.textDirty=t.unresolved=!1,t.value=et(e),F(e))try{const n=this.parse(e.slice(1),0,0,t),r=this.sheetNames.findIndex(i=>i!==void 0);Z(n,i=>{const o=i.type==="ref"?i:i.type==="range"?i.start:void 0;!o||o.sheet!==void 0||(o.sheet=r,i.type==="range"&&(i.end.sheet=r),t.textDirty=!0)}),t.ast=n,t.crossSheet=!0,t.value=null,this.link(t)}catch(n){if(!(n instanceof I))throw n;t.value=A("#ERROR!",n.message)}this.dirty.add(t)}reresolve(){for(const t of[...this.unresolved]){if(this.unresolved.delete(t),t.removed)continue;const e=this.textOf(t);t.key<0?this.setNameExpression(t,e):(this.unlink(t),t.ast=void 0,t.crossSheet=t.unresolved=!1,this.compile(t),this.dirty.add(t))}}isNameDefined(t){const e=this.names.get(t.toUpperCase());return e!==void 0&&e.raw!==null}definedName(t){if(!this.isNameDefined(t))throw new Error(`Named expression "${t}" does not exist`);return this.names.get(t.toUpperCase())}nameRecord(t){const e=t.toUpperCase();let n=this.names.get(e);return n||this.names.set(e,n={key:-1,raw:null,value:null,name:t}),n}nameValue(t){const e=this.names.get(t.toUpperCase());if(!e||e.raw===null)return A("#NAME?",`Unknown name "${t}"`);if(!e.ast)return e.value;if(this.evaluatingNames.has(e))return A("#CYCLE!");this.evaluatingNames.add(e);try{return Y(e.ast,{...this.ctx,sheet:-1,row:0,col:0})}finally{this.evaluatingNames.delete(e)}}ensureCell(t,e,n){const r=this.sheetData[t];if(!r||e<0||n<0)return;const i=N(e,n,t);let o=r.get(i);return o||r.set(i,o={key:i,raw:null,value:null}),o}rangeEntry(t,e,n,r,i){var c;const o=(c=this.rangeIndex)[t]??(c[t]=new Map),l=ns(e,n,r,i);let a=o.get(l);return a||o.set(l,a={sheet:t,r0:e,c0:n,r1:r,c1:i,id:l,dependents:new Set}),a}link(t){if(!t.ast)return;const e=this.homeSheet(t),n=t.key>=0?O(t.key):0,r=t.key>=0?U(t.key):0,i=[],o=[],l=a=>{a&&(i.push(a),(a.dependents??(a.dependents=new Set)).add(t))};Z(t.ast,a=>{if(a.type==="name")a.name!==""&&l(this.nameRecord(a.name));else if(a.type==="ref")l(this.ensureCell(a.sheet??e,xt(a,n),bt(a,r)));else{const c=a.start.sheet??e;if(!this.sheetData[c])return;const[h,u]=Pt(xt(a.start,n),xt(a.end,n)),[d,f]=Pt(bt(a.start,r),bt(a.end,r)),y=this.rangeEntry(c,h,d,u,f);y.dependents.add(t),o.push(y)}}),t.precedents=i.length?i:void 0,t.rangeDeps=o.length?o:void 0,t.volatile=t.positional=!1,St(t.ast,a=>{const c=we(a);c!=null&&c.volatile&&(t.volatile=!0),c!=null&&c.positional&&(t.positional=!0)}),t.volatile&&this.volatiles.add(t)}unlink(t){var e;if(t.precedents)for(const n of t.precedents)(e=n.dependents)==null||e.delete(t),this.collectPlaceholder(n);if(t.rangeDeps)for(const n of t.rangeDeps){n.dependents.delete(t);const r=this.rangeIndex[n.sheet];n.dependents.size===0&&(r==null?void 0:r.get(n.id))===n&&r.delete(n.id)}t.precedents=t.rangeDeps=void 0,this.volatiles.delete(t)}collectPlaceholder(t){var e;if(!(t.raw!==null||t.removed||(e=t.dependents)!=null&&e.size||t.spillOwner)){if(t.key<0){const n=t.name.toUpperCase();this.names.get(n)===t&&this.names.delete(n)}else{const n=this.sheetData[_(t.key)];(n==null?void 0:n.get(t.key))===t&&n.delete(t.key)}t.removed=!0}}forEachDependent(t,e,n,r=!1){var a,c;if((a=t==null?void 0:t.dependents)==null||a.forEach(n),r&&((c=t==null?void 0:t.spillCells)!=null&&c.length)&&this.forEachSpillDependent(t,n),e<0)return;const i=this.rangeIndex[_(e)];if(!(i!=null&&i.size))return;const o=O(e),l=U(e);for(const h of i.values())o>=h.r0&&o<=h.r1&&l>=h.c0&&l<=h.c1&&h.dependents.forEach(n)}recalculate(t,e){var l;const n=this.trace=new Map;let r=t,i=this.volatiles.size?[...e,...this.volatiles]:e;try{for(let a=1;this.spillSeeds=new Set,this.spillDirty=new Set,this.evaluatePass(r,i),!(!this.spillSeeds.size&&!this.spillDirty.size);a++){if(a===ur){for(const c of this.spillDirty)this.unspill(c),c.value=A("#SPILL!","Spill does not settle");break}r=this.spillSeeds,i=this.spillDirty}}finally{this.trace=null}const o=new Map;for(const a of t)this.sheetData[_(a)]&&o.set(a,{address:me(a),value:((l=this.recordAt(a))==null?void 0:l.value)??null});for(const[a,c]of n)a.key<0||t.has(a.key)||!this.sheetData[_(a.key)]||rs(c,a.value)||a.removed&&this.recordAt(a.key)||o.set(a.key,{address:me(a.key),value:a.value});return[...o.values()]}evaluatePass(t,e){const n=this.trace,r=new Map,i=[],o=u=>{u.removed||r.has(u)||(r.set(u,0),i.push(u),n.has(u)||n.set(u,u.value))},l=(u,d)=>{u!=null&&u.ast?o(u):this.forEachDependent(u,d,o)};for(const u of t)l(this.recordAt(u),u),this.anchors.size&&this.forEachAnchorCovering(u,o);for(const u of e)u.removed||l(u,u.key);const a=new Map;for(let u=0;u<i.length;u++){const d=i[u],f=[];this.forEachDependent(d,d.key,y=>{y.removed||(o(y),f.push(y),r.set(y,r.get(y)+1))},!0),f.length&&a.set(d,f)}const c=i.filter(u=>r.get(u)===0),h=this.ctx;this.rangeCache=new Map;try{for(;c.length;){const u=c.pop();r.set(u,-1),u.key>=0&&(h.sheet=_(u.key),h.row=O(u.key),h.col=U(u.key),this.assign(u,Y(u.ast,h)));for(const d of a.get(u)??[]){const f=r.get(d)-1;r.set(d,f),f===0&&c.push(d)}}}finally{this.rangeCache=null}for(const u of i)r.get(u)!==-1&&(u.spillArea&&this.unspill(u,!1),u.value=A("#CYCLE!"))}finalize(t){if(t instanceof R&&(t.height===0||t.width===0))return A("#CALC!","The result is an empty array");const e=k(t);return e===null?0:e}assign(t,e){if(e instanceof R&&e.height>0&&e.width>0&&(e.height>1||e.width>1)){this.spill(t,e);return}t.spillArea&&this.unspill(t),t.value=this.finalize(e)}spill(t,e){const n=_(t.key),r=O(t.key),i=U(t.key),o={r0:r,c0:i,r1:r+e.height-1,c1:i+e.width-1};t.spillArea=o,this.anchors.add(t);const l=this.sheetData[n];if(o.r1>=1048576||o.c1>=16384||this.isBlocked(t,o,l)){this.touchAnchors(this.clearSpill(t),t),t.value=A("#SPILL!","The spill range is not empty");return}const a=new Set(t.spillCells),c=[],h=[];for(let u=0;u<e.height;u++)for(let d=0;d<e.width;d++){if(u===0&&d===0)continue;const f=N(r+u,i+d,n);let y=l.get(f);y||l.set(f,y={key:f,raw:null,value:null});const S=this.finalize(e.values[u][d]);if(y.spillOwner===t){if(a.delete(y),rs(y.value,S)){c.push(y);continue}}else y.spillOwner=t,h.push(f),this.spillSeeds.add(f);this.noteBefore(y),y.value=S,c.push(y)}for(const u of a)u.spillOwner!==t||u.removed||(this.vacate(u),h.push(u.key));t.spillCells=c,this.touchAnchors(h,t),this.rangeCache=new Map,t.value=this.finalize(e.values[0][0])}isBlocked(t,e,n){const r=_(t.key);for(let i=e.r0;i<=e.r1;i++)for(let o=e.c0;o<=e.c1;o++){const l=n.get(N(i,o,r));if(l&&l!==t&&(l.raw!==null||l.spillOwner&&l.spillOwner!==t))return!0}return!1}unspill(t,e=!0){const n=this.clearSpill(t);e&&this.touchAnchors(n,t),this.anchors.delete(t),t.spillArea=void 0}dropSpill(t){const e=this.clearSpill(t);return this.anchors.delete(t),t.spillArea=void 0,e}clearSpill(t){const e=[];for(const n of t.spillCells??[])n.spillOwner!==t||n.removed||(this.vacate(n),e.push(n.key));return t.spillCells=void 0,e}vacate(t){this.noteBefore(t),t.spillOwner=void 0,t.value=null,this.collectPlaceholder(t)}noteBefore(t){this.trace&&!this.trace.has(t)&&this.trace.set(t,t.value)}touchAnchors(t,e){if(!(this.anchors.size<2||t.length===0))for(const n of t)this.forEachAnchorCovering(n,r=>{r!==e&&this.spillDirty.add(r)})}forEachAnchorCovering(t,e){const n=_(t),r=O(t),i=U(t);for(const o of this.anchors){const l=o.spillArea;o.key!==t&&_(o.key)===n&&r>=l.r0&&r<=l.r1&&i>=l.c0&&i<=l.c1&&e(o)}}forEachSpillDependent(t,e){var a;let n=1/0,r=1/0,i=-1,o=-1;for(const c of t.spillCells){if(c.spillOwner!==t||c.removed)continue;(a=c.dependents)==null||a.forEach(e);const h=O(c.key),u=U(c.key);h<n&&(n=h),h>i&&(i=h),u<r&&(r=u),u>o&&(o=u)}const l=this.rangeIndex[_(t.key)];if(!(i<0||!(l!=null&&l.size)))for(const c of l.values())c.r0<=i&&c.r1>=n&&c.c0<=o&&c.c1>=r&&c.dependents.forEach(e)}restructure(t){return this.requireSheet(t.sheet),t.count<=0?[]:this.remap(new ir(t))}move(t,e,n,r,i){this.requireSheet(i);const o=t==="row"?1048576:16384;if(![e,n,r].every(Number.isInteger)||e<0||n<0||r<0||e+n>o||r>o)throw new RangeError(`Invalid move of ${n} ${t==="row"?"rows":"columns"} from ${e} to ${r}`);return n===0||r>=e&&r<=e+n?[]:this.remap(new or(i,t,e,n,r))}remap(t){const e=this.requireSheet(t.sheet),n=t.axis==="row";return this.batch(()=>{const r=new ar(t),i=[],o=(d,f,y,S)=>{d.ast=r.adjust(d.ast,f,y,S),r.text&&(d.textDirty=!0),r.meaning?i.push(d):d.positional&&(r.text||y!==S)&&this.dirty.add(d)};this.sheetData.forEach((d,f)=>{if(!(!d||f===t.sheet))for(const y of d.values())y.ast&&y.crossSheet&&o(y,f,n?O(y.key):U(y.key),n?O(y.key):U(y.key))});for(const d of this.names.values())d.ast&&o(d,-1,0,0);const l=new Map,a=[],c=t.sheet*17179869184;e.forEach((d,f)=>{const y=f-c,S=Math.floor(y/16384),x=y-S*16384,g=n?S:x,p=t.index(g);if(p===qt){d.removed=!0,a.push(d);return}d.ast&&o(d,t.sheet,g,p),p!==g&&(d.key=n?f+(p-g)*16384:f+(p-g)),l.set(d.key,d)}),this.sheetData[t.sheet]=l;const h=[];for(const d of a)this.unlink(d),this.unresolved.delete(d),d.spillArea&&h.push(...this.dropSpill(d));for(const d of this.anchors)_(d.key)===t.sheet&&this.dirty.add(d);const u=this.rangeIndex[t.sheet];if(u){const d=new Map;for(const f of u.values()){const[y,S]=n?[f.r0,f.r1]:[f.c0,f.c1],x=t.span(y,S);!x||Js(t,y,S,x)||(n?[f.r0,f.r1]=x:[f.c0,f.c1]=x,f.id=ns(f.r0,f.c0,f.r1,f.c1),d.set(f.id,f))}this.rangeIndex[t.sheet]=d}for(const d of i)d.removed||(this.unlink(d),this.link(d),this.dirty.add(d));if(this.pendingKeys.size){const d=this.pendingKeys;this.pendingKeys=new Set;for(const f of d){if(_(f)!==t.sheet){this.pendingKeys.add(f);continue}const y=O(f),S=U(f),x=t.index(n?y:S);x!==qt&&this.pendingKeys.add(n?N(x,S,t.sheet):N(y,x,t.sheet))}}h.forEach(d=>this.pendingKeys.add(d))})}}const oe=s=>s.startsWith("=")?s.slice(1):s,xt=(s,t)=>s.rowAbs?s.row:s.row+t,bt=(s,t)=>s.colAbs?s.col:s.col+t,Pt=(s,t)=>s<=t?[s,t]:[t,s];function At(s,t,e){return s===0?{row:t,col:e}:{row:t,col:e,sheet:s}}function dr(s,t){let e=!1;return Z(s,n=>{(n.type==="ref"&&n.sheet===t||n.type==="range"&&n.start.sheet===t)&&(e=!0)}),e}function rs(s,t){return s instanceof Object&&t instanceof Object?s.code===t.code:s===t}function fr(s,t,e){const n=s.length,r=[],i=s.every(a=>typeof a=="number")?s:null,o=i&&n>=2?tn(i):void 0,l=pr(s);for(let a=0;a<t;a++){if(i&&o!==void 0){r.push(mr(i[n-1]+o*(a+1)));continue}if(l){const u=a+1;r.push(`${l.prefix}${l.last+l.step*u}${l.suffix}`);continue}const c=a%n,h=s[c];r.push(F(h)?e(h,c,n+a):h)}return r}function tn(s){const t=s[1]-s[0];for(let e=2;e<s.length;e++)if(Math.abs(s[e]-s[e-1]-t)>1e-9)return;return t}const is=/^(.*?)(\d+)(\D*)$/;function pr(s){if(!s.every(o=>typeof o=="string"&&!F(o)&&is.test(o)))return;const t=s.map(o=>is.exec(o)),{1:e,3:n}=t[0];if(!t.every(o=>o[1]===e&&o[3]===n))return;const r=t.map(o=>Number(o[2])),i=r.length>=2?tn(r):1;if(i!==void 0)return{prefix:e,suffix:n,last:r[r.length-1],step:i}}const mr=s=>Number(s.toPrecision(15));class Lt{constructor(t,e,n){v(this,"sizes");v(this,"prefix",null);this.defaultSize=e,this.sizes=Array.from({length:t},(r,i)=>Array.isArray(n)?n[i]??e:n??e)}get count(){return this.sizes.length}get total(){return this.offset(this.count)}size(t){return this.sizes[t]??this.defaultSize}setSize(t,e){this.sizes[t]=e,this.prefix=null}offset(t){if(!this.prefix){const e=new Float64Array(this.sizes.length+1);for(let n=0;n<this.sizes.length;n++)e[n+1]=e[n]+this.sizes[n];this.prefix=e}return this.prefix[Math.max(0,Math.min(t,this.sizes.length))]}indexAt(t){if(this.count===0)return 0;let e=0,n=this.count-1;for(;e<n;){const r=e+n+1>>1;this.offset(r)<=t?e=r:n=r-1}return e}insert(t,e){this.sizes.splice(t,0,...Array(e).fill(this.defaultSize)),this.prefix=null}remove(t,e){this.sizes.splice(t,e),this.prefix=null}resize(t){t>this.count?this.insert(this.count,t-this.count):t<this.count&&this.remove(t,this.count-t)}}const en=s=>s.length>0&&s.every(t=>t!==null&&typeof t=="object"&&!Array.isArray(t));function gr(s,t){let e=s;for(const n of t.split(".")){if(e===null||typeof e!="object")return;e=e[n]}return e}function wr(s,t,e){const n=t.split(".");let r=s;for(const i of n.slice(0,-1))(r[i]===null||typeof r[i]!="object")&&(r[i]={}),r=r[i];r[n[n.length-1]]=e}function yr(s){return s==null?null:typeof s=="number"||typeof s=="string"||typeof s=="boolean"?s:s instanceof Date?kt(s.getFullYear(),s.getMonth()+1,s.getDate()):String(s)}class ee{constructor(t,e,n){this.objects=t,this.fields=e,this.schema=n}static create(t,e,n){const r=e.some(i=>i!==void 0)?[...e]:Object.keys(t[0]??(n==null?void 0:n())??{});return new ee(t,r,n)}toRows(){return this.objects.map(t=>this.fields.map(e=>e===void 0?null:yr(gr(t,e))))}write(t,e,n){const r=this.fields[e];if(r!==void 0){for(;this.objects.length<=t;)this.objects.push(this.newRow());wr(this.objects[t],r,n)}}insertRows(t,e){this.objects.splice(t,0,...Array.from({length:e},()=>this.newRow()))}removeRows(t,e){this.objects.splice(t,e)}ensureRows(t){for(;this.objects.length<t;)this.objects.push(this.newRow())}insertCols(t,e){t<=this.fields.length&&this.fields.splice(t,0,...Array(e))}removeCols(t,e){this.fields.splice(t,e)}snapshot(){return{objects:[...this.objects],fields:[...this.fields]}}restore(t){this.objects.splice(0,this.objects.length,...t.objects),this.fields=[...t.fields]}newRow(){return this.schema?this.schema():{}}}function vr(s){let t="";return s.bold&&(t+=" ct-b"),s.italic&&(t+=" ct-i"),s.underline&&(t+=" ct-u"),s.strike&&(t+=" ct-s"),s.wrap&&(t+=" ct-wrap"),s.align&&(t+=` ct-al-${s.align[0]}`),t}const os=new Map;function xr(s,t){const e=`${s}|${JSON.stringify(t)}`;let n=os.get(e);return n||(n=new Intl.NumberFormat(s,{style:t.style??"decimal",currency:t.style==="currency"?t.currency??"TRY":void 0,minimumFractionDigits:t.minimumFractionDigits,maximumFractionDigits:t.maximumFractionDigits??(t.style==="currency"||t.style==="percent"?void 0:Math.max(t.minimumFractionDigits??0,10)),useGrouping:t.useGrouping??!0}),os.set(e,n)),n}const He=s=>s!=null&&s.startsWith("tr")||s!=null&&s.startsWith("de")?"DD.MM.YYYY":"YYYY-MM-DD";function ls(s,t,e){return t.type==="checkbox"?{text:s===!0?"☑":"☐",kind:"check"}:s==null?{text:""}:s instanceof rt?{text:s.code,kind:"err"}:typeof s=="number"?t.type==="date"?{text:Te(s,t.dateFormat??He(e)),kind:"date"}:t.numericFormat?{text:xr(e,t.numericFormat).format(s),kind:"num"}:{text:ke(s),kind:"num"}:typeof s=="boolean"?{text:s?"TRUE":"FALSE",kind:"bool"}:{text:s}}function br(s,t,e){return s==null?"":t.type==="date"&&typeof s=="number"?Te(s,t.dateFormat??He(e)):String(s)}function as(s,t={}){if(s==="")return null;if(s.length>1&&s[0]==="=")return s;if(t.type==="date")return Qt(s.trim())??s;if(t.type==="checkbox"){const n=et(s);return typeof n=="boolean"?n:typeof n=="number"?n!==0:s}if(t.type==="numeric"){const n=s.trim();if(/^[+-]?\d{1,3}(\.\d{3})*(,\d+)?$/.test(n)||/^[+-]?\d+,\d+$/.test(n)){const r=wt(n.replace(/\./g,"").replace(",","."));if(r!==void 0)return r}}if(t.type==="dropdown"||t.type==="text")return(t.type==="text"?void 0:wt(s))??s;const e=et(s);return typeof e=="number"||typeof e=="boolean"?e:s}function cs(s,t,e,n,r){if(t==null||t==="")return;if(!F(t)){if(e.type==="numeric"&&typeof s!="number")return"Not a number";if(e.type==="date"&&typeof s!="number")return"Not a date";if(e.type==="dropdown"&&e.strict!==!1&&e.source&&!e.source.includes(String(s)))return"Not in list"}const i=e.validator;if(!i)return;if(i instanceof RegExp)return i.test(String(s??""))?void 0:"Invalid value";const o=i(s,n,r);return o===!0?void 0:typeof o=="string"?o:"Invalid value"}const le=s=>!!s.validator||s.type==="numeric"||s.type==="date"||s.type==="dropdown",Ar=["contains","notContains","equals","notEquals","greaterThan","greaterOrEqual","lessThan","lessOrEqual","isEmpty","isNotEmpty"],hs=1e3;function Cr(s){var f,y,S,x,g,p;const t=s.anchor.ownerDocument,e=s.messages,n=t.createElement("div");n.className="ct-menu",n.setAttribute("role","dialog"),n.setAttribute("aria-label",e.columnMenu);const r=(b,C,M)=>{const E=t.createElement("button");return E.type="button",E.className=C,E.textContent=b,E.addEventListener("click",M),E};if(s.sortable){const b=t.createElement("div");b.className="ct-menu-section",b.append(r(e.sortAsc,`ct-menu-item${s.sort==="asc"?" ct-on":""}`,()=>(s.onSort("asc"),d())),r(e.sortDesc,`ct-menu-item${s.sort==="desc"?" ct-on":""}`,()=>(s.onSort("desc"),d()))),s.sort&&b.append(r(e.sortClear,"ct-menu-item",()=>(s.onSort(null),d()))),n.append(b)}let i=()=>{};if(s.filterable){const b=t.createElement("div");b.className="ct-menu-section";const C=t.createElement("div");C.className="ct-menu-title",C.textContent=e.filterByCondition;const M=t.createElement("select");M.append(new Option(e.none,""));for(const $ of Ar)M.append(new Option(e[$],$));M.value=((y=(f=s.filter)==null?void 0:f.condition)==null?void 0:y.op)??"";const E=t.createElement("input");E.type="text",E.value=((x=(S=s.filter)==null?void 0:S.condition)==null?void 0:x.value)??"";const z=()=>{E.hidden=!M.value||M.value==="isEmpty"||M.value==="isNotEmpty"};M.addEventListener("change",z),z(),b.append(C,M,E);const D=t.createElement("div");D.className="ct-menu-section";const ut=t.createElement("div");ut.className="ct-menu-title",ut.textContent=e.filterByValue;const ot=t.createElement("input");ot.type="search",ot.placeholder=e.search;const W=t.createElement("div");W.className="ct-menu-list";const Nt=new Set(((g=s.filter)==null?void 0:g.values)??s.values),$t=s.values.slice(0,hs),Q=[],zt=($,j)=>{const q=t.createElement("label"),_t=t.createElement("input");return _t.type="checkbox",_t.checked=j,q.append(_t,t.createTextNode($)),[q,_t]},[xn,Be]=zt(e.selectAll,$t.every($=>Nt.has($)));Be.addEventListener("change",()=>Q.forEach(([,$,j])=>!j.hidden&&($.checked=Be.checked))),W.append(xn);for(const $ of $t){const[j,q]=zt($===""?e.blanks:$,Nt.has($));Q.push([$,q,j]),W.append(j)}ot.addEventListener("input",()=>{const $=ot.value.toLowerCase();Q.forEach(([j,,q])=>q.hidden=!j.toLowerCase().includes($))}),D.append(ut,ot,W),n.append(b,D),i=()=>{const $={};M.value&&($.condition={op:M.value,value:E.value});const j=Q.filter(([,q])=>q.checked).map(([q])=>q);j.length<Q.length&&($.values=[...j,...s.values.slice(hs)]),s.onFilter($.condition||$.values?$:null),d()};const se=t.createElement("div");se.className="ct-menu-footer",se.append(r(e.clearFilter,"ct-menu-link",()=>(s.onFilter(null),d())),r(e.cancel,"ct-btn",()=>d()),r(e.ok,"ct-btn ct-primary",()=>i())),n.append(se)}t.body.append(n);const o=s.anchor.getBoundingClientRect(),l=n.offsetWidth||240,a=Math.max(8,Math.min(o.right-l,(((p=t.defaultView)==null?void 0:p.innerWidth)??1024)-l-8));n.style.left=`${a}px`,n.style.top=`${o.bottom+2}px`;const c=b=>{n.contains(b.target)||d()},h=b=>{b.key==="Escape"?(b.stopPropagation(),d()):b.key==="Enter"&&s.filterable&&b.target.tagName!=="BUTTON"&&i()};t.addEventListener("mousedown",c,!0),n.addEventListener("keydown",h);let u=!1;function d(){u||(u=!0,t.removeEventListener("mousedown",c,!0),n.remove(),s.onClose())}return d}function sn(s){return s.replace(/"[^"]*"|\\.|_.|\*./g,"").replace(/\[(?![hms]+\])[^\]]*\]/gi,"")}function nn(s){if(!s)return!1;const t=s.split(";")[0];return/[dmyhs]/i.test(sn(t).replace(/General/gi,""))}const Sr=/[-/.:, $+()!^&'~{}<>=]/;function rn(s){const t={YYYY:"yyyy",YY:"yy",MM:"mm",M:"m",DD:"dd",D:"d",HH:"hh",mm:"mm",ss:"ss"};let e="";const n=/YYYY|YY|MM|M|DD|D|HH|mm|ss/g;let r=0;for(let i=n.exec(s);i;i=n.exec(s))e+=us(s.slice(r,i.index))+t[i[0]],r=i.index+i[0].length;return e+us(s.slice(r))}function us(s){let t="";for(const e of s)t+=Sr.test(e)?e:`\\${e}`;return t}const Er=s=>s?`"${s.replace(/"/g,"")}"`:"";function ae(s,t,e){return e<=0?s:`${s}.${"0".repeat(t)}${"#".repeat(Math.max(0,e-t))}`}function Mr(s,t){var i;const e=s.style??"decimal",n=s.useGrouping===!1?"0":"#,##0";if(e==="percent"){const o=s.minimumFractionDigits??s.maximumFractionDigits??0;return`${ae(n,o,s.maximumFractionDigits??o)}%`}if(e==="currency"){const o=new Intl.NumberFormat(t,{style:"currency",currency:s.currency??"TRY"}),l=o.resolvedOptions(),a=s.minimumFractionDigits??l.minimumFractionDigits??2,c=Math.max(a,s.maximumFractionDigits??l.maximumFractionDigits??a),h=o.formatToParts(1),u=h.findIndex(x=>x.type==="currency"),d=h.findIndex(x=>x.type==="integer"),f=Er(((i=h[u])==null?void 0:i.value)??s.currency??""),y=h.slice(Math.min(u,d)+1,Math.max(u,d)).some(x=>x.type==="literal")?" ":"",S=ae(n,a,c);return u<d?`${f}${y}${S}`:`${S}${y}${f}`}if(s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0)return;const r=s.minimumFractionDigits??0;return ae(n,r,Math.max(r,s.maximumFractionDigits??r))}function on(s,t){if(s.type==="date")return rn(s.dateFormat??He(t));if(s.numericFormat)return Mr(s.numericFormat,t)}const G=(s,t=2)=>String(s).padStart(t,"0");function ln(s,t,e){const n=t.split(";")[0],{year:r,month:i,day:o}=at(s);let l=Math.round((s-Math.floor(s))*86400);l>=86400&&(l=86399);const a=Math.floor(l/3600),c=Math.floor(l/60)%60,h=l%60,u=/AM\/PM|A\/P/i.test(sn(n)),d=a%12===0?12:a%12,f=new Date(Date.UTC(2e3,0,1));f.setUTCFullYear(r,i-1,o);const y=p=>new Intl.DateTimeFormat(e,{...p,timeZone:"UTC"}).format(f),S=/"([^"]*)"|\\(.)|_(.)|\*(.)|\[(h+|m+|s+)\]|\[[^\]]*\]|AM\/PM|A\/P|y+|m+|d+|h+|s+|./gi,x=[];for(let p=S.exec(n);p;p=S.exec(n))x.push(p[0]);let g="";return x.forEach((p,b)=>{const C=p.toLowerCase();if(p[0]==='"')g+=p.slice(1,-1);else if(p[0]==="\\")g+=p[1];else if(p[0]==="_")g+=" ";else if(p[0]==="*")g+="";else if(/^\[h+\]$/i.test(p))g+=G(Math.floor(s)*24+a,C.length-2);else if(/^\[m+\]$/i.test(p))g+=G(Math.floor(s*1440),C.length-2);else if(/^\[s+\]$/i.test(p))g+=G(Math.floor(s*86400),C.length-2);else if(p[0]==="[")g+="";else if(C==="am/pm")g+=a<12?"AM":"PM";else if(C==="a/p")g+=a<12?"A":"P";else if(C[0]==="y")g+=C.length<=2?G(r%100):G(r,4);else if(C[0]==="d")g+=C.length===1?String(o):C.length===2?G(o):y({weekday:C.length===3?"short":"long"});else if(C[0]==="h")g+=C.length===1?String(u?d:a):G(u?d:a);else if(C[0]==="s")g+=C.length===1?String(h):G(h);else if(C[0]==="m"){const M=x.slice(0,b).reverse().find(D=>/^(\[?h+\]?|[dmys]+)$/i.test(D)),E=x.slice(b+1).find(D=>/^(\[?s+\]?|[dmyh]+)$/i.test(D));(!!M&&/h/i.test(M)||!!E&&/s/i.test(E))&&C.length<=2?g+=C.length===1?String(c):G(c):C.length===1?g+=String(i):C.length===2?g+=G(i):g+=y({month:C.length===3?"short":C.length===4?"long":"narrow"})}else g+=p}),g}const Rr=/^[=+\-@\t\r]/;function kr(s,t){return s.includes(t)||/["\r\n]/.test(s)||/^\s|\s$/.test(s)}const Dr=(s,t)=>kr(s,t)?`"${s.replace(/"/g,'""')}"`:s;function Nr(s,t,e,n){var i,o;const r=(o=(i=s.values)==null?void 0:i[t])==null?void 0:o[e];return r!==void 0?r:F(n)?n:et(n)}function an(s,t={}){var f,y,S,x;const e=t.delimiter??",",n=t.lineEnding??`\r
3
+ `,r=t.decimalSeparator??".",i=t.values==="raw",o=t.escapeFormulas!==!1,l=g=>o&&Rr.test(g)?`'${g}`:g,a=Math.max(s.data.length,((f=s.values)==null?void 0:f.length)??0);let c=0;for(let g=0;g<a;g++)c=Math.max(c,((y=s.data[g])==null?void 0:y.length)??0,((x=(S=s.values)==null?void 0:S[g])==null?void 0:x.length)??0);const h=(g,p)=>{var M,E,z;const b=(M=s.data[g])==null?void 0:M[p];if(i)return b==null?"":typeof b=="boolean"?b?"TRUE":"FALSE":typeof b=="string"?F(b)?b:l(b):u(b);const C=Nr(s,g,p,b);if(C==null)return"";if(C instanceof rt)return C.code;if(typeof C=="boolean")return C?"TRUE":"FALSE";if(typeof C=="number"){if(t.values==="formatted"&&s.text)return s.text(g,p);const D=(z=(E=s.format)==null?void 0:E.call(s,g,p))==null?void 0:z.numberFormat;return nn(D)&&Number.isFinite(C)&&C>=0?ln(C,D,t.locale):u(C)}return C===b&&F(b)?C:l(C)},u=g=>{if(typeof g=="string")return g;const p=String(T(g));return r==="."?p:p.replace(".",r)},d=[];for(let g=0;g<a;g++){const p=[];for(let b=0;b<c;b++)p.push(Dr(h(g,b),e));d.push(p.join(e))}return(t.bom===!1?"":"\uFEFF")+d.join(n)}const cn="text/csv;charset=utf-8";function Ce(s,t,e){const n=new Blob([s],{type:e}),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r,i.download=t,i.style.display="none",document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(r),0)}const $r=new RegExp("[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F￾￿]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]","g"),zr={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function tt(s){return s.replace($r,"").replace(/[&<>"']/g,t=>zr[t])}function Se(s){let t="";for(const[e,n]of Object.entries(s))n===void 0||n===!1||(t+=` ${e}="${n===!0?"1":tt(String(n))}"`);return t}const J=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
4
+ `,Lr="http://schemas.openxmlformats.org/spreadsheetml/2006/main",Tr={General:0,0:1,"0.00":2,"#,##0":3,"#,##0.00":4,"0%":9,"0.00%":10,"0.00E+00":11,"@":49};function ds(s){if(!s)return;let t=/^#?([0-9a-f]{6})$/i.exec(s.trim());return t?`FF${t[1].toUpperCase()}`:(t=/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(s.trim()),t?`FF${(t[1]+t[1]+t[2]+t[2]+t[3]+t[3]).toUpperCase()}`:void 0)}class ce{constructor(t){v(this,"items",[]);v(this,"index",new Map);t.forEach(e=>this.add(e))}add(t){let e=this.index.get(t);return e===void 0&&(e=this.items.push(t)-1,this.index.set(t,e)),e}}const fs=(s,t,e,n)=>`<font>${s?"<b/>":""}${t?"<i/>":""}${e?"<u/>":""}<sz val="11"/>${n?`<color rgb="${n}"/>`:""}<name val="Calibri"/><family val="2"/></font>`;class Fr{constructor(){v(this,"fonts",new ce([fs()]));v(this,"fills",new ce(['<fill><patternFill patternType="none"/></fill>','<fill><patternFill patternType="gray125"/></fill>']));v(this,"numFmts",new Map);v(this,"xfs",new ce(['<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>']))}numFmtId(t){const e=Tr[t];if(e!==void 0)return e;let n=this.numFmts.get(t);return n===void 0&&this.numFmts.set(t,n=164+this.numFmts.size),n}styleId(t){if(!t)return 0;const e=t.numberFormat?this.numFmtId(t.numberFormat):0,n=ds(t.color),r=t.bold||t.italic||t.underline||n?this.fonts.add(fs(t.bold,t.italic,t.underline,n)):0,i=ds(t.background),o=i?this.fills.add(`<fill><patternFill patternType="solid"><fgColor rgb="${i}"/><bgColor indexed="64"/></patternFill></fill>`):0,l=t.align||t.wrap?`<alignment${Se({horizontal:t.align,wrapText:t.wrap})}/>`:"",a=`<xf${Se({numFmtId:e,fontId:r,fillId:o,borderId:0,xfId:0,applyNumberFormat:e>0,applyFont:r>0,applyFill:o>0,applyAlignment:!!l})}`+(l?`>${l}</xf>`:"/>");return this.xfs.add(a)}toXml(){const t=[...this.numFmts].map(([n,r])=>`<numFmt numFmtId="${r}" formatCode="${tt(n)}"/>`).join(""),e=(n,r)=>`<${n} count="${r.length}">${r.join("")}</${n}>`;return J+`<styleSheet xmlns="${Lr}">`+(this.numFmts.size?`<numFmts count="${this.numFmts.size}">${t}</numFmts>`:"")+e("fonts",this.fonts.items)+e("fills",this.fills.items)+'<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'+e("cellXfs",this.xfs.items)+'<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles><dxfs count="0"/><tableStyles count="0"/></styleSheet>'}}let Tt;function Ir(){if(Tt)return Tt;Tt=new Uint32Array(256);for(let s=0;s<256;s++){let t=s;for(let e=0;e<8;e++)t=t&1?3988292384^t>>>1:t>>>1;Tt[s]=t>>>0}return Tt}function _e(s){const t=Ir();let e=4294967295;for(let n=0;n<s.length;n++)e=t[(e^s[n])&255]^e>>>8;return(e^4294967295)>>>0}function Or(s){const t=Math.max(1980,s.getFullYear());return{time:s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1,date:t-1980<<9|s.getMonth()+1<<5|s.getDate()}}const hn=0,Ur=8,ps=2048;function un(s,t){if(s.length>65535)throw new RangeError("Too many ZIP entries");const{time:e,date:n}=Or(t);let r=0,i=0;for(const f of s)r+=30+f.name.length+f.payload.length,i+=46+f.name.length;if(r+i+22>4294967295)throw new RangeError("ZIP archive too large (no ZIP64 support)");const o=new Uint8Array(r+i+22),l=new DataView(o.buffer),a=[];let c=0;const h=f=>(l.setUint16(c,f,!0),c+=2),u=f=>(l.setUint32(c,f>>>0,!0),c+=4);for(const f of s)a.push(c),u(67324752),h(20),h(ps),h(f.method),h(e),h(n),u(f.crc),u(f.payload.length),u(f.size),h(f.name.length),h(0),o.set(f.name,c),c+=f.name.length,o.set(f.payload,c),c+=f.payload.length;const d=c;return s.forEach((f,y)=>{u(33639248),h(20),h(20),h(ps),h(f.method),h(e),h(n),u(f.crc),u(f.payload.length),u(f.size),h(f.name.length),h(0),h(0),h(0),h(0),u(0),u(a[y]),o.set(f.name,c),c+=f.name.length}),u(101010256),h(0),h(0),h(s.length),h(s.length),u(i),u(d),h(0),o}const dn=new TextEncoder;function fn(s,t=new Date){return un(s.map(e=>({name:dn.encode(e.path),crc:_e(e.data),size:e.data.length,method:hn,payload:e.data})),t)}async function Hr(s){const t=new Blob([s]).stream().pipeThrough(new CompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}const _r=()=>typeof CompressionStream=="function";async function pn(s,t=new Date){const e=_r(),n=[];for(const r of s){let i=r.data,o=hn;if(e&&r.data.length>0)try{const l=await Hr(r.data);l.length<r.data.length&&(i=l,o=Ur)}catch{}n.push({name:dn.encode(r.path),crc:_e(r.data),size:r.data.length,method:o,payload:i})}return un(n,t)}const mn="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",Pe="http://schemas.openxmlformats.org/spreadsheetml/2006/main",pt="http://schemas.openxmlformats.org/officeDocument/2006/relationships",he="http://schemas.openxmlformats.org/package/2006/relationships",Vt="application/vnd.openxmlformats-officedocument.spreadsheetml",Ve=32767,Pr=new Set(["#NULL!","#DIV/0!","#VALUE!","#REF!","#NAME?","#NUM!","#N/A"]);function gn(s){const t=new Set;return s.map((e,n)=>{let r=e.replace(/[:\\/?*[\]]/g,"_").replace(/^'+|'+$/g,"").trim();r||(r=`Sheet${n+1}`),r=[...r].slice(0,31).join("");let i=r;for(let o=2;t.has(i.toLowerCase());o++){const l=` (${o})`;i=[...r].slice(0,31-l.length).join("")+l}return t.add(i.toLowerCase()),i})}const wn=s=>Math.max(0,Math.round((s-5)/7*256)/256),Vr=s=>Math.round(s*.75*100)/100,Mt=(s,t)=>`${Rt(t)}${s+1}`,ue=(s,t,e,n)=>`${Mt(s,t)}:${Mt(s+e-1,t+n-1)}`;class Xr{constructor(){v(this,"index",new Map);v(this,"list",[]);v(this,"count",0)}add(t){this.count++;let e=this.index.get(t);return e===void 0&&(e=this.list.push(t)-1,this.index.set(t,e)),e}toXml(){const t=this.list.map(e=>`<si>${Br(e)}</si>`).join("");return`${J}<sst xmlns="${Pe}" count="${this.count}" uniqueCount="${this.list.length}">${t}</sst>`}}const Br=s=>`<t${/^\s|\s$|\n/.test(s)?' xml:space="preserve"':""}>${tt(s.slice(0,Ve))}</t>`;function yn(s){return Pr.has(s.code)?s.code:"#VALUE!"}function Wr(s,t,e,n){return e===null?t?`<c r="${s}"${t}/>`:"":typeof e=="number"?Number.isFinite(e)?`<c r="${s}"${t}><v>${e}</v></c>`:`<c r="${s}"${t} t="e"><v>#NUM!</v></c>`:typeof e=="boolean"?`<c r="${s}"${t} t="b"><v>${e?1:0}</v></c>`:e instanceof rt?`<c r="${s}"${t} t="e"><v>${yn(e)}</v></c>`:`<c r="${s}"${t} t="s"><v>${n.add(e.slice(0,Ve))}</v></c>`}function jr(s,t,e,n){const r=`<f>${tt(e.slice(1))}</f>`;return n==null?`<c r="${s}"${t}>${r}</c>`:typeof n=="number"?Number.isFinite(n)?`<c r="${s}"${t}>${r}<v>${n}</v></c>`:`<c r="${s}"${t} t="e">${r}<v>#NUM!</v></c>`:typeof n=="boolean"?`<c r="${s}"${t} t="b">${r}<v>${n?1:0}</v></c>`:n instanceof rt?`<c r="${s}"${t} t="e">${r}<v>${yn(n)}</v></c>`:`<c r="${s}"${t} t="str">${r}<v>${tt(n.slice(0,Ve))}</v></c>`}function Yr(s){const t=[];for(const e of s??[]){if(e.rowspan<1||e.colspan<1||e.rowspan*e.colspan<2||e.row<0||e.col<0)continue;t.some(r=>e.row<r.row+r.rowspan&&r.row<e.row+e.rowspan&&e.col<r.col+r.colspan&&r.col<e.col+e.colspan)||t.push(e)}return t}function Kr(s,t,e,n){var g,p,b,C,M;const r=s.data.length;let i=0;for(const E of s.data)i=Math.max(i,(E==null?void 0:E.length)??0);if(r>1048576||i>16384)throw new RangeError(`Sheet "${s.name}" exceeds 1048576 rows or 16384 columns`);let o=`${J}<worksheet xmlns="${Pe}" xmlns:r="${pt}">`;o+=`<dimension ref="${r&&i?ue(0,0,r,i):"A1"}"/>`;const l=Math.max(0,Math.floor(((g=s.frozen)==null?void 0:g.rows)??0)),a=Math.max(0,Math.floor(((p=s.frozen)==null?void 0:p.cols)??0)),c=t===0?' tabSelected="1"':"";if(l||a){const E=l&&a?"bottomRight":l?"bottomLeft":"topRight";o+=`<sheetViews><sheetView${c} workbookViewId="0"><pane${Se({xSplit:a||void 0,ySplit:l||void 0,topLeftCell:Mt(l,a),activePane:E,state:"frozen"})}/><selection pane="${E}" activeCell="${Mt(l,a)}" sqref="${Mt(l,a)}"/></sheetView></sheetViews>`}else o+=`<sheetViews><sheetView${c} workbookViewId="0"/></sheetViews>`;o+='<sheetFormatPr defaultRowHeight="15"/>';const h=s.colWidths??[],u=[];h.forEach((E,z)=>{typeof E=="number"&&E>0&&z<16384&&u.push(`<col min="${z+1}" max="${z+1}" width="${wn(E)}" customWidth="1"/>`)}),u.length&&(o+=`<cols>${u.join("")}</cols>`);const d=s.rowHeights??[],f=Math.min(1048576,Math.max(r,d.length)),y=[];for(let E=0;E<f;E++){const z=s.data[E]??[];let D="";for(let W=0;W<z.length;W++){const Nt=e.styleId((b=s.format)==null?void 0:b.call(s,E,W)),$t=Nt?` s="${Nt}"`:"",Q=z[W],zt=Mt(E,W);D+=F(Q)?jr(zt,$t,Q,(M=(C=s.values)==null?void 0:C[E])==null?void 0:M[W]):Wr(zt,$t,et(Q),n)}const ut=d[E],ot=typeof ut=="number"&&ut>0?` ht="${Vr(ut)}" customHeight="1"`:"";(D||ot)&&y.push(`<row r="${E+1}"${ot}>${D}</row>`)}o+=y.length?`<sheetData>${y.join("")}</sheetData>`:"<sheetData/>";const S=s.autoFilter;S&&S.rows>0&&S.cols>0&&(o+=`<autoFilter ref="${ue(S.row,S.col,S.rows,S.cols)}"/>`);const x=Yr(s.merges);if(x.length){o+=`<mergeCells count="${x.length}">`;for(const E of x)o+=`<mergeCell ref="${ue(E.row,E.col,E.rowspan,E.colspan)}"/>`;o+="</mergeCells>"}return o+='<pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>',o+"</worksheet>"}const qr=s=>s.toISOString().replace(/\.\d{3}Z$/,"Z");function Xe(s,t={}){if(!s.length)throw new Error("A workbook needs at least one sheet");const e=gn(s.map(p=>p.name)),n=new Fr,r=new Xr,i=s.map((p,b)=>Kr(p,b,n,r)),o=qr(t.modified??new Date),l=`${J}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="${Vt}.sheet.main+xml"/>`+s.map((p,b)=>`<Override PartName="/xl/worksheets/sheet${b+1}.xml" ContentType="${Vt}.worksheet+xml"/>`).join("")+`<Override PartName="/xl/styles.xml" ContentType="${Vt}.styles+xml"/><Override PartName="/xl/sharedStrings.xml" ContentType="${Vt}.sharedStrings+xml"/><Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/><Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/></Types>`,a=`${J}<Relationships xmlns="${he}"><Relationship Id="rId1" Type="${pt}/officeDocument" Target="xl/workbook.xml"/><Relationship Id="rId2" Type="${he}/metadata/core-properties" Target="docProps/core.xml"/><Relationship Id="rId3" Type="${pt}/extended-properties" Target="docProps/app.xml"/></Relationships>`,c=tt(t.creator??"CenituTable"),h=`${J}<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><dc:creator>${c}</dc:creator><cp:lastModifiedBy>${c}</cp:lastModifiedBy><dcterms:created xsi:type="dcterms:W3CDTF">${o}</dcterms:created><dcterms:modified xsi:type="dcterms:W3CDTF">${o}</dcterms:modified></cp:coreProperties>`,u=`${J}<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"><Application>CenituTable</Application><HeadingPairs><vt:vector size="2" baseType="variant"><vt:variant><vt:lpstr>Worksheets</vt:lpstr></vt:variant><vt:variant><vt:i4>${e.length}</vt:i4></vt:variant></vt:vector></HeadingPairs><TitlesOfParts><vt:vector size="${e.length}" baseType="lpstr">`+e.map(p=>`<vt:lpstr>${tt(p)}</vt:lpstr>`).join("")+"</vt:vector></TitlesOfParts></Properties>",d=s.map((p,b)=>{const C=p.autoFilter;if(!C||C.rows<1||C.cols<1)return"";const M=(z,D)=>`$${Rt(D)}$${z+1}`,E=`'${e[b].replace(/'/g,"''")}'!${M(C.row,C.col)}:${M(C.row+C.rows-1,C.col+C.cols-1)}`;return`<definedName name="_xlnm._FilterDatabase" localSheetId="${b}" hidden="1">${tt(E)}</definedName>`}).join(""),f=`${J}<workbook xmlns="${Pe}" xmlns:r="${pt}"><bookViews><workbookView activeTab="0"/></bookViews><sheets>`+e.map((p,b)=>`<sheet name="${tt(p)}" sheetId="${b+1}" r:id="rId${b+1}"/>`).join("")+"</sheets>"+(d?`<definedNames>${d}</definedNames>`:"")+'<calcPr calcId="191029" fullCalcOnLoad="1"/></workbook>',y=s.length,S=`${J}<Relationships xmlns="${he}">`+s.map((p,b)=>`<Relationship Id="rId${b+1}" Type="${pt}/worksheet" Target="worksheets/sheet${b+1}.xml"/>`).join("")+`<Relationship Id="rId${y+1}" Type="${pt}/styles" Target="styles.xml"/><Relationship Id="rId${y+2}" Type="${pt}/sharedStrings" Target="sharedStrings.xml"/></Relationships>`,x=new TextEncoder,g=(p,b)=>({path:p,data:x.encode(b)});return[g("[Content_Types].xml",l),g("_rels/.rels",a),g("docProps/core.xml",h),g("docProps/app.xml",u),g("xl/workbook.xml",f),g("xl/_rels/workbook.xml.rels",S),g("xl/styles.xml",n.toXml()),g("xl/sharedStrings.xml",r.toXml()),...i.map((p,b)=>g(`xl/worksheets/sheet${b+1}.xml`,p))]}function Gr(s,t={}){return fn(Xe(s,t),t.modified)}function vn(s,t={}){return pn(Xe(s,t),t.modified)}function Zr(s,t,e,n,r){var x;const i=s.createElement("div");i.className="ct-menu ct-context",i.setAttribute("role","menu");const o=[];let l=!0;for(const g of t){if(g==="---"){l||i.append(Object.assign(s.createElement("div"),{className:"ct-menu-sep"})),l=!0;continue}l=!1;const p=s.createElement("button");p.type="button",p.className="ct-menu-item",p.setAttribute("role","menuitem"),p.dataset.key=g.key,p.disabled=!!g.disabled;const b=s.createElement("span");if(b.textContent=g.name,p.append(b),g.hint){const C=s.createElement("span");C.className="ct-menu-hint",C.textContent=g.hint,p.append(C)}p.addEventListener("click",()=>{S(),g.run()}),o.push(p),i.append(p)}s.body.append(i);const a=s.defaultView,c=i.offsetWidth||220,h=i.offsetHeight||300;i.style.left=`${Math.max(4,Math.min(e,((a==null?void 0:a.innerWidth)??1024)-c-4))}px`,i.style.top=`${Math.max(4,Math.min(n,((a==null?void 0:a.innerHeight)??768)-h-4))}px`;const u=()=>o.filter(g=>!g.disabled);(x=u()[0])==null||x.focus();const d=g=>{var C;const p=u(),b=p.indexOf(s.activeElement);if(g.key==="ArrowDown"||g.key==="ArrowUp"){g.preventDefault();const M=g.key==="ArrowDown"?(b+1)%p.length:(b-1+p.length)%p.length;(C=p[M])==null||C.focus()}else(g.key==="Escape"||g.key==="Tab")&&(g.preventDefault(),S());g.stopPropagation()},f=g=>{i.contains(g.target)||S()};i.addEventListener("keydown",d),s.addEventListener("mousedown",f,!0),a==null||a.addEventListener("blur",S);let y=!1;function S(){y||(y=!0,s.removeEventListener("mousedown",f,!0),a==null||a.removeEventListener("blur",S),i.remove(),r())}return S}function ms(s,t,e){if(e.values&&!e.values.includes(t))return!1;const n=e.condition;if(!n)return!0;const r=s===null||t==="";switch(n.op){case"isEmpty":return r;case"isNotEmpty":return!r}const i=(n.value??"").toLowerCase(),o=t.toLowerCase();switch(n.op){case"contains":return o.includes(i);case"notContains":return!o.includes(i)}const l=wt((n.value??"").replace(",",".")),a=typeof s=="number"&&l!==void 0?Math.sign(s-l):L(o,i);switch(n.op){case"equals":return a===0;case"notEquals":return a!==0;case"greaterThan":return!r&&a>0;case"greaterOrEqual":return!r&&a>=0;case"lessThan":return!r&&a<0;default:return!r&&a<=0}}const gs=s=>typeof s=="number"?0:typeof s=="string"?1:typeof s=="boolean"?2:s instanceof rt?3:4;function Qr(s,t,e){const n=s===null||s==="",r=t===null||t==="";if(n||r)return n===r?0:n?1:-1;const i=gs(s),o=gs(t);let l;return i!==o?l=i-o:i===3?l=0:i===1?l=s.localeCompare(t,void 0,{sensitivity:"base",numeric:!0}):l=L(s,t),e==="asc"?l:-l}const de=s=>({start:{row:s.row,col:s.col},end:{row:s.row+s.rowspan-1,col:s.col+s.colspan-1}}),ws=(s,t)=>s.start.row<=t.end.row&&s.end.row>=t.start.row&&s.start.col<=t.end.col&&s.end.col>=t.start.col;class Jr{constructor(){v(this,"areas",[]);v(this,"index",new Map)}get list(){return this.areas}set(t){this.areas=[];for(const e of t)this.add(e);this.reindex()}add(t){if(t.rowspan<1||t.colspan<1||t.rowspan===1&&t.colspan===1)return!1;const e=de(t);return this.areas=this.areas.filter(n=>!ws(de(n),e)),this.areas.push({...t}),this.reindex(),!0}removeAt(t,e){const n=this.get(t,e);return n?(this.areas=this.areas.filter(r=>r!==n),this.reindex(),!0):!1}get(t,e){return this.index.get(t*1048576+e)}expand(t){const e={start:{...t.start},end:{...t.end}};let n=this.areas.length>0;for(;n;){n=!1;for(const r of this.areas){const i=de(r);ws(i,e)&&(i.start.row<e.start.row&&(e.start.row=i.start.row,n=!0),i.start.col<e.start.col&&(e.start.col=i.start.col,n=!0),i.end.row>e.end.row&&(e.end.row=i.end.row,n=!0),i.end.col>e.end.col&&(e.end.col=i.end.col,n=!0))}}return e}shift(t,e,n){const r=t==="row"?"rowspan":"colspan",i=[];for(const o of this.areas){const l={...o},a=l[t],c=a+l[r]-1;if(n>0)a>=e?l[t]+=n:c>=e&&(l[r]+=n);else{const h=-n,u=Math.max(a,e),d=Math.min(c,e+h-1),f=Math.max(0,d-u+1);a>=e+h?l[t]-=h:a>=e&&(l[t]=e),l[r]-=f}l[r]>0&&(l.rowspan>1||l.colspan>1)&&i.push(l)}this.areas=i,this.reindex()}reindex(){this.index.clear();for(const t of this.areas)for(let e=t.row;e<t.row+t.rowspan;e++)for(let n=t.col;n<t.col+t.colspan;n++)this.index.set(e*1048576+n,t)}}const Ee={sortAsc:"Sort A → Z",sortDesc:"Sort Z → A",sortClear:"Clear sort",filterByCondition:"Filter by condition",filterByValue:"Filter by value",search:"Search",selectAll:"(Select all)",blanks:"(Blanks)",ok:"OK",cancel:"Cancel",clearFilter:"Clear filter",none:"None",contains:"Contains",notContains:"Does not contain",equals:"Is equal to",notEquals:"Is not equal to",greaterThan:"Greater than",greaterOrEqual:"Greater than or equal to",lessThan:"Less than",lessOrEqual:"Less than or equal to",isEmpty:"Is empty",isNotEmpty:"Is not empty",columnMenu:"Column menu",cut:"Cut",copy:"Copy",paste:"Paste",insertRowAbove:"Insert row above",insertRowBelow:"Insert row below",removeRow:"Delete row",removeRows:"Delete rows",insertColLeft:"Insert column left",insertColRight:"Insert column right",removeCol:"Delete column",removeCols:"Delete columns",mergeCells:"Merge cells",unmergeCells:"Unmerge cells",clearContents:"Clear contents",undo:"Undo",redo:"Redo",hideColumn:"Hide column",hideColumns:"Hide columns",showColumns:"Show hidden columns",cellAnnouncement:"{cell}: {value}"},ti={sortAsc:"A → Z sırala",sortDesc:"Z → A sırala",sortClear:"Sıralamayı kaldır",filterByCondition:"Koşula göre filtrele",filterByValue:"Değere göre filtrele",search:"Ara",selectAll:"(Tümünü seç)",blanks:"(Boş)",ok:"Tamam",cancel:"İptal",clearFilter:"Filtreyi temizle",none:"Yok",contains:"İçerir",notContains:"İçermez",equals:"Eşittir",notEquals:"Eşit değildir",greaterThan:"Büyüktür",greaterOrEqual:"Büyük veya eşittir",lessThan:"Küçüktür",lessOrEqual:"Küçük veya eşittir",isEmpty:"Boş",isNotEmpty:"Boş değil",columnMenu:"Sütun menüsü",cut:"Kes",copy:"Kopyala",paste:"Yapıştır",insertRowAbove:"Üste satır ekle",insertRowBelow:"Alta satır ekle",removeRow:"Satırı sil",removeRows:"Satırları sil",insertColLeft:"Sola sütun ekle",insertColRight:"Sağa sütun ekle",removeCol:"Sütunu sil",removeCols:"Sütunları sil",mergeCells:"Hücreleri birleştir",unmergeCells:"Birleştirmeyi kaldır",clearContents:"İçeriği temizle",undo:"Geri al",redo:"Yinele",hideColumn:"Sütunu gizle",hideColumns:"Sütunları gizle",showColumns:"Gizli sütunları göster",cellAnnouncement:"{cell}: {value}"};class ys{constructor(t,e=0){v(this,"order");v(this,"hidden",new Set);v(this,"visible",[]);v(this,"inverse",new Int32Array(0));v(this,"sorted",!1);v(this,"identity",!0);this.pinned=e,this.order=Array.from({length:t},(n,r)=>r),this.rebuild()}get count(){return this.visible.length}get physicalCount(){return this.order.length}get pinnedCount(){return Math.min(this.pinned,this.order.length)}get isIdentity(){return this.identity}get isSorted(){return this.sorted}toPhysical(t){return this.visible[t]??t-this.visible.length+this.order.length}toVisual(t){return t<this.inverse.length?this.inverse[t]:-1}setPinned(t){this.pinned=t,this.rebuild()}sort(t){const e=this.order.filter(r=>r<this.pinned).sort((r,i)=>r-i),n=this.order.filter(r=>r>=this.pinned);n.sort(t??((r,i)=>r-i)),this.order=[...e,...n],this.rebuild()}setHidden(t){this.hidden=new Set([...t].filter(e=>e>=this.pinned)),this.rebuild()}insert(t,e,n=this.count){const r=a=>a>=t?a+e:a,i=this.visible[n];this.order=this.order.map(r),this.hidden=new Set([...this.hidden].map(r));const o=Array.from({length:e},(a,c)=>t+c),l=i===void 0?this.order.length:this.order.indexOf(r(i));this.order.splice(l,0,...o),this.rebuild()}remove(t,e){const n=i=>i>=t+e?i-e:i,r=i=>i>=t&&i<t+e;this.order=this.order.filter(i=>!r(i)).map(n),this.hidden=new Set([...this.hidden].filter(i=>!r(i)).map(n)),this.rebuild()}snapshot(){return{order:[...this.order],hidden:[...this.hidden]}}restore(t){this.order=[...t.order],this.hidden=new Set(t.hidden),this.rebuild()}reset(t){this.order=Array.from({length:t},(e,n)=>n),this.hidden.clear(),this.rebuild()}rebuild(){const t=this.order.filter(e=>e<this.pinned).sort((e,n)=>e-n);this.order=[...t,...this.order.filter(e=>e>=this.pinned)],this.visible=this.order.filter(e=>!this.hidden.has(e)),this.inverse=new Int32Array(this.order.length).fill(-1),this.visible.forEach((e,n)=>this.inverse[e]=n),this.sorted=!this.order.every((e,n)=>e===n),this.identity=!this.sorted&&this.hidden.size===0}}const ei=`
5
+ --ct-bg: #fff;
6
+ --ct-fg: #1f2328;
7
+ --ct-muted: #57606a;
8
+ --ct-grid: #e1e4e8;
9
+ --ct-header-bg: #f6f8fa;
10
+ --ct-header-fg: #57606a;
11
+ --ct-header-hl: #dde7f8;
12
+ --ct-accent: #1a73e8;
13
+ --ct-range: rgba(26, 115, 232, 0.1);
14
+ --ct-error: #cf222e;
15
+ --ct-invalid-bg: #ffebe9;
16
+ --ct-readonly-fg: #6e7781;
17
+ --ct-shadow: rgba(31, 35, 40, .15);`,vs=`
18
+ --ct-bg: #0d1117;
19
+ --ct-fg: #e6edf3;
20
+ --ct-muted: #8b949e;
21
+ --ct-grid: #30363d;
22
+ --ct-header-bg: #161b22;
23
+ --ct-header-fg: #8b949e;
24
+ --ct-header-hl: #1f3a5f;
25
+ --ct-accent: #4c8dff;
26
+ --ct-range: rgba(76, 141, 255, 0.16);
27
+ --ct-error: #ff7b72;
28
+ --ct-invalid-bg: #3d1d1f;
29
+ --ct-readonly-fg: #7d8590;
30
+ --ct-shadow: rgba(0, 0, 0, .5);`,si=`
31
+ .ct-root, .ct-menu {${ei}
32
+ }
33
+ @media (prefers-color-scheme: dark) {
34
+ .ct-root:not(.ct-light), .ct-menu {${vs}
35
+ }
36
+ }
37
+ .ct-root.ct-dark {${vs}
38
+ }
39
+ .ct-root {
40
+ position: relative;
41
+ overflow: auto;
42
+ outline: none;
43
+ background: var(--ct-bg);
44
+ color: var(--ct-fg);
45
+ font: 13px/1.2 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
46
+ border: 1px solid var(--ct-grid);
47
+ box-sizing: border-box;
48
+ user-select: none;
49
+ }
50
+ .ct-canvas { position: relative; }
51
+ .ct-band { display: flex; }
52
+ .ct-band-top { position: sticky; top: 0; z-index: 3; }
53
+ .ct-pane { position: relative; flex: none; }
54
+ .ct-pane-corner, .ct-pane-left { position: sticky; left: 0; background: var(--ct-bg); }
55
+ .ct-pane-corner { z-index: 4; }
56
+ .ct-pane-left { z-index: 2; }
57
+ .ct-pane-top { background: var(--ct-bg); }
58
+ .ct-edge-r { box-shadow: 2px 0 3px -1px var(--ct-shadow); }
59
+ .ct-edge-b { box-shadow: 0 2px 3px -1px var(--ct-shadow); }
60
+ .ct-pane-corner.ct-edge-r.ct-edge-b { box-shadow: 2px 2px 3px -1px var(--ct-shadow); }
61
+
62
+ .ct-cell, .ct-header {
63
+ position: absolute; box-sizing: border-box; padding: 0 6px; overflow: hidden;
64
+ white-space: nowrap; text-overflow: ellipsis; display: flex; align-items: center;
65
+ border-right: 1px solid var(--ct-grid); border-bottom: 1px solid var(--ct-grid);
66
+ }
67
+ .ct-cell { background: var(--ct-bg); }
68
+ .ct-cell.ct-num, .ct-cell.ct-date { justify-content: flex-end; font-variant-numeric: tabular-nums; }
69
+ .ct-cell.ct-bool, .ct-cell.ct-check { justify-content: center; }
70
+ .ct-cell.ct-err { color: var(--ct-error); justify-content: center; }
71
+ .ct-cell.ct-readonly { color: var(--ct-readonly-fg); }
72
+ .ct-cell.ct-invalid { background: var(--ct-invalid-bg); box-shadow: inset 0 0 0 1px var(--ct-error); }
73
+ .ct-cell.ct-dd { padding-right: 18px; }
74
+ .ct-cell.ct-dd::after { content: "▾"; position: absolute; right: 5px; color: var(--ct-muted); font-size: 11px; }
75
+ .ct-cell.ct-b { font-weight: 700; }
76
+ .ct-cell.ct-i { font-style: italic; }
77
+ .ct-cell.ct-u { text-decoration: underline; }
78
+ .ct-cell.ct-s { text-decoration: line-through; }
79
+ .ct-cell.ct-u.ct-s { text-decoration: underline line-through; }
80
+ .ct-cell.ct-wrap { white-space: normal; overflow-wrap: anywhere; line-height: 1.25; }
81
+ .ct-cell.ct-al-l { justify-content: flex-start; }
82
+ .ct-cell.ct-al-c { justify-content: center; }
83
+ .ct-cell.ct-al-r { justify-content: flex-end; }
84
+ .ct-checkbox { font-size: 15px; cursor: pointer; line-height: 1; }
85
+
86
+ .ct-header { background: var(--ct-header-bg); color: var(--ct-header-fg); justify-content: center; font-size: 12px; cursor: default; }
87
+ .ct-header.ct-hl { background: var(--ct-header-hl); color: var(--ct-fg); font-weight: 600; }
88
+ .ct-colhead { gap: 3px; padding: 0 4px; }
89
+ .ct-label { overflow: hidden; text-overflow: ellipsis; }
90
+ .ct-sort { font-size: 9px; color: var(--ct-accent); }
91
+ .ct-sort:empty { display: none; }
92
+ .ct-menu-btn {
93
+ margin-left: auto; border: 0; background: transparent; color: var(--ct-muted); cursor: pointer;
94
+ font: inherit; font-size: 11px; padding: 1px 3px; border-radius: 3px; opacity: 0; flex: none;
95
+ }
96
+ .ct-colhead:hover .ct-menu-btn, .ct-filtered .ct-menu-btn { opacity: 1; }
97
+ .ct-menu-btn:hover { background: var(--ct-grid); }
98
+ .ct-filtered .ct-menu-btn { color: var(--ct-bg); background: var(--ct-accent); }
99
+ .ct-cornerhead { cursor: pointer; }
100
+ .ct-colhead.ct-gap-r { box-shadow: inset -3px 0 0 -1px var(--ct-accent); }
101
+ .ct-colhead.ct-gap-l { box-shadow: inset 3px 0 0 -1px var(--ct-accent); }
102
+ .ct-rresize { position: absolute; left: 0; bottom: 0; width: 100%; height: 5px; cursor: row-resize; z-index: 1; }
103
+ .ct-rresize:hover { background: var(--ct-accent); opacity: .5; }
104
+ .ct-drop { position: absolute; width: 3px; background: var(--ct-accent); z-index: 6; pointer-events: none; }
105
+ .ct-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
106
+ .ct-resize { position: absolute; top: 0; right: 0; width: 6px; height: 100%; cursor: col-resize; z-index: 1; }
107
+ .ct-resize:hover { background: var(--ct-accent); opacity: .5; }
108
+
109
+ .ct-range { position: absolute; pointer-events: none; background: var(--ct-range); border: 1px solid var(--ct-accent); box-sizing: border-box; z-index: 1; }
110
+ .ct-active { position: absolute; pointer-events: none; border: 2px solid var(--ct-accent); box-sizing: border-box; z-index: 1; }
111
+ .ct-fill-area { position: absolute; pointer-events: none; border: 1px dashed var(--ct-accent); box-sizing: border-box; z-index: 1; }
112
+ .ct-fill {
113
+ position: absolute; z-index: 2; background: var(--ct-accent); border: 1px solid var(--ct-bg);
114
+ box-sizing: border-box; cursor: crosshair;
115
+ }
116
+ /* Larger hit area than the visible square. Resize handles sit inside their header because headers clip overflow. */
117
+ .ct-fill::before { content: ""; position: absolute; inset: -4px; }
118
+
119
+ .ct-editor {
120
+ position: absolute; z-index: 5; box-sizing: border-box; margin: 0; padding: 3px 5px; resize: none; overflow: hidden;
121
+ border: 2px solid var(--ct-accent); outline: none; font: inherit; color: var(--ct-fg); background: var(--ct-bg);
122
+ white-space: pre; box-shadow: 0 2px 8px var(--ct-shadow);
123
+ }
124
+ .ct-editor.ct-idle { opacity: 0; pointer-events: none; box-shadow: none; z-index: 0; caret-color: transparent; }
125
+ .ct-dd-list {
126
+ position: absolute; z-index: 6; max-height: 220px; overflow: auto; background: var(--ct-bg);
127
+ border: 1px solid var(--ct-grid); box-shadow: 0 4px 12px var(--ct-shadow); padding: 2px 0;
128
+ }
129
+ .ct-dd-item { padding: 4px 8px; cursor: pointer; white-space: nowrap; }
130
+ .ct-dd-item:hover { background: var(--ct-range); }
131
+ .ct-dd-item.ct-on { background: var(--ct-accent); color: #fff; }
132
+
133
+ .ct-menu {
134
+ position: fixed; z-index: 1000; width: 240px; box-sizing: border-box; padding: 6px 0;
135
+ background: var(--ct-bg); color: var(--ct-fg); border: 1px solid var(--ct-grid); border-radius: 6px;
136
+ box-shadow: 0 8px 24px var(--ct-shadow); font: 13px/1.3 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
137
+ }
138
+ .ct-menu-section { padding: 4px 10px; border-bottom: 1px solid var(--ct-grid); display: flex; flex-direction: column; gap: 4px; }
139
+ .ct-menu-title { font-size: 11px; font-weight: 600; color: var(--ct-muted); text-transform: uppercase; letter-spacing: .03em; padding-top: 2px; }
140
+ .ct-menu-item { text-align: left; border: 0; background: transparent; color: inherit; font: inherit; padding: 4px 6px; border-radius: 4px; cursor: pointer; }
141
+ .ct-menu-item:hover { background: var(--ct-range); }
142
+ .ct-menu-item.ct-on { color: var(--ct-accent); font-weight: 600; }
143
+ .ct-menu select, .ct-menu input[type=text], .ct-menu input[type=search] {
144
+ font: inherit; padding: 4px 6px; border: 1px solid var(--ct-grid); border-radius: 4px; background: var(--ct-bg); color: inherit;
145
+ }
146
+ .ct-menu-list { max-height: 180px; overflow: auto; display: flex; flex-direction: column; }
147
+ .ct-menu-list label { display: flex; gap: 6px; align-items: center; padding: 2px 0; white-space: nowrap; cursor: pointer; }
148
+ .ct-menu-list label[hidden] { display: none; }
149
+ .ct-menu-footer { display: flex; gap: 6px; padding: 8px 10px 2px; align-items: center; }
150
+ .ct-menu-link { margin-right: auto; border: 0; background: transparent; color: var(--ct-accent); font: inherit; cursor: pointer; padding: 0; }
151
+ .ct-context { width: auto; min-width: 200px; padding: 4px; }
152
+ .ct-context .ct-menu-item { display: flex; justify-content: space-between; gap: 24px; width: 100%; padding: 5px 8px; }
153
+ .ct-context .ct-menu-item:focus { outline: none; background: var(--ct-range); }
154
+ .ct-context .ct-menu-item:disabled { opacity: .45; cursor: default; background: transparent; }
155
+ .ct-menu-hint { color: var(--ct-muted); font-size: 12px; }
156
+ .ct-menu-sep { height: 1px; background: var(--ct-grid); margin: 4px 2px; }
157
+ .ct-btn { font: inherit; padding: 4px 10px; border-radius: 4px; border: 1px solid var(--ct-grid); background: var(--ct-bg); color: inherit; cursor: pointer; }
158
+ .ct-btn.ct-primary { background: var(--ct-accent); border-color: var(--ct-accent); color: #fff; }
159
+ `;function ni(s){if(s.getElementById("ct-styles"))return;const t=s.createElement("style");t.id="ct-styles",t.textContent=si,s.head.appendChild(t)}function ri(s){return s.map(t=>t.map(e=>/[\t\n\r"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e).join(" ")).join(`
160
+ `)}function ii(s){const t=[];let e=[],n="",r=0;const i=s.replace(/\r\n?/g,`
161
+ `).replace(/\n$/,"");for(;r<i.length;){const o=i[r];if(o==='"'&&n===""){const l=oi(i,r+1);if(l!==-1&&(l+1===i.length||i[l+1]===" "||i[l+1]===`
162
+ `)){n=i.slice(r+1,l).replace(/""/g,'"'),r=l+1;continue}}o===" "?(e.push(n),n=""):o===`
163
+ `?(e.push(n),t.push(e),e=[],n=""):n+=o,r++}return e.push(n),t.push(e),t}function oi(s,t){for(let e=t;e<s.length;e++)if(s[e]==='"'){if(s[e+1]==='"'){e++;continue}return e}return-1}const li=26,ai=50,Xt=4;class ci{constructor(t,e={}){v(this,"root");v(this,"data",[]);v(this,"binding");v(this,"bindingPaused",!1);v(this,"rows");v(this,"cols");v(this,"mapper");v(this,"merges",new Jr);v(this,"engine");v(this,"ownsEngine",!1);v(this,"sheet",0);v(this,"opts");v(this,"messages");v(this,"headerH");v(this,"rowHeaderW");v(this,"frozenRows");v(this,"frozenCols");v(this,"columnMeta",[]);v(this,"cellMeta",new Map);v(this,"labels");v(this,"filters",new Map);v(this,"sortState",null);v(this,"invalid",new Map);v(this,"rowHeights",new Map);v(this,"rowsCustomized",!1);v(this,"hiddenCols",new Map);v(this,"announcer");v(this,"announceTimer",0);v(this,"canvas");v(this,"topBand");v(this,"bodyBand");v(this,"panes");v(this,"cornerHead");v(this,"input");v(this,"editing",!1);v(this,"editorEnterMode",!1);v(this,"dropdown");v(this,"closeMenu");v(this,"anchor",null);v(this,"selEnd",null);v(this,"dragging",null);v(this,"moveDrop",null);v(this,"fillTarget",null);v(this,"hooks",new Map);v(this,"undoStack",[]);v(this,"redoStack",[]);v(this,"clipboard",null);v(this,"frame",0);v(this,"cleanup",[]);v(this,"onValuesUpdated",t=>{for(const{address:e}of t)(e.sheet??0)!==this.sheet||e.row>=this.data.length||(le(this.metaAt(e.row,e.col))&&this.revalidate(e.row,e.col),this.bindingPaused||this.writeComputed(e.row,e.col,!0));this.scheduleRender()});v(this,"onInput",()=>{if(!this.editing){this.openEditor(this.input.value);return}this.autoSizeInput(),this.dropdown&&this.filterDropdown(this.input.value)});v(this,"onEditorKey",t=>{if(!this.editing)return;t.stopPropagation();const e=this.dropdown,n=(r,i)=>{t.preventDefault(),this.commitAndMove(r,i)};if(e&&e.items.length&&(t.key==="ArrowDown"||t.key==="ArrowUp")){t.preventDefault(),e.active=Math.max(0,Math.min(e.items.length-1,e.active+(t.key==="ArrowDown"?1:-1))),this.highlightDropdown();return}switch(t.key){case"Enter":if(t.altKey){t.preventDefault(),this.input.setRangeText(`
164
+ `,this.input.selectionStart,this.input.selectionEnd,"end");return}return e&&e.active>=0&&(this.input.value=e.items[e.active]),n(t.shiftKey?-1:1,0);case"Tab":return n(0,t.shiftKey?-1:1);case"Escape":t.preventDefault(),this.closeEditor(!1);return;case"ArrowUp":case"ArrowDown":case"ArrowLeft":case"ArrowRight":if(this.editorEnterMode){const[r,i]=fe[t.key];return n(r,i)}}});v(this,"dropLine");var c;this.opts=e,this.messages={...Ee,...e.language},this.headerH=e.colHeaders===!1?0:li,this.rowHeaderW=e.rowHeaders===!1?0:ai,this.labels=Array.isArray(e.colHeaders)?[...e.colHeaders]:void 0,this.columnMeta=[...e.columns??[]];const n=t.ownerDocument;ni(n),this.root=n.createElement("div"),this.root.className="ct-root",this.root.setAttribute("role","grid"),this.root.setAttribute("aria-multiselectable","true"),e.theme==="light"&&this.root.classList.add("ct-light"),e.theme==="dark"&&this.root.classList.add("ct-dark"),this.root.style.height=typeof e.height=="number"?`${e.height}px`:e.height??"400px",this.buildDom(),t.appendChild(this.root);const r=e.formulas instanceof gt?e.formulas:void 0,i=r&&e.sheetName!==void 0?r.getSheetId(e.sheetName):r?0:void 0,o=e.data??(r&&i!==void 0?r.getSheetSerialized(i):[]);this.data=this.normalize(this.bind(o)),this.frozenRows=Math.min(e.fixedRowsTop??0,this.data.length),this.frozenCols=Math.min(e.fixedColumnsStart??0,this.countCols()),this.mapper=new ys(this.data.length,this.frozenRows),this.rows=new Lt(this.data.length,e.rowHeight??24);const l=typeof e.colWidths=="number"?e.colWidths:100,a=Array.isArray(e.colWidths)?e.colWidths:this.columnMeta.some(h=>h==null?void 0:h.width)?Array.from({length:this.countCols()},(h,u)=>{var d;return((d=this.columnMeta[u])==null?void 0:d.width)??l}):e.colWidths;this.cols=new Lt(this.countCols(),100,a),e.mergeCells&&this.merges.set(e.mergeCells.filter(h=>this.mergeAllowed(h)));for(const h of e.hiddenColumns??[])this.hiddenCols.set(h,this.cols.size(h));for(const h of this.hiddenCols.keys())this.cols.setSize(h,0);r?(this.engine=r,this.sheet=i??r.addSheet(e.sheetName),(e.data||i===void 0)&&r.setSheetContent(this.data,this.sheet)):e.formulas!==!1&&(this.engine=gt.buildFromArray(this.data,e.sheetName),this.ownsEngine=!0),(c=this.engine)==null||c.on("valuesUpdated",this.onValuesUpdated),this.syncBoundObjects(),this.validateAll(),this.bindEvents(),this.render()}countRows(){return this.mapper.count}countSourceRows(){return this.data.length}countCols(){var t;return((t=this.data[0])==null?void 0:t.length)??0}getEngine(){return this.engine}getSheetId(){return this.sheet}getSheetName(){var t;return(t=this.engine)==null?void 0:t.getSheetName(this.sheet)}toPhysicalRow(t){return this.mapper.toPhysical(t)}toVisualRow(t){return this.mapper.toVisual(t)}getDataAtCell(t,e){return this.valueAt(this.mapper.toPhysical(t),e)}getSourceDataAtCell(t,e){return this.rawAt(this.mapper.toPhysical(t),e)}getData(){return Array.from({length:this.countRows()},(t,e)=>Array.from({length:this.countCols()},(n,r)=>this.getDataAtCell(e,r)))}getSourceData(){return this.data.map((t,e)=>t.map((n,r)=>this.rawAt(e,r)))}getBoundRows(){return this.data.map((t,e)=>t.map((n,r)=>this.boundValueAt(e,r)))}getSourceObjects(){var t;return(t=this.binding)==null?void 0:t.objects}getSourceDataAtRow(t){const e=this.mapper.toPhysical(t);return this.binding?this.binding.objects[e]:this.getSourceData()[e]}propToCol(t){var e;return((e=this.binding)==null?void 0:e.fields.indexOf(t))??-1}colToProp(t){var e;return(e=this.binding)==null?void 0:e.fields[t]}setDataAtCell(t,e,n,r){const i=typeof t=="number"?[[t,e,n]]:t,o=(typeof t=="number"?r:e)??"api";this.applyChanges(i.map(([l,a,c])=>this.change(this.mapper.toPhysical(l),a,c)),o)}loadData(t){var e;this.data=this.normalize(this.bind(t)),this.frozenRows=Math.min(this.frozenRows,this.data.length),this.mapper=new ys(this.data.length,this.frozenRows),this.syncRows(),this.cols.resize(this.countCols()),this.filters.clear(),this.sortState=null,this.cellMeta.clear(),this.rowHeights.clear(),this.bindingPaused=!0,(e=this.engine)==null||e.setSheetContent(this.data,this.sheet),this.bindingPaused=!1,this.syncBoundObjects(),this.undoStack=[],this.redoStack=[],this.anchor=this.selEnd=null,this.validateAll(),this.render()}getCellMeta(t,e){return this.metaAt(this.mapper.toPhysical(t),e)}setCellMeta(t,e,n){const r=this.mapper.toPhysical(t),i=N(r,e);this.cellMeta.set(i,{...this.cellMeta.get(i),...n}),this.revalidate(r,e),this.render()}updateSettings(t){this.opts={...this.opts,...t},t.language&&(this.messages={...Ee,...t.language}),t.columns&&(this.columnMeta=[...t.columns]),t.colHeaders!==void 0&&(this.labels=Array.isArray(t.colHeaders)?[...t.colHeaders]:void 0),(t.columnSorting!==void 0||t.filters!==void 0)&&this.resetHeaders(),(t.fixedRowsTop!==void 0||t.fixedColumnsStart!==void 0)&&(this.frozenRows=Math.min(t.fixedRowsTop??this.frozenRows,this.data.length),this.frozenCols=Math.min(t.fixedColumnsStart??this.frozenCols,this.countCols()),this.mapper.setPinned(this.frozenRows),this.syncRows(),this.merges.set(this.merges.list.filter(e=>this.mergeAllowed(e)))),t.mergeCells&&this.merges.set(t.mergeCells.filter(e=>this.mergeAllowed(e))),t.columns&&this.validateAll(),this.render()}selectCell(t,e,n=t,r=e){const i=h=>Math.max(0,Math.min(h,this.countRows()-1)),o=h=>Math.max(0,Math.min(h,this.countCols()-1));let l={row:i(t),col:o(e)},a={row:i(n),col:o(r)};const c=this.mergeAt(l.row,l.col);c&&t===n&&e===r&&(l={row:c.row,col:c.col},a={...l}),this.anchor=l,this.selEnd=a,this.scrollIntoView(this.selEnd),this.render(),this.announce(),this.run("afterSelection",l.row,l.col,a.row,a.col)}announce(){if(!this.anchor)return;const{row:t,col:e}=this.anchor,n=this.mapper.toPhysical(t),r=this.messages.cellAnnouncement.replace("{cell}",As({row:n,col:e})).replace("{value}",this.displayText(n,e)||"—");this.input.setAttribute("aria-label",r),clearTimeout(this.announceTimer),this.announceTimer=setTimeout(()=>this.announcer.textContent=r,120)}getSelected(){if(!(!this.anchor||!this.selEnd))return[[this.anchor.row,this.anchor.col,this.selEnd.row,this.selEnd.col]]}getSelectedRange(){if(!this.anchor||!this.selEnd)return;const t=Cs(this.anchor,this.selEnd);return this.mergesActive()?this.merges.expand(t):t}focus(){!this.anchor&&this.countRows()&&this.countCols()&&this.selectCell(0,0),this.focusInput()}deselectCell(){this.anchor=this.selEnd=null,this.render()}setCellStyle(t,e){const n=[];for(let r=t.start.row;r<=t.end.row;r++){const i=this.mapper.toPhysical(r);for(let o=t.start.col;o<=t.end.col;o++){const l=N(i,o),a=this.cellMeta.get(l),c={...a};e?c.style={...a==null?void 0:a.style,...e}:delete c.style,n.push({key:l,before:a,after:Object.keys(c).length?c:void 0})}}this.applyMeta(n,"after"),this.undoStack.push({kind:"meta",changes:n}),this.redoStack=[],this.render(),this.run("afterStyle",t,e)}getCellStyle(t,e){const n=this.mapper.toPhysical(t);return{...this.metaAt(n,e).style,...this.conditionalStyle(n,e,this.valueAt(n,e))}}toggleCellStyle(t){const e=this.getSelectedRange();if(!e||this.opts.readOnly)return;let n=!0;for(let r=e.start.row;r<=e.end.row&&n;r++)for(let i=e.start.col;i<=e.end.col&&n;i++)n=!!this.getCellStyle(r,i)[t];this.setCellStyle(e,{[t]:!n})}setRowHeight(t,e){const n=Math.max(12,Math.round(e));this.rowHeights.set(this.mapper.toPhysical(t),n),this.rowsCustomized=!0,this.rows.setSize(t,n),this.render()}getRowHeight(t){return this.rows.size(t)}hideColumns(t){for(const e of t)e<0||e>=this.countCols()||this.hiddenCols.has(e)||(this.hiddenCols.set(e,this.cols.size(e)),this.cols.setSize(e,0));this.anchor&&this.hiddenCols.has(this.anchor.col)&&this.moveActive(0,0,!1),this.render()}showColumns(t){for(const e of t??[...this.hiddenCols.keys()]){const n=this.hiddenCols.get(e);n!==void 0&&(this.hiddenCols.delete(e),this.cols.setSize(e,n||this.cols.defaultSize))}this.render()}isColumnHidden(t){return this.hiddenCols.has(t)}getHiddenColumns(){return[...this.hiddenCols.keys()].sort((t,e)=>t-e)}toExportSheet(){const t=this.getSourceData(),e=t.map((l,a)=>l.map((c,h)=>this.valueAt(a,h))),n=this.opts.locale,r=(l,a)=>{var f,y,S;const c=this.metaAt(l,a),h={...c.style,...this.conditionalStyle(l,a,((f=e[l])==null?void 0:f[a])??null)},u={},d=on(c,n);return d&&(u.numberFormat=d),h.bold&&(u.bold=!0),h.italic&&(u.italic=!0),h.underline&&(u.underline=!0),(y=h.color)!=null&&y.startsWith("#")&&(u.color=h.color),(S=h.background)!=null&&S.startsWith("#")&&(u.background=h.background),h.align&&(u.align=h.align),h.wrap&&(u.wrap=!0),Object.keys(u).length?u:void 0},i=this.rowHeights.size?Array.from({length:t.length},(l,a)=>this.rowHeights.get(a)??this.rows.defaultSize):void 0,o={name:this.getSheetName()??"Sheet1",data:t,values:e,colWidths:Array.from({length:this.countCols()},(l,a)=>this.cols.size(a)),rowHeights:i,frozen:{rows:this.frozenRows,cols:this.frozenCols},merges:this.mapper.isIdentity?this.getMergedCells():[],format:r,text:(l,a)=>{var c;return this.displayText(l,a,((c=e[l])==null?void 0:c[a])??null)}};return this.opts.filters&&this.frozenRows>0&&(o.autoFilter={row:this.frozenRows-1,col:0,rows:t.length-this.frozenRows+1,cols:this.countCols()}),o}exportCSV(t={}){const e=hi(this.opts.locale);return an(this.toExportSheet(),{delimiter:e?";":",",decimalSeparator:e?",":".",locale:this.opts.locale,...t})}downloadCSV(t="data.csv",e={}){Ce(this.exportCSV(e),t,cn)}async downloadXLSX(t="data.xlsx",e=[]){const n=await vn([this,...e].map(r=>r.toExportSheet()));Ce(n,t,mn)}sort(t,e){if(e===null)this.mapper.sort(null),this.sortState=null;else{const n=Array.from({length:this.data.length},(r,i)=>this.valueAt(i,t));this.mapper.sort((r,i)=>Qr(n[r],n[i],e)),this.sortState={col:t,order:e}}this.afterRowMapping(),this.run("afterColumnSort",t,e)}getSortState(){return this.sortState&&{...this.sortState}}setFilter(t,e){e?this.filters.set(t,e):this.filters.delete(t),this.applyFilters()}clearFilters(){this.filters.clear(),this.applyFilters()}getFilters(){return new Map(this.filters)}applyFilters(){const t=[];if(this.filters.size){const e=[...this.filters];for(let n=this.mapper.pinnedCount;n<this.data.length;n++)this.passes(n,e)||t.push(n)}this.mapper.setHidden(t),this.afterRowMapping(),this.run("afterFilter",this.getFilters())}mergeCells(t,e,n,r){const i={row:t,col:e,rowspan:n,colspan:r};return!this.mergeAllowed(i)||!this.merges.add(i)?!1:(this.render(),!0)}unmergeCells(t,e){const n=this.merges.removeAt(t,e);return n&&this.render(),n}getMergedCells(){return this.merges.list.map(t=>({...t}))}alter(t,e,n=1){const r=this.getSelectedRange(),i=t.includes("row"),o=t.startsWith("remove"),l=t==="insert_row_below"||t==="insert_col_end",a=i?this.countRows():this.countCols();let c;if(e!==void 0?c=l?e+1:e:i?c=l?((r==null?void 0:r.end.row)??a-1)+1:(r==null?void 0:r.start.row)??0:c=l?((r==null?void 0:r.end.col)??a-1)+1:(r==null?void 0:r.start.col)??0,c=Math.max(0,Math.min(c,a)),o&&(n=Math.min(n,a-c)),n<=0)return;const h=this.snapshot(),u=[];i?this.alterRows(c,n,o,u):this.alterCols(c,n,o,u),this.undoStack.push({kind:"structure",state:h,ops:u}),this.redoStack=[],this.validateAll(),this.clampSelection(),this.render(),this.run("afterAlter",t,c,n)}moveColumns(t,e,n){if(!this.canMoveColumns(t,e,n))return!1;const r=this.countCols(),i=this.snapshot(),o=[],l=h=>xs(h,t,e,n),a=h=>{const u=new Array(h.length);return h.forEach((d,f)=>u[l(f)]=d),u};this.data=this.data.map(h=>a(h)),this.binding&&(this.binding.fields=a(this.binding.fields.length<r?[...this.binding.fields,...Array(r-this.binding.fields.length)]:this.binding.fields));const c=a(Array.from({length:r},(h,u)=>this.cols.size(u)));return this.cols=new Lt(r,this.cols.defaultSize,c),this.columnMeta.length&&(this.columnMeta=a([...this.columnMeta,...Array(Math.max(0,r-this.columnMeta.length))])),this.labels&&(this.labels=a([...this.labels,...Array(Math.max(0,r-this.labels.length)).fill("")])),this.filters=new Map([...this.filters].map(([h,u])=>[l(h),u])),this.sortState&&(this.sortState={...this.sortState,col:l(this.sortState.col)}),this.hiddenCols=Ct(this.hiddenCols,l),this.cellMeta=Ct(this.cellMeta,h=>h-h%16384+l(h%16384)),this.merges.set(this.merges.list.map(h=>({...h,col:l(h.col)}))),this.applyEngineOp(Ft(o,{axis:"col",index:t,count:e,remove:!1,target:n})),this.undoStack.push({kind:"structure",state:i,ops:o}),this.redoStack=[],this.anchor&&this.selEnd&&(this.anchor={...this.anchor,col:l(this.anchor.col)},this.selEnd={...this.selEnd,col:l(this.selEnd.col)}),this.validateAll(),this.render(),this.run("afterColumnMove",t,e,n),!0}canMoveColumns(t,e,n){const r=this.countCols();if(e<=0||t<0||t+e>r||n<0||n>r||n>=t&&n<=t+e)return!1;const i=o=>xs(o,t,e,n);return this.merges.list.every(o=>{for(let l=1;l<o.colspan;l++)if(i(o.col+l)!==i(o.col)+l)return!1;return!0})}undo(){this.replay(this.undoStack,this.redoStack,"undo")}redo(){this.replay(this.redoStack,this.undoStack,"redo")}isUndoAvailable(){return this.undoStack.length>0}isRedoAvailable(){return this.redoStack.length>0}setColWidth(t,e){this.cols.setSize(t,Math.max(24,e)),this.render()}getColWidth(t){return this.cols.size(t)}addHook(t,e){let n=this.hooks.get(t);n||this.hooks.set(t,n=new Set),n.add(e)}removeHook(t,e){var n;(n=this.hooks.get(t))==null||n.delete(e)}getCellError(t,e){return this.invalid.get(N(this.mapper.toPhysical(t),e))}openContextMenu(t,e){var o;const n=this.getSelectedRange();if(!n||!this.opts.contextMenu)return;if((o=this.closeMenu)==null||o.call(this),t===void 0||e===void 0){const l=this.input.getBoundingClientRect();t=l.left+l.width/2,e=l.bottom}const r=this.contextMenuEntries(n),i=typeof this.opts.contextMenu=="function"?this.opts.contextMenu(r,this):r;this.closeMenu=Zr(this.root.ownerDocument,i,t,e,()=>{this.closeMenu=void 0,this.focusInput()})}contextMenuEntries(t){var h;const e=this.messages,n=!!this.opts.readOnly,r=t.end.row-t.start.row+1,i=t.end.col-t.start.col+1,o=this.mergeAt(t.start.row,t.start.col),l=!!o&&r===o.rowspan&&i===o.colspan,a=(h=this.root.ownerDocument.defaultView)==null?void 0:h.navigator.clipboard,c=this.mergeAllowed({row:t.start.row,col:t.start.col,rowspan:r,colspan:i});return[{key:"cut",name:e.cut,hint:"Ctrl+X",disabled:n,run:()=>this.writeClipboard(this.copy(!0))},{key:"copy",name:e.copy,hint:"Ctrl+C",run:()=>this.writeClipboard(this.copy())},{key:"paste",name:e.paste,hint:"Ctrl+V",disabled:n||!(a!=null&&a.readText)&&!this.clipboard,run:()=>{const u=()=>this.clipboard&&this.paste(this.clipboard.text);a!=null&&a.readText?a.readText().then(d=>d?this.paste(d):u(),u):u()}},"---",{key:"row_above",name:e.insertRowAbove,disabled:n,run:()=>this.alter("insert_row_above",t.start.row,r)},{key:"row_below",name:e.insertRowBelow,disabled:n,run:()=>this.alter("insert_row_below",t.end.row,r)},{key:"remove_row",name:r>1?e.removeRows:e.removeRow,disabled:n,run:()=>this.alter("remove_row",t.start.row,r)},"---",{key:"col_left",name:e.insertColLeft,disabled:n,run:()=>this.alter("insert_col_start",t.start.col,i)},{key:"col_right",name:e.insertColRight,disabled:n,run:()=>this.alter("insert_col_end",t.end.col,i)},{key:"remove_col",name:i>1?e.removeCols:e.removeCol,disabled:n,run:()=>this.alter("remove_col",t.start.col,i)},{key:"hide_col",name:i>1?e.hideColumns:e.hideColumn,disabled:i>=this.countCols()-this.hiddenCols.size,run:()=>this.hideColumns(Array.from({length:i},(u,d)=>t.start.col+d))},...this.hiddenCols.size?[{key:"show_cols",name:e.showColumns,run:()=>this.showColumns()}]:[],"---",l?{key:"unmerge",name:e.unmergeCells,disabled:n,run:()=>this.unmergeCells(t.start.row,t.start.col)}:{key:"merge",name:e.mergeCells,disabled:n||r===1&&i===1||!c,run:()=>this.mergeCells(t.start.row,t.start.col,r,i)},{key:"clear",name:e.clearContents,hint:"Del",disabled:n,run:()=>this.clearRange(t,"clear")},"---",{key:"undo",name:e.undo,hint:"Ctrl+Z",disabled:!this.isUndoAvailable(),run:()=>this.undo()},{key:"redo",name:e.redo,hint:"Ctrl+Y",disabled:!this.isRedoAvailable(),run:()=>this.redo()}]}writeClipboard(t){var e,n;t!==void 0&&((n=(e=this.root.ownerDocument.defaultView)==null?void 0:e.navigator.clipboard)==null||n.writeText(t).catch(()=>{}))}copy(t=!1){const e=this.getSelectedRange();if(!e)return;const n=[],r=[],i=[];for(let l=e.start.row;l<=e.end.row;l++){const a=this.mapper.toPhysical(l);i.push(a);const c=[],h=[];for(let u=e.start.col;u<=e.end.col;u++)c.push(this.rawAt(a,u)),h.push(this.displayText(a,u));n.push(c),r.push(h)}const o=ri(r);return this.clipboard={text:o,raws:n,rows:i,col:e.start.col},t&&this.clearRange(e,"cut"),o}paste(t){const e=this.getSelectedRange();if(!e||this.opts.readOnly)return;const n=this.clipboard&&this.clipboard.text===t?this.clipboard:null,r=n?n.raws:ii(t),i=r.length===1&&r[0].length===1,o=i?e.end.row-e.start.row+1:r.length,l=i?e.end.col-e.start.col+1:Bt(r,c=>c.length);this.ensureVisualRows(e.start.row+o);const a=[];for(let c=0;c<o;c++){const h=this.mapper.toPhysical(e.start.row+c);for(let u=0;u<l;u++){const d=e.start.col+u,f=i?0:c,y=i?0:u;let S=r[f][y]??null;n?F(S)&&this.engine&&(S=this.engine.shiftFormula(S,h-n.rows[f],d-(n.col+y))):S=as(String(S??""),this.metaAt(h,d)),a.push(this.change(h,d,S))}}this.applyChanges(a,"paste"),this.selectCell(e.start.row,e.start.col,e.start.row+o-1,e.start.col+l-1)}autofill(t,e){const n=e.start.row>t.end.row?"down":e.end.row<t.start.row?"up":e.start.col>t.end.col?"right":"left",r=n==="down"||n==="up",i=r?e.end.row-e.start.row+1:e.end.col-e.start.col+1;n==="down"&&this.ensureVisualRows(e.end.row+1),n==="right"&&this.ensureSize(this.data.length,e.end.col+1);const o=[],[l,a]=r?[t.start.col,t.end.col]:[t.start.row,t.end.row];for(let h=l;h<=a;h++){let u=[];for(let x=r?t.start.row:t.start.col;x<=(r?t.end.row:t.end.col);x++)u.push(x);(n==="up"||n==="left")&&(u=u.reverse());const d=Array.from({length:i},(x,g)=>n==="down"?t.end.row+1+g:n==="up"?t.start.row-1-g:n==="right"?t.end.col+1+g:t.start.col-1-g),f=x=>r?{p:this.mapper.toPhysical(x),c:h}:{p:this.mapper.toPhysical(h),c:x},y=[...u,...d],S=fr(u.map(x=>{const{p:g,c:p}=f(x);return this.rawAt(g,p)}),i,(x,g,p)=>{if(!this.engine)return x;const b=f(y[g]),C=f(y[p]);return this.engine.shiftFormula(x,C.p-b.p,C.c-b.c)});d.forEach((x,g)=>{const{p,c:b}=f(x);o.push(this.change(p,b,S[g]))})}this.applyChanges(o,"autofill");const c=bs(t,e);this.selectCell(c.start.row,c.start.col,c.end.row,c.end.col),this.run("afterAutofill",t,e)}render(){di(this.frame),this.frame=0,this.layout();const t=this.viewport(),{corner:e,top:n,left:r,main:i}=this.panes,o=[0,this.frozenRows-1],l=[0,this.frozenCols-1];this.renderPane(e,o,l),this.renderPane(n,o,[t.c0,t.c1]),this.renderPane(r,[t.r0,t.r1],l),this.renderPane(i,[t.r0,t.r1],[t.c0,t.c1]),this.editing||this.placeInput()}destroy(){var t,e,n;(t=this.closeMenu)==null||t.call(this),clearTimeout(this.announceTimer),this.cleanup.forEach(r=>r()),(e=this.engine)==null||e.off("valuesUpdated",this.onValuesUpdated),this.ownsEngine&&((n=this.engine)==null||n.destroy()),this.root.remove()}valueAt(t,e){var n;return this.engine?this.engine.getCellValue({row:t,col:e,sheet:this.sheet}):et((n=this.data[t])==null?void 0:n[e])}rawAt(t,e){var n;return this.engine?t<this.data.length?this.engine.getCellSerialized({row:t,col:e,sheet:this.sheet}):null:((n=this.data[t])==null?void 0:n[e])??null}metaAt(t,e){var l,a;const n=this.columnMeta[e],r=(a=(l=this.opts).cells)==null?void 0:a.call(l,t,e),i=this.cellMeta.size?this.cellMeta.get(N(t,e)):void 0;if(!r&&!i)return n??{};const o={...n,...r,...i};return(n!=null&&n.style||r!=null&&r.style||i!=null&&i.style)&&(o.style={...n==null?void 0:n.style,...r==null?void 0:r.style,...i==null?void 0:i.style}),o}displayText(t,e,n=this.valueAt(t,e)){return ls(n,this.metaAt(t,e),this.opts.locale).text}passes(t,e){for(const[n,r]of e){const i=this.valueAt(t,n);if(!ms(i,this.displayText(t,n,i),r))return!1}return!0}change(t,e,n){var i;const r=(i=this.binding)==null?void 0:i.fields[e];return{row:this.mapper.toVisual(t),physicalRow:t,col:e,...r?{prop:r}:{},oldValue:this.rawAt(t,e),newValue:n}}isReadOnly(t,e){return!!this.opts.readOnly||!!this.metaAt(t,e).readOnly}applyChanges(t,e,n=!0){var l,a;const r=e!=="api"&&e!=="undo"&&e!=="redo";if(r&&(t=t.filter(c=>!this.isReadOnly(c.physicalRow,c.col))),!t.length||this.run("beforeChange",t,e)===!1||r&&(t=t.filter(c=>{const h=this.metaAt(c.physicalRow,c.col);return h.allowInvalid!==!1||F(c.newValue)?!0:!cs(et(c.newValue),c.newValue,h,c.physicalRow,c.col)}),!t.length))return;const i=Bt(t,c=>c.physicalRow),o=Bt(t,c=>c.col);this.ensureSize(i+1,o+1);for(const c of t)this.data[c.physicalRow][c.col]=c.newValue??null,this.computedBinding()&&F(c.newValue)||(l=this.binding)==null||l.write(c.physicalRow,c.col,c.newValue??null);(a=this.engine)==null||a.batch(()=>{for(const c of t)this.engine.setCellContents({row:c.physicalRow,col:c.col,sheet:this.sheet},c.newValue??null)});for(const c of t)this.revalidate(c.physicalRow,c.col);n&&(this.undoStack.push({kind:"cells",changes:t}),this.redoStack=[]),this.render(),this.run("afterChange",t,e)}clearRange(t,e){const n=[];for(let r=t.start.row;r<=t.end.row;r++){const i=this.mapper.toPhysical(r);for(let o=t.start.col;o<=t.end.col;o++)pe(this.rawAt(i,o))||n.push(this.change(i,o,null))}this.applyChanges(n,e)}replay(t,e,n){const r=t.pop();if(r){if(r.kind==="meta")this.applyMeta(r.changes,n==="undo"?"before":"after"),this.render();else if(r.kind==="cells"){const i=r.changes.map(o=>n==="undo"?{...o,oldValue:o.newValue,newValue:o.oldValue}:{...o});this.applyChanges(i,n,!1)}else{const i=this.snapshot();this.bindingPaused=!0,n==="undo"?[...r.ops].reverse().forEach(o=>this.undoEngineOp(o)):r.ops.forEach(o=>this.applyEngineOp(o)),this.bindingPaused=!1,this.restore(r.state),this.syncBoundObjects(),r.state=i}e.push(r)}}applyMeta(t,e){for(const n of t){const r=n[e];r?this.cellMeta.set(n.key,r):this.cellMeta.delete(n.key)}}applyEngineOp(t){const e=this.engine;e&&(t.target!==void 0?e.moveColumns(t.index,t.count,t.target,this.sheet):t.remove?(t.record=e.captureRemoval(t.axis,t.index,t.count,this.sheet),t.axis==="row"?e.removeRows(t.index,t.count,this.sheet):e.removeColumns(t.index,t.count,this.sheet)):t.axis==="row"?e.addRows(t.index,t.count,this.sheet):e.addColumns(t.index,t.count,this.sheet))}undoEngineOp(t){const e=this.engine;if(e)if(t.target!==void 0){const n=e.inverseMove(t.index,t.count,t.target);e.moveColumns(n.start,n.count,n.target,this.sheet)}else t.remove?e.restoreRemoval(t.record):t.axis==="row"?e.removeRows(t.index,t.count,this.sheet):e.removeColumns(t.index,t.count,this.sheet)}snapshot(){var t;return{data:this.data.map(e=>[...e]),binding:(t=this.binding)==null?void 0:t.snapshot(),colSizes:Array.from({length:this.cols.count},(e,n)=>this.cols.size(n)),rows:this.mapper.snapshot(),merges:this.getMergedCells(),columns:[...this.columnMeta],labels:this.labels&&[...this.labels],filters:[...this.filters].map(([e,n])=>[e,{...n}]),sort:this.sortState&&{...this.sortState},cellMeta:[...this.cellMeta],rowHeights:[...this.rowHeights],hidden:[...this.hiddenCols]}}restore(t){var e;this.data=t.data.map(n=>[...n]),t.binding&&((e=this.binding)==null||e.restore(t.binding)),this.mapper.restore(t.rows),this.syncRows(),this.cols=new Lt(t.colSizes.length,this.cols.defaultSize,t.colSizes),this.merges.set(t.merges),this.columnMeta=[...t.columns],this.labels=t.labels&&[...t.labels],this.filters=new Map(t.filters),this.sortState=t.sort,this.cellMeta=new Map(t.cellMeta),this.rowHeights=new Map(t.rowHeights),this.hiddenCols=new Map(t.hidden),this.syncRows(),this.frozenCols=Math.min(this.frozenCols,this.countCols()),this.validateAll(),this.clampSelection(),this.render()}alterRows(t,e,n,r){var i,o;if(n){const l=Array.from({length:e},(a,c)=>this.mapper.toPhysical(t+c)).sort((a,c)=>c-a);for(const a of l)this.data.splice(a,1),(i=this.binding)==null||i.removeRows(a,1),this.mapper.remove(a,1),this.shiftRowState(a,-1),this.applyEngineOp(Ft(r,{axis:"row",index:a,count:1,remove:!0}));this.merges.shift("row",t,-e)}else{const l=t<this.countRows()?this.mapper.toPhysical(t):this.data.length;this.data.splice(l,0,...Array.from({length:e},()=>Array(this.countCols()).fill(null))),(o=this.binding)==null||o.insertRows(l,e),this.mapper.insert(l,e,t),this.shiftRowState(l,e),this.applyEngineOp(Ft(r,{axis:"row",index:l,count:e,remove:!1})),this.merges.shift("row",t,e)}this.syncRows()}shiftRowState(t,e){this.cellMeta=Ct(this.cellMeta,n=>{const r=Wt(Math.floor(n/16384),t,e);return r<0?-1:r*16384+n%16384}),this.rowHeights=Ct(this.rowHeights,n=>Wt(n,t,e))}alterCols(t,e,n,r){var l,a,c,h;for(const u of this.data)n?u.splice(t,e):u.splice(t,0,...Array(e).fill(null));n?(l=this.binding)==null||l.removeCols(t,e):(a=this.binding)==null||a.insertCols(t,e),n?(this.cols.remove(t,e),this.applyEngineOp(Ft(r,{axis:"col",index:t,count:e,remove:!0})),this.columnMeta.splice(t,e),(c=this.labels)==null||c.splice(t,e)):(this.cols.insert(t,e),this.applyEngineOp(Ft(r,{axis:"col",index:t,count:e,remove:!1})),t<this.columnMeta.length&&this.columnMeta.splice(t,0,...Array(e)),(h=this.labels)==null||h.splice(t,0,...Array(e).fill("")));const i=u=>n?u>=t+e?u-e:u>=t?-1:u:u>=t?u+e:u;if(this.filters=new Map([...this.filters].map(([u,d])=>[i(u),d]).filter(([u])=>u>=0)),this.sortState){const u=i(this.sortState.col);this.sortState=u>=0?{...this.sortState,col:u}:null}this.merges.shift("col",t,n?-e:e),this.frozenCols=Math.min(this.frozenCols,this.countCols());const o=n?-e:e;this.cellMeta=Ct(this.cellMeta,u=>{const d=Wt(u%16384,t,o);return d<0?-1:u-u%16384+d}),this.hiddenCols=Ct(this.hiddenCols,u=>Wt(u,t,o))}ensureSize(t,e){var n;if(e>this.countCols()){for(const r of this.data)for(;r.length<e;)r.push(null);this.cols.resize(e)}if(t>this.data.length){const r=t-this.data.length;for(let i=0;i<r;i++)this.data.push(Array(this.countCols()).fill(null));(n=this.binding)==null||n.ensureRows(this.data.length),this.mapper.insert(this.data.length-r,r),this.syncRows()}}ensureVisualRows(t){t>this.countRows()&&this.ensureSize(this.data.length+t-this.countRows(),this.countCols())}bind(t){return en(t)?(this.binding=ee.create(t,this.columnMeta.map(e=>e==null?void 0:e.data),this.opts.dataSchema),this.binding.toRows()):(this.binding=void 0,t)}normalize(t){const e=t.length===0,n=Math.max(t.length,this.opts.minRows??(e?50:0)),r=Math.max(Bt(t,i=>i.length),this.opts.minCols??(e?26:0),this.columnMeta.length,1);return Array.from({length:n},(i,o)=>Array.from({length:r},(l,a)=>{var c;return((c=t[o])==null?void 0:c[a])??null}))}syncRows(){const t=this.mapper.count;if(!this.rowsCustomized){this.rows.resize(t);return}const e=this.rows.defaultSize,n=Array.from({length:t},(r,i)=>this.rowHeights.get(this.mapper.toPhysical(i))??e);this.rows=new Lt(t,e,n),this.rowsCustomized=this.rowHeights.size>0}afterRowMapping(){this.syncRows(),this.clampSelection(),this.render()}revalidate(t,e){const n=this.metaAt(t,e),r=N(t,e),i=this.invalid.get(r),o=le(n)?cs(this.valueAt(t,e),this.rawAt(t,e),n,t,e):void 0;o?this.invalid.set(r,o):this.invalid.delete(r),o!==i&&this.run("afterValidate",this.mapper.toVisual(t),e,o)}validateAll(){this.invalid.clear();const t=Array.from({length:this.countCols()},(n,r)=>r),e=this.opts.cells?t:t.filter(n=>this.columnMeta[n]&&le(this.columnMeta[n]));for(let n=0;n<this.data.length;n++)for(const r of e)this.revalidate(n,r);for(const n of this.cellMeta.keys())this.revalidate(Math.floor(n/16384),n%16384)}computedBinding(){return!!this.binding&&!!this.engine&&this.opts.bindFormulas!=="text"}boundValueAt(t,e){const n=this.rawAt(t,e);if(!this.computedBinding()||!(n===null||F(n)))return n;const r=this.valueAt(t,e);return r instanceof rt?null:r}writeComputed(t,e,n){if(!this.computedBinding())return;const r=this.boundValueAt(t,e);(F(this.rawAt(t,e))||r!==null||n&&this.rawAt(t,e)===null)&&this.binding.write(t,e,r)}syncBoundObjects(){if(this.computedBinding())for(let t=0;t<this.data.length;t++)for(let e=0;e<this.data[t].length;e++)this.writeComputed(t,e,!1)}run(t,...e){let n=!0;for(const r of this.hooks.get(t)??[])r(...e)===!1&&(n=!1);return n}mergesActive(){return this.merges.list.length>0&&this.mapper.isIdentity}mergeAt(t,e){return this.mergesActive()?this.merges.get(t,e):void 0}mergeAllowed(t){const e=(n,r,i)=>i>0&&n<i&&n+r>i;return this.mapper.isIdentity&&t.row>=0&&t.col>=0&&t.row+t.rowspan<=this.data.length&&t.col+t.colspan<=this.countCols()&&!e(t.row,t.rowspan,this.frozenRows)&&!e(t.col,t.colspan,this.frozenCols)}el(t,e,n="div"){const r=this.root.ownerDocument.createElement(n);return r.className=t,e.appendChild(r),r}makePane(t,e,n,r){const i=this.el(`ct-pane ${t}`,e);return{el:i,frozenRows:n,frozenCols:r,cells:new Map,pool:[],colHeads:[],rowHeads:[],rangeBox:this.el("ct-range",i),fillBox:this.el("ct-fill-area",i),activeBox:this.el("ct-active",i),handle:this.el("ct-fill",i)}}buildDom(){this.canvas=this.el("ct-canvas",this.root),this.topBand=this.el("ct-band ct-band-top",this.canvas),this.bodyBand=this.el("ct-band ct-band-body",this.canvas),this.panes={corner:this.makePane("ct-pane-corner",this.topBand,!0,!0),top:this.makePane("ct-pane-top",this.topBand,!0,!1),left:this.makePane("ct-pane-left",this.bodyBand,!1,!0),main:this.makePane("ct-pane-main",this.bodyBand,!1,!1)},this.cornerHead=this.el("ct-header ct-cornerhead",this.panes.corner.el),this.announcer=this.el("ct-sr",this.root),this.announcer.setAttribute("aria-live","polite"),this.announcer.setAttribute("aria-atomic","true"),this.input=this.root.ownerDocument.createElement("textarea"),this.input.className="ct-editor ct-idle",this.input.setAttribute("aria-label","Cell editor"),this.input.spellcheck=!1,this.input.addEventListener("keydown",this.onEditorKey),this.input.addEventListener("input",this.onInput),this.input.addEventListener("compositionstart",()=>this.openEditor("")),this.input.addEventListener("blur",()=>this.closeEditor(!0)),this.panes.main.el.appendChild(this.input)}resetHeaders(){for(const t of Object.values(this.panes))t.colHeads.forEach(e=>e.remove()),t.colHeads=[]}frozenSize(){return{fw:this.cols.offset(this.frozenCols),fh:this.rows.offset(this.frozenRows)}}layout(){const t=this.cols.total,e=this.rows.total,{fw:n,fh:r}=this.frozenSize(),i=(o,l,a)=>{o.style.width=`${Math.max(0,l)}px`,o.style.height=`${Math.max(0,a)}px`};i(this.canvas,this.rowHeaderW+t,this.headerH+e),i(this.topBand,this.rowHeaderW+t,this.headerH+r),this.topBand.style.display=this.headerH+r>0?"":"none",i(this.bodyBand,this.rowHeaderW+t,e-r),i(this.panes.corner.el,this.rowHeaderW+n,this.headerH+r),i(this.panes.top.el,t-n,this.headerH+r),i(this.panes.left.el,this.rowHeaderW+n,e-r),i(this.panes.main.el,t-n,e-r),this.panes.corner.el.classList.toggle("ct-edge-r",n>0),this.panes.left.el.classList.toggle("ct-edge-r",n>0),this.panes.corner.el.classList.toggle("ct-edge-b",r>0),this.panes.top.el.classList.toggle("ct-edge-b",r>0),this.root.setAttribute("aria-rowcount",String(this.countRows()+(this.headerH?1:0))),this.root.setAttribute("aria-colcount",String(this.countCols()+(this.rowHeaderW?1:0))),ft(this.cornerHead,0,0,this.rowHeaderW,this.headerH),this.cornerHead.style.display=this.rowHeaderW&&this.headerH?"":"none"}cellX(t,e){return(t.frozenCols?this.rowHeaderW:0)+this.cols.offset(e)-(t.frozenCols?0:this.cols.offset(this.frozenCols))}cellY(t,e){return(t.frozenRows?this.headerH:0)+this.rows.offset(e)-(t.frozenRows?0:this.rows.offset(this.frozenRows))}viewport(){const{fw:t,fh:e}=this.frozenSize(),n=this.root.scrollTop+e,r=this.root.scrollLeft+t,i=(this.root.clientHeight||600)-this.headerH-e,o=(this.root.clientWidth||1e3)-this.rowHeaderW-t;return{r0:Math.max(this.frozenRows,this.rows.indexAt(n)-Xt),r1:Math.min(this.countRows()-1,this.rows.indexAt(n+i)+Xt),c0:Math.max(this.frozenCols,this.cols.indexAt(r)-Xt),c1:Math.min(this.countCols()-1,this.cols.indexAt(r+o)+Xt)}}paneOf(t,e){const n=t<this.frozenRows,r=e<this.frozenCols;return n?r?this.panes.corner:this.panes.top:r?this.panes.left:this.panes.main}renderPane(t,[e,n],[r,i]){const o=[];if(n>=e&&i>=r){const c=new Set;for(let h=e;h<=n;h++)for(let u=r;u<=i;u++){if(this.hiddenCols.size&&this.hiddenCols.has(u))continue;const d=this.mergeAt(h,u);if(d&&(d.row!==h||d.col!==u)){(d.row<e||d.col<r)&&c.add(d);continue}o.push([h,u,d])}for(const h of c)o.push([h.row,h.col,h])}const l=new Set(o.map(([c,h])=>N(c,h)));for(const[c,h]of t.cells)l.has(c)||t.pool.push(h);const a=new Map;for(const[c,h,u]of o){const d=N(c,h),f=t.cells.get(d)??t.pool.pop()??this.makeCell(t);a.set(d,f);const y=u?this.cols.offset(h+u.colspan)-this.cols.offset(h):this.cols.size(h),S=u?this.rows.offset(c+u.rowspan)-this.rows.offset(c):this.rows.size(c);this.paintCell(f,c,h),ft(f,this.cellX(t,h),this.cellY(t,c),y,S),f.style.display=""}for(const c of t.pool)c.style.display="none";t.cells=a,this.renderHeaders(t,[e,n],[r,i]),this.renderSelection(t)}makeCell(t){const e=this.el("ct-cell",t.el);return e.setAttribute("role","gridcell"),e}paintCell(t,e,n){var g;const r=this.mapper.toPhysical(e),i=this.metaAt(r,n),o=this.valueAt(r,n),{text:l,kind:a}=ls(o,i,this.opts.locale);let c=a?`ct-cell ct-${a}`:"ct-cell";i.type==="dropdown"&&(c+=" ct-dd"),i.readOnly&&(c+=" ct-readonly");const h=this.invalid.size?this.invalid.get(N(r,n)):void 0;h&&(c+=" ct-invalid"),i.className&&(c+=` ${i.className}`);const u=this.conditionalStyle(r,n,o),d=u?{...i.style,...u}:i.style;d&&(c+=vr(d)),t.className!==c&&(t.className=c);const f=(d==null?void 0:d.color)??"";t.dataset.fg!==f&&(t.style.color=f,t.dataset.fg=f);const y=(d==null?void 0:d.background)??"";t.dataset.bg!==y&&(t.style.backgroundColor=y,t.dataset.bg=y);const S=String(e+(this.headerH?2:1)),x=String(n+(this.rowHeaderW?2:1));t.getAttribute("aria-rowindex")!==S&&t.setAttribute("aria-rowindex",S),t.getAttribute("aria-colindex")!==x&&t.setAttribute("aria-colindex",x),a==="check"?t.dataset.check!==l&&(t.textContent="",this.el("ct-checkbox",t,"span").textContent=l,t.dataset.check=l):(t.dataset.check!==void 0&&delete t.dataset.check,t.textContent!==l&&(t.textContent=l)),h?t.title=h:t.title&&(t.title=""),(g=i.renderer)==null||g.call(i,t,o,{row:e,col:n,meta:i})}conditionalStyle(t,e,n){const r=this.opts.conditionalFormats;if(!(r!=null&&r.length))return;let i;for(const o of r){if(!o.entireRow&&o.columns&&!o.columns.includes(e))continue;(o.entireRow?o.columns??[]:[e]).some(c=>{const h=c===e?n:this.valueAt(t,c);return typeof o.when=="function"?o.when(h,this.mapper.toVisual(t),c):ms(h,this.displayText(t,c,h),{condition:o.when})})&&(i={...i,...o.style})}return i}renderHeaders(t,[e,n],[r,i]){var l,a,c,h;const o=this.getSelectedRange();if(t.frozenRows&&this.headerH){let u=0;for(let d=r;d<=i;d++){if(this.hiddenCols.size&&this.hiddenCols.has(d))continue;const f=t.colHeads[u]??this.makeColHeader(t,u);u++,f.classList.toggle("ct-gap-r",this.hiddenCols.has(d+1)),f.classList.toggle("ct-gap-l",d>0&&this.hiddenCols.has(d-1)),f.setAttribute("aria-colindex",String(d+(this.rowHeaderW?2:1))),f.dataset.col=String(d);const y=((l=this.labels)==null?void 0:l[d])||((a=this.columnMeta[d])==null?void 0:a.title)||((c=this.binding)==null?void 0:c.fields[d])||Rt(d),S=f.children[0];S.textContent!==y&&(S.textContent=y);const x=((h=this.sortState)==null?void 0:h.col)===d?this.sortState.order==="asc"?"▲":"▼":"",g=f.children[1];g.textContent!==x&&(g.textContent=x),f.classList.toggle("ct-hl",!!o&&d>=o.start.col&&d<=o.end.col),f.classList.toggle("ct-filtered",this.filters.has(d)),ft(f,this.cellX(t,d),0,this.cols.size(d),this.headerH),f.style.display=""}for(;u<t.colHeads.length;u++)t.colHeads[u].style.display="none"}if(t.frozenCols&&this.rowHeaderW){let u=0;for(let d=e;d<=n;d++,u++){const f=t.rowHeads[u]??this.makeRowHeader(t,u);f.dataset.row=String(d);const y=String(this.mapper.toPhysical(d)+1),S=f.children[0];S.textContent!==y&&(S.textContent=y),f.setAttribute("aria-rowindex",String(d+(this.headerH?2:1))),f.classList.toggle("ct-hl",!!o&&d>=o.start.row&&d<=o.end.row),ft(f,0,this.cellY(t,d),this.rowHeaderW,this.rows.size(d)),f.style.display=""}for(;u<t.rowHeads.length;u++)t.rowHeads[u].style.display="none"}}makeRowHeader(t,e){const n=this.el("ct-header ct-rowhead",t.el);return n.setAttribute("role","rowheader"),this.el("ct-label",n,"span"),this.el("ct-rresize",n),t.rowHeads[e]=n,n}makeColHeader(t,e){const n=this.el("ct-header ct-colhead",t.el);if(n.setAttribute("role","columnheader"),this.el("ct-label",n,"span"),this.el("ct-sort",n,"span"),this.opts.columnSorting||this.opts.filters){const r=this.el("ct-menu-btn",n,"button");r.type="button",r.tabIndex=-1,r.textContent="▾",r.setAttribute("aria-label",this.messages.columnMenu)}return this.el("ct-resize",n),t.colHeads[e]=n,n}boxFor(t,e){const n=Math.max(e.start.row,t.frozenRows?0:this.frozenRows),r=Math.min(e.end.row,t.frozenRows?this.frozenRows-1:this.countRows()-1),i=Math.max(e.start.col,t.frozenCols?0:this.frozenCols),o=Math.min(e.end.col,t.frozenCols?this.frozenCols-1:this.countCols()-1);if(n>r||i>o)return null;const l=this.cellX(t,i),a=this.cellY(t,n);return[l-1,a-1,this.cellX(t,o+1)-l+1,this.cellY(t,r+1)-a+1]}renderSelection(t){const e=this.getSelectedRange(),n=(...c)=>c.forEach(h=>h.style.display="none");if(!e||!this.anchor){n(t.rangeBox,t.activeBox,t.handle,t.fillBox);return}const r=(c,h)=>{if(!h)return n(c);ft(c,...h),c.style.display=""},i=this.mergeAt(this.anchor.row,this.anchor.col),o=i?{start:{row:i.row,col:i.col},end:{row:i.row+i.rowspan-1,col:i.col+i.colspan-1}}:{start:this.anchor,end:this.anchor},l=e.start.row!==o.start.row||e.start.col!==o.start.col||e.end.row!==o.end.row||e.end.col!==o.end.col;r(t.rangeBox,l?this.boxFor(t,e):null),r(t.activeBox,this.boxFor(t,o)),r(t.fillBox,this.fillTarget?this.boxFor(t,bs(e,this.fillTarget.range)):null),this.opts.fillHandle!==!1&&!this.opts.readOnly&&!this.editing&&this.paneOf(e.end.row,e.end.col)===t?(ft(t.handle,this.cellX(t,e.end.col+1)-4,this.cellY(t,e.end.row+1)-4,7,7),t.handle.style.display=""):n(t.handle)}scheduleRender(){this.frame||(this.frame=ui(()=>{this.frame=0,this.render()}))}scrollIntoView({row:t,col:e}){const{fw:n,fh:r}=this.frozenSize(),i=this.root.clientHeight-this.headerH,o=this.root.clientWidth-this.rowHeaderW;if(!(i<=0||o<=0)){if(t>=this.frozenRows){const l=this.rows.offset(t),a=l+this.rows.size(t);l-r<this.root.scrollTop?this.root.scrollTop=l-r:a>this.root.scrollTop+i&&(this.root.scrollTop=a-i)}if(e>=this.frozenCols){const l=this.cols.offset(e),a=l+this.cols.size(e);l-n<this.root.scrollLeft?this.root.scrollLeft=l-n:a>this.root.scrollLeft+o&&(this.root.scrollLeft=a-o)}}}clampSelection(){if(!this.anchor||!this.selEnd)return;if(!this.countRows()||!this.countCols()){this.anchor=this.selEnd=null;return}const t=e=>({row:Math.min(e.row,this.countRows()-1),col:Math.min(e.col,this.countCols()-1)});this.anchor=t(this.anchor),this.selEnd=t(this.selEnd)}cellAtClient(t,e){const n=this.root.getBoundingClientRect(),{fw:r,fh:i}=this.frozenSize(),o=t-n.left-this.root.clientLeft-this.rowHeaderW,l=e-n.top-this.root.clientTop-this.headerH,a=o<r?Math.max(0,o):o+this.root.scrollLeft,c=l<i?Math.max(0,l):l+this.root.scrollTop;return{row:this.rows.indexAt(c),col:this.cols.indexAt(a)}}isEditing(){return this.editing}openEditor(t){if(!this.anchor||this.editing)return;const e=this.mapper.toPhysical(this.anchor.row),n=this.metaAt(e,this.anchor.col);if(this.isReadOnly(e,this.anchor.col)||n.type==="checkbox"){this.input.value="";return}const r=this.input;this.editing=!0,this.editorEnterMode=t!==void 0,r.value=t??br(this.rawAt(e,this.anchor.col),n,this.opts.locale),r.classList.remove("ct-idle"),this.placeInput(),this.autoSizeInput(),this.focusInput(),r.setSelectionRange(r.value.length,r.value.length),n.type==="dropdown"&&n.source&&this.showDropdown(n.source,t!==void 0?r.value:""),this.render()}closeEditor(t){if(!this.editing||!this.anchor)return;this.editing=!1,this.hideDropdown();const e=this.mapper.toPhysical(this.anchor.row),n=this.anchor.col,r=this.input.value;if(this.input.value="",this.input.classList.add("ct-idle"),t){const i=as(r,this.metaAt(e,n));i!==this.rawAt(e,n)&&this.applyChanges([this.change(e,n,i)],"edit")}this.render()}focusInput(){this.root.ownerDocument.activeElement!==this.input&&this.input.focus({preventScroll:!0})}placeInput(){if(!this.anchor)return;const{row:t,col:e}=this.anchor,n=this.paneOf(t,e);if(this.input.parentElement!==n.el){const l=this.root.ownerDocument.activeElement===this.input;n.el.appendChild(this.input),l&&this.input.focus({preventScroll:!0})}const r=this.mergeAt(t,e),i=r?this.cols.offset(e+r.colspan)-this.cols.offset(e):this.cols.size(e),o=r?this.rows.offset(t+r.rowspan)-this.rows.offset(t):this.rows.size(t);ft(this.input,this.cellX(n,e)-1,this.cellY(n,t)-1,i+2,o+2),this.input.style.minWidth=this.editing?`${i+2}px`:""}autoSizeInput(){if(!this.editing||!this.anchor)return;const t=this.input,e=this.cols.size(this.anchor.col)+2;t.style.width="0",t.style.width=`${Math.max(e,t.scrollWidth+4)}px`}showDropdown(t,e){this.hideDropdown();const n=this.el("ct-dd-list",this.input.parentElement);n.setAttribute("role","listbox"),n.addEventListener("mousedown",r=>{r.preventDefault();const i=r.target.closest("[data-i]");!i||!this.dropdown||(this.input.value=this.dropdown.items[Number(i.dataset.i)],this.commitAndMove(1,0))}),this.dropdown={el:n,items:[],active:-1},n.style.left=this.input.style.left,n.style.top=`${parseFloat(this.input.style.top)+parseFloat(this.input.style.height)}px`,n.style.minWidth=this.input.style.width,this.filterDropdown(e,t)}filterDropdown(t,e){const n=this.dropdown;if(!n||!this.anchor)return;const r=e??this.metaAt(this.mapper.toPhysical(this.anchor.row),this.anchor.col).source??[],i=t.toLowerCase();n.items=r.filter(o=>o.toLowerCase().includes(i)),n.active=i&&n.items.length?0:-1,n.el.textContent="",n.items.forEach((o,l)=>{const a=this.el("ct-dd-item",n.el);a.dataset.i=String(l),a.setAttribute("role","option"),a.textContent=o}),this.highlightDropdown()}highlightDropdown(){var e,n;const t=this.dropdown;t&&([...t.el.children].forEach((r,i)=>r.classList.toggle("ct-on",i===t.active)),(n=(e=t.el.children[t.active])==null?void 0:e.scrollIntoView)==null||n.call(e,{block:"nearest"}))}hideDropdown(){var t;(t=this.dropdown)==null||t.el.remove(),this.dropdown=void 0}commitAndMove(t,e){this.closeEditor(!0),this.moveActive(t,e,!1)}listen(t,e,n){t.addEventListener(e,n),this.cleanup.push(()=>t.removeEventListener(e,n))}bindEvents(){const t=this.root.ownerDocument;this.listen(this.root,"scroll",()=>{this.dropdown&&this.closeEditor(!0),this.scheduleRender()}),this.listen(this.root,"keydown",r=>this.onKeyDown(r)),this.listen(this.canvas,"mousedown",r=>this.onMouseDown(r)),this.listen(this.canvas,"dblclick",r=>this.onDoubleClick(r)),this.listen(this.canvas,"contextmenu",r=>this.onContextMenu(r)),this.listen(t,"mousemove",r=>this.onDrag(r)),this.listen(t,"mouseup",()=>this.onMouseUp());const e=()=>this.root.contains(t.activeElement)&&!this.editing,n=r=>i=>{var l;if(!e())return;const o=this.copy(r);o!==void 0&&((l=i.clipboardData)==null||l.setData("text/plain",o),i.preventDefault())};this.listen(t,"copy",n(!1)),this.listen(t,"cut",n(!0)),this.listen(t,"paste",r=>{var o;if(!e())return;const i=(o=r.clipboardData)==null?void 0:o.getData("text/plain");i&&(r.preventDefault(),this.paste(i))})}onMouseDown(t){const e=t.target;if(this.editing&&e===this.input||e.closest(".ct-dd-list")||t.button!==0)return;t.preventDefault(),this.editing&&this.closeEditor(!0),this.focusInput();const n=e.closest(".ct-menu-btn");if(n)return this.openMenu(Number(n.parentElement.dataset.col),n);const r=e.closest(".ct-resize");if(r)return this.startResize(Number(r.parentElement.dataset.col),t.clientX);const i=e.closest(".ct-rresize");if(i)return this.startRowResize(Number(i.parentElement.dataset.row),t.clientY);if(e.closest(".ct-fill")){this.dragging="fill";return}if(e.closest(".ct-cornerhead"))return this.selectCell(0,0,this.countRows()-1,this.countCols()-1);const o=e.closest(".ct-colhead");if(o){const c=Number(o.dataset.col),h=this.getSelectedRange(),u=!!h&&h.start.row===0&&h.end.row===this.countRows()-1;if(!t.shiftKey&&u&&c>=h.start.col&&c<=h.end.col&&!this.opts.readOnly){this.dragging="move",this.moveDrop=null;return}this.selectCell(0,t.shiftKey&&this.anchor?this.anchor.col:c,this.countRows()-1,c),this.dragging="cols";return}const l=e.closest(".ct-rowhead");if(l){const c=Number(l.dataset.row);this.selectCell(t.shiftKey&&this.anchor?this.anchor.row:c,0,c,this.countCols()-1),this.dragging="rows";return}const a=this.cellAtClient(t.clientX,t.clientY);if(e.closest(".ct-checkbox")){this.selectCell(a.row,a.col),this.toggleCheckboxes({start:a,end:a});return}t.shiftKey&&this.anchor?this.selectCell(this.anchor.row,this.anchor.col,a.row,a.col):this.selectCell(a.row,a.col),this.dragging="cells"}onContextMenu(t){if(!this.opts.contextMenu)return;t.preventDefault(),this.editing&&this.closeEditor(!0);const e=t.target,n=this.getSelectedRange(),r=(l,a)=>!!n&&l>=n.start.row&&l<=n.end.row&&a>=n.start.col&&a<=n.end.col,i=e.closest(".ct-colhead"),o=e.closest(".ct-rowhead");if(i){const l=Number(i.dataset.col),a=!!n&&n.start.row===0&&n.end.row===this.countRows()-1;(!r(0,l)||!a)&&this.selectCell(0,l,this.countRows()-1,l)}else if(o){const l=Number(o.dataset.row),a=!!n&&n.start.col===0&&n.end.col===this.countCols()-1;(!r(l,0)||!a)&&this.selectCell(l,0,l,this.countCols()-1)}else if(!e.closest(".ct-cornerhead")){const l=this.cellAtClient(t.clientX,t.clientY);r(l.row,l.col)||this.selectCell(l.row,l.col)}this.focusInput(),this.openContextMenu(t.clientX,t.clientY)}onDoubleClick(t){const e=t.target;if(e.closest(".ct-fill"))return this.fillToDataEnd();e.closest(".ct-header")||e.closest(".ct-checkbox")||e.closest(".ct-dd-list")||this.editing||this.openEditor()}onDrag(t){if(!this.dragging||!this.anchor)return;const e=this.cellAtClient(t.clientX,t.clientY);this.dragging==="cells"?this.selectCell(this.anchor.row,this.anchor.col,e.row,e.col):this.dragging==="rows"?this.selectCell(this.anchor.row,0,e.row,this.countCols()-1):this.dragging==="cols"?this.selectCell(0,this.anchor.col,this.countRows()-1,e.col):this.dragging==="move"?this.updateMoveDrop(t.clientX):this.updateFillTarget(e)}onMouseUp(){var e;if(this.dragging==="move"){const n=this.moveDrop;this.moveDrop=null,this.dragging=null,(e=this.dropLine)==null||e.remove(),this.dropLine=void 0,n&&this.moveColumns(n.start,n.count,n.target);return}const t=this.fillTarget;this.fillTarget=null,this.dragging==="fill"&&t?this.autofill(this.getSelectedRange(),t.range):t&&this.render(),this.dragging=null}updateMoveDrop(t){const e=this.getSelectedRange(),n=this.root.getBoundingClientRect(),{fw:r}=this.frozenSize(),i=t-n.left-this.root.clientLeft-this.rowHeaderW,o=i<r?Math.max(0,i):i+this.root.scrollLeft,l=this.cols.indexAt(o),a=o-this.cols.offset(l)>this.cols.size(l)/2?l+1:l,c=e.end.col-e.start.col+1,h=this.canMoveColumns(e.start.col,c,a);this.moveDrop=h?{start:e.start.col,count:c,target:a}:null,this.dropLine||(this.dropLine=this.el("ct-drop",this.root));const u=this.rowHeaderW+this.cols.offset(a)-(a>=this.frozenCols?this.root.scrollLeft:0);this.dropLine.style.display=h?"":"none",this.dropLine.style.left=`${this.root.scrollLeft+u-1}px`,this.dropLine.style.top=`${this.root.scrollTop}px`,this.dropLine.style.height=`${this.root.clientHeight}px`}updateFillTarget(t){const e=this.getSelectedRange(),n=t.row-e.end.row,r=e.start.row-t.row,i=t.col-e.end.col,o=e.start.col-t.col,l=Math.max(n,r,i,o);let a=null;l>0&&(l===n?a={direction:"down",range:{start:{row:e.end.row+1,col:e.start.col},end:{row:t.row,col:e.end.col}}}:l===r?a={direction:"up",range:{start:{row:t.row,col:e.start.col},end:{row:e.start.row-1,col:e.end.col}}}:l===i?a={direction:"right",range:{start:{row:e.start.row,col:e.end.col+1},end:{row:e.end.row,col:t.col}}}:a={direction:"left",range:{start:{row:e.start.row,col:t.col},end:{row:e.end.row,col:e.start.col-1}}}),this.fillTarget=a,this.render()}fillToDataEnd(){const t=this.getSelectedRange();if(!t)return;const e=t.start.col>0?t.start.col-1:t.end.col+1;if(e>=this.countCols())return;let n=t.end.row;for(;n+1<this.countRows()&&!pe(this.getSourceDataAtCell(n+1,e));)n++;n>t.end.row&&this.autofill(t,{start:{row:t.end.row+1,col:t.start.col},end:{row:n,col:t.end.col}})}startResize(t,e){const n=this.root.ownerDocument,r=this.cols.size(t),i=l=>this.setColWidth(t,r+l.clientX-e),o=()=>{n.removeEventListener("mousemove",i),n.removeEventListener("mouseup",o)};n.addEventListener("mousemove",i),n.addEventListener("mouseup",o)}startRowResize(t,e){const n=this.root.ownerDocument,r=this.rows.size(t),i=l=>this.setRowHeight(t,r+l.clientY-e),o=()=>{n.removeEventListener("mousemove",i),n.removeEventListener("mouseup",o)};n.addEventListener("mousemove",i),n.addEventListener("mouseup",o)}openMenu(t,e){var o,l;(o=this.closeMenu)==null||o.call(this);const n=[...this.filters].filter(([a])=>a!==t),r=new Set;for(let a=this.mapper.pinnedCount;a<this.data.length;a++)this.passes(a,n)&&r.add(this.displayText(a,t));const i=[...r].sort((a,c)=>a===""?1:c===""?-1:a.localeCompare(c,this.opts.locale,{numeric:!0,sensitivity:"base"}));this.closeMenu=Cr({anchor:e,messages:this.messages,sort:((l=this.sortState)==null?void 0:l.col)===t?this.sortState.order:null,filter:this.filters.get(t),values:i,sortable:!!this.opts.columnSorting,filterable:!!this.opts.filters,onSort:a=>this.sort(t,a),onFilter:a=>this.setFilter(t,a),onClose:()=>{this.closeMenu=void 0,this.focusInput()}})}toggleCheckboxes(t){const e=[];for(let n=t.start.row;n<=t.end.row;n++){const r=this.mapper.toPhysical(n);for(let i=t.start.col;i<=t.end.col;i++)this.metaAt(r,i).type==="checkbox"&&e.push(this.change(r,i,this.valueAt(r,i)!==!0))}this.applyChanges(e,"edit")}moveActive(t,e,n){if(!this.anchor||!this.selEnd)return;const r=n?this.selEnd:this.anchor;let i=r.row,o=r.col;const l=this.mergeAt(r.row,r.col);l&&!n&&(t>0&&(i=l.row+l.rowspan-1),e>0&&(o=l.col+l.colspan-1)),i+=t,o+=e;const a=e<0?-1:1;for(;this.hiddenCols.has(o)&&o+a>=0&&o+a<this.countCols();)o+=a;this.hiddenCols.has(o)&&(o=r.col),n?this.selectCell(this.anchor.row,this.anchor.col,i,o):this.selectCell(i,o)}jump(t,e,n){const r=n?this.selEnd:this.anchor,i=this.countRows()-1,o=this.countCols()-1,l=(u,d)=>!pe(this.getSourceDataAtCell(u,d)),a=(u,d)=>u>=0&&d>=0&&u<=i&&d<=o;let c=r.row,h=r.col;if(a(c+t,h+e)&&l(c,h)&&l(c+t,h+e))for(;a(c+t,h+e)&&l(c+t,h+e);)c+=t,h+=e;else for(c+=t,h+=e;a(c,h)&&!l(c,h)&&a(c+t,h+e);)c+=t,h+=e;c=Math.max(0,Math.min(c,i)),h=Math.max(0,Math.min(h,o)),n?this.selectCell(this.anchor.row,this.anchor.col,c,h):this.selectCell(c,h)}onKeyDown(t){if(this.editing||!this.anchor||!this.selEnd)return;const e=t.ctrlKey||t.metaKey,n=t.key,r=this.metaAt(this.mapper.toPhysical(this.anchor.row),this.anchor.col);if(n==="ContextMenu"||t.shiftKey&&n==="F10"){this.opts.contextMenu&&(t.preventDefault(),this.openContextMenu());return}if(n in fe){t.preventDefault();const[i,o]=fe[n];if(t.altKey&&n==="ArrowDown"&&r.type==="dropdown")return this.openEditor();e?this.jump(i,o,t.shiftKey):this.moveActive(i,o,t.shiftKey);return}if(e){const i=n.toLowerCase();if(i==="b"||i==="i"||i==="u")t.preventDefault(),this.toggleCellStyle(i==="b"?"bold":i==="i"?"italic":"underline");else if(i==="a")t.preventDefault(),this.selectCell(0,0,this.countRows()-1,this.countCols()-1);else if(i==="z")t.preventDefault(),t.shiftKey?this.redo():this.undo();else if(i==="y")t.preventDefault(),this.redo();else if(i==="d"){t.preventDefault();const o=this.getSelectedRange();o.end.row>o.start.row&&this.autofill({start:o.start,end:{row:o.start.row,col:o.end.col}},{start:{row:o.start.row+1,col:o.start.col},end:o.end})}else n==="Home"?(t.preventDefault(),this.selectCell(0,0)):n==="End"&&(t.preventDefault(),this.selectCell(this.countRows()-1,this.countCols()-1));return}switch(n){case"Tab":t.preventDefault(),this.moveActive(0,t.shiftKey?-1:1,!1);return;case"Enter":case"F2":t.preventDefault(),r.type==="checkbox"?this.toggleCheckboxes(this.getSelectedRange()):this.openEditor();return;case" ":r.type==="checkbox"&&(t.preventDefault(),this.toggleCheckboxes(this.getSelectedRange()));return;case"Delete":case"Backspace":t.preventDefault(),this.clearRange(this.getSelectedRange(),"clear");return;case"Home":t.preventDefault(),this.moveActive(0,-this.selEnd.col,t.shiftKey);return;case"End":t.preventDefault(),this.moveActive(0,this.countCols(),t.shiftKey);return;case"PageDown":case"PageUp":{t.preventDefault();const i=Math.max(1,Math.floor((this.root.clientHeight-this.headerH)/this.rows.defaultSize)-1);this.moveActive(n==="PageDown"?i:-i,0,t.shiftKey);return}}}}const fe={ArrowUp:[-1,0],ArrowDown:[1,0],ArrowLeft:[0,-1],ArrowRight:[0,1]},Ft=(s,t)=>(s.push(t),t);function Bt(s,t){let e=-1/0;for(const n of s)e=Math.max(e,t(n));return e}function hi(s){return s?new Intl.NumberFormat(s).format(1.5).includes(","):!1}function xs(s,t,e,n){const r=t+e;return s>=t&&s<r?n>t?s+(n-r):s-(t-n):n>r&&s>=r&&s<n?s-e:n<t&&s>=n&&s<t?s+e:s}const Wt=(s,t,e)=>s<t?s:e>0?s+e:s<t-e?-1:s+e;function Ct(s,t){const e=new Map;for(const[n,r]of s){const i=t(n);i>=0&&e.set(i,r)}return e}const pe=s=>s==null||s==="",bs=(s,t)=>({start:{row:Math.min(s.start.row,t.start.row),col:Math.min(s.start.col,t.start.col)},end:{row:Math.max(s.end.row,t.end.row),col:Math.max(s.end.col,t.end.col)}});function ft(s,t,e,n,r){const i=s.style;i.left=`${t}px`,i.top=`${e}px`,i.width=`${n}px`,i.height=`${r}px`}const ui=s=>typeof requestAnimationFrame=="function"?requestAnimationFrame(s):setTimeout(s,16),di=s=>{s&&(typeof cancelAnimationFrame=="function"?cancelAnimationFrame(s):clearTimeout(s))};exports.CSV_MIME=cn;exports.CellError=rt;exports.CenituGrid=ci;exports.FormulaEngine=gt;exports.FormulaSyntaxError=I;exports.MAX_COLS=16384;exports.MAX_ROWS=1048576;exports.ObjectBinding=ee;exports.RangeValue=R;exports.SHEET_SPAN=17179869184;exports.XLSX_MIME=mn;exports.cellKey=N;exports.columnIndex=Me;exports.columnLabel=Rt;exports.crc32=_e;exports.dateCodeFromPattern=rn;exports.dateToSerial=kt;exports.downloadBlob=Ce;exports.enUS=Ee;exports.formatDateCode=ln;exports.formatSerialDate=Te;exports.getRegisteredFunctionNames=Nn;exports.inverseMove=Qs;exports.isDateFormat=nn;exports.isError=m;exports.isFormula=F;exports.isObjectData=en;exports.keyToAddress=me;exports.normalizeRange=Cs;exports.numberFormatFromMeta=on;exports.parseA1=Re;exports.parseDateString=Qt;exports.parseFormula=xe;exports.pxToColWidth=wn;exports.quoteSheetName=Ss;exports.rangeContains=Sn;exports.registerFunction=w;exports.sanitizeSheetNames=gn;exports.serialToDate=at;exports.setClock=Fn;exports.setRandom=In;exports.toA1=As;exports.toCSV=an;exports.toXLSX=Gr;exports.toXLSXCompressed=vn;exports.trTR=ti;exports.unparse=jt;exports.unregisterFunction=Dn;exports.xlsxParts=Xe;exports.zipDeflate=pn;exports.zipStore=fn;