@odoo/o-spreadsheet 18.4.38 → 18.4.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/o_spreadsheet.cjs.js +106 -6
- package/dist/o_spreadsheet.css +3 -3
- package/dist/o_spreadsheet.esm.js +106 -6
- package/dist/o_spreadsheet.iife.js +106 -6
- package/dist/o_spreadsheet.iife.min.js +18 -18
- package/dist/o_spreadsheet.xml +4 -4
- package/package.json +21 -21
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
(function(e,t){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),l=(e,t)=>{let n={};for(var i in e)r(n,i,{get:e[i],enumerable:!0});return t||r(n,Symbol.toStringTag,{value:`Module`}),n},u=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=a(t),l=0,u=c.length,d;l<u;l++)d=c[l],!s.call(e,d)&&d!==n&&r(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(o=i(t,d))||o.enumerable});return e},d=(e,t,i)=>(i=e==null?{}:n(o(e)),u(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e));function f(e){return e.map(m).sort((e,t)=>e.sequence-t.sequence)}let p=1;function m(e){let t=e.name,n=e.children,r=e.description,i=e.icon,a=e.secondaryIcon,o=e.id||p++,s=e.isEnabled?e.isEnabled:()=>!0;return{id:o.toString(),name:typeof t==`function`?t:()=>t,isVisible:e.isVisible?e.isVisible:()=>!0,isEnabled:s,isActive:e.isActive,execute:e.execute?(t,n)=>{if(s(t))return e.execute(t,n)}:void 0,children:n?e=>n.map(t=>typeof t==`function`?t(e):t).flat().map(m).sort((e,t)=>e.sequence-t.sequence):()=>[],isReadonlyAllowed:e.isReadonlyAllowed||!1,separator:e.separator||!1,icon:typeof i==`function`?i:()=>i||``,iconColor:e.iconColor,secondaryIcon:typeof a==`function`?a:()=>a||``,description:typeof r==`function`?r:()=>r||``,textColor:e.textColor,sequence:e.sequence||0,onStartHover:e.onStartHover,onStopHover:e.onStopHover}}function h(e,t){let n=[];for(let r=0;r<t.length;r++){let i=t[r];i.isVisible(e)&&n.push(i),i.separator&&r!==t.length-1&&n[n.length-1]!==`separator`&&n.push(`separator`)}return n[n.length-1]===`separator`&&n.pop(),n.length===1&&n[0]===`separator`?[]:n}var g=class{content={};add(e,t){if(e in this.content)throw Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(e,t){return this.content[e]=t,this}get(e){let t=this.content[e];if(!t&&!(e in this.content))throw Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}};let _=.5,v=`#017E84`,y=`#f5f5f5`,ee=`#F8F9FA`,te=`#E8EAED`,ne=`#595959`,re=`#666666`,ie=`#c9ccd2`,ae=`#3266ca`,oe=`#FFFFFF`,se=`#CACACA`,ce=11982760,le=v,ue=`#188038`,de=`#E0E2E4`,fe=`#4A4F59`,pe=`#999`,me=`#E2E3E3`,he=`#BCBCBC`,ge=`#9B359B`,_e=`#00000000`,ve=`#111827`,ye=`#D8DADD`,be=`#E7E9ED`,xe=`#F9FAFB`,Se=`#374151`,Ce=Se+`C2`,we=`#111827`,Te=`#714B67`,Ee=ye,De=`#111827`,Oe=`#e6f2f3`,ke=`#111827`,Ae=v,je=`#D44C591A`,Me=`#C34A41`,Ne=`#98DBE2`,Pe=`#E6F2F3`,Fe=`#F28C28`,Ie=`#000000.#434343.#666666.#999999.#B7B7B7.#CCCCCC.#D9D9D9.#EFEFEF.#F3F3F3.#FFFFFF.#980000.#FF0000.#FF9900.#FFFF00.#00FF00.#00FFFF.#4A86E8.#0000FF.#9900FF.#FF00FF.#E6B8AF.#F4CCCC.#FCE5CD.#FFF2CC.#D9EAD3.#D0E0E3.#C9DAF8.#CFE2F3.#D9D2E9.#EAD1DC.#DD7E6B.#EA9999.#F9CB9C.#FFE599.#B6D7A8.#A2C4C9.#A4C2F4.#9FC5E8.#B4A7D6.#D5A6BD.#CC4125.#E06666.#F6B26B.#FFD966.#93C47D.#76A5AF.#6D9EEB.#6FA8DC.#8E7CC3.#C27BA0.#A61C00.#CC0000.#E69138.#F1C232.#6AA84F.#45818E.#3C78D8.#3D85C6.#674EA7.#A64D79.#85200C.#990000.#B45F06.#BF9000.#38761D.#134F5C.#1155CC.#0B5394.#351C75.#741B47.#5B0F00.#660000.#783F04.#7F6000.#274E13.#0C343D.#1C4587.#073763.#20124D.#4C1130`.split(`.`),Le={align:`left`,verticalAlign:`bottom`,wrapping:`overflow`,bold:!1,italic:!1,strikethrough:!1,underline:!1,fontSize:10,fillColor:``,textColor:``},Re={...Le,align:`right`},ze=Le.verticalAlign,Be=Le.wrapping,Ve=Le.fontSize,He=`'Roboto', arial`,Ue={style:`thin`,color:`#000000`},We=`START_REVISION`,Ge=`difference`,Ke=`#43C5B1`,qe=`#EA6175`,Je=.4,Ye=[`'`,`*`,`?`,`/`,`\\`,`[`,`]`],Xe=/'|\*|\?|\/|\\|\[|\]/,Ze=0;function Qe(){return Ze}function $e(e){Ze=e}let et=[6,7,8,9,10,11,12,14,18,24,36],tt={hasFilters:!1,totalRow:!1,firstColumn:!0,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,styleId:`TableStyleMedium5`,automaticAutofill:!1},nt={symbol:`$`,position:`before`,decimalPlaces:2,code:``,name:`Dollar`},rt=new RegExp(Xe,`g`);function it(e){return e[0]===`"`&&(e=e.slice(1)),e[e.length-1]===`"`&&e[e.length-2]!==`\\`?e.slice(0,e.length-1):e}function at(e){return`clone`in e&&e.clone instanceof Function}function ot(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function b(e){switch(typeof e){case`object`:{if(e===null)return e;if(at(e))return e.clone();if(!(st(e)||e instanceof Array))throw Error(`Unsupported type: only objects and arrays are supported`);let t=Array.isArray(e)?Array(e.length):{};if(Array.isArray(e))for(let n=0,r=e.length;n<r;n++)n in e&&(t[n]=b(e[n]));else for(let n in e)t[n]=b(e[n]);return t}case`number`:case`string`:case`boolean`:case`function`:case`undefined`:return e;default:throw Error(`Unsupported type: ${typeof e}`)}}function st(e){return typeof e==`object`&&!!e&&(e?.constructor===Object||e?.constructor===void 0)}function ct(e){return lt(e,`'`)}function lt(e,t=`"`){return e.startsWith(t)&&(e=e.slice(1)),e.endsWith(t)&&(e=e.slice(0,-1)),e}function ut(e){return e.match(/\w/g)?.length!==e.length&&(e=`'${e}'`),e}function dt(e,t=` `){return e.replace(rt,t)}function x(e,t,n){return e<t?t:e>n?n:e}function S(e,t,n=1){if(t<=e&&n>0)return[];if(n===0)throw Error(`range() step must not be zero`);let r=Math.ceil(Math.abs((t-e)/n)),i=Array(r);for(let t=0;t<r;t++)i[t]=e+t*n;return i}function ft(e){return e.reduce((e,t,n,r)=>(Math.abs(t-r[n-1])===1?e[e.length-1].push(t):e.push([t]),e),[])}function*pt(e,t){t.next();for(let n of e){let e=t.next();yield{...n,next:e.done?void 0:e.value}}}function mt(e){let t=e.toUpperCase();return t===`TRUE`||t===`FALSE`}let ht=/^\[(.+)\]\((.+)\)$/,gt=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function _t(e){return ht.test(e)}function vt(e){return gt.test(e)}function yt(e,t){return`[${e}](${t})`}function bt(e){let t=e.match(ht)||[],n=t[1],r=t[2];if(!n||!r)throw Error(`Could not parse markdown link ${e}.`);return{label:n,url:r}}let xt=`o-spreadsheet://`;function St(e){return e.startsWith(xt)}function Ct(e){return`${xt}${e}`}function wt(e){if(e.startsWith(xt))return e.slice(16);throw Error(`${e} is not a valid sheet link`)}function C(e){return e!==void 0}function Tt(e){return e===void 0?!0:Object.values(e).every(e=>typeof e==`object`?Tt(e):!e)}function Et(e,t,n){let r,i=function(){let i=this,a=Array.from(arguments);function o(){r=void 0,n||e.apply(i,a)}let s=n&&!r;clearTimeout(r),r=setTimeout(o,t),s&&e.apply(i,a)};return i.isDebouncePending=()=>r!==void 0,i.stopDebounce=()=>{clearTimeout(r)},i}function Dt(e){let t=!1;return async(...n)=>{t||(t=!0,await Promise.resolve(),t=!1,e(...n))}}function Ot(e){let t=``;for(let n=0,r=e.length;n<r;n++)t+=e[n];return t}function kt(e){let t=!1,n,r=()=>(t||=(n=e instanceof Function?e():e,!0),n);return r.map=e=>kt(()=>e(r())),r}function At(e,t){let n=e.slice(t).find(e=>e);return n||=e.slice(0,t).reverse().find(e=>e),n||``}function jt(e,t){return e===`after`?t+1:t}function w(e,t){if(e===t)return!0;if(e&&!t||t&&!e||typeof e!=typeof t||typeof e!=`object`)return!1;for(let n in t)if(!(n in e)&&t[n]!==void 0)return!1;for(let n in e){if(typeof e[n]!=typeof t[n])return!1;if(typeof e[n]==`object`){if(!w(e[n],t[n]))return!1}else if(e[n]!==t[n])return!1}return!0}function Mt(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!w(e[n],t[n]))return!1;return!0}function Nt(e,t){if(e.length<t.length)return!1;let n=new Set(e);return t.every(e=>n.has(e))}function Pt(e){if(!e)return e;let t={...e};return Object.keys(t).forEach(e=>!t[e]&&delete t[e]),t}let Ft=[` `,`\f`,`\v`,`\xA0`,` `,` `,` `,`\u2028`,`\u2029`,` `,` `,` `,``],It=new RegExp(Ft.join(`|`),`g`),Lt=/(\r\n|\r)/g,Rt=Ft.concat([` `]);function zt(e){return e?e.replace(Lt,`
|
|
2
2
|
`):``}function Bt(e){let t=Array.from(e).sort((e,t)=>e-t);for(let e=1;e<t.length;e++)if(t[e]-t[e-1]!==1)return!1;return!0}function Vt(e){let t=new Map,n=e.name?e.name+` (memoized)`:`memoized`;return{[n](...n){return t.has(n[0])||t.set(n[0],e(...n)),t.get(n[0])}}[n]}function Ht(e,t){let n=new Set(t),r=[];for(let t=0;t<e.length;t++)n.has(t)||r.push(e[t]);return r}function Ut(e,t,n){return e.slice(0,n).concat(t).concat(e.slice(n))}function Wt(e,t,n){let r=[...e];return r[n]=t,r}function Gt(e){return e.split(`
|
|
3
3
|
`).map(e=>e.replace(/\s+/g,` `).trim()).join(`
|
|
4
|
-
`)}function Kt(e,t,n){return t>n?Kt(e,n,t):e>=t&&e<=n}function qt(e,t){let n=ot(e),r=t.matchCase?``:`i`;return t.exactMatch&&(n=`^${n}$`),RegExp(n,r)}function Jt(e){let t=e.length;if(t<1e5)return Math.max(...e);let n=-1/0;for(;t--;)n=e[t]>n?e[t]:n;return n}function Yt(e){let t=e.length;if(t<1e5)return Math.min(...e);let n=1/0;for(;t--;)n=e[t]<n?e[t]:n;return n}var Xt=class{text;currentIndex=0;current;constructor(e){this.text=e,this.current=e[0]}shift(){let e=this.current,t=this.text[++this.currentIndex];return this.current=t,e}advanceBy(e){this.currentIndex+=e,this.current=this.text[this.currentIndex]}isOver(){return this.currentIndex>=this.text.length}remaining(){return this.text.substring(this.currentIndex)}currentStartsWith(e){if(this.current!==e[0])return!1;for(let t=1;t<e.length;t++)if(this.text[this.currentIndex+t]!==e[t])return!1;return!0}};function Zt(e,t=e=>e){let n=new Set;return e.filter(e=>{let r=t(e);return n.has(r)?!1:(n.add(r),!0)})}function Qt(e){let t={};for(let n in e)for(let r in e[n])t[r]||(t[r]={}),t[r][n]=e[n][r];return t}function $t(e,t,n={}){let r=n.compute??((e,t)=>`${e} (${t})`),i=n.computeFirstOne??!1,a=n.start??1,o=i?r(e,a):e;for(;t.includes(o);)o=r(e,a++);return o}function en(e){return e.startsWith(`=`)||e.startsWith(`+`)}let tn=/rgba?\(|\s+|\)/gi,nn=/^#([A-F\d]{2}){3,4}$/,rn=[`#eb6d00`,`#0074d9`,`#ad8e00`,`#169ed4`,`#b10dc9`,`#00a82d`,`#00a3a3`,`#f012be`,`#3d9970`,`#111111`,`#62A300`,`#ff4136`,`#949494`,`#85144b`,`#001f3f`];function an(e,t=1){let n=t===1?``:Math.round(t*255).toString(16).padStart(2,`0`);return sn(e.toString(16).padStart(6,`0`))+n}function on(e){return typeof e==`number`?e:Number.parseInt(sn(e).slice(1,7),16)}function sn(e){let t=e;if(e.startsWith(`rgb`)?t=pn(e):(t=e.replace(`#`,``).toUpperCase(),(t.length===3||t.length===4)&&(t=t.split(``).reduce((e,t)=>e+t+t,``)),t=`#${t}`),!nn.test(t))throw Error(`invalid color input: ${e}`);return t}function cn(e){try{return sn(e),!0}catch{return!1}}function ln(e){try{return vn(e),!0}catch{return!1}}let un=e=>e>=0&&e<=255;function dn(e,t,n,r=1){if(!un(e)||!un(t)||!un(n)||r<0||r>1)throw Error(`Invalid RGBA values ${[e,t,n,r]}`);return{a:r,b:n,g:t,r:e}}function fn(e){let{r:t,g:n,b:r}=hn(e);t/=255,n/=255,r/=255;let i=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4,a=i(t),o=i(n),s=i(r);return .2126*a+.7152*o+.0722*s}function pn(e){let t=e.replace(tn,``).split(`,`),n=255;if(t.length!==3&&t.length!==4)throw Error(`invalid color`);if(t.length===4){let e=parseFloat(t.pop()||`1`);if(isNaN(e))throw Error(`invalid alpha value`);n=Math.round(e*255)}let r=t.map(e=>parseInt(e,10));return n!==255&&r.push(n),`#`+Ot(r.map(e=>e.toString(16).padStart(2,`0`))).toUpperCase()}function mn(e){let t=e.r.toString(16),n=e.g.toString(16),r=e.b.toString(16),i=Math.round(e.a*255).toString(16);return t.length===1&&(t=`0`+t),n.length===1&&(n=`0`+n),r.length===1&&(r=`0`+r),i.length===1&&(i=`0`+i),i===`ff`&&(i=``),(`#`+t+n+r+i).toUpperCase()}function hn(e){e=sn(e);let t,n,r,i;if(e.length===7)t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16),i=255;else if(e.length===9)t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16),i=parseInt(e[7]+e[8],16);else throw Error(`Invalid color`);return i=+(i/255).toFixed(3),{a:i,r:t,g:n,b:r}}function gn(e){e={...e},e.s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,n=t*(1-Math.abs(e.h/60%2-1)),r=e.l-t/2,i=0,a=0,o=0;return 0<=e.h&&e.h<60?(i=t,a=n,o=0):60<=e.h&&e.h<120?(i=n,a=t,o=0):120<=e.h&&e.h<180?(i=0,a=t,o=n):180<=e.h&&e.h<240?(i=0,a=n,o=t):240<=e.h&&e.h<300?(i=n,a=0,o=t):300<=e.h&&e.h<360&&(i=t,a=0,o=n),i=Math.round((i+r)*255),a=Math.round((a+r)*255),o=Math.round((o+r)*255),{a:e.a,r:i,g:a,b:o}}function _n(e){let t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=a-i,s=0,c=0,l=0;return s=o===0?0:a===t?(n-r)/o%6:a===n?(r-t)/o+2:(t-n)/o+4,s=Math.round(s*60),s<0&&(s+=360),l=(a+i)/2,c=o===0?0:o/(1-Math.abs(2*l-1)),c=+(c*100).toFixed(1),l=+(l*100).toFixed(1),{a:e.a,h:s,s:c,l}}function vn(e){return mn(gn(e))}function yn(e){return _n(hn(e))}function bn(e){return hn(typeof e==`number`?an(e):e)}function xn(e,t,n=0){if(!(cn(e)&&cn(t)))return!1;let r=hn(e),i=hn(t);return r.a===i.a?Math.sqrt(((r.r-i.r)/255)**2+((r.g-i.g)/255)**2+((r.b-i.b)/255)**2)<=n:!1}function Sn(e,t){return t===1?sn(e).slice(0,7):mn({...hn(e),a:t})}function Cn(e,t){let n=yn(e);return t===1?`#fff`:(n.l=t*(100-n.l)+n.l,vn(n))}function wn(e,t){let n=yn(e);return t===1?`#000`:(n.s=Math.min(100,t*n.s+n.s),n.l-=t*n.l,vn(n))}function Tn(e){return fn(e)<.6?Cn(e,.9):wn(e,.75)}let En=[`#4EA7F2`,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#FFD86D`],Dn=[`#4EA7F2`,`#3188E6`,`#43C5B1`,`#00A78D`,`#EA6175`,`#CE4257`,`#F4A261`,`#F48935`,`#8481DD`,`#5752D1`,`#FFD86D`,`#FFBC2C`],On=[`#4EA7F2`,`#3188E6`,`#056BD9`,`#A76DBC`,`#7F4295`,`#6D2387`,`#EA6175`,`#CE4257`,`#982738`,`#43C5B1`,`#00A78D`,`#0E8270`,`#F4A261`,`#F48935`,`#BE5D10`,`#8481DD`,`#5752D1`,`#3A3580`,`#A4A8B6`,`#7E8290`,`#545B70`,`#FFD86D`,`#FFBC2C`,`#C08A16`],kn=`#4EA7F2.#3188E6.#056BD9.#155193.#A76DBC.#7F4295.#6D2387.#4F1565.#EA6175.#CE4257.#982738.#791B29.#43C5B1.#00A78D.#0E8270.#105F53.#F4A261.#F48935.#BE5D10.#7D380D.#8481DD.#5752D1.#3A3580.#26235F.#A4A8B6.#7E8290.#545B70.#3F4250.#FFD86D.#FFBC2C.#C08A16.#936A12`.split(`.`),An=[`#4EA7F2`,`#43C5B1`,`#EA6175`,`#F4A261`,`#8481DD`,`#FFD86D`,`#3188E6`,`#00A78D`,`#CE4257`,`#F48935`,`#5752D1`,`#FFBC2C`],jn=[`#4EA7F2`,`#A76DBC`,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#A4A8B6`,`#FFD86D`,`#3188E6`,`#7F4295`,`#CE4257`,`#00A78D`,`#F48935`,`#5752D1`,`#7E8290`,`#FFBC2C`,`#056BD9`,`#6D2387`,`#982738`,`#0E8270`,`#BE5D10`,`#3A3580`,`#545B70`,`#C08A16`],Mn=`#4EA7F2.#A76DBC.#EA6175.#43C5B1.#F4A261.#8481DD.#A4A8B6.#FFD86D.#3188E6.#7F4295.#CE4257.#00A78D.#F48935.#5752D1.#7E8290.#FFBC2C.#056BD9.#6D2387.#982738.#0E8270.#BE5D10.#3A3580.#545B70.#C08A16.#155193.#4F1565.#791B29.#105F53.#7D380D.#26235F.#3F4250.#936A12`.split(`.`);function Nn(e,t){return t[e%t.length]}function Pn(e){return e<=6?En:e<=12?Dn:e<=24?On:kn}function Fn(e){return e<=6?En:e<=12?An:e<=24?jn:Mn}var In=class{currentColorIndex=0;palette;constructor(e,t=[]){this.preferredColors=t,this.palette=Pn(e).filter(e=>!t.includes(e))}next(){return this.preferredColors?.[this.currentColorIndex]?this.preferredColors[this.currentColorIndex++]:Nn(this.currentColorIndex++,this.palette)}},Ln=class extends In{constructor(e,t=[]){super(e,t),this.palette=Fn(e).filter(e=>!t.includes(e))}},Rn=class{availableColors;colors={};constructor(e=12){this.availableColors=new Ln(e)}get(e){return this.colors[e]||(this.colors[e]=this.availableColors.next()),this.colors[e]}};function zn(e){if(e.length<2)throw Error(`Color scale must have at least 2 points`);let t=[...e.sort((e,t)=>e.value-t.value)],n=[];for(let e=1;e<t.length;e++){let r=bn(t[e-1].color).a,i=bn(t[e].color).a,a=on(t[e-1].color),o=on(t[e].color);n.push({min:t[e-1].value,max:t[e].value,minColor:a,maxColor:o,minColorAlpha:r,maxColorAlpha:i,colorDiff:Bn(t[e-1].value,t[e].value,a,o)})}return e=>{if(e<n[0].min)return an(n[0].minColor,n[0].minColorAlpha);for(let t of n)if(e>=t.min&&e<=t.max)return an(Vn(e,t.min,t.minColor,t.colorDiff),t.maxColorAlpha);return an(n[n.length-1].maxColor,n[n.length-1].maxColorAlpha)}}function Bn(e,t,n,r){let i=t-e,a=(n>>16)%256-(r>>16)%256,o=(n>>8)%256-(r>>8)%256,s=n%256-r%256;return[a/i,o/i,s/i]}function Vn(e,t,n,r){let[i,a,o]=r,s=Math.round((n>>16)%256-i*(e-t)),c=Math.round((n>>8)%256-a*(e-t)),l=Math.round(n%256-o*(e-t));return s<<16|c<<8|l}function Hn(e){if(e<0)throw Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Hn(Math.floor(e/26)-1)+Hn(e%26)}function Un(e){let t=0,n=e.length;for(let r=0;r<n;r++){let n=Wn(e[r]);t=t*26+n}return t-1}function Wn(e){let t=e.charCodeAt(0);return t>=65&&t<=90?t-64:t-96}function Gn(e){return e>=`A`&&e<=`Z`||e>=`a`&&e<=`z`}function Kn(e){return e>=`0`&&e<=`9`}let qn=Un(`ZZZ`);function Jn(e){for(;e.current===` `;)e.advanceBy(1)}function Yn(e){if(e.current===`$`&&e.advanceBy(1),!e.current||!Gn(e.current))return-1;let t=0;for(;e.current&&Gn(e.current);)t=t*26+Wn(e.shift());return t}function Xn(e){if(e.current===`$`&&e.advanceBy(1),!e.current||!Kn(e.current))return-1;let t=0;for(;e.current&&Kn(e.current);)t=t*10+Number(e.shift());return t}function Zn(e){let t=new Xt(e);Jn(t);let n=Yn(t);if(n===-1||!t.current)throw Error(`Invalid cell description: ${e}`);let r=Xn(t);Jn(t);let i=n-1,a=r-1;if(!t.isOver()||i>qn||a>9999998)throw Error(`Invalid cell description: ${e}`);return{col:i,row:a}}function T(e,t,n={colFixed:!1,rowFixed:!1}){return(n.colFixed?`$`:``)+Hn(e)+(n.rowFixed?`$`:``)+String(t+1)}let Qn=e=>e,$n=()=>!1,er=Qn,tr=$n;function nr(e,...t){if(t.length===1&&typeof t[0]==`object`&&!(t[0]instanceof String)){let n=t[0];e=e.replace(/\%\(([^\)]+)\)s/g,(e,t)=>n[t])}else t.length>0&&(e=e.replace(/\%s/g,()=>t.shift()));return e}function rr(e,t=()=>!0){er=e,tr=t}function ir(){er===Qn&&tr===$n&&(tr=()=>!0)}let E=function(e,...t){return tr()?nr(er(e),...t):new ar(e,t)};var ar=class extends String{constructor(e,t){super(e),this.values=t}valueOf(){let e=super.valueOf();return tr()?nr(er(e),...this.values):nr(e,...this.values)}toString(){return this.valueOf()}};function or(e){return`sheetId`in e}function sr(e){return`dimension`in e&&`sheetId`in e&&`elements`in e}function cr(e){return`target`in e&&`sheetId`in e}function lr(e){return`ranges`in e}function ur(e){return`col`in e&&`row`in e&&`sheetId`in e}function dr(e){return`sheetId`in e&&`zone`in e}let fr=new Set([`RENAME_SHEET`,`DELETE_SHEET`,`CREATE_SHEET`,`DUPLICATE_SHEET`,`ADD_COLUMNS_ROWS`,`REMOVE_COLUMNS_ROWS`,`UNDO`,`REDO`,`ADD_MERGE`,`REMOVE_MERGE`,`UPDATE_LOCALE`,`ADD_PIVOT`,`UPDATE_PIVOT`,`INSERT_PIVOT`,`RENAME_PIVOT`,`REMOVE_PIVOT`,`DUPLICATE_PIVOT`]),pr=new Set([`EVALUATE_CELLS`,`EVALUATE_CHARTS`,`UPDATE_CELL`,`UNHIDE_COLUMNS_ROWS`,`HIDE_COLUMNS_ROWS`,`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUP`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_ALL_HEADER_GROUPS`,`UNFOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`UPDATE_TABLE`,`UPDATE_FILTER`,`UNDO`,`REDO`]),mr=new Set([`MOVE_RANGES`]),hr=new Set([`EVALUATE_CELLS`,`ADD_CONDITIONAL_FORMAT`,`REMOVE_CONDITIONAL_FORMAT`,`CHANGE_CONDITIONAL_FORMAT_PRIORITY`]),gr=new Set([`AUTOFILL_CELL`,`SET_BORDER`,`SET_ZONE_BORDERS`,`SET_BORDERS_ON_TARGET`]),_r=new Set([`START`,`ACTIVATE_SHEET`,`COPY`,`RESIZE_SHEETVIEW`,`SET_VIEWPORT_OFFSET`,`EVALUATE_CELLS`,`EVALUATE_CHARTS`,`SET_FORMULA_VISIBILITY`,`UPDATE_FILTER`,`UPDATE_CHART`]),vr=new Set(`UPDATE_CELL.UPDATE_CELL_POSITION.CLEAR_CELL.CLEAR_CELLS.DELETE_CONTENT.ADD_COLUMNS_ROWS.REMOVE_COLUMNS_ROWS.RESIZE_COLUMNS_ROWS.HIDE_COLUMNS_ROWS.UNHIDE_COLUMNS_ROWS.SET_GRID_LINES_VISIBILITY.UNFREEZE_COLUMNS.UNFREEZE_ROWS.FREEZE_COLUMNS.FREEZE_ROWS.UNFREEZE_COLUMNS_ROWS.ADD_MERGE.REMOVE_MERGE.CREATE_SHEET.DELETE_SHEET.DUPLICATE_SHEET.MOVE_SHEET.RENAME_SHEET.COLOR_SHEET.HIDE_SHEET.SHOW_SHEET.MOVE_RANGES.ADD_CONDITIONAL_FORMAT.REMOVE_CONDITIONAL_FORMAT.CHANGE_CONDITIONAL_FORMAT_PRIORITY.CREATE_FIGURE.DELETE_FIGURE.UPDATE_FIGURE.SET_FORMATTING.CLEAR_FORMATTING.SET_BORDER.SET_ZONE_BORDERS.SET_BORDERS_ON_TARGET.CREATE_CHART.UPDATE_CHART.CREATE_TABLE.REMOVE_TABLE.UPDATE_TABLE.CREATE_TABLE_STYLE.REMOVE_TABLE_STYLE.CREATE_IMAGE.GROUP_HEADERS.UNGROUP_HEADERS.UNFOLD_HEADER_GROUP.FOLD_HEADER_GROUP.FOLD_ALL_HEADER_GROUPS.UNFOLD_ALL_HEADER_GROUPS.UNFOLD_HEADER_GROUPS_IN_ZONE.FOLD_HEADER_GROUPS_IN_ZONE.ADD_DATA_VALIDATION_RULE.REMOVE_DATA_VALIDATION_RULE.UPDATE_LOCALE.ADD_PIVOT.UPDATE_PIVOT.INSERT_PIVOT.RENAME_PIVOT.REMOVE_PIVOT.DUPLICATE_PIVOT`.split(`.`));function yr(e){return vr.has(e.type)}function br(e){return _r.has(e.type)}var xr=class{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter(e=>e!==`Success`)}static get Success(){return Sr}get isSuccessful(){return this.reasons.length===0}isCancelledBecause(e){return this.reasons.includes(e)}};let Sr=new xr,Cr=function(e){return e.Success=`Success`,e.CancelledForUnknownReason=`CancelledForUnknownReason`,e.WillRemoveExistingMerge=`WillRemoveExistingMerge`,e.CannotMoveTableHeader=`CannotMoveTableHeader`,e.MergeIsDestructive=`MergeIsDestructive`,e.CellIsMerged=`CellIsMerged`,e.InvalidTarget=`InvalidTarget`,e.EmptyUndoStack=`EmptyUndoStack`,e.EmptyRedoStack=`EmptyRedoStack`,e.NotEnoughElements=`NotEnoughElements`,e.NotEnoughSheets=`NotEnoughSheets`,e.MissingSheetName=`MissingSheetName`,e.UnchangedSheetName=`UnchangedSheetName`,e.DuplicatedSheetName=`DuplicatedSheetName`,e.DuplicatedSheetId=`DuplicatedSheetId`,e.ForbiddenCharactersInSheetName=`ForbiddenCharactersInSheetName`,e.WrongSheetMove=`WrongSheetMove`,e.WrongSheetPosition=`WrongSheetPosition`,e.InvalidAnchorZone=`InvalidAnchorZone`,e.SelectionOutOfBound=`SelectionOutOfBound`,e.TargetOutOfSheet=`TargetOutOfSheet`,e.WrongCutSelection=`WrongCutSelection`,e.WrongPasteSelection=`WrongPasteSelection`,e.WrongPasteOption=`WrongPasteOption`,e.WrongFigurePasteOption=`WrongFigurePasteOption`,e.EmptyClipboard=`EmptyClipboard`,e.EmptyRange=`EmptyRange`,e.InvalidRange=`InvalidRange`,e.InvalidZones=`InvalidZones`,e.InvalidSheetId=`InvalidSheetId`,e.InvalidCellId=`InvalidCellId`,e.InvalidFigureId=`InvalidFigureId`,e.InputAlreadyFocused=`InputAlreadyFocused`,e.MaximumRangesReached=`MaximumRangesReached`,e.MinimumRangesReached=`MinimumRangesReached`,e.InvalidChartDefinition=`InvalidChartDefinition`,e.InvalidDataSet=`InvalidDataSet`,e.InvalidLabelRange=`InvalidLabelRange`,e.InvalidScorecardKeyValue=`InvalidScorecardKeyValue`,e.InvalidScorecardBaseline=`InvalidScorecardBaseline`,e.InvalidGaugeDataRange=`InvalidGaugeDataRange`,e.EmptyGaugeRangeMin=`EmptyGaugeRangeMin`,e.GaugeRangeMinNaN=`GaugeRangeMinNaN`,e.EmptyGaugeRangeMax=`EmptyGaugeRangeMax`,e.GaugeRangeMaxNaN=`GaugeRangeMaxNaN`,e.GaugeLowerInflectionPointNaN=`GaugeLowerInflectionPointNaN`,e.GaugeUpperInflectionPointNaN=`GaugeUpperInflectionPointNaN`,e.InvalidAutofillSelection=`InvalidAutofillSelection`,e.MinBiggerThanMax=`MinBiggerThanMax`,e.LowerBiggerThanUpper=`LowerBiggerThanUpper`,e.MidBiggerThanMax=`MidBiggerThanMax`,e.MinBiggerThanMid=`MinBiggerThanMid`,e.FirstArgMissing=`FirstArgMissing`,e.SecondArgMissing=`SecondArgMissing`,e.MinNaN=`MinNaN`,e.MidNaN=`MidNaN`,e.MaxNaN=`MaxNaN`,e.ValueUpperInflectionNaN=`ValueUpperInflectionNaN`,e.ValueLowerInflectionNaN=`ValueLowerInflectionNaN`,e.MinInvalidFormula=`MinInvalidFormula`,e.MidInvalidFormula=`MidInvalidFormula`,e.MaxInvalidFormula=`MaxInvalidFormula`,e.ValueUpperInvalidFormula=`ValueUpperInvalidFormula`,e.ValueLowerInvalidFormula=`ValueLowerInvalidFormula`,e.InvalidSortAnchor=`InvalidSortAnchor`,e.InvalidSortZone=`InvalidSortZone`,e.SortZoneWithArrayFormulas=`SortZoneWithArrayFormulas`,e.WaitingSessionConfirmation=`WaitingSessionConfirmation`,e.MergeOverlap=`MergeOverlap`,e.TooManyHiddenElements=`TooManyHiddenElements`,e.Readonly=`Readonly`,e.InvalidViewportSize=`InvalidViewportSize`,e.InvalidScrollingDirection=`InvalidScrollingDirection`,e.ViewportScrollLimitsReached=`ViewportScrollLimitsReached`,e.FigureDoesNotExist=`FigureDoesNotExist`,e.InvalidConditionalFormatId=`InvalidConditionalFormatId`,e.InvalidConditionalFormatType=`InvalidConditionalFormatType`,e.InvalidCellPopover=`InvalidCellPopover`,e.EmptyTarget=`EmptyTarget`,e.InvalidFreezeQuantity=`InvalidFreezeQuantity`,e.FrozenPaneOverlap=`FrozenPaneOverlap`,e.ValuesNotChanged=`ValuesNotChanged`,e.InvalidFilterZone=`InvalidFilterZone`,e.TableNotFound=`TableNotFound`,e.TableOverlap=`TableOverlap`,e.InvalidTableConfig=`InvalidTableConfig`,e.InvalidTableStyle=`InvalidTableStyle`,e.FilterNotFound=`FilterNotFound`,e.MergeInTable=`MergeInTable`,e.NonContinuousTargets=`NonContinuousTargets`,e.DuplicatedFigureId=`DuplicatedFigureId`,e.InvalidSelectionStep=`InvalidSelectionStep`,e.DuplicatedChartId=`DuplicatedChartId`,e.ChartDoesNotExist=`ChartDoesNotExist`,e.InvalidHeaderIndex=`InvalidHeaderIndex`,e.InvalidQuantity=`InvalidQuantity`,e.MoreThanOneColumnSelected=`MoreThanOneColumnSelected`,e.EmptySplitSeparator=`EmptySplitSeparator`,e.SplitWillOverwriteContent=`SplitWillOverwriteContent`,e.NoSplitSeparatorInSelection=`NoSplitSeparatorInSelection`,e.NoActiveSheet=`NoActiveSheet`,e.InvalidLocale=`InvalidLocale`,e.MoreThanOneRangeSelected=`MoreThanOneRangeSelected`,e.NoColumnsProvided=`NoColumnsProvided`,e.ColumnsNotIncludedInZone=`ColumnsNotIncludedInZone`,e.DuplicatesColumnsSelected=`DuplicatesColumnsSelected`,e.InvalidHeaderGroupStartEnd=`InvalidHeaderGroupStartEnd`,e.HeaderGroupAlreadyExists=`HeaderGroupAlreadyExists`,e.UnknownHeaderGroup=`UnknownHeaderGroup`,e.UnknownDataValidationRule=`UnknownDataValidationRule`,e.UnknownDataValidationCriterionType=`UnknownDataValidationCriterionType`,e.InvalidDataValidationCriterionValue=`InvalidDataValidationCriterionValue`,e.InvalidNumberOfCriterionValues=`InvalidNumberOfCriterionValues`,e.InvalidCopyPasteSelection=`InvalidCopyPasteSelection`,e.NoChanges=`NoChanges`,e.InvalidInputId=`InvalidInputId`,e.SheetIsHidden=`SheetIsHidden`,e.InvalidTableResize=`InvalidTableResize`,e.PivotIdNotFound=`PivotIdNotFound`,e.PivotInError=`PivotInError`,e.EmptyName=`EmptyName`,e.ValueCellIsInvalidFormula=`ValueCellIsInvalidFormula`,e.InvalidDefinition=`InvalidDefinition`,e.InvalidColor=`InvalidColor`,e.InvalidPivotDataSet=`InvalidPivotDataSet`,e}({}),wr=new Set([`containsText`,`notContainsText`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`beginsWithText`,`endsWithText`,`isNotEmpty`,`isEmpty`,`isNotEqual`,`isEqual`]),Tr=new Set([`containsText`,`notContainsText`,`isEqualText`,`isEmail`,`isLink`,`dateIs`,`dateIsBefore`,`dateIsOnOrBefore`,`dateIsAfter`,`dateIsOnOrAfter`,`dateIsBetween`,`dateIsNotBetween`,`dateIsValid`,`isEqual`,`isNotEqual`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`isBoolean`,`isValueInList`,`isValueInRange`,`customFormula`]),Er=[{name:`English (US)`,code:`en_US`,thousandsSeparator:`,`,decimalSeparator:`.`,weekStart:7,dateFormat:`m/d/yyyy`,timeFormat:`hh:mm:ss a`,formulaArgSeparator:`,`},{name:`French`,code:`fr_FR`,thousandsSeparator:` `,decimalSeparator:`,`,weekStart:1,dateFormat:`dd/mm/yyyy`,timeFormat:`hh:mm:ss`,formulaArgSeparator:`;`}],D=Er[0],Dr=[`thin`,`medium`,`thick`,`dashed`,`dotted`];function Or(e){return Array.isArray(e)&&Array.isArray(e[0])}let kr={Background:0,Highlights:1,Clipboard:2,Chart:4,Autofill:5,Selection:6,Headers:100},Ar=Vt(()=>Object.keys(kr).sort((e,t)=>kr[e]-kr[t]));function jr(e,t){if(kr[e])throw Error(`Layer ${e} already exists`);kr[e]=t}let Mr=[`containsText`,`notContainsText`,`isEqualText`,`isEmpty`,`isNotEmpty`,`beginsWithText`,`endsWithText`],Nr=[`isEqual`,`isNotEqual`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`isEmpty`,`isNotEmpty`],Pr=[`dateIs`,`dateIsBefore`,`dateIsOnOrBefore`,`dateIsAfter`,`dateIsOnOrAfter`,`dateIsBetween`,`dateIsNotBetween`,`isEmpty`,`isNotEmpty`];function Fr(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}let Ir=new g;function Lr(e,t){return e=Fr(e),{url:e,label:t||e,isExternal:!0,isUrlEditable:!0}}Ir.add(`sheet_URL`,{match:e=>St(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){let n=wt(e);return t.tryGetSheetName(n)||E(`Invalid sheet`)},open(e,t){let n=wt(e);t.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:n}).isCancelledBecause(`SheetIsHidden`)&&t.notifyUser({type:`warning`,sticky:!1,text:E(`Cannot open the link because the linked sheet is hidden.`)})},sequence:0});let Rr={createLink:Lr,match:e=>vt(e),open:e=>window.open(e,`_blank`),urlRepresentation:e=>e,sequence:0};function zr(e){return Ir.getAll().sort((e,t)=>e.sequence-t.sequence).find(t=>t.match(e))||Rr}function Br(e,t){return zr(e.url).urlRepresentation(e.url,t)}function Vr(e,t,n){zr(e.url).open(e.url,t,n)}function Hr(e){if(typeof e==`string`){if(_t(e)){let{label:t,url:n}=bt(e);return zr(n).createLink(n,t)}else if(vt(e))return Lr(e)}}var O=class e{jsDate;constructor(e,t,n,r=0,i=0,a=0){this.jsDate=new Date(Date.UTC(e,t,n,r,i,a,0))}static fromTimestamp(t){let n=new Date(t);return new e(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds())}static now(){let t=new Date;return new e(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds())}toString(){return this.jsDate.toString()}toLocaleDateString(){return this.jsDate.toLocaleDateString()}getTime(){return this.jsDate.getTime()}getFullYear(){return this.jsDate.getUTCFullYear()}getMonth(){return this.jsDate.getUTCMonth()}getQuarter(){return Math.floor(this.getMonth()/3)+1}getDate(){return this.jsDate.getUTCDate()}getDay(){return this.jsDate.getUTCDay()}getHours(){return this.jsDate.getUTCHours()}getMinutes(){return this.jsDate.getUTCMinutes()}getSeconds(){return this.jsDate.getUTCSeconds()}getIsoWeek(){let e=new Date(this.jsDate.getTime()),t=e.getUTCDay()||7;e.setUTCDate(e.getUTCDate()+4-t);let n=new Date(Date.UTC(e.getUTCFullYear(),0,1));return Math.ceil(((e.getTime()-n.getTime())/864e5+1)/7)}setFullYear(e){return this.jsDate.setUTCFullYear(e)}setMonth(e){return this.jsDate.setUTCMonth(e)}setDate(e){return this.jsDate.setUTCDate(e)}setHours(e){return this.jsDate.setUTCHours(e)}setMinutes(e){return this.jsDate.setUTCMinutes(e)}setSeconds(e){return this.jsDate.setUTCSeconds(e)}};let Ur=new O(1899,11,30),Wr=1440*60*1e3,Gr=2e3,Kr=O.now().getFullYear(),qr=O.now().getMonth(),Jr=O.fromTimestamp(0).getTime()-Ur.getTime(),Yr=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,Xr=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,Zr=Rt.join(``),Qr=RegExp(`\/|-|${Rt.join(`|`)}`),$r=RegExp(`^(\\d{1,4})[\/${Zr}\-](\\d{1,4})([\/${Zr}\-](\\d{1,4}))?$`),ei=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function ti(e,t){switch(typeof e){case`number`:return e;case`string`:return ni(e,t)?ii(e,t)?.value:!e||isNaN(Number(e))?void 0:Number(e);default:return}}function ni(e,t){return ii(e,t)!==null}let ri=new Map;function ii(e,t){return ri.has(t)||ri.set(t,new Map),ri.get(t).has(e)||ri.get(t).set(e,ai(e,t)),ri.get(t).get(e)}function ai(e,t){e=e.trim();let n=null,r=e.match(ei);if(r){if(n=pi(r[0]),n===null)return null;e=e.replace(r[0],``).trim()}let i=null,a=oi(e,t);if(a){let t=a.dateString.match(Qr)[0];if(i=ci(a,t),i===null)return null;e=e.replace(a.dateString,``).trim()}return e!==``||!(i||n)?null:i&&i.jsDate&&n&&n.jsDate?{value:i.value+n.value,format:i.format+` `+(n.format===`hhhh:mm:ss`?`hh:mm:ss`:n.format),jsDate:new O(i.jsDate.getFullYear()+n.jsDate.getFullYear()-1899,i.jsDate.getMonth()+n.jsDate.getMonth()-11,i.jsDate.getDate()+n.jsDate.getDate()-30,i.jsDate.getHours()+n.jsDate.getHours(),i.jsDate.getMinutes()+n.jsDate.getMinutes(),i.jsDate.getSeconds()+n.jsDate.getSeconds())}:i||n}function oi(e,t){let n=e.match($r);if(!n)return null;let[,r,i,,a]=n;if(r.length>2&&a&&a.length>2)return null;if(r.length>2)return{year:r,month:i,day:a,dateString:e,type:`ymd`};let o=si(t);return a?a.length>2?o===`mdy`?{month:r,day:i,year:a,dateString:e,type:`mdy`}:{day:r,month:i,year:a,dateString:e,type:`dmy`}:o===`mdy`?{month:r,day:i,year:a,dateString:e,type:`mdy`}:o===`ymd`?{year:r,month:i,day:a,dateString:e,type:`ymd`}:o===`dmy`?{day:r,month:i,year:a,dateString:e,type:`dmy`}:null:i.length>2?{month:r,year:i,day:void 0,dateString:e,type:o}:o===`dmy`?{day:r,month:i,year:a,dateString:e,type:`dmy`}:{month:r,day:i,year:a,dateString:e,type:`mdy`}}function si(e){switch(e.dateFormat[0]){case`d`:return`dmy`;case`m`:return`mdy`;case`y`:return`ymd`}throw Error(`Invalid date format in locale`)}function ci(e,t){let{year:n,month:r,day:i}=e,a=di(r),o=fi(i),s=ui(n);if(s===null||a===null||o===null)return null;let c=r?.length===2&&a+1<10||i?.length===2&&o<10,l=n?.length!==2,u=new O(s,a,o);if(u.getMonth()!==a||u.getDate()!==o)return null;let d=u.getTime()-Ur.getTime(),f=li(e,t,c,l);return{value:Math.round(d/Wr),format:f,jsDate:u}}function li(e,t,n,r){let i=e.year?r?`yyyy`:`yy`:void 0,a=e.month?n?`mm`:`m`:void 0,o=e.day?n?`dd`:`d`:void 0;switch(e.type){case`mdy`:return[a,o,i].filter(C).join(t);case`ymd`:return[i,a,o].filter(C).join(t);case`dmy`:return[o,a,i].filter(C).join(t)}}function ui(e){if(!e)return Kr;let t=Number(e);switch(e.length){case 1:return Gr+t;case 2:return Gr+(Gr+t>Kr+10?-100:0)+t;case 3:case 4:return t}return null}function di(e){if(!e)return qr;let t=Number(e);return t>=1&&t<=12?t-1:null}function fi(e){if(!e)return 1;let t=Number(e);return t>=0&&t<=31?t:null}function pi(e){if(e=e.trim(),ei.test(e)){let t=/AM/i.test(e),n=/PM/i.test(e),r=(t||n?e.substring(0,e.length-2).trim():e).split(/:/),i=r.length>=2,a=r.length===3,o=Number(r[0]),s=i?Number(r[1]):0,c=a?Number(r[2]):0,l=a?`hh:mm:ss`:`hh:mm`;if(t||n)l+=` a`;else if(!i)return null;o>=12&&t?o-=12:o<12&&n&&(o+=12),s+=Math.floor(c/60),c%=60,o+=Math.floor(s/60),s%=60,o>=24&&(l=`hhhh:mm:ss`);let u=new O(1899,11,30,o,s,c);return{value:o/24+s/1440+c/86400,format:l,jsDate:u}}return null}function mi(e){let t=Math.trunc(e),n=O.fromTimestamp(t*Wr-Jr),r=e-t;r=r<0?1+r:r;let i=Math.round(r*24),a=Math.round((r-i/24)*24*60),o=Math.round((r-i/24-a/24/60)*24*60*60);return n.setHours(i),n.setMinutes(a),n.setSeconds(o),n}function hi(e){return Math.round(gi(e))}function gi(e){return(e.getTime()-Ur.getTime())/Wr}function _i(e){return new O(e.getFullYear(),e.getMonth()+1,0).getDate()}function vi(e){return _i(e)===e.getDate()}function yi(e,t,n){let r=e.getFullYear(),i=e.getMonth(),a=e.getDate(),o=new O(r,i+t,1);return n&&a===_i(e)||a>_i(o)?o.setDate(_i(o)):o.setDate(a),o}function bi(e){let t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function xi(e,t,n){if(e===t)return 0;if(e>t){let n=t;t=e,e=n}let r=mi(e),i=mi(t),a=r.getDate(),o=i.getDate(),s=r.getMonth(),c=i.getMonth(),l=r.getFullYear(),u=i.getFullYear(),d=0,f=0;switch(n){case 0:a===31&&(a=30),a===30&&o===31&&(o=30),s===1&&a===(bi(l)?29:28)&&(a=30,c===1&&o===(bi(u)?29:28)&&(o=30)),d=l+(s*30+a)/360,f=u+(c*30+o)/360;break;case 1:let n=365,r=l===u,i=l+1===u;if(!r&&!i||!r&&s<c||!r&&s===c&&a<o){let e=0,t=0;for(let n=l;n<=u;n++)e++,t+=bi(n)?366:365;n=t/e}else r?bi(l)&&(n=366):(bi(l)&&s<2&&(n=366),bi(u)&&(c>1||c===1&&o===29)&&(n=366));d=e/n,f=t/n;break;case 2:d=e/360,f=t/360;break;case 3:d=e/365,f=t/365;break;case 4:a===31&&(a=30),o===31&&(o=30),d=l+(s*30+a)/360,f=u+(c*30+o)/360;break}return f-d}function Si(e,t){let n=(t.getFullYear()-e.getFullYear())*12+t.getMonth()-e.getMonth();return e.getDate()>t.getDate()?n-1:n}function Ci(e,t){let n=e.getTime(),r=t.getTime();return Math.floor((r-n)/Wr)}function wi(e,t){let n=t.getFullYear()-e.getFullYear(),r=e.getMonth(),i=t.getMonth(),a=e.getDate(),o=t.getDate();return i>r||i===r&&o>=a?n:n-1}function Ti(e,t){return xi(e,t,1)<1}function Ei(e,t){return Math.trunc(e)===Math.trunc(t)}function Di(e,t,n){return t>n?Di(e,n,t):(e=Math.trunc(e),t=Math.trunc(t),n=Math.trunc(n),e>=t&&e<=n)}function Oi(e,t){return Math.trunc(e)<Math.trunc(t)}function ki(e,t){return Math.trunc(e)<=Math.trunc(t)}function Ai(e,t){return Math.trunc(e)>Math.trunc(t)}function ji(e,t){return Math.trunc(e)>=Math.trunc(t)}let Mi=Vt(function(e){return e=ot(e),RegExp(`(?:^-?\\d+(?:${e}?\\d*(?:e(\\+|-)?\\d+)?)?|^-?${e}\\d+)(?!\\w|!)`)}),Ni=Vt(function(e){let t=ot(e.decimalSeparator),n=`(?:\\d+(?:${ot(e.thousandsSeparator||``)}\\d{3,})*(?:${t}\\d*)?)`,r=`(?:${t}\\d+)`,i=`(?:\\s*`+n+`|`+r+`)(?:e(?:\\+|-)?\\d+)?(?:\\s*%)?`,a=`(?:\\s*-)?`,o=`(?:\\s*[\\$€])?`,s=`^(?:(?:`+[a+o+i,a+i+o,o+a+i].join(`)|(?:`)+`))$`;return new RegExp(s,`i`)});function Pi(e,t){return e?Ni(t).test(e.trim()):!1}let Fi=Vt(function(e){return RegExp(`[\$€${ot(e.thousandsSeparator||``)}]`,`g`)});function Ii(e,t){e=e.replace(Fi(t),``),t.decimalSeparator!==`.`&&(e=e.replace(t.decimalSeparator,`.`));let n=Number(e);return isNaN(n)&&e.includes(`%`)&&(n=Number(e.split(`%`)[0]),!isNaN(n))?n/100:n}function Li(e,t,n){let r=[...e].sort((e,t)=>e-t),i=(r.length+(n?-1:1))*t;if(n||i--,Number.isInteger(i))return r[i];let a=Math.ceil(i),o=Math.floor(i);return r[a]*(i-o)+r[o]*(a-i)}let k={NotAvailable:`#N/A`,InvalidReference:`#REF`,BadExpression:`#BAD_EXPR`,CircularDependency:`#CYCLE`,UnknownFunction:`#NAME?`,DivisionByZero:`#DIV/0!`,SpilledBlocked:`#SPILL!`,GenericError:`#ERROR`,NullError:`#NULL!`},Ri=new Set(Object.values(k));var A=class{constructor(e=E(`Error`),t=k.GenericError){this.message=e,this.value=t,this.message=e.toString()}},zi=class extends A{constructor(e=E(`Invalid expression`)){super(e,k.BadExpression)}},Bi=class extends A{constructor(e=E(`Circular reference`)){super(e,k.CircularDependency)}},Vi=class extends A{constructor(e=E(`Invalid reference`)){super(e,k.InvalidReference)}},Hi=class extends A{constructor(e=E(`Data not available`)){super(e,k.NotAvailable)}},Ui=class extends A{constructor(e=E(`Unknown function`)){super(e,k.UnknownFunction)}},Wi=class extends A{constructor(e=E(`Spill range is not empty`),t){super(e,k.SpilledBlocked),this.errorOriginPosition=t}},Gi=class extends A{constructor(e=E(`Division by zero`)){super(e,k.DivisionByZero)}};let Ki=[`number`,`string`,`boolean`,`undefined`];function qi(e){if(e!==void 0)return Or(e)?e[0][0]?.format:e.format}function j(e){return typeof e==`string`&&Ri.has(e)}function Ji(e){return{value:k.NotAvailable,message:E(`Did not find value '%s' in [[FUNCTION_NAME]] evaluation.`,N(e))}}let Yi=e=>E(`The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.`,e),Xi=(e,t,n)=>E(`The function [[FUNCTION_NAME]] expects a number value between %s and %s inclusive, but receives %s.`,e.toString(),t.toString(),n.toString()),Zi=(e,t)=>E(`The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.`,t,e.map(e=>`'${e}'`).join(`, `));function M(e,t){let n=oa(e);switch(typeof n){case`number`:return n;case`boolean`:return+!!n;case`string`:if(Pi(n,t)||n===``)return Ii(n,t);let e=ii(n,t);if(e)return e.value;throw new A(Yi(n));default:return 0}}function Qi(e,t){try{return M(e,t)}catch{return}}function $i(e,t){return I(e).map(e=>e.map(e=>{if(typeof e.value!=`number`){let n=``;throw typeof e==`object`?n=E(`Function [[FUNCTION_NAME]] expects number values for %s, but got an empty value.`,t):typeof e==`string`?n=E(`Function [[FUNCTION_NAME]] expects number values for %s, but got a string.`,t):typeof e==`boolean`&&(n=E(`Function [[FUNCTION_NAME]] expects number values for %s, but got a boolean.`,t)),new A(n)}return e.value}))}function ea(e,t){let n=oa(e);if(n===``)throw new A(Yi(n));return M(n,t)}function ta(e,t){return Math.trunc(M(e,t))}function na(e,t){return Math.trunc(ea(e,t))}function N(e){let t=oa(e);switch(typeof t){case`string`:return t;case`number`:return t.toString();case`boolean`:return t?`TRUE`:`FALSE`;default:return``}}let ra=Vt(function(e){return e.toLowerCase().normalize(`NFD`).replace(/[\u0300-\u036f]/g,``)}),ia=e=>E(`The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a boolean.`,e);function P(e){let t=oa(e);switch(typeof t){case`boolean`:return t;case`string`:if(t){let e=t.toUpperCase();if(e===`TRUE`)return!0;if(e===`FALSE`)return!1;throw new A(ia(t))}else return!1;case`number`:return!!t;default:return!1}}function aa(e){let t=oa(e);if(t===``)throw new A(ia(t));return P(t)}function F(e,t){return mi(M(oa(e),t))}function oa(e){if(typeof e==`object`&&e&&`value`in e){if(j(e.value))throw e;return e.value}if(j(e))throw new A(``,e);return e}function sa(e,t,n){for(let r of e)if(Or(r)){let e=r.length,n=r[0].length;for(let i=0;i<n;i++)for(let n=0;n<e;n++)t(r[n][i])}else n(r)}function ca(e,t){sa(e,e=>{if(j(e.value))throw e;t(e)},e=>{if(j(e?.value))throw e;t(e)})}function la(e,t,n){sa(e,e=>{if(typeof e?.value==`number`&&t(e),j(e?.value))throw e},e=>{t({value:ea(e,n),format:e?.format})})}function ua(e,t,n,r,i=`rowFirst`){let a=r;for(let r of e)if(Or(r)){let e=r.length,n=r[0].length;if(i===`rowFirst`)for(let i=0;i<n;i++)for(let n=0;n<e;n++)a=t(a,r[n][i]);else for(let i=0;i<e;i++)for(let e=0;e<n;e++)a=t(a,r[i][e])}else a=n(a,r);return a}function da(e,t,n,r=`rowFirst`){return ua(e,t,t,n,r)}function fa(e,t,n,r){return ua(e,(e,n)=>{let r=n?.value;if(typeof r==`number`)return t(e,r);if(j(r))throw n;return e},(e,n)=>t(e,ea(n,r)),n)}function pa(e,t,n,r){return ua(e,(e,n)=>{let i=n?.value;if(i!=null){if(typeof i==`number`)return t(e,i);if(typeof i==`boolean`)return t(e,M(i,r));if(j(i))throw n;return t(e,0)}return e},(e,n)=>t(e,M(n,r)),n)}function ma(e,t,n){let r=Array(e);for(let i=0;i<e;i++){r[i]=Array(t);for(let e=0;e<t;e++)r[i][e]=n(i,e)}return r}function ha(e,t){return e.length===0?[]:ma(e.length,e[0].length,(n,r)=>t(e[n][r]))}function ga(e,t){let n=e.length,r=e[0]?.length??0;for(let i=0;i<n;i++)for(let n=0;n<r;n++)t(e[i][n])}function _a(e){return e.length?ma(e[0].length,e.length,(t,n)=>e[n][t]):[]}function va(e,t,n=void 0){let r=1,i=1,a=1/0,o=1/0,s;for(let e=0;e<t.length;e++){let c=t[e];if(Or(c)&&(n===void 0||n[e])){let n=c.length,l=c[0].length;n!==1||l!==1?(s??=Array(t.length),n!==1&&l!==1?(s[e]=`matrix`,r=Math.max(r,n),i=Math.max(i,l),a=Math.min(a,n),o=Math.min(o,l)):n===1?l!==1&&(s[e]=`vertical`,i=Math.max(i,l),o=Math.min(o,l)):(s[e]=`horizontal`,r=Math.max(r,n),a=Math.min(a,n))):t[e]=c[0][0]}}if(r===1&&i===1)return e(...t);let c=(e,n)=>t.map((t,r)=>{switch(s?.[r]){case`matrix`:return t[e][n];case`horizontal`:return t[e][0];case`vertical`:return t[0][n];case void 0:return t}});return ma(r,i,(t,n)=>{if(t>a-1||n>o-1)return new Hi(E(`Array arguments to [[FUNCTION_NAME]] are of different size.`));let r=e(...c(t,n));return Or(r)?r[0][0]:r})}function ya(e,t,n){for(let r of e)if(Or(r)){let e=r.length,n=r[0].length;for(let i=0;i<n;i++)for(let n=0;n<e;n++)if(!t(r[n][i]??void 0))return}else if(!n(r))return}function ba(e,t){return ya(e,e=>{let n=e?.value;if(typeof n==`boolean`)return t(n);if(typeof n==`number`)return t(!!n);if(j(n))throw e;return!0},e=>e!==void 0&&e.value!==null?t(aa(e)):!0)}function xa(e,t){let n,r,i=e.substring(0,2);return i===`<=`||i===`>=`||i===`<>`?(n=i,r=e.substring(2)):(i=e.substring(0,1),i===`<`||i===`>`||i===`=`?(n=i,r=e.substring(1)):(n=`=`,r=e)),Pi(r,t)||ni(r,t)?r=M(r,t):(r===`TRUE`||r===`FALSE`)&&(r=P(r)),{operator:n,operand:r}}let Sa=Vt(function(e){if(e===`*`)return/.+/;let t=``,n=``;for(let r of e)r===`?`&&n!==`~`?t+=`.`:r===`*`&&n!==`~`?t+=`.*`:((r===`*`||r===`?`)&&(t=t.slice(0,-1)),[`^`,`.`,`[`,`]`,`$`,`(`,`)`,`*`,`+`,`?`,`|`,`{`,`}`,`\\`].includes(r)&&(t+=`\\`),t+=r),n=r;return RegExp(`^`+t+`$`,`i`)});function Ca(e=``,t,n){let{operator:r,operand:i}=t;if(i===void 0||e===null||i===null)return!1;if(typeof i==`number`&&r===`=`)return typeof e==`string`&&(Pi(e,n)||ni(e,n))?M(e,n)===i:e===i;if(r===`<>`||r===`=`){let t;return t=typeof e==typeof i?typeof e==`string`&&typeof i==`string`?Sa(i).test(e):e===i:!1,r===`=`?t:!t}if(typeof e==typeof i)switch(r){case`<`:return e<i;case`>`:return e>i;case`<=`:return e<=i;case`>=`:return e>=i}return!1}function wa(e,t,n,r=!1){let i=e.length;if(i%2==1)throw new A(E(`Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs.`));let a=I(e[0]),o=a.length,s=a[0].length,c=[];for(let t=0;t<i-1;t+=2){let i=I(e[t]);if(i.length!==o||i[0].length!==s)throw new A(E(`Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension`));let a=xa(N(e[t+1]),n);r&&typeof a.operand==`string`&&(a.operand+=`*`),c.push(a)}for(let r=0;r<o;r++)for(let a=0;a<s;a++){let o=!0;for(let t=0;t<i-1;t+=2){let i=I(e[t])[r][a].value,s=c[t/2];if(o=Ca(i??void 0,s,n),!o)break}o&&t(r,a)}}function Ta(e,t,n,r,i,a){if(t===void 0||t.value===null)return-1;if(j(t.value))throw t;let o=Oa(t.value),s=typeof o,c,l,u=0,d=i-1,f,p,m,h,g=r===`desc`?t=>Oa(a(e,i-t-1)):t=>Oa(a(e,t));for(;d-u>=0;){for(f=Math.floor((u+d)/2),p=f,m=g(p),h=typeof m;u<p&&s!==h;)p--,m=g(p),h=typeof m;if(h!==s||m==null){u=f+1;continue}n===`strict`&&m===o?(c=m,l=p):n===`nextSmaller`&&m<=o?(c==null||c<m||c===m&&l<p)&&(c=m,l=p):n===`nextGreater`&&m>=o&&(c===void 0||c>m||c===m&&l<p)&&(c=m,l=p),m>o||n===`strict`&&m===o?d=p-1:u=f+1}return l===void 0?-1:r===`desc`?i-l-1:l}function Ea(e,t,n,r,i,a,o=!1){if(t===void 0||t.value===null)return-1;if(j(t.value))throw t;let s=Oa(t.value),c=o?(e,t)=>Oa(i(e,r-t-1)):(e,t)=>Oa(i(e,t)),l=n!==`wildcard`||typeof s!=`string`||!(s.includes(`*`)||s.includes(`?`));if(a&&l){let t=o?`reverseSearch`:`forwardSearch`,i=a[t].get(e);if(i===void 0){i=new Map;for(let t=0;t<r;t++){let n=c(e,t)??null;i.has(n)||i.set(n,t)}a[t].set(e,i)}if(i.has(s)){let e=i.get(s);return o?r-e-1:e}if(n===`strict`)return-1}let u=Da(e,s,n,r,c);return o&&u!==-1?r-u-1:u}function Da(e,t,n,r,i){let a=n=>i(e,n)===t;if(n===`wildcard`&&typeof t==`string`&&(t.includes(`*`)||t.includes(`?`))){let n=Sa(t);a=t=>{let r=i(e,t);return typeof r==`string`?n.test(r):!1}}let o,s=-1;n===`nextSmaller`&&(a=n=>{let r=i(e,n);return(!o&&ka(t,r)>=0||ka(t,r)>=0&&ka(r,o)>0)&&(o=r,s=n),r===t}),n===`nextGreater`&&(a=n=>{let r=i(e,n);return(!o&&ka(t,r)<=0||ka(t,r)<=0&&ka(r,o)<0)&&(o=r,s=n),r===t});for(let e=0;e<r;e++)if(a(e))return e;return s}function Oa(e){return typeof e==`string`?ra(e):e}function ka(e,t){let n=Ki.indexOf(typeof e)-Ki.indexOf(typeof t);return n===0&&(typeof e==`string`&&typeof t==`string`?n=e.localeCompare(t):typeof e==`number`&&typeof t==`number`?n=e-t:typeof e==`boolean`&&typeof t==`boolean`&&(n=Number(e)-Number(t))),n}function I(e){return e===void 0?[[]]:Or(e)?e:[[e]]}function Aa(e,t){return da(e,(e,n)=>(e.push(t(n)),e),[],`rowFirst`)}function ja(e){if(e===void 0)return!1;let{value:t}=e;return!(t===null||t===``)}let Ma=E(`[[FUNCTION_NAME]] has no valid input data.`);function Na(e){return E(`[[FUNCTION_NAME]] expects the provided values of %(argName)s to be a non-empty matrix.`,{argName:e})}function Pa(e){let t=new Xt(e),n=[],r=[];for(n.push(r);!t.isOver();){if(t.current===`;`){r=[],n.push(r),t.shift();continue}let e=Ha(t)||Fa(t)||La(t)||Ra(t)||Ba(t)||Va(t)||Wa(t)||za(t)||Ga(t);if(!e)throw Error(`Unknown token at `+t.remaining());r.push(e)}return n}function Fa(e){let t;if(e.current===`"`?(e.shift(),t=`"`):e.currentStartsWith(`[$`)&&(e.advanceBy(2),t=`]`),!t)return null;let n=``;for(;e.current&&e.current!==t;)n+=e.shift();if(e.current===t)e.shift();else throw Error(`Unterminated string in format`);return{type:`STRING`,value:n}}let Ia=new Set(`$+-/():!^&~{}<>= `);function La(e){if(e.current===`\\`){e.shift();let t=e.shift();if(!t)throw Error(`Unexpected end of format string`);return{type:`CHAR`,value:t}}return Ia.has(e.current)?{type:`CHAR`,value:e.shift()}:null}function Ra(e){return e.current===`,`?(e.shift(),{type:`THOUSANDS_SEPARATOR`,value:`,`}):null}function za(e){return e.current===`@`?(e.shift(),{type:`TEXT_PLACEHOLDER`,value:`@`}):null}function Ba(e){return e.current===`.`?(e.shift(),{type:`DECIMAL_POINT`,value:`.`}):null}function Va(e){return e.current===`%`?(e.shift(),{type:`PERCENT`,value:`%`}):null}function Ha(e){if(e.current===`0`||e.current===`#`){let t=e.current;return e.shift(),{type:`DIGIT`,value:t}}return null}let Ua=new Set(`dmqyhsa`);function Wa(e){if(!Ua.has(e.current))return null;let t=e.current,n=``;for(;e.current===t;)n+=e.shift();return{type:`DATE_PART`,value:n}}function Ga(e){if(e.current!==`*`)return null;e.shift();let t=e.shift();if(!t)throw Error(`Unexpected end of format string`);return{type:`REPEATED_CHAR`,value:t}}let Ka={};function qa(e){let t=Ka[e];return t===void 0&&(t=Ja(e),Ka[e]=t),t}function Ja(e){let t=Pa(e);for(let e of t){let t=e.filter(e=>e.type===`REPEATED_CHAR`);for(let e of t.slice(1))e.type=`CHAR`}let n=$a(t[0])||Qa(t[0])||eo(t[0]);if(!n)throw Error(`Invalid first format part of: `+e);if(t.length>1&&n.type===`text`)throw Error(`The first format in a multi-part format must be a number format: `+e);let r=$a(t[1])||Qa(t[1]);if(t[1]?.length&&!r)throw Error(`Invalid second format part of: `+e);let i=$a(t[2])||Qa(t[2]);if(t[2]?.length&&!i)throw Error(`Invalid third format part of: `+e);let a=eo(t[3]);if(t[3]?.length&&!a)throw Error(`Invalid fourth format part of: `+e);return{positive:n,negative:r,zero:i,text:a}}function Ya(e){return e.every(e=>e.type===`DATE_PART`||e.type===`DECIMAL_POINT`||e.type===`THOUSANDS_SEPARATOR`||e.type===`STRING`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function Xa(e){return e.every(e=>e.type===`DIGIT`||e.type===`DECIMAL_POINT`||e.type===`THOUSANDS_SEPARATOR`||e.type===`PERCENT`||e.type===`STRING`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function Za(e){return e.every(e=>e.type===`STRING`||e.type===`TEXT_PLACEHOLDER`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function Qa(e){if(!e||!Xa(e))return;let t=[],n,r=t,i=0,a=0,o=e.findLastIndex(e=>e.type===`DIGIT`),s=!1,c=0;for(let l=0;l<e.length;l++){let u=e[l];switch(u.type){case`DIGIT`:r===t?r.push(u):c<20&&(r.push(u),c++);break;case`DECIMAL_POINT`:if(r===t)n=[],r=n;else throw Error(`Multiple decimal points in a number format`);break;case`REPEATED_CHAR`:case`CHAR`:case`STRING`:r.push(u);break;case`PERCENT`:i++,r.push(u);break;case`THOUSANDS_SEPARATOR`:l-1===o?(a+=1,o++,r.push(u)):e[l+1]?.type===`DIGIT`&&e[l-1]?.type===`DIGIT`?(r===t&&(s=!0),r.push(u)):r.push({type:`CHAR`,value:`,`});break}}return{type:`number`,integerPart:t,decimalPart:n,percentSymbols:i,thousandsSeparator:s,magnitude:a}}function $a(e){let t=e&&Ya(e)?{type:`date`,tokens:e}:void 0;if(t){if(t.tokens.length&&t.tokens.every(e=>e.type===`DATE_PART`&&e.value===`a`))throw Error(`Invalid date format`);return{type:`date`,tokens:to(t.tokens.map(e=>e.type===`THOUSANDS_SEPARATOR`||e.type===`DECIMAL_POINT`?{type:`CHAR`,value:e.value}:e))}}}function eo(e){return e&&Za(e)?{type:`text`,tokens:e}:void 0}function to(e){let t=e.filter(e=>e.type===`DATE_PART`);for(let e=0;e<t.length;e++)!t[e].value.startsWith(`m`)||t[e].value.length>2||(t[e-1]?.value.startsWith(`h`)||t[e+1]?.value.startsWith(`s`))&&(t[e].value=t[e].value.replaceAll(`m`,`M`));return e}function no(e){return[ro(e.positive),ro(e.negative),ro(e.zero),ro(e.text)].filter(C).join(`;`)}function ro(e){if(!e)return;let t=``,n=e.type===`number`?io(e):e.tokens;for(let e of n)switch(e.type){case`STRING`:t+=`[$${e.value}]`;break;case`CHAR`:t+=ao(e.value)?`\\${e.value}`:e.value;break;case`REPEATED_CHAR`:t+=`*`+e.value;break;case`DATE_PART`:t+=e.value===`MM`?`mm`:e.value;break;default:t+=e.value}return t}function io(e){let t=[...e.integerPart];return e.decimalPart&&(t.push({type:`DECIMAL_POINT`,value:`.`}),t.push(...e.decimalPart)),t}function ao(e){return!Ia.has(e)}let oo=`REPEATED_CHAR_PLACEHOLDER_`,so={0:E(`January`),1:E(`February`),2:E(`March`),3:E(`April`),4:E(`May`),5:E(`June`),6:E(`July`),7:E(`August`),8:E(`September`),9:E(`October`),10:E(`November`),11:E(`December`)},co={0:E(`Sunday`),1:E(`Monday`),2:E(`Tuesday`),3:E(`Wednesday`),4:E(`Thursday`),5:E(`Friday`),6:E(`Saturday`)};function L(e,{format:t,locale:n,formatWidth:r}){switch(typeof e==`boolean`&&(e=e?`TRUE`:`FALSE`),typeof e){case`string`:{if(e.includes(`\\"`)&&(e=e.replaceAll(/\\"/g,`"`)),!t)return e;let n=qa(t),i=n.text||n.positive;return!i||i.type!==`text`?e:lo(e,i,r)}case`number`:t||=Eo(e);let i=qa(t);if(i.positive.type===`text`)return lo(e.toString(),i.positive,r);let a=i.positive;if(e<0&&i.negative?(a=i.negative,e=-e):e===0&&i.zero&&(a=i.zero),a.type===`date`)return uo(Co(e,a),r);let o=e<0,s=uo(fo(Math.abs(e),a,n),r);return o?`-`+s:s;case`object`:return``}}function lo(e,t,n){let r=``;for(let n of t.tokens)switch(n.type){case`TEXT_PLACEHOLDER`:r+=e;break;case`CHAR`:case`STRING`:r+=n.value;break;case`REPEATED_CHAR`:r+=oo+n.value;break}return uo(r,n)}function uo(e,t){let n=e.indexOf(oo);if(n===-1)return e;let r=e.slice(0,n),i=e.slice(n+26+1),a=e[n+26];function o(){if(!t)return{timesToRepeat:0,padding:``};let e=t.measureText(r+i),n=t.measureText(a),o=t.availableWidth-e;if(o<=0)return{timesToRepeat:0,padding:``};let s=Math.floor(o/n),c=o-s*n,l=t.measureText(` `);return{timesToRepeat:s,padding:` `.repeat(Math.floor(c/l))}}let{timesToRepeat:s,padding:c}=o();return r+a.repeat(s)+c+i}function fo(e,t,n){if(e===1/0)return`∞`+(t.percentSymbols?`%`:``);let r=t.percentSymbols*2-t.magnitude*3;e*=10**r;let i=0;t.decimalPart!==void 0&&(i=t.decimalPart.filter(e=>e.type===`DIGIT`).length);let{integerDigits:a,decimalDigits:o}=go(Math.abs(e),i),s=po(a,t,t.thousandsSeparator?n.thousandsSeparator:void 0);return t.decimalPart!==void 0&&(s+=n.decimalSeparator+mo(o||``,t)),s}function po(e,t,n){let r=t.integerPart;r.some(e=>e.type===`DIGIT`)||(r=[...r,{type:`DIGIT`,value:`#`}]),e===`0`&&(e=``);let i=``,a=r.findIndex(e=>e.type===`DIGIT`),o=e.length-1;function s(t,r){if(r===`0`&&(t||=`0`),!t)return;let a=e.length-1-o;i=n&&a>0&&a%3==0?t+n+i:t+i}for(let t=r.length-1;t>=0;t--){let n=r[t];switch(n.type){case`DIGIT`:let r=e[o];if(s(r,n.value),o--,a===t)for(;o>=0;)s(e[o],`0`),o--;break;case`THOUSANDS_SEPARATOR`:break;case`REPEATED_CHAR`:i=oo+n.value+i;break;default:i=n.value+i;break}}return i}function mo(e,t){if(!t.decimalPart)return``;let n=``,r=0;for(let i of t.decimalPart)switch(i.type){case`DIGIT`:let t=i.value===`#`?e[r]||``:e[r]||`0`;n+=t,r++;break;case`THOUSANDS_SEPARATOR`:break;case`REPEATED_CHAR`:n+=oo+i.value;break;default:n+=i.value;break}return n}let ho=[];function go(e,t=20){let n=e.toString();if(n.includes(`e`))return bo(e,t);if(Number.isInteger(e))return{integerDigits:n,decimalDigits:void 0};let r=n.indexOf(`.`),i=n.substring(0,r),a=n.substring(r+1);if(t===0)return Number(a[0])>=5&&(i=(Number(i)+1).toString()),{integerDigits:i,decimalDigits:void 0};if(a.length>t){let{integerDigits:e,decimalDigits:n}=yo(a,t);a=n,e!==`0`&&(i=(Number(i)+Number(e)).toString())}return{integerDigits:i,decimalDigits:_o(a||``)}}function _o(e){let t=e.length-1;for(;t>=0&&e[t]===`0`;)t--;return e.slice(0,t+1)||void 0}let vo=/^0+/;function yo(e,t){let n=`0`,r=e,i=e.slice(0,t);if(Number(e[t])<5)return{integerDigits:n,decimalDigits:i};let a=i.match(vo)?.[0]||``,o=(Number(i)+1).toString(),s=i.slice(a.length),c=o.length>s.length;return c&&!a?(n=`1`,r=void 0):r=c?a.slice(0,-1)+o:a+o,{integerDigits:n,decimalDigits:r}}function bo(e,t=20){let n=ho[t];n||(n=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:t,useGrouping:!1}),ho[t]=n);let[r,i]=n.format(e).split(`.`);return{integerDigits:r,decimalDigits:i}}function xo(e,t){let{integerDigits:n,decimalDigits:r}=go(e,20);return r?n+t+r:n}let So=Vt(function(e){if(!e)return!1;try{return qa(e).positive.type===`date`}catch{return!1}});function Co(e,t){let n=mi(e);if(isNaN(n.getTime()))return e.toString();let r=t.tokens.some(e=>e.type===`DATE_PART`&&e.value===`a`),i=``;for(let e of t.tokens)switch(e.type){case`DATE_PART`:i+=wo(n,e.value,r);break;case`REPEATED_CHAR`:i+=oo+e.value;break;default:i+=e.value;break}return i}function wo(e,t,n){switch(t){case`d`:return e.getDate();case`dd`:return e.getDate().toString().padStart(2,`0`);case`ddd`:return co[e.getDay()].slice(0,3);case`dddd`:return co[e.getDay()].toString();case`m`:return e.getMonth()+1;case`mm`:return String(e.getMonth()+1).padStart(2,`0`);case`mmm`:return so[e.getMonth()].slice(0,3);case`mmmm`:return so[e.getMonth()].toString();case`mmmmm`:return so[e.getMonth()].slice(0,1);case`qq`:return E(`Q%(quarter)s`,{quarter:e.getQuarter()}).toString();case`qqqq`:return E(`Quarter %(quarter)s`,{quarter:e.getQuarter()}).toString();case`yy`:let r=String(e.getFullYear()).replace(`-`,``).padStart(2,`0`);return r.slice(r.length-2);case`yyyy`:return String(e.getFullYear()).replace(`-`,``).padStart(4,`0`);case`hhhh`:return Math.floor((e.getTime()-Ur.getTime())/(3600*1e3)).toString();case`hh`:let i=e.getHours();return n&&(i=i===0?12:i>12?i-12:i),i.toString().padStart(2,`0`);case`MM`:return e.getMinutes().toString().padStart(2,`0`);case`ss`:return e.getSeconds().toString().padStart(2,`0`);case`a`:return e.getHours()>=12?`PM`:`AM`;default:throw Error(`invalid date format token: ${t}`)}}let To=Vt(function(e){return RegExp(`[0-9]+${ot(e.decimalSeparator)}[0-9]`)});function Eo(e){let{integerDigits:t,decimalDigits:n}=go(e);if(!n)return`0`;let r=t.replace(`-`,``).length;if(r+2>11)return`0`;let i=11-r-1;return{decimalDigits:n}=go(e,Math.min(i,n.length)),n?`0.`+`0`.repeat(n.length):`0`}function Do(e,t){if(ni(e,t))return ii(e,t).format}function Oo(e){let t=e.includes(`.`)?`0.00`:`0`,n=e.match(/[\$€]/);if(n){let r=e.match(/[\d]/),i=`[$`+n.values().next().value+`]`;return r.index<n.index?`#,##`+t+i:i+`#,##`+t}if(e.includes(`%`))return t+`%`}function ko(e){let t=e.decimalPlaces??2,n=e.position??`before`,r=e.code??``,i=e.symbol??``,a=`#,##0`+(t?`.`+`0`.repeat(t):``),o=`${r} ${i}`.trim();return n===`after`&&r&&(o=` `+o),Mo(o,n,a)}function Ao(e){let t=e.decimalPlaces??2,n=e.position??`before`,r=e.code??``,i=e.symbol??``,a=`#,##0`+(t?`.`+`0`.repeat(t):``),o=`${r} ${i}`.trim();return n===`after`&&r&&(o=` `+o),[jo(o,n,` ${a} `),jo(o,n,`(${a})`),jo(o,n,` - `)].join(`;`)}function jo(e,t,n){let r=`[$${e}]`;return t===`before`?r+`* `+n:n+`* `+r}function Mo(e,t,n){let r=`[$${e}]`;return t===`before`?r+n:n+r}function No(e){let t=qa(e);return no({positive:Po(t.positive),negative:t.negative?Po(t.negative):void 0,zero:t.zero?Po(t.zero):void 0,text:t.text})}function Po(e){if(e.type!==`number`||!e.decimalPart)return e;let t=e.decimalPart.filter(e=>e.type!==`DIGIT`);return{...e,decimalPart:void 0,integerPart:[...e.integerPart,...t]}}function Fo({value:e,format:t},n){return L(e,{format:Io({value:e,format:t},void 0,n),locale:n})}function Io(e,t,n){let r=0;try{r=Math.abs(M(e?.value,n))}catch{return``}let i=e?.format;if(t!==void 0)switch(t?.value){case`k`:return Lo(i,1,`k`,n);case`m`:return Lo(i,2,`m`,n);case`b`:return Lo(i,3,`b`,n);default:throw new A(E(`The formatting unit should be 'k', 'm' or 'b'.`))}return r<1e5?Lo(i,0,``,n):r<1e8?Lo(i,1,`k`,n):r<1e11?Lo(i,2,`m`,n):Lo(i,3,`b`,n)}function Lo(e,t,n,r){let i=qa(e||`#,##0`);return no({positive:Ro(i.positive,t,n),negative:i.negative?Ro(i.negative,t,n):void 0,zero:i.zero?Ro(i.zero,t,n):void 0,text:i.text})}function Ro(e,t,n){if(e.type!==`number`)return e;let r=Po(e),i={type:`STRING`,value:n},a=[...r.integerPart],o=a.findLastIndex(e=>e.type===`DIGIT`);if(o===-1)throw Error(`Cannot create a large number format from a format with no digit.`);for(;a[o+1]?.type===`THOUSANDS_SEPARATOR`;)a=Ht(a,[o+1]);let s=a[o+1];a=s?.type===`STRING`&&[`m`,`k`,`b`].includes(s.value)?Wt(a,i,o+1):Ut(a,[i],o+1),t>0&&(a=Ut(a,Array(t).fill({type:`THOUSANDS_SEPARATOR`,value:`,`}),o+1));let c=r.percentSymbols-a.filter(e=>e.type===`PERCENT`).length;return a.push(...Array(c).fill({type:`PERCENT`,value:`%`})),{...r,integerPart:a,magnitude:t}}function zo(e,t){let n=qa(e);return no(qa(no({positive:Bo(n.positive,t),negative:n.negative?Bo(n.negative,t):void 0,zero:n.zero?Bo(n.zero,t):void 0,text:n.text})))}function Bo(e,t){return e.type===`number`?t>0?Ho(e,t):Vo(e,Math.abs(t)):e}function Vo(e,t){let n=e.decimalPart;if(!n)return e;let r=[],i=0;for(let e=n.length-1;e>=0&&!(i>=Math.abs(t));e--)n[e].type===`DIGIT`&&(i++,r.push(e));return n=Ht(n,r),n.some(e=>e.type===`DIGIT`)?{...e,decimalPart:n}:{...e,decimalPart:void 0,integerPart:[...e.integerPart,...n]}}function Ho(e,t){let n=e.integerPart,r=e.decimalPart;if(!r){let e=n.findLastIndex(e=>e.type===`DIGIT`);r=n.slice(e+1),n=n.slice(0,e+1)}let i=S(0,t).map(()=>({type:`DIGIT`,value:`0`})),a=r.findLastIndex(e=>e.type===`DIGIT`);return r=a===-1?[...i,...r]:Ut(r,i,a+1),{...e,decimalPart:r,integerPart:n}}function Uo(e){let t=qa(e);for(let e of[t.positive,t.negative,t.zero])if(e&&e.type===`date`&&e.tokens.some(e=>e.type===`DATE_PART`&&e.value.includes(`q`)))return!1;return!0}function Wo(e){if(!e)return!1;try{return qa(e).positive.type===`text`}catch{return!1}}function Go(e,t){return qo({value:Wo(t.format)&&e.parsedValue!==null?e.content:e.parsedValue,format:t.format},t.locale)}function Ko(e,t){if(e.startsWith(`=`))throw Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);if(e===``)return null;if(Pi(e,D))return Ii(e,D);let n=ii(e,t);return n?n.value:mt(e)?e.toUpperCase()===`TRUE`:e}function qo(e,t=D,n){let r=Hr(e.value);if(!r)return Jo(e,t,n);let i=Ko(r.label,t);return{...Jo({value:i,format:e.format||(typeof i==`number`?Do(r.label,t)||Oo(r.label):void 0)},t,n),link:r}}function Jo(e,t,n){let{value:r,format:i,message:a,errorOriginPosition:o}=e;i=n?.format||i;let s=L(r,{format:i,locale:t});return j(r)?es(r,a,o):r===null?Zo(i):Wo(i)?Yo(N(r),i,s):typeof r==`number`?So(i||``)?Qo(r,i,s):Xo(r,i,s):typeof r==`boolean`?$o(r,i,s):Yo(r,i,s)}function Yo(e,t,n){return{value:e,format:t,formattedValue:n,type:`text`,isAutoSummable:!0,defaultAlign:`left`}}function Xo(e,t,n){return{value:e||0,format:t,formattedValue:n,type:`number`,isAutoSummable:!0,defaultAlign:`right`}}let Zo=Vt(function(e){return{value:null,format:e,formattedValue:``,type:`empty`,isAutoSummable:!0,defaultAlign:`left`}});function Qo(e,t,n){return{value:e,format:t,formattedValue:n,type:`number`,isAutoSummable:!1,defaultAlign:`right`}}function $o(e,t,n){return{value:e,format:t,formattedValue:n,type:`boolean`,isAutoSummable:!1,defaultAlign:`center`}}function es(e,t,n){return{value:e,formattedValue:e,message:t,type:`error`,isAutoSummable:!1,defaultAlign:`center`,errorOriginPosition:n}}function ts(e){let t=O.now();switch(e){case`today`:return Math.floor(gi(t));case`yesterday`:return t.setDate(t.getDate()-1),Math.floor(gi(t));case`tomorrow`:return t.setDate(t.getDate()+1),Math.floor(gi(t));case`lastWeek`:return t.setDate(t.getDate()-6),Math.floor(gi(t));case`lastMonth`:{let e=t.getMonth()===0?11:t.getMonth()-1,n=new O(t.getFullYear(),e,1);return t.getDate()>_i(n)?t.setDate(1):(t.setDate(t.getDate()+1),t.setMonth(t.getMonth()-1)),Math.floor(gi(t))}case`lastYear`:return t.getMonth()===1&&t.getDate()===29?(t.setDate(28),t.setFullYear(t.getFullYear()-1)):(t.setDate(t.getDate()+1),t.setFullYear(t.getFullYear()-1)),Math.floor(gi(t))}}function ns(e,t){return`dateValue`in e&&e.dateValue!==`exactDate`?[ts(e.dateValue)]:e.values.map(e=>ti(e,t))}function rs(e,t){return e.map(e=>{if(e.startsWith(`=`))return e;let n=Ko(e,t);return typeof n==`number`?L(n,{format:t.dateFormat,locale:t}):``})}function R(e,t=[]){if(e.length<=1&&t.length===0)return e;let n=[0],r=new Map([[0,[]]]);return is(n,r,e,!1),is(n,r,t,!0),cs(n,r)}function is(e,t,n,r=!1){for(let i of n){let n=i.left,a=i.right===void 0?void 0:i.right+1,o=as(e,t,n,!0,0),s=as(e,t,a,!1,o);for(let n=o;n<=s;n++)os(t.get(e[n]),i,r);ss(e,t,o,s)}}function as(e,t,n,r,i){if(n===void 0)return e.length-1;let a=ls(e,n,i);return n===e[a]?r?a:a-1:(e.splice(a+1,0,n),t.set(n,[...t.get(e[a])]),r?a+1:a)}function os(e,t,n=!1){let r=t.top,i=t.bottom===void 0?void 0:t.bottom+1,a=[],o=ls(e,r,0,!1);if((o%2!=0&&!n||o%2==0&&n)&&a.push(r),i===void 0){e.splice(o+1),e.push(...a);return}let s=us(e,i,0,!1);(s%2==0&&!n||s%2!=0&&n)&&a.push(i),e.splice(o+1,s-o-1,...a)}function ss(e,t,n,r){let i=n-1==-1?0:n-1,a=r===e.length-1?r:r+1;for(let n=a;n>i;n--)Mt(t.get(e[n]),t.get(e[n-1]))&&(t.delete(e[n]),e.splice(n,1))}function cs(e,t){let n=[],r=[];for(let i=0;i<e.length;i++){let a=e[i],o=t.get(a);if(!o||o.length===0){n.push(...r),r=[];continue}let s=e[i+1];s!==void 0&&s--;let c=[];for(let e=0;e<o.length;e+=2){let t=o[e],n=o[e+1];n!==void 0&&n--;let i={top:t,left:a,bottom:n,right:s,hasHeader:n===void 0&&t!==0||s===void 0&&a!==0},l=!1;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.top===i.top&&t.bottom===i.bottom){t.right=i.right,r.splice(e,1),c.push(t),l=!0;break}}l||c.push(i)}n.push(...r),r=c}return n.push(...r),n}function ls(e,t,n=0,r=!0){let i=e.length-1,a=-1;for(;n<=i;){let o=Math.floor((n+i)/2);if(e[o]===t&&r)return o;e[o]<t?(a=o,n=o+1):i=o-1}return a}function us(e,t,n=0,r=!0){let i=e.length-1,a=e.length;for(;n<=i;){let o=Math.floor((n+i)/2);if(e[o]===t&&r)return o;e[o]>t?(a=o,i=o-1):n=o+1}return a}function ds(e){let t=new Xt(e);Jn(t);let n=e.indexOf(`!`);n!==-1&&t.advanceBy(n+1);let r=Yn(t),i=Xn(t),a,o,s,c,l=!1,u=!1,d=!1;if(i===-1?(s=c=r-1,a=o=0,l=!0):r===-1?(a=o=i-1,s=c=0,u=!0):(s=c=r-1,a=o=i-1,d=!0),Jn(t),t.current===`:`){t.advanceBy(1),Jn(t);let e=Yn(t),n=Xn(t);n===-1?(c=e-1,l=!0):e===-1?(o=n-1,u=!0):(c=e-1,o=n-1,a=l?o:a,s=u?c:s,d=!0)}let f={top:a,left:s,bottom:l?void 0:o,right:u?void 0:c};return d&&=u||l,d&&(f.hasHeader=d),f}function fs(e){let t=Is(ds(e)),n=t.bottom,r=t.right;if(n!==void 0&&n>9999998||r!==void 0&&r>qn)throw Error(`Range string out of bounds: ${e}`);if(n===void 0&&r===void 0)throw Error(`Wrong zone xc. The zone cannot be at the same time a full column and a full row`);return t}function ps(e){let t=fs(e);if(t.bottom===void 0||t.right===void 0)throw Error(`This does not support unbounded ranges`);return t}function ms(e){return gs(fs(e))}function hs(e){try{return ms(e)}catch{return!1}}function gs(e){let{bottom:t,top:n,left:r,right:i}=e;return t!==void 0&&isNaN(t)||isNaN(n)||isNaN(r)||i!==void 0&&isNaN(i)?!1:_s(e)&&e.top>=0&&e.left>=0}function _s(e){return(e.bottom===void 0||e.bottom>=e.top&&e.bottom>=0)&&(e.right===void 0||e.right>=e.left&&e.right>=0)}function vs(e){let{top:t,bottom:n,left:r,right:i}=e,a=`hasHeader`in e?e.hasHeader:!1,o=t===n&&r===i;if(n===void 0&&i!==void 0)return t===0&&!a?`${Hn(r)}:${Hn(i)}`:`${T(r,t)}:${Hn(i)}`;if(i===void 0&&n!==void 0)return r===0&&!a?`${t+1}:${n+1}`:`${T(r,t)}:${n+1}`;if(n!==void 0&&i!==void 0)return o?T(r,t):`${T(r,t)}:${T(i,n)}`;throw Error(`Bad zone format`)}function ys(e,t,n,r,i){let a=t===`left`?`columns`:`rows`,o=r===`before`?n-1:n,s=e[t===`left`?`right`:`bottom`];return e[t]<=o&&s&&s>o?Ls(e,a,`RESIZE`,i):o<e[t]?Ls(e,a,`MOVE`,i):{...e}}function bs(e,t,n,r,i){let a=t===`left`?`columns`:`rows`,o=r===`before`?n-1:n,s=t===`left`?`right`:`bottom`;return e[t]<=o&&e[s]>o?Ls(e,a,`RESIZE`,i):o<e[t]?Ls(e,a,`MOVE`,i):{...e}}function xs(e,t,n){let r=t===`left`?`right`:`bottom`,i=e[t],a=e[r];for(let o of n.sort((e,t)=>t-e))e[t]>o&&(i--,a--),e[t]<o&&e[r]>=o&&a--;return{...e,[t]:i,[r]:a}}function Ss(e,t,n){let r=t===`left`?`right`:`bottom`,i=e[t],a=e[r],o=e[r];for(let r of n.sort((e,t)=>t-e))e[t]>r&&(i--,a!==void 0&&a--),o!==void 0&&a!==void 0&&e[t]<=r&&o>=r&&a--;if(!(a!==void 0&&i>a))return{...e,[t]:i,[r]:a}}function Cs(...e){return{top:Math.min(...e.map(e=>e.top)),left:Math.min(...e.map(e=>e.left)),bottom:Math.max(...e.map(e=>e.bottom)),right:Math.max(...e.map(e=>e.right))}}function ws(...e){return{top:Math.min(...e.map(e=>e.top)),left:Math.min(...e.map(e=>e.left)),bottom:e.some(e=>e.bottom===void 0)?void 0:Math.max(...e.map(e=>e.bottom)),right:e.some(e=>e.right===void 0)?void 0:Math.max(...e.map(e=>e.right))}}function Ts(e,t){if(Ds(e,t))return{top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),bottom:Math.min(e.bottom,t.bottom),right:Math.min(e.right,t.right)}}function Es(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function Ds(e,t){return!(e.bottom<t.top||t.bottom<e.top||e.right<t.left||t.right<e.left)}function Os(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++)if(Ds(e[t],e[n]))return!0;return!1}function ks(e,t,n){let{left:r,right:i,top:a,bottom:o}=n;return e>=r&&e<=i&&t>=a&&t<=o}function As(e,t){return e.left>=t.left&&e.right<=t.right&&e.top>=t.top&&e.bottom<=t.bottom}function js(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function Ms(e){let{numberOfCols:t,numberOfRows:n}=js(e);return t===1||n===1}function Ns(e){let{top:t,left:n,bottom:r,right:i}=e;if(Ws(e)===1)return[];let a={top:t+1,bottom:r,left:n,right:n};if(i===n)return[a];let o={top:t,bottom:r,left:n+1,right:i};return t===r?[o]:[a,o]}function Ps(e){let t={};for(let n of e)t[n.sheetId]??=[],t[n.sheetId].push(z(n));for(let e in t)t[e]=R(t[e]);return t}function Fs(e){let t=[],{left:n,right:r,top:i,bottom:a}=Is(e);for(let e of S(n,r+1))for(let n of S(i,a+1))t.push({col:e,row:n});return t}function Is(e){return e.right!==void 0&&e.left>e.right&&(e={...e,left:e.right,right:e.left}),e.bottom!==void 0&&e.top>e.bottom&&(e={...e,top:e.bottom,bottom:e.top}),e}function Ls(e,t,n,r){let i=t===`both`?r[0]:t===`columns`?r:0,a=t===`both`?r[1]:t===`rows`?r:0,o=`hasHeader`in e?e.hasHeader:!1,s;s=Us(e)&&!o?t!==`rows`:Hs(e)&&!o?t!==`columns`:!0;let c={...e};return s&&n===`MOVE`&&(c.left+=i,c.top+=a),c.right!==void 0&&(c.right+=i),c.bottom!==void 0&&(c.bottom+=a),c}function Rs(e){return e.reverse().filter((e,t,n)=>t===n.findIndex(t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)).reverse()}function zs(e){return e.reduce((e,t)=>{let n=e.length;for(let r=0;r<n;r++)if(Ds(e[r],t))return e[r]=Cs(e[r],t),e;return e[n]=t,e},[])}function Bs(e,t){let n,r,{left:i,right:a,top:o,bottom:s}=e,{left:c,right:l,top:u,bottom:d}=t;return n=c===i?l===a?c:l:c,r=u===o?d===s?u:d:u,{col:n,row:r}}function z(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function Vs(e){return{...e,right:e.left,bottom:e.top}}function Hs(e){return e.right===void 0}function Us(e){return e.bottom===void 0}function Ws(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function Gs(e,t,n){return e.left<t&&t<=e.right||e.top<n&&n<=e.bottom}function Ks(e,t,n){return e.some(e=>Gs(e,t,n))}function qs(e,t){let{left:n,top:r,bottom:i,right:a}=e;if(a!==void 0&&i!==void 0)return e;if(i===void 0&&a!==void 0)return{right:a,top:r,left:n,bottom:t.numberOfRows-1};if(a===void 0&&i!==void 0)return{bottom:i,left:n,top:r,right:t.numberOfCols-1};throw Error(`Bad zone format`)}function Js(e){return e.length<2?!0:R(e).length===1}function Ys(e){let t=new Set;for(let n of R(e))for(let e of S(n.left,n.right+1))t.add(e);return t}function Xs(e){let t=new Set;for(let n of R(e))for(let e of S(n.top,n.bottom+1))t.add(e);return t}function Zs(e,t){return e.right+1===t.left||e.left===t.right+1?e.top<=t.bottom&&e.top>=t.top||t.top<=e.bottom&&t.top>=e.top:e.bottom+1===t.top||e.top===t.bottom+1?e.left<=t.right&&e.left>=t.left||t.left<=e.right&&t.left>=e.left:!1}function Qs(e){let t=[...e],n=!0;for(;n;){n=!1;for(let e=0;e<t.length;e++){let r=t[e],i=t.findIndex((t,n)=>e!==n&&(Zs(t,r)||Ds(t,r)));if(i!==-1){t[e]=Cs(t[i],r),t.splice(i,1),n=!0;break}}}return t}let $s=new WeakMap,ec=new WeakMap;function tc(e,t){$s.has(t)||($s.set(t,new Map),ec.set(t,0));let n=$s.get(t),r=ic(e);if(n.has(r)){let i=n.get(r);return t[i]=e,i}let i=ec.get(t)+1;return n.set(r,i),ec.set(t,i),t[i]=e,i}function nc(e){let t={};for(let n in e){let r=R(e[n].map(z));for(let e of r)t[vs(e)]=Number(n)}return t}function*rc(e,t){for(let n in t){let r=ps(n),i=t[n];for(let t=r.top;t<=r.bottom;t++)for(let n=r.left;n<=r.right;n++)yield[{sheetId:e,col:n,row:t},i]}}function ic(e){if(e===null)return`null`;if(e===void 0)return`undefined`;if(typeof e!=`object`)return String(e);if(Array.isArray(e)){let t=e.length,n=`[`;for(let r=0;r<t;r++)r>0&&(n+=`,`),n+=ic(e[r]);return n+`]`}let t=Object.keys(e).sort(),n=`{`;for(let r of t)e[r]!==void 0&&(n+=`"${r}":${ic(e[r])},`);return n+=`}`,n}function ac(e){return 20+120*Math.exp(-.035*(e-1))}let oc=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,`i`),sc=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,`i`),cc=new RegExp(/^\$?([A-Z]{1,3})+$/,`i`),lc=new RegExp(/^\$?([0-9]{1,7})+$/,`i`),uc=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,`i`),dc=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,`i`),fc=RegExp(`^\\s*('.+'!|[^']+!)?(`+[oc.source,`(\\$?[A-Z]{1,3})?\\$?[0-9]{1,7}\\s*:\\s*(\\$?[A-Z]{1,3})?\\$?[0-9]{1,7}\\s*`,`\\$?[A-Z]{1,3}(\\$?[0-9]{1,7})?\\s*:\\s*\\$?[A-Z]{1,3}(\\$?[0-9]{1,7})?\\s*`].join(`|`)+`)$`,`i`);function pc(e){return uc.test(e)}function mc(e){return dc.test(e)}function hc(e){return cc.test(e)}function gc(e){return lc.test(e)}function _c(e){return sc.test(e)}function vc(e){if(!e.includes(`!`))return{xc:e};let t=e.split(`!`),n=t.pop();return{sheetName:ct(t.join(`!`))||void 0,xc:n}}function yc(e,t){return e===void 0?t:`${ut(e)}!${t}`}function bc(e,t){let n=e.zone,r=qs(n,t(e.sheetId)),i=e.parts;return e.parts.length===1&&Ws(r)>1?i=[e.parts[0],e.parts[0]]:e.parts.length===2&&Ws(r)===1&&(i=[e.parts[0]]),{unboundedZone:n,zone:r,parts:i,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function xc(e,t){let n=e.xc,{xc:r,sheetName:i}=vc(n),a=fs(r);return bc({zone:a,parts:kc(r,a),sheetId:e.sheetId,prefixSheet:!!i,invalidSheetName:e.invalidSheetName},t)}function Sc(e){let t={left:-1,top:-1,right:-1,bottom:-1};return{sheetId:``,zone:t,unboundedZone:t,parts:[],invalidXc:e,prefixSheet:!1}}function Cc(e){return Us(e.unboundedZone)}function wc(e){return Hs(e.unboundedZone)}function Tc(e,t,n,r={useBoundedReference:!1,useFixedReference:!1}){if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0||e.zone.left<0||e.zone.top<0)return k.InvalidReference;let i=e.sheetId!==t||e.invalidSheetName||e.prefixSheet,a=``;if(i&&(a=e.invalidSheetName?ut(e.invalidSheetName):ut(n(e.sheetId))),i&&!a)return k.InvalidReference;let o=zc(e,0,r);return e.parts&&e.parts.length===2&&(e.zone.top!==e.zone.bottom||e.zone.left!==e.zone.right||e.parts[0].rowFixed||e.parts[0].colFixed||e.parts[1].rowFixed||e.parts[1].colFixed)&&(o+=`:`,o+=zc(e,1,r)),`${i?a+`!`:``}${o}`}function Ec(e,t,n){let r=n.sheetId===e?t:n.sheetId;return{...n,sheetId:r}}function Dc(e,t,n){if(!n)return;let r=e.getRangeFromSheetXC(t,n);return r.invalidSheetName||r.invalidXc?void 0:r}function Oc(e){let t=[];for(let n of e)for(let e of Fs(n.zone))t.push({...e,sheetId:n.sheetId});return t}function kc(e,t){let n=e.split(`:`).map(e=>{let t=mc(e);return{colFixed:t?!1:e.startsWith(`$`),rowFixed:t?e.startsWith(`$`):e.includes(`$`,1)}}),r=t.bottom===void 0,i=t.right===void 0;return r&&(n[0].rowFixed=n[0].rowFixed||n[1].rowFixed,n[1].rowFixed=n[0].rowFixed||n[1].rowFixed),i&&(n[0].colFixed=n[0].colFixed||n[1].colFixed,n[1].colFixed=n[0].colFixed||n[1].colFixed),n}function Ac(e){if(_s(e.zone))return e;let t={...e.unboundedZone},n={...e.zone},r=e.parts;if(t.right!==void 0&&t.right<t.left){let e=t.right;t.right=t.left,t.left=e,n.right=n.left,n.left=e,r=[{colFixed:r[1]?.colFixed||!1,rowFixed:r[0]?.rowFixed||!1},{colFixed:r[0]?.colFixed||!1,rowFixed:r[1]?.rowFixed||!1}]}if(t.bottom!==void 0&&t.bottom<t.top){let e=t.bottom;t.bottom=t.top,t.top=e,n.bottom=n.top,n.top=e,r=[{colFixed:r[0]?.colFixed||!1,rowFixed:r[1]?.rowFixed||!1},{colFixed:r[1]?.colFixed||!1,rowFixed:r[0]?.rowFixed||!1}]}return{unboundedZone:t,zone:n,parts:r,invalidXc:e.invalidXc,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function jc(e){return Mc.get(e.type)?.(e)}let Mc=new class extends g{add(e,t){return super.add(e,t),this}get(e){return this.content[e]}};Mc.add(`REMOVE_COLUMNS_ROWS`,e=>({applyChange:Nc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`ADD_COLUMNS_ROWS`,e=>({applyChange:Pc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`DELETE_SHEET`,e=>({applyChange:Fc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`RENAME_SHEET`,e=>({applyChange:Ic(e),sheetId:e.sheetId,sheetName:{old:e.oldName,current:e.newName}})).add(`MOVE_RANGES`,e=>({applyChange:Lc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}}));function Nc(e){let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`,i=[...e.elements];i.sort((e,t)=>t-e);let a=ft(i);return i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`,range:i};let o=i,s=`NONE`;for(let e of a){let a=Yt(e),c=Jt(e);if(i.zone[t]<=a&&a<=i.zone[n]){let e=Math.min(i.zone[n],c)-a+1;s=`RESIZE`,o=Rc(o,r,s,-e)}else if(i.zone[t]>=a&&i.zone[n]<=c)s=`REMOVE`,o=Sc(k.InvalidReference);else if(i.zone[t]<=c&&i.zone[n]>=c){let e=c-i.zone[t]+1;s=`RESIZE`,o=Rc(o,r,s,-e),o=Rc(o,r,`MOVE`,-(i.zone[t]-a))}else a<i.zone[t]&&(s=`MOVE`,o=Rc(o,r,s,-(c-a+1)))}return{changeType:s,range:o}}}function Pc(e){let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`;return i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`,range:i};if(e.position===`after`){if(i.zone[t]<=e.base&&e.base<i.zone[n])return{changeType:`RESIZE`,range:Rc(i,r,`RESIZE`,e.quantity)};if(e.base<i.zone[t])return{changeType:`MOVE`,range:Rc(i,r,`MOVE`,e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[n])return{changeType:`RESIZE`,range:Rc(i,r,`RESIZE`,e.quantity)};if(e.base<=i.zone[t])return{changeType:`MOVE`,range:Rc(i,r,`MOVE`,e.quantity)}}return{changeType:`NONE`,range:i}}}function Fc(e){return t=>{if(t.sheetId!==e.sheetId&&t.invalidSheetName!==e.sheetName)return{changeType:`NONE`,range:t};let n=e.sheetName;return t={...Sc(k.InvalidReference),invalidSheetName:n},{changeType:`REMOVE`,range:t}}}function Ic(e){return t=>{if(t.sheetId===e.sheetId)return{changeType:`CHANGE`,range:t};if(e.newName&&t.invalidSheetName===e.newName){let n=e.sheetId;return{changeType:`CHANGE`,range:{...t,sheetId:n,invalidSheetName:void 0}}}if(e.oldName&&t.invalidSheetName===e.oldName){let n=e.sheetId;return{changeType:`CHANGE`,range:{...t,sheetId:n,invalidSheetName:void 0}}}return{changeType:`NONE`,range:t}}}function Lc(e){let t=e.target[0];return n=>{if(n.sheetId!==e.sheetId||!As(n.zone,t))return{changeType:`NONE`,range:n};let r=e.targetSheetId,i=Rc(n,`both`,`MOVE`,[e.col-t.left,e.row-t.top]),a=e.sheetId===r?i.prefixSheet:!0;return{changeType:`MOVE`,range:{...i,sheetId:r,prefixSheet:a}}}}function Rc(e,t,n,r){return{...e,unboundedZone:Ls(e.unboundedZone,t,n,r),zone:Ls(e.zone,t,n,r)}}function zc(e,t,n={useBoundedReference:!1,useFixedReference:!1}){let r=e.parts[t]?.colFixed||n.useFixedReference?`$`:``,i=Hn(t===0?e.zone.left:e.zone.right),a=e.parts[t]?.rowFixed||n.useFixedReference?`$`:``,o=String(t===0?e.zone.top+1:e.zone.bottom+1),s=``;return s=Us(e.unboundedZone)&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:r+i:Hs(e.unboundedZone)&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:a+o:r+i+a+o,s}function Bc(e,t){e=e.toLocaleLowerCase(),t=t.toLocaleLowerCase();let n=0,r=0,i=t.length,a=0;for(let o=0;o<i;o++)t[o]===e[a]?(a++,r+=100+r-o/200):r=0,n+=r;return a===e.length?n:0}function Vc(e,t,n){let r=[];return t.forEach(t=>{let i=Bc(e,n(t));i>0&&r.push({score:i,elem:t})}),r.sort((e,t)=>t.score-e.score),r.map(e=>e.elem)}function Hc(e){let t=[];for(let n=0;n<e;n++)t.push({cells:{}});return t}function Uc(e,t,n){return n.map(n=>n>=e?n+t:n)}function Wc(e,t){return e=[...e].sort((e,t)=>t-e),t.map(t=>{for(let n of e)if(t>n)t--;else if(t===n)return;return t}).filter(C)}function Gc(e,t=`Sheet`){let n=1,r=`${t}${n}`;for(;e.includes(r);)r=`${t}${n}`,n++;return r}function Kc(e,t){let n=1,r=E(`Copy of %s`,e),i=r.toString();for(;t.includes(i);)i=`${r} (${n})`,n++;return i}function qc(e,t){return e===void 0||t===void 0?!1:ct(e.trim().toUpperCase())===ct(t.trim().toUpperCase())}function Jc(e,t=1){return t*(e+4)-4}function Yc(e,t,n,r){if(!t||!t.isFormula&&!t.content)return 23;let i=``;try{if(!t.isFormula){let e={format:t.format,locale:n};i=L(Ko(t.content,n),e)}}catch{i=k.GenericError}return Xc(e,i,t.style,r)}function Xc(e,t,n,r){let i=cl(e,t,n,n?.wrapping===`wrap`?r-8:void 0).length;return Jc(ol(n),i)+6}function Zc(e,t=!1,n=!1){return`${n?`italic`:``} ${t?`bold`:``} ${e}px ${He}`}let Qc={};function $c(e,t,n,r=`pt`){return el(e,t,al(n,r))}function el(e,t,n){if(Qc[n]||(Qc[n]={}),Qc[n][t]===void 0){let r=e.font;e.font=n,Qc[n][t]=e.measureText(t).width,e.font=r}return Qc[n][t]}let tl={};function nl(e,t,n,r=`pt`){let i=al(n,r);e.save(),e.font=i;let a=rl(e,t);return e.restore(),a}function rl(e,t){let n=e.font;if(tl[n]||(tl[n]={}),tl[n][t]===void 0){let r=e.measureText(t),i=r.width,a=r.fontBoundingBoxAscent+r.fontBoundingBoxDescent;tl[n][t]={width:i,height:a}}return tl[n][t]}function il(e){return Math.round(e*96/72)}function al(e,t=`pt`){return`${e.italic?`italic `:``}${e.bold?`bold`:`400`} ${(t===`pt`?ol(e):e.fontSize)??Ve}px ${He}`}function ol(e){return il(e?.fontSize||Ve)}function sl(e,t,n,r){if($c(e,t,r)<=n)return[t];let i=[],a=``;for(let o of t)$c(e,a+o,r)>n?(i.push(a),a=o):a+=o;return i.push(a),i}function cl(e,t,n,r){n||={},_t(t)&&(t=bt(t).label);let i=[],a=t.includes(`
|
|
4
|
+
`)}function Kt(e,t,n){return t>n?Kt(e,n,t):e>=t&&e<=n}function qt(e,t){let n=ot(e),r=t.matchCase?``:`i`;return t.exactMatch&&(n=`^${n}$`),RegExp(n,r)}function Jt(e){let t=e.length;if(t<1e5)return Math.max(...e);let n=-1/0;for(;t--;)n=e[t]>n?e[t]:n;return n}function Yt(e){let t=e.length;if(t<1e5)return Math.min(...e);let n=1/0;for(;t--;)n=e[t]<n?e[t]:n;return n}var Xt=class{text;currentIndex=0;current;constructor(e){this.text=e,this.current=e[0]}shift(){let e=this.current,t=this.text[++this.currentIndex];return this.current=t,e}advanceBy(e){this.currentIndex+=e,this.current=this.text[this.currentIndex]}isOver(){return this.currentIndex>=this.text.length}remaining(){return this.text.substring(this.currentIndex)}currentStartsWith(e){if(this.current!==e[0])return!1;for(let t=1;t<e.length;t++)if(this.text[this.currentIndex+t]!==e[t])return!1;return!0}};function Zt(e,t=e=>e){let n=new Set;return e.filter(e=>{let r=t(e);return n.has(r)?!1:(n.add(r),!0)})}function Qt(e){let t={};for(let n in e)for(let r in e[n])t[r]||(t[r]={}),t[r][n]=e[n][r];return t}function $t(e,t,n={}){let r=n.compute??((e,t)=>`${e} (${t})`),i=n.computeFirstOne??!1,a=n.start??1,o=i?r(e,a):e;for(;t.includes(o);)o=r(e,a++);return o}function en(e){return e.startsWith(`=`)||e.startsWith(`+`)}let tn=/rgba?\(|\s+|\)/gi,nn=/^#([A-F\d]{2}){3,4}$/,rn=[`#eb6d00`,`#0074d9`,`#ad8e00`,`#169ed4`,`#b10dc9`,`#00a82d`,`#00a3a3`,`#f012be`,`#3d9970`,`#111111`,`#62A300`,`#ff4136`,`#949494`,`#85144b`,`#001f3f`];function an(e,t=1){let n=t===1?``:Math.round(t*255).toString(16).padStart(2,`0`);return sn(e.toString(16).padStart(6,`0`))+n}function on(e){return typeof e==`number`?e:Number.parseInt(sn(e).slice(1,7),16)}function sn(e){let t=e;if(e.startsWith(`rgb`)?t=pn(e):(t=e.replace(`#`,``).toUpperCase(),(t.length===3||t.length===4)&&(t=t.split(``).reduce((e,t)=>e+t+t,``)),t=`#${t}`),!nn.test(t))throw Error(`invalid color input: ${e}`);return t}function cn(e){try{return sn(e),!0}catch{return!1}}function ln(e){try{return vn(e),!0}catch{return!1}}let un=e=>e>=0&&e<=255;function dn(e,t,n,r=1){if(!un(e)||!un(t)||!un(n)||r<0||r>1)throw Error(`Invalid RGBA values ${[e,t,n,r]}`);return{a:r,b:n,g:t,r:e}}function fn(e){let{r:t,g:n,b:r}=hn(e);t/=255,n/=255,r/=255;let i=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4,a=i(t),o=i(n),s=i(r);return .2126*a+.7152*o+.0722*s}function pn(e){let t=e.replace(tn,``).split(`,`),n=255;if(t.length!==3&&t.length!==4)throw Error(`invalid color`);if(t.length===4){let e=parseFloat(t.pop()||`1`);if(isNaN(e))throw Error(`invalid alpha value`);n=Math.round(e*255)}let r=t.map(e=>parseInt(e,10));return n!==255&&r.push(n),`#`+Ot(r.map(e=>e.toString(16).padStart(2,`0`))).toUpperCase()}function mn(e){let t=e.r.toString(16),n=e.g.toString(16),r=e.b.toString(16),i=Math.round(e.a*255).toString(16);return t.length===1&&(t=`0`+t),n.length===1&&(n=`0`+n),r.length===1&&(r=`0`+r),i.length===1&&(i=`0`+i),i===`ff`&&(i=``),(`#`+t+n+r+i).toUpperCase()}function hn(e){e=sn(e);let t,n,r,i;if(e.length===7)t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16),i=255;else if(e.length===9)t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16),i=parseInt(e[7]+e[8],16);else throw Error(`Invalid color`);return i=+(i/255).toFixed(3),{a:i,r:t,g:n,b:r}}function gn(e){e={...e},e.s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,n=t*(1-Math.abs(e.h/60%2-1)),r=e.l-t/2,i=0,a=0,o=0;return 0<=e.h&&e.h<60?(i=t,a=n,o=0):60<=e.h&&e.h<120?(i=n,a=t,o=0):120<=e.h&&e.h<180?(i=0,a=t,o=n):180<=e.h&&e.h<240?(i=0,a=n,o=t):240<=e.h&&e.h<300?(i=n,a=0,o=t):300<=e.h&&e.h<360&&(i=t,a=0,o=n),i=Math.round((i+r)*255),a=Math.round((a+r)*255),o=Math.round((o+r)*255),{a:e.a,r:i,g:a,b:o}}function _n(e){let t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=a-i,s=0,c=0,l=0;return s=o===0?0:a===t?(n-r)/o%6:a===n?(r-t)/o+2:(t-n)/o+4,s=Math.round(s*60),s<0&&(s+=360),l=(a+i)/2,c=o===0?0:o/(1-Math.abs(2*l-1)),c=+(c*100).toFixed(1),l=+(l*100).toFixed(1),{a:e.a,h:s,s:c,l}}function vn(e){return mn(gn(e))}function yn(e){return _n(hn(e))}function bn(e){return hn(typeof e==`number`?an(e):e)}function xn(e,t,n=0){if(!(cn(e)&&cn(t)))return!1;let r=hn(e),i=hn(t);return r.a===i.a?Math.sqrt(((r.r-i.r)/255)**2+((r.g-i.g)/255)**2+((r.b-i.b)/255)**2)<=n:!1}function Sn(e,t){return t===1?sn(e).slice(0,7):mn({...hn(e),a:t})}function Cn(e,t){let n=yn(e);return t===1?`#fff`:(n.l=t*(100-n.l)+n.l,vn(n))}function wn(e,t){let n=yn(e);return t===1?`#000`:(n.s=Math.min(100,t*n.s+n.s),n.l-=t*n.l,vn(n))}function Tn(e){return fn(e)<.6?Cn(e,.9):wn(e,.75)}let En=[`#4EA7F2`,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#FFD86D`],Dn=[`#4EA7F2`,`#3188E6`,`#43C5B1`,`#00A78D`,`#EA6175`,`#CE4257`,`#F4A261`,`#F48935`,`#8481DD`,`#5752D1`,`#FFD86D`,`#FFBC2C`],On=[`#4EA7F2`,`#3188E6`,`#056BD9`,`#A76DBC`,`#7F4295`,`#6D2387`,`#EA6175`,`#CE4257`,`#982738`,`#43C5B1`,`#00A78D`,`#0E8270`,`#F4A261`,`#F48935`,`#BE5D10`,`#8481DD`,`#5752D1`,`#3A3580`,`#A4A8B6`,`#7E8290`,`#545B70`,`#FFD86D`,`#FFBC2C`,`#C08A16`],kn=`#4EA7F2.#3188E6.#056BD9.#155193.#A76DBC.#7F4295.#6D2387.#4F1565.#EA6175.#CE4257.#982738.#791B29.#43C5B1.#00A78D.#0E8270.#105F53.#F4A261.#F48935.#BE5D10.#7D380D.#8481DD.#5752D1.#3A3580.#26235F.#A4A8B6.#7E8290.#545B70.#3F4250.#FFD86D.#FFBC2C.#C08A16.#936A12`.split(`.`),An=[`#4EA7F2`,`#43C5B1`,`#EA6175`,`#F4A261`,`#8481DD`,`#FFD86D`,`#3188E6`,`#00A78D`,`#CE4257`,`#F48935`,`#5752D1`,`#FFBC2C`],jn=[`#4EA7F2`,`#A76DBC`,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#A4A8B6`,`#FFD86D`,`#3188E6`,`#7F4295`,`#CE4257`,`#00A78D`,`#F48935`,`#5752D1`,`#7E8290`,`#FFBC2C`,`#056BD9`,`#6D2387`,`#982738`,`#0E8270`,`#BE5D10`,`#3A3580`,`#545B70`,`#C08A16`],Mn=`#4EA7F2.#A76DBC.#EA6175.#43C5B1.#F4A261.#8481DD.#A4A8B6.#FFD86D.#3188E6.#7F4295.#CE4257.#00A78D.#F48935.#5752D1.#7E8290.#FFBC2C.#056BD9.#6D2387.#982738.#0E8270.#BE5D10.#3A3580.#545B70.#C08A16.#155193.#4F1565.#791B29.#105F53.#7D380D.#26235F.#3F4250.#936A12`.split(`.`);function Nn(e,t){return t[e%t.length]}function Pn(e){return e<=6?En:e<=12?Dn:e<=24?On:kn}function Fn(e){return e<=6?En:e<=12?An:e<=24?jn:Mn}var In=class{preferredColors;currentColorIndex=0;palette;constructor(e,t=[]){this.preferredColors=t,this.palette=Pn(e).filter(e=>!t.includes(e))}next(){return this.preferredColors?.[this.currentColorIndex]?this.preferredColors[this.currentColorIndex++]:Nn(this.currentColorIndex++,this.palette)}},Ln=class extends In{constructor(e,t=[]){super(e,t),this.palette=Fn(e).filter(e=>!t.includes(e))}},Rn=class{availableColors;colors={};constructor(e=12){this.availableColors=new Ln(e)}get(e){return this.colors[e]||(this.colors[e]=this.availableColors.next()),this.colors[e]}};function zn(e){if(e.length<2)throw Error(`Color scale must have at least 2 points`);let t=[...e.sort((e,t)=>e.value-t.value)],n=[];for(let e=1;e<t.length;e++){let r=bn(t[e-1].color).a,i=bn(t[e].color).a,a=on(t[e-1].color),o=on(t[e].color);n.push({min:t[e-1].value,max:t[e].value,minColor:a,maxColor:o,minColorAlpha:r,maxColorAlpha:i,colorDiff:Bn(t[e-1].value,t[e].value,a,o)})}return e=>{if(e<n[0].min)return an(n[0].minColor,n[0].minColorAlpha);for(let t of n)if(e>=t.min&&e<=t.max)return an(Vn(e,t.min,t.minColor,t.colorDiff),t.maxColorAlpha);return an(n[n.length-1].maxColor,n[n.length-1].maxColorAlpha)}}function Bn(e,t,n,r){let i=t-e,a=(n>>16)%256-(r>>16)%256,o=(n>>8)%256-(r>>8)%256,s=n%256-r%256;return[a/i,o/i,s/i]}function Vn(e,t,n,r){let[i,a,o]=r,s=Math.round((n>>16)%256-i*(e-t)),c=Math.round((n>>8)%256-a*(e-t)),l=Math.round(n%256-o*(e-t));return s<<16|c<<8|l}function Hn(e){if(e<0)throw Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Hn(Math.floor(e/26)-1)+Hn(e%26)}function Un(e){let t=0,n=e.length;for(let r=0;r<n;r++){let n=Wn(e[r]);t=t*26+n}return t-1}function Wn(e){let t=e.charCodeAt(0);return t>=65&&t<=90?t-64:t-96}function Gn(e){return e>=`A`&&e<=`Z`||e>=`a`&&e<=`z`}function Kn(e){return e>=`0`&&e<=`9`}let qn=Un(`ZZZ`);function Jn(e){for(;e.current===` `;)e.advanceBy(1)}function Yn(e){if(e.current===`$`&&e.advanceBy(1),!e.current||!Gn(e.current))return-1;let t=0;for(;e.current&&Gn(e.current);)t=t*26+Wn(e.shift());return t}function Xn(e){if(e.current===`$`&&e.advanceBy(1),!e.current||!Kn(e.current))return-1;let t=0;for(;e.current&&Kn(e.current);)t=t*10+Number(e.shift());return t}function Zn(e){let t=new Xt(e);Jn(t);let n=Yn(t);if(n===-1||!t.current)throw Error(`Invalid cell description: ${e}`);let r=Xn(t);Jn(t);let i=n-1,a=r-1;if(!t.isOver()||i>qn||a>9999998)throw Error(`Invalid cell description: ${e}`);return{col:i,row:a}}function T(e,t,n={colFixed:!1,rowFixed:!1}){return(n.colFixed?`$`:``)+Hn(e)+(n.rowFixed?`$`:``)+String(t+1)}let Qn=e=>e,$n=()=>!1,er=Qn,tr=$n;function nr(e,...t){if(t.length===1&&typeof t[0]==`object`&&!(t[0]instanceof String)){let n=t[0];e=e.replace(/\%\(([^\)]+)\)s/g,(e,t)=>n[t])}else t.length>0&&(e=e.replace(/\%s/g,()=>t.shift()));return e}function rr(e,t=()=>!0){er=e,tr=t}function ir(){er===Qn&&tr===$n&&(tr=()=>!0)}let E=function(e,...t){return tr()?nr(er(e),...t):new ar(e,t)};var ar=class extends String{values;constructor(e,t){super(e),this.values=t}valueOf(){let e=super.valueOf();return tr()?nr(er(e),...this.values):nr(e,...this.values)}toString(){return this.valueOf()}};function or(e){return`sheetId`in e}function sr(e){return`dimension`in e&&`sheetId`in e&&`elements`in e}function cr(e){return`target`in e&&`sheetId`in e}function lr(e){return`ranges`in e}function ur(e){return`col`in e&&`row`in e&&`sheetId`in e}function dr(e){return`sheetId`in e&&`zone`in e}let fr=new Set([`RENAME_SHEET`,`DELETE_SHEET`,`CREATE_SHEET`,`DUPLICATE_SHEET`,`ADD_COLUMNS_ROWS`,`REMOVE_COLUMNS_ROWS`,`UNDO`,`REDO`,`ADD_MERGE`,`REMOVE_MERGE`,`UPDATE_LOCALE`,`ADD_PIVOT`,`UPDATE_PIVOT`,`INSERT_PIVOT`,`RENAME_PIVOT`,`REMOVE_PIVOT`,`DUPLICATE_PIVOT`]),pr=new Set([`EVALUATE_CELLS`,`EVALUATE_CHARTS`,`UPDATE_CELL`,`UNHIDE_COLUMNS_ROWS`,`HIDE_COLUMNS_ROWS`,`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUP`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_ALL_HEADER_GROUPS`,`UNFOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`UPDATE_TABLE`,`UPDATE_FILTER`,`UNDO`,`REDO`]),mr=new Set([`MOVE_RANGES`]),hr=new Set([`EVALUATE_CELLS`,`ADD_CONDITIONAL_FORMAT`,`REMOVE_CONDITIONAL_FORMAT`,`CHANGE_CONDITIONAL_FORMAT_PRIORITY`]),gr=new Set([`AUTOFILL_CELL`,`SET_BORDER`,`SET_ZONE_BORDERS`,`SET_BORDERS_ON_TARGET`]),_r=new Set([`START`,`ACTIVATE_SHEET`,`COPY`,`RESIZE_SHEETVIEW`,`SET_VIEWPORT_OFFSET`,`EVALUATE_CELLS`,`EVALUATE_CHARTS`,`SET_FORMULA_VISIBILITY`,`UPDATE_FILTER`,`UPDATE_CHART`]),vr=new Set(`UPDATE_CELL.UPDATE_CELL_POSITION.CLEAR_CELL.CLEAR_CELLS.DELETE_CONTENT.ADD_COLUMNS_ROWS.REMOVE_COLUMNS_ROWS.RESIZE_COLUMNS_ROWS.HIDE_COLUMNS_ROWS.UNHIDE_COLUMNS_ROWS.SET_GRID_LINES_VISIBILITY.UNFREEZE_COLUMNS.UNFREEZE_ROWS.FREEZE_COLUMNS.FREEZE_ROWS.UNFREEZE_COLUMNS_ROWS.ADD_MERGE.REMOVE_MERGE.CREATE_SHEET.DELETE_SHEET.DUPLICATE_SHEET.MOVE_SHEET.RENAME_SHEET.COLOR_SHEET.HIDE_SHEET.SHOW_SHEET.MOVE_RANGES.ADD_CONDITIONAL_FORMAT.REMOVE_CONDITIONAL_FORMAT.CHANGE_CONDITIONAL_FORMAT_PRIORITY.CREATE_FIGURE.DELETE_FIGURE.UPDATE_FIGURE.SET_FORMATTING.CLEAR_FORMATTING.SET_BORDER.SET_ZONE_BORDERS.SET_BORDERS_ON_TARGET.CREATE_CHART.UPDATE_CHART.CREATE_TABLE.REMOVE_TABLE.UPDATE_TABLE.CREATE_TABLE_STYLE.REMOVE_TABLE_STYLE.CREATE_IMAGE.GROUP_HEADERS.UNGROUP_HEADERS.UNFOLD_HEADER_GROUP.FOLD_HEADER_GROUP.FOLD_ALL_HEADER_GROUPS.UNFOLD_ALL_HEADER_GROUPS.UNFOLD_HEADER_GROUPS_IN_ZONE.FOLD_HEADER_GROUPS_IN_ZONE.ADD_DATA_VALIDATION_RULE.REMOVE_DATA_VALIDATION_RULE.UPDATE_LOCALE.ADD_PIVOT.UPDATE_PIVOT.INSERT_PIVOT.RENAME_PIVOT.REMOVE_PIVOT.DUPLICATE_PIVOT`.split(`.`));function yr(e){return vr.has(e.type)}function br(e){return _r.has(e.type)}var xr=class{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter(e=>e!==`Success`)}static get Success(){return Sr}get isSuccessful(){return this.reasons.length===0}isCancelledBecause(e){return this.reasons.includes(e)}};let Sr=new xr,Cr=function(e){return e.Success=`Success`,e.CancelledForUnknownReason=`CancelledForUnknownReason`,e.WillRemoveExistingMerge=`WillRemoveExistingMerge`,e.CannotMoveTableHeader=`CannotMoveTableHeader`,e.MergeIsDestructive=`MergeIsDestructive`,e.CellIsMerged=`CellIsMerged`,e.InvalidTarget=`InvalidTarget`,e.EmptyUndoStack=`EmptyUndoStack`,e.EmptyRedoStack=`EmptyRedoStack`,e.NotEnoughElements=`NotEnoughElements`,e.NotEnoughSheets=`NotEnoughSheets`,e.MissingSheetName=`MissingSheetName`,e.UnchangedSheetName=`UnchangedSheetName`,e.DuplicatedSheetName=`DuplicatedSheetName`,e.DuplicatedSheetId=`DuplicatedSheetId`,e.ForbiddenCharactersInSheetName=`ForbiddenCharactersInSheetName`,e.WrongSheetMove=`WrongSheetMove`,e.WrongSheetPosition=`WrongSheetPosition`,e.InvalidAnchorZone=`InvalidAnchorZone`,e.SelectionOutOfBound=`SelectionOutOfBound`,e.TargetOutOfSheet=`TargetOutOfSheet`,e.WrongCutSelection=`WrongCutSelection`,e.WrongPasteSelection=`WrongPasteSelection`,e.WrongPasteOption=`WrongPasteOption`,e.WrongFigurePasteOption=`WrongFigurePasteOption`,e.EmptyClipboard=`EmptyClipboard`,e.EmptyRange=`EmptyRange`,e.InvalidRange=`InvalidRange`,e.InvalidZones=`InvalidZones`,e.InvalidSheetId=`InvalidSheetId`,e.InvalidCellId=`InvalidCellId`,e.InvalidFigureId=`InvalidFigureId`,e.InputAlreadyFocused=`InputAlreadyFocused`,e.MaximumRangesReached=`MaximumRangesReached`,e.MinimumRangesReached=`MinimumRangesReached`,e.InvalidChartDefinition=`InvalidChartDefinition`,e.InvalidDataSet=`InvalidDataSet`,e.InvalidLabelRange=`InvalidLabelRange`,e.InvalidScorecardKeyValue=`InvalidScorecardKeyValue`,e.InvalidScorecardBaseline=`InvalidScorecardBaseline`,e.InvalidGaugeDataRange=`InvalidGaugeDataRange`,e.EmptyGaugeRangeMin=`EmptyGaugeRangeMin`,e.GaugeRangeMinNaN=`GaugeRangeMinNaN`,e.EmptyGaugeRangeMax=`EmptyGaugeRangeMax`,e.GaugeRangeMaxNaN=`GaugeRangeMaxNaN`,e.GaugeLowerInflectionPointNaN=`GaugeLowerInflectionPointNaN`,e.GaugeUpperInflectionPointNaN=`GaugeUpperInflectionPointNaN`,e.InvalidAutofillSelection=`InvalidAutofillSelection`,e.MinBiggerThanMax=`MinBiggerThanMax`,e.LowerBiggerThanUpper=`LowerBiggerThanUpper`,e.MidBiggerThanMax=`MidBiggerThanMax`,e.MinBiggerThanMid=`MinBiggerThanMid`,e.FirstArgMissing=`FirstArgMissing`,e.SecondArgMissing=`SecondArgMissing`,e.MinNaN=`MinNaN`,e.MidNaN=`MidNaN`,e.MaxNaN=`MaxNaN`,e.ValueUpperInflectionNaN=`ValueUpperInflectionNaN`,e.ValueLowerInflectionNaN=`ValueLowerInflectionNaN`,e.MinInvalidFormula=`MinInvalidFormula`,e.MidInvalidFormula=`MidInvalidFormula`,e.MaxInvalidFormula=`MaxInvalidFormula`,e.ValueUpperInvalidFormula=`ValueUpperInvalidFormula`,e.ValueLowerInvalidFormula=`ValueLowerInvalidFormula`,e.InvalidSortAnchor=`InvalidSortAnchor`,e.InvalidSortZone=`InvalidSortZone`,e.SortZoneWithArrayFormulas=`SortZoneWithArrayFormulas`,e.WaitingSessionConfirmation=`WaitingSessionConfirmation`,e.MergeOverlap=`MergeOverlap`,e.TooManyHiddenElements=`TooManyHiddenElements`,e.Readonly=`Readonly`,e.InvalidViewportSize=`InvalidViewportSize`,e.InvalidScrollingDirection=`InvalidScrollingDirection`,e.ViewportScrollLimitsReached=`ViewportScrollLimitsReached`,e.FigureDoesNotExist=`FigureDoesNotExist`,e.InvalidConditionalFormatId=`InvalidConditionalFormatId`,e.InvalidConditionalFormatType=`InvalidConditionalFormatType`,e.InvalidCellPopover=`InvalidCellPopover`,e.EmptyTarget=`EmptyTarget`,e.InvalidFreezeQuantity=`InvalidFreezeQuantity`,e.FrozenPaneOverlap=`FrozenPaneOverlap`,e.ValuesNotChanged=`ValuesNotChanged`,e.InvalidFilterZone=`InvalidFilterZone`,e.TableNotFound=`TableNotFound`,e.TableOverlap=`TableOverlap`,e.InvalidTableConfig=`InvalidTableConfig`,e.InvalidTableStyle=`InvalidTableStyle`,e.FilterNotFound=`FilterNotFound`,e.MergeInTable=`MergeInTable`,e.NonContinuousTargets=`NonContinuousTargets`,e.DuplicatedFigureId=`DuplicatedFigureId`,e.InvalidSelectionStep=`InvalidSelectionStep`,e.DuplicatedChartId=`DuplicatedChartId`,e.ChartDoesNotExist=`ChartDoesNotExist`,e.InvalidHeaderIndex=`InvalidHeaderIndex`,e.InvalidQuantity=`InvalidQuantity`,e.MoreThanOneColumnSelected=`MoreThanOneColumnSelected`,e.EmptySplitSeparator=`EmptySplitSeparator`,e.SplitWillOverwriteContent=`SplitWillOverwriteContent`,e.NoSplitSeparatorInSelection=`NoSplitSeparatorInSelection`,e.NoActiveSheet=`NoActiveSheet`,e.InvalidLocale=`InvalidLocale`,e.MoreThanOneRangeSelected=`MoreThanOneRangeSelected`,e.NoColumnsProvided=`NoColumnsProvided`,e.ColumnsNotIncludedInZone=`ColumnsNotIncludedInZone`,e.DuplicatesColumnsSelected=`DuplicatesColumnsSelected`,e.InvalidHeaderGroupStartEnd=`InvalidHeaderGroupStartEnd`,e.HeaderGroupAlreadyExists=`HeaderGroupAlreadyExists`,e.UnknownHeaderGroup=`UnknownHeaderGroup`,e.UnknownDataValidationRule=`UnknownDataValidationRule`,e.UnknownDataValidationCriterionType=`UnknownDataValidationCriterionType`,e.InvalidDataValidationCriterionValue=`InvalidDataValidationCriterionValue`,e.InvalidNumberOfCriterionValues=`InvalidNumberOfCriterionValues`,e.InvalidCopyPasteSelection=`InvalidCopyPasteSelection`,e.NoChanges=`NoChanges`,e.InvalidInputId=`InvalidInputId`,e.SheetIsHidden=`SheetIsHidden`,e.InvalidTableResize=`InvalidTableResize`,e.PivotIdNotFound=`PivotIdNotFound`,e.PivotInError=`PivotInError`,e.EmptyName=`EmptyName`,e.ValueCellIsInvalidFormula=`ValueCellIsInvalidFormula`,e.InvalidDefinition=`InvalidDefinition`,e.InvalidColor=`InvalidColor`,e.InvalidPivotDataSet=`InvalidPivotDataSet`,e}({}),wr=new Set([`containsText`,`notContainsText`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`beginsWithText`,`endsWithText`,`isNotEmpty`,`isEmpty`,`isNotEqual`,`isEqual`]),Tr=new Set([`containsText`,`notContainsText`,`isEqualText`,`isEmail`,`isLink`,`dateIs`,`dateIsBefore`,`dateIsOnOrBefore`,`dateIsAfter`,`dateIsOnOrAfter`,`dateIsBetween`,`dateIsNotBetween`,`dateIsValid`,`isEqual`,`isNotEqual`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`isBoolean`,`isValueInList`,`isValueInRange`,`customFormula`]),Er=[{name:`English (US)`,code:`en_US`,thousandsSeparator:`,`,decimalSeparator:`.`,weekStart:7,dateFormat:`m/d/yyyy`,timeFormat:`hh:mm:ss a`,formulaArgSeparator:`,`},{name:`French`,code:`fr_FR`,thousandsSeparator:` `,decimalSeparator:`,`,weekStart:1,dateFormat:`dd/mm/yyyy`,timeFormat:`hh:mm:ss`,formulaArgSeparator:`;`}],D=Er[0],Dr=[`thin`,`medium`,`thick`,`dashed`,`dotted`];function Or(e){return Array.isArray(e)&&Array.isArray(e[0])}let kr={Background:0,Highlights:1,Clipboard:2,Chart:4,Autofill:5,Selection:6,Headers:100},Ar=Vt(()=>Object.keys(kr).sort((e,t)=>kr[e]-kr[t]));function jr(e,t){if(kr[e])throw Error(`Layer ${e} already exists`);kr[e]=t}let Mr=[`containsText`,`notContainsText`,`isEqualText`,`isEmpty`,`isNotEmpty`,`beginsWithText`,`endsWithText`],Nr=[`isEqual`,`isNotEqual`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`isEmpty`,`isNotEmpty`],Pr=[`dateIs`,`dateIsBefore`,`dateIsOnOrBefore`,`dateIsAfter`,`dateIsOnOrAfter`,`dateIsBetween`,`dateIsNotBetween`,`isEmpty`,`isNotEmpty`];function Fr(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}let Ir=new g;function Lr(e,t){return e=Fr(e),{url:e,label:t||e,isExternal:!0,isUrlEditable:!0}}Ir.add(`sheet_URL`,{match:e=>St(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){let n=wt(e);return t.tryGetSheetName(n)||E(`Invalid sheet`)},open(e,t){let n=wt(e);t.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:n}).isCancelledBecause(`SheetIsHidden`)&&t.notifyUser({type:`warning`,sticky:!1,text:E(`Cannot open the link because the linked sheet is hidden.`)})},sequence:0});let Rr={createLink:Lr,match:e=>vt(e),open:e=>window.open(e,`_blank`),urlRepresentation:e=>e,sequence:0};function zr(e){return Ir.getAll().sort((e,t)=>e.sequence-t.sequence).find(t=>t.match(e))||Rr}function Br(e,t){return zr(e.url).urlRepresentation(e.url,t)}function Vr(e,t,n){zr(e.url).open(e.url,t,n)}function Hr(e){if(typeof e==`string`){if(_t(e)){let{label:t,url:n}=bt(e);return zr(n).createLink(n,t)}else if(vt(e))return Lr(e)}}var O=class e{jsDate;constructor(e,t,n,r=0,i=0,a=0){this.jsDate=new Date(Date.UTC(e,t,n,r,i,a,0))}static fromTimestamp(t){let n=new Date(t);return new e(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds())}static now(){let t=new Date;return new e(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds())}toString(){return this.jsDate.toString()}toLocaleDateString(){return this.jsDate.toLocaleDateString()}getTime(){return this.jsDate.getTime()}getFullYear(){return this.jsDate.getUTCFullYear()}getMonth(){return this.jsDate.getUTCMonth()}getQuarter(){return Math.floor(this.getMonth()/3)+1}getDate(){return this.jsDate.getUTCDate()}getDay(){return this.jsDate.getUTCDay()}getHours(){return this.jsDate.getUTCHours()}getMinutes(){return this.jsDate.getUTCMinutes()}getSeconds(){return this.jsDate.getUTCSeconds()}getIsoWeek(){let e=new Date(this.jsDate.getTime()),t=e.getUTCDay()||7;e.setUTCDate(e.getUTCDate()+4-t);let n=new Date(Date.UTC(e.getUTCFullYear(),0,1));return Math.ceil(((e.getTime()-n.getTime())/864e5+1)/7)}setFullYear(e){return this.jsDate.setUTCFullYear(e)}setMonth(e){return this.jsDate.setUTCMonth(e)}setDate(e){return this.jsDate.setUTCDate(e)}setHours(e){return this.jsDate.setUTCHours(e)}setMinutes(e){return this.jsDate.setUTCMinutes(e)}setSeconds(e){return this.jsDate.setUTCSeconds(e)}};let Ur=new O(1899,11,30),Wr=1440*60*1e3,Gr=2e3,Kr=O.now().getFullYear(),qr=O.now().getMonth(),Jr=O.fromTimestamp(0).getTime()-Ur.getTime(),Yr=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,Xr=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,Zr=Rt.join(``),Qr=RegExp(`\/|-|${Rt.join(`|`)}`),$r=RegExp(`^(\\d{1,4})[\/${Zr}\-](\\d{1,4})([\/${Zr}\-](\\d{1,4}))?$`),ei=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function ti(e,t){switch(typeof e){case`number`:return e;case`string`:return ni(e,t)?ii(e,t)?.value:!e||isNaN(Number(e))?void 0:Number(e);default:return}}function ni(e,t){return ii(e,t)!==null}let ri=new Map;function ii(e,t){return ri.has(t)||ri.set(t,new Map),ri.get(t).has(e)||ri.get(t).set(e,ai(e,t)),ri.get(t).get(e)}function ai(e,t){e=e.trim();let n=null,r=e.match(ei);if(r){if(n=pi(r[0]),n===null)return null;e=e.replace(r[0],``).trim()}let i=null,a=oi(e,t);if(a){let t=a.dateString.match(Qr)[0];if(i=ci(a,t),i===null)return null;e=e.replace(a.dateString,``).trim()}return e!==``||!(i||n)?null:i&&i.jsDate&&n&&n.jsDate?{value:i.value+n.value,format:i.format+` `+(n.format===`hhhh:mm:ss`?`hh:mm:ss`:n.format),jsDate:new O(i.jsDate.getFullYear()+n.jsDate.getFullYear()-1899,i.jsDate.getMonth()+n.jsDate.getMonth()-11,i.jsDate.getDate()+n.jsDate.getDate()-30,i.jsDate.getHours()+n.jsDate.getHours(),i.jsDate.getMinutes()+n.jsDate.getMinutes(),i.jsDate.getSeconds()+n.jsDate.getSeconds())}:i||n}function oi(e,t){let n=e.match($r);if(!n)return null;let[,r,i,,a]=n;if(r.length>2&&a&&a.length>2)return null;if(r.length>2)return{year:r,month:i,day:a,dateString:e,type:`ymd`};let o=si(t);return a?a.length>2?o===`mdy`?{month:r,day:i,year:a,dateString:e,type:`mdy`}:{day:r,month:i,year:a,dateString:e,type:`dmy`}:o===`mdy`?{month:r,day:i,year:a,dateString:e,type:`mdy`}:o===`ymd`?{year:r,month:i,day:a,dateString:e,type:`ymd`}:o===`dmy`?{day:r,month:i,year:a,dateString:e,type:`dmy`}:null:i.length>2?{month:r,year:i,day:void 0,dateString:e,type:o}:o===`dmy`?{day:r,month:i,year:a,dateString:e,type:`dmy`}:{month:r,day:i,year:a,dateString:e,type:`mdy`}}function si(e){switch(e.dateFormat[0]){case`d`:return`dmy`;case`m`:return`mdy`;case`y`:return`ymd`}throw Error(`Invalid date format in locale`)}function ci(e,t){let{year:n,month:r,day:i}=e,a=di(r),o=fi(i),s=ui(n);if(s===null||a===null||o===null)return null;let c=r?.length===2&&a+1<10||i?.length===2&&o<10,l=n?.length!==2,u=new O(s,a,o);if(u.getMonth()!==a||u.getDate()!==o)return null;let d=u.getTime()-Ur.getTime(),f=li(e,t,c,l);return{value:Math.round(d/Wr),format:f,jsDate:u}}function li(e,t,n,r){let i=e.year?r?`yyyy`:`yy`:void 0,a=e.month?n?`mm`:`m`:void 0,o=e.day?n?`dd`:`d`:void 0;switch(e.type){case`mdy`:return[a,o,i].filter(C).join(t);case`ymd`:return[i,a,o].filter(C).join(t);case`dmy`:return[o,a,i].filter(C).join(t)}}function ui(e){if(!e)return Kr;let t=Number(e);switch(e.length){case 1:return Gr+t;case 2:return Gr+(Gr+t>Kr+10?-100:0)+t;case 3:case 4:return t}return null}function di(e){if(!e)return qr;let t=Number(e);return t>=1&&t<=12?t-1:null}function fi(e){if(!e)return 1;let t=Number(e);return t>=0&&t<=31?t:null}function pi(e){if(e=e.trim(),ei.test(e)){let t=/AM/i.test(e),n=/PM/i.test(e),r=(t||n?e.substring(0,e.length-2).trim():e).split(/:/),i=r.length>=2,a=r.length===3,o=Number(r[0]),s=i?Number(r[1]):0,c=a?Number(r[2]):0,l=a?`hh:mm:ss`:`hh:mm`;if(t||n)l+=` a`;else if(!i)return null;o>=12&&t?o-=12:o<12&&n&&(o+=12),s+=Math.floor(c/60),c%=60,o+=Math.floor(s/60),s%=60,o>=24&&(l=`hhhh:mm:ss`);let u=new O(1899,11,30,o,s,c);return{value:o/24+s/1440+c/86400,format:l,jsDate:u}}return null}function mi(e){let t=Math.trunc(e),n=O.fromTimestamp(t*Wr-Jr),r=e-t;r=r<0?1+r:r;let i=Math.round(r*24),a=Math.round((r-i/24)*24*60),o=Math.round((r-i/24-a/24/60)*24*60*60);return n.setHours(i),n.setMinutes(a),n.setSeconds(o),n}function hi(e){return Math.round(gi(e))}function gi(e){return(e.getTime()-Ur.getTime())/Wr}function _i(e){return new O(e.getFullYear(),e.getMonth()+1,0).getDate()}function vi(e){return _i(e)===e.getDate()}function yi(e,t,n){let r=e.getFullYear(),i=e.getMonth(),a=e.getDate(),o=new O(r,i+t,1);return n&&a===_i(e)||a>_i(o)?o.setDate(_i(o)):o.setDate(a),o}function bi(e){let t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function xi(e,t,n){if(e===t)return 0;if(e>t){let n=t;t=e,e=n}let r=mi(e),i=mi(t),a=r.getDate(),o=i.getDate(),s=r.getMonth(),c=i.getMonth(),l=r.getFullYear(),u=i.getFullYear(),d=0,f=0;switch(n){case 0:a===31&&(a=30),a===30&&o===31&&(o=30),s===1&&a===(bi(l)?29:28)&&(a=30,c===1&&o===(bi(u)?29:28)&&(o=30)),d=l+(s*30+a)/360,f=u+(c*30+o)/360;break;case 1:let n=365,r=l===u,i=l+1===u;if(!r&&!i||!r&&s<c||!r&&s===c&&a<o){let e=0,t=0;for(let n=l;n<=u;n++)e++,t+=bi(n)?366:365;n=t/e}else r?bi(l)&&(n=366):(bi(l)&&s<2&&(n=366),bi(u)&&(c>1||c===1&&o===29)&&(n=366));d=e/n,f=t/n;break;case 2:d=e/360,f=t/360;break;case 3:d=e/365,f=t/365;break;case 4:a===31&&(a=30),o===31&&(o=30),d=l+(s*30+a)/360,f=u+(c*30+o)/360;break}return f-d}function Si(e,t){let n=(t.getFullYear()-e.getFullYear())*12+t.getMonth()-e.getMonth();return e.getDate()>t.getDate()?n-1:n}function Ci(e,t){let n=e.getTime(),r=t.getTime();return Math.floor((r-n)/Wr)}function wi(e,t){let n=t.getFullYear()-e.getFullYear(),r=e.getMonth(),i=t.getMonth(),a=e.getDate(),o=t.getDate();return i>r||i===r&&o>=a?n:n-1}function Ti(e,t){return xi(e,t,1)<1}function Ei(e,t){return Math.trunc(e)===Math.trunc(t)}function Di(e,t,n){return t>n?Di(e,n,t):(e=Math.trunc(e),t=Math.trunc(t),n=Math.trunc(n),e>=t&&e<=n)}function Oi(e,t){return Math.trunc(e)<Math.trunc(t)}function ki(e,t){return Math.trunc(e)<=Math.trunc(t)}function Ai(e,t){return Math.trunc(e)>Math.trunc(t)}function ji(e,t){return Math.trunc(e)>=Math.trunc(t)}let Mi=Vt(function(e){return e=ot(e),RegExp(`(?:^-?\\d+(?:${e}?\\d*(?:e(\\+|-)?\\d+)?)?|^-?${e}\\d+)(?!\\w|!)`)}),Ni=Vt(function(e){let t=ot(e.decimalSeparator),n=`(?:\\d+(?:${ot(e.thousandsSeparator||``)}\\d{3,})*(?:${t}\\d*)?)`,r=`(?:${t}\\d+)`,i=`(?:\\s*`+n+`|`+r+`)(?:e(?:\\+|-)?\\d+)?(?:\\s*%)?`,a=`(?:\\s*-)?`,o=`(?:\\s*[\\$€])?`,s=`^(?:(?:`+[a+o+i,a+i+o,o+a+i].join(`)|(?:`)+`))$`;return new RegExp(s,`i`)});function Pi(e,t){return e?Ni(t).test(e.trim()):!1}let Fi=Vt(function(e){return RegExp(`[\$€${ot(e.thousandsSeparator||``)}]`,`g`)});function Ii(e,t){e=e.replace(Fi(t),``),t.decimalSeparator!==`.`&&(e=e.replace(t.decimalSeparator,`.`));let n=Number(e);return isNaN(n)&&e.includes(`%`)&&(n=Number(e.split(`%`)[0]),!isNaN(n))?n/100:n}function Li(e,t,n){let r=[...e].sort((e,t)=>e-t),i=(r.length+(n?-1:1))*t;if(n||i--,Number.isInteger(i))return r[i];let a=Math.ceil(i),o=Math.floor(i);return r[a]*(i-o)+r[o]*(a-i)}let k={NotAvailable:`#N/A`,InvalidReference:`#REF`,BadExpression:`#BAD_EXPR`,CircularDependency:`#CYCLE`,UnknownFunction:`#NAME?`,DivisionByZero:`#DIV/0!`,SpilledBlocked:`#SPILL!`,GenericError:`#ERROR`,NullError:`#NULL!`},Ri=new Set(Object.values(k));var A=class{message;value;constructor(e=E(`Error`),t=k.GenericError){this.message=e,this.value=t,this.message=e.toString()}},zi=class extends A{constructor(e=E(`Invalid expression`)){super(e,k.BadExpression)}},Bi=class extends A{constructor(e=E(`Circular reference`)){super(e,k.CircularDependency)}},Vi=class extends A{constructor(e=E(`Invalid reference`)){super(e,k.InvalidReference)}},Hi=class extends A{constructor(e=E(`Data not available`)){super(e,k.NotAvailable)}},Ui=class extends A{constructor(e=E(`Unknown function`)){super(e,k.UnknownFunction)}},Wi=class extends A{errorOriginPosition;constructor(e=E(`Spill range is not empty`),t){super(e,k.SpilledBlocked),this.errorOriginPosition=t}},Gi=class extends A{constructor(e=E(`Division by zero`)){super(e,k.DivisionByZero)}};let Ki=[`number`,`string`,`boolean`,`undefined`];function qi(e){if(e!==void 0)return Or(e)?e[0][0]?.format:e.format}function j(e){return typeof e==`string`&&Ri.has(e)}function Ji(e){return{value:k.NotAvailable,message:E(`Did not find value '%s' in [[FUNCTION_NAME]] evaluation.`,N(e))}}let Yi=e=>E(`The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.`,e),Xi=(e,t,n)=>E(`The function [[FUNCTION_NAME]] expects a number value between %s and %s inclusive, but receives %s.`,e.toString(),t.toString(),n.toString()),Zi=(e,t)=>E(`The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.`,t,e.map(e=>`'${e}'`).join(`, `));function M(e,t){let n=oa(e);switch(typeof n){case`number`:return n;case`boolean`:return+!!n;case`string`:if(Pi(n,t)||n===``)return Ii(n,t);let e=ii(n,t);if(e)return e.value;throw new A(Yi(n));default:return 0}}function Qi(e,t){try{return M(e,t)}catch{return}}function $i(e,t){return I(e).map(e=>e.map(e=>{if(typeof e.value!=`number`){let n=``;throw typeof e==`object`?n=E(`Function [[FUNCTION_NAME]] expects number values for %s, but got an empty value.`,t):typeof e==`string`?n=E(`Function [[FUNCTION_NAME]] expects number values for %s, but got a string.`,t):typeof e==`boolean`&&(n=E(`Function [[FUNCTION_NAME]] expects number values for %s, but got a boolean.`,t)),new A(n)}return e.value}))}function ea(e,t){let n=oa(e);if(n===``)throw new A(Yi(n));return M(n,t)}function ta(e,t){return Math.trunc(M(e,t))}function na(e,t){return Math.trunc(ea(e,t))}function N(e){let t=oa(e);switch(typeof t){case`string`:return t;case`number`:return t.toString();case`boolean`:return t?`TRUE`:`FALSE`;default:return``}}let ra=Vt(function(e){return e.toLowerCase().normalize(`NFD`).replace(/[\u0300-\u036f]/g,``)}),ia=e=>E(`The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a boolean.`,e);function P(e){let t=oa(e);switch(typeof t){case`boolean`:return t;case`string`:if(t){let e=t.toUpperCase();if(e===`TRUE`)return!0;if(e===`FALSE`)return!1;throw new A(ia(t))}else return!1;case`number`:return!!t;default:return!1}}function aa(e){let t=oa(e);if(t===``)throw new A(ia(t));return P(t)}function F(e,t){return mi(M(oa(e),t))}function oa(e){if(typeof e==`object`&&e&&`value`in e){if(j(e.value))throw e;return e.value}if(j(e))throw new A(``,e);return e}function sa(e,t,n){for(let r of e)if(Or(r)){let e=r.length,n=r[0].length;for(let i=0;i<n;i++)for(let n=0;n<e;n++)t(r[n][i])}else n(r)}function ca(e,t){sa(e,e=>{if(j(e.value))throw e;t(e)},e=>{if(j(e?.value))throw e;t(e)})}function la(e,t,n){sa(e,e=>{if(typeof e?.value==`number`&&t(e),j(e?.value))throw e},e=>{t({value:ea(e,n),format:e?.format})})}function ua(e,t,n,r,i=`rowFirst`){let a=r;for(let r of e)if(Or(r)){let e=r.length,n=r[0].length;if(i===`rowFirst`)for(let i=0;i<n;i++)for(let n=0;n<e;n++)a=t(a,r[n][i]);else for(let i=0;i<e;i++)for(let e=0;e<n;e++)a=t(a,r[i][e])}else a=n(a,r);return a}function da(e,t,n,r=`rowFirst`){return ua(e,t,t,n,r)}function fa(e,t,n,r){return ua(e,(e,n)=>{let r=n?.value;if(typeof r==`number`)return t(e,r);if(j(r))throw n;return e},(e,n)=>t(e,ea(n,r)),n)}function pa(e,t,n,r){return ua(e,(e,n)=>{let i=n?.value;if(i!=null){if(typeof i==`number`)return t(e,i);if(typeof i==`boolean`)return t(e,M(i,r));if(j(i))throw n;return t(e,0)}return e},(e,n)=>t(e,M(n,r)),n)}function ma(e,t,n){let r=Array(e);for(let i=0;i<e;i++){r[i]=Array(t);for(let e=0;e<t;e++)r[i][e]=n(i,e)}return r}function ha(e,t){return e.length===0?[]:ma(e.length,e[0].length,(n,r)=>t(e[n][r]))}function ga(e,t){let n=e.length,r=e[0]?.length??0;for(let i=0;i<n;i++)for(let n=0;n<r;n++)t(e[i][n])}function _a(e){return e.length?ma(e[0].length,e.length,(t,n)=>e[n][t]):[]}function va(e,t,n=void 0){let r=1,i=1,a=1/0,o=1/0,s;for(let e=0;e<t.length;e++){let c=t[e];if(Or(c)&&(n===void 0||n[e])){let n=c.length,l=c[0].length;n!==1||l!==1?(s??=Array(t.length),n!==1&&l!==1?(s[e]=`matrix`,r=Math.max(r,n),i=Math.max(i,l),a=Math.min(a,n),o=Math.min(o,l)):n===1?l!==1&&(s[e]=`vertical`,i=Math.max(i,l),o=Math.min(o,l)):(s[e]=`horizontal`,r=Math.max(r,n),a=Math.min(a,n))):t[e]=c[0][0]}}if(r===1&&i===1)return e(...t);let c=(e,n)=>t.map((t,r)=>{switch(s?.[r]){case`matrix`:return t[e][n];case`horizontal`:return t[e][0];case`vertical`:return t[0][n];case void 0:return t}});return ma(r,i,(t,n)=>{if(t>a-1||n>o-1)return new Hi(E(`Array arguments to [[FUNCTION_NAME]] are of different size.`));let r=e(...c(t,n));return Or(r)?r[0][0]:r})}function ya(e,t,n){for(let r of e)if(Or(r)){let e=r.length,n=r[0].length;for(let i=0;i<n;i++)for(let n=0;n<e;n++)if(!t(r[n][i]??void 0))return}else if(!n(r))return}function ba(e,t){return ya(e,e=>{let n=e?.value;if(typeof n==`boolean`)return t(n);if(typeof n==`number`)return t(!!n);if(j(n))throw e;return!0},e=>e!==void 0&&e.value!==null?t(aa(e)):!0)}function xa(e,t){let n,r,i=e.substring(0,2);return i===`<=`||i===`>=`||i===`<>`?(n=i,r=e.substring(2)):(i=e.substring(0,1),i===`<`||i===`>`||i===`=`?(n=i,r=e.substring(1)):(n=`=`,r=e)),Pi(r,t)||ni(r,t)?r=M(r,t):(r===`TRUE`||r===`FALSE`)&&(r=P(r)),{operator:n,operand:r}}let Sa=Vt(function(e){if(e===`*`)return/.+/;let t=``,n=``;for(let r of e)r===`?`&&n!==`~`?t+=`.`:r===`*`&&n!==`~`?t+=`.*`:((r===`*`||r===`?`)&&(t=t.slice(0,-1)),[`^`,`.`,`[`,`]`,`$`,`(`,`)`,`*`,`+`,`?`,`|`,`{`,`}`,`\\`].includes(r)&&(t+=`\\`),t+=r),n=r;return RegExp(`^`+t+`$`,`i`)});function Ca(e=``,t,n){let{operator:r,operand:i}=t;if(i===void 0||e===null||i===null)return!1;if(typeof i==`number`&&r===`=`)return typeof e==`string`&&(Pi(e,n)||ni(e,n))?M(e,n)===i:e===i;if(r===`<>`||r===`=`){let t;return t=typeof e==typeof i?typeof e==`string`&&typeof i==`string`?Sa(i).test(e):e===i:!1,r===`=`?t:!t}if(typeof e==typeof i)switch(r){case`<`:return e<i;case`>`:return e>i;case`<=`:return e<=i;case`>=`:return e>=i}return!1}function wa(e,t,n,r=!1){let i=e.length;if(i%2==1)throw new A(E(`Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs.`));let a=I(e[0]),o=a.length,s=a[0].length,c=[];for(let t=0;t<i-1;t+=2){let i=I(e[t]);if(i.length!==o||i[0].length!==s)throw new A(E(`Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension`));let a=xa(N(e[t+1]),n);r&&typeof a.operand==`string`&&(a.operand+=`*`),c.push(a)}for(let r=0;r<o;r++)for(let a=0;a<s;a++){let o=!0;for(let t=0;t<i-1;t+=2){let i=I(e[t])[r][a].value,s=c[t/2];if(o=Ca(i??void 0,s,n),!o)break}o&&t(r,a)}}function Ta(e,t,n,r,i,a){if(t===void 0||t.value===null)return-1;if(j(t.value))throw t;let o=Oa(t.value),s=typeof o,c,l,u=0,d=i-1,f,p,m,h,g=r===`desc`?t=>Oa(a(e,i-t-1)):t=>Oa(a(e,t));for(;d-u>=0;){for(f=Math.floor((u+d)/2),p=f,m=g(p),h=typeof m;u<p&&s!==h;)p--,m=g(p),h=typeof m;if(h!==s||m==null){u=f+1;continue}n===`strict`&&m===o?(c=m,l=p):n===`nextSmaller`&&m<=o?(c==null||c<m||c===m&&l<p)&&(c=m,l=p):n===`nextGreater`&&m>=o&&(c===void 0||c>m||c===m&&l<p)&&(c=m,l=p),m>o||n===`strict`&&m===o?d=p-1:u=f+1}return l===void 0?-1:r===`desc`?i-l-1:l}function Ea(e,t,n,r,i,a,o=!1){if(t===void 0||t.value===null)return-1;if(j(t.value))throw t;let s=Oa(t.value),c=o?(e,t)=>Oa(i(e,r-t-1)):(e,t)=>Oa(i(e,t)),l=n!==`wildcard`||typeof s!=`string`||!(s.includes(`*`)||s.includes(`?`));if(a&&l){let t=o?`reverseSearch`:`forwardSearch`,i=a[t].get(e);if(i===void 0){i=new Map;for(let t=0;t<r;t++){let n=c(e,t)??null;i.has(n)||i.set(n,t)}a[t].set(e,i)}if(i.has(s)){let e=i.get(s);return o?r-e-1:e}if(n===`strict`)return-1}let u=Da(e,s,n,r,c);return o&&u!==-1?r-u-1:u}function Da(e,t,n,r,i){let a=n=>i(e,n)===t;if(n===`wildcard`&&typeof t==`string`&&(t.includes(`*`)||t.includes(`?`))){let n=Sa(t);a=t=>{let r=i(e,t);return typeof r==`string`?n.test(r):!1}}let o,s=-1;n===`nextSmaller`&&(a=n=>{let r=i(e,n);return(!o&&ka(t,r)>=0||ka(t,r)>=0&&ka(r,o)>0)&&(o=r,s=n),r===t}),n===`nextGreater`&&(a=n=>{let r=i(e,n);return(!o&&ka(t,r)<=0||ka(t,r)<=0&&ka(r,o)<0)&&(o=r,s=n),r===t});for(let e=0;e<r;e++)if(a(e))return e;return s}function Oa(e){return typeof e==`string`?ra(e):e}function ka(e,t){let n=Ki.indexOf(typeof e)-Ki.indexOf(typeof t);return n===0&&(typeof e==`string`&&typeof t==`string`?n=e.localeCompare(t):typeof e==`number`&&typeof t==`number`?n=e-t:typeof e==`boolean`&&typeof t==`boolean`&&(n=Number(e)-Number(t))),n}function I(e){return e===void 0?[[]]:Or(e)?e:[[e]]}function Aa(e,t){return da(e,(e,n)=>(e.push(t(n)),e),[],`rowFirst`)}function ja(e){if(e===void 0)return!1;let{value:t}=e;return!(t===null||t===``)}let Ma=E(`[[FUNCTION_NAME]] has no valid input data.`);function Na(e){return E(`[[FUNCTION_NAME]] expects the provided values of %(argName)s to be a non-empty matrix.`,{argName:e})}function Pa(e){let t=new Xt(e),n=[],r=[];for(n.push(r);!t.isOver();){if(t.current===`;`){r=[],n.push(r),t.shift();continue}let e=Ha(t)||Fa(t)||La(t)||Ra(t)||Ba(t)||Va(t)||Wa(t)||za(t)||Ga(t);if(!e)throw Error(`Unknown token at `+t.remaining());r.push(e)}return n}function Fa(e){let t;if(e.current===`"`?(e.shift(),t=`"`):e.currentStartsWith(`[$`)&&(e.advanceBy(2),t=`]`),!t)return null;let n=``;for(;e.current&&e.current!==t;)n+=e.shift();if(e.current===t)e.shift();else throw Error(`Unterminated string in format`);return{type:`STRING`,value:n}}let Ia=new Set(`$+-/():!^&~{}<>= `);function La(e){if(e.current===`\\`){e.shift();let t=e.shift();if(!t)throw Error(`Unexpected end of format string`);return{type:`CHAR`,value:t}}return Ia.has(e.current)?{type:`CHAR`,value:e.shift()}:null}function Ra(e){return e.current===`,`?(e.shift(),{type:`THOUSANDS_SEPARATOR`,value:`,`}):null}function za(e){return e.current===`@`?(e.shift(),{type:`TEXT_PLACEHOLDER`,value:`@`}):null}function Ba(e){return e.current===`.`?(e.shift(),{type:`DECIMAL_POINT`,value:`.`}):null}function Va(e){return e.current===`%`?(e.shift(),{type:`PERCENT`,value:`%`}):null}function Ha(e){if(e.current===`0`||e.current===`#`){let t=e.current;return e.shift(),{type:`DIGIT`,value:t}}return null}let Ua=new Set(`dmqyhsa`);function Wa(e){if(!Ua.has(e.current))return null;let t=e.current,n=``;for(;e.current===t;)n+=e.shift();return{type:`DATE_PART`,value:n}}function Ga(e){if(e.current!==`*`)return null;e.shift();let t=e.shift();if(!t)throw Error(`Unexpected end of format string`);return{type:`REPEATED_CHAR`,value:t}}let Ka={};function qa(e){let t=Ka[e];return t===void 0&&(t=Ja(e),Ka[e]=t),t}function Ja(e){let t=Pa(e);for(let e of t){let t=e.filter(e=>e.type===`REPEATED_CHAR`);for(let e of t.slice(1))e.type=`CHAR`}let n=$a(t[0])||Qa(t[0])||eo(t[0]);if(!n)throw Error(`Invalid first format part of: `+e);if(t.length>1&&n.type===`text`)throw Error(`The first format in a multi-part format must be a number format: `+e);let r=$a(t[1])||Qa(t[1]);if(t[1]?.length&&!r)throw Error(`Invalid second format part of: `+e);let i=$a(t[2])||Qa(t[2]);if(t[2]?.length&&!i)throw Error(`Invalid third format part of: `+e);let a=eo(t[3]);if(t[3]?.length&&!a)throw Error(`Invalid fourth format part of: `+e);return{positive:n,negative:r,zero:i,text:a}}function Ya(e){return e.every(e=>e.type===`DATE_PART`||e.type===`DECIMAL_POINT`||e.type===`THOUSANDS_SEPARATOR`||e.type===`STRING`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function Xa(e){return e.every(e=>e.type===`DIGIT`||e.type===`DECIMAL_POINT`||e.type===`THOUSANDS_SEPARATOR`||e.type===`PERCENT`||e.type===`STRING`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function Za(e){return e.every(e=>e.type===`STRING`||e.type===`TEXT_PLACEHOLDER`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function Qa(e){if(!e||!Xa(e))return;let t=[],n,r=t,i=0,a=0,o=e.findLastIndex(e=>e.type===`DIGIT`),s=!1,c=0;for(let l=0;l<e.length;l++){let u=e[l];switch(u.type){case`DIGIT`:r===t?r.push(u):c<20&&(r.push(u),c++);break;case`DECIMAL_POINT`:if(r===t)n=[],r=n;else throw Error(`Multiple decimal points in a number format`);break;case`REPEATED_CHAR`:case`CHAR`:case`STRING`:r.push(u);break;case`PERCENT`:i++,r.push(u);break;case`THOUSANDS_SEPARATOR`:l-1===o?(a+=1,o++,r.push(u)):e[l+1]?.type===`DIGIT`&&e[l-1]?.type===`DIGIT`?(r===t&&(s=!0),r.push(u)):r.push({type:`CHAR`,value:`,`});break}}return{type:`number`,integerPart:t,decimalPart:n,percentSymbols:i,thousandsSeparator:s,magnitude:a}}function $a(e){let t=e&&Ya(e)?{type:`date`,tokens:e}:void 0;if(t){if(t.tokens.length&&t.tokens.every(e=>e.type===`DATE_PART`&&e.value===`a`))throw Error(`Invalid date format`);return{type:`date`,tokens:to(t.tokens.map(e=>e.type===`THOUSANDS_SEPARATOR`||e.type===`DECIMAL_POINT`?{type:`CHAR`,value:e.value}:e))}}}function eo(e){return e&&Za(e)?{type:`text`,tokens:e}:void 0}function to(e){let t=e.filter(e=>e.type===`DATE_PART`);for(let e=0;e<t.length;e++)!t[e].value.startsWith(`m`)||t[e].value.length>2||(t[e-1]?.value.startsWith(`h`)||t[e+1]?.value.startsWith(`s`))&&(t[e].value=t[e].value.replaceAll(`m`,`M`));return e}function no(e){return[ro(e.positive),ro(e.negative),ro(e.zero),ro(e.text)].filter(C).join(`;`)}function ro(e){if(!e)return;let t=``,n=e.type===`number`?io(e):e.tokens;for(let e of n)switch(e.type){case`STRING`:t+=`[$${e.value}]`;break;case`CHAR`:t+=ao(e.value)?`\\${e.value}`:e.value;break;case`REPEATED_CHAR`:t+=`*`+e.value;break;case`DATE_PART`:t+=e.value===`MM`?`mm`:e.value;break;default:t+=e.value}return t}function io(e){let t=[...e.integerPart];return e.decimalPart&&(t.push({type:`DECIMAL_POINT`,value:`.`}),t.push(...e.decimalPart)),t}function ao(e){return!Ia.has(e)}let oo=`REPEATED_CHAR_PLACEHOLDER_`,so={0:E(`January`),1:E(`February`),2:E(`March`),3:E(`April`),4:E(`May`),5:E(`June`),6:E(`July`),7:E(`August`),8:E(`September`),9:E(`October`),10:E(`November`),11:E(`December`)},co={0:E(`Sunday`),1:E(`Monday`),2:E(`Tuesday`),3:E(`Wednesday`),4:E(`Thursday`),5:E(`Friday`),6:E(`Saturday`)};function L(e,{format:t,locale:n,formatWidth:r}){switch(typeof e==`boolean`&&(e=e?`TRUE`:`FALSE`),typeof e){case`string`:{if(e.includes(`\\"`)&&(e=e.replaceAll(/\\"/g,`"`)),!t)return e;let n=qa(t),i=n.text||n.positive;return!i||i.type!==`text`?e:lo(e,i,r)}case`number`:t||=Eo(e);let i=qa(t);if(i.positive.type===`text`)return lo(e.toString(),i.positive,r);let a=i.positive;if(e<0&&i.negative?(a=i.negative,e=-e):e===0&&i.zero&&(a=i.zero),a.type===`date`)return uo(Co(e,a),r);let o=e<0,s=uo(fo(Math.abs(e),a,n),r);return o?`-`+s:s;case`object`:return``}}function lo(e,t,n){let r=``;for(let n of t.tokens)switch(n.type){case`TEXT_PLACEHOLDER`:r+=e;break;case`CHAR`:case`STRING`:r+=n.value;break;case`REPEATED_CHAR`:r+=oo+n.value;break}return uo(r,n)}function uo(e,t){let n=e.indexOf(oo);if(n===-1)return e;let r=e.slice(0,n),i=e.slice(n+26+1),a=e[n+26];function o(){if(!t)return{timesToRepeat:0,padding:``};let e=t.measureText(r+i),n=t.measureText(a),o=t.availableWidth-e;if(o<=0)return{timesToRepeat:0,padding:``};let s=Math.floor(o/n),c=o-s*n,l=t.measureText(` `);return{timesToRepeat:s,padding:` `.repeat(Math.floor(c/l))}}let{timesToRepeat:s,padding:c}=o();return r+a.repeat(s)+c+i}function fo(e,t,n){if(e===1/0)return`∞`+(t.percentSymbols?`%`:``);let r=t.percentSymbols*2-t.magnitude*3;e*=10**r;let i=0;t.decimalPart!==void 0&&(i=t.decimalPart.filter(e=>e.type===`DIGIT`).length);let{integerDigits:a,decimalDigits:o}=go(Math.abs(e),i),s=po(a,t,t.thousandsSeparator?n.thousandsSeparator:void 0);return t.decimalPart!==void 0&&(s+=n.decimalSeparator+mo(o||``,t)),s}function po(e,t,n){let r=t.integerPart;r.some(e=>e.type===`DIGIT`)||(r=[...r,{type:`DIGIT`,value:`#`}]),e===`0`&&(e=``);let i=``,a=r.findIndex(e=>e.type===`DIGIT`),o=e.length-1;function s(t,r){if(r===`0`&&(t||=`0`),!t)return;let a=e.length-1-o;i=n&&a>0&&a%3==0?t+n+i:t+i}for(let t=r.length-1;t>=0;t--){let n=r[t];switch(n.type){case`DIGIT`:let r=e[o];if(s(r,n.value),o--,a===t)for(;o>=0;)s(e[o],`0`),o--;break;case`THOUSANDS_SEPARATOR`:break;case`REPEATED_CHAR`:i=oo+n.value+i;break;default:i=n.value+i;break}}return i}function mo(e,t){if(!t.decimalPart)return``;let n=``,r=0;for(let i of t.decimalPart)switch(i.type){case`DIGIT`:let t=i.value===`#`?e[r]||``:e[r]||`0`;n+=t,r++;break;case`THOUSANDS_SEPARATOR`:break;case`REPEATED_CHAR`:n+=oo+i.value;break;default:n+=i.value;break}return n}let ho=[];function go(e,t=20){let n=e.toString();if(n.includes(`e`))return bo(e,t);if(Number.isInteger(e))return{integerDigits:n,decimalDigits:void 0};let r=n.indexOf(`.`),i=n.substring(0,r),a=n.substring(r+1);if(t===0)return Number(a[0])>=5&&(i=(Number(i)+1).toString()),{integerDigits:i,decimalDigits:void 0};if(a.length>t){let{integerDigits:e,decimalDigits:n}=yo(a,t);a=n,e!==`0`&&(i=(Number(i)+Number(e)).toString())}return{integerDigits:i,decimalDigits:_o(a||``)}}function _o(e){let t=e.length-1;for(;t>=0&&e[t]===`0`;)t--;return e.slice(0,t+1)||void 0}let vo=/^0+/;function yo(e,t){let n=`0`,r=e,i=e.slice(0,t);if(Number(e[t])<5)return{integerDigits:n,decimalDigits:i};let a=i.match(vo)?.[0]||``,o=(Number(i)+1).toString(),s=i.slice(a.length),c=o.length>s.length;return c&&!a?(n=`1`,r=void 0):r=c?a.slice(0,-1)+o:a+o,{integerDigits:n,decimalDigits:r}}function bo(e,t=20){let n=ho[t];n||(n=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:t,useGrouping:!1}),ho[t]=n);let[r,i]=n.format(e).split(`.`);return{integerDigits:r,decimalDigits:i}}function xo(e,t){let{integerDigits:n,decimalDigits:r}=go(e,20);return r?n+t+r:n}let So=Vt(function(e){if(!e)return!1;try{return qa(e).positive.type===`date`}catch{return!1}});function Co(e,t){let n=mi(e);if(isNaN(n.getTime()))return e.toString();let r=t.tokens.some(e=>e.type===`DATE_PART`&&e.value===`a`),i=``;for(let e of t.tokens)switch(e.type){case`DATE_PART`:i+=wo(n,e.value,r);break;case`REPEATED_CHAR`:i+=oo+e.value;break;default:i+=e.value;break}return i}function wo(e,t,n){switch(t){case`d`:return e.getDate();case`dd`:return e.getDate().toString().padStart(2,`0`);case`ddd`:return co[e.getDay()].slice(0,3);case`dddd`:return co[e.getDay()].toString();case`m`:return e.getMonth()+1;case`mm`:return String(e.getMonth()+1).padStart(2,`0`);case`mmm`:return so[e.getMonth()].slice(0,3);case`mmmm`:return so[e.getMonth()].toString();case`mmmmm`:return so[e.getMonth()].slice(0,1);case`qq`:return E(`Q%(quarter)s`,{quarter:e.getQuarter()}).toString();case`qqqq`:return E(`Quarter %(quarter)s`,{quarter:e.getQuarter()}).toString();case`yy`:let r=String(e.getFullYear()).replace(`-`,``).padStart(2,`0`);return r.slice(r.length-2);case`yyyy`:return String(e.getFullYear()).replace(`-`,``).padStart(4,`0`);case`hhhh`:return Math.floor((e.getTime()-Ur.getTime())/(3600*1e3)).toString();case`hh`:let i=e.getHours();return n&&(i=i===0?12:i>12?i-12:i),i.toString().padStart(2,`0`);case`MM`:return e.getMinutes().toString().padStart(2,`0`);case`ss`:return e.getSeconds().toString().padStart(2,`0`);case`a`:return e.getHours()>=12?`PM`:`AM`;default:throw Error(`invalid date format token: ${t}`)}}let To=Vt(function(e){return RegExp(`[0-9]+${ot(e.decimalSeparator)}[0-9]`)});function Eo(e){let{integerDigits:t,decimalDigits:n}=go(e);if(!n)return`0`;let r=t.replace(`-`,``).length;if(r+2>11)return`0`;let i=11-r-1;return{decimalDigits:n}=go(e,Math.min(i,n.length)),n?`0.`+`0`.repeat(n.length):`0`}function Do(e,t){if(ni(e,t))return ii(e,t).format}function Oo(e){let t=e.includes(`.`)?`0.00`:`0`,n=e.match(/[\$€]/);if(n){let r=e.match(/[\d]/),i=`[$`+n.values().next().value+`]`;return r.index<n.index?`#,##`+t+i:i+`#,##`+t}if(e.includes(`%`))return t+`%`}function ko(e){let t=e.decimalPlaces??2,n=e.position??`before`,r=e.code??``,i=e.symbol??``,a=`#,##0`+(t?`.`+`0`.repeat(t):``),o=`${r} ${i}`.trim();return n===`after`&&r&&(o=` `+o),Mo(o,n,a)}function Ao(e){let t=e.decimalPlaces??2,n=e.position??`before`,r=e.code??``,i=e.symbol??``,a=`#,##0`+(t?`.`+`0`.repeat(t):``),o=`${r} ${i}`.trim();return n===`after`&&r&&(o=` `+o),[jo(o,n,` ${a} `),jo(o,n,`(${a})`),jo(o,n,` - `)].join(`;`)}function jo(e,t,n){let r=`[$${e}]`;return t===`before`?r+`* `+n:n+`* `+r}function Mo(e,t,n){let r=`[$${e}]`;return t===`before`?r+n:n+r}function No(e){let t=qa(e);return no({positive:Po(t.positive),negative:t.negative?Po(t.negative):void 0,zero:t.zero?Po(t.zero):void 0,text:t.text})}function Po(e){if(e.type!==`number`||!e.decimalPart)return e;let t=e.decimalPart.filter(e=>e.type!==`DIGIT`);return{...e,decimalPart:void 0,integerPart:[...e.integerPart,...t]}}function Fo({value:e,format:t},n){return L(e,{format:Io({value:e,format:t},void 0,n),locale:n})}function Io(e,t,n){let r=0;try{r=Math.abs(M(e?.value,n))}catch{return``}let i=e?.format;if(t!==void 0)switch(t?.value){case`k`:return Lo(i,1,`k`,n);case`m`:return Lo(i,2,`m`,n);case`b`:return Lo(i,3,`b`,n);default:throw new A(E(`The formatting unit should be 'k', 'm' or 'b'.`))}return r<1e5?Lo(i,0,``,n):r<1e8?Lo(i,1,`k`,n):r<1e11?Lo(i,2,`m`,n):Lo(i,3,`b`,n)}function Lo(e,t,n,r){let i=qa(e||`#,##0`);return no({positive:Ro(i.positive,t,n),negative:i.negative?Ro(i.negative,t,n):void 0,zero:i.zero?Ro(i.zero,t,n):void 0,text:i.text})}function Ro(e,t,n){if(e.type!==`number`)return e;let r=Po(e),i={type:`STRING`,value:n},a=[...r.integerPart],o=a.findLastIndex(e=>e.type===`DIGIT`);if(o===-1)throw Error(`Cannot create a large number format from a format with no digit.`);for(;a[o+1]?.type===`THOUSANDS_SEPARATOR`;)a=Ht(a,[o+1]);let s=a[o+1];a=s?.type===`STRING`&&[`m`,`k`,`b`].includes(s.value)?Wt(a,i,o+1):Ut(a,[i],o+1),t>0&&(a=Ut(a,Array(t).fill({type:`THOUSANDS_SEPARATOR`,value:`,`}),o+1));let c=r.percentSymbols-a.filter(e=>e.type===`PERCENT`).length;return a.push(...Array(c).fill({type:`PERCENT`,value:`%`})),{...r,integerPart:a,magnitude:t}}function zo(e,t){let n=qa(e);return no(qa(no({positive:Bo(n.positive,t),negative:n.negative?Bo(n.negative,t):void 0,zero:n.zero?Bo(n.zero,t):void 0,text:n.text})))}function Bo(e,t){return e.type===`number`?t>0?Ho(e,t):Vo(e,Math.abs(t)):e}function Vo(e,t){let n=e.decimalPart;if(!n)return e;let r=[],i=0;for(let e=n.length-1;e>=0&&!(i>=Math.abs(t));e--)n[e].type===`DIGIT`&&(i++,r.push(e));return n=Ht(n,r),n.some(e=>e.type===`DIGIT`)?{...e,decimalPart:n}:{...e,decimalPart:void 0,integerPart:[...e.integerPart,...n]}}function Ho(e,t){let n=e.integerPart,r=e.decimalPart;if(!r){let e=n.findLastIndex(e=>e.type===`DIGIT`);r=n.slice(e+1),n=n.slice(0,e+1)}let i=S(0,t).map(()=>({type:`DIGIT`,value:`0`})),a=r.findLastIndex(e=>e.type===`DIGIT`);return r=a===-1?[...i,...r]:Ut(r,i,a+1),{...e,decimalPart:r,integerPart:n}}function Uo(e){let t=qa(e);for(let e of[t.positive,t.negative,t.zero])if(e&&e.type===`date`&&e.tokens.some(e=>e.type===`DATE_PART`&&e.value.includes(`q`)))return!1;return!0}function Wo(e){if(!e)return!1;try{return qa(e).positive.type===`text`}catch{return!1}}function Go(e,t){return qo({value:Wo(t.format)&&e.parsedValue!==null?e.content:e.parsedValue,format:t.format},t.locale)}function Ko(e,t){if(e.startsWith(`=`))throw Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);if(e===``)return null;if(Pi(e,D))return Ii(e,D);let n=ii(e,t);return n?n.value:mt(e)?e.toUpperCase()===`TRUE`:e}function qo(e,t=D,n){let r=Hr(e.value);if(!r)return Jo(e,t,n);let i=Ko(r.label,t);return{...Jo({value:i,format:e.format||(typeof i==`number`?Do(r.label,t)||Oo(r.label):void 0)},t,n),link:r}}function Jo(e,t,n){let{value:r,format:i,message:a,errorOriginPosition:o}=e;i=n?.format||i;let s=L(r,{format:i,locale:t});return j(r)?es(r,a,o):r===null?Zo(i):Wo(i)?Yo(N(r),i,s):typeof r==`number`?So(i||``)?Qo(r,i,s):Xo(r,i,s):typeof r==`boolean`?$o(r,i,s):Yo(r,i,s)}function Yo(e,t,n){return{value:e,format:t,formattedValue:n,type:`text`,isAutoSummable:!0,defaultAlign:`left`}}function Xo(e,t,n){return{value:e||0,format:t,formattedValue:n,type:`number`,isAutoSummable:!0,defaultAlign:`right`}}let Zo=Vt(function(e){return{value:null,format:e,formattedValue:``,type:`empty`,isAutoSummable:!0,defaultAlign:`left`}});function Qo(e,t,n){return{value:e,format:t,formattedValue:n,type:`number`,isAutoSummable:!1,defaultAlign:`right`}}function $o(e,t,n){return{value:e,format:t,formattedValue:n,type:`boolean`,isAutoSummable:!1,defaultAlign:`center`}}function es(e,t,n){return{value:e,formattedValue:e,message:t,type:`error`,isAutoSummable:!1,defaultAlign:`center`,errorOriginPosition:n}}function ts(e){let t=O.now();switch(e){case`today`:return Math.floor(gi(t));case`yesterday`:return t.setDate(t.getDate()-1),Math.floor(gi(t));case`tomorrow`:return t.setDate(t.getDate()+1),Math.floor(gi(t));case`lastWeek`:return t.setDate(t.getDate()-6),Math.floor(gi(t));case`lastMonth`:{let e=t.getMonth()===0?11:t.getMonth()-1,n=new O(t.getFullYear(),e,1);return t.getDate()>_i(n)?t.setDate(1):(t.setDate(t.getDate()+1),t.setMonth(t.getMonth()-1)),Math.floor(gi(t))}case`lastYear`:return t.getMonth()===1&&t.getDate()===29?(t.setDate(28),t.setFullYear(t.getFullYear()-1)):(t.setDate(t.getDate()+1),t.setFullYear(t.getFullYear()-1)),Math.floor(gi(t))}}function ns(e,t){return`dateValue`in e&&e.dateValue!==`exactDate`?[ts(e.dateValue)]:e.values.map(e=>ti(e,t))}function rs(e,t){return e.map(e=>{if(e.startsWith(`=`))return e;let n=Ko(e,t);return typeof n==`number`?L(n,{format:t.dateFormat,locale:t}):``})}function R(e,t=[]){if(e.length<=1&&t.length===0)return e;let n=[0],r=new Map([[0,[]]]);return is(n,r,e,!1),is(n,r,t,!0),cs(n,r)}function is(e,t,n,r=!1){for(let i of n){let n=i.left,a=i.right===void 0?void 0:i.right+1,o=as(e,t,n,!0,0),s=as(e,t,a,!1,o);for(let n=o;n<=s;n++)os(t.get(e[n]),i,r);ss(e,t,o,s)}}function as(e,t,n,r,i){if(n===void 0)return e.length-1;let a=ls(e,n,i);return n===e[a]?r?a:a-1:(e.splice(a+1,0,n),t.set(n,[...t.get(e[a])]),r?a+1:a)}function os(e,t,n=!1){let r=t.top,i=t.bottom===void 0?void 0:t.bottom+1,a=[],o=ls(e,r,0,!1);if((o%2!=0&&!n||o%2==0&&n)&&a.push(r),i===void 0){e.splice(o+1),e.push(...a);return}let s=us(e,i,0,!1);(s%2==0&&!n||s%2!=0&&n)&&a.push(i),e.splice(o+1,s-o-1,...a)}function ss(e,t,n,r){let i=n-1==-1?0:n-1,a=r===e.length-1?r:r+1;for(let n=a;n>i;n--)Mt(t.get(e[n]),t.get(e[n-1]))&&(t.delete(e[n]),e.splice(n,1))}function cs(e,t){let n=[],r=[];for(let i=0;i<e.length;i++){let a=e[i],o=t.get(a);if(!o||o.length===0){n.push(...r),r=[];continue}let s=e[i+1];s!==void 0&&s--;let c=[];for(let e=0;e<o.length;e+=2){let t=o[e],n=o[e+1];n!==void 0&&n--;let i={top:t,left:a,bottom:n,right:s,hasHeader:n===void 0&&t!==0||s===void 0&&a!==0},l=!1;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.top===i.top&&t.bottom===i.bottom){t.right=i.right,r.splice(e,1),c.push(t),l=!0;break}}l||c.push(i)}n.push(...r),r=c}return n.push(...r),n}function ls(e,t,n=0,r=!0){let i=e.length-1,a=-1;for(;n<=i;){let o=Math.floor((n+i)/2);if(e[o]===t&&r)return o;e[o]<t?(a=o,n=o+1):i=o-1}return a}function us(e,t,n=0,r=!0){let i=e.length-1,a=e.length;for(;n<=i;){let o=Math.floor((n+i)/2);if(e[o]===t&&r)return o;e[o]>t?(a=o,i=o-1):n=o+1}return a}function ds(e){let t=new Xt(e);Jn(t);let n=e.indexOf(`!`);n!==-1&&t.advanceBy(n+1);let r=Yn(t),i=Xn(t),a,o,s,c,l=!1,u=!1,d=!1;if(i===-1?(s=c=r-1,a=o=0,l=!0):r===-1?(a=o=i-1,s=c=0,u=!0):(s=c=r-1,a=o=i-1,d=!0),Jn(t),t.current===`:`){t.advanceBy(1),Jn(t);let e=Yn(t),n=Xn(t);n===-1?(c=e-1,l=!0):e===-1?(o=n-1,u=!0):(c=e-1,o=n-1,a=l?o:a,s=u?c:s,d=!0)}let f={top:a,left:s,bottom:l?void 0:o,right:u?void 0:c};return d&&=u||l,d&&(f.hasHeader=d),f}function fs(e){let t=Is(ds(e)),n=t.bottom,r=t.right;if(n!==void 0&&n>9999998||r!==void 0&&r>qn)throw Error(`Range string out of bounds: ${e}`);if(n===void 0&&r===void 0)throw Error(`Wrong zone xc. The zone cannot be at the same time a full column and a full row`);return t}function ps(e){let t=fs(e);if(t.bottom===void 0||t.right===void 0)throw Error(`This does not support unbounded ranges`);return t}function ms(e){return gs(fs(e))}function hs(e){try{return ms(e)}catch{return!1}}function gs(e){let{bottom:t,top:n,left:r,right:i}=e;return t!==void 0&&isNaN(t)||isNaN(n)||isNaN(r)||i!==void 0&&isNaN(i)?!1:_s(e)&&e.top>=0&&e.left>=0}function _s(e){return(e.bottom===void 0||e.bottom>=e.top&&e.bottom>=0)&&(e.right===void 0||e.right>=e.left&&e.right>=0)}function vs(e){let{top:t,bottom:n,left:r,right:i}=e,a=`hasHeader`in e?e.hasHeader:!1,o=t===n&&r===i;if(n===void 0&&i!==void 0)return t===0&&!a?`${Hn(r)}:${Hn(i)}`:`${T(r,t)}:${Hn(i)}`;if(i===void 0&&n!==void 0)return r===0&&!a?`${t+1}:${n+1}`:`${T(r,t)}:${n+1}`;if(n!==void 0&&i!==void 0)return o?T(r,t):`${T(r,t)}:${T(i,n)}`;throw Error(`Bad zone format`)}function ys(e,t,n,r,i){let a=t===`left`?`columns`:`rows`,o=r===`before`?n-1:n,s=e[t===`left`?`right`:`bottom`];return e[t]<=o&&s&&s>o?Ls(e,a,`RESIZE`,i):o<e[t]?Ls(e,a,`MOVE`,i):{...e}}function bs(e,t,n,r,i){let a=t===`left`?`columns`:`rows`,o=r===`before`?n-1:n,s=t===`left`?`right`:`bottom`;return e[t]<=o&&e[s]>o?Ls(e,a,`RESIZE`,i):o<e[t]?Ls(e,a,`MOVE`,i):{...e}}function xs(e,t,n){let r=t===`left`?`right`:`bottom`,i=e[t],a=e[r];for(let o of n.sort((e,t)=>t-e))e[t]>o&&(i--,a--),e[t]<o&&e[r]>=o&&a--;return{...e,[t]:i,[r]:a}}function Ss(e,t,n){let r=t===`left`?`right`:`bottom`,i=e[t],a=e[r],o=e[r];for(let r of n.sort((e,t)=>t-e))e[t]>r&&(i--,a!==void 0&&a--),o!==void 0&&a!==void 0&&e[t]<=r&&o>=r&&a--;if(!(a!==void 0&&i>a))return{...e,[t]:i,[r]:a}}function Cs(...e){return{top:Math.min(...e.map(e=>e.top)),left:Math.min(...e.map(e=>e.left)),bottom:Math.max(...e.map(e=>e.bottom)),right:Math.max(...e.map(e=>e.right))}}function ws(...e){return{top:Math.min(...e.map(e=>e.top)),left:Math.min(...e.map(e=>e.left)),bottom:e.some(e=>e.bottom===void 0)?void 0:Math.max(...e.map(e=>e.bottom)),right:e.some(e=>e.right===void 0)?void 0:Math.max(...e.map(e=>e.right))}}function Ts(e,t){if(Ds(e,t))return{top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),bottom:Math.min(e.bottom,t.bottom),right:Math.min(e.right,t.right)}}function Es(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function Ds(e,t){return!(e.bottom<t.top||t.bottom<e.top||e.right<t.left||t.right<e.left)}function Os(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++)if(Ds(e[t],e[n]))return!0;return!1}function ks(e,t,n){let{left:r,right:i,top:a,bottom:o}=n;return e>=r&&e<=i&&t>=a&&t<=o}function As(e,t){return e.left>=t.left&&e.right<=t.right&&e.top>=t.top&&e.bottom<=t.bottom}function js(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function Ms(e){let{numberOfCols:t,numberOfRows:n}=js(e);return t===1||n===1}function Ns(e){let{top:t,left:n,bottom:r,right:i}=e;if(Ws(e)===1)return[];let a={top:t+1,bottom:r,left:n,right:n};if(i===n)return[a];let o={top:t,bottom:r,left:n+1,right:i};return t===r?[o]:[a,o]}function Ps(e){let t={};for(let n of e)t[n.sheetId]??=[],t[n.sheetId].push(z(n));for(let e in t)t[e]=R(t[e]);return t}function Fs(e){let t=[],{left:n,right:r,top:i,bottom:a}=Is(e);for(let e of S(n,r+1))for(let n of S(i,a+1))t.push({col:e,row:n});return t}function Is(e){return e.right!==void 0&&e.left>e.right&&(e={...e,left:e.right,right:e.left}),e.bottom!==void 0&&e.top>e.bottom&&(e={...e,top:e.bottom,bottom:e.top}),e}function Ls(e,t,n,r){let i=t===`both`?r[0]:t===`columns`?r:0,a=t===`both`?r[1]:t===`rows`?r:0,o=`hasHeader`in e?e.hasHeader:!1,s;s=Us(e)&&!o?t!==`rows`:Hs(e)&&!o?t!==`columns`:!0;let c={...e};return s&&n===`MOVE`&&(c.left+=i,c.top+=a),c.right!==void 0&&(c.right+=i),c.bottom!==void 0&&(c.bottom+=a),c}function Rs(e){return e.reverse().filter((e,t,n)=>t===n.findIndex(t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)).reverse()}function zs(e){return e.reduce((e,t)=>{let n=e.length;for(let r=0;r<n;r++)if(Ds(e[r],t))return e[r]=Cs(e[r],t),e;return e[n]=t,e},[])}function Bs(e,t){let n,r,{left:i,right:a,top:o,bottom:s}=e,{left:c,right:l,top:u,bottom:d}=t;return n=c===i?l===a?c:l:c,r=u===o?d===s?u:d:u,{col:n,row:r}}function z(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function Vs(e){return{...e,right:e.left,bottom:e.top}}function Hs(e){return e.right===void 0}function Us(e){return e.bottom===void 0}function Ws(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function Gs(e,t,n){return e.left<t&&t<=e.right||e.top<n&&n<=e.bottom}function Ks(e,t,n){return e.some(e=>Gs(e,t,n))}function qs(e,t){let{left:n,top:r,bottom:i,right:a}=e;if(a!==void 0&&i!==void 0)return e;if(i===void 0&&a!==void 0)return{right:a,top:r,left:n,bottom:t.numberOfRows-1};if(a===void 0&&i!==void 0)return{bottom:i,left:n,top:r,right:t.numberOfCols-1};throw Error(`Bad zone format`)}function Js(e){return e.length<2?!0:R(e).length===1}function Ys(e){let t=new Set;for(let n of R(e))for(let e of S(n.left,n.right+1))t.add(e);return t}function Xs(e){let t=new Set;for(let n of R(e))for(let e of S(n.top,n.bottom+1))t.add(e);return t}function Zs(e,t){return e.right+1===t.left||e.left===t.right+1?e.top<=t.bottom&&e.top>=t.top||t.top<=e.bottom&&t.top>=e.top:e.bottom+1===t.top||e.top===t.bottom+1?e.left<=t.right&&e.left>=t.left||t.left<=e.right&&t.left>=e.left:!1}function Qs(e){let t=[...e],n=!0;for(;n;){n=!1;for(let e=0;e<t.length;e++){let r=t[e],i=t.findIndex((t,n)=>e!==n&&(Zs(t,r)||Ds(t,r)));if(i!==-1){t[e]=Cs(t[i],r),t.splice(i,1),n=!0;break}}}return t}let $s=new WeakMap,ec=new WeakMap;function tc(e,t){$s.has(t)||($s.set(t,new Map),ec.set(t,0));let n=$s.get(t),r=ic(e);if(n.has(r)){let i=n.get(r);return t[i]=e,i}let i=ec.get(t)+1;return n.set(r,i),ec.set(t,i),t[i]=e,i}function nc(e){let t={};for(let n in e){let r=R(e[n].map(z));for(let e of r)t[vs(e)]=Number(n)}return t}function*rc(e,t){for(let n in t){let r=ps(n),i=t[n];for(let t=r.top;t<=r.bottom;t++)for(let n=r.left;n<=r.right;n++)yield[{sheetId:e,col:n,row:t},i]}}function ic(e){if(e===null)return`null`;if(e===void 0)return`undefined`;if(typeof e!=`object`)return String(e);if(Array.isArray(e)){let t=e.length,n=`[`;for(let r=0;r<t;r++)r>0&&(n+=`,`),n+=ic(e[r]);return n+`]`}let t=Object.keys(e).sort(),n=`{`;for(let r of t)e[r]!==void 0&&(n+=`"${r}":${ic(e[r])},`);return n+=`}`,n}function ac(e){return 20+120*Math.exp(-.035*(e-1))}let oc=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,`i`),sc=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,`i`),cc=new RegExp(/^\$?([A-Z]{1,3})+$/,`i`),lc=new RegExp(/^\$?([0-9]{1,7})+$/,`i`),uc=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,`i`),dc=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,`i`),fc=RegExp(`^\\s*('.+'!|[^']+!)?(`+[oc.source,`(\\$?[A-Z]{1,3})?\\$?[0-9]{1,7}\\s*:\\s*(\\$?[A-Z]{1,3})?\\$?[0-9]{1,7}\\s*`,`\\$?[A-Z]{1,3}(\\$?[0-9]{1,7})?\\s*:\\s*\\$?[A-Z]{1,3}(\\$?[0-9]{1,7})?\\s*`].join(`|`)+`)$`,`i`);function pc(e){return uc.test(e)}function mc(e){return dc.test(e)}function hc(e){return cc.test(e)}function gc(e){return lc.test(e)}function _c(e){return sc.test(e)}function vc(e){if(!e.includes(`!`))return{xc:e};let t=e.split(`!`),n=t.pop();return{sheetName:ct(t.join(`!`))||void 0,xc:n}}function yc(e,t){return e===void 0?t:`${ut(e)}!${t}`}function bc(e,t){let n=e.zone,r=qs(n,t(e.sheetId)),i=e.parts;return e.parts.length===1&&Ws(r)>1?i=[e.parts[0],e.parts[0]]:e.parts.length===2&&Ws(r)===1&&(i=[e.parts[0]]),{unboundedZone:n,zone:r,parts:i,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function xc(e,t){let n=e.xc,{xc:r,sheetName:i}=vc(n),a=fs(r);return bc({zone:a,parts:kc(r,a),sheetId:e.sheetId,prefixSheet:!!i,invalidSheetName:e.invalidSheetName},t)}function Sc(e){let t={left:-1,top:-1,right:-1,bottom:-1};return{sheetId:``,zone:t,unboundedZone:t,parts:[],invalidXc:e,prefixSheet:!1}}function Cc(e){return Us(e.unboundedZone)}function wc(e){return Hs(e.unboundedZone)}function Tc(e,t,n,r={useBoundedReference:!1,useFixedReference:!1}){if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0||e.zone.left<0||e.zone.top<0)return k.InvalidReference;let i=e.sheetId!==t||e.invalidSheetName||e.prefixSheet,a=``;if(i&&(a=e.invalidSheetName?ut(e.invalidSheetName):ut(n(e.sheetId))),i&&!a)return k.InvalidReference;let o=zc(e,0,r);return e.parts&&e.parts.length===2&&(e.zone.top!==e.zone.bottom||e.zone.left!==e.zone.right||e.parts[0].rowFixed||e.parts[0].colFixed||e.parts[1].rowFixed||e.parts[1].colFixed)&&(o+=`:`,o+=zc(e,1,r)),`${i?a+`!`:``}${o}`}function Ec(e,t,n){let r=n.sheetId===e?t:n.sheetId;return{...n,sheetId:r}}function Dc(e,t,n){if(!n)return;let r=e.getRangeFromSheetXC(t,n);return r.invalidSheetName||r.invalidXc?void 0:r}function Oc(e){let t=[];for(let n of e)for(let e of Fs(n.zone))t.push({...e,sheetId:n.sheetId});return t}function kc(e,t){let n=e.split(`:`).map(e=>{let t=mc(e);return{colFixed:t?!1:e.startsWith(`$`),rowFixed:t?e.startsWith(`$`):e.includes(`$`,1)}}),r=t.bottom===void 0,i=t.right===void 0;return r&&(n[0].rowFixed=n[0].rowFixed||n[1].rowFixed,n[1].rowFixed=n[0].rowFixed||n[1].rowFixed),i&&(n[0].colFixed=n[0].colFixed||n[1].colFixed,n[1].colFixed=n[0].colFixed||n[1].colFixed),n}function Ac(e){if(_s(e.zone))return e;let t={...e.unboundedZone},n={...e.zone},r=e.parts;if(t.right!==void 0&&t.right<t.left){let e=t.right;t.right=t.left,t.left=e,n.right=n.left,n.left=e,r=[{colFixed:r[1]?.colFixed||!1,rowFixed:r[0]?.rowFixed||!1},{colFixed:r[0]?.colFixed||!1,rowFixed:r[1]?.rowFixed||!1}]}if(t.bottom!==void 0&&t.bottom<t.top){let e=t.bottom;t.bottom=t.top,t.top=e,n.bottom=n.top,n.top=e,r=[{colFixed:r[0]?.colFixed||!1,rowFixed:r[1]?.rowFixed||!1},{colFixed:r[1]?.colFixed||!1,rowFixed:r[0]?.rowFixed||!1}]}return{unboundedZone:t,zone:n,parts:r,invalidXc:e.invalidXc,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function jc(e){return Mc.get(e.type)?.(e)}let Mc=new class extends g{add(e,t){return super.add(e,t),this}get(e){return this.content[e]}};Mc.add(`REMOVE_COLUMNS_ROWS`,e=>({applyChange:Nc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`ADD_COLUMNS_ROWS`,e=>({applyChange:Pc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`DELETE_SHEET`,e=>({applyChange:Fc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`RENAME_SHEET`,e=>({applyChange:Ic(e),sheetId:e.sheetId,sheetName:{old:e.oldName,current:e.newName}})).add(`MOVE_RANGES`,e=>({applyChange:Lc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}}));function Nc(e){let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`,i=[...e.elements];i.sort((e,t)=>t-e);let a=ft(i);return i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`,range:i};let o=i,s=`NONE`;for(let e of a){let a=Yt(e),c=Jt(e);if(i.zone[t]<=a&&a<=i.zone[n]){let e=Math.min(i.zone[n],c)-a+1;s=`RESIZE`,o=Rc(o,r,s,-e)}else if(i.zone[t]>=a&&i.zone[n]<=c)s=`REMOVE`,o=Sc(k.InvalidReference);else if(i.zone[t]<=c&&i.zone[n]>=c){let e=c-i.zone[t]+1;s=`RESIZE`,o=Rc(o,r,s,-e),o=Rc(o,r,`MOVE`,-(i.zone[t]-a))}else a<i.zone[t]&&(s=`MOVE`,o=Rc(o,r,s,-(c-a+1)))}return{changeType:s,range:o}}}function Pc(e){let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`;return i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`,range:i};if(e.position===`after`){if(i.zone[t]<=e.base&&e.base<i.zone[n])return{changeType:`RESIZE`,range:Rc(i,r,`RESIZE`,e.quantity)};if(e.base<i.zone[t])return{changeType:`MOVE`,range:Rc(i,r,`MOVE`,e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[n])return{changeType:`RESIZE`,range:Rc(i,r,`RESIZE`,e.quantity)};if(e.base<=i.zone[t])return{changeType:`MOVE`,range:Rc(i,r,`MOVE`,e.quantity)}}return{changeType:`NONE`,range:i}}}function Fc(e){return t=>{if(t.sheetId!==e.sheetId&&t.invalidSheetName!==e.sheetName)return{changeType:`NONE`,range:t};let n=e.sheetName;return t={...Sc(k.InvalidReference),invalidSheetName:n},{changeType:`REMOVE`,range:t}}}function Ic(e){return t=>{if(t.sheetId===e.sheetId)return{changeType:`CHANGE`,range:t};if(e.newName&&t.invalidSheetName===e.newName){let n=e.sheetId;return{changeType:`CHANGE`,range:{...t,sheetId:n,invalidSheetName:void 0}}}if(e.oldName&&t.invalidSheetName===e.oldName){let n=e.sheetId;return{changeType:`CHANGE`,range:{...t,sheetId:n,invalidSheetName:void 0}}}return{changeType:`NONE`,range:t}}}function Lc(e){let t=e.target[0];return n=>{if(n.sheetId!==e.sheetId||!As(n.zone,t))return{changeType:`NONE`,range:n};let r=e.targetSheetId,i=Rc(n,`both`,`MOVE`,[e.col-t.left,e.row-t.top]),a=e.sheetId===r?i.prefixSheet:!0;return{changeType:`MOVE`,range:{...i,sheetId:r,prefixSheet:a}}}}function Rc(e,t,n,r){return{...e,unboundedZone:Ls(e.unboundedZone,t,n,r),zone:Ls(e.zone,t,n,r)}}function zc(e,t,n={useBoundedReference:!1,useFixedReference:!1}){let r=e.parts[t]?.colFixed||n.useFixedReference?`$`:``,i=Hn(t===0?e.zone.left:e.zone.right),a=e.parts[t]?.rowFixed||n.useFixedReference?`$`:``,o=String(t===0?e.zone.top+1:e.zone.bottom+1),s=``;return s=Us(e.unboundedZone)&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:r+i:Hs(e.unboundedZone)&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:a+o:r+i+a+o,s}function Bc(e,t){e=e.toLocaleLowerCase(),t=t.toLocaleLowerCase();let n=0,r=0,i=t.length,a=0;for(let o=0;o<i;o++)t[o]===e[a]?(a++,r+=100+r-o/200):r=0,n+=r;return a===e.length?n:0}function Vc(e,t,n){let r=[];return t.forEach(t=>{let i=Bc(e,n(t));i>0&&r.push({score:i,elem:t})}),r.sort((e,t)=>t.score-e.score),r.map(e=>e.elem)}function Hc(e){let t=[];for(let n=0;n<e;n++)t.push({cells:{}});return t}function Uc(e,t,n){return n.map(n=>n>=e?n+t:n)}function Wc(e,t){return e=[...e].sort((e,t)=>t-e),t.map(t=>{for(let n of e)if(t>n)t--;else if(t===n)return;return t}).filter(C)}function Gc(e,t=`Sheet`){let n=1,r=`${t}${n}`;for(;e.includes(r);)r=`${t}${n}`,n++;return r}function Kc(e,t){let n=1,r=E(`Copy of %s`,e),i=r.toString();for(;t.includes(i);)i=`${r} (${n})`,n++;return i}function qc(e,t){return e===void 0||t===void 0?!1:ct(e.trim().toUpperCase())===ct(t.trim().toUpperCase())}function Jc(e,t=1){return t*(e+4)-4}function Yc(e,t,n,r){if(!t||!t.isFormula&&!t.content)return 23;let i=``;try{if(!t.isFormula){let e={format:t.format,locale:n};i=L(Ko(t.content,n),e)}}catch{i=k.GenericError}return Xc(e,i,t.style,r)}function Xc(e,t,n,r){let i=cl(e,t,n,n?.wrapping===`wrap`?r-8:void 0).length;return Jc(ol(n),i)+6}function Zc(e,t=!1,n=!1){return`${n?`italic`:``} ${t?`bold`:``} ${e}px ${He}`}let Qc={};function $c(e,t,n,r=`pt`){return el(e,t,al(n,r))}function el(e,t,n){if(Qc[n]||(Qc[n]={}),Qc[n][t]===void 0){let r=e.font;e.font=n,Qc[n][t]=e.measureText(t).width,e.font=r}return Qc[n][t]}let tl={};function nl(e,t,n,r=`pt`){let i=al(n,r);e.save(),e.font=i;let a=rl(e,t);return e.restore(),a}function rl(e,t){let n=e.font;if(tl[n]||(tl[n]={}),tl[n][t]===void 0){let r=e.measureText(t),i=r.width,a=r.fontBoundingBoxAscent+r.fontBoundingBoxDescent;tl[n][t]={width:i,height:a}}return tl[n][t]}function il(e){return Math.round(e*96/72)}function al(e,t=`pt`){return`${e.italic?`italic `:``}${e.bold?`bold`:`400`} ${(t===`pt`?ol(e):e.fontSize)??Ve}px ${He}`}function ol(e){return il(e?.fontSize||Ve)}function sl(e,t,n,r){if($c(e,t,r)<=n)return[t];let i=[],a=``;for(let o of t)$c(e,a+o,r)>n?(i.push(a),a=o):a+=o;return i.push(a),i}function cl(e,t,n,r){n||={},_t(t)&&(t=bt(t).label);let i=[],a=t.includes(`
|
|
5
5
|
`)?t.split(`
|
|
6
|
-
`):[t];for(let t of a){let a=t.includes(` `)?t.split(` `):[t];if(!r){i.push(t);continue}let o=``,s=r;for(let t of a){let a=sl(e,t,r,n),c=a.pop(),l=$c(e,c,n);if(a.length)o!==``&&(i.push(o),o=``,s=r),a.forEach(e=>{i.push(e)}),o=c,s=r-l;else{let t=o===``?c:` `+c,a=$c(e,t,n);a<=s?(o+=t,s-=a):(i.push(o),o=c,s=r-l)}}o!==``&&i.push(o)}return i}function ll(e,t,n,r=.25){let i=1;if(n(i)>e)return i;if(n(t)<e)return t;let a=(i+t)/2,o=n(a),s=0;for(;Math.abs(o-e)>r&&s<20;)o>=e?t=(i+t)/2:i=(i+t)/2,a=(i+t)/2,o=n(a),s++;return a}function ul(e){return e?e.toLowerCase():``}let dl=/([0-9\.]*)px/;function fl(e){return Number(e.match(dl)?.[1])}function pl(e,t,n){let r=el(e,t,e.font);if(r<=n)return t;let i=el(e,`…`,e.font);if(r<=i)return t;let a=t.length;for(;r>=n-i&&a-- >0;)t=t.substring(0,a),r=el(e,t,e.font);return t+`…`}function ml(e,t,n,r=!1,i=!1,a=fl(e.font)/10){if(e.fillText(t,n.x,n.y),!r&&!i)return;let o=e.measureText(t),s=o.width,c=o.actualBoundingBoxAscent+o.actualBoundingBoxDescent,l=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent,{x:u,y:d}=n,f=d,p=d;switch(e.textAlign){case`center`:u-=s/2;break;case`right`:u-=s;break}switch(e.textBaseline){case`top`:p+=l-2*a,f+=l/2-a;break;case`middle`:p+=l/2-a;break;case`alphabetic`:p+=2*a,f-=3*a;break;case`bottom`:p=d,f-=c/2-a/2;break}r&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,p),e.lineTo(u+s,p),e.stroke()),i&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,f),e.lineTo(u+s,f),e.stroke())}function hl(e,t,n,r,i=`pt`){if($c(e,n,r,i)<=t)return n;let a=$c(e,`...`,r,i);if(a>=t)return``;let o=1,s=n.length,c;for(;o<=s;){let l=Math.floor((o+s)/2);c=$c(e,n.slice(0,l),r,i),c+a>t?s=l-1:o=l+1}let l=n.slice(0,Math.max(0,o-1));return l?l+`...`:``}var gl=class{smallUuid(){return window.crypto?`10000000-1000`.replace(/[01]/g,e=>{let t=Number(e);return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)}):`xxxxxxxx-xxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}uuidv4(){return window.crypto?`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>{let t=Number(e);return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)}):`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}};let _l=[`image/avif`,`image/bmp`,`image/gif`,`image/vnd.microsoft.icon`,`image/jpeg`,`image/png`,`image/tiff`,`image/webp`];function vl(e,t){let n=new Set(t.map(e=>e.left)),r=new Set(t.map(e=>e.right)),i=new Set(t.map(e=>e.top)),a=new Set(t.map(e=>e.bottom)),o=i.size===1&&a.size===1||n.size===1&&r.size===1?zs(t):[t[t.length-1]],s=o.map(e=>Fs(e)).flat();return{sheetId:e,zones:t,clippedZones:o,columnsIndexes:[...new Set(s.map(e=>e.col))].sort((e,t)=>e-t),rowsIndexes:[...new Set(s.map(e=>e.row))].sort((e,t)=>e-t)}}function yl(e,t,n){let r=Math.max(e.right-t+1,e.left),i=Math.max(e.bottom-n+1,e.top),a=[];for(let o=e.left;o<=r;o+=t)for(let r=e.top;r<=i;r+=n)a.push({left:o,top:r,bottom:r+n-1,right:o+t-1});return a}function bl(e,t){if(!t.length||!t[0].length)return e;let n=t[0].length,r=t.length;return e.map(e=>yl(e,n,r)).flat()}function xl(e){let t;e[`text/html`]&&(t=Sl(new DOMParser().parseFromString(e[`text/html`],`text/html`)));let n=e[`text/plain`]||``,r;if(!n.trim()){for(let t of _l)if(e[t]){r=e[t];break}}return{text:n,data:t,imageBlob:r}}function Sl(e){if([...e.documentElement.attributes].some(e=>e.value.includes(`microsoft`)))return;let t=e.querySelector(`div`)?.getAttribute(`data-osheet-clipboard`);return t&&JSON.parse(t)}let Cl=(e,t,n,r)=>{e.forEach(({handlerName:e,handler:i})=>{let a=t[e];a&&i.paste(n,a,r)})};function wl(e,t,n,r,i){let a,o=[],s={sheetId:e,zones:t};for(let{handlerName:c,handler:l}of r){let r=n[c];if(!r)continue;let u=l.getPasteTarget(e,t,r,i);u.figureId&&(s.figureId=u.figureId);for(let e of u.zones){if(o.push(e),a===void 0){a=e;continue}a=Cs(a,e)}}return{target:s,zone:a,selectedZones:o}}let Tl=(e,t,n)=>{let r={col:t[0].left,row:t[0].top};e.getBackToDefault(),e.selectZone({cell:r,zone:Cs(...n)},{scrollIntoView:!1})};var El=class{constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,n=`copyPaste`){}paste(e,t,n){}isPasteAllowed(e,t,n,r){return`Success`}isCutAllowed(e){return`Success`}getPasteTarget(e,t,n,r){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}},Dl=class extends El{copy(e,t,n=`copyPaste`){}pasteFromCopy(e,t,n,r){if(t.length===1)for(let i of bl(t,n))this.pasteZone(e,i.left,i.top,n,r);else for(let i of R(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++)this.pasteZone(e,t,a,n,r)}pasteZone(e,t,n,r,i){}},Ol=class extends Dl{queuedBordersToAdd={};copy(e){let t=e.sheetId;if(e.zones.length===0)return;let{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getCellBorder(r))}i.push(n)}return{borders:i}}paste(e,t,n){let r=e.sheetId;if(n.pasteOption===`asValue`)return;let i=e.zones;if(!n.isCutOperation)this.pasteFromCopy(r,i,t.borders);else{let{left:e,top:n}=i[0];this.pasteZone(r,e,n,t.borders)}this.executeQueuedChanges(r)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteBorder(o,a)}}pasteBorder(e,t){let n={...this.getters.getCellBorder(t),...e},r=JSON.stringify(n);this.queuedBordersToAdd[r]||(this.queuedBordersToAdd[r]=[]),this.queuedBordersToAdd[r].push(z(t))}executeQueuedChanges(e){for(let t in this.queuedBordersToAdd){let n=this.queuedBordersToAdd[t],r=JSON.parse(t),i=R(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}};let kl=[`%`],Al=`+,-,*,/,:,=,<>,>=,>,<=,<,^,&`.split(`,`).concat(kl);function jl(e,t=D){e=zt(e);let n=new Xt(e),r=[],i=It.test(e)?Ul:Wl;for(;!n.isOver();){let e=Gl(n)||i(n)||Fl(n,t)||Pl(n)||Il(n)||zl(n)||Ml(n)||Kl(n)||Rl(n,t)||Hl(n);e||={type:`UNKNOWN`,value:n.shift()},r.push(e)}return r}function Ml(e){return e.current===`?`?(e.shift(),{type:`DEBUGGER`,value:`?`}):null}let Nl={"(":{type:`LEFT_PAREN`,value:`(`},")":{type:`RIGHT_PAREN`,value:`)`}};function Pl(e){return e.current===`(`||e.current===`)`?Nl[e.shift()]:null}function Fl(e,t){return e.current===t.formulaArgSeparator?{type:`ARG_SEPARATOR`,value:e.shift()}:null}function Il(e){for(let t of Al)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:`OPERATOR`,value:t};return null}let Ll=new Set(`0123456789`);function Rl(e,t){if(!Ll.has(e.current)&&e.current!==t.decimalSeparator)return null;let n=e.remaining().match(Mi(t.decimalSeparator));return n?(e.advanceBy(n[0].length),{type:`NUMBER`,value:n[0]}):null}function zl(e){if(e.current===`"`){let t=e.shift(),n=t;for(;e.current&&(e.current!==t||n[n.length-1]===`\\`);)n+=e.shift();return e.current===`"`&&(n+=e.shift()),{type:`STRING`,value:n}}return null}let Bl=/\p{L}|\p{N}|_|\.|!|\$/u,Vl=new Set(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$`);function Hl(e){let t=``;if(e.current===`'`){let n=e.shift();for(t+=n;e.current;)if(n=e.shift(),t+=n,n===`'`)if(e.current&&e.current===`'`)n=e.shift(),t+=n;else break;if(n!==`'`)return{type:`UNKNOWN`,value:t}}for(;e.current&&(Vl.has(e.current)||e.current.match(Bl));)t+=e.shift();if(t.length){let e=t;return fc.test(e)?{type:`REFERENCE`,value:e}:{type:`SYMBOL`,value:e}}return null}function Ul(e){let t=``;for(;e.current===` `||e.current&&e.current.match(It);)t+=e.shift();return t?{type:`SPACE`,value:t}:null}function Wl(e){let t=``;for(;e.current===` `;)t+=e.shift();return t?{type:`SPACE`,value:t}:null}function Gl(e){let t=0;for(;e.current===`
|
|
6
|
+
`):[t];for(let t of a){let a=t.includes(` `)?t.split(` `):[t];if(!r){i.push(t);continue}let o=``,s=r;for(let t of a){let a=sl(e,t,r,n),c=a.pop(),l=$c(e,c,n);if(a.length)o!==``&&(i.push(o),o=``,s=r),a.forEach(e=>{i.push(e)}),o=c,s=r-l;else{let t=o===``?c:` `+c,a=$c(e,t,n);a<=s?(o+=t,s-=a):(i.push(o),o=c,s=r-l)}}o!==``&&i.push(o)}return i}function ll(e,t,n,r=.25){let i=1;if(n(i)>e)return i;if(n(t)<e)return t;let a=(i+t)/2,o=n(a),s=0;for(;Math.abs(o-e)>r&&s<20;)o>=e?t=(i+t)/2:i=(i+t)/2,a=(i+t)/2,o=n(a),s++;return a}function ul(e){return e?e.toLowerCase():``}let dl=/([0-9\.]*)px/;function fl(e){return Number(e.match(dl)?.[1])}function pl(e,t,n){let r=el(e,t,e.font);if(r<=n)return t;let i=el(e,`…`,e.font);if(r<=i)return t;let a=t.length;for(;r>=n-i&&a-- >0;)t=t.substring(0,a),r=el(e,t,e.font);return t+`…`}function ml(e,t,n,r=!1,i=!1,a=fl(e.font)/10){if(e.fillText(t,n.x,n.y),!r&&!i)return;let o=e.measureText(t),s=o.width,c=o.actualBoundingBoxAscent+o.actualBoundingBoxDescent,l=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent,{x:u,y:d}=n,f=d,p=d;switch(e.textAlign){case`center`:u-=s/2;break;case`right`:u-=s;break}switch(e.textBaseline){case`top`:p+=l-2*a,f+=l/2-a;break;case`middle`:p+=l/2-a;break;case`alphabetic`:p+=2*a,f-=3*a;break;case`bottom`:p=d,f-=c/2-a/2;break}r&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,p),e.lineTo(u+s,p),e.stroke()),i&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,f),e.lineTo(u+s,f),e.stroke())}function hl(e,t,n,r,i=`pt`){if($c(e,n,r,i)<=t)return n;let a=$c(e,`...`,r,i);if(a>=t)return``;let o=1,s=n.length,c;for(;o<=s;){let l=Math.floor((o+s)/2);c=$c(e,n.slice(0,l),r,i),c+a>t?s=l-1:o=l+1}let l=n.slice(0,Math.max(0,o-1));return l?l+`...`:``}var gl=class{smallUuid(){return window.crypto?`10000000-1000`.replace(/[01]/g,e=>{let t=Number(e);return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)}):`xxxxxxxx-xxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}uuidv4(){return window.crypto?`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>{let t=Number(e);return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)}):`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}};let _l=[`image/avif`,`image/bmp`,`image/gif`,`image/vnd.microsoft.icon`,`image/jpeg`,`image/png`,`image/tiff`,`image/webp`];function vl(e,t){let n=new Set(t.map(e=>e.left)),r=new Set(t.map(e=>e.right)),i=new Set(t.map(e=>e.top)),a=new Set(t.map(e=>e.bottom)),o=i.size===1&&a.size===1||n.size===1&&r.size===1?zs(t):[t[t.length-1]],s=o.map(e=>Fs(e)).flat();return{sheetId:e,zones:t,clippedZones:o,columnsIndexes:[...new Set(s.map(e=>e.col))].sort((e,t)=>e-t),rowsIndexes:[...new Set(s.map(e=>e.row))].sort((e,t)=>e-t)}}function yl(e,t,n){let r=Math.max(e.right-t+1,e.left),i=Math.max(e.bottom-n+1,e.top),a=[];for(let o=e.left;o<=r;o+=t)for(let r=e.top;r<=i;r+=n)a.push({left:o,top:r,bottom:r+n-1,right:o+t-1});return a}function bl(e,t){if(!t.length||!t[0].length)return e;let n=t[0].length,r=t.length;return e.map(e=>yl(e,n,r)).flat()}function xl(e){let t;e[`text/html`]&&(t=Sl(new DOMParser().parseFromString(e[`text/html`],`text/html`)));let n=e[`text/plain`]||``,r;if(!n.trim()){for(let t of _l)if(e[t]){r=e[t];break}}return{text:n,data:t,imageBlob:r}}function Sl(e){if([...e.documentElement.attributes].some(e=>e.value.includes(`microsoft`)))return;let t=e.querySelector(`div`)?.getAttribute(`data-osheet-clipboard`);return t&&JSON.parse(t)}let Cl=(e,t,n,r)=>{e.forEach(({handlerName:e,handler:i})=>{let a=t[e];a&&i.paste(n,a,r)})};function wl(e,t,n,r,i){let a,o=[],s={sheetId:e,zones:t};for(let{handlerName:c,handler:l}of r){let r=n[c];if(!r)continue;let u=l.getPasteTarget(e,t,r,i);u.figureId&&(s.figureId=u.figureId);for(let e of u.zones){if(o.push(e),a===void 0){a=e;continue}a=Cs(a,e)}}return{target:s,zone:a,selectedZones:o}}let Tl=(e,t,n)=>{let r={col:t[0].left,row:t[0].top};e.getBackToDefault(),e.selectZone({cell:r,zone:Cs(...n)},{scrollIntoView:!1})};var El=class{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,n=`copyPaste`){}paste(e,t,n){}isPasteAllowed(e,t,n,r){return`Success`}isCutAllowed(e){return`Success`}getPasteTarget(e,t,n,r){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}},Dl=class extends El{copy(e,t,n=`copyPaste`){}pasteFromCopy(e,t,n,r){if(t.length===1)for(let i of bl(t,n))this.pasteZone(e,i.left,i.top,n,r);else for(let i of R(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++)this.pasteZone(e,t,a,n,r)}pasteZone(e,t,n,r,i){}},Ol=class extends Dl{queuedBordersToAdd={};copy(e){let t=e.sheetId;if(e.zones.length===0)return;let{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getCellBorder(r))}i.push(n)}return{borders:i}}paste(e,t,n){let r=e.sheetId;if(n.pasteOption===`asValue`)return;let i=e.zones;if(!n.isCutOperation)this.pasteFromCopy(r,i,t.borders);else{let{left:e,top:n}=i[0];this.pasteZone(r,e,n,t.borders)}this.executeQueuedChanges(r)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteBorder(o,a)}}pasteBorder(e,t){let n={...this.getters.getCellBorder(t),...e},r=JSON.stringify(n);this.queuedBordersToAdd[r]||(this.queuedBordersToAdd[r]=[]),this.queuedBordersToAdd[r].push(z(t))}executeQueuedChanges(e){for(let t in this.queuedBordersToAdd){let n=this.queuedBordersToAdd[t],r=JSON.parse(t),i=R(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}};let kl=[`%`],Al=`+,-,*,/,:,=,<>,>=,>,<=,<,^,&`.split(`,`).concat(kl);function jl(e,t=D){e=zt(e);let n=new Xt(e),r=[],i=It.test(e)?Ul:Wl;for(;!n.isOver();){let e=Gl(n)||i(n)||Fl(n,t)||Pl(n)||Il(n)||zl(n)||Ml(n)||Kl(n)||Rl(n,t)||Hl(n);e||={type:`UNKNOWN`,value:n.shift()},r.push(e)}return r}function Ml(e){return e.current===`?`?(e.shift(),{type:`DEBUGGER`,value:`?`}):null}let Nl={"(":{type:`LEFT_PAREN`,value:`(`},")":{type:`RIGHT_PAREN`,value:`)`}};function Pl(e){return e.current===`(`||e.current===`)`?Nl[e.shift()]:null}function Fl(e,t){return e.current===t.formulaArgSeparator?{type:`ARG_SEPARATOR`,value:e.shift()}:null}function Il(e){for(let t of Al)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:`OPERATOR`,value:t};return null}let Ll=new Set(`0123456789`);function Rl(e,t){if(!Ll.has(e.current)&&e.current!==t.decimalSeparator)return null;let n=e.remaining().match(Mi(t.decimalSeparator));return n?(e.advanceBy(n[0].length),{type:`NUMBER`,value:n[0]}):null}function zl(e){if(e.current===`"`){let t=e.shift(),n=t;for(;e.current&&(e.current!==t||n[n.length-1]===`\\`);)n+=e.shift();return e.current===`"`&&(n+=e.shift()),{type:`STRING`,value:n}}return null}let Bl=/\p{L}|\p{N}|_|\.|!|\$/u,Vl=new Set(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$`);function Hl(e){let t=``;if(e.current===`'`){let n=e.shift();for(t+=n;e.current;)if(n=e.shift(),t+=n,n===`'`)if(e.current&&e.current===`'`)n=e.shift(),t+=n;else break;if(n!==`'`)return{type:`UNKNOWN`,value:t}}for(;e.current&&(Vl.has(e.current)||e.current.match(Bl));)t+=e.shift();if(t.length){let e=t;return fc.test(e)?{type:`REFERENCE`,value:e}:{type:`SYMBOL`,value:e}}return null}function Ul(e){let t=``;for(;e.current===` `||e.current&&e.current.match(It);)t+=e.shift();return t?{type:`SPACE`,value:t}:null}function Wl(e){let t=``;for(;e.current===` `;)t+=e.shift();return t?{type:`SPACE`,value:t}:null}function Gl(e){let t=0;for(;e.current===`
|
|
7
7
|
`;)t++,e.shift();return t?{type:`SPACE`,value:`
|
|
8
8
|
`.repeat(t)}:null}function Kl(e){return e.currentStartsWith(k.InvalidReference)?(e.advanceBy(k.InvalidReference.length),{type:`INVALID_REFERENCE`,value:k.InvalidReference}):null}function ql(e){if(!e||typeof e!=`object`||!(!e.thousandsSeparator||typeof e.thousandsSeparator==`string`))return!1;for(let t of[`code`,`name`,`decimalSeparator`,`dateFormat`,`timeFormat`,`formulaArgSeparator`])if(!e[t]||typeof e[t]!=`string`)return!1;if(e.formulaArgSeparator===e.decimalSeparator||e.thousandsSeparator===e.decimalSeparator)return!1;try{L(1,{locale:e,format:`#,##0.00`}),L(1,{locale:e,format:e.dateFormat}),L(1,{locale:e,format:e.timeFormat})}catch{return!1}return!0}function Jl(e,t){return en(e)?Ql(e,t):tu(e,t)}function Yl(e,t){return en(e)?Ql(e,t):nu(e,t)}function Xl(e,t){return e.startsWith(`=`)?$l(e,t):iu(e,t)}function Zl(e,t){return en(e)?Ql(e,t):tu(e,t)}function Ql(e,t){return eu(e.startsWith(`+`)?`=`+e.slice(1):e,t,D)}function $l(e,t){return eu(e,D,t)}function eu(e,t,n){if(t.formulaArgSeparator===n.formulaArgSeparator&&t.decimalSeparator===n.decimalSeparator)return e;let r=jl(e,t),i=``;for(let e of r)e.type===`NUMBER`?i+=e.value.replace(t.decimalSeparator,n.decimalSeparator):e.type===`ARG_SEPARATOR`?i+=n.formulaArgSeparator:i+=e.value;return i}function tu(e,t){return t.decimalSeparator===`.`||!Pi(e,t)?e:(t.thousandsSeparator&&(e=e.replaceAll(t.thousandsSeparator,``)),e.replace(t.decimalSeparator,`.`))}function nu(e,t){if(ni(e,t)){let n=M(e,t),r=D.dateFormat;return Number.isInteger(n)||(r+=` `+D.timeFormat),L(n,{locale:D,format:r})}return tu(e,t)}function ru(e,t){if(t.decimalSeparator===`.`||!Pi(e,D))return e;let n=To(D);return e.replace(n,e=>e.replace(`.`,t.decimalSeparator))}function iu(e,t){if(ni(e,D)){let n=M(e,D),r=t.dateFormat;return Number.isInteger(n)||(r+=` `+t.timeFormat),L(n,{locale:t,format:r})}return ru(e,t)}function au(e,t){return cu(e,e=>Yl(e,t))}function ou(e,t){return cu(e,e=>Xl(e,t))}function su(e,t){let n=b(e);return n.criterion.values=n.criterion.values.map(e=>Xl(e,t)),n}function cu(e,t){switch(e=b(e),e.type){case`CellIsRule`:switch(e.operator){case`isBetween`:case`isNotBetween`:case`isEqual`:case`isNotEqual`:case`isGreaterThan`:case`isGreaterOrEqualTo`:case`isLessThan`:case`isLessOrEqualTo`:return e.values=e.values.map(e=>t(e)),e;case`beginsWithText`:case`containsText`:case`endsWithText`:case`notContainsText`:case`isEmpty`:case`isNotEmpty`:return e}case`DataBarRule`:return e;case`ColorScaleRule`:return e.minimum=lu(e.minimum,t),e.maximum=lu(e.maximum,t),e.midpoint&&=lu(e.midpoint,t),e;case`IconSetRule`:return e.lowerInflectionPoint.value=t(e.lowerInflectionPoint.value),e.upperInflectionPoint.value=t(e.upperInflectionPoint.value),e}}function lu(e,t){if(!e?.value)return e;let n=t(e.type===`formula`?`=`+e.value:e.value),r=e.type===`formula`?n.slice(1):n;return{...e,value:r}}function uu(e){return e.dateFormat+` `+e.timeFormat}function du(e){let t=!1,n=!0;return ba(e,e=>(t=!0,n&&=e,n)),{foundBoolean:t,result:n}}function fu(e){let t=!1,n=!1;return ba(e,e=>(t=!0,n||=e,!n)),{foundBoolean:t,result:n}}function pu(e,t){return fa(e,(e,t)=>e+t,0,t)}function mu(e){return da(e,(e,t)=>ja(t)?e.add(t?.value):e,new Set).size}function hu(e,t){if(!e)throw new A(t)}function gu(e,t=E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)){if(e===0)throw new Gi(t)}function _u(e){return e.length===1||e[0].length===1}function vu(...e){if(e.every(Or)){let t=e[0].length,n=e[0][0].length;for(let r of e)if(r.length!==t||r[0].length!==n)return!1;return!0}return!e.some(e=>Array.isArray(e)&&(e.length!==1||e[0].length!==1))}function yu(e){return e.length===e[0].length}let bu=e=>E(`The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.`,e);function xu(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=Array(e).fill(0),t[n][n]=1;return t}function Su(e){if(e.length<1||e[0].length<1)throw Error(`invertMatrix: an empty matrix cannot be inverted.`);if(e.length!==e[0].length)throw Error(`invertMatrix: only square matrices are invertible`);let t=1,n=e.length,r=xu(n),i=e.map(e=>e.slice());for(let e=0;e<n;e++){let a=i[e][e];if(a===0){for(let a=e+1;a<n;a++)if(i[e][a]!==0){Cu(i,e,a),Cu(r,e,a),t*=-1;break}if(a=i[e][e],a===0)return{determinant:0}}for(let t=0;t<n;t++)i[t][e]=i[t][e]/a,r[t][e]=r[t][e]/a;t*=a;for(let t=0;t<n;t++){if(t===e)continue;let a=i[e][t];for(let o=0;o<n;o++)i[o][t]-=a*i[o][e],r[o][t]-=a*r[o][e]}}return{inverted:r,determinant:t}}function Cu(e,t,n){for(let r=0;r<e.length;r++){let i=e[r][t];e[r][t]=e[r][n],e[r][n]=i}}function wu(e,t){if(e.length<1||t.length<1)throw Error(`multiplyMatrices: empty matrices cannot be multiplied.`);if(e.length!==t[0].length)throw Error(`multiplyMatrices: incompatible matrices size.`);let n=e[0].length,r=t.length,i=e.length,a=Array(r);for(let o=0;o<r;o++){a[o]=Array(n);for(let r=0;r<n;r++){let n=0;for(let a=0;a<i;a++)n+=e[a][r]*t[o][a];a[o][r]=n}}return a}function Tu(e){if(!Or(e))return e;if(!Eu(e))throw Error(`The value should be a scalar or a 1x1 matrix`);return e[0][0]}function Eu(e){return e.length===1&&e[0].length===1}function Du(e){return Or(e)&&!Eu(e)}function Ou(...e){let t=e[0].length;e.forEach((e,n)=>hu(e.length===t,E(`[[FUNCTION_NAME]] has mismatched dimensions for argument %s (%s vs %s).`,n.toString(),t.toString(),e.length.toString())))}function ku(e,t){let n=0,r=fa(e,(e,t)=>(n+=1,e+t),0,t);return gu(n),r/n}function Au(e,t){let n=0;for(let r of e)if(Or(r))for(let e of r)for(let t of e)typeof t.value==`number`&&(n+=1);else{let e=r?.value;!j(e)&&(typeof e!=`string`||Pi(e,t)||ii(e,t))&&(n+=1)}return n}function ju(e){return da(e,(e,t)=>t!==void 0&&t.value!==null?e+1:e,0)}function Mu(e,t){let n={value:-1/0};return la(e,e=>{e.value>=n.value&&(n=e)},t),n.value===-1/0?{value:0}:n}function Nu(e,t){let n={value:1/0};return la(e,e=>{e.value<=n.value&&(n=e)},t),n.value===1/0?{value:0}:n}function Pu(e,t,n){let r=e[0].length?e:[S(1,t.flat().length+1)],i=r.length,a=n[0].length?n:r;return a=a.length===i?_a(a):a,{_X:r,_newX:a}}function Fu(e,t,n=!0,r=!1){let i=t.flat(),a=i.length,{_X:o}=Pu(e,t,[[]]);o=o.length===a?_a(o):o.slice(),Ou(o[0],i);let s=o.length,c=a-s-+!!n,l=[i],u=_a(o.reverse()),d=[];for(let e=0;e<s;e++)if(d.push(0),n){for(let t of o[e])d[e]+=t;d[e]/=a}let f=0;if(n){for(let e of i)f+=e;f/=a}let p=u.map(e=>e.map((e,t)=>e-d[t]));n&&u.forEach(e=>e.push(1));let m=Lu(u,l);if(n||m.push([0]),!r)return m;let{inverted:h}=Su(wu(p,_a(p)));if(h===void 0)throw new A(E(`Matrix is not invertible`));let g=0,_=0;for(let e=0;e<a;e++){let t=i[e]-f,n=0;for(let t=0;t<s;t++){let r=p[e][t];n+=r*m[t][0]}let r=t-n;g+=r*r,_+=n*n}let v=Math.sqrt(g/c),y=_/(_+g),ee=_/s/(g/c),te=[];for(let e=0;e<s;e++)te.push(v*Math.sqrt(h[e][e]));if(n){let e=wu(h,[d]),t=wu(_a([d]),e);te.push(v*Math.sqrt(t[0][0]+1/i.length))}let ne=[[m[0][0],te[0],y,ee,_],[m[1][0],te[1],v,c,g]];for(let e=2;e<s;e++)ne.push([m[e][0],te[e],``,``,``]);return n?ne.push([m[s][0],te[s],``,``,``]):ne.push([0,``,``,``,``]),ne}function Iu(e,t,n,r){Ou(t,e),hu(n>=1,E(`Function [[FUNCTION_NAME]] A regression of order less than 1 cannot be possible.`));let i=[e],a=t.map(e=>S(0,n).map(t=>e**+(n-t)));r&&a.forEach(e=>e.push(1));let o=Lu(a,i);return r||o.push([0]),o}function Lu(e,t){let{inverted:n}=Su(wu(e,_a(e)));if(n===void 0)throw new A(E(`Matrix is not invertible`));return _a(wu(n,wu(e,t)))}function Ru(e,t,n){return e.reduce((e,r,i)=>e+r*t**+(n-i),0)}function zu(e){return e.map(e=>e.map(e=>Math.exp(e)))}function Bu(e){return e.map(e=>e.map(e=>Math.log(e)))}function Vu(e,t,n,r){let{_X:i,_newX:a}=Pu(t,e,n),o=Fu(i,e,r,!1),s=o.length-1,c=a.map(e=>{let t=0;for(let n=0;n<s;n++)t+=o[n][0]*e[s-n-1];return t+=o[s][0],[t]});return c.length===n.length?c:_a(c)}function Hu(e,t,n=2){let r=[];for(let e=0;e<n-1;e++)r.push({x:t[e],y:NaN});for(let i=0;i<=e.length-n;i++){let a=0;for(let t=i;t<i+n;t++)a+=e[t];r.push({x:t[i+n-1],y:a/n})}return r}let Uu=new g;function Wu(e){return Uu.get(e)}let Gu={normalizeFunctionValue(e){return M(e,D)},toValueAndFormat(e,t){return{value:M(e,D),format:`dd mmm yyyy`}},toFunctionValue(e){let t=F(e,D);return`DATE(${t.getFullYear()},${t.getMonth()+1},${t.getDate()})`}},Ku={normalizeFunctionValue(e){let t=M(e,D);if(t<1||t>31)throw new A(E(`%s is not a valid day of month (it should be a number between 1 and 31)`,t));return t},toValueAndFormat(e){return{value:M(e,D),format:`0`}},toFunctionValue(e){return`${e}`}},qu={normalizeFunctionValue(e){let t=M(e,D);if(t<1||t>7)throw new A(E(`%s is not a valid day of week (it should be a number between 1 and 7)`,t));return t},toValueAndFormat(e,t){return{value:co[(e-1+(t||D).weekStart)%7].toString(),format:`@`}},toFunctionValue(e){return`${e}`}},Ju={normalizeFunctionValue(e){let t=M(e,D);if(t<0||t>53)throw new A(E(`%s is not a valid week (it should be a number between 0 and 53)`,t));return t},toValueAndFormat(e){return{value:M(e,D),format:`0`}},toFunctionValue(e){return`${e}`}},Yu={normalizeFunctionValue(e){let t=M(e,D);if(t<1||t>12)throw new A(E(`%s is not a valid month (it should be a number between 1 and 12)`,t));return t},toValueAndFormat(e){return{value:so[M(e,D)-1].toString(),format:`@`}},toFunctionValue(e){return`${e}`}},Xu={normalizeFunctionValue(e){return L(M(e,D),{locale:D,format:`mm/yyyy`})},toValueAndFormat(e){return{value:M(e,D),format:`mmmm yyyy`}},toFunctionValue(e){let t=F(e,D);return`DATE(${t.getFullYear()},${t.getMonth()+1},1)`}},Zu={normalizeFunctionValue(e){let t=M(e,D);if(t<1||t>4)throw new A(E(`%s is not a valid quarter (it should be a number between 1 and 4)`,t));return t},toValueAndFormat(e){return{value:E(`Q%(quarter_number)s`,{quarter_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},Qu={normalizeFunctionValue(e){let t=M(e,D);return t>3e3?F(t,D).getFullYear():t},toValueAndFormat(e){return{value:M(e,D),format:`0`}},toFunctionValue(e){return`${e}`}},$u={normalizeFunctionValue(e){let t=M(e,D);if(t<0||t>23)throw new A(E(`%s is not a valid hour (it should be a number between 0 and 23)`,t));return t},toValueAndFormat(e){return{value:E(`%(hour_number)sh`,{hour_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},ed={normalizeFunctionValue(e){let t=M(e,D);if(t<0||t>59)throw new A(E(`%s is not a valid minute (it should be a number between 0 and 59)`,t));return t},toValueAndFormat(e){return{value:E(`%(minute_number)s'`,{minute_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},td={normalizeFunctionValue(e){let t=M(e,D);if(t<0||t>59)throw new A(E(`%s is not a valid second (it should be a number between 0 and 59)`,t));return t},toValueAndFormat(e){return{value:E(`%(second_number)s''`,{second_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}};function nd(e){return{normalizeFunctionValue(t){return t===null?null:e.normalizeFunctionValue(t)},toValueAndFormat(t,n){return t===null?{value:E(`(Undefined)`)}:e.toValueAndFormat(t,n)},toFunctionValue(t){return t===null?`false`:e.toFunctionValue(t)}}}Uu.add(`day`,nd(Gu)).add(`year`,nd(Qu)).add(`day_of_month`,nd(Ku)).add(`iso_week_number`,nd(Ju)).add(`month_number`,nd(Yu)).add(`month`,nd(Xu)).add(`quarter_number`,nd(Zu)).add(`day_of_week`,nd(qu)).add(`hour_number`,nd($u)).add(`minute_number`,nd(ed)).add(`second_number`,nd(td));let rd={count:E(`Count`),count_distinct:E(`Count Distinct`),bool_and:E(`Boolean And`),bool_or:E(`Boolean Or`),max:E(`Maximum`),min:E(`Minimum`),avg:E(`Average`),sum:E(`Sum`)},id=[`max`,`min`,`avg`,`sum`,`count_distinct`,`count`],ad={integer:id,char:id,datetime:id,boolean:[`count_distinct`,`count`,`bool_and`,`bool_or`]},od={};for(let e in ad){od[e]={};for(let t of ad[e])od[e][t]=rd[t]}let sd={count:e=>({value:ju([e]),format:`0`}),count_distinct:e=>({value:mu([e]),format:`0`}),bool_and:e=>({value:du([e]).result}),bool_or:e=>({value:fu([e]).result}),max:(e,t)=>Mu([e],t),min:(e,t)=>Nu([e],t),avg:(e,t)=>({value:ku([e],t),format:qi(e)}),sum:(e,t)=>({value:pu([e],t),format:qi(e)})};function cd(e){let t=Object.keys(e);if(!t.length)return 0;let n=t.map(e=>parseInt(e,10));return Math.max(...n)}let ld={year:E(`Year`),quarter:E(`Quarter & Year`),month:E(`Month & Year`),week:E(`Week & Year`),day:E(`Day`),quarter_number:E(`Quarter`),month_number:E(`Month`),iso_week_number:E(`Week`),day_of_month:E(`Day of Month`),day_of_week:E(`Day of Week`),hour_number:E(`Hour`),minute_number:E(`Minute`),second_number:E(`Second`)},ud=[`date`,`datetime`];function dd(e){let[t,n]=e.split(`:`);return n?{fieldName:t,granularity:n}:{fieldName:t}}function fd(e){return ud.includes(e.type)}function pd(e,t,n){let r=[e];n&&r.push(`"${n}"`);for(let{field:e,value:n,type:i}of t){if(e===`measure`){r.push(`"measure"`,`"${n}"`);continue}let{granularity:t}=dd(e),a=vd(n,{type:i,granularity:t});r.push(`"${e}"`,a)}return r}function md(e,t){let n=0,r=0,i=t.columns.map(e=>e.nameWithGranularity),a=t.rows.map(e=>e.nameWithGranularity);for(;e[n]!==void 0&&e[n]===a[r];)n++,r++;for(r=0;e[n]!==void 0&&e[n]===i[r];)n++,r++;return e.length===n}function hd(e,t){switch(t.type){case`HEADER`:return`=PIVOT.HEADER(${pd(e,t.domain).join(`,`)})`;case`VALUE`:return`=PIVOT.VALUE(${pd(e,t.domain,t.measure).join(`,`)})`;case`MEASURE_HEADER`:return`=PIVOT.HEADER(${pd(e,[...t.domain,{field:`measure`,value:t.measure,type:`char`}]).join(`,`)})`}return``}function gd(e,t){if(t===null||t===`null`)return null;let n=typeof t==`object`?t.value:t;if(j(n))return n;let r=typeof t==`boolean`?N(t).toLocaleLowerCase():N(t);if(r===`null`)return null;if(!bd.contains(e.type))throw new A(E(`Field %(field)s is not supported because of its type (%(type)s)`,{field:e.displayName,type:e.type}));return r.toLowerCase()===`false`?!1:bd.get(e.type)(r,e.granularity)}function _d(e,t){return Wu(t??`month`).normalizeFunctionValue(e)}function vd(e,t){return e===null?`"null"`:xd.contains(t.type)?xd.get(t.type)(e,t.granularity):`"${e}"`}function yd(e,t){return Wu(t??`month`).toFunctionValue(e)}let bd=new g;bd.add(`date`,_d).add(`datetime`,_d).add(`integer`,e=>M(e,D)).add(`boolean`,e=>P(e)).add(`char`,e=>N(e));let xd=new g;xd.add(`date`,yd).add(`datetime`,yd).add(`integer`,e=>`${M(e,D)}`).add(`boolean`,e=>P(e)?`TRUE`:`FALSE`).add(`char`,e=>`"${N(e).replace(/"/g,`\\"`)}"`);function Sd(e){return e.displayName+(e.granularity?` (${ld[e.granularity]})`:``)}function Cd(e,t){return e.length===0?t:{...t,format:(t.format||`@`)+`* `}}function wd(e,t){try{if(!t.getMeasure(e.measure))return!1;let n=t.definition.columns;for(let r=0;r<e.domain.length;r++){if(n[r].nameWithGranularity!==e.domain[r].field)return!1;let i=t.getPossibleFieldValues(n[r]).map(e=>e.value);if(!i.includes(e.domain[r].value)&&!(e.domain[r].value===null&&i.includes(``)))return!1}return!0}catch{return!1}}var Td=class extends Dl{isCutAllowed(e){return e.zones.length===1?`Success`:`WrongCutSelection`}copy(e,t,n=`copyPaste`){let r=e.sheetId,{clippedZones:i,rowsIndexes:a,columnsIndexes:o}=e,s=[],c=a.length===1&&o.length===1;for(let t of a){let i=[];for(let s of o){let l={col:s,row:t,sheetId:r},u=this.getters.getCell(l),d=this.getters.getEvaluatedCell(l),f=this.getters.getPivotIdFromPosition(l),p=this.getters.getArrayFormulaSpreadingOn(l);if(n!==`shiftCells`&&f&&p){let t=this.getters.getSpreadZone(p);if((!w(p,l)||!c)&&t&&!e.zones.some(e=>As(t,e))){let e=this.getters.getPivotCellFromPosition(l),t=hd(this.getters.getPivotFormulaId(f),e);u={id:u?.id||``,style:u?.style,format:u?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if(n!==`shiftCells`&&p&&!w(p,l)){let e=a.includes(p.row)&&o.includes(p.col)?``:L(d.value,{locale:this.getters.getLocale()});u={id:u?.id||``,style:u?.style,format:d.format,content:e,isFormula:!1,parsedValue:d.value}}i.push({content:u?.content??``,style:u?.style,format:u?.format,tokens:u?.isFormula?u.compiledFormula.tokens.map(({value:e,type:t})=>({value:e,type:t})):[],border:this.getters.getCellBorder(l)||void 0,evaluatedCell:d,position:l})}s.push(i)}return{cells:s,zones:i,sheetId:e.sheetId}}isPasteAllowed(e,t,n,r){if(!n.cells)return`Success`;if(r?.isCutOperation&&r?.pasteOption!==void 0)return`WrongPasteOption`;if(t.length>1&&(n.cells.length>1||n.cells[0].length>1))return`WrongPasteSelection`;let i=n.cells.length,a=n.cells[0].length;for(let r of bl(t,n.cells))if(this.getters.doesIntersectMerge(e,r)&&(t.length>1||!this.getters.isSingleCellOrMerge(e,t[0])||i*a!==1))return`WillRemoveExistingMerge`;return`Success`}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.cells,n)}getPasteTarget(e,t,n,r){let i=n.cells[0].length,a=n.cells.length;return r?.isCutOperation?{sheetId:e,zones:[{left:t[0].left,top:t[0].top,right:t[0].left+i-1,bottom:t[0].top+a-1}]}:i===1&&a===1?{zones:[],sheetId:e}:{sheetId:e,zones:bl(t,n.cells)}}pasteFromCut(e,t,n,r){this.clearClippedZones(n);let i=t[0];this.pasteZone(e,i.left,i.top,n.cells,r)}clearClippedZones(e){this.dispatch(`CLEAR_CELLS`,{sheetId:e.sheetId,target:e.zones}),this.dispatch(`CLEAR_FORMATTING`,{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){if(!s)continue;let o={col:t+r,row:n+a,sheetId:e};this.pasteCell(s,o,i)}}pasteCell(e,t,n){let{sheetId:r,col:i,row:a}=t,o=this.getters.getEvaluatedCell(t),s=e?.format||e.evaluatedCell.format;if(n?.pasteOption===`asValue`){this.dispatch(`UPDATE_CELL`,{...t,content:e.evaluatedCell.value?.toString()||``});return}if(n?.pasteOption===`onlyFormat`){this.dispatch(`UPDATE_CELL`,{...t,style:e?.style??null,format:s??o.format});return}let c=e?.content;e?.tokens&&e.tokens.length>0&&!n?.isCutOperation?c=this.getters.getTranslatedCellFormula(r,i-e.position.col,a-e.position.row,e.tokens):e?.tokens&&e.tokens.length>0&&(c=this.getters.getFormulaMovedInSheet(e.position.sheetId,r,e.tokens)),c!==``||e?.format||e?.style?this.dispatch(`UPDATE_CELL`,{...t,content:c,style:e?.style||null,format:e?.format}):o&&this.dispatch(`CLEAR_CELL`,t)}convertTextToClipboardData(e){let t=this.getters.getLocale(),n={cells:[]},r=[],i=0;for(let[t,n]of e.replace(/\r/g,``).split(`
|
|
9
|
-
`).entries())r.push(n.split(` `)),r[t].length>i&&(i=r[t].length);for(let e of r){let r=[];for(let n=0;n<i;n++){let i=Zl(e[n]||``,t);r.push({content:i,evaluatedCell:{formattedValue:i}})}n.cells.push(r)}return n}},Ed=class extends El{copy(e){}},Dd=class extends Ed{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`chart`)return;let r={...n},i=this.getters.getChart(e.figureId);if(!i)throw Error(`No chart for the given id: ${e.figureId}`);let a=i.copyInSheetId(t);return{figureId:e.figureId,copiedFigure:r,copiedChart:a}}getPasteTarget(e,t,n,r){return{zones:[],figureId:new gl().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=t.copiedChart.copyInSheetId(a),l=this.getters.getMaxAnchorOffset(a,s,o),{left:u,top:d}=r[0],f={x:0,y:0};u>l.col&&(u=l.col,f.x=l.offset.x),d>l.row&&(d=l.row,f.y=l.offset.y),this.dispatch(`CREATE_CHART`,{figureId:i,sheetId:a,definition:c.getDefinition(),col:u,row:d,offset:f,size:{height:s,width:o}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedChart.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},Od=class extends Dl{uuidGenerator=new gl;queuedChanges={};copy(e){if(!e.zones.length)return;let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n=Array.from(this.getters.getRulesByCell(r,i,e));t.push({position:{col:i,row:e,sheetId:r},rules:n})}i.push(t)}return{cfRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption===`asValue`)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.cfRules,n),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.cfRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteCf(s,o,i?.isCutOperation)}}pasteCf(e,t,n){if(e?.rules&&e.rules.length>0){let r=z(e.position),i=z(t);for(let a of e.rules){let o=[];if(n&&o.push(r),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,a,[i],o);else{this.adaptCFRules(e.position.sheetId,a,[],o);let n=this.getCFToCopyTo(t.sheetId,a);this.adaptCFRules(t.sheetId,n,[i],[])}}}}adaptCFRules(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,cf:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,cf:r}of this.queuedChanges[e]){let i=this.getters.getAdaptedCfRanges(e,r,t,n);if(i){if(i.length===0){this.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{id:r.id,sheetId:e});continue}this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:r.id,rule:r.rule,stopIfTrue:r.stopIfTrue},ranges:i,sheetId:e})}}}getCFToCopyTo(e,t){let n=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&w(e.rule,t.rule)),r=this.queuedChanges[e];return!n&&r&&(n=r.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&w(e.cf.rule,t.rule))?.cf),n||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}},kd=class extends Dl{uuidGenerator=new gl;queuedChanges={};copy(e){let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n={sheetId:r,col:i,row:e},a=this.getters.getValidationRuleForCell(n);t.push({position:n,rule:a})}i.push(t)}return{dvRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.dvRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteDataValidation(s,o,i?.isCutOperation)}}pasteDataValidation(e,t,n){if(e){let r=z(t),i=z(e.position),a=e.rule;if(!a){let e=this.getters.getValidationRuleForCell(t);e&&this.adaptDataValidationRule(t.sheetId,e,[],[r]);return}let o=[];if(n&&o.push(i),e.position.sheetId===t.sheetId){let n=this.getDataValidationRuleToCopyTo(t.sheetId,a,!1);this.adaptDataValidationRule(e.position.sheetId,n,[r],o)}else{let n=this.getters.getValidationRuleForCell(e.position);n&&this.adaptDataValidationRule(e.position.sheetId,n,[],o);let i=this.getDataValidationRuleToCopyTo(t.sheetId,a);this.adaptDataValidationRule(t.sheetId,i,[r],[])}}}getDataValidationRuleToCopyTo(e,t,n=!0){let r=this.getters.getDataValidationRules(e).find(e=>w(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking),i=this.queuedChanges[e];return!r&&i&&(r=i.find(e=>w(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),r||{...t,id:n?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,rule:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,rule:r}of this.queuedChanges[e]){let i=R([...R(r.ranges.map(e=>e.zone),n),...t],[]);if(i.length===0){this.dispatch(`REMOVE_DATA_VALIDATION_RULE`,{sheetId:e,id:r.id});continue}this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:{id:r.id,criterion:r.criterion,isBlocking:r.isBlocking},ranges:i.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}},Ad=class extends Ed{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);let r={...n};if(n.tag!==`image`)return;let i=b(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:r,copiedImage:i,sheetId:t}}getPasteTarget(e,t,n,r){return{sheetId:e,zones:[],figureId:new gl().smallUuid()}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=this.getters.getActiveSheetId(),{width:o,height:s}=t.copiedFigure,c=b(t.copiedImage),l=this.getters.getMaxAnchorOffset(a,s,o),{left:u,top:d}=r[0],f={x:0,y:0};u>l.col&&(u=l.col,f.x=l.offset.x),d>l.row&&(d=l.row,f.y=l.offset.y),this.dispatch(`CREATE_IMAGE`,{figureId:i,sheetId:a,col:u,row:d,offset:f,size:{height:s,width:o},definition:c}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},jd=class extends Dl{copy(e){let t=this.getters.getActiveSheetId(),{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getMerge(r))}i.push(n)}return{merges:i,sheetId:t}}paste(e,t,n){if(n.isCutOperation){let e=t.merges.flat().filter(C);this.dispatch(`REMOVE_MERGE`,{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,n)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteMerge(o,a)}}pasteMerge(e,t){if(!e||this.getters.isInMerge(t))return;let{sheetId:n,col:r,row:i}=t;this.dispatch(`ADD_MERGE`,{sheetId:n,force:!0,target:[{left:r,top:i,right:r+e.right-e.left,bottom:i+e.bottom-e.top}]})}},Md=class extends Dl{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,n){if(n.isCutOperation){let n=e.zones[0];this.dispatch(`MOVE_RANGES`,{target:t.zones,sheetId:t.sheetId,sheetName:this.getters.getSheetName(t.sheetId),targetSheetId:e.sheetId,col:n.left,row:n.top})}}},Nd=class extends Dl{isPasteAllowed(e,t,n,r){if(!(`cells`in n))return`Success`;let{xSplit:i,ySplit:a}=this.getters.getPaneDivisions(e);return Ks(bl(t,n.cells),i,a)?`FrozenPaneOverlap`:`Success`}},Pd=class extends Dl{copy(e,t,n=`copyPaste`){let r=e.sheetId,{rowsIndexes:i,columnsIndexes:a,zones:o}=e,s=new Set,c=[];for(let e of i){let l=[];c.push(l);for(let c of a){let a={col:c,row:e,sheetId:r},u=this.getters.getTable(a);if(!u){l.push({});continue}let d=this.getters.getCoreTable(a),f=d?.range.zone,p;if(!s.has(u.id)&&d&&f&&o.some(e=>As(f,e))){s.add(u.id);let{numberOfRows:e}=js(f);for(let n=f.top;n<=f.bottom;n++)!t&&!i.includes(n)&&e--;let n=d.range,r=this.getters.extendRange(d.range,`ROW`,n.zone.top+e-1-n.zone.bottom);p={range:this.getters.getRangeData(r),config:d.config,type:d.type}}n!==`shiftCells`&&l.push({table:p,style:this.getTableStyleToCopy(a),isWholeTableCopied:s.has(u.id)})}}return{tableCells:c,sheetId:e.sheetId}}getTableStyleToCopy(e){let t=this.getters.getCellTableStyle(e),n=this.getters.getCellStyle(e),r=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Pt(n)},border:{...r,...Pt(i)}}}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.tableCells,n)}pasteFromCut(e,t,n,r){for(let e of n.tableCells)for(let t of e)t.table&&this.dispatch(`REMOVE_TABLE`,{sheetId:n.sheetId,target:[this.getters.getRangeFromRangeData(t.table.range).zone]});let i=t[0];this.pasteZone(e,i.left,i.top,n.tableCells,r)}pasteZone(e,t,n,r,i){for(let a=0;a<r.length;a++){let o=r[a];for(let r=0;r<o.length;r++){let s=o[r];if(!s)continue;let c={col:t+r,row:n+a,sheetId:e};this.pasteTableCell(e,s,c,i)}}if(r.length===1)for(let i=0;i<r[0].length;i++)this.dispatch(`AUTOFILL_TABLE_COLUMN`,{col:t+i,row:n,sheetId:e})}pasteTableCell(e,t,n,r){if(t.table&&!r?.pasteOption){let{range:r}=t.table,i=js(this.getters.getRangeFromRangeData(r).zone),a={left:n.col,top:n.row,right:n.col+i.numberOfCols-1,bottom:n.row+i.numberOfRows-1};this.dispatch(`CREATE_TABLE`,{sheetId:n.sheetId,ranges:[this.getters.getRangeDataFromZone(e,a)],config:t.table.config,tableType:t.table.type})}this.getters.getCoreTable(n)||r?.pasteOption===`asValue`||(!r?.pasteOption&&!t.isWholeTableCopied||r?.pasteOption===`onlyFormat`)&&(t.style?.style&&this.dispatch(`UPDATE_CELL`,{...n,style:t.style.style}),t.style?.border&&this.dispatch(`SET_BORDER`,{...n,border:t.style.border}))}};let Fd={figureHandlers:new g,cellHandlers:new g};Fd.figureHandlers.add(`chart`,Dd).add(`image`,Ad),Fd.cellHandlers.add(`dataValidation`,kd).add(`cell`,Td).add(`sheet`,Nd).add(`merge`,jd).add(`border`,Ol).add(`table`,Pd).add(`conditionalFormat`,Od).add(`references`,Md);function Id(e,t){return t.type===`REMOVE_COLUMNS_ROWS`?Ss(e,t.dimension===`COL`?`left`:`top`,t.elements):t.type===`ADD_COLUMNS_ROWS`?ys(e,t.dimension===`COL`?`left`:`top`,t.base,t.position,t.quantity):e}function Ld(e,t){let n=t.type===`DELETE_SHEET`&&t.sheetId;if(`sheetId`in t&&e._sheetId!==t.sheetId)return e;{let r=Id(e._zone,t);if(r&&n!==e._sheetId)return{...e,_zone:r}}}var Rd=class{subscriptions={};on(e,t,n){if(!n)throw Error(`Missing callback`);this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:n})}trigger(e,t){let n=this.subscriptions[e]||[];for(let e=0,r=n.length;e<r;e++){let r=n[e];r.callback.call(r.owner,t)}}off(e,t){let n=this.subscriptions[e];n&&(this.subscriptions[e]=n.filter(e=>e.owner!==t))}clear(){this.subscriptions={}}},zd=class extends Rd{dependencies=new Map;factory=new Bd(this.get.bind(this));inject(e,t){if(this.dependencies.has(e)&&this.dependencies.get(e)!==t)throw Error(`Store ${e.name} already has an instance`);this.dependencies.set(e,t)}get(e){return this.dependencies.has(e)||this.dependencies.set(e,this.instantiate(e)),this.dependencies.get(e)}instantiate(e,...t){return this.factory.build(e,...t)}resetStores(){this.dependencies.clear()}dispose(){for(let e of this.dependencies.values())`dispose`in e&&typeof e.dispose==`function`&&e.dispose()}},Bd=class{pendingBuilds=new Set;constructor(e){this.get=e}build(e,...t){if(this.pendingBuilds.has(e))throw Error(`Circular dependency detected: ${[...this.pendingBuilds,e].map(e=>e.name).join(` -> `)}`);this.pendingBuilds.add(e);let n=new e(this.get,...t);return this.pendingBuilds.delete(e),n}};function Vd(e){class t{constructor(t){throw Error(`This is a abstract store for ${e}, it cannot be instantiated.
|
|
9
|
+
`).entries())r.push(n.split(` `)),r[t].length>i&&(i=r[t].length);for(let e of r){let r=[];for(let n=0;n<i;n++){let i=Zl(e[n]||``,t);r.push({content:i,evaluatedCell:{formattedValue:i}})}n.cells.push(r)}return n}},Ed=class extends El{copy(e){}},Dd=class extends Ed{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`chart`)return;let r={...n},i=this.getters.getChart(e.figureId);if(!i)throw Error(`No chart for the given id: ${e.figureId}`);let a=i.copyInSheetId(t);return{figureId:e.figureId,copiedFigure:r,copiedChart:a}}getPasteTarget(e,t,n,r){return{zones:[],figureId:new gl().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=t.copiedChart.copyInSheetId(a),l=this.getters.getMaxAnchorOffset(a,s,o),{left:u,top:d}=r[0],f={x:0,y:0};u>l.col&&(u=l.col,f.x=l.offset.x),d>l.row&&(d=l.row,f.y=l.offset.y),this.dispatch(`CREATE_CHART`,{figureId:i,sheetId:a,definition:c.getDefinition(),col:u,row:d,offset:f,size:{height:s,width:o}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedChart.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},Od=class extends Dl{uuidGenerator=new gl;queuedChanges={};copy(e){if(!e.zones.length)return;let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n=Array.from(this.getters.getRulesByCell(r,i,e));t.push({position:{col:i,row:e,sheetId:r},rules:n})}i.push(t)}return{cfRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption===`asValue`)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.cfRules,n),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.cfRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteCf(s,o,i?.isCutOperation)}}pasteCf(e,t,n){if(e?.rules&&e.rules.length>0){let r=z(e.position),i=z(t);for(let a of e.rules){let o=[];if(n&&o.push(r),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,a,[i],o);else{this.adaptCFRules(e.position.sheetId,a,[],o);let n=this.getCFToCopyTo(t.sheetId,a);this.adaptCFRules(t.sheetId,n,[i],[])}}}}adaptCFRules(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,cf:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,cf:r}of this.queuedChanges[e]){let i=this.getters.getAdaptedCfRanges(e,r,t,n);if(i){if(i.length===0){this.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{id:r.id,sheetId:e});continue}this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:r.id,rule:r.rule,stopIfTrue:r.stopIfTrue},ranges:i,sheetId:e})}}}getCFToCopyTo(e,t){let n=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&w(e.rule,t.rule)),r=this.queuedChanges[e];return!n&&r&&(n=r.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&w(e.cf.rule,t.rule))?.cf),n||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}},kd=class extends Dl{uuidGenerator=new gl;queuedChanges={};copy(e){let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n={sheetId:r,col:i,row:e},a=this.getters.getValidationRuleForCell(n);t.push({position:n,rule:a})}i.push(t)}return{dvRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.dvRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteDataValidation(s,o,i?.isCutOperation)}}pasteDataValidation(e,t,n){if(e){let r=z(t),i=z(e.position),a=e.rule;if(!a){let e=this.getters.getValidationRuleForCell(t);e&&this.adaptDataValidationRule(t.sheetId,e,[],[r]);return}let o=[];if(n&&o.push(i),e.position.sheetId===t.sheetId){let n=this.getDataValidationRuleToCopyTo(t.sheetId,a,!1);this.adaptDataValidationRule(e.position.sheetId,n,[r],o)}else{let n=this.getters.getValidationRuleForCell(e.position);n&&this.adaptDataValidationRule(e.position.sheetId,n,[],o);let i=this.getDataValidationRuleToCopyTo(t.sheetId,a);this.adaptDataValidationRule(t.sheetId,i,[r],[])}}}getDataValidationRuleToCopyTo(e,t,n=!0){let r=this.getters.getDataValidationRules(e).find(e=>w(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking),i=this.queuedChanges[e];return!r&&i&&(r=i.find(e=>w(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),r||{...t,id:n?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,rule:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,rule:r}of this.queuedChanges[e]){let i=R([...R(r.ranges.map(e=>e.zone),n),...t],[]);if(i.length===0){this.dispatch(`REMOVE_DATA_VALIDATION_RULE`,{sheetId:e,id:r.id});continue}this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:{id:r.id,criterion:r.criterion,isBlocking:r.isBlocking},ranges:i.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}},Ad=class extends Ed{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);let r={...n};if(n.tag!==`image`)return;let i=b(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:r,copiedImage:i,sheetId:t}}getPasteTarget(e,t,n,r){return{sheetId:e,zones:[],figureId:new gl().smallUuid()}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=this.getters.getActiveSheetId(),{width:o,height:s}=t.copiedFigure,c=b(t.copiedImage),l=this.getters.getMaxAnchorOffset(a,s,o),{left:u,top:d}=r[0],f={x:0,y:0};u>l.col&&(u=l.col,f.x=l.offset.x),d>l.row&&(d=l.row,f.y=l.offset.y),this.dispatch(`CREATE_IMAGE`,{figureId:i,sheetId:a,col:u,row:d,offset:f,size:{height:s,width:o},definition:c}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},jd=class extends Dl{copy(e){let t=this.getters.getActiveSheetId(),{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getMerge(r))}i.push(n)}return{merges:i,sheetId:t}}paste(e,t,n){if(n.isCutOperation){let e=t.merges.flat().filter(C);this.dispatch(`REMOVE_MERGE`,{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,n)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteMerge(o,a)}}pasteMerge(e,t){if(!e||this.getters.isInMerge(t))return;let{sheetId:n,col:r,row:i}=t;this.dispatch(`ADD_MERGE`,{sheetId:n,force:!0,target:[{left:r,top:i,right:r+e.right-e.left,bottom:i+e.bottom-e.top}]})}},Md=class extends Dl{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,n){if(n.isCutOperation){let n=e.zones[0];this.dispatch(`MOVE_RANGES`,{target:t.zones,sheetId:t.sheetId,sheetName:this.getters.getSheetName(t.sheetId),targetSheetId:e.sheetId,col:n.left,row:n.top})}}},Nd=class extends Dl{isPasteAllowed(e,t,n,r){if(!(`cells`in n))return`Success`;let{xSplit:i,ySplit:a}=this.getters.getPaneDivisions(e);return Ks(bl(t,n.cells),i,a)?`FrozenPaneOverlap`:`Success`}},Pd=class extends Dl{copy(e,t,n=`copyPaste`){let r=e.sheetId,{rowsIndexes:i,columnsIndexes:a,zones:o}=e,s=new Set,c=[];for(let e of i){let l=[];c.push(l);for(let c of a){let a={col:c,row:e,sheetId:r},u=this.getters.getTable(a);if(!u){l.push({});continue}let d=this.getters.getCoreTable(a),f=d?.range.zone,p;if(!s.has(u.id)&&d&&f&&o.some(e=>As(f,e))){s.add(u.id);let{numberOfRows:e}=js(f);for(let n=f.top;n<=f.bottom;n++)!t&&!i.includes(n)&&e--;let n=d.range,r=this.getters.extendRange(d.range,`ROW`,n.zone.top+e-1-n.zone.bottom);p={range:this.getters.getRangeData(r),config:d.config,type:d.type}}n!==`shiftCells`&&l.push({table:p,style:this.getTableStyleToCopy(a),isWholeTableCopied:s.has(u.id)})}}return{tableCells:c,sheetId:e.sheetId}}getTableStyleToCopy(e){let t=this.getters.getCellTableStyle(e),n=this.getters.getCellStyle(e),r=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Pt(n)},border:{...r,...Pt(i)}}}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.tableCells,n)}pasteFromCut(e,t,n,r){for(let e of n.tableCells)for(let t of e)t.table&&this.dispatch(`REMOVE_TABLE`,{sheetId:n.sheetId,target:[this.getters.getRangeFromRangeData(t.table.range).zone]});let i=t[0];this.pasteZone(e,i.left,i.top,n.tableCells,r)}pasteZone(e,t,n,r,i){for(let a=0;a<r.length;a++){let o=r[a];for(let r=0;r<o.length;r++){let s=o[r];if(!s)continue;let c={col:t+r,row:n+a,sheetId:e};this.pasteTableCell(e,s,c,i)}}if(r.length===1)for(let i=0;i<r[0].length;i++)this.dispatch(`AUTOFILL_TABLE_COLUMN`,{col:t+i,row:n,sheetId:e})}pasteTableCell(e,t,n,r){if(t.table&&!r?.pasteOption){let{range:r}=t.table,i=js(this.getters.getRangeFromRangeData(r).zone),a={left:n.col,top:n.row,right:n.col+i.numberOfCols-1,bottom:n.row+i.numberOfRows-1};this.dispatch(`CREATE_TABLE`,{sheetId:n.sheetId,ranges:[this.getters.getRangeDataFromZone(e,a)],config:t.table.config,tableType:t.table.type})}this.getters.getCoreTable(n)||r?.pasteOption===`asValue`||(!r?.pasteOption&&!t.isWholeTableCopied||r?.pasteOption===`onlyFormat`)&&(t.style?.style&&this.dispatch(`UPDATE_CELL`,{...n,style:t.style.style}),t.style?.border&&this.dispatch(`SET_BORDER`,{...n,border:t.style.border}))}};let Fd={figureHandlers:new g,cellHandlers:new g};Fd.figureHandlers.add(`chart`,Dd).add(`image`,Ad),Fd.cellHandlers.add(`dataValidation`,kd).add(`cell`,Td).add(`sheet`,Nd).add(`merge`,jd).add(`border`,Ol).add(`table`,Pd).add(`conditionalFormat`,Od).add(`references`,Md);function Id(e,t){return t.type===`REMOVE_COLUMNS_ROWS`?Ss(e,t.dimension===`COL`?`left`:`top`,t.elements):t.type===`ADD_COLUMNS_ROWS`?ys(e,t.dimension===`COL`?`left`:`top`,t.base,t.position,t.quantity):e}function Ld(e,t){let n=t.type===`DELETE_SHEET`&&t.sheetId;if(`sheetId`in t&&e._sheetId!==t.sheetId)return e;{let r=Id(e._zone,t);if(r&&n!==e._sheetId)return{...e,_zone:r}}}var Rd=class{subscriptions={};on(e,t,n){if(!n)throw Error(`Missing callback`);this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:n})}trigger(e,t){let n=this.subscriptions[e]||[];for(let e=0,r=n.length;e<r;e++){let r=n[e];r.callback.call(r.owner,t)}}off(e,t){let n=this.subscriptions[e];n&&(this.subscriptions[e]=n.filter(e=>e.owner!==t))}clear(){this.subscriptions={}}},zd=class extends Rd{dependencies=new Map;factory=new Bd(this.get.bind(this));inject(e,t){if(this.dependencies.has(e)&&this.dependencies.get(e)!==t)throw Error(`Store ${e.name} already has an instance`);this.dependencies.set(e,t)}get(e){return this.dependencies.has(e)||this.dependencies.set(e,this.instantiate(e)),this.dependencies.get(e)}instantiate(e,...t){return this.factory.build(e,...t)}resetStores(){this.dependencies.clear()}dispose(){for(let e of this.dependencies.values())`dispose`in e&&typeof e.dispose==`function`&&e.dispose()}},Bd=class{get;pendingBuilds=new Set;constructor(e){this.get=e}build(e,...t){if(this.pendingBuilds.has(e))throw Error(`Circular dependency detected: ${[...this.pendingBuilds,e].map(e=>e.name).join(` -> `)}`);this.pendingBuilds.add(e);let n=new e(this.get,...t);return this.pendingBuilds.delete(e),n}};function Vd(e){class t{constructor(t){throw Error(`This is a abstract store for ${e}, it cannot be instantiated.
|
|
10
10
|
Did you forget to inject your store instance?
|
|
11
11
|
|
|
12
12
|
const stores = useStoreProvider();
|
|
13
13
|
stores.inject(MyMetaStore, storeInstance);
|
|
14
|
-
`)}}return t}var Hd=class{disposeCallbacks=[];constructor(e){this.get=e}onDispose(e){this.disposeCallbacks.push(e)}dispose(){this.disposeCallbacks.forEach(e=>e())}};function Ud(){let e=(0,t.useEnv)();if(e.__spreadsheet_stores__ instanceof zd)return e.__spreadsheet_stores__;let n=new zd;return(0,t.useSubEnv)({__spreadsheet_stores__:n,getStore:e=>Kd(n.get(e),()=>n.trigger(`store-updated`))}),(0,t.onWillUnmount)(()=>n.dispose()),n}function B(e){let n=qd((0,t.useEnv)());return Gd(n,n.get(e))}function Wd(e,...n){let r=qd((0,t.useEnv)()),i=r.instantiate(e,...n);return(0,t.onWillUnmount)(()=>i.dispose()),Gd(r,i)}function Gd(e,n){let r=(0,t.useComponent)();return Kd(n,()=>{(0,t.status)(r)===`mounted`&&e.trigger(`store-updated`)})}function Kd(e,t){return new Proxy(e,{get(n,r,i){let a=n,o=Reflect.get(n,r,a);return e.mutators?.includes(r)?new Proxy(o,{apply(e,n,r){Reflect.apply(e,a,r)!==`noStateChange`&&t()}}):o}})}function qd(e){let t=e.__spreadsheet_stores__;if(!(t instanceof zd))throw Error(`No store provider found. Did you forget to call useStoreProvider()?`);return t}let Jd=Vd(`Model`);var Yd=class{mutators=[`register`,`unRegister`,`draw`,`startAnimation`,`stopAnimation`];renderers={};model;context=void 0;animationFrameId=null;registeredAnimations=new Set;constructor(e){this.model=e(Jd)}register(e){if(e.renderingLayers.length)for(let t of e.renderingLayers)this.renderers[t]||(this.renderers[t]=[]),this.renderers[t].push(e)}unRegister(e){for(let t of Object.keys(this.renderers))this.renderers[t]=this.renderers[t].filter(t=>t!==e)}drawLayer(e,t,n){let r=this.renderers[t];if(r)for(let i of r)e.ctx.save(),i.drawLayer(e,t,n),e.ctx.restore();return`noStateChange`}draw(e,t){if(e||=this.context,!e)throw Error(`Rendering context is not defined`);this.context=e;for(let n of Ar())this.model.drawLayer(e,n),this.drawLayer(e,n,t);return`noStateChange`}startAnimation(e){if(this.registeredAnimations.add(e),!this.animationFrameId){let e=t=>{this.animationFrameId=requestAnimationFrame(e),this.draw(void 0,t)};this.animationFrameId=requestAnimationFrame(e)}return`noStateChange`}stopAnimation(e){return this.registeredAnimations.delete(e),this.registeredAnimations.size===0&&this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),`noStateChange`}dispose(){this.animationFrameId&&=(cancelAnimationFrame(this.animationFrameId),null)}},Xd=class extends Hd{model=this.get(Jd);getters=this.model.getters;renderer=this.get(Yd);constructor(e){super(e),this.model.on(`command-dispatched`,this,this.handle),this.model.on(`command-finalized`,this,this.finalize),this.renderer.register(this),this.onDispose(()=>{this.model.off(`command-dispatched`,this),this.model.off(`command-finalized`,this),this.renderer.unRegister(this)})}get renderingLayers(){return[]}handle(e){}finalize(){}drawLayer(e,t,n){}};let Zd={id:`void-composer`,get editionMode(){return`inactive`},startEdition:()=>{throw Error(`No composer is registered`)},stopEdition:()=>{throw Error(`No composer is registered`)},setCurrentContent:()=>{throw Error(`No composer is registered`)}};var Qd=class extends Xd{mutators=[`focusComposer`,`focusActiveComposer`];activeComposer=Zd;_focusMode=`inactive`;get focusMode(){return this.activeComposer.editionMode===`inactive`?`inactive`:this._focusMode}focusComposer(e,t){if(this.activeComposer=e,this.getters.isReadonly())return`noStateChange`;this._focusMode=t.focusMode||`contentFocus`,this._focusMode!==`inactive`&&this.setComposerContent(t)}focusActiveComposer(e){if(this.getters.isReadonly())return`noStateChange`;if(!this.activeComposer)throw Error(`No composer is registered`);this._focusMode=e.focusMode||`contentFocus`,this._focusMode!==`inactive`&&this.setComposerContent(e)}setComposerContent({content:e,selection:t}){this.activeComposer.editionMode===`inactive`?this.activeComposer.startEdition(e,t):e&&this.activeComposer.setCurrentContent(e,t)}};let $d={},ef=0;function V(e,...t){let n=`__sheet__${ef++}`;return nf(n,String.raw(e,...t)),rf(n),n}function tf(e){let t=e.split(/(\{|\}|;)/).map(e=>e.trim()),n=[],r=[],i=[];function a(e,t){let r=[];for(let i of n[e]){let o=t&&t+` `+i||i;o.includes(`&`)&&(o=i.replace(/&/g,t||``)),e<n.length-1&&(o=a(e+1,o)),r.push(o)}return r.join(`, `)}function o(){i.length&&(r.push(a(0)+` {`),r.push(...i),r.push(`}`),i=[])}for(;t.length;){let e=t.shift();e===`}`?(o(),n.pop()):(t[0]===`{`&&(o(),n.push(e.split(/\s*,\s*/)),t.shift()),t[0]===`;`&&i.push(` `+e+`;`))}return r.join(`
|
|
15
|
-
`)}function nf(e,t){let n=document.createElement(`style`);n.textContent=tf(t),$d[e]=n}function rf(e){let t=$d[e];t.setAttribute(`component`,e),document.head.appendChild(t)}function af({strikethrough:e,underline:t}){return!e&&!t?`none`:`${e?`line-through`:``} ${t?`underline`:``}`}function of(e){let t=sf(e);return e&&e.fillColor&&(t.background=e.fillColor),t}function sf(e){let t={};if(!e)return t;if(e.bold&&(t[`font-weight`]=`bold`),e.italic&&(t[`font-style`]=`italic`),e.strikethrough||e.underline){let n=e.strikethrough?`line-through`:``;n=e.underline?n+` underline`:n,t[`text-decoration`]=n}return e.textColor&&(t.color=e.textColor),t}function H(e){let t=``;for(let n in e)e[n]&&(t+=`${n}:${e[n]}; `);return t}function cf(e){let t=window.getComputedStyle(e);return{top:parseInt(t.marginTop,10)||0,bottom:parseInt(t.marginBottom,10)||0,left:parseInt(t.marginLeft,10)||0,right:parseInt(t.marginRight,10)||0}}let lf=new g;function uf(){return!!window.Chart.registry.plugins.get(`chartShowValuesPlugin`)}function df(){if(!(!window.Chart||uf()))for(let e of lf.getAll())e.register(window.Chart)}function ff(){if(window.Chart)for(let e of lf.getAll())e.unregister(window.Chart)}var pf=class extends Xd{mutators=[`disableAnimationForChart`,`enableAnimationForChart`];animationPlayed={};disableAnimationForChart(e,t){return this.animationPlayed[e]=t,`noStateChange`}enableAnimationForChart(e){return this.animationPlayed[e]=void 0,`noStateChange`}};function mf(){return class extends window.Chart.BarController{static id=`funnel`;static defaults={...window.Chart?.BarController.defaults,dataElementType:`funnel`,animation:{duration:e=>e.type===`data`?1e3*(e.raw[1]/Math.max(...e.dataset.data.map(e=>e[1]))):1e3}};updateElements(e,t,n,r){super.updateElements(e,t,n,r);for(let i=t;i<t+n;i++){let t=e[i];this.updateElement(t,i,{nextElement:e[i+1]},r)}}}}function hf(){return class extends window.Chart.BarElement{static id=`funnel`;draw(e){e.save();let{x:t,y:n,height:r,nextElement:i,base:a,options:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=gf(this),c=(s-(i?gf(i):0))/2,l=Math.min(t,a),u=n-r/2;e.fillStyle=o.backgroundColor,e.beginPath(),e.moveTo(l,u),e.lineTo(l+s,u),e.lineTo(l+s-c,u+r),e.lineTo(l+c,u+r),e.closePath(),e.fill(),o.borderWidth&&(e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,e.stroke()),e.restore()}inRange(e,t){let{x:n,y:r,height:i,nextElement:a,base:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=gf(this),c=a?gf(a):0,l=Math.min(n,o),u=r-i/2;if(t<u||t>u+i)return!1;let d=(s-c)/2,f=l+d*(t-u)/i,p=l+s-d*(t-u)/i;return!(e<f||e>p)}}}function gf(e){let{x:t,base:n}=e.getProps([`x`,`base`]);return Math.max(t,n)-Math.min(t,n)}let _f=function(e){if(!e.length)return{x:0,y:0};let{x:t,y:n,base:r,width:i,height:a}=e[0].element.getProps([`x`,`y`,`width`,`height`,`base`]),o=Math.min(t,r),s=n-a/2;return{x:o+i*2/3,y:s+a/2}},vf=`000000`,yf={arrows:`3Arrows`,smiley:`3Symbols`,dots:`3TrafficLights1`},bf={styleSheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,sst:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,Relationships:`http://schemas.openxmlformats.org/package/2006/relationships`,Types:`http://schemas.openxmlformats.org/package/2006/content-types`,worksheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,workbook:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,drawing:`http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing`,table:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,revision:`http://schemas.microsoft.com/office/spreadsheetml/2014/revision`,revision3:`http://schemas.microsoft.com/office/spreadsheetml/2016/revision3`,markupCompatibility:`http://schemas.openxmlformats.org/markup-compatibility/2006`},xf=`http://schemas.openxmlformats.org/drawingml/2006/main`,Sf=`http://schemas.openxmlformats.org/drawingml/2006/chart`,Cf={workbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml`,macroEnabledWorkbook:`application/vnd.ms-excel.sheet.macroEnabled.main+xml`,templateWorkbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml`,macroEnabledTemplateWorkbook:`application/vnd.ms-excel.template.macroEnabled.main+xml`,excelAddInWorkbook:`application/vnd.ms-excel.addin.macroEnabled.main+xml`,sheet:`application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml`,metadata:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml`,sharedStrings:`application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml`,styles:`application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml`,drawing:`application/vnd.openxmlformats-officedocument.drawing+xml`,chart:`application/vnd.openxmlformats-officedocument.drawingml.chart+xml`,themes:`application/vnd.openxmlformats-officedocument.theme+xml`,table:`application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml`,pivot:`application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml`,externalLink:`application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml`},wf={document:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument`,sheet:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet`,metadata:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata`,sharedStrings:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings`,styles:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles`,drawing:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing`,chart:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart`,theme:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme`,table:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/table`,hyperlink:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink`,image:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/image`},Tf=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,Ef=.75,Df=.143,Of=8.43,kf=12.75,Af={FLOOR:[{type:`NUMBER`,value:1}],CEILING:[{type:`NUMBER`,value:1}],ROUND:[{type:`NUMBER`,value:0}],ROUNDUP:[{type:`NUMBER`,value:0}],ROUNDDOWN:[{type:`NUMBER`,value:0}]},jf=`ACOT,ACOTH,AGGREGATE,ARABIC,BASE,BETA.DIST,BETA.INV,BINOM.DIST,BINOM.DIST.RANGE,BINOM.INV,BITAND,BITLSHIFT,BITOR,BITRSHIFT,BITXOR,BYCOL,BYROW,CEILING.MATH,CEILING.PRECISE,CHISQ.DIST,CHISQ.DIST.RT,CHISQ.INV,CHISQ.INV.RT,CHISQ.TEST,CHOOSECOLS,CHOOSEROWS,COMBINA,CONCAT,CONFIDENCE.NORM,CONFIDENCE.T,COT,COTH,COVARIANCE.P,COVARIANCE.S,CSC,CSCH,DAYS,DECIMAL,DROP,ERF.PRECISE,ERFC.PRECISE,EXPAND,EXPON.DIST,F.DIST,F.DIST.RT,F.INV,F.INV.RT,F.TEST,FIELDVALUE,FILTERXML,FLOOR.MATH,FLOOR.PRECISE,FORECAST.ETS,FORECAST.ETS.CONFINT,FORECAST.ETS.SEASONALITY,FORECAST.ETS.STAT,FORECAST.LINEAR,FORMULATEXT,GAMMA,GAMMA.DIST,GAMMA.INV,GAMMALN.PRECISE,GAUSS,HSTACK,HYPGEOM.DIST,IFNA,IFS,IMCOSH,IMCOT,IMCSC,IMCSCH,IMSEC,IMSECH,IMSINH,IMTAN,ISFORMULA,ISOMITTED,ISOWEEKNUM,LAMBDA,LET,LOGNORM.DIST,LOGNORM.INV,MAKEARRAY,MAP,MAXIFS,MINIFS,MODE.MULT,MODE.SNGL,MUNIT,NEGBINOM.DIST,NORM.DIST,NORM.INV,NORM.S.DIST,NORM.S.INV,NUMBERVALUE,PDURATION,PERCENTILE.EXC,PERCENTILE.INC,PERCENTRANK.EXC,PERCENTRANK.INC,PERMUTATIONA,PHI,POISSON.DIST,PQSOURCE,PYTHON_STR,PYTHON_TYPE,PYTHON_TYPENAME,QUARTILE.EXC,QUARTILE.INC,QUERYSTRING,RANDARRAY,RANK.AVG,RANK.EQ,REDUCE,RRI,SCAN,SEC,SECH,SEQUENCE,SHEET,SHEETS,SKEW.P,SORTBY,STDEV.P,STDEV.S,SWITCH,T.DIST,T.DIST.2T,T.DIST.RT,T.INV,T.INV.2T,T.TEST,TAKE,TEXTAFTER,TEXTBEFORE,TEXTJOIN,TEXTSPLIT,TOCOL,TOROW,UNICHAR,UNICODE,UNIQUE,VAR.P,VAR.S,VSTACK,WEBSERVICE,WEIBULL.DIST,WRAPCOLS,WRAPROWS,XLOOKUP,XOR,Z.TEST`.split(`,`),Mf=/(.*?)\((.*?)\)(.*)/,Nf=[`ANY`,`BOOLEAN`,`DATE`,`NUMBER`,`STRING`,`RANGE`,`RANGE<BOOLEAN>`,`RANGE<DATE>`,`RANGE<NUMBER>`,`RANGE<STRING>`,`META`];function U(e,t=``){return Pf(e,t)}function Pf(e,t){let n=e.match(Mf),r=n[1].trim();if(!r)throw Error(`Function argument definition is missing a name: '${e}'.`);let i=[],a=!1,o=!1,s;for(let e of n[2].split(`,`)){let t=e.trim().toUpperCase(),n=Nf.find(e=>t===e);n?i.push(n):t===`RANGE<ANY>`?i.push(`RANGE`):t===`OPTIONAL`?a=!0:t===`REPEATING`?o=!0:t.startsWith(`DEFAULT=`)&&(s=e.trim().slice(8))}let c={name:r,description:t,type:i};return(i.includes(`ANY`)||i.includes(`RANGE`))&&(c.acceptErrors=!0),a&&(c.optional=!0),o&&(c.repeating=!0),s!==void 0&&(c.default=!0,c.defaultValue=s),i.some(e=>e.startsWith(`RANGE`))&&(c.acceptMatrix=!0),i.every(e=>e.startsWith(`RANGE`))&&(c.acceptMatrixOnly=!0),c}function Ff(e,t){let n=0,r=0,i=0,a=0;for(let e of t.args)n++,!e.optional&&!e.repeating&&!e.default&&r++,e.repeating&&i++,(e.optional||e.default)&&a++;let o=t;return o.minArgRequired=r,o.maxArgPossible=i?1/0:n,o.nbrArgRepeating=i,o.nbrArgOptional=a,o.hidden=t.hidden||!1,o.name=e,o}let If={};function Lf(e,t){let n=e.name;return If[n]?.[t]||(If[n]||(If[n]={}),If[n][t]||(If[n][t]=Rf(e,t)),If[n][t])}function Rf(e,t){let n={},r=e.nbrArgRepeating?Math.floor((t-e.minArgRequired)/e.nbrArgRepeating):0,i=e.nbrArgRepeating*r,a=t-e.minArgRequired-i,o=0,s=0;for(let t=0;t<e.args.length;t++){let i=e.args[t];if(i.optional||i.default){s<a&&(n[o]=t,o++),s++;continue}if(i.repeating){for(let i=0;i<r;i++)for(let r=0;r<e.nbrArgRepeating;r++)n[o]=t+r,o++;t+=e.nbrArgRepeating-1;continue}n[o]=t,o++}return e=>n[e]}function zf(e){if(e.nbrArgRepeating&&e.nbrArgOptional>=e.nbrArgRepeating)throw Error(`Function ${e.name} has more optional arguments than repeatable ones.`);let t=!1,n=!1;for(let r of e.args){if(r.type.includes(`META`)&&r.type.length>1)throw Error(`Function ${e.name} has an argument that has been declared with more than one type whose type 'META'. The 'META' type can only be declared alone.`);if(r.repeating){if(!n&&t)throw Error(`Function ${e.name} has non-consecutive repeating arguments. All repeating arguments must be declared consecutively.`);t=!0,n=!0}else n=!1}}var Bf=l({ARRAY_CONSTRAIN:()=>Vf,CHOOSECOLS:()=>Hf,CHOOSEROWS:()=>Uf,EXPAND:()=>Wf,FLATTEN:()=>Gf,FREQUENCY:()=>Kf,HSTACK:()=>qf,MDETERM:()=>Jf,MINVERSE:()=>Yf,MMULT:()=>Xf,SUMPRODUCT:()=>Zf,SUMX2MY2:()=>$f,SUMX2PY2:()=>ep,SUMXMY2:()=>tp,TOCOL:()=>ip,TOROW:()=>ap,TRANSPOSE:()=>op,VSTACK:()=>sp,WRAPCOLS:()=>cp,WRAPROWS:()=>lp});let Vf={description:E(`Returns a result array constrained to a specific width and height.`),args:[U(`input_range (any, range<any>)`,E(`The range to constrain.`)),U(`rows (number)`,E(`The number of rows in the constrained array.`)),U(`columns (number)`,E(`The number of columns in the constrained array.`))],compute:function(e,t,n){let r=I(e),i=ta(t?.value,this.locale),a=ta(n?.value,this.locale);if(i<=0)return new A(E(`The rows argument (%s) must be strictly positive.`,i.toString()));if(a<=0)return new A(E(`The columns argument (%s) must be strictly positive.`,a.toString()));let o=Math.min(i,r[0].length);return ma(Math.min(a,r.length),o,(e,t)=>r[e][t])},isExported:!1},Hf={description:E(`Creates a new array from the selected columns in the existing range.`),args:[U(`array (any, range<any>)`,E(`The array that contains the columns to be returned.`)),U(`col_num (number, range<number>)`,E(`The first column index of the columns to be returned.`)),U(`col_num2 (number, range<number>, repeating)`,E(`The columns indexes of the columns to be returned.`))],compute:function(e,...t){let n=I(e),r=Aa(t,e=>ta(e?.value,this.locale)),i=r.filter(e=>e===0||n.length<Math.abs(e));if(i.length!==0)return new A(E(`The columns arguments must be between -%s and %s (got %s), excluding 0.`,n.length.toString(),n.length.toString(),i.join(`,`)));let a=Array(r.length);for(let e=0;e<r.length;e++)r[e]>0?a[e]=n[r[e]-1]:a[e]=n[n.length+r[e]];return a},isExported:!0},Uf={description:E(`Creates a new array from the selected rows in the existing range.`),args:[U(`array (any, range<any>)`,E(`The array that contains the rows to be returned.`)),U(`row_num (number, range<number>)`,E(`The first row index of the rows to be returned.`)),U(`row_num2 (number, range<number>, repeating)`,E(`The rows indexes of the rows to be returned.`))],compute:function(e,...t){let n=I(e),r=Aa(t,e=>ta(e?.value,this.locale)),i=n.length,a=r.filter(e=>e===0||n[0].length<Math.abs(e));return a.length===0?ma(i,r.length,(e,t)=>r[t]>0?n[e][r[t]-1]:n[e][n[e].length+r[t]]):new A(E(`The rows arguments must be between -%s and %s (got %s), excluding 0.`,n[0].length.toString(),n[0].length.toString(),a.join(`,`)))},isExported:!0},Wf={description:E(`Expands or pads an array to specified row and column dimensions.`),args:[U(`array (any, range<any>)`,E(`The array to expand.`)),U(`rows (number)`,E(`The number of rows in the expanded array. If missing, rows will not be expanded.`)),U(`columns (number, optional)`,E(`The number of columns in the expanded array. If missing, columns will not be expanded.`)),U(`pad_with (any, default=0)`,E(`The value with which to pad.`))],compute:function(e,t,n,r={value:0}){let i=I(e),a=ta(t?.value,this.locale),o=n===void 0?i.length:ta(n.value,this.locale);return a<i[0].length?new A(E(`The rows arguments (%s) must be greater or equal than the number of rows of the array.`,a.toString())):o<i.length?new A(E(`The columns arguments (%s) must be greater or equal than the number of columns of the array.`,o.toString())):ma(o,a,(e,t)=>e>=i.length||t>=i[e].length?r:i[e][t])},isExported:!0},Gf={description:E(`Flattens all the values from one or more ranges into a single column.`),args:[U(`range (any, range<any>)`,E(`The first range to flatten.`)),U(`range2 (any, range<any>, repeating)`,E(`Additional ranges to flatten.`))],compute:function(...e){return[Aa(e,e=>e===void 0?{value:``}:e)]},isExported:!1},Kf={description:E(`Calculates the frequency distribution of a range.`),args:[U(`data (range<number>)`,E(`The array of ranges containing the values to be counted.`)),U(`classes (number, range<number>)`,E(`The range containing the set of classes.`))],compute:function(e,t){let n=Aa([e],e=>e.value).filter(e=>typeof e==`number`),r=Aa([t],e=>e.value).filter(e=>typeof e==`number`).map((e,t)=>({initialIndex:t,value:e,count:0})).sort((e,t)=>e.value-t.value);r.push({initialIndex:r.length,value:1/0,count:0});let i=n.sort((e,t)=>e-t),a=0;for(let e of i){for(;e>r[a].value&&a<r.length-1;)a++;r[a].count++}return[r.sort((e,t)=>e.initialIndex-t.initialIndex).map(e=>e.count)]},isExported:!0},qf={description:E(`Appends ranges horizontally and in sequence to return a larger array.`),args:[U(`range1 (any, range<any>)`,E(`The first range to be appended.`)),U(`range2 (any, range<any>, repeating)`,E(`Additional ranges to add to range1.`))],compute:function(...e){let t=Math.max(...e.map(e=>e?.[0]?.length??0)),n=[];for(let r of e){let e=I(r);for(let r=0;r<e.length;r++){let i=Array(t).fill({value:null});for(let t=0;t<e[r].length;t++)i[t]=e[r][t];n.push(i)}}return n},isExported:!0},Jf={description:E(`Returns the matrix determinant of a square matrix.`),args:[U(`square_matrix (number, range<number>)`,E(`An range with an equal number of rows and columns representing a matrix whose determinant will be calculated.`))],compute:function(e){let t=$i(e,`square_matrix`);return yu(t)?Su(t).determinant:new A(E(`The argument square_matrix must have the same number of columns and rows.`))},isExported:!0},Yf={description:E(`Returns the multiplicative inverse of a square matrix.`),args:[U(`square_matrix (number, range<number>)`,E(`An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated.`))],compute:function(e){let t=$i(e,`square_matrix`);if(!yu(t))return new A(E(`The argument square_matrix must have the same number of columns and rows.`));let{inverted:n}=Su(t);return n||new A(E(`The matrix is not invertible.`))},isExported:!0},Xf={description:E(`Calculates the matrix product of two matrices.`),args:[U(`matrix1 (number, range<number>)`,E(`The first matrix in the matrix multiplication operation.`)),U(`matrix2 (number, range<number>)`,E(`The second matrix in the matrix multiplication operation.`))],compute:function(e,t){let n=$i(e,`matrix1`),r=$i(t,`matrix2`);return n.length===0||r.length===0?new A(E(`The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.`)):n.length===r[0].length?wu(n,r):new A(E(`In [[FUNCTION_NAME]], the number of columns of the first matrix (%s) must be equal to the number of rows of the second matrix (%s).`,n.length.toString(),r[0].length.toString()))},isExported:!0},Zf={description:E(`Calculates the sum of the products of corresponding entries in equal-sized ranges.`),args:[U(`range1 (number, range<number>)`,E(`The first range whose entries will be multiplied with corresponding entries in the other ranges.`)),U(`range2 (number, range<number>, repeating)`,E(`The other range whose entries will be multiplied with corresponding entries in the other ranges.`))],compute:function(...e){if(!vu(...e))return new A(E(`All the ranges must have the same dimensions.`));let t=e.map(I),n=0;for(let e=0;e<t[0].length;e++)for(let r=0;r<t[0][e].length;r++){if(!t.every(t=>typeof t[e][r].value==`number`))continue;let i=1;for(let n of t)i*=M(n[e][r],this.locale);n+=i}return n},isExported:!0};function Qf(e,t,n){if(!vu(e,t))return new A(E(`The arguments array_x and array_y must have the same dimensions.`));let r=I(e),i=I(t),a=!1,o=0;for(let e in r)for(let t in r[e]){let s=r[e][t].value,c=i[e][t].value;typeof s!=`number`||typeof c!=`number`||(a=!0,o+=n(s,c))}return a?o:new A(E(`The arguments array_x and array_y must contain at least one pair of numbers.`))}let $f={description:E(`Calculates the sum of the difference of the squares of the values in two array.`),args:[U(`array_x (number, range<number>)`,E(`The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.`)),U(`array_y (number, range<number>)`,E(`The array or range of values whose squares will be subtracted from the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return Qf(e,t,(e,t)=>e**2-t**2)},isExported:!0},ep={description:E(`Calculates the sum of the sum of the squares of the values in two array.`),args:[U(`array_x (number, range<number>)`,E(`The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.`)),U(`array_y (number, range<number>)`,E(`The array or range of values whose squares will be added to the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return Qf(e,t,(e,t)=>e**2+t**2)},isExported:!0},tp={description:E(`Calculates the sum of squares of the differences of values in two array.`),args:[U(`array_x (number, range<number>)`,E(`The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.`)),U(`array_y (number, range<number>)`,E(`The array or range of values that will be subtracted from corresponding entries in array_x, the result squared, and all such results added together.`))],compute:function(e,t){return Qf(e,t,(e,t)=>(e-t)**2)},isExported:!0},np=[U(`array (any, range<any>)`,E(`The array which will be transformed.`)),U(`ignore (number, default=0)`,E(`The control to ignore blanks and errors. 0 (default) is to keep all values, 1 is to ignore blanks, 2 is to ignore errors, and 3 is to ignore blanks and errors.`)),U(`scan_by_column (number, default=false)`,E(`Whether the array should be scanned by column. True scans the array by column and false (default) scans the array by row.`))];function rp(e){let t=Math.trunc(e);if(t===0)return()=>!0;if(t===1)return e=>e.value!==null;if(t===2)return e=>!j(e.value);if(t===3)return e=>e.value!==null&&!j(e.value);throw new A(E(`Argument ignore must be between 0 and 3`))}let ip={description:E(`Transforms a range of cells into a single column.`),args:np,compute:function(e,t={value:0},n={value:!1}){let r=I(e),i=M(t.value,this.locale),a=(P(n.value)?r:_a(r)).flat().filter(rp(i));return a.length===0?new Hi(E(`No results for the given arguments of TOCOL.`)):[a]},isExported:!0},ap={description:E(`Transforms a range of cells into a single row.`),args:np,compute:function(e,t={value:0},n={value:!1}){let r=I(e),i=M(t.value,this.locale),a=(P(n.value)?r:_a(r)).flat().filter(rp(i)).map(e=>[e]);return a.length===0||a[0].length===0?new Hi(E(`No results for the given arguments of TOROW.`)):a},isExported:!0},op={description:E(`Transposes the rows and columns of a range.`),args:[U(`range (any, range<any>)`,E(`The range to be transposed.`))],compute:function(e){let t=I(e),n=t[0].length,r=t.length;return ma(n,r,(e,n)=>t[n][e])},isExported:!0},sp={description:E(`Appends ranges vertically and in sequence to return a larger array.`),args:[U(`range1 (any, range<any>)`,E(`The first range to be appended.`)),U(`range2 (any, range<any>, repeating)`,E(`Additional ranges to add to range1.`))],compute:function(...e){let t=Math.max(...e.map(e=>I(e).length)),n=e.reduce((e,t)=>e+I(t)[0].length,0),r=Array(t).fill([]).map(()=>Array(n).fill({value:0})),i=0;for(let t of e){let e=I(t);for(let t=0;t<e.length;t++)for(let n=0;n<e[t].length;n++)r[t][i+n]=e[t][n];i+=e[0].length}return r},isExported:!0},cp={description:E(`Wraps the provided row or column of cells by columns after a specified number of elements to form a new array.`),args:[U(`range (any, range<any>)`,E(`The range to wrap.`)),U(`wrap_count (number)`,E(`The maximum number of cells for each column, rounded down to the nearest whole number.`)),U(`pad_with (any, default=0)`,E(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=I(e),i=ta(t?.value,this.locale);if(!_u(r))return new A(E(`Argument range must be a single row or column.`));let a=r.flat();return ma(Math.ceil(a.length/i),i,(e,t)=>{let r=e*i+t;return r<a.length?a[r]:n})},isExported:!0},lp={description:E(`Wraps the provided row or column of cells by rows after a specified number of elements to form a new array.`),args:[U(`range (any, range<any>)`,E(`The range to wrap.`)),U(`wrap_count (number)`,E(`The maximum number of cells for each row, rounded down to the nearest whole number.`)),U(`pad_with (any, default=0)`,E(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=I(e),i=ta(t?.value,this.locale);if(!_u(r))return new A(E(`Argument range must be a single row or column.`));let a=r.flat();return ma(i,Math.ceil(a.length/i),(e,t)=>{let r=t*i+e;return r<a.length?a[r]:n})},isExported:!0};var up=l({FORMAT_LARGE_NUMBER:()=>dp});let dp={description:E(`Apply a large number format`),args:[U(`value (number)`,E(`The number.`)),U(`unit (string, optional)`,E(`The formatting unit. Use 'k', 'm', or 'b' to force the unit`))],compute:function(e,t){return{value:M(e,this.locale),format:Io(e,t,this.locale)}}};var fp=l({ABS:()=>mp,ACOS:()=>hp,ACOSH:()=>gp,ACOT:()=>_p,ACOTH:()=>vp,ASIN:()=>yp,ASINH:()=>bp,ATAN:()=>xp,ATAN2:()=>Sp,ATANH:()=>Cp,CEILING:()=>wp,CEILING_MATH:()=>Ep,CEILING_PRECISE:()=>Dp,COS:()=>Op,COSH:()=>kp,COT:()=>Ap,COTH:()=>jp,COUNTBLANK:()=>Mp,COUNTIF:()=>Np,COUNTIFS:()=>Pp,COUNTUNIQUE:()=>Fp,COUNTUNIQUEIFS:()=>Ip,CSC:()=>Lp,CSCH:()=>Rp,DECIMAL:()=>zp,DEGREES:()=>Bp,EXP:()=>Vp,FLOOR:()=>Hp,FLOOR_MATH:()=>Wp,FLOOR_PRECISE:()=>Gp,INT:()=>Cm,ISEVEN:()=>Kp,ISODD:()=>Jp,ISO_CEILING:()=>qp,LN:()=>Yp,LOG:()=>Xp,MOD:()=>Qp,MUNIT:()=>$p,ODD:()=>em,PI:()=>tm,POWER:()=>nm,PRODUCT:()=>rm,RAND:()=>im,RANDARRAY:()=>am,RANDBETWEEN:()=>om,ROUND:()=>sm,ROUNDDOWN:()=>cm,ROUNDUP:()=>lm,SEC:()=>um,SECH:()=>dm,SEQUENCE:()=>fm,SIN:()=>pm,SINH:()=>mm,SQRT:()=>hm,SUM:()=>gm,SUMIF:()=>_m,SUMIFS:()=>vm,TAN:()=>ym,TANH:()=>bm,TRUNC:()=>Sm});let pp=/^-?[a-z0-9]+$/i,mp={description:E(`Absolute value of a number.`),args:[U(`value (number)`,E(`The number of which to return the absolute value.`))],compute:function(e){return Math.abs(M(e,this.locale))},isExported:!0},hp={description:E(`Inverse cosine of a value, in radians.`),args:[U(`value (number)`,E(`The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=M(e,this.locale);return Math.abs(t)>1?new A(E(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.acos(t)},isExported:!0},gp={description:E(`Inverse hyperbolic cosine of a number.`),args:[U(`value (number)`,E(`The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.`))],compute:function(e){let t=M(e,this.locale);return t<1?new A(E(`The value (%s) must be greater than or equal to 1.`,t)):Math.acosh(t)},isExported:!0},_p={description:E(`Inverse cotangent of a value.`),args:[U(`value (number)`,E(`The value for which to calculate the inverse cotangent.`))],compute:function(e){let t=M(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},vp={description:E(`Inverse hyperbolic cotangent of a value.`),args:[U(`value (number)`,E(`The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.`))],compute:function(e){let t=M(e,this.locale);return Math.abs(t)<=1?new A(E(`The value (%s) cannot be between -1 and 1 inclusive.`,t)):Math.log((t+1)/(t-1))/2},isExported:!0},yp={description:E(`Inverse sine of a value, in radians.`),args:[U(`value (number)`,E(`The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=M(e,this.locale);return Math.abs(t)>1?new A(E(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.asin(t)},isExported:!0},bp={description:E(`Inverse hyperbolic sine of a number.`),args:[U(`value (number)`,E(`The value for which to calculate the inverse hyperbolic sine.`))],compute:function(e){return Math.asinh(M(e,this.locale))},isExported:!0},xp={description:E(`Inverse tangent of a value, in radians.`),args:[U(`value (number)`,E(`The value for which to calculate the inverse tangent.`))],compute:function(e){return Math.atan(M(e,this.locale))},isExported:!0},Sp={description:E(`Angle from the X axis to a point (x,y), in radians.`),args:[U(`x (number)`,E(`The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`)),U(`y (number)`,E(`The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`))],compute:function(e,t){let n=M(e,this.locale),r=M(t,this.locale);return n===0&&r===0?new Gi(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):Math.atan2(r,n)},isExported:!0},Cp={description:E(`Inverse hyperbolic tangent of a number.`),args:[U(`value (number)`,E(`The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.`))],compute:function(e){let t=M(e,this.locale);return Math.abs(t)>=1?new A(E(`The value (%s) must be between -1 and 1 exclusive.`,t)):Math.atanh(t)},isExported:!0},wp={description:E(`Rounds number up to nearest multiple of factor.`),args:[U(`value (number)`,E(`The value to round up to the nearest integer multiple of factor.`)),U(`factor (number, default=1)`,E(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=M(e,this.locale),r=M(t,this.locale);return r<0&&n>0?new A(E(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.ceil(n/r)*r:0,format:e?.format}},isExported:!0};function Tp(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.ceil(e/t)*t:n===0?-Math.floor(Math.abs(e)/t)*t:-Math.ceil(Math.abs(e)/t)*t)}let Ep={description:E(`Rounds number up to nearest multiple of factor.`),args:[U(`number (number)`,E(`The value to round up to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),U(`mode (number, default=0)`,E(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.`))],compute:function(e,t={value:1},n={value:0}){let r=M(t,this.locale);return{value:Tp(M(e,this.locale),r,M(n,this.locale)),format:e?.format}},isExported:!0},Dp={description:E(`Rounds number up to nearest multiple of factor.`),args:[U(`number (number)`,E(`The value to round up to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=M(t,this.locale);return{value:Tp(M(e,this.locale),n),format:e?.format}},isExported:!0},Op={description:E(`Cosine of an angle provided in radians.`),args:[U(`angle (number)`,E(`The angle to find the cosine of, in radians.`))],compute:function(e){return Math.cos(M(e,this.locale))},isExported:!0},kp={description:E(`Hyperbolic cosine of any real number.`),args:[U(`value (number)`,E(`Any real value to calculate the hyperbolic cosine of.`))],compute:function(e){return Math.cosh(M(e,this.locale))},isExported:!0},Ap={description:E(`Cotangent of an angle provided in radians.`),args:[U(`angle (number)`,E(`The angle to find the cotangent of, in radians.`))],compute:function(e){let t=M(e,this.locale);return t===0?new Gi(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tan(t)},isExported:!0},jp={description:E(`Hyperbolic cotangent of any real number.`),args:[U(`value (number)`,E(`Any real value to calculate the hyperbolic cotangent of.`))],compute:function(e){let t=M(e,this.locale);return t===0?new Gi(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tanh(t)},isExported:!0},Mp={description:E(`Number of empty values.`),args:[U(`value1 (any, range)`,E(`The first value or range in which to count the number of blanks.`)),U(`value2 (any, range, repeating)`,E(`Additional values or ranges in which to count the number of blanks.`))],compute:function(...e){return da(e,(e,t)=>t===void 0||t.value===null||t.value===``?e+1:e,0)},isExported:!0},Np={description:E(`A conditional count across a range.`),args:[U(`range (range)`,E(`The range that is tested against criterion.`)),U(`criterion (string)`,E(`The pattern or test to apply to range.`))],compute:function(...e){let t=0;return wa(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},Pp={description:E(`Count values depending on multiple criteria.`),args:[U(`criteria_range1 (range)`,E(`The range to check against criterion1.`)),U(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1.`)),U(`criteria_range2 (any, range, repeating)`,E(`Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.`)),U(`criterion2 (string, repeating)`,E(`Additional criteria to check.`))],compute:function(...e){let t=0;return wa(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},Fp={description:E(`Counts number of unique values in a range.`),args:[U(`value1 (any, range)`,E(`The first value or range to consider for uniqueness.`)),U(`value2 (any, range, repeating)`,E(`Additional values or ranges to consider for uniqueness.`))],compute:function(...e){return mu(e)}},Ip={description:E(`Counts number of unique values in a range, filtered by a set of criteria.`),args:[U(`range (range)`,E(`The range of cells from which the number of unique values will be counted.`)),U(`criteria_range1 (range)`,E(`The range of cells over which to evaluate criterion1.`)),U(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.`)),U(`criteria_range2 (any, range, repeating)`,E(`Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.`)),U(`criterion2 (string, repeating)`,E(`The pattern or test to apply to criteria_range2.`))],compute:function(e,...t){let n=new Set;return wa(t,(t,r)=>{let i=e[t]?.[r];ja(i)&&n.add(i.value)},this.locale),n.size}},Lp={description:E(`Cosecant of an angle provided in radians.`),args:[U(`angle (number)`,E(`The angle to find the cosecant of, in radians.`))],compute:function(e){let t=M(e,this.locale);return t===0?new Gi(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sin(t)},isExported:!0},Rp={description:E(`Hyperbolic cosecant of any real number.`),args:[U(`value (number)`,E(`Any real value to calculate the hyperbolic cosecant of.`))],compute:function(e){let t=M(e,this.locale);return t===0?new Gi(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sinh(t)},isExported:!0},zp={description:E(`Converts from another base to decimal.`),args:[U(`value (string)`,E(`The number to convert.`)),U(`base (number)`,E(`The base to convert the value from.`))],compute:function(e,t){let n=M(t,this.locale);if(n=Math.floor(n),2>n||n>36)return new A(E(`The base (%s) must be between 2 and 36 inclusive.`,n));let r=N(e);if(r===``)return 0;if(!pp.test(r))return new A(E(`The value (%s) must be a valid base %s representation.`,r,n));let i=parseInt(r,n);return isNaN(i)?new A(E(`The value (%s) must be a valid base %s representation.`,r,n)):i},isExported:!0},Bp={description:E(`Converts an angle value in radians to degrees.`),args:[U(`angle (number)`,E(`The angle to convert from radians to degrees.`))],compute:function(e){return M(e,this.locale)*180/Math.PI},isExported:!0},Vp={description:E(`Euler's number, e (~2.718) raised to a power.`),args:[U(`value (number)`,E(`The exponent to raise e.`))],compute:function(e){return Math.exp(M(e,this.locale))},isExported:!0},Hp={description:E(`Rounds number down to nearest multiple of factor.`),args:[U(`value (number)`,E(`The value to round down to the nearest integer multiple of factor.`)),U(`factor (number, default=1)`,E(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=M(e,this.locale),r=M(t,this.locale);return r<0&&n>0?new A(E(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.floor(n/r)*r:0,format:e?.format}},isExported:!0};function Up(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.floor(e/t)*t:n===0?-Math.ceil(Math.abs(e)/t)*t:-Math.floor(Math.abs(e)/t)*t)}let Wp={description:E(`Rounds number down to nearest multiple of factor.`),args:[U(`number (number)`,E(`The value to round down to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),U(`mode (number, default=0)`,E(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.`))],compute:function(e,t={value:1},n={value:0}){let r=M(t,this.locale);return{value:Up(M(e,this.locale),r,M(n,this.locale)),format:e?.format}},isExported:!0},Gp={description:E(`Rounds number down to nearest multiple of factor.`),args:[U(`number (number)`,E(`The value to round down to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=M(t,this.locale);return{value:Up(M(e,this.locale),n),format:e?.format}},isExported:!0},Kp={description:E(`Whether the provided value is even.`),args:[U(`value (number)`,E(`The value to be verified as even.`))],compute:function(e){let t=ea(e,this.locale);return!(Math.floor(Math.abs(t))&1)},isExported:!0},qp={description:E(`Rounds number up to nearest multiple of factor.`),args:[U(`number (number)`,E(`The value to round up to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){return{value:Tp(M(e,this.locale),M(t,this.locale)),format:e?.format}},isExported:!0},Jp={description:E(`Whether the provided value is even.`),args:[U(`value (number)`,E(`The value to be verified as even.`))],compute:function(e){let t=ea(e,this.locale);return!!(Math.floor(Math.abs(t))&1)},isExported:!0},Yp={description:E(`The logarithm of a number, base e (euler's number).`),args:[U(`value (number)`,E(`The value for which to calculate the logarithm, base e.`))],compute:function(e){let t=M(e,this.locale);return t<=0?new A(E(`The value (%s) must be strictly positive.`,t)):Math.log(t)},isExported:!0},Xp={description:E(`The logarithm of a number, for a given base.`),args:[U(`value (number)`,E(`The value for which to calculate the logarithm.`)),U(`base (number, default=10)`,E(`The base of the logarithm.`))],compute:function(e,t={value:10}){let n=M(e,this.locale),r=M(t,this.locale);return n<=0?new A(E(`The value (%s) must be strictly positive.`,n)):r<=0?new A(E(`The base (%s) must be strictly positive.`,r)):r===1?new A(E(`The base must be different from 1.`)):Math.log10(n)/Math.log10(r)},isExported:!0};function Zp(e,t){gu(t,E(`The divisor must be different from 0.`));let n=e%t;return n>0&&t<0||n<0&&t>0?n+t:n}let Qp={description:E(`Modulo (remainder) operator.`),args:[U(`dividend (number)`,E(`The number to be divided to find the remainder.`)),U(`divisor (number)`,E(`The number to divide by.`))],compute:function(e,t){let n=M(t,this.locale);return{value:Zp(M(e,this.locale),n),format:e?.format}},isExported:!0},$p={description:E(`Returns a n x n unit matrix, where n is the input dimension.`),args:[U(`dimension (number)`,E(`An integer specifying the dimension size of the unit matrix. It must be positive.`))],compute:function(e){let t=ta(e,this.locale);return t<1?new A(E(`The argument dimension must be positive`)):xu(t)},isExported:!0},em={description:E(`Rounds a number up to the nearest odd integer.`),args:[U(`value (number)`,E(`The value to round to the next greatest odd number.`))],compute:function(e){let t=M(e,this.locale),n=Math.ceil(Math.abs(t));return n=n&1?n:n+1,{value:t<0?-n:n,format:e?.format}},isExported:!0},tm={description:E(`The number pi.`),args:[],compute:function(){return Math.PI},isExported:!0},nm={description:E(`A number raised to a power.`),args:[U(`base (number)`,E(`The number to raise to the exponent power.`)),U(`exponent (number)`,E(`The exponent to raise base to.`))],compute:function(e,t){let n=M(e,this.locale),r=M(t,this.locale);return n<0&&!Number.isInteger(r)?new A(E(`The exponent (%s) must be an integer when the base is negative.`,r)):{value:n**+r,format:e?.format}},isExported:!0},rm={description:E(`Result of multiplying a series of numbers together.`),args:[U(`factor1 (number, range<number>)`,E(`The first number or range to calculate for the product.`)),U(`factor2 (number, range<number>, repeating)`,E(`More numbers or ranges to calculate for the product.`))],compute:function(...e){let t=0,n=1;for(let r of e)if(Or(r))for(let e of r)for(let r of e){let e=r.value;if(typeof e==`number`&&(n*=e,t+=1),j(e))return r}else r!==void 0&&r.value!==null&&(n*=ea(r,this.locale),t+=1);return{value:t===0?0:n,format:qi(e[0])}},isExported:!0},im={description:E(`A random number between 0 inclusive and 1 exclusive.`),args:[],compute:function(){return Math.random()},isExported:!0},am={description:E(`Returns a grid of random numbers between 0 inclusive and 1 exclusive.`),args:[U(`rows (number, default=1)`,E(`The number of rows to be returned.`)),U(`columns (number, default=1)`,E(`The number of columns to be returned.`)),U(`min (number, default=0)`,E(`The minimum number you would like returned.`)),U(`max (number, default=1)`,E(`The maximum number you would like returned.`)),U(`whole_number (number, default=FALSE)`,E(`Return a whole number or a decimal value.`))],compute:function(e={value:1},t={value:1},n={value:0},r={value:1},i={value:!1}){let a=ta(t,this.locale),o=ta(e,this.locale),s=M(n,this.locale),c=M(r,this.locale),l=P(i);if(a<1)return new A(E(`The number of columns (%s) must be positive.`,a));if(o<1)return new A(E(`The number of rows (%s) must be positive.`,o));if(s>c)return new A(E(`The maximum (%s) must be greater than or equal to the minimum (%s).`,c,s));if(l&&(!Number.isInteger(s)||!Number.isInteger(c)))return new A(E(`The maximum (%s) and minimum (%s) must be integers when whole_number is TRUE.`,c.toString(),s.toString()));let u=Array(a);for(let e=0;e<a;e++){u[e]=Array(o);for(let t=0;t<o;t++)l?u[e][t]=Math.floor(Math.random()*(c-s+1)+s):u[e][t]=s+Math.random()*(c-s)}return u},isExported:!0},om={description:E(`Random integer between two values, inclusive.`),args:[U(`low (number)`,E(`The low end of the random range.`)),U(`high (number)`,E(`The high end of the random range.`))],compute:function(e,t){let n=M(e,this.locale);Number.isInteger(n)||(n=Math.ceil(n));let r=M(t,this.locale);return Number.isInteger(r)||(r=Math.floor(r)),n>r?new A(E(`The high (%s) must be greater than or equal to the low (%s).`,r,n)):{value:n+Math.ceil((r-n+1)*Math.random())-1,format:e?.format}},isExported:!0},sm={description:E(`Rounds a number according to standard rules.`),args:[U(`value (number)`,E(`The value to round to places number of places.`)),U(`places (number, default=0)`,E(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=M(e,this.locale),r=M(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.round(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.round(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},cm={description:E(`Rounds down a number.`),args:[U(`value (number)`,E(`The value to round to places number of places, always rounding down.`)),U(`places (number, default=0)`,E(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=M(e,this.locale),r=M(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.floor(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.floor(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},lm={description:E(`Rounds up a number.`),args:[U(`value (number)`,E(`The value to round to places number of places, always rounding up.`)),U(`places (number, default=0)`,E(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=M(e,this.locale),r=M(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.ceil(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.ceil(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},um={description:E(`Secant of an angle provided in radians.`),args:[U(`angle (number)`,E(`The angle to find the secant of, in radians.`))],compute:function(e){return 1/Math.cos(M(e,this.locale))},isExported:!0},dm={description:E(`Hyperbolic secant of any real number.`),args:[U(`value (number)`,E(`Any real value to calculate the hyperbolic secant of.`))],compute:function(e){return 1/Math.cosh(M(e,this.locale))},isExported:!0},fm={description:E(`Returns a sequence of numbers.`),args:[U(`rows (number)`,E(`The number of rows to return`)),U(`columns (number, optional, default=1)`,E(`The number of columns to return`)),U(`start (number, optional, default=1)`,E(`The first number in the sequence`)),U(`step (number, optional, default=1)`,E(`The amount to increment each value in the sequence`))],compute:function(e,t={value:1},n={value:1},r={value:1}){let i=M(n,this.locale),a=M(r,this.locale),o=ta(e,this.locale),s=ta(t,this.locale);return s<1?new A(E(`The number of columns (%s) must be positive.`,s)):o<1?new A(E(`The number of rows (%s) must be positive.`,o)):ma(s,o,(e,t)=>({value:i+t*s*a+e*a}))},isExported:!0},pm={description:E(`Sine of an angle provided in radians.`),args:[U(`angle (number)`,E(`The angle to find the sine of, in radians.`))],compute:function(e){return Math.sin(M(e,this.locale))},isExported:!0},mm={description:E(`Hyperbolic sine of any real number.`),args:[U(`value (number)`,E(`Any real value to calculate the hyperbolic sine of.`))],compute:function(e){return Math.sinh(M(e,this.locale))},isExported:!0},hm={description:E(`Positive square root of a positive number.`),args:[U(`value (number)`,E(`The number for which to calculate the positive square root.`))],compute:function(e){let t=M(e,this.locale);return t<0?new A(E(`The value (%s) must be positive or null.`,t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},gm={description:E(`Sum of a series of numbers and/or cells.`),args:[U(`value1 (number, range<number>)`,E(`The first number or range to add together.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional numbers or ranges to add to value1.`))],compute:function(...e){let t=e[0];return{value:pu(e,this.locale),format:qi(t)}},isExported:!0},_m={description:E(`A conditional sum across a range.`),args:[U(`criteria_range (range)`,E(`The range which is tested against criterion.`)),U(`criterion (string)`,E(`The pattern or test to apply to range.`)),U(`sum_range (range, default=criteria_range)`,E(`The range to be summed, if different from range.`))],compute:function(e,t,n){n===void 0&&(n=e);let r=0;return wa([e,t],(e,t)=>{let i=n[e]?.[t]?.value;typeof i==`number`&&(r+=i)},this.locale),r},isExported:!0},vm={description:E(`Sums a range depending on multiple criteria.`),args:[U(`sum_range (range)`,E(`The range to sum.`)),U(`criteria_range1 (range)`,E(`The range to check against criterion1.`)),U(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1.`)),U(`criteria_range2 (any, range, repeating)`,E(`Additional ranges to check.`)),U(`criterion2 (string, repeating)`,E(`Additional criteria to check.`))],compute:function(e,...t){let n=0;return wa(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n+=i)},this.locale),n},isExported:!0},ym={description:E(`Tangent of an angle provided in radians.`),args:[U(`angle (number)`,E(`The angle to find the tangent of, in radians.`))],compute:function(e){return Math.tan(M(e,this.locale))},isExported:!0},bm={description:E(`Hyperbolic tangent of any real number.`),args:[U(`value (number)`,E(`Any real value to calculate the hyperbolic tangent of.`))],compute:function(e){return Math.tanh(M(e,this.locale))},isExported:!0};function xm(e,t){return t===0?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*10**t)/10**t)}let Sm={description:E(`Truncates a number.`),args:[U(`value (number)`,E(`The value to be truncated.`)),U(`places (number, default=0)`,E(`The number of significant digits to the right of the decimal point to retain.`))],compute:function(e,t={value:0}){return{value:xm(M(e,this.locale),M(t,this.locale)),format:e?.format}},isExported:!0},Cm={description:E(`Rounds a number down to the nearest integer that is less than or equal to it.`),args:[U(`value (number)`,E(`The number to round down to the nearest integer.`))],compute:function(e){return Math.floor(M(e,this.locale))},isExported:!0};var wm=l({AVEDEV:()=>km,AVERAGE:()=>Am,AVERAGEA:()=>Pm,AVERAGEIF:()=>Fm,AVERAGEIFS:()=>Im,AVERAGE_WEIGHTED:()=>Nm,CORREL:()=>ih,COUNT:()=>Lm,COUNTA:()=>Rm,COVAR:()=>zm,COVARIANCE_P:()=>Bm,COVARIANCE_S:()=>Vm,FORECAST:()=>Hm,GROWTH:()=>Um,INTERCEPT:()=>Wm,LARGE:()=>Gm,LINEST:()=>Km,LOGEST:()=>qm,MATTHEWS:()=>Jm,MAX:()=>Ym,MAXA:()=>Xm,MAXIFS:()=>Zm,MEDIAN:()=>Qm,MIN:()=>$m,MINA:()=>eh,MINIFS:()=>th,PEARSON:()=>rh,PERCENTILE:()=>ah,PERCENTILE_EXC:()=>oh,PERCENTILE_INC:()=>sh,POLYFIT_COEFFS:()=>ch,POLYFIT_FORECAST:()=>lh,QUARTILE:()=>uh,QUARTILE_EXC:()=>dh,QUARTILE_INC:()=>fh,RANK:()=>ph,RSQ:()=>mh,SLOPE:()=>hh,SMALL:()=>gh,SPEARMAN:()=>_h,STDEV:()=>vh,STDEVA:()=>xh,STDEVP:()=>Sh,STDEVPA:()=>Ch,STDEV_P:()=>yh,STDEV_S:()=>bh,STEYX:()=>wh,TREND:()=>Th,VAR:()=>Eh,VARA:()=>kh,VARP:()=>Ah,VARPA:()=>jh,VAR_P:()=>Dh,VAR_S:()=>Oh});function Tm(e,t){let n=[],r=[],i=0,a=0;ca([e],e=>{n.push(e),i+=1}),ca([t],e=>{r.push(e),a+=1}),hu(i===a,E(`[[FUNCTION_NAME]] has mismatched argument count %s vs %s.`,i,a));let o=[],s=[];for(let e=0;e<i;e++){let t=n[e]?.value,i=r[e]?.value;typeof t==`number`&&typeof i==`number`&&(s.push(t),o.push(i))}return{flatDataX:o,flatDataY:s}}function Em(e,t,n){let{flatDataX:r,flatDataY:i}=Tm(e,t),a=i.length;gu(a),n&&gu(a-1);let o=0,s=0;for(let e=0;e<a;e++)o+=i[e],s+=r[e];let c=o/a,l=s/a,u=0;for(let e=0;e<a;e++)u+=(i[e]-c)*(r[e]-l);return u/(a-+!!n)}function Dm(e,t,n,r){let i=0,a=n?pa:fa,o=a(e,(e,t)=>(i+=1,e+t),0,r);gu(i),t&&gu(i-1);let s=o/i;return a(e,(e,t)=>e+(t-s)**2,0,r)/(i-+!!t)}function Om(e,t,n,r){let i=M(t,r);hu(n?0<=i&&i<=1:0<i&&i<1,E(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`));let a=[],o,s=0;return ca(e,e=>{let t=e?.value;typeof t==`number`&&(o=Ta(a,e,`nextSmaller`,`asc`,a.length,(e,t)=>e[t]),a.splice(o+1,0,t),s++)}),hu(s!==0,Ma),n||hu(1/(s+1)<=i&&i<=s/(s+1),E(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`)),Li(a,i,n)}let km={description:E(`Average magnitude of deviations from mean.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){let t=0,n=fa(e,(e,n)=>(t+=1,e+n),0,this.locale);if(t===0)return new Gi(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`));let r=n/t;return fa(e,(e,t)=>e+Math.abs(r-t),0,this.locale)/t},isExported:!0},Am={description:E(`Numerical average value in a dataset, ignoring text.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the average value.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the average value.`))],compute:function(...e){return{value:ku(e,this.locale),format:qi(e[0])}},isExported:!0},jm=E(`[[FUNCTION_NAME]] has mismatched range sizes.`),Mm=E(`[[FUNCTION_NAME]] expects the weight to be positive or equal to 0.`),Nm={description:E(`Weighted average.`),args:[U(`values (number, range<number>)`,E(`Values to average.`)),U(`weights (number, range<number>)`,E(`Weights for each corresponding value.`)),U(`additional_values (number, range<number>, repeating)`,E(`Additional values to average.`)),U(`additional_weights (number, range<number>, repeating)`,E(`Additional weights.`))],compute:function(...e){let t=0,n=0;for(let r=0;r<e.length-1;r+=2){let i=e[r],a=e[r+1];if(!vu(i,a))return new A(jm);if(Or(i))for(let e=0;e<i.length;e++)for(let r=0;r<i[0].length;r++){let o=i[e][r].value,s=Or(a)?a?.[e][r].value:M(a,this.locale),c=typeof o==`number`,l=typeof s==`number`;if(c&&l){if(s<0)return new A(Mm);t+=o*s,n+=s;continue}if(c!==l)return new A(E(`[[FUNCTION_NAME]] expects number values.`))}else{let e=M(i,this.locale),r=Or(a)?a?.[0][0].value:M(a,this.locale);if(typeof r==`number`){if(r<0)return new A(Mm);t+=e*r,n+=r}}}return n===0?new Gi(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:t/n,format:qi(e[0])}}},Pm={description:E(`Numerical average value in a dataset.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the average value.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the average value.`))],compute:function(...e){let t=0,n=pa(e,(e,n)=>(t+=1,e+n),0,this.locale);return t===0?new Gi(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:n/t,format:qi(e[0])}},isExported:!0},Fm={description:E(`Average of values depending on criteria.`),args:[U(`criteria_range (number, range<number>)`,E(`The range to check against criterion.`)),U(`criterion (string)`,E(`The pattern or test to apply to criteria_range.`)),U(`average_range (number, range<number>, default=criteria_range)`,E(`The range to average. If not included, criteria_range is used for the average instead.`))],compute:function(e,t,n){let r=I(n===void 0?e:n),i=0,a=0;return wa([e,t],(e,t)=>{let n=r[e]?.[t]?.value;typeof n==`number`&&(i+=1,a+=n)},this.locale),i===0?new Gi(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):a/i},isExported:!0},Im={description:E(`Average of values depending on multiple criteria.`),args:[U(`average_range (range)`,E(`The range to average.`)),U(`criteria_range1 (range)`,E(`The range to check against criterion1.`)),U(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1.`)),U(`criteria_range2 (any, range, repeating)`,E(`Additional criteria_range and criterion to check.`)),U(`criterion2 (string, repeating)`,E(`The pattern or test to apply to criteria_range2.`))],compute:function(e,...t){let n=I(e),r=0,i=0;return wa(t,(e,t)=>{let a=n[e]?.[t]?.value;typeof a==`number`&&(r+=1,i+=a)},this.locale),r===0?new Gi(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):i/r},isExported:!0},Lm={description:E(`The number of numeric values in dataset.`),args:[U(`value1 (number, any, range<number>)`,E(`The first value or range to consider when counting.`)),U(`value2 (number, any, range<number>, repeating)`,E(`Additional values or ranges to consider when counting.`))],compute:function(...e){return Au(e,this.locale)},isExported:!0},Rm={description:E(`The number of values in a dataset.`),args:[U(`value1 (any, range)`,E(`The first value or range to consider when counting.`)),U(`value2 (any, range, repeating)`,E(`Additional values or ranges to consider when counting.`))],compute:function(...e){return ju(e)},isExported:!0},zm={description:E(`The covariance of a dataset.`),args:[U(`data_y (any, range)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (any, range)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return Em(e,t,!1)},isExported:!0},Bm={description:E(`The covariance of a dataset.`),args:[U(`data_y (any, range)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (any, range)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return Em(e,t,!1)},isExported:!0},Vm={description:E(`The sample covariance of a dataset.`),args:[U(`data_y (any, range)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (any, range)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return Em(e,t,!0)},isExported:!0},Hm={description:E(`Calculates the expected y-value for a specified x based on a linear regression of a dataset.`),args:[U(`x (number, range<number>)`,E(`The value(s) on the x-axis to forecast.`)),U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t,n){let{flatDataX:r,flatDataY:i}=Tm(t,n);return r.length===0||i.length===0?new Hi(Ma):Vu([i],[r],ha(I(e),e=>M(e,this.locale)),!0)},isExported:!0},Um={description:E(`Fits points to exponential growth trend.`),args:[U(`known_data_y (range<number>)`,E(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.`)),U(`known_data_x (range<number>, default={1;2;3;...})`,E(`The values of the independent variable(s) corresponding with known_data_y.`)),U(`new_data_x (any, range, default=known_data_x)`,E(`The data points to return the y values for on the ideal curve fit.`)),U(`b (boolean, default=TRUE)`,E(`Given a general exponential form of y = b*m^x for a curve fit, calculates b if TRUE or forces b to be 1 and only calculates the m values if FALSE.`))],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new A(Na(`known_data_y`)):zu(Vu(Bu($i(e,`known_data_y`)),$i(t,`known_data_x`),$i(n,`new_data_y`),P(r)))}},Wm={description:E(`Compute the intercept of the linear regression.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=Tm(e,t);if(n.length===0||r.length===0)return new Hi(Ma);let[[],[i]]=Fu([n],[r]);return i},isExported:!0},Gm={description:E(`Nth largest element from a data set.`),args:[U(`data (any, range)`,E(`Array or range containing the dataset to consider.`)),U(`n (number)`,E(`The rank from largest to smallest of the element to return.`))],compute:function(e,t){let n=Math.trunc(M(t?.value,this.locale)),r=[],i,a=0;ca([e],e=>{typeof e?.value==`number`&&(i=Ta(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.shift(),a--))});let o=r.shift();return o===void 0?new A(Ma):a<n?new A(E(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},Km={description:E(`Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>, default={1;2;3;...})`,E(`The range representing the array or matrix of independent data.`)),U(`calculate_b (boolean, default=TRUE)`,E(`A flag specifying wheter to compute the slope or not`)),U(`verbose (boolean, default=FALSE)`,E(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`))],compute:function(e,t=[[]],n={value:!0},r={value:!1}){return e.length===0||e[0].length===0?new A(Na(`data_y`)):Fu($i(t,`data_x`),$i(e,`data_y`),P(n),P(r))},isExported:!0},qm={description:E(`Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>, optional, default={1;2;3;...})`,E(`The range representing the array or matrix of independent data.`)),U(`calculate_b (boolean, default=TRUE)`,E(`A flag specifying wheter to compute the slope or not`)),U(`verbose (boolean, default=FALSE)`,E(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`))],compute:function(e,t=[[]],n={value:!0},r={value:!1}){if(e.length===0||e[0].length===0)return new A(Na(`data_y`));let i=Fu($i(t,`data_x`),Bu($i(e,`data_y`)),P(n),P(r));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},Jm={description:E(`Compute the Matthews correlation coefficient of a dataset.`),args:[U(`data_x (range)`,E(`The range representing the array or matrix of observed data.`)),U(`data_y (range)`,E(`The range representing the array or matrix of predicted data.`))],compute:function(e,t){let n=e.flat(),r=t.flat();if(Ou(n,r),n.length===0||r.length===0)return new Hi(Ma);let i=n.length,a=0,o=0,s=0,c=0;for(let e=0;e<i;++e){let t=P(n[e]);t===P(r[e])?t?o++:a++:t?c++:s++}return(o*a-s*c)/Math.sqrt((o+s)*(o+c)*(a+s)*(a+c))},isExported:!1},Ym={description:E(`Maximum value in a numeric dataset.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the maximum value.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the maximum value.`))],compute:function(...e){return Mu(e,this.locale)},isExported:!0},Xm={description:E(`Maximum numeric value in a dataset.`),args:[U(`value1 (any, range)`,E(`The first value or range to consider when calculating the maximum value.`)),U(`value2 (any, range, repeating)`,E(`Additional values or ranges to consider when calculating the maximum value.`))],compute:function(...e){let t=pa(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:qi(e[0])}},isExported:!0},Zm={description:E(`Returns the maximum value in a range of cells, filtered by a set of criteria.`),args:[U(`range (range)`,E(`The range of cells from which the maximum will be determined.`)),U(`criteria_range1 (range)`,E(`The range of cells over which to evaluate criterion1.`)),U(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.`)),U(`criteria_range2 (any, range, repeating)`,E(`Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.`)),U(`criterion2 (string, repeating)`,E(`The pattern or test to apply to criteria_range2.`))],compute:function(e,...t){let n=-1/0;return wa(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n<i?i:n)},this.locale),n===-1/0?0:n},isExported:!0},Qm={description:E(`Median value in a numeric dataset.`),args:[U(`value1 (any, range)`,E(`The first value or range to consider when calculating the median value.`)),U(`value2 (any, range, repeating)`,E(`Additional values or ranges to consider when calculating the median value.`))],compute:function(...e){let t=[];return la(e,e=>{t.push(e)},this.locale),{value:Om(t,{value:.5},!0,this.locale),format:qi(t[0])}},isExported:!0},$m={description:E(`Minimum value in a numeric dataset.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the minimum value.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the minimum value.`))],compute:function(...e){return Nu(e,this.locale)},isExported:!0},eh={description:E(`Minimum numeric value in a dataset.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the minimum value.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the minimum value.`))],compute:function(...e){let t=pa(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:qi(e[0])}},isExported:!0},th={description:E(`Returns the minimum value in a range of cells, filtered by a set of criteria.`),args:[U(`range (range)`,E(`The range of cells from which the minimum will be determined.`)),U(`criteria_range1 (range)`,E(`The range of cells over which to evaluate criterion1.`)),U(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.`)),U(`criteria_range2 (any, range, repeating)`,E(`Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.`)),U(`criterion2 (string, repeating)`,E(`The pattern or test to apply to criteria_range2.`))],compute:function(e,...t){let n=1/0;return wa(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n>i?i:n)},this.locale),n===1/0?0:n},isExported:!0};function nh(e,t){let{flatDataX:n,flatDataY:r}=Tm(e,t);if(n.length===0||r.length===0)return new Hi(Ma);let i=n.length,a=0,o=0,s=0,c=0,l=0;for(let e=0;e<i;e++){let t=n[e],i=r[e];a+=t,o+=i,s+=t*i,c+=t*t,l+=i*i}return(i*s-a*o)/Math.sqrt((i*c-a*a)*(i*l-o*o))}let rh={description:E(`Compute the Pearson product-moment correlation coefficient of a dataset.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return nh(e,t)},isExported:!0},ih=rh,ah={description:E(`Value at a given percentile of a dataset.`),args:[U(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),U(`percentile (number)`,E(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return sh.compute.bind(this)(e,t)},isExported:!0},oh={description:E(`Value at a given percentile of a dataset exclusive of 0 and 1.`),args:[U(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),U(`percentile (number)`,E(`The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.`))],compute:function(e,t){return{value:Om([e],t,!1,this.locale),format:qi(e)}},isExported:!0},sh={description:E(`Value at a given percentile of a dataset.`),args:[U(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),U(`percentile (number)`,E(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return{value:Om([e],t,!0,this.locale),format:qi(e)}},isExported:!0},ch={description:E(`Compute the coefficients of polynomial regression of the dataset.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`)),U(`order (number)`,E(`The order of the polynomial to fit the data, between 1 and 6.`)),U(`intercept (boolean, default=TRUE)`,E(`A flag specifying whether to compute the intercept or not.`))],compute:function(e,t,n,r={value:!0}){let{flatDataX:i,flatDataY:a}=Tm(e,t);return i.length===0||a.length===0?new Hi(Ma):Iu(a,i,M(n,this.locale),P(r))},isExported:!1},lh={description:E(`Predict value by computing a polynomial regression of the dataset.`),args:[U(`x (number, range<number>)`,E(`The value(s) on the x-axis to forecast.`)),U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`)),U(`order (number)`,E(`The order of the polynomial to fit the data, between 1 and 6.`)),U(`intercept (boolean, default=TRUE)`,E(`A flag specifying whether to compute the intercept or not.`))],compute:function(e,t,n,r,i={value:!0}){let a=M(r,this.locale),{flatDataX:o,flatDataY:s}=Tm(t,n);if(o.length===0||s.length===0)return new Hi(Ma);let c=Iu(s,o,a,P(i)).flat();return ha(I(e),e=>Ru(c,M(e,this.locale),a))},isExported:!1},uh={description:E(`Value nearest to a specific quartile of a dataset.`),args:[U(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),U(`quartile_number (number)`,E(`Which quartile value to return.`))],compute:function(e,t){return fh.compute.bind(this)(e,t)},isExported:!0},dh={description:E(`Value nearest to a specific quartile of a dataset exclusive of 0 and 4.`),args:[U(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),U(`quartile_number (number)`,E(`Which quartile value, exclusive of 0 and 4, to return.`))],compute:function(e,t){let n={value:.25*Math.trunc(M(t,this.locale))};return{value:Om([e],n,!1,this.locale),format:qi(e)}},isExported:!0},fh={description:E(`Value nearest to a specific quartile of a dataset.`),args:[U(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),U(`quartile_number (number)`,E(`Which quartile value to return.`))],compute:function(e,t){let n={value:.25*Math.trunc(M(t,this.locale))};return{value:Om([e],n,!0,this.locale),format:qi(e)}},isExported:!0},ph={description:E(`Returns the rank of a specified value in a dataset.`),args:[U(`value (number)`,E(`The value whose rank will be determined.`)),U(`data (range)`,E(`The range containing the dataset to consider.`)),U(`is_ascending (boolean, default=FALSE)`,E(`Whether to consider the values in data in descending or ascending order.`))],compute:function(e,t,n={value:!1}){let r=P(n),i=M(e,this.locale),a=1,o=!1;for(let e of t)for(let t of e){if(typeof t.value!=`number`)continue;let e=M(t,this.locale);e===i?o=!0:e>i!==r&&a++}return o?a:new Hi(E(`Value not found in the given data.`))},isExported:!0},mh={description:E(`Compute the square of r, the Pearson product-moment correlation coefficient of a dataset.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let n=nh(e,t);if(n instanceof Error)throw n;return n**2},isExported:!0},hh={description:E(`Compute the slope of the linear regression.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=Tm(e,t);if(n.length===0||r.length===0)return new Hi(Ma);let[[i]]=Fu([n],[r]);return i},isExported:!0},gh={description:E(`Nth smallest element in a data set.`),args:[U(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),U(`n (number)`,E(`The rank from smallest to largest of the element to return.`))],compute:function(e,t){let n=Math.trunc(M(t?.value,this.locale)),r=[],i,a=0;ca([e],e=>{typeof e?.value==`number`&&(i=Ta(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.pop(),a--))});let o=r.pop();return o===void 0?new A(Ma):a<n?new A(E(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},_h={description:E(`Compute the Spearman rank correlation coefficient of a dataset.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=Tm(t,e);if(n.length===0||r.length===0)return new Hi(Ma);let i=n.length,a=n.map((e,t)=>[e,r[t]]);a.sort((e,t)=>e[0]-t[0]);for(let e=0;e<i;++e)a[e][0]=e;a.sort((e,t)=>e[1]-t[1]);let o=0;for(let e=0;e<i;++e)o+=(a[e][0]-e)**2;return 1-6*o/(i**3-i)},isExported:!1},vh={description:E(`Standard deviation.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Math.sqrt(Eh.compute.bind(this)(...e))},isExported:!0},yh={description:E(`Standard deviation of entire population.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Math.sqrt(Dh.compute.bind(this)(...e))},isExported:!0},bh={description:E(`Standard deviation.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Math.sqrt(Oh.compute.bind(this)(...e))},isExported:!0},xh={description:E(`Standard deviation of sample (text as 0).`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Math.sqrt(kh.compute.bind(this)(...e))},isExported:!0},Sh={description:E(`Standard deviation of entire population.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Math.sqrt(Ah.compute.bind(this)(...e))},isExported:!0},Ch={description:E(`Standard deviation of entire population (text as 0).`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Math.sqrt(jh.compute.bind(this)(...e))},isExported:!0},wh={description:E(`Calculates the standard error of the predicted y-value for each x in the regression of a dataset.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=Tm(e,t);return n.length===0||r.length===0?new Hi(Ma):Fu([n],[r],!0,!0)[1][2]},isExported:!0},Th={description:E(`Fits points to linear trend derived via least-squares.`),args:[U(`known_data_y (number, range<number>)`,E(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.`)),U(`known_data_x (number, range<number>, optional, default={1;2;3;...})`,E(`The values of the independent variable(s) corresponding with known_data_y.`)),U(`new_data_x (number, range<number>, optional, default=known_data_x)`,E(`The data points to return the y values for on the ideal curve fit.`)),U(`b (boolean, optional, default=TRUE)`,E(`Given a general linear form of y = m*x+b for a curve fit, calculates b if TRUE or forces b to be 0 and only calculates the m values if FALSE, i.e. forces the curve fit to pass through the origin.`))],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new A(Na(`known_data_y`)):Vu($i(e,`known_data_y`),$i(t,`known_data_x`),$i(n,`new_data_y`),P(r))}},Eh={description:E(`Variance.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Dm(e,!0,!1,this.locale)},isExported:!0},Dh={description:E(`Variance of entire population.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Dm(e,!1,!1,this.locale)},isExported:!0},Oh={description:E(`Variance.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Dm(e,!0,!1,this.locale)},isExported:!0},kh={description:E(`Variance of sample (text as 0).`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Dm(e,!0,!0,this.locale)},isExported:!0},Ah={description:E(`Variance of entire population.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Dm(e,!1,!1,this.locale)},isExported:!0},jh={description:E(`Variance of entire population (text as 0).`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Dm(e,!1,!0,this.locale)},isExported:!0};var Mh=l({DAVERAGE:()=>Fh,DCOUNT:()=>Ih,DCOUNTA:()=>Lh,DGET:()=>Rh,DMAX:()=>zh,DMIN:()=>Bh,DPRODUCT:()=>Vh,DSTDEV:()=>Hh,DSTDEVP:()=>Uh,DSUM:()=>Wh,DVAR:()=>Gh,DVARP:()=>Kh});function Nh(e,t,n,r){let i=new Map,a=e.length;for(let t=a-1;t>=0;t--)i.set(N(e[t][0]).toUpperCase(),t);let o=t?.value;if(typeof o!=`number`&&typeof o!=`string`)throw new A(E(`The field must be a number or a string`));let s;if(typeof o==`number`){if(s=Math.trunc(o)-1,s<0||a-1<s)throw new A(E(`The field (%(fieldValue)s) must be one of %(dimRowDB)s or must be a number between 1 and %s inclusive.`,{fieldValue:o.toString(),dimRowDB:a.toString()}))}else{let e=N(t).toUpperCase();if(s=i.get(e)??-1,s===-1)throw new A(E(`The field (%s) must be one of %s.`,N(t),[...i.keys()].toString()))}let c=n[0].length;if(c<2)throw new A(E(`The criteria range contains %s row, it must be at least 2 rows.`,c.toString()));let l=new Set,u=e[0].length;for(let t=1;t<c;t++){let a=[],o=!0;for(let r=0;r<n.length;r++){let s=N(n[r][0]).toUpperCase(),c=i.get(s),l=n[r][t];if(l.value!==null)if(c!==void 0)a.push([e[c].slice(1,u)]),a.push(l);else{o=!1;break}}if(o)if(a.length>0)wa(a,(e,t)=>{l.add(t)},r,!0);else{l=new Set(Array(u-1).keys());break}}let d=e[s];return[...l].map(e=>d[e+1])}let Ph=[U(`database (range)`,E(`The array or range containing the data to consider, structured in such a way that the first row contains the labels for each column's values.`)),U(`field (number, string)`,E(`Indicates which column in database contains the values to be extracted and operated on.`)),U(`criteria (range)`,E(`An array or range containing zero or more criteria to filter the database values by before operating.`))],Fh={description:E(`Average of a set of values from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return Am.compute.bind(this)([r])},isExported:!0},Ih={description:E(`Counts values from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return Lm.compute.bind(this)([r])},isExported:!0},Lh={description:E(`Counts values and text from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return Rm.compute.bind(this)([r])},isExported:!0},Rh={description:E(`Single value from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return r.length===1?r[0]:new A(E(`More than one match found in DGET evaluation.`))},isExported:!0},zh={description:E(`Maximum of values from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return Ym.compute.bind(this)([r])},isExported:!0},Bh={description:E(`Minimum of values from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return $m.compute.bind(this)([r])},isExported:!0},Vh={description:E(`Product of values from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return rm.compute.bind(this)([r])},isExported:!0},Hh={description:E(`Standard deviation of population sample from table.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return vh.compute.bind(this)([r])},isExported:!0},Uh={description:E(`Standard deviation of entire population from table.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return Sh.compute.bind(this)([r])},isExported:!0},Wh={description:E(`Sum of values from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return gm.compute.bind(this)([r])},isExported:!0},Gh={description:E(`Variance of population sample from table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return Eh.compute.bind(this)([r])},isExported:!0},Kh={description:E(`Variance of a population from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return Ah.compute.bind(this)([r])},isExported:!0};var qh=l({DATE:()=>Yh,DATEDIF:()=>Xh,DATEVALUE:()=>Zh,DAY:()=>Qh,DAYS:()=>$h,DAYS360:()=>eg,EDATE:()=>tg,EOMONTH:()=>ng,HOUR:()=>rg,ISOWEEKNUM:()=>ig,MINUTE:()=>ag,MONTH:()=>og,MONTH_END:()=>Sg,MONTH_START:()=>xg,NETWORKDAYS:()=>sg,NETWORKDAYS_INTL:()=>lg,NOW:()=>ug,QUARTER:()=>Cg,QUARTER_END:()=>Tg,QUARTER_START:()=>wg,SECOND:()=>dg,TIME:()=>fg,TIMEVALUE:()=>pg,TODAY:()=>mg,WEEKDAY:()=>hg,WEEKNUM:()=>gg,WORKDAY:()=>_g,WORKDAY_INTL:()=>vg,YEAR:()=>yg,YEARFRAC:()=>bg,YEAR_END:()=>Dg,YEAR_START:()=>Eg}),Jh=function(e){return e.WHOLE_YEARS=`Y`,e.WHOLE_MONTHS=`M`,e.WHOLE_DAYS=`D`,e.DAYS_WITHOUT_WHOLE_MONTHS=`MD`,e.MONTH_WITHOUT_WHOLE_YEARS=`YM`,e.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR=`YD`,e}(Jh||{});let Yh={description:E(`Converts year/month/day into a date.`),args:[U(`year (number)`,E(`The year component of the date.`)),U(`month (number)`,E(`The month component of the date.`)),U(`day (number)`,E(`The day component of the date.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=Math.trunc(M(n,this.locale));if(r<0||r>9999)return new A(E(`The year (%s) must be between 0 and 9999 inclusive.`,r.toString()));r<1900&&(r+=1900);let o=hi(new O(r,i-1,a));return o<0?new A(E(`The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.`)):{value:o,format:this.locale.dateFormat}},isExported:!0},Xh={description:E(`Calculates the number of days, months, or years between two dates.`),args:[U(`start_date (date)`,E(`The start date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),U(`end_date (date)`,E(`The end date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),U(`unit (string)`,E(`A text abbreviation for unit of time. Accepted values are "Y" (the number of whole years between start_date and end_date), "M" (the number of whole months between start_date and end_date), "D" (the number of days between start_date and end_date), "MD" (the number of days between start_date and end_date after subtracting whole months), "YM" (the number of whole months between start_date and end_date after subtracting whole years), "YD" (the number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart).`))],compute:function(e,t,n){let r=N(n).toUpperCase();if(!Object.values(Jh).includes(r))return new A(Zi(Object.values(Jh),N(n)));let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=mi(i),s=mi(a);if(a<i)return new A(E(`start_date (%s) should be on or before end_date (%s).`,o.toLocaleDateString(),s.toLocaleDateString()));switch(r){case`Y`:return wi(o,s);case`M`:return Si(o,s);case`D`:return Ci(o,s);case`YM`:return Si(o,s)-wi(o,s)*12;case`MD`:let e=s.getDate()-o.getDate();return e<0&&(e=_i(new O(s.getFullYear(),s.getMonth()-1,1))-Math.abs(e)),e;case`YD`:{if(Ti(i,a))return Ci(o,s);let e=new O(o.getFullYear(),s.getMonth(),s.getDate()),t=Ci(o,e);return t<0&&(e.setFullYear(o.getFullYear()+1),t=Ci(o,e)),t}}},isExported:!0},Zh={description:E(`Converts a date string to a date value.`),args:[U(`date_string (string)`,E(`The string representing the date.`))],compute:function(e){let t=N(e),n=ii(t,this.locale);return n===null?new A(E(`The date_string (%s) cannot be parsed to date/time.`,t.toString())):Math.trunc(n.value)},isExported:!0},Qh={description:E(`Day of the month that a specific date falls on.`),args:[U(`date (string)`,E(`The date from which to extract the day.`))],compute:function(e){return F(e,this.locale).getDate()},isExported:!0},$h={description:E(`Number of days between two dates.`),args:[U(`end_date (date)`,E(`The end of the date range.`)),U(`start_date (date)`,E(`The start of the date range.`))],compute:function(e,t){let n=F(e,this.locale),r=F(t,this.locale),i=n.getTime()-r.getTime();return Math.round(i/Wr)},isExported:!0},eg={description:E(`Number of days between two dates on a 360-day year (months of 30 days).`),args:[U(`start_date (date)`,E(`The start date to consider in the calculation.`)),U(`end_date (date)`,E(`The end date to consider in the calculation.`)),U(`method (number, default=0)`,E(`An indicator of what day count method to use. (0) US NASD method (1) European method`))],compute:function(e,t,n={value:0}){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=xi(r,i,P(n)?4:0);return Math.sign(i-r)*Math.round(a*360)},isExported:!0},tg={description:E(`Date a number of months before/after another date.`),args:[U(`start_date (date)`,E(`The date from which to calculate the result.`)),U(`months (number)`,E(`The number of months before (negative) or after (positive) 'start_date' to calculate.`))],compute:function(e,t){return{value:hi(yi(F(e,this.locale),Math.trunc(M(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},ng={description:E(`Last day of a month before or after a date.`),args:[U(`start_date (date)`,E(`The date from which to calculate the result.`)),U(`months (number)`,E(`The number of months before (negative) or after (positive) 'start_date' to consider.`))],compute:function(e,t){let n=F(e,this.locale),r=Math.trunc(M(t,this.locale));return{value:hi(new O(n.getFullYear(),n.getMonth()+r+1,0)),format:this.locale.dateFormat}},isExported:!0},rg={description:E(`Hour component of a specific time.`),args:[U(`time (date)`,E(`The time from which to calculate the hour component.`))],compute:function(e){return F(e,this.locale).getHours()},isExported:!0},ig={description:E(`ISO week number of the year.`),args:[U(`date (date)`,E(`The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`))],compute:function(e){let t=F(e,this.locale),n=t.getFullYear(),r=1;for(;new O(n,0,r).getDay()!==4;)r+=1;let i=new O(n,0,r-3),a=31;for(;new O(n,11,a).getDay()!==4;)--a;let o=new O(n,11,a+3),s;s=i.getTime()<=t.getTime()?t.getTime()<=o.getTime()?0:1:-1;let c;switch(s){case 0:c=i;break;case 1:c=new O(n,11,a+3+1);break;case-1:let e=1;for(;new O(n-1,0,e).getDay()!==4;)e+=1;c=new O(n-1,0,e-3);break}let l=(t.getTime()-c.getTime())/Wr;return Math.floor(l/7)+1},isExported:!0},ag={description:E(`Minute component of a specific time.`),args:[U(`time (date)`,E(`The time from which to calculate the minute component.`))],compute:function(e){return F(e,this.locale).getMinutes()},isExported:!0},og={description:E(`Month of the year a specific date falls in`),args:[U(`date (date)`,E(`The date from which to extract the month.`))],compute:function(e){return F(e,this.locale).getMonth()+1},isExported:!0},sg={description:E(`Net working days between two provided days.`),args:[U(`start_date (date)`,E(`The start date of the period from which to calculate the number of net working days.`)),U(`end_date (date)`,E(`The end date of the period from which to calculate the number of net working days.`)),U(`holidays (date, range<date>, optional)`,E(`A range or array constant containing the date serial numbers to consider holidays.`))],compute:function(e,t,n){return lg.compute.bind(this)(e,t,{value:1},n)},isExported:!0};function cg(e){let t=e?.value;if(typeof t==`string`){hu(t.length===7&&[...t].every(e=>e===`0`||e===`1`),E(`When weekend is a string (%s) it must be composed of "0" or "1".`,t));let e=[];for(let n=0;n<7;n++)t[n]===`1`&&e.push((n+1)%7);return e}if(typeof t==`number`)return hu(1<=t&&t<=7||11<=t&&t<=17,E(`The weekend (%s) must be a string or a number in the range 1-7 or 11-17.`,t.toString())),t<=7?[t-2==-1?6:t-2,t-1]:[t-11];throw new A(E(`The weekend must be a number or a string.`))}let lg={description:E(`Net working days between two dates (specifying weekends).`),args:[U(`start_date (date)`,E(`The start date of the period from which to calculate the number of net working days.`)),U(`end_date (date)`,E(`The end date of the period from which to calculate the number of net working days.`)),U(`weekend (any, default=1)`,E(`A number or string representing which days of the week are considered weekends.`)),U(`holidays (date, range<date>, optional)`,E(`A range or array constant containing the dates to consider as holidays.`))],compute:function(e,t,n={value:1},r){let i=F(e,this.locale),a=F(t,this.locale),o=cg(n),s=new Set;r!==void 0&&ca([r],e=>{let t=F(e,this.locale);s.add(t.getTime())});let c=i.getTime()>a.getTime(),l=O.fromTimestamp((c?i:a).getTime()),u=O.fromTimestamp((c?a:i).getTime()),d=l.getTime(),f=u.getTime(),p=0;for(;f<=d;)!o.includes(u.getDay())&&!s.has(f)&&(p+=1),u.setDate(u.getDate()+1),f=u.getTime();return c?-p:p},isExported:!0},ug={description:E(`Current date and time as a date value.`),args:[],compute:function(){let e=O.now(),t=e.getTime()-Ur.getTime(),n=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/Wr)+n,format:uu(this.locale)}},isExported:!0},dg={description:E(`Minute component of a specific time.`),args:[U(`time (date)`,E(`The time from which to calculate the second component.`))],compute:function(e){return F(e,this.locale).getSeconds()},isExported:!0},fg={description:E(`Converts hour/minute/second into a time.`),args:[U(`hour (number)`,E(`The hour component of the time.`)),U(`minute (number)`,E(`The minute component of the time.`)),U(`second (number)`,E(`The second component of the time.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=Math.trunc(M(n,this.locale));return i+=Math.floor(a/60),a=a%60+(a<0?60:0),r+=Math.floor(i/60),i=i%60+(i<0?60:0),r%=24,r<0?new A(E(`The function [[FUNCTION_NAME]] result cannot be negative`)):{value:r/24+i/1440+a/(1440*60),format:this.locale.timeFormat}},isExported:!0},pg={description:E(`Converts a time string into its serial number representation.`),args:[U(`time_string (string)`,E(`The string that holds the time representation.`))],compute:function(e){let t=N(e),n=ii(t,this.locale);if(n===null)return new A(E(`The time_string (%s) cannot be parsed to date/time.`,t));let r=n.value-Math.trunc(n.value);return r<0?1+r:r},isExported:!0},mg={description:E(`Current date as a date value.`),args:[],compute:function(){let e=O.now();return{value:hi(new O(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},hg={description:E(`Day of the week of the date provided (as number).`),args:[U(`date (date)`,E(`The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),U(`type (number, default=1)`,E(`A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.`))],compute:function(e,t={value:1}){let n=F(e,this.locale),r=Math.round(M(t,this.locale)),i=n.getDay();return[1,2,3].includes(r)?r===1?i+1:r===2?i===0?7:i:i===0?6:i-1:new A(E(`The type (%s) must be 1, 2 or 3.`,r))},isExported:!0},gg={description:E(`Week number of the year.`),args:[U(`date (date)`,E(`The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),U(`type (number, default=1)`,E(`A number representing the day that a week starts on. Sunday = 1.`))],compute:function(e,t={value:1}){let n=F(e,this.locale),r=Math.round(M(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(r))return new A(E(`The type (%s) is out of range.`,r.toString()));if(r===21)return ig.compute.bind(this)(e);let i;i=r===1||r===2?r-1:r-10==7?0:r-10;let a=n.getFullYear(),o=1,s=new O(a,0,o);for(;s.getDay()!==i;)o+=1,s=new O(a,0,o);let c=(n.getTime()-s.getTime())/Wr;return c<0?1:Math.floor(c/7)+(o===1?1:2)},isExported:!0},_g={description:E(`Date after a number of workdays.`),args:[U(`start_date (date)`,E(`The date from which to begin counting.`)),U(`num_days (number)`,E(`The number of working days to advance from start_date. If negative, counts backwards.`)),U(`holidays (date, range<date>, optional)`,E(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:null}){return vg.compute.bind(this)(e,t,{value:1},n)},isExported:!0},vg={description:E(`Date after a number of workdays (specifying weekends).`),args:[U(`start_date (date)`,E(`The date from which to begin counting.`)),U(`num_days (number)`,E(`The number of working days to advance from start_date. If negative, counts backwards.`)),U(`weekend (any, default=1)`,E(`A number or string representing which days of the week are considered weekends.`)),U(`holidays (date, range<date>, optional)`,E(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:1},r){let i=F(e,this.locale),a=Math.trunc(M(t,this.locale));if(n.value===`1111111`)return new A(E(`The weekend must be different from '1111111'.`));let o=cg(n),s=new Set;r!==void 0&&ca([r],e=>{let t=F(e,this.locale);s.add(t.getTime())});let c=O.fromTimestamp(i.getTime()),l=c.getTime(),u=Math.sign(a),d=Math.abs(a);for(;d>0;)c.setDate(c.getDate()+u),l=c.getTime(),!o.includes(c.getDay())&&!s.has(l)&&--d;let f=l-Ur.getTime();return{value:Math.round(f/Wr),format:this.locale.dateFormat}},isExported:!0},yg={description:E(`Year specified by a given date.`),args:[U(`date (date)`,E(`The date from which to extract the year.`))],compute:function(e){return F(e,this.locale).getFullYear()},isExported:!0},bg={description:E(`Exact number of years between two dates.`),args:[U(`start_date (date)`,E(`The start date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),U(`end_date (date)`,E(`The end date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),U(`day_count_convention (number, default=0)`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n={value:0}){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=Math.trunc(M(n,this.locale));return r<0?new A(E(`The start_date (%s) must be positive or null.`,r)):i<0?new A(E(`The end_date (%s) must be positive or null.`,i)):0>a||a>4?new A(E(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,a)):xi(r,i,a)}},xg={description:E(`First day of the month preceding a date.`),args:[U(`date (date)`,E(`The date from which to calculate the result.`))],compute:function(e){let t=F(e,this.locale);return{value:hi(new O(t.getFullYear(),t.getMonth(),1)),format:this.locale.dateFormat}}},Sg={description:E(`Last day of the month following a date.`),args:[U(`date (date)`,E(`The date from which to calculate the result.`))],compute:function(e){return ng.compute.bind(this)(e,{value:0})}},Cg={description:E(`Quarter of the year a specific date falls in`),args:[U(`date (date)`,E(`The date from which to extract the quarter.`))],compute:function(e){return Math.ceil((F(e,this.locale).getMonth()+1)/3)}},wg={description:E(`First day of the quarter of the year a specific date falls in.`),args:[U(`date (date)`,E(`The date from which to calculate the start of quarter.`))],compute:function(e){let t=Cg.compute.bind(this)(e);return{value:hi(new O(yg.compute.bind(this)(e),(t-1)*3,1)),format:this.locale.dateFormat}}},Tg={description:E(`Last day of the quarter of the year a specific date falls in.`),args:[U(`date (date)`,E(`The date from which to calculate the end of quarter.`))],compute:function(e){let t=Cg.compute.bind(this)(e);return{value:hi(new O(yg.compute.bind(this)(e),t*3,0)),format:this.locale.dateFormat}}},Eg={description:E(`First day of the year a specific date falls in.`),args:[U(`date (date)`,E(`The date from which to calculate the start of the year.`))],compute:function(e){return{value:hi(new O(yg.compute.bind(this)(e),0,1)),format:this.locale.dateFormat}}},Dg={description:E(`Last day of the year a specific date falls in.`),args:[U(`date (date)`,E(`The date from which to calculate the end of the year.`))],compute:function(e){return{value:hi(new O(yg.compute.bind(this)(e)+1,0,0)),format:this.locale.dateFormat}}};var Og=l({DELTA:()=>kg});let kg={description:E(`Compare two numeric values, returning 1 if they're equal.`),args:[U(`number1 (number)`,E(`The first number to compare.`)),U(`number2 (number, default=0)`,E(`The second number to compare.`))],compute:function(e,t={value:0}){return+(M(e,this.locale)===M(t,this.locale))},isExported:!0},Ag=[`number`,`error`,`text`,`boolean`];function jg(e){let t=e===`asc`?1:-1;return(e,n)=>{if(e.type===`empty`)return n.type===`empty`?0:1;if(n.type===`empty`)return-1;let r=Ag.indexOf(e.type)-Ag.indexOf(n.type);return r===0&&(r=e.type===`text`||e.type===`error`?e.value.localeCompare(n.value):e.value-n.value),t*r}}function Mg(e,t,n){let r=e.map((e,t)=>({index:t,type:e.type,value:e.value}));return(n?r.map(e=>e.type===`empty`?{...e,type:`number`,value:0}:e):r).sort(jg(t))}function Ng(e,t,n,r,i){let a=r.right>r.left;if(e.model.getters.doesIntersectMerge(t,r)){a=!1;let n;for(let i=r.top;i<=r.bottom;i++){n=[];for(let a=r.left;a<=r.right;a++){let r=e.model.getters.getMerge({sheetId:t,col:a,row:i});r&&!n.includes(r.id.toString())&&n.push(r.id.toString())}if(n.length>=2){a=!0;break}}}if(a){Pg(e,t,n,r,i);return}let o=e.model.getters.getContiguousZone(t,r);Es(o,r)?Pg(e,t,n,r,i):e.askConfirmation(E(`We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?`),()=>Pg(e,t,n,o,i),()=>Pg(e,t,n,r,i))}function Pg(e,t,n,r,i,a){let o=e.model.dispatch(`SORT_CELLS`,{sheetId:t,col:n.col,row:n.row,zone:r,sortDirection:i,sortOptions:a});if(o.isCancelledBecause(`InvalidSortZone`)){let{col:t,row:i}=n;e.model.selection.selectZone({cell:{col:t,row:i},zone:r}),e.raiseError(E(`Cannot sort. To sort, select only cells or only merges that have the same size.`))}if(o.isCancelledBecause(`SortZoneWithArrayFormulas`)){let{col:t,row:i}=n;e.model.selection.selectZone({cell:{col:t,row:i},zone:r}),e.raiseError(E(`Cannot sort a zone with array formulas.`))}}var Fg=l({FILTER:()=>Lg,SORT:()=>Rg,SORTN:()=>zg,UNIQUE:()=>Bg});function Ig(e,t,...n){for(let e=0;e<n.length;e++){let t=e%2==0?`sort_column`:`is_ascending`;hu(n[e]!==void 0,E(`Value for parameter %s is missing in [[FUNCTION_NAME]].`,t))}let r=[],i=[],a=e.length;for(let o=0;o<n.length;o+=2){r.push(P(Tu(n[o+1])?.value)?`asc`:`desc`);let s=n[o];if(Or(s)&&(s.length>1||s[0].length>1))hu(s.length===1&&s[0].length===a,E(`Wrong size for %s. Expected a range of size 1x%s. Got %sx%s.`,`sort_column${o+1}`,a,s.length,s[0].length)),i.push(s.flat().map(e=>e.value));else{let n=M(Tu(s)?.value,t);if(n<1||n>e[0].length)return e;i.push(e.map(e=>e[n-1].value))}}if(i.length===0)for(let t=0;t<e[0].length;t++)i.push(e.map(e=>e[t].value)),r.push(`asc`);let o={desc:jg(`desc`),asc:jg(`asc`)},s=S(0,e.length);return s.sort((e,t)=>{for(let[n,a]of i.entries()){let i=a[e],s=a[t],c={value:i,type:i===null?`empty`:typeof i==`string`?`text`:typeof i},l={value:s,type:s===null?`empty`:typeof s==`string`?`text`:typeof s},u=o[r[n]](c,l);if(u!==0)return u}return 0}),s.map(t=>e[t])}let Lg={description:E(`Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions.`),args:[U(`range (any, range<any>)`,E(`The data to be filtered.`)),U(`condition1 (boolean, range<boolean>)`,E(`A column or row containing true or false values corresponding to the first column or row of range.`)),U(`condition2 (boolean, range<boolean>, repeating)`,E(`Additional column or row containing true or false values.`))],compute:function(e,...t){let n=I(e),r=t.map(e=>ha(I(e),e=>e.value));for(let e of r)if(!_u(e))return new A(E(`The arguments condition must be a single column or row.`));if(!vu(...t))return new A(E(`The arguments conditions must have the same dimensions.`));let i=r.map(e=>e.flat()),a=r[0].length===1?`row`:`col`;if(n=a===`row`?_a(n):n,i.some(e=>e.length!==n.length))return new A(E(`FILTER has mismatched sizes on the range and conditions.`));let o=[];for(let e=0;e<n.length;e++){let t=n[e];i.every(t=>(typeof t[e]==`boolean`||typeof t[e]==`number`)&&t[e])&&o.push(t)}return o.length?a===`row`?_a(o):o:new Hi(E(`No match found in FILTER evaluation`))},isExported:!1},Rg={description:E(`Sorts the rows of a given array or range by the values in one or more columns.`),args:[U(`range (range)`,E(`The data to be sorted.`)),U(`sort_column (any, range<number>, repeating)`,E(`The index of the column in range or a range outside of range containing the values by which to sort.`)),U(`is_ascending (boolean, repeating)`,E(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`))],compute:function(e,...t){return _a(Ig(_a(e),this.locale,...t))},isExported:!0},zg={description:E(`Returns the first n items in a data set after performing a sort.`),args:[U(`range (range)`,E(`The data to be sorted.`)),U(`n (number)`,E(`The number of items to return.`)),U(`display_ties_mode (number, default=0)`,E(`A number representing the way to display ties.`)),U(`sort_column (number, range<number>, repeating)`,E(`The index of the column in range or a range outside of range containing the values by which to sort.`)),U(`is_ascending (boolean, repeating)`,E(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`))],compute:function(e,t,...n){let r=M(t?.value??1,this.locale),i=n.length%2==0?0:M(n[0]?.value,this.locale),a=n.length%2==0?n:n.slice(1);if(r<0)return new A(E(`Wrong value of 'n'. Expected a positive number. Got %s.`,r));if(i<0||i>3)return new A(E(`Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.`,i));let o=Ig(_a(e),this.locale,...a),s=(e,t)=>JSON.stringify(o[e].map(e=>e.value))===JSON.stringify(o[t].map(e=>e.value));switch(i){case 0:return _a(o.slice(0,r));case 1:for(let e=r;e<o.length;e++)if(!s(e,r-1))return _a(o.slice(0,e));return _a(o);case 2:{let e=[o[0]];for(let t=1;t<o.length;t++)for(let n=0;n<t&&!s(t,n);n++)n===t-1&&e.push(o[t]);return _a(e.slice(0,r))}case 3:{let e=[o[0]],t=1;for(let n=1;n<o.length&&(s(n,n-1)||t++,!(t>r));n++)e.push(o[n]);return _a(e)}}},isExported:!1},Bg={description:E(`Unique rows in the provided source range.`),args:[U(`range (any, range<any>)`,E(`The data to filter by unique entries.`)),U(`by_column (boolean, default=FALSE)`,E(`Whether to filter the data by columns or by rows.`)),U(`exactly_once (boolean, default=FALSE)`,E(`Whether to return only entries with no duplicates.`))],compute:function(e={value:``},t,n){if(!Or(e))return[[e]];let r=P(t?.value)||!1,i=P(n?.value)||!1;r||(e=_a(e));let a=new Map;for(let t of e){let e=JSON.stringify(t.map(e=>e.value)),n=a.get(e);n?n.count++:a.set(e,{data:t,count:1})}let o=[];for(let e of a.values())i&&e.count>1||o.push(e.data);return o.length?r?o:_a(o):new A(E(`No unique values found`))},isExported:!0},Vg=E(`The cashflow_amounts and cashflow_dates ranges must have the same dimensions.`),Hg=E(`There must be both positive and negative values in cashflow_amounts.`),Ug=e=>E(`The cost (%s) must be positive or null.`,e),Wg=e=>E(`The cost (%s) must be strictly positive.`,e),Gg=e=>E(`The frequency (%s) must be one of %s`,e,[1,2,4].toString()),Kg=e=>E(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,e),qg=e=>E(`The depreciation factor (%s) must be strictly positive.`,e),Jg=e=>E(`The discount (%s) must be different from -1.`,e),Yg=e=>E(`The discount (%s) must be strictly positive.`,e),Xg=e=>E(`The discount (%s) must be smaller than 1.`,e),Zg=e=>E(`The effective_rate (%s) must be strictly positive.`,e),Qg=e=>E(`The end_period (%s) must be positive or null.`,e),$g=(e,t)=>E(`The end_period (%(end)s) must be smaller or equal to the life (%(life)s).`,{end:e,life:t}),e_=e=>E(`All the dates should be greater or equal to the first date in cashflow_dates (%s).`,e),t_=(e,t)=>E(`The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).`,{first:e,last:t}),n_=e=>E(`The first_period (%s) must be strictly positive.`,e),r_=e=>E(`The future_value (%s) must be strictly positive.`,e),i_=e=>E(`The investment (%s) must be strictly positive.`,e),a_=e=>E(`The issue (%s) must be positive or null.`,e),o_=(e,t)=>E(`The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).`,{last:e,nPeriods:t}),s_=e=>E(`The last_period (%s) must be strictly positive.`,e),c_=e=>E(`The life (%s) must be strictly positive.`,e),l_=(e,t)=>E(`The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).`,{maturity:t,settlement:e}),u_=e=>E(`The month (%s) must be between 1 and 12 inclusive.`,e),d_=e=>E(`The nominal_rate (%s) must be strictly positive.`,e),f_=e=>E(`The number_of_periods (%s) must be different from zero.`,e),p_=e=>E(`The number_of_periods (%s) must be strictly positive.`,e),m_=e=>E(`The period must be between 1 and number_of_periods (%s)`,e),h_=(e,t)=>E(`The period (%(period)s) must be less than or equal to %(lifeLimit)s.`,{period:e,lifeLimit:t}),g_=e=>E(`The period (%s) must be positive or null.`,e),__=e=>E(`The periods_by_year (%s) must be strictly positive.`,e),v_=(e,t)=>E(`The period (%(period)s) must be less than or equal life (%(life)s).`,{period:e,life:t}),y_=e=>E(`The period (%s) must be strictly positive.`,e),b_=e=>E(`The present_value (%s) must be strictly positive.`,e),x_=e=>E(`The price (%s) must be strictly positive.`,e),S_=(e,t)=>E(`The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).`,{purchaseDate:e,firstPeriodEnd:t}),C_=e=>E(`The purchase_date (%s) must be positive or null.`,e),w_=e=>E(`The rate_guess (%s) must be strictly greater than -1.`,e),T_=e=>E(`The rate (%s) must be positive or null.`,e),E_=e=>E(`The rate (%s) must be strictly positive.`,e),D_=e=>E(`The redemption (%s) must be strictly positive.`,e),O_=e=>E(`The salvage (%s) must be positive or null.`,e),k_=(e,t)=>E(`The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).`,{salvage:e,cost:t}),A_=(e,t)=>E(`The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).`,{settlement:e,issue:t}),j_=(e,t)=>E(`The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).`,{settlement:e,maturity:t}),M_=(e,t)=>E(`The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).`,{settlement:e,issue:t}),N_=e=>E(`The start_period (%s) must be positive or null.`,e),P_=(e,t)=>E(`The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).`,{start:e,end:t}),F_=e=>E(`The unit (%s) must be strictly positive.`,e),I_=e=>E(`The yield (%s) must be positive or null.`,e);function L_(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function R_(e){return![0,1,2,3,4].includes(e)}function z_(e){return![1,2,4].includes(e)}function B_(e,t,n){let r=F(e,n),i=F(t,n),a=F(e,n);return a.setFullYear(r.getFullYear()+1),i.getTime()<=a.getTime()}var V_=l({ACCRINTM:()=>W_,AMORLINC:()=>G_,COUPDAYBS:()=>q_,COUPDAYS:()=>K_,COUPDAYSNC:()=>J_,COUPNCD:()=>Y_,COUPNUM:()=>X_,COUPPCD:()=>Z_,CUMIPMT:()=>Q_,CUMPRINC:()=>$_,DB:()=>ev,DDB:()=>nv,DISC:()=>rv,DOLLARDE:()=>iv,DOLLARFR:()=>av,DURATION:()=>ov,EFFECT:()=>sv,FV:()=>lv,FVSCHEDULE:()=>uv,INTRATE:()=>dv,IPMT:()=>pv,IRR:()=>hv,ISPMT:()=>gv,MDURATION:()=>_v,MIRR:()=>vv,NOMINAL:()=>yv,NPER:()=>bv,NPV:()=>Sv,PDURATION:()=>Cv,PMT:()=>Tv,PPMT:()=>Dv,PRICE:()=>kv,PRICEDISC:()=>Av,PRICEMAT:()=>jv,PV:()=>Ov,RATE:()=>Nv,RECEIVED:()=>Pv,RRI:()=>Fv,SLN:()=>Iv,SYD:()=>Lv,TBILLEQ:()=>Bv,TBILLPRICE:()=>zv,TBILLYIELD:()=>Vv,VDB:()=>Hv,XIRR:()=>Uv,XNPV:()=>Wv,YIELD:()=>Gv,YIELDDISC:()=>Kv,YIELDMAT:()=>qv});let H_=[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))];function U_(e,t,n,r,i=1e-10,a){let o=n,s,c,l,u=!1,d=0,f;do{if(l=e(o),isNaN(l)){hu(d<r&&a!==void 0,E(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++,o=a(f),f=o;continue}s=o-l/t(o),c=Math.abs(s-o),o=s,u=c<i||Math.abs(l)<i,hu(d<r,E(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++}while(!u);return o}let W_={description:E(`Accrued interest of security paying at maturity.`),args:[U(`issue (date)`,E(`The date the security was initially issued.`)),U(`maturity (date)`,E(`The maturity date of the security.`)),U(`rate (number)`,E(`The annualized rate of interest.`)),U(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(r,this.locale),c=M(n,this.locale),l=Math.trunc(M(i,this.locale));if(a<0)return new A(a_(a));if(a>=o)return new A(l_(a,o));if(R_(l))return new A(Kg(l));if(s<=0)return new A(D_(s));if(c<=0)return new A(E_(c));let u=xi(a,o,l);return s*c*u},isExported:!0},G_={description:E(`Depreciation for an accounting period.`),args:[U(`cost (number)`,E(`The initial cost of the asset.`)),U(`purchase_date (date)`,E(`The date the asset was purchased.`)),U(`first_period_end (date)`,E(`The date the first period ended.`)),U(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),U(`period (number)`,E(`The single period within life for which to calculate depreciation.`)),U(`rate (number)`,E(`The deprecation rate.`)),U(`day_count_convention (number, optional)`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=M(e,this.locale),c=Math.trunc(M(t,this.locale)),l=Math.trunc(M(n,this.locale)),u=M(r,this.locale),d=M(i,this.locale),f=M(a,this.locale),p=Math.trunc(M(o,this.locale));if(s<=0)return new A(Wg(s));if(c<0)return new A(C_(c));if(u<0)return new A(O_(u));if(u>s)return new A(k_(u,s));if(d<0)return new A(g_(d));if(f<=0)return new A(E_(f));if(R_(p))return new A(Kg(p));if(c>l)return new A(S_(c,l));let m=d<1&&d>0?1:Math.trunc(d),h=s*f,g=xi(c,l,p),_=c===l?h:h*g,v=s-_-h*m;return v>=u?m===0?_:h:u-v<h?h-(u-v):0},isExported:!0},K_={description:E(`Days in coupon period containing settlement date.`),args:H_,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A(l_(i,a));if(z_(o))return new A(Gg(o));if(R_(s))return new A(Kg(s));if(s===1){let i=Z_.compute.bind(this)(e,t,n,r).value,a=Y_.compute.bind(this)(e,t,n,r).value;return M(a,this.locale)-M(i,this.locale)}return(s===3?365:360)/o},isExported:!0},q_={description:E(`Days from settlement until next coupon.`),args:H_,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A(l_(i,a));if(z_(o))return new A(Gg(o));if(R_(s))return new A(Kg(s));let c=Z_.compute.bind(this)(e,t,n,r).value,l=M(c,this.locale);if([1,2,3].includes(s))return i-l;if(s===4){let e=xi(l,i,s);return Math.round(e*360)}let u=F(i,this.locale),d=F(l,this.locale),f=d.getFullYear(),p=u.getFullYear(),m=d.getMonth()+1,h=u.getMonth()+1,g=d.getDate(),_=u.getDate();return m===2&&h===2&&vi(d)&&vi(u)&&(_=30),_===31&&(g===30||g===31)&&(_=30),m===2&&vi(d)&&(g=30),g===31&&(g=30),(p-f)*360+(h-m)*30+(_-g)},isExported:!0},J_={description:E(`Days from settlement until next coupon.`),args:H_,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A(l_(i,a));if(z_(o))return new A(Gg(o));if(R_(s))return new A(Kg(s));let c=Y_.compute.bind(this)(e,t,n,r).value,l=M(c,this.locale);if([1,2,3].includes(s))return l-i;if(s===4){let e=xi(i,l,s);return Math.round(e*360)}let u=q_.compute.bind(this)(e,t,n,r);return M(K_.compute.bind(this)(e,t,n,r),this.locale)-M(u,this.locale)},isExported:!0},Y_={description:E(`Next coupon date after the settlement date.`),args:H_,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A(l_(i,a));if(z_(o))return new A(Gg(o));if(R_(s))return new A(Kg(s));let c=12/o,l=X_.compute.bind(this)(e,t,n,r);return{value:hi(yi(F(a,this.locale),-(M(l,this.locale)-1)*c,!0)),format:this.locale.dateFormat}},isExported:!0},X_={description:E(`Number of coupons between settlement and maturity.`),args:H_,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A(l_(i,a));if(z_(o))return new A(Gg(o));if(R_(s))return new A(Kg(s));let c=1,l=a,u=12/o;for(;l>i;)l=hi(yi(F(l,this.locale),-u,!1)),c++;return c-1},isExported:!0},Z_={description:E(`Last coupon date prior to or on the settlement date.`),args:H_,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A(l_(i,a));if(z_(o))return new A(Gg(o));if(R_(s))return new A(Kg(s));let c=12/o,l=X_.compute.bind(this)(e,t,n,r);return{value:hi(yi(F(a,this.locale),-l*c,!0)),format:this.locale.dateFormat}},isExported:!0},Q_={description:E(`Cumulative interest paid over a set of periods.`),args:[U(`rate (number)`,E(`The interest rate.`)),U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`present_value (number)`,E(`The current value of the annuity.`)),U(`first_period (number)`,E(`The number of the payment period to begin the cumulative calculation.`)),U(`last_period (number)`,E(`The number of the payment period to end the cumulative calculation.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`))],compute:function(e,t,n,r,i,a={value:0}){let o=M(r,this.locale),s=M(i,this.locale),c=M(e,this.locale),l=M(n,this.locale),u=M(t,this.locale),d=+!!P(a);if(u<=0)return new A(p_(u));if(o<=0)return new A(n_(o));if(s<=0)return new A(s_(s));if(o>s)return new A(t_(o,s));if(s>u)return new A(o_(s,u));if(c<=0)return new A(E_(c));if(l<=0)return new A(b_(l));let f=0;for(let e=o;e<=s;e++)f+=fv(c,e,u,l,0,d);return f},isExported:!0},$_={description:E(`Cumulative principal paid over a set of periods.`),args:[U(`rate (number)`,E(`The interest rate.`)),U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`present_value (number)`,E(`The current value of the annuity.`)),U(`first_period (number)`,E(`The number of the payment period to begin the cumulative calculation.`)),U(`last_period (number)`,E(`The number of the payment period to end the cumulative calculation.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`))],compute:function(e,t,n,r,i,a={value:0}){let o=M(r,this.locale),s=M(i,this.locale),c=M(e,this.locale),l=M(n,this.locale),u=M(t,this.locale),d=+!!P(a);if(u<=0)return new A(p_(u));if(o<=0)return new A(n_(o));if(s<=0)return new A(s_(s));if(o>s)return new A(t_(o,s));if(s>u)return new A(o_(s,u));if(c<=0)return new A(E_(c));if(l<=0)return new A(b_(l));let f=0;for(let e=o;e<=s;e++)f+=Ev(c,e,u,l,0,d);return f},isExported:!0},ev={description:E(`Depreciation via declining balance method.`),args:[U(`cost (number)`,E(`The initial cost of the asset.`)),U(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),U(`life (number)`,E(`The number of periods over which the asset is depreciated.`)),U(`period (number)`,E(`The single period within life for which to calculate depreciation.`)),U(`month (number, optional)`,E(`The number of months in the first year of depreciation.`))],compute:function(e,t,n,r,...i){let a=M(e,this.locale),o=M(t,this.locale),s=M(n,this.locale),c=Math.trunc(M(r,this.locale)),l=i.length?Math.trunc(M(i[0],this.locale)):12,u=s+(l===12?0:1);if(a<0)return new A(Ug(a));if(o<0)return new A(O_(o));if(c<=0)return new A(y_(c));if(s<=0)return new A(c_(s));if(1>l||l>12)return new A(u_(l));if(c>u)return new A(h_(c,u));let d=l/12,f=1-(o/a)**(1/s);f=Math.round(f*1e3)/1e3;let p=a,m=a*(1-f*d);for(let e=1;e<c;e++)p=m,m=p*(1-f),e===s&&(m=p*(1-f*(1-d)));return{value:p-m,format:`#,##0.00`}},isExported:!0},tv=`#,##0.00`,nv={description:E(`Depreciation via double-declining balance method.`),args:[U(`cost (number)`,E(`The initial cost of the asset.`)),U(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),U(`life (number)`,E(`The number of periods over which the asset is depreciated.`)),U(`period (number)`,E(`The single period within life for which to calculate depreciation.`)),U(`factor (number, default=2)`,E(`The factor by which depreciation decreases.`))],compute:function(e,t,n,r,i={value:2}){let a=M(e,this.locale),o=M(t,this.locale),s=M(n,this.locale),c=M(r,this.locale),l=M(i,this.locale);if(a<0)return new A(Ug(a));if(o<0)return new A(O_(o));if(c<=0)return new A(y_(c));if(s<=0)return new A(c_(s));if(c>s)return new A(v_(c,s));if(l<=0)return new A(qg(l));if(a===0||o>=a)return{value:0,format:tv};let u=l/s;if(u>1)return{value:c===1?a-o:0,format:tv};if(c<=1)return{value:a*u,format:tv};let d=a*(1-u)**(c-1),f=a*(1-u)**c,p=f<o?d-o:d-f;return{value:Math.max(p,0),format:tv}},isExported:!0},rv={description:E(`Discount rate of a security based on price.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`price (number)`,E(`The price at which the security is bought per 100 face value.`)),U(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(n,this.locale),c=M(r,this.locale),l=Math.trunc(M(i,this.locale));if(a>=o)return new A(l_(a,o));if(R_(l))return new A(Kg(l));if(s<=0)return new A(x_(s));if(c<=0)return new A(D_(c));let u=xi(a,o,l);return(c-s)/c/u},isExported:!0},iv={description:E(`Convert a decimal fraction to decimal value.`),args:[U(`fractional_price (number)`,E(`The price quotation given using fractional decimal conventions.`)),U(`unit (number)`,E(`The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=M(e,this.locale),r=Math.trunc(M(t,this.locale));if(r<=0)return new A(F_(r));let i=Math.trunc(n);return i+(n-i)*(10**Math.ceil(Math.log10(r))/r)},isExported:!0},av={description:E(`Convert a decimal value to decimal fraction.`),args:[U(`decimal_price (number)`,E(`The price quotation given as a decimal value.`)),U(`unit (number)`,E(`The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=M(e,this.locale),r=Math.trunc(M(t,this.locale));if(r<=0)return new A(F_(r));let i=Math.trunc(n);return i+(n-i)*(r/10**Math.ceil(Math.log10(r)))},isExported:!0},ov={description:E(`Number of periods for an investment to reach a value.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`rate (number)`,E(`The annualized rate of interest.`)),U(`yield (number)`,E(`The expected annual yield of the security.`)),U(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){let o=Math.trunc(M(e,this.locale)),s=Math.trunc(M(t,this.locale)),c=M(n,this.locale),l=M(r,this.locale),u=Math.trunc(M(i,this.locale)),d=Math.trunc(M(a,this.locale));if(o>=s)return new A(l_(o,s));if(z_(u))return new A(Gg(u));if(R_(d))return new A(Kg(d));if(c<0)return new A(T_(c));if(l<0)return new A(I_(l));let f=xi(o,s,d),p=f-Math.trunc(f)||1/u,m=Math.ceil(f*u),h=c/u,g=l/u,_=0,v=0;for(let e=1;e<=m;e++){let t=(h+ +(e===m))/(1+g)**e;v+=(p+(e-1)/u)*t,_+=t}return _===0?0:v/_},isExported:!0},sv={description:E(`Annual effective interest rate.`),args:[U(`nominal_rate (number)`,E(`The nominal interest rate per year.`)),U(`periods_per_year (number)`,E(`The number of compounding periods per year.`))],compute:function(e,t){let n=M(e,this.locale),r=Math.trunc(M(t,this.locale));return n<=0?new A(d_(n)):r<=0?new A(__(r)):(1+n/r)**+r-1},isExported:!0};function cv(e,t,n,r,i){return e===0?-(r+n*t):-r*(1+e)**t-n*(1+e*i)*((1+e)**t-1)/e}let lv={description:E(`Future value of an annuity investment.`),args:[U(`rate (number)`,E(`The interest rate.`)),U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`payment_amount (number)`,E(`The amount per period to be paid.`)),U(`present_value (number, default=0)`,E(`The current value of the annuity.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`))],compute:function(e,t,n,r={value:0},i={value:0}){return r||=0,i||=0,{value:cv(M(e,this.locale),M(t,this.locale),M(n,this.locale),M(r,this.locale),+!!P(i)),format:`#,##0.00`}},isExported:!0},uv={description:E(`Future value of principal from series of rates.`),args:[U(`principal (number)`,E(`The amount of initial capital or value to compound against.`)),U(`rate_schedule (number, range<number>)`,E(`A series of interest rates to compound against the principal.`))],compute:function(e,t){let n=M(e,this.locale);return da([t],(e,t)=>e*(1+M(t,this.locale)),n)},isExported:!0},dv={description:E(`Calculates effective interest rate.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`investment (number)`,E(`The amount invested in the security.`)),U(`redemption (number)`,E(`The amount to be received at maturity.`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(r,this.locale),c=M(n,this.locale),l=Math.trunc(M(i,this.locale));if(a>=o)return new A(l_(a,o));if(c<=0)return new A(i_(c));if(s<=0)return new A(D_(s));if(R_(l))return new A(Kg(l));let u=xi(a,o,l);return(s-c)/c/u},isExported:!0};function fv(e,t,n,r,i,a){return wv(e,n,r,i,a)-Ev(e,t,n,r,i,a)}let pv={description:E(`Payment on the principal of an investment.`),args:[U(`rate (number)`,E(`The annualized rate of interest.`)),U(`period (number)`,E(`The amortization period, in terms of number of periods.`)),U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`present_value (number)`,E(`The current value of the annuity.`)),U(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`))],compute:function(e,t,n,r,i={value:0},a={value:0}){return{value:fv(M(e,this.locale),M(t,this.locale),M(n,this.locale),M(r,this.locale),M(i,this.locale),+!!P(a)),format:`#,##0.00`}},isExported:!0},mv=.1,hv={description:E(`Internal rate of return given periodic cashflows.`),args:[U(`cashflow_amounts (number, range<number>)`,E(`An array or range containing the income or payments associated with the investment.`)),U(`rate_guess (number, default=${mv})`,E(`An estimate for what the internal rate of return will be.`))],compute:function(e,t={value:mv}){let n=M(t,this.locale);if(n<=-1)return new A(w_(n));let r=!1,i=!1,a=[];if(la([e],({value:e})=>{e>0&&(r=!0),e<0&&(i=!0),a.push(e)},this.locale),!r||!i)return new A(Hg);let o=a.shift();function s(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*e**(r-i)),t*e**r)}function c(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*(r-i)*e**(r-i-1)),t*r*e**(r-1))}function l(e){return s(e,o,a)}function u(e){return c(e,o,a)}return{value:U_(l,u,n+1,20,1e-5)-1,format:`0%`}},isExported:!0},gv={description:E(`Returns the interest paid at a particular period of an investment.`),args:[U(`rate (number)`,E(`The interest rate.`)),U(`period (number)`,E(`The period for which you want to view the interest payment.`)),U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`present_value (number)`,E(`The current value of the annuity.`))],compute:function(e,t,n,r){let i=M(e,this.locale),a=M(t,this.locale),o=M(n,this.locale),s=M(r,this.locale);return o===0?new A(f_(o)):-1*(s-a/o*s)*i},isExported:!0},_v={description:E(`Modified Macaulay duration.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`rate (number)`,E(`The annualized rate of interest.`)),U(`yield (number)`,E(`The expected annual yield of the security.`)),U(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){let o=ov.compute.bind(this)(e,t,n,r,i,a),s=M(r,this.locale),c=Math.trunc(M(i,this.locale));return M(o,this.locale)/(1+s/c)},isExported:!0},vv={description:E(`Modified internal rate of return.`),args:[U(`cashflow_amounts (range<number>)`,E(`A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.`)),U(`financing_rate (number)`,E(`The interest rate paid on funds invested.`)),U(`reinvestment_return_rate (number)`,E(`The return (as a percentage) earned on reinvestment of income received from the investment.`))],compute:function(e,t,n){let r=M(t,this.locale),i=M(n,this.locale),a=_a(e).flat().filter(e=>e.value!==null).map(e=>M(e,this.locale)),o=a.length,s=0,c=0;for(let e of S(0,o)){let t=a[e];t>=0?s+=t*(i+1)**(o-e-1):c+=t/(r+1)**e}if(c===0||s===0)return new A(Hg);let l=1/(o-1);return(-s/c)**l-1},isExported:!0},yv={description:E(`Annual nominal interest rate.`),args:[U(`effective_rate (number)`,E(`The effective interest rate per year.`)),U(`periods_per_year (number)`,E(`The number of compounding periods per year.`))],compute:function(e,t){let n=M(e,this.locale),r=Math.trunc(M(t,this.locale));return n<=0?new A(Zg(n)):r<=0?new A(__(r)):((n+1)**(1/r)-1)*r},isExported:!0},bv={description:E(`Number of payment periods for an investment.`),args:[U(`rate (number)`,E(`The interest rate.`)),U(`payment_amount (number)`,E(`The amount of each payment made.`)),U(`present_value (number)`,E(`The current value of the annuity.`)),U(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`))],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=M(e,this.locale),o=M(t,this.locale),s=M(n,this.locale),c=M(r,this.locale),l=+!!P(i);if(a===0)return-(c+s)/o;let u=o*(1+a*l)/a;return Math.log((u-c)/(s+u))/Math.log(1+a)},isExported:!0};function xv(e,t,n,r){let i=0;return fa(n,(t,n)=>(i++,t+n/(1+e)**i),t,r)}let Sv={description:E(`The net present value of an investment based on a series of periodic cash flows and a discount rate.`),args:[U(`discount (number)`,E(`The discount rate of the investment over one period.`)),U(`cashflow1 (number, range<number>)`,E(`The first future cash flow.`)),U(`cashflow2 (number, range<number>, repeating)`,E(`Additional future cash flows.`))],compute:function(e,...t){let n=M(e,this.locale);return n===-1?new A(Jg(n)):{value:xv(n,0,t,this.locale),format:`#,##0.00`}},isExported:!0},Cv={description:E(`Computes the number of periods needed for an investment to reach a value.`),args:[U(`rate (number)`,E(`The rate at which the investment grows each period.`)),U(`present_value (number)`,E(`The investment's current value.`)),U(`future_value (number)`,E(`The investment's desired future value.`))],compute:function(e,t,n){let r=M(e,this.locale),i=M(t,this.locale),a=M(n,this.locale);return r<=0?new A(E_(r)):i<=0?new A(b_(i)):a<=0?new A(r_(a)):(Math.log(a)-Math.log(i))/Math.log(1+r)},isExported:!0};function wv(e,t,n,r,i){if(t<=0)throw new A(p_(t));if(e===0)return-(r+n)/t;let a=-(n*(1+e)**t+r);return a=a*e/((1+e*i)*((1+e)**t-1)),a}let Tv={description:E(`Periodic payment for an annuity investment.`),args:[U(`rate (number)`,E(`The annualized rate of interest.`)),U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`present_value (number)`,E(`The current value of the annuity.`)),U(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`))],compute:function(e,t,n,r={value:0},i={value:0}){let a=M(t,this.locale),o=M(e,this.locale),s=+!!P(i),c=M(r,this.locale);return{value:wv(o,a,M(n,this.locale),c,s),format:`#,##0.00`}},isExported:!0};function Ev(e,t,n,r,i,a){if(n<=0)throw new A(p_(n));if(t<=0||t>n)throw new A(m_(n));let o=wv(e,n,r,i,a);return a===1&&t===1?o:o+-cv(e,a===0?t-1:t-2,o,r+o*a,0)*e}let Dv={description:E(`Payment on the principal of an investment.`),args:[U(`rate (number)`,E(`The annualized rate of interest.`)),U(`period (number)`,E(`The amortization period, in terms of number of periods.`)),U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`present_value (number)`,E(`The current value of the annuity.`)),U(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`))],compute:function(e,t,n,r,i={value:0},a={value:0}){let o=M(n,this.locale),s=M(e,this.locale),c=M(t,this.locale),l=+!!P(a),u=M(i,this.locale);return{value:Ev(s,c,o,M(r,this.locale),u,l),format:`#,##0.00`}},isExported:!0},Ov={description:E(`Present value of an annuity investment.`),args:[U(`rate (number)`,E(`The interest rate.`)),U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`payment_amount (number)`,E(`The amount per period to be paid.`)),U(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`))],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=M(e,this.locale),o=M(t,this.locale),s=M(n,this.locale),c=M(r,this.locale),l=+!!P(i);return{value:a?-(s*(1+a*l)*((1+a)**o-1)/a+c)/(1+a)**o:-(c+s*o),format:`#,##0.00`}},isExported:!0},kv={description:E(`Price of a security paying periodic interest.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`rate (number)`,E(`The annualized rate of interest.`)),U(`yield (number)`,E(`The expected annual yield of the security.`)),U(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),U(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(M(e,this.locale)),c=Math.trunc(M(t,this.locale)),l=M(n,this.locale),u=M(r,this.locale),d=M(i,this.locale),f=Math.trunc(M(a,this.locale)),p=Math.trunc(M(o,this.locale));if(s>=c)return new A(l_(s,c));if(z_(f))return new A(Gg(f));if(R_(p))return new A(Kg(p));if(l<0)return new A(T_(l));if(u<0)return new A(I_(u));if(d<=0)return new A(D_(d));let m=xi(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=1+u/f,v=100*l/f;if(h===1)return(v+d)/(g*u/f+1)-v*(1-g);let y=0;for(let e=1;e<=h;e++)y+=v/_**(e-1+g);return d/_**(h-1+g)+y-v*(1-g)},isExported:!0},Av={description:E(`Price of a discount security.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`discount (number)`,E(`The discount rate of the security at time of purchase.`)),U(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(n,this.locale),c=M(r,this.locale),l=Math.trunc(M(i,this.locale));if(a>=o)return new A(l_(a,o));if(R_(l))return new A(Kg(l));if(s<=0)return new A(Yg(s));if(c<=0)return new A(D_(c));let u=xi(a,o,l);return c-s*c*u},isExported:!0},jv={description:E(`Calculates the price of a security paying interest at maturity, based on expected yield.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`issue (date)`,E(`The date the security was initially issued.`)),U(`rate (number)`,E(`The annualized rate of interest.`)),U(`yield (number)`,E(`The expected annual yield of the security.`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(M(e,this.locale)),s=Math.trunc(M(t,this.locale)),c=Math.trunc(M(n,this.locale)),l=M(r,this.locale),u=M(i,this.locale),d=Math.trunc(M(a,this.locale));if(o<=c)return new A(M_(o,c));if(o>=s)return new A(l_(o,s));if(R_(d))return new A(Kg(d));if(l<0)return new A(T_(l));if(u<0)return new A(I_(u));let f=xi(o,s,d),p=xi(o,c,d),m=100+xi(c,s,d)*l*100,h=1+f*u,g=p*l*100;return m/h-g},isExported:!0},Mv=.1,Nv={description:E(`Interest rate of an annuity investment.`),args:[U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`payment_per_period (number)`,E(`The amount per period to be paid.`)),U(`present_value (number)`,E(`The current value of the annuity.`)),U(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`)),U(`rate_guess (number, default=${Mv})`,E(`An estimate for what the interest rate will be.`))],compute:function(e,t,n,r={value:0},i={value:0},a={value:Mv}){let o=M(e,this.locale),s=M(t,this.locale),c=+!!P(i),l=M(a,this.locale)||Mv,u=M(r,this.locale),d=M(n,this.locale);return o<=0?new A(p_(o)):L_([s,d,u])?l<=-1?new A(w_(l)):(u-=s*c,d+=s*c,{value:U_(e=>{let t=(1+e)**+o,n=(t-1)/e;return u+d*t+s*n},e=>{let t=(1+e)**(o-1),n=((1+e)**+o-1)/e,r=o*t/e-n/e;return d*o*t+s*r},l,40,1e-5),format:`0%`}):new A(E(`There must be both positive and negative values in [payment_amount, present_value, future_value].`))},isExported:!0},Pv={description:E(`Amount received at maturity for a security.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`investment (number)`,E(`The amount invested (irrespective of face value of each security).`)),U(`discount (number)`,E(`The discount rate of the security invested in.`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(n,this.locale),c=M(r,this.locale),l=Math.trunc(M(i,this.locale));return a>=o?new A(l_(a,o)):R_(l)?new A(Kg(l)):s<=0?new A(i_(s)):c<=0?new A(Yg(c)):s/(1-c*xi(a,o,l))},isExported:!0},Fv={description:E(`Computes the rate needed for an investment to reach a specific value within a specific number of periods.`),args:[U(`number_of_periods (number)`,E(`The number of periods.`)),U(`present_value (number)`,E(`The present value of the investment.`)),U(`future_value (number)`,E(`The future value of the investment.`))],compute:function(e,t,n){let r=M(e,this.locale),i=M(t,this.locale),a=M(n,this.locale);return r<=0?new A(p_(r)):(a/i)**(1/r)-1},isExported:!0},Iv={description:E(`Depreciation of an asset using the straight-line method.`),args:[U(`cost (number)`,E(`The initial cost of the asset.`)),U(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),U(`life (number)`,E(`The number of periods over which the asset is depreciated.`))],compute:function(e,t,n){let r=M(e,this.locale),i=M(t,this.locale),a=M(n,this.locale);return{value:(r-i)/a,format:`#,##0.00`}},isExported:!0},Lv={description:E(`Depreciation via sum of years digit method.`),args:[U(`cost (number)`,E(`The initial cost of the asset.`)),U(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),U(`life (number)`,E(`The number of periods over which the asset is depreciated.`)),U(`period (number)`,E(`The single period within life for which to calculate depreciation.`))],compute:function(e,t,n,r){let i=M(e,this.locale),a=M(t,this.locale),o=M(n,this.locale),s=M(r,this.locale);if(s<=0)return new A(y_(s));if(o<=0)return new A(c_(o));if(s>o)return new A(v_(s,o));let c=o*(o+1)/2,l=o-s+1;return{value:(i-a)*(l/c),format:`#,##0.00`}},isExported:!0};function Rv(e,t,n){return 100*(1-n*xi(e,t,2))}let zv={description:E(`Price of a US Treasury bill.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`discount (number)`,E(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=M(n,this.locale);return r>=i?new A(l_(r,i)):B_(r,i,this.locale)?a<=0?new A(Yg(a)):a>=1?new A(Xg(a)):Rv(r,i,a):new A(j_(r,i))},isExported:!0},Bv={description:E(`Equivalent rate of return for a US Treasury bill.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`discount (number)`,E(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=M(n,this.locale);if(r>=i)return new A(l_(r,i));if(!B_(r,i,this.locale))return new A(j_(r,i));if(a<=0)return new A(Yg(a));if(a>=1)return new A(Xg(a));let o=$h.compute.bind(this)({value:i},{value:r});if(o<=182)return 365*a/(360-a*o);let s=Rv(r,i,a)/100,c=o/(o===366?366:365);return(-2*c+2*Math.sqrt(c**2-(2*c-1)*(1-1/s)))/(2*c-1)},isExported:!0},Vv={description:E(`The yield of a US Treasury bill based on price.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`price (number)`,E(`The price at which the security is bought per 100 face value.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=M(n,this.locale);if(r>=i)return new A(l_(r,i));if(!B_(r,i,this.locale))return new A(j_(r,i));if(a<=0)return new A(x_(a));let o=xi(r,i,2);return(100-a)/a*(1/o)},isExported:!0},Hv={description:E(`Variable declining balance. WARNING : does not handle decimal periods.`),args:[U(`cost (number)`,E(`The initial cost of the asset.`)),U(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),U(`life (number)`,E(`The number of periods over which the asset is depreciated.`)),U(`start (number)`,E(`Starting period to calculate depreciation.`)),U(`end (number)`,E(`Ending period to calculate depreciation.`)),U(`factor (number, default=2)`,E(`The number of months in the first year of depreciation.`)),U(`no_switch (number, default=false)`,E(`Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.`))],compute:function(e,t,n,r,i,a={value:2},o={value:!1}){a||=0;let s=M(e,this.locale),c=M(t,this.locale),l=M(n,this.locale),u=Math.trunc(M(r,this.locale)),d=Math.trunc(M(i,this.locale)),f=M(a,this.locale),p=P(o);if(s<0)return new A(Ug(s));if(c<0)return new A(O_(c));if(l<=0)return new A(c_(l));if(u<0)return new A(N_(u));if(d<0)return new A(Qg(d));if(u>d)return new A(P_(u,d));if(d>l)return new A($g(d,l));if(f<=0)return new A(qg(f));if(s===0)return 0;if(c>=s)return u<1?s-c:0;let m=f/l;if(m>=1)return u<1?s-c:0;let h=s,g=0,_=0,v=!1;for(let e=0;e<d;e++){if(!v||p){let t=h*m,n=l-e,r=(h-c)/n;!p&&r>t?(v=!0,g=r):g=t}let t=Math.max(h-g,c);e>=u&&(_+=h-t),h=t}return _},isExported:!0},Uv={description:E(`Internal rate of return given non-periodic cash flows.`),args:[U(`cashflow_amounts (range<number>)`,E(`An range containing the income or payments associated with the investment.`)),U(`cashflow_dates (range<number>)`,E(`An range with dates corresponding to the cash flows in cashflow_amounts.`)),U(`rate_guess (number, default=${Mv})`,E(`An estimate for what the internal rate of return will be.`))],compute:function(e,t,n={value:Mv}){let r=M(n,this.locale);if(!vu(e,t))return new A(Vg);let i=e.flat().map(e=>M(e,this.locale)),a=t.flat().map(e=>M(e,this.locale));if(!L_(i))return new A(Hg);if(a.some(e=>e<a[0]))return new A(e_(a[0]));if(r<=-1)return new A(w_(r));let o=new Map;for(let e of S(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e));return U_(e=>{let t=c[0];for(let n of S(1,c.length)){let r=(s[0]-s[n])/365;t+=c[n]*(1+e)**r}return t},e=>{let t=0;for(let n of S(1,c.length)){let r=(s[0]-s[n])/365;t+=r*c[n]*(1+e)**(r-1)}return t},r,40,1e-5,e=>e?e/10-.9:-.9)},isExported:!0},Wv={description:E(`Net present value given to non-periodic cash flows..`),args:[U(`discount (number)`,E(`The discount rate of the investment over one period.`)),U(`cashflow_amounts (number, range<number>)`,E(`An range containing the income or payments associated with the investment.`)),U(`cashflow_dates (number, range<number>)`,E(`An range with dates corresponding to the cash flows in cashflow_amounts.`))],compute:function(e,t,n){let r=M(e,this.locale);if(!vu(t,n))return new A(Vg);let i=I(t).flat().map(e=>ea(e,this.locale)),a=I(n).flat().map(e=>ea(e,this.locale));if(a.some(e=>e<a[0]))return new A(e_(a[0]));if(r<=0)return new A(E_(r));if(i.length===1)return i[0];let o=new Map;for(let e of S(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e)),l=c[0];for(let e of S(1,c.length)){let t=(s[0]-s[e])/365;l+=c[e]*(1+r)**t}return l},isExported:!0},Gv={description:E(`Annual yield of a security paying periodic interest.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`rate (number)`,E(`The annualized rate of interest.`)),U(`price (number)`,E(`The price at which the security is bought per 100 face value.`)),U(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),U(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(M(e,this.locale)),c=Math.trunc(M(t,this.locale)),l=M(n,this.locale),u=M(r,this.locale),d=M(i,this.locale),f=Math.trunc(M(a,this.locale)),p=Math.trunc(M(o,this.locale));if(s>=c)return new A(l_(s,c));if(z_(f))return new A(Gg(f));if(R_(p))return new A(Kg(p));if(l<0)return new A(T_(l));if(u<=0)return new A(x_(u));if(d<=0)return new A(D_(d));let m=xi(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=100*l/f;if(h===1){let e=u+_*(1-g);return(d+_-e)*f*(1/g)/e}function v(e,t,n,r,i,a){let o=a-(e+i*(1-t))*r**(n-1+t);for(let e=1;e<=n;e++)o+=i*r**(e-1);return o}function y(e,t,n,r,i){let a=-(e+i*(1-t))*(n-1+t)*r**(n-2+t);for(let e=1;e<=n;e++)a+=i*(e-1)*r**(e-2);return a}function ee(e){return v(u,g,h,e,_,d)}function te(e){return y(u,g,h,e,_)}return(U_(ee,te,1+(l+1)/f,100,1e-5)-1)*f},isExported:!0},Kv={description:E(`Annual yield of a discount security.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`price (number)`,E(`The price at which the security is bought per 100 face value.`)),U(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(n,this.locale),c=M(r,this.locale),l=Math.trunc(M(i,this.locale));if(a>=o)return new A(l_(a,o));if(R_(l))return new A(Kg(l));if(s<=0)return new A(x_(s));if(c<=0)return new A(D_(c));let u=xi(a,o,l);return(c/s-1)/u},isExported:!0},qv={description:E(`Annual yield of a security paying interest at maturity.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`issue (date)`,E(`The date the security was initially issued.`)),U(`rate (number)`,E(`The annualized rate of interest.`)),U(`price (number)`,E(`The price at which the security is bought.`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(M(e,this.locale)),s=Math.trunc(M(t,this.locale)),c=Math.trunc(M(n,this.locale)),l=M(r,this.locale),u=M(i,this.locale),d=Math.trunc(M(a,this.locale));if(o>=s)return new A(l_(o,s));if(R_(d))return new A(Kg(d));if(o<c)return new A(A_(o,c));if(l<0)return new A(T_(l));if(u<=0)return new A(x_(u));let f=xi(c,s,d),p=xi(c,o,d),m=xi(o,s,d);return(100*(1+l*f)/(u+100*l*p)-1)/m},isExported:!0},Jv=(e,t=()=>!0)=>[{goTo:e,guard:t}],Yv=(e,t=()=>!0)=>({goTo:e,guard:t}),Xv={0:{REFERENCE:Jv(2),NUMBER:Jv(4),SYMBOL:[Yv(3,e=>pc(e.value)),Yv(4,e=>mc(e.value))]},3:{SPACE:Jv(3),OPERATOR:Jv(5,e=>e.value===`:`)},4:{SPACE:Jv(4),OPERATOR:Jv(6,e=>e.value===`:`)},2:{SPACE:Jv(2),OPERATOR:Jv(1,e=>e.value===`:`)},1:{SPACE:Jv(1),NUMBER:Jv(7),REFERENCE:Jv(7,e=>_c(e.value)),SYMBOL:Jv(7,e=>hc(e.value)||gc(e.value))},5:{SPACE:Jv(5),SYMBOL:Jv(7,e=>hc(e.value)),REFERENCE:Jv(7,e=>_c(e.value))},6:{SPACE:Jv(6),NUMBER:Jv(7),REFERENCE:Jv(7,e=>_c(e.value)),SYMBOL:Jv(7,e=>gc(e.value))},7:{}};function Zv(e){let t=0,n=Xv[0],r=``;for(;n!==void 0;){let i=e[t++];if(!i)return null;let a=n[i.type]?.find(e=>e.guard(i)),o=a?a.goTo:void 0;switch(o){case void 0:return null;case 7:return r+=i.value,e.splice(0,t),{type:`REFERENCE`,value:r};default:n=Xv[o],r+=i.value;break}}return null}function Qv(e,t=D){let n=jl(e,t),r=[];for(;n.length;)r.push(Zv(n)||n.shift());return r}let $v=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,ey=[`-`,`+`],ty=[`%`],ny=[`*`,`+`,`&`];var ry=class{tokens;currentIndex=0;current;length;constructor(e){this.tokens=e,this.current=e[0],this.length=e.length}shift(){let e=this.tokens[this.currentIndex];return this.current=this.tokens[++this.currentIndex],e}get next(){return this.tokens[this.currentIndex+1]}};let iy={"^":30,"%":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function ay(e){let t=e.shift();if(!t)throw new zi;switch(t.type){case`DEBUGGER`:let n=ly(e,1e3);return n.debug=!0,n;case`NUMBER`:return{type:`NUMBER`,value:Ii(t.value,D),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`STRING`:return{type:`STRING`,value:it(t.value),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`INVALID_REFERENCE`:return{type:`REFERENCE`,value:k.InvalidReference,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`REFERENCE`:if(e.current?.value===`:`&&e.next?.type===`REFERENCE`){e.shift();let n=e.shift();return{type:`REFERENCE`,value:`${t.value}:${n?.value}`,tokenStartIndex:t.tokenIndex,tokenEndIndex:n.tokenIndex}}return{type:`REFERENCE`,value:t.value,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`SYMBOL`:let r=t.value;if(e.current?.type===`LEFT_PAREN`&&$v.test(t.value)&&r===lt(r,`'`)){let{args:n,rightParen:i}=oy(e);return{type:`FUNCALL`,value:r,args:n,tokenStartIndex:t.tokenIndex,tokenEndIndex:i.tokenIndex}}let i=r.toUpperCase();return i===`TRUE`||i===`FALSE`?{type:`BOOLEAN`,value:i===`TRUE`,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:{type:`SYMBOL`,value:lt(t.value,`'`),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`LEFT_PAREN`:let a=ly(e),o=cy(e,`RIGHT_PAREN`,E(`Missing closing parenthesis`));return{...a,tokenStartIndex:t.tokenIndex,tokenEndIndex:o.tokenIndex};case`OPERATOR`:let s=t.value;if(ey.includes(s)){let n=ly(e,iy[s]);return{type:`UNARY_OPERATION`,value:s,operand:n,tokenStartIndex:t.tokenIndex,tokenEndIndex:n.tokenEndIndex}}throw new zi(E(`Unexpected token: %s`,t.value));default:throw new zi(E(`Unexpected token: %s`,t.value))}}function oy(e){if(cy(e,`LEFT_PAREN`,E(`Missing opening parenthesis`)),e.current?.type===`RIGHT_PAREN`)return{args:[],rightParen:cy(e,`RIGHT_PAREN`)};let t=[];for(t.push(sy(e));e.current?.type!==`RIGHT_PAREN`;)cy(e,`ARG_SEPARATOR`,E(`Wrong function call`)),t.push(sy(e));return{args:t,rightParen:cy(e,`RIGHT_PAREN`)}}function sy(e){let t=e.current;return t?.type===`ARG_SEPARATOR`||t?.type===`RIGHT_PAREN`?{type:`EMPTY`,value:``,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:ly(e)}function cy(e,t,n){let r=e.shift();if(!r||r.type!==t)throw new zi(n);return r}function ly(e,t=0){if(e.length===0)throw new zi;let n=ay(e);for(;e.current?.type===`OPERATOR`&&iy[e.current.value]>t;){let t=e.shift(),r=t.value;if(ty.includes(r))n={type:`UNARY_OPERATION`,value:r,operand:n,postfix:!0,tokenStartIndex:n.tokenStartIndex,tokenEndIndex:t.tokenIndex};else{let t=ly(e,iy[r]);n={type:`BIN_OPERATION`,value:r,left:n,right:t,tokenStartIndex:n.tokenStartIndex,tokenEndIndex:t.tokenEndIndex}}}return n}function uy(e){return dy(Qv(e))}function dy(e){let t=new ry(e.map((e,t)=>({type:e.type,value:e.value,tokenIndex:t})).filter(e=>e.type!==`SPACE`));t.current?.value===`=`&&t.shift();let n=ly(t);if(t.current)throw new zi;return n}function fy(e,t,n){return hy(e,e=>e.type===t?n(e):e)}function py(e){return Array.from(my(e))}function*my(e){switch(yield e,e.type){case`FUNCALL`:for(let t of e.args)yield*my(t);break;case`UNARY_OPERATION`:yield*my(e.operand);break;case`BIN_OPERATION`:yield*my(e.left),yield*my(e.right);break}}function hy(e,t){switch(e=t(e),e.type){case`FUNCALL`:return{...e,args:e.args.map(e=>hy(e,t))};case`UNARY_OPERATION`:return{...e,operand:hy(e.operand,t)};case`BIN_OPERATION`:return{...e,right:hy(e.right,t),left:hy(e.left,t)};default:return e}}function gy(e){switch(e.type){case`FUNCALL`:let t=e.args.map(e=>gy(e));return`${e.value}(${t.join(`,`)})`;case`NUMBER`:return e.value.toString();case`REFERENCE`:return e.value;case`STRING`:return`"${e.value}"`;case`BOOLEAN`:return e.value?`TRUE`:`FALSE`;case`UNARY_OPERATION`:return e.postfix?_y(e)+e.value:e.value+vy(e);case`BIN_OPERATION`:return _y(e)+e.value+vy(e);default:return e.value}}function _y(e){let t=e.value,n=`left`in e?e.left:e.operand,r=n.value;return n.type===`BIN_OPERATION`&&iy[r]<iy[t]?`(${gy(n)})`:gy(n)}function vy(e){let t=e.value,n=`right`in e?e.right:e.operand,r=iy[n.value],i=iy[t],a=!1;return n.type===`BIN_OPERATION`?(r<i||r===i&&!ny.includes(t))&&(a=!0):a=!1,a?`(${gy(n)})`:gy(n)}function yy(e){let t=0;return e.map(e=>{let n=e.value.toString().length,r=Object.assign({},e,{start:t,end:t+n,length:n});return t=r.end,r})}function by(e){let t=[],n=0;return e.map((r,i)=>{if(r.type===`LEFT_PAREN`){t.push(n+1),n=0;for(let n=i-1;n>=0;n--){if(e[n].type===`SPACE`){e[n].parenthesesCode=t.join(`:`);continue}e[n].type===`SYMBOL`&&(e[n].parenthesesCode=t.join(`:`));break}}return r.parenthesesCode=t.join(`:`),r.type===`RIGHT_PAREN`&&t.length&&(n=t.pop()),r})}function xy(e){let t=[],n=``;function r(e){if(t.length===0)return;let n=t.at(-1);if(n&&n.argsTokens){let{argsTokens:t,argPosition:r}=n;t[r]||(t[r]=[]),t[r].push({value:e.value,type:e.type})}}return e.map((e,i)=>{switch([`SPACE`,`LEFT_PAREN`].includes(e.type)||(n=``),e.type){case`SYMBOL`:r(e),n=e.value;break;case`LEFT_PAREN`:t.push({parent:n,argPosition:0,argsTokens:[],args:[]}),r(e),n=``;break;case`RIGHT_PAREN`:t.pop()?.argsTokens?.flat().forEach(r),r(e);break;case`ARG_SEPARATOR`:t.length&&t[t.length-1].argPosition++,r(e);break;default:r(e);break}if(t.length){let n=t[t.length-1];n.parent&&(e.functionContext=Object.assign({},n))}return e})}function Sy(e){for(let t of e)if(t.functionContext){let{argsTokens:e,args:n}=t.functionContext;if(delete t.functionContext.argsTokens,n.length||!e)continue;e[0]?.[0]?.type===`LEFT_PAREN`&&(e[0]=e[0].slice(1));for(let t of e){let e=t;e.at(0)?.type===`ARG_SEPARATOR`&&(e=e.slice(1));try{n.push(dy(e))}catch{n.push(void 0)}}}return e}function Cy(e,t){return Sy(xy(by(yy(Qv(e,t)))))}function wy(e){if(e.type!==`REFERENCE`)return e;let{xc:t,sheetName:n}=vc(e.value),[r,i]=t.split(`:`),a=Ty(r),o=i?`:${Ty(i)}`:``;return{...e,value:yc(n,a+o)}}function Ty(e){switch(Oy(e)){case`none`:e=Ey(e,`colrow`);break;case`colrow`:e=Ey(e,`row`);break;case`row`:e=Ey(e,`col`);break;case`col`:e=Ey(e,`none`);break}return e}function Ey(e,t){let n;({sheetName:n,xc:e}=vc(e)),n=n?ut(n)+`!`:``,e=e.replace(/\$/g,``);let r=e.indexOf(`:`);return r>=0?`${n}${Dy(e.slice(0,r),t)}:${Dy(e.slice(r+1),t)}`:n+Dy(e,t)}function Dy(e,t){let n=e.search(/[0-9]/),r=n!==0,i=n>=0;switch(t){case`col`:return r?`$`+e:e;case`row`:return i?e.slice(0,n)+`$`+e.slice(n):e;case`colrow`:return!i||!r?`$`+e:`$`+e.slice(0,n)+`$`+e.slice(n);case`none`:return e}}function Oy(e){return jy(e)?`colrow`:ky(e)?`col`:Ay(e)?`row`:`none`}function ky(e){return e.startsWith(`$`)}function Ay(e){return e.includes(`$`,1)}function jy(e){return e.startsWith(`$`)&&e.length>1&&e.slice(1).includes(`$`)}function My(e,t,n){let r=(t.startsWith(`=`)?Cy(t,n):[]).filter(t=>t.start<=e.start&&t.end>=e.start||t.start>=e.start&&t.start<e.end),i=r.filter(e=>e.type===`REFERENCE`);if(i.length===0)return;let a=r.map(wy).map(e=>e.value).join(``),o=r[0].start,s=r[r.length-1].end,c=t.slice(0,o)+a+t.slice(s),l=c.length-t.length,u={start:i[0].start,end:i[i.length-1].end+l};return i.length===1&&e.start===e.end&&(u.start=u.end),{content:c,selection:u}}var Ny=l({CELL:()=>Fy,ISBLANK:()=>Uy,ISERR:()=>Iy,ISERROR:()=>Ly,ISLOGICAL:()=>Ry,ISNA:()=>zy,ISNONTEXT:()=>By,ISNUMBER:()=>Vy,ISTEXT:()=>Hy,NA:()=>Wy});let Py=[`address`,`col`,`contents`,`format`,`row`,`type`],Fy={description:E(`Gets information about a cell.`),args:[U(`info_type (string)`,E(`The type of information requested. Can be one of %s`,Py.join(`, `))),U(`reference (meta)`,E(`The reference to the cell.`))],compute:function(e,t){let n=N(e).toLowerCase();if(!Py.includes(n))return new A(E(`The info_type should be one of %s.`,Py.join(`, `)));let r=this.__originSheetId,i=N(t),{sheetName:a,xc:o}=vc(i.includes(`:`)?i.split(`:`)[0]:i);a=a===this.getters.getSheetName(r)?void 0:a;let s=yc(a,Ey(o,`colrow`)),c=this.getters.getRangeFromSheetXC(r,s);switch(n){case`address`:return this.getters.getRangeString(c,r);case`col`:return c.zone.left+1;case`contents`:{let e={sheetId:c.sheetId,col:c.zone.left,row:c.zone.top};return this.getters.getEvaluatedCell(e).value}case`format`:{let e={sheetId:c.sheetId,col:c.zone.left,row:c.zone.top};return this.getters.getEvaluatedCell(e).format||``}case`row`:return c.zone.top+1;case`type`:{let e={sheetId:c.sheetId,col:c.zone.left,row:c.zone.top},t=this.getters.getEvaluatedCell(e).type;return t===`empty`?`b`:t===`text`?`l`:`v`}}return``},isExported:!0},Iy={description:E(`Whether a value is an error other than #N/A.`),args:[U(`value (any)`,E(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return j(t)&&t!==k.NotAvailable},isExported:!0},Ly={description:E(`Whether a value is an error.`),args:[U(`value (any)`,E(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return j(t)},isExported:!0},Ry={description:E("Whether a value is `true` or `false`."),args:[U(`value (any)`,E(`The value to be verified as a logical TRUE or FALSE.`))],compute:function(e){return typeof e?.value==`boolean`},isExported:!0},zy={description:E(`Whether a value is the error #N/A.`),args:[U(`value (any)`,E(`The value to be verified as an error type.`))],compute:function(e){return e?.value===k.NotAvailable},isExported:!0},By={description:E(`Whether a value is non-textual.`),args:[U(`value (any)`,E(`The value to be checked.`))],compute:function(e){return!Hy.compute.bind(this)(e)},isExported:!0},Vy={description:E(`Whether a value is a number.`),args:[U(`value (any)`,E(`The value to be verified as a number.`))],compute:function(e){return typeof e?.value==`number`},isExported:!0},Hy={description:E(`Whether a value is text.`),args:[U(`value (any)`,E(`The value to be verified as text.`))],compute:function(e){return typeof e?.value==`string`&&j(e?.value)===!1},isExported:!0},Uy={description:E(`Whether the referenced cell is empty`),args:[U(`value (any)`,E(`Reference to the cell that will be checked for emptiness.`))],compute:function(e){return e?.value===null},isExported:!0},Wy={description:E(`Returns the error value #N/A.`),args:[],compute:function(){return{value:k.NotAvailable}},isExported:!0};var Gy=l({AND:()=>Ky,FALSE:()=>qy,IF:()=>Jy,IFERROR:()=>Yy,IFNA:()=>Xy,IFS:()=>Zy,NOT:()=>Qy,OR:()=>$y,SWITCH:()=>eb,TRUE:()=>tb,XOR:()=>nb});let Ky={description:E("Logical `and` operator."),args:[U(`logical_expression1 (boolean, range<boolean>)`,E(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.`)),U(`logical_expression2 (boolean, range<boolean>, repeating)`,E(`More expressions that represent logical values.`))],compute:function(...e){let{result:t,foundBoolean:n}=du(e);return n?t:new A(Ma)},isExported:!0},qy={description:E("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},Jy={description:E(`Returns value depending on logical expression.`),args:[U(`logical_expression (boolean, range<boolean>)`,E(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.`)),U(`value_if_true (any, range)`,E(`The value the function returns if logical_expression is TRUE.`)),U(`value_if_false (any, range, default=FALSE)`,E(`The value the function returns if logical_expression is FALSE.`))],compute:function(e,t,n){return Du(e)?va(Jy.compute,[e,t,n]):(P(Tu(e))?t:n)??{value:0}},isExported:!0},Yy={description:E(`Value if it is not an error, otherwise 2nd argument.`),args:[U(`value (any, range)`,E(`The value to return if value itself is not an error.`)),U(`value_if_error (any, range, default="empty")`,E(`The value the function returns if value is an error.`))],compute:function(e,t){return Du(e)?va(Yy.compute,[e,t]):(j(Tu(e)?.value)?t:e)??{value:0}},isExported:!0},Xy={description:E(`Value if it is not an #N/A error, otherwise 2nd argument.`),args:[U(`value (any, range)`,E(`The value to return if value itself is not #N/A an error.`)),U(`value_if_error (any, range, default="empty")`,E(`The value the function returns if value is an #N/A error.`))],compute:function(e,t){return Du(e)?va(Xy.compute,[e,t]):(Tu(e)?.value===k.NotAvailable?t:e)??{value:0}},isExported:!0},Zy={description:E(`Returns a value depending on multiple logical expressions.`),args:[U(`condition1 (boolean, range<boolean>)`,E(`The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.`)),U(`value1 (any, range)`,E(`The returned value if condition1 is TRUE.`)),U(`condition2 (boolean, any, range, repeating)`,E(`Additional conditions to be evaluated if the previous ones are FALSE.`)),U(`value2 (any, range, repeating)`,E(`Additional values to be returned if their corresponding conditions are TRUE.`))],compute:function(...e){if(e.length%2!=0)return new A(E(`Wrong number of arguments. Expected an even number of arguments.`));for(;e.length>0;){if(Du(e[0]))return va(Zy.compute,e);let t=P(Tu(e.shift())),n=e.shift();if(t)return n??{value:0}}return new A(E(`No match.`))},isExported:!0},Qy={description:E(`Returns opposite of provided logical value.`),args:[U(`logical_expression (boolean)`,E(`An expression or reference to a cell holding an expression that represents some logical value.`))],compute:function(e){return!P(e)},isExported:!0},$y={description:E("Logical `or` operator."),args:[U(`logical_expression1 (boolean, range<boolean>)`,E(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.`)),U(`logical_expression2 (boolean, range<boolean>, repeating)`,E(`More expressions that evaluate to logical values.`))],compute:function(...e){let{result:t,foundBoolean:n}=fu(e);return n?t:new A(Ma)},isExported:!0},eb={description:E(`Returns a value by comparing cases to an expression.`),args:[U(`expression (number, boolean, string)`,E(`The value to be checked.`)),U(`case1 (number, boolean, string)`,E(`The first case to be checked against expression.`)),U(`value1 (any)`,E(`The corresponding value to be returned if case1 matches expression.`)),U(`case2 (any, repeating)`,E(`Additional cases to try if the previous ones don't match expression.`)),U(`value2 (any, repeating)`,E(`Additional values to be returned if their corresponding cases match expression.`)),U(`default (any, default="empty")`,E(`An optional default value to be returned if none of the cases match expression.`))],compute:function(e,...t){let n=t.length%2==0?Ji(e):t.pop();for(let n=0;n<t.length;n+=2){let r=t[n];if(r&&j(r.value))return r;if(e?.value===r?.value)return t[n+1]||{value:0}}return n||{value:0}},isExported:!0},tb={description:E("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},nb={description:E("Logical `xor` operator."),args:[U(`logical_expression1 (boolean, range<boolean>)`,E(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.`)),U(`logical_expression2 (boolean, range<boolean>, repeating)`,E(`More expressions that evaluate to logical values.`))],compute:function(...e){let t=!1,n=!1;return ba(e,e=>(t=!0,n=n?!e:e,!0)),t?n:new A(Ma)},isExported:!0};function rb(e,t){let n=t.getPivotId(e);if(!n)throw new A(E(`There is no pivot with id "%s"`,e));return n}function ib(e,t,n){let{measures:r}=n.getPivotCoreDefinition(e);if(!r.find(e=>e.id===t))throw new A(E(`The argument %s is not a valid measure. Here are the measures: %s`,t,`(${r.map(e=>e.id).join(`, `)})`))}function ab(e){if(e.length%2!=0)throw new A(E(`Function PIVOT takes an even number of arguments.`))}function ob(e,t,n){let r=[],i=e.getters.getPivotCoreDefinition(t);if(i.type===`SPREADSHEET`&&i.dataSet){let{sheetId:t,zone:n}=i.dataSet,a=vs(n),o=e.getters.getRangeFromSheetXC(t,a);if(o===void 0||o.invalidXc||o.invalidSheetName)throw new Vi;if(e.__originCellPosition&&o.sheetId===e.__originSheetId&&As(z(e.__originCellPosition),n))throw new Bi;r.push(o)}for(let i of n)i.computedBy&&r.push(...e.getters.getMeasureFullDependencies(t,i));let a=e.__originCellPosition;a&&r.length&&(e.updateDependencies?.(a),e.addDependencies?.(a,r))}var sb=l({ADDRESS:()=>cb,COLUMN:()=>lb,COLUMNS:()=>ub,HLOOKUP:()=>db,INDEX:()=>fb,INDIRECT:()=>pb,LOOKUP:()=>mb,MATCH:()=>hb,OFFSET:()=>wb,PIVOT:()=>Cb,PIVOT_HEADER:()=>Sb,PIVOT_VALUE:()=>xb,ROW:()=>gb,ROWS:()=>_b,VLOOKUP:()=>vb,XLOOKUP:()=>bb});let cb={description:E(`Returns a cell reference as a string. `),args:[U(`row (number)`,E(`The row number of the cell reference. `)),U(`column (number)`,E(`The column number (not name) of the cell reference. A is column number 1. `)),U(`absolute_relative_mode (number, default=1)`,E(`An indicator of whether the reference is row/column absolute. 1 is row and column absolute (e.g. $A$1), 2 is row absolute and column relative (e.g. A$1), 3 is row relative and column absolute (e.g. $A1), and 4 is row and column relative (e.g. A1).`)),U(`use_a1_notation (boolean, default=TRUE)`,E(`A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).`)),U(`sheet (string, optional)`,E(`A string indicating the name of the sheet into which the address points.`))],compute:function(e,t,n={value:1},r={value:!0},i){let a=na(e,this.locale),o=na(t,this.locale);if(a<1)return new A(bu(a));if(o<1)return new A(bu(o));let s=na(n,this.locale);if(![1,2,3,4].includes(s))return new A(Xi(1,4,s));let c=P(r),l;if(c){let e={rowFixed:[1,2].includes(s),colFixed:[1,3].includes(s)};l=T(o-1,a-1,e)}else l=([1,2].includes(s)?`R${a}`:`R[${a}]`)+([1,3].includes(s)?`C${o}`:`C[${o}]`);return i===void 0?l:yc(N(i),l)},isExported:!0},lb={description:E(`Column number of a specified cell.`),args:[U(`cell_reference (meta, default='this cell')`,E(`The cell whose column number will be returned. Column A corresponds to 1. By default, the function use the cell in which the formula is entered.`))],compute:function(e){if(j(e?.value))return e;if(e===void 0)return this.__originCellPosition?.col===void 0?new A(E(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.col+1;let t=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),e.value).zone;return t.left===t.right?t.left+1:ma(t.right-t.left+1,1,(e,n)=>({value:t.left+e+1}))},isExported:!0},ub={description:E(`Number of columns in a specified array or range.`),args:[U(`range (meta)`,E(`The range whose column count will be returned.`))],compute:function(e){if(j(e?.value))return e;let t=ps(e.value);return t.right-t.left+1},isExported:!0},db={description:E(`Horizontal lookup`),args:[U(`search_key (string, number, boolean)`,E(`The value to search for. For example, 42, 'Cats', or I24.`)),U(`range (any, range)`,E(`The range to consider for the search. The first row in the range is searched for the key specified in search_key.`)),U(`index (number)`,E(`The row index of the value to be returned, where the first row in range is numbered 1.`)),U(`is_sorted (boolean, default=true)`,E(`Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned.`))],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(M(n?.value,this.locale)),a=I(t);if(1>i||i>a[0].length)return new A(E(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[t][0].value,s=a[P(r.value)?Ta(a,e,`nextSmaller`,`asc`,a.length,o):Ea(a,e,`wildcard`,a.length,o,this.lookupCaches)];return s===void 0?Ji(e):s[i-1]},isExported:!0},fb={description:E(`Returns the content of a cell, specified by row and column offset.`),args:[U(`reference (any, range)`,E(`The range of cells from which the values are returned.`)),U(`row (number, default=0)`,E(`The index of the row to be returned from within the reference range of cells.`)),U(`column (number, default=0)`,E(`The index of the column to be returned from within the reference range of cells.`))],compute:function(e,t={value:0},n={value:0}){let r=I(e),i=M(t.value,this.locale),a=M(n.value,this.locale);return a<0||a-1>=r.length||i<0||i-1>=r[0].length?new A(E(`Index out of range.`)):i===0&&a===0?r:i===0?[r[a-1]]:a===0?r.map(e=>[e[i-1]]):r[a-1][i-1]},isExported:!0},pb={description:E(`Returns the content of a cell, specified by a string.`),args:[U(`reference (string)`,E(`The range of cells from which the values are returned.`)),U(`use_a1_notation (boolean, default=TRUE)`,E(`A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).`))],compute:function(e,t={value:!0}){let n=e?.value?.toString();if(!n)return new Vi(E(`Reference should be defined.`));if(!P(t))return new A(E(`R1C1 notation is not supported.`));let r=this.__originSheetId,i=this.__originCellPosition;i&&this.updateDependencies?.(i);let a=this.getters.getRangeFromSheetXC(r,n);if(a===void 0||a.invalidXc||a.invalidSheetName)return new Vi;i&&this.addDependencies?.(i,[a]);let o=[];for(let e=a.zone.left;e<=a.zone.right;e++){let t=[];for(let n=a.zone.top;n<=a.zone.bottom;n++){let r={sheetId:a.sheetId,col:e,row:n};t.push(this.getters.getEvaluatedCell(r))}o.push(t)}return o.length===1&&o[0].length===1?o[0][0]:o},isExported:!0},mb={description:E(`Look up a value.`),args:[U(`search_key (string, number, boolean)`,E(`The value to search for. For example, 42, 'Cats', or I24.`)),U(`search_array (any, range)`,E(`One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.`)),U(`result_range (any, range, optional)`,E(`The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method.`))],compute:function(e,t,n){let r=I(t),i=I(n),a=r.length,o=r[0].length,s=o>=a,c=Ta(r,e,`nextSmaller`,`asc`,s?o:a,s?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value);return c===-1||s&&r[0][c]===void 0||!s&&r[c][o-1]===void 0?Ji(e):i[0].length===0?s?r[a-1][c]:r[c][o-1]:(a=i.length,o=i[0].length,a!==1&&o!==1?new A(E(`The result_range must be a single row or a single column.`)):a>1?c>a-1?new A(E(`[[FUNCTION_NAME]] evaluates to an out of range row value %s.`,c+1)):i[c][0]:c>o-1?new A(E(`[[FUNCTION_NAME]] evaluates to an out of range column value %s.`,c+1)):i[0][c])},isExported:!0},hb={description:E(`Position of item in range that matches value.`),args:[U(`search_key (string, number, boolean)`,E(`The value to search for. For example, 42, 'Cats', or I24.`)),U(`range (any, range)`,E(`The one-dimensional array to be searched.`)),U(`search_type (number, default=1)`,E(`The search method. 1 (default) finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order.`))],compute:function(e,t,n={value:1}){let r=M(n,this.locale),i=I(t),a=i.length,o=i[0].length;if(a!==1&&o!==1)return new A(E(`The range must be a single row or a single column.`));let s=-1,c=a===1?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,l=a===1?i[0].length:i.length;switch(r=Math.sign(r),r){case 1:s=Ta(i,e,`nextSmaller`,`asc`,l,c);break;case 0:s=Ea(i,e,`wildcard`,l,c,this.lookupCaches);break;case-1:s=Ta(i,e,`nextGreater`,`desc`,l,c);break}return a===1&&i[0][s]===void 0||a!==1&&i[s]===void 0?Ji(e):s+1},isExported:!0},gb={description:E(`Row number of a specified cell.`),args:[U(`cell_reference (meta, default='this cell')`,E(`The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered.`))],compute:function(e){if(j(e?.value))return e;if(e===void 0)return this.__originCellPosition?.row===void 0?new A(E(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.row+1;let t=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),e.value).zone;return t.top===t.bottom?t.top+1:ma(1,t.bottom-t.top+1,(e,n)=>({value:t.top+n+1}))},isExported:!0},_b={description:E(`Number of rows in a specified array or range.`),args:[U(`range (meta)`,E(`The range whose row count will be returned.`))],compute:function(e){if(j(e?.value))return e;let t=ps(e.value);return t.bottom-t.top+1},isExported:!0},vb={description:E(`Vertical lookup.`),args:[U(`search_key (string, number, boolean)`,E(`The value to search for. For example, 42, 'Cats', or I24.`)),U(`range (any, range)`,E(`The range to consider for the search. The first column in the range is searched for the key specified in search_key.`)),U(`index (number)`,E(`The column index of the value to be returned, where the first column in range is numbered 1.`)),U(`is_sorted (boolean, default=true)`,E(`Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned.`))],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(M(n?.value,this.locale)),a=I(t);if(1>i||i>a.length)return new A(E(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[0][t].value,s=P(r.value)?Ta(a,e,`nextSmaller`,`asc`,a[0].length,o):Ea(a,e,`wildcard`,a[0].length,o,this.lookupCaches),c=a[i-1][s];return c===void 0?Ji(e):c},isExported:!0},yb={0:`strict`,1:`nextGreater`,"-1":`nextSmaller`,2:`wildcard`},bb={description:E(`Search a range for a match and return the corresponding item from a second range.`),args:[U(`search_key (string,number,boolean)`,E(`The value to search for.`)),U(`lookup_range (any, range)`,E(`The range to consider for the search. Should be a single column or a single row.`)),U(`return_range (any, range)`,E(`The range containing the return value. Should have the same dimensions as lookup_range.`)),U(`if_not_found (any, optional)`,E(`If a valid match is not found, return this value.`)),U(`match_mode (any, default=0)`,E(`(0) Exact match. (-1) Return next smaller item if no match. (1) Return next greater item if no match. (2) Wildcard match.`)),U(`search_mode (any, default=1)`,E(`(1) Search starting at first item. (-1) Search starting at last item. (2) Perform a binary search that relies on lookup_array being sorted in ascending order. If not sorted, invalid results will be returned. (-2) Perform a binary search that relies on lookup_array being sorted in descending order. If not sorted, invalid results will be returned. `))],compute:function(e,t,n,r,i={value:0},a={value:1}){let o=Math.trunc(M(i.value,this.locale)),s=Math.trunc(M(a.value,this.locale)),c=I(t),l=I(n);if(c.length!==1&&c[0].length!==1)return new A(E(`lookup_range should be either a single row or single column.`));if(![1,-1,2,-2].includes(s))return new A(E(`search_mode should be a value in [-1, 1, -2, 2].`));if(![-1,0,1,2].includes(o))return new A(E(`match_mode should be a value in [-1, 0, 1, 2].`));let u=c.length===1?`col`:`row`;if(o===2&&[-2,2].includes(s))return new A(E(`The search and match mode combination is not supported for XLOOKUP evaluation.`));if(u===`col`?l[0].length!==c[0].length:l.length!==c.length)return new A(E(`return_range should have the same dimensions as lookup_range.`));let d=u===`col`?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,f=u===`col`?c[0].length:c.length,p=yb[o],m=s===-1,h=s===2||s===-2?Ta(c,e,p,s===2?`asc`:`desc`,f,d):Ea(c,e,p,f,d,this.lookupCaches,m);return h===-1?r===void 0?Ji(e):[[r]]:u===`col`?l.map(e=>[e[h]]):[l[h]]},isExported:!0},xb={description:E(`Get the value from a pivot.`),args:[U(`pivot_id (number,string)`,E(`ID of the pivot.`)),U(`measure_name (string)`,E(`Name of the measure.`)),U(`domain_field_name (string,repeating)`,E(`Field name.`)),U(`domain_value (number,string,boolean,repeating)`,E(`Value.`))],compute:function(e,t,...n){let r=N(e),i=N(t),a=rb(r,this.getters);ib(a,i,this.getters),ab(n);let o=this.getters.getPivot(a),s=this.getters.getPivotCoreDefinition(a);ob(this,a,s.measures.filter(e=>e.id===i)),o.init({reload:o.needsReevaluation});let c=o.assertIsValid({throwOnError:!1});if(c)return c;if(!o.areDomainArgsFieldsValid(n)){let e=E(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${r})`);return{value:k.GenericError,message:E(`Dimensions don't match the pivot definition`)+`. `+e}}let l=o.parseArgsToPivotDomain(n);return this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(a)?.trackValue(i,l),o.getPivotCellValueAndFormat(i,l)}},Sb={description:E(`Get the header of a pivot.`),args:[U(`pivot_id (number,string)`,E(`ID of the pivot.`)),U(`domain_field_name (string,repeating)`,E(`Field name.`)),U(`domain_value (number,string,value,repeating)`,E(`Value.`))],compute:function(e,...t){let n=N(e),r=rb(n,this.getters);ab(t);let i=this.getters.getPivot(r);ob(this,r,[]),i.init({reload:i.needsReevaluation});let a=i.assertIsValid({throwOnError:!1});if(a)return a;if(!i.areDomainArgsFieldsValid(t)){let e=E(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${n})`);return{value:k.GenericError,message:E(`Dimensions don't match the pivot definition`)+`. `+e}}let o=i.parseArgsToPivotDomain(t);this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(r)?.trackHeader(o);let s=o.at(-1);if(s?.field===`measure`)return i.getPivotMeasureValue(N(s.value),o);let{value:c,format:l}=i.getPivotHeaderValueAndFormat(o);return{value:c,format:!s||s.field===`measure`||s.value===`false`?void 0:l}}},Cb={description:E(`Get a pivot table.`),args:[U(`pivot_id (string)`,E(`ID of the pivot.`)),U(`row_count (number, optional)`,E(`number of rows`)),U(`include_total (boolean, default=TRUE)`,E(`Whether to include total/sub-totals or not.`)),U(`include_column_titles (boolean, default=TRUE)`,E(`Whether to include the column titles or not.`)),U(`column_count (number, optional)`,E(`number of columns`)),U(`include_measure_titles (boolean, default=TRUE)`,E(`Whether to include the measure titles row or not.`))],compute:function(e,t={value:1e4},n={value:!0},r={value:!0},i={value:Number.MAX_VALUE},a={value:!0}){let o=N(e),s=M(t,this.locale);if(s<0)return new A(E(`The number of rows must be positive.`));let c=M(i,this.locale);if(c<0)return new A(E(`The number of columns must be positive.`));let l={displayColumnHeaders:P(r),displayTotals:P(n),displayMeasuresRow:P(a)},u=rb(o,this.getters),d=this.getters.getPivot(u),f=this.getters.getPivotCoreDefinition(u);ob(this,u,f.measures),d.init({reload:d.needsReevaluation});let p=d.assertIsValid({throwOnError:!1});if(p)return p;let m=d.getCollapsedTableStructure(),h=m.getPivotCells(l),g=0;l.displayColumnHeaders&&(g=m.columns.length-1),l.displayMeasuresRow&&g++;let _=this.getters.getPivotName(u),v=Math.min(g+s,h[0].length);if(v===0)return[[{value:_}]];let y=Math.min(1+c,h.length),ee=[];for(let e of S(0,y)){ee[e]=[];for(let t of S(0,v)){let n=h[e][t];switch(n.type){case`EMPTY`:ee[e].push({value:``});break;case`HEADER`:let t=d.getPivotHeaderValueAndFormat(n.domain);ee[e].push(Cd(n.domain,t));break;case`MEASURE_HEADER`:ee[e].push(d.getPivotMeasureValue(n.measure,n.domain));break;case`VALUE`:ee[e].push(d.getPivotCellValueAndFormat(n.measure,n.domain));break}}}return(l.displayColumnHeaders||l.displayMeasuresRow)&&(ee[0][0]={value:_}),ee}},wb={description:E(`Returns a range reference shifted by a specified number of rows and columns from a starting cell reference.`),args:[U(`cell_reference (meta)`,E(`The starting point from which to count the offset rows and columns.`)),U(`offset_rows (number)`,E(`The number of rows to offset by.`)),U(`offset_columns (number)`,E(`The number of columns to offset by.`)),U(`height (number, default='height of cell_reference')`,E(`The number of rows of the range to return starting at the offset target.`)),U(`width (number, default='width of cell_reference')`,E(`The number of columns of the range to return starting at the offset target.`))],compute:function(e,t,n,r,i){if(j(e?.value))return e;let a=e?.value;if(!a)return new A(`In this context, the function OFFSET needs to have a cell or range in parameter.`);let o=ps(a),s=o.bottom-o.top+1,c=o.right-o.left+1;if(r){let e=M(r,this.locale);if(e<1)return new A(E(`Height value is %(_height)s. It should be greater than or equal to 1.`,{_height:e}));s=e}if(i){let e=M(i,this.locale);if(e<1)return new A(E(`Width value is %(_width)s. It should be greater than or equal to 1.`,{_width:e}));c=e}let{sheetName:l}=vc(a),u=l&&this.getters.getSheetIdByName(l)||this.getters.getActiveSheetId(),d=M(t,this.locale),f=M(n,this.locale),p=this.__originCellPosition;p&&this.updateDependencies?.(p);let m=o.left+f,h=o.top+d;if(m<0||h<0)return new Vi(E(`OFFSET evaluates to an out of bounds range.`));let g={left:m,top:h,right:m+c-1,bottom:h+s-1},_=this.getters.getRangeFromZone(u,g);return _.invalidXc||_.invalidSheetName?new Vi:(p&&this.addDependencies?.(p,[_]),ma(c,s,(e,t)=>this.getters.getEvaluatedCell({sheetId:u,col:m+e,row:h+t})))}};var Tb=l({ADD:()=>Eb,CONCAT:()=>Db,DIVIDE:()=>Ob,EQ:()=>Mb,GT:()=>Pb,GTE:()=>Fb,LT:()=>Ib,LTE:()=>Lb,MINUS:()=>Rb,MULTIPLY:()=>zb,NE:()=>Bb,POW:()=>Vb,UMINUS:()=>Hb,UNARY_PERCENT:()=>Ub,UPLUS:()=>Wb});let Eb={description:E(`Sum of two numbers.`),args:[U(`value1 (number)`,E(`The first addend.`)),U(`value2 (number)`,E(`The second addend.`))],compute:function(e,t){return{value:M(e,this.locale)+M(t,this.locale),format:e?.format||t?.format}}},Db={description:E(`Concatenation of two values.`),args:[U(`value1 (string)`,E(`The value to which value2 will be appended.`)),U(`value2 (string)`,E(`The value to append to value1.`))],compute:function(e,t){return N(e)+N(t)},isExported:!0},Ob={description:E(`One number divided by another.`),args:[U(`dividend (number)`,E(`The number to be divided.`)),U(`divisor (number)`,E(`The number to divide by.`))],compute:function(e,t){let n=M(t,this.locale);return n===0?new Gi(E(`The divisor must be different from zero.`)):{value:M(e,this.locale)/n,format:e?.format||t?.format}}};function kb(e){return e===void 0||e.value===null}let Ab={number:0,string:``,boolean:!1};function jb(e,t,n=2e-16){return Math.abs(e-t)<n}let Mb={description:E(`Equal.`),args:[U(`value1 (string, number, boolean)`,E(`The first value.`)),U(`value2 (string, number, boolean)`,E(`The value to test against value1 for equality.`))],compute:function(e,t){if(j(e?.value))return e;if(j(t?.value))return t;let n=kb(e)?Ab[typeof t?.value]:e?.value,r=kb(t)?Ab[typeof e?.value]:t?.value;return typeof n==`string`&&(n=n.toUpperCase()),typeof r==`string`&&(r=r.toUpperCase()),typeof n==`number`&&typeof r==`number`?{value:jb(n,r)}:{value:n===r}}};function Nb(e,t,n){if(j(e?.value))return e;if(j(t?.value))return t;let r=kb(e)?Ab[typeof t?.value]:e?.value,i=kb(t)?Ab[typeof e?.value]:t?.value;typeof r!=`number`&&(r=N(r).toUpperCase()),typeof i!=`number`&&(i=N(i).toUpperCase());let a=typeof r,o=typeof i;return a===`string`&&o===`number`?{value:!0}:o===`string`&&a===`number`?{value:!1}:{value:n(r,i)}}let Pb={description:E(`Strictly greater than.`),args:[U(`value1 (number, string, boolean)`,E(`The value to test as being greater than value2.`)),U(`value2 (number, string, boolean)`,E(`The second value.`))],compute:function(e,t){return Nb(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?!jb(e,t)&&e>t:e>t)}},Fb={description:E(`Greater than or equal to.`),args:[U(`value1 (number, string, boolean)`,E(`The value to test as being greater than or equal to value2.`)),U(`value2 (number, string, boolean)`,E(`The second value.`))],compute:function(e,t){return Nb(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?jb(e,t)||e>t:e>=t)}},Ib={description:E(`Less than.`),args:[U(`value1 (number, string, boolean)`,E(`The value to test as being less than value2.`)),U(`value2 (number, string, boolean)`,E(`The second value.`))],compute:function(e,t){let n=Fb.compute.bind(this)(e,t);return j(n.value)?n:{value:!n.value}}},Lb={description:E(`Less than or equal to.`),args:[U(`value1 (number, string, boolean)`,E(`The value to test as being less than or equal to value2.`)),U(`value2 (number, string, boolean)`,E(`The second value.`))],compute:function(e,t){let n=Pb.compute.bind(this)(e,t);return j(n.value)?n:{value:!n.value}}},Rb={description:E(`Difference of two numbers.`),args:[U(`value1 (number)`,E(`The minuend, or number to be subtracted from.`)),U(`value2 (number)`,E(`The subtrahend, or number to subtract from value1.`))],compute:function(e,t){return{value:M(e,this.locale)-M(t,this.locale),format:e?.format||t?.format}}},zb={description:E(`Product of two numbers`),args:[U(`factor1 (number)`,E(`The first multiplicand.`)),U(`factor2 (number)`,E(`The second multiplicand.`))],compute:function(e,t){return{value:M(e,this.locale)*M(t,this.locale),format:e?.format||t?.format}}},Bb={description:E(`Not equal.`),args:[U(`value1 (string, number, boolean)`,E(`The first value.`)),U(`value2 (string, number, boolean)`,E(`The value to test against value1 for inequality.`))],compute:function(e,t){let n=Mb.compute.bind(this)(e,t);return j(n.value)?n:{value:!n.value}}},Vb={description:E(`A number raised to a power.`),args:[U(`base (number)`,E(`The number to raise to the exponent power.`)),U(`exponent (number)`,E(`The exponent to raise base to.`))],compute:function(e,t){return nm.compute.bind(this)(e,t)}},Hb={description:E(`A number with the sign reversed.`),args:[U(`value (number)`,E(`The number to have its sign reversed. Equivalently, the number to multiply by -1.`))],compute:function(e){return{value:-M(e,this.locale),format:e?.format}}},Ub={description:E(`Value interpreted as a percentage.`),args:[U(`percentage (number)`,E(`The value to interpret as a percentage.`))],compute:function(e){return M(e,this.locale)/100}},Wb={description:E(`A specified number, unchanged.`),args:[U(`value (any)`,E(`The number to return.`))],compute:function(e={value:null}){return e}},W=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),Gb={transform:e=>e,inverseTransform:e=>e},Kb=1e-10,qb=.0254,Jb=qb/72,Yb=.3048,Xb=.9144,Zb=1609.34,Qb=1852,$b=946073047258e4,ex={g:{...Gb,category:`weight`},u:{...W(166053e-29),category:`weight`},grain:{...W(.0647989),category:`weight`},ozm:{...W(28.3495),category:`weight`},lbm:{...W(453.592),category:`weight`},stone:{...W(6350.29),category:`weight`},sg:{...W(14593.90294),category:`weight`},cwt:{...W(45359.237),category:`weight`},uk_cwt:{...W(50802.3),category:`weight`},ton:{...W(907184.74),category:`weight`},uk_ton:{...W(1016046.9),category:`weight`},m:{...Gb,category:`distance`},km:{...W(1e3),category:`distance`},ang:{...W(Kb),category:`distance`},Picapt:{...W(Jb),category:`distance`},pica:{...W(qb/6),category:`distance`},in:{...W(qb),category:`distance`},ft:{...W(Yb),category:`distance`},yd:{...W(Xb),category:`distance`},ell:{...W(1.143),category:`distance`},mi:{...W(Zb),category:`distance`},survey_mi:{...W(1609.34),category:`distance`},Nmi:{...W(Qb),category:`distance`},ly:{...W($b),category:`distance`},parsec:{...W(0x6da012f95c9fd0),category:`distance`},sec:{...Gb,category:`time`},min:{...W(60),category:`time`},hr:{...W(3600),category:`time`},day:{...W(86400),category:`time`},yr:{...W(31556952),category:`time`},Pa:{...Gb,category:`pressure`},bar:{...W(1e5),category:`pressure`},mmHg:{...W(133.322),category:`pressure`},Torr:{...W(133.322),category:`pressure`},psi:{...W(6894.76),category:`pressure`},atm:{...W(101325),category:`pressure`},N:{...Gb,category:`force`},dyn:{...W(1e-5),category:`force`},pond:{...W(.00980665),category:`force`},lbf:{...W(4.44822),category:`force`},J:{...Gb,category:`energy`},eV:{...W(160218e-24),category:`energy`},e:{...W(1e-7),category:`energy`},flb:{...W(1.3558179483),category:`energy`},c:{...W(4.184),category:`energy`},cal:{...W(4.1868),category:`energy`},BTU:{...W(1055.06),category:`energy`},Wh:{...W(3600),category:`energy`},HPh:{...W(2684520),category:`energy`},W:{...Gb,category:`power`},PS:{...W(735.499),category:`power`},HP:{...W(745.7),category:`power`},T:{...Gb,category:`magnetism`},ga:{...W(1e-4),category:`magnetism`},K:{...Gb,category:`temperature`},C:{transform:e=>e+273.15,inverseTransform:e=>e-273.15,category:`temperature`},F:{transform:e=>(e-32)*5/9+273.15,inverseTransform:e=>(e-273.15)*9/5+32,category:`temperature`},Rank:{...W(5/9),category:`temperature`},Reau:{transform:e=>e*1.25+273.15,inverseTransform:e=>(e-273.15)/1.25,category:`temperature`},"m^3":{...Gb,category:`volume`,order:3},"ang^3":{...W(Kb**3),category:`volume`,order:3},"Picapt^3":{...W(Jb**3),category:`volume`,order:3},tsp:{...W(492892e-11),category:`volume`},tspm:{...W(5e-6),category:`volume`},tbs:{...W(14786764825785619e-21),category:`volume`},"in^3":{...W(qb**3),category:`volume`,order:3},oz:{...W(295735295625e-16),category:`volume`},cup:{...W(237e-6),category:`volume`},pt:{...W(.0004731765),category:`volume`},uk_pt:{...W(568261e-9),category:`volume`},qt:{...W(.0009463529),category:`volume`},l:{...W(.001),category:`volume`},uk_qt:{...W(.0011365225),category:`volume`},gal:{...W(.0037854118),category:`volume`},uk_gal:{...W(.00454609),category:`volume`},"ft^3":{...W(Yb**3),category:`volume`,order:3},bushel:{...W(.0352390704),category:`volume`},barrel:{...W(.158987295),category:`volume`},"yd^3":{...W(Xb**3),category:`volume`,order:3},MTON:{...W(1.13267386368),category:`volume`},GRT:{...W(2.83168),category:`volume`},"mi^3":{...W(Zb**3),category:`volume`,order:3},"Nmi^3":{...W(Qb**3),category:`volume`,order:3},"ly^3":{...W($b**3),category:`volume`,order:3},"m^2":{...Gb,category:`area`,order:2},"ang^2":{...W(Kb**2),category:`area`,order:2},"Picapt^2":{...W(Jb**2),category:`area`,order:2},"in^2":{...W(qb**2),category:`area`,order:2},"ft^2":{...W(Yb**2),category:`area`,order:2},"yd^2":{...W(Xb**2),category:`area`,order:2},ar:{...W(100),category:`area`},Morgen:{...W(2500),category:`area`},uk_acre:{...W(4046.8564224),category:`area`},us_acre:{...W(4046.8726098743),category:`area`},ha:{...W(1e4),category:`area`},"mi^2":{...W(Zb**2),category:`area`,order:2},"Nmi^2":{...W(Qb**2),category:`area`,order:2},"ly^2":{...W($b**2),category:`area`,order:2},bit:{...Gb,category:`information`},byte:{...W(8),category:`information`},"m/s":{...Gb,category:`speed`},"m/hr":{...W(1/3600),category:`speed`},"km/hr":{...W(1/3.6),category:`speed`},mph:{...W(.44704),category:`speed`},kn:{...W(.5144444444),category:`speed`},admkn:{...W(.5147733333),category:`speed`}},tx={shweight:`cwt`,lcwt:`uk_cwt`,hweight:`uk_cwt`,LTON:`uk_ton`,brton:`uk_ton`,pc:`parsec`,Pica:`Picapt`,d:`day`,mn:`min`,s:`sec`,p:`Pa`,at:`atm`,dy:`dyn`,ev:`eV`,hh:`HPh`,wh:`Wh`,btu:`BTU`,h:`HP`,cel:`C`,fah:`F`,kel:`K`,us_pt:`pt`,L:`l`,lt:`l`,ang3:`ang^3`,ft3:`ft^3`,in3:`in^3`,ly3:`ly^3`,m3:`m^3`,mi3:`mi^3`,yd3:`yd^3`,Nmi3:`Nmi^3`,Picapt3:`Picapt^3`,"Pica^3":`Picapt^3`,Pica3:`Picapt^3`,regton:`GRT`,ang2:`ang^2`,ft2:`ft^2`,in2:`in^2`,ly2:`ly^2`,m2:`m^2`,mi2:`mi^2`,Nmi2:`Nmi^2`,Picapt2:`Picapt^2`,"Pica^2":`Picapt^2`,Pica2:`Picapt^2`,yd2:`yd^2`,"m/h":`m/hr`,"m/sec":`m/s`},nx={"":1,Y:1e24,Z:1e21,E:0xde0b6b3a7640000,P:0x38d7ea4c68000,T:0xe8d4a51000,G:1e9,M:1e6,k:1e3,h:100,da:10,e:10,d:.1,c:.01,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15,a:1e-18,z:1e-21,y:1e-21,Yi:2**80,Zi:2**70,Ei:2**60,Pi:2**50,Ti:2**40,Gi:2**30,Mi:2**20,ki:2**10},rx={weight:E(`Weight`),distance:E(`Distance`),time:E(`Time`),pressure:E(`Pressure`),force:E(`Force`),energy:E(`Energy`),power:E(`Power`),magnetism:E(`Magnetism`),temperature:E(`Temperature`),volume:E(`Volume`),area:E(`Area`),information:E(`Information`),speed:E(`Speed`)};function ix(e){return rx[e]??``}function ax(e){for(let[t,n]of Object.entries(nx)){if(t&&!e.startsWith(t))continue;let r=e.slice(t.length),i=ex[r];if(!i&&tx[r]&&(i=ex[tx[r]]),i)return{...i,factor:i.order?n**+i.order:n}}}var ox=l({CONVERT:()=>sx});let sx={description:E(`Converts a numeric value to a different unit of measure.`),args:[U(`value (number)`,E(`the numeric value in start_unit to convert to end_unit`)),U(`start_unit (string)`,E(`The starting unit, the unit currently assigned to value`)),U(`end_unit (string)`,E(`The unit of measure into which to convert value`))],compute:function(e,t,n){let r=M(e,this.locale),i=N(t),a=N(n),o=ax(i),s=ax(a);return o?s?o.category===s.category?{value:s.inverseTransform(o.factor*o.transform(r))/s.factor,format:e?.format}:{value:k.GenericError,message:E(`Incompatible units of measure ('%s' vs '%s')`,ix(o.category),ix(s.category))}:{value:k.GenericError,message:E(`Invalid units of measure ('%s')`,a)}:{value:k.GenericError,message:E(`Invalid units of measure ('%s')`,i)}},isExported:!0};var cx=l({CHAR:()=>ux,CLEAN:()=>dx,CONCATENATE:()=>fx,EXACT:()=>px,FIND:()=>mx,JOIN:()=>hx,LEFT:()=>gx,LEN:()=>_x,LOWER:()=>vx,MID:()=>yx,PROPER:()=>bx,REPLACE:()=>xx,RIGHT:()=>Sx,SEARCH:()=>Cx,SPLIT:()=>wx,SUBSTITUTE:()=>Tx,TEXT:()=>Ax,TEXTJOIN:()=>Ex,TEXTSPLIT:()=>Dx,TRIM:()=>Ox,UPPER:()=>kx,VALUE:()=>jx});let lx=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,ux={description:E(`Gets character associated with number.`),args:[U(`table_number (number)`,E(`The number of the character to look up from the current Unicode table in decimal format.`))],compute:function(e){let t=Math.trunc(M(e,this.locale));return t<1?new A(E(`The table_number (%s) is out of range.`,t)):String.fromCharCode(t)},isExported:!0},dx={description:E(`Remove non-printable characters from a piece of text.`),args:[U(`text (string)`,E(`The text whose non-printable characters are to be removed.`))],compute:function(e){let t=N(e),n=``;for(let e of t)e&&e.charCodeAt(0)>31&&(n+=e);return n},isExported:!0},fx={description:E(`Appends strings to one another.`),args:[U(`string1 (string, range<string>)`,E(`The initial string.`)),U(`string2 (string, range<string>, repeating)`,E(`More strings to append in sequence.`))],compute:function(...e){return da(e,(e,t)=>e+N(t),``)},isExported:!0},px={description:E(`Tests whether two strings are identical.`),args:[U(`string1 (string)`,E(`The first string to compare.`)),U(`string2 (string)`,E(`The second string to compare.`))],compute:function(e,t){return N(e)===N(t)},isExported:!0},mx={description:E(`First position of string found in text, case-sensitive.`),args:[U(`search_for (string)`,E(`The string to look for within text_to_search.`)),U(`text_to_search (string)`,E(`The text to search for the first occurrence of search_for.`)),U(`starting_at (number, default=1)`,E(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=N(e),i=N(t),a=M(n,this.locale);if(i===``)return new A(E(`The text_to_search must be non-empty.`));if(a<1)return new A(E(`The starting_at (%s) must be greater than or equal to 1.`,a));let o=i.indexOf(r,a-1);return o===-1?new A(E(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)):o+1},isExported:!0},hx={description:E(`Concatenates elements of arrays with delimiter.`),args:[U(`delimiter (string)`,E(`The character or string to place between each concatenated value.`)),U(`value_or_array1 (string, range<string>)`,E(`The value or values to be appended using delimiter.`)),U(`value_or_array2 (string, range<string>, repeating)`,E(`More values to be appended using delimiter.`))],compute:function(e,...t){let n=N(e);return da(t,(e,t)=>(e?e+n:``)+N(t),``)}},gx={description:E(`Substring from beginning of specified string.`),args:[U(`text (string)`,E(`The string from which the left portion will be returned.`)),U(`number_of_characters (number, optional)`,E(`The number of characters to return from the left side of string.`))],compute:function(e,...t){let n=t.length?M(t[0],this.locale):1;return n<0?new A(E(`The number_of_characters (%s) must be positive or null.`,n)):N(e).substring(0,n)},isExported:!0},_x={description:E(`Length of a string.`),args:[U(`text (string)`,E(`The string whose length will be returned.`))],compute:function(e){return N(e).length},isExported:!0},vx={description:E(`Converts a specified string to lowercase.`),args:[U(`text (string)`,E(`The string to convert to lowercase.`))],compute:function(e){return N(e).toLowerCase()},isExported:!0},yx={description:E(`A segment of a string.`),args:[U(`text (string)`,E(`The string to extract a segment from.`)),U(`starting_at (number)`,E(`The index from the left of string from which to begin extracting. The first character in string has the index 1.`)),U(`extract_length (number)`,E(`The length of the segment to extract.`))],compute:function(e,t,n){let r=N(e),i=M(t,this.locale),a=M(n,this.locale);return i<1?new A(E(`The starting_at argument (%s) must be positive greater than one.`,i.toString())):a<0?new A(E(`The extract_length argument (%s) must be positive or null.`,a)):r.slice(i-1,i+a-1)},isExported:!0},bx={description:E(`Capitalizes each word in a specified string.`),args:[U(`text_to_capitalize (string)`,E(`The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase.`))],compute:function(e){return N(e).replace(lx,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},xx={description:E(`Replaces part of a text string with different text.`),args:[U(`text (string)`,E(`The text, a part of which will be replaced.`)),U(`position (number)`,E(`The position where the replacement will begin (starting from 1).`)),U(`length (number)`,E(`The number of characters in the text to be replaced.`)),U(`new_text (string)`,E(`The text which will be inserted into the original text.`))],compute:function(e,t,n,r){let i=M(t,this.locale);if(i<1)return new A(E(`The position (%s) must be greater than or equal to 1.`,i));let a=N(e),o=M(n,this.locale),s=N(r);return a.substring(0,i-1)+s+a.substring(i-1+o)},isExported:!0},Sx={description:E(`A substring from the end of a specified string.`),args:[U(`text (string)`,E(`The string from which the right portion will be returned.`)),U(`number_of_characters (number, optional)`,E(`The number of characters to return from the right side of string.`))],compute:function(e,...t){let n=t.length?M(t[0],this.locale):1;if(n<0)return new A(E(`The number_of_characters (%s) must be positive or null.`,n));let r=N(e),i=r.length;return r.substring(i-n,i)},isExported:!0},Cx={description:E(`First position of string found in text, ignoring case.`),args:[U(`search_for (string)`,E(`The string to look for within text_to_search.`)),U(`text_to_search (string)`,E(`The text to search for the first occurrence of search_for.`)),U(`starting_at (number, default=1)`,E(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=N(e).toLowerCase(),i=N(t).toLowerCase(),a=M(n,this.locale);if(i===``)return{value:k.GenericError,message:E(`The text_to_search must be non-empty.`)};if(a<1)return{value:k.GenericError,message:E(`The starting_at (%s) must be greater than or equal to 1.`,a)};let o=i.indexOf(r,a-1);return o===-1?{value:k.GenericError,message:E(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)}:{value:o+1}},isExported:!0},wx={description:E(`Split text by specific character delimiter(s).`),args:[U(`text (string)`,E(`The text to divide.`)),U(`delimiter (string)`,E(`The character or characters to use to split text.`)),U(`split_by_each (boolean, default=true})`,E(`Whether or not to divide text around each character contained in delimiter.`)),U(`remove_empty_text (boolean, default=true)`,E(`Whether or not to remove empty text messages from the split results. The default behavior is to treat consecutive delimiters as one (if TRUE). If FALSE, empty cells values are added between consecutive delimiters.`))],compute:function(e,t,n={value:!0},r={value:!0}){let i=N(e),a=ot(N(t)),o=P(n),s=P(r);if(a.length<=0)return new A(E(`The delimiter (%s) must be not be empty.`,a));let c=o?RegExp(`[${a}]`,`g`):new RegExp(a,`g`),l=i.split(c);return s&&(l=l.filter(e=>e!==``)),_a([l])},isExported:!1},Tx={description:E(`Replaces existing text with new text in a string.`),args:[U(`text_to_search (string)`,E(`The text within which to search and replace.`)),U(`search_for (string)`,E(`The string to search for within text_to_search.`)),U(`replace_with (string)`,E(`The string that will replace search_for.`)),U(`occurrence_number (number, optional)`,E(`The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced.`))],compute:function(e,t,n,r){let i=M(r,this.locale);if(i<0)return new A(E(`The occurrenceNumber (%s) must be positive or null.`,i));let a=N(e),o=N(t);if(o===``)return a;let s=N(n),c=new RegExp(ot(o),`g`);if(i===0)return a.replace(c,s);let l=0;return a.replace(c,e=>++l===i?s:e)},isExported:!0},Ex={description:E(`Combines text from multiple strings and/or arrays.`),args:[U(`delimiter (string)`,E(` A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.`)),U(`ignore_empty (boolean)`,E(`A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.`)),U(`text1 (string, range<string>)`,E(`Any text item. This could be a string, or an array of strings in a range.`)),U(`text2 (string, range<string>, repeating)`,E(`Additional text item(s).`))],compute:function(e,t,...n){let r=N(e),i=P(t),a=0;return da(n,(e,t)=>i&&N(t)===``?e:(a++?e+r:``)+N(t),``)},isExported:!0},Dx={description:E(`Splits text into rows or columns using specified column and row delimiters.`),args:[U(`text (string)`,E(`The text to split.`)),U(`col_delimiter (string, range<string>)`,E(`Character or string to split columns by.`)),U(`row_delimiter (string, range<string>, optional)`,E(`Character or string to split rows by.`)),U(`ignore_empty (boolean, default=false)`,E(`Whether to ignore empty cells.`)),U(`match_mode (number, default=0)`,E(`Searches the text for a delimiter match. 0 = case-sensitive, 1 = case-insensitive.`)),U(`pad_with (string, default="${k.NotAvailable}")`,E(`The value to use for padding empty cells.`))],compute:function(e,t,n,r={value:!1},i={value:0},a=new Hi){let o=N(e);if(o.length<=0)return new A(E(`No text to split.`));if(t===void 0&&n===void 0)return new A(E(`At least one delimiter must be provided.`));let s=I(t).flat().map(e=>ot(N(e))),c=I(n).flat().map(e=>ot(N(e)));if(s.some(e=>e===``)||c.some(e=>e===``))return new A(E(`The delimiters cannot be empty values.`));let l=P(r),u=M(i,this.locale);if(![0,1].includes(u))return new A(E(`match_mode should be a value of 0 or 1.`));let d=[],f=u===1?`gi`:`g`,p=c.filter(e=>!s.includes(e)),m=p.length?o.split(new RegExp(p.join(`|`),f)):[o];l&&(m=m.filter(e=>e!==``));let h=new RegExp(s.join(`|`),f);for(let e of m){let t=s.length?e.split(h):[e];l&&(t=t.filter(e=>e!==``)),d.push(t.map(e=>({value:e})))}let g=Math.max(...d.map(e=>e.length));for(let e of d)for(;e.length<g;)e.push(a);return _a(d)},isExported:!0},Ox={description:E(`Removes space characters.`),args:[U(`text (string)`,E(`The text or reference to a cell containing text to be trimmed.`))],compute:function(e){return Gt(N(e))},isExported:!0},kx={description:E(`Converts a specified string to uppercase.`),args:[U(`text (string)`,E(`The string to convert to uppercase.`))],compute:function(e){return N(e).toUpperCase()},isExported:!0},Ax={description:E(`Converts a number to text according to a specified format.`),args:[U(`number (number)`,E(`The number, date or time to format.`)),U(`format (string)`,E(`The case-sensitive format of the result, enclosed in quotation marks. Examples: "0.00" rounded to 2 decimal places, "hh:mm:ss" for hour:minutes:seconds.`))],compute:function(e,t){return L(M(e,this.locale),{format:N(t),locale:this.locale})},isExported:!0},jx={description:E(`Converts a string to a numeric value.`),args:[U(`value (number)`,E(`the string to be converted`))],compute:function(e){return M(e,this.locale)},isExported:!0};var Mx=l({HYPERLINK:()=>Nx});let Nx={description:E(`Creates a hyperlink in a cell.`),args:[U(`url (string)`,E(`The full URL of the link enclosed in quotation marks.`)),U(`link_label (string, optional)`,E(`The text to display in the cell, enclosed in quotation marks.`))],compute:function(e,t){let n=N(e).trim(),r=N(t)||n;return n===``?r:yt(r,n)},isExported:!0},Px=[{name:E(`Array`),functions:Bf},{name:E(`Database`),functions:Mh},{name:E(`Date`),functions:qh},{name:E(`Filter`),functions:Fg},{name:E(`Financial`),functions:V_},{name:E(`Info`),functions:Ny},{name:E(`Lookup`),functions:sb},{name:E(`Logical`),functions:Gy},{name:E(`Math`),functions:fp},{name:E(`Misc`),functions:up},{name:E(`Operator`),functions:Tb},{name:E(`Statistical`),functions:wm},{name:E(`Text`),functions:cx},{name:E(`Engineering`),functions:Og},{name:E(`Web`),functions:Mx},{name:E(`Parser`),functions:ox}],Fx=/^[A-Z0-9\_\.]+$/,Ix=new class extends g{mapping={};add(e,t){if(e=e.toUpperCase(),e in this.content)throw Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(e,t){if(e=e.toUpperCase(),!Fx.test(e))throw Error(E(`Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)`,e));let n=Ff(e,t);return zf(n),this.mapping[e]=Lx(n),super.replace(e,n),this}};for(let e of Px){let t=e.functions;for(let n in t){let r=t[n];r.category=r.category||e.name,n=n.replace(/_/g,`.`),Ix.add(n,{isExported:!1,...r})}}function Lx(e){function t(...t){let i=[],a=Lf(e,t.length);for(let n=0;n<t.length;n++){let r=a(n)??-1,o=e.args[r],s=t[n];if(!Or(s)&&o.acceptMatrixOnly)throw new zi(E(`Function %s expects the parameter '%s' to be reference to a cell or range.`,e.name,(n+1).toString()));i.push(!o.acceptMatrix)}return n(va(r.bind(this),t,i))}function n(t){return Or(t)?ga(t,t=>Bx(t,e.name)):Bx(t,e.name),t}function r(...t){for(let n=0;n<t.length;n++){let r=t[n],i=Lf(e,t.length);if(!e.args[i(n)||n].acceptErrors&&!Or(r)&&j(r?.value))return r}try{return i.apply(this,t)}catch(t){return Rx(t,e.name)}}function i(...t){this.debug&&=!1;let n=e.compute.apply(this,t);return Or(n)?typeof n[0][0]==`object`&&n[0][0]!==null&&`value`in n[0][0]?n:ha(n,e=>({value:e})):typeof n==`object`&&n&&`value`in n?n:(e.name,{value:n})}return t}function Rx(e,t){return zx(e)&&j(e.value)?(Hx(e)&&Bx(e,t),e):(console.error(e),new A(Vx+(Hx(e)?` `+e.message:``)))}function zx(e){return e?.value!==void 0&&typeof e.value==`string`}function Bx(e,t){e.message?.includes(`[[FUNCTION_NAME]]`)&&(e.message=e.message.replace(`[[FUNCTION_NAME]]`,t))}let Vx=E(`An unexpected error occurred. Submit a support ticket at odoo.com/help.`);function Hx(e){return e?.message!==void 0&&typeof e.message==`string`}var Ux=class{code=``;constructor(e=new Gx){this.scope=e}append(...e){this.code+=e.map(e=>e.toString()).join(`
|
|
14
|
+
`)}}return t}var Hd=class{get;disposeCallbacks=[];constructor(e){this.get=e}onDispose(e){this.disposeCallbacks.push(e)}dispose(){this.disposeCallbacks.forEach(e=>e())}};function Ud(){let e=(0,t.useEnv)();if(e.__spreadsheet_stores__ instanceof zd)return e.__spreadsheet_stores__;let n=new zd;return(0,t.useSubEnv)({__spreadsheet_stores__:n,getStore:e=>Kd(n.get(e),()=>n.trigger(`store-updated`))}),(0,t.onWillUnmount)(()=>n.dispose()),n}function B(e){let n=qd((0,t.useEnv)());return Gd(n,n.get(e))}function Wd(e,...n){let r=qd((0,t.useEnv)()),i=r.instantiate(e,...n);return(0,t.onWillUnmount)(()=>i.dispose()),Gd(r,i)}function Gd(e,n){let r=(0,t.useComponent)();return Kd(n,()=>{(0,t.status)(r)===`mounted`&&e.trigger(`store-updated`)})}function Kd(e,t){return new Proxy(e,{get(n,r,i){let a=n,o=Reflect.get(n,r,a);return e.mutators?.includes(r)?new Proxy(o,{apply(e,n,r){Reflect.apply(e,a,r)!==`noStateChange`&&t()}}):o}})}function qd(e){let t=e.__spreadsheet_stores__;if(!(t instanceof zd))throw Error(`No store provider found. Did you forget to call useStoreProvider()?`);return t}let Jd=Vd(`Model`);var Yd=class{mutators=[`register`,`unRegister`,`draw`,`startAnimation`,`stopAnimation`];renderers={};model;context=void 0;animationFrameId=null;registeredAnimations=new Set;constructor(e){this.model=e(Jd)}register(e){if(e.renderingLayers.length)for(let t of e.renderingLayers)this.renderers[t]||(this.renderers[t]=[]),this.renderers[t].push(e)}unRegister(e){for(let t of Object.keys(this.renderers))this.renderers[t]=this.renderers[t].filter(t=>t!==e)}drawLayer(e,t,n){let r=this.renderers[t];if(r)for(let i of r)e.ctx.save(),i.drawLayer(e,t,n),e.ctx.restore();return`noStateChange`}draw(e,t){if(e||=this.context,!e)throw Error(`Rendering context is not defined`);this.context=e;for(let n of Ar())this.model.drawLayer(e,n),this.drawLayer(e,n,t);return`noStateChange`}startAnimation(e){if(this.registeredAnimations.add(e),!this.animationFrameId){let e=t=>{this.animationFrameId=requestAnimationFrame(e),this.draw(void 0,t)};this.animationFrameId=requestAnimationFrame(e)}return`noStateChange`}stopAnimation(e){return this.registeredAnimations.delete(e),this.registeredAnimations.size===0&&this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),`noStateChange`}dispose(){this.animationFrameId&&=(cancelAnimationFrame(this.animationFrameId),null)}},Xd=class extends Hd{model=this.get(Jd);getters=this.model.getters;renderer=this.get(Yd);constructor(e){super(e),this.model.on(`command-dispatched`,this,this.handle),this.model.on(`command-finalized`,this,this.finalize),this.renderer.register(this),this.onDispose(()=>{this.model.off(`command-dispatched`,this),this.model.off(`command-finalized`,this),this.renderer.unRegister(this)})}get renderingLayers(){return[]}handle(e){}finalize(){}drawLayer(e,t,n){}};let Zd={id:`void-composer`,get editionMode(){return`inactive`},startEdition:()=>{throw Error(`No composer is registered`)},stopEdition:()=>{throw Error(`No composer is registered`)},setCurrentContent:()=>{throw Error(`No composer is registered`)}};var Qd=class extends Xd{mutators=[`focusComposer`,`focusActiveComposer`];activeComposer=Zd;_focusMode=`inactive`;get focusMode(){return this.activeComposer.editionMode===`inactive`?`inactive`:this._focusMode}focusComposer(e,t){if(this.activeComposer=e,this.getters.isReadonly())return`noStateChange`;this._focusMode=t.focusMode||`contentFocus`,this._focusMode!==`inactive`&&this.setComposerContent(t)}focusActiveComposer(e){if(this.getters.isReadonly())return`noStateChange`;if(!this.activeComposer)throw Error(`No composer is registered`);this._focusMode=e.focusMode||`contentFocus`,this._focusMode!==`inactive`&&this.setComposerContent(e)}setComposerContent({content:e,selection:t}){this.activeComposer.editionMode===`inactive`?this.activeComposer.startEdition(e,t):e&&this.activeComposer.setCurrentContent(e,t)}};let $d={},ef=0;function V(e,...t){let n=`__sheet__${ef++}`;return nf(n,String.raw(e,...t)),rf(n),n}function tf(e){let t=e.split(/(\{|\}|;)/).map(e=>e.trim()),n=[],r=[],i=[];function a(e,t){let r=[];for(let i of n[e]){let o=t&&t+` `+i||i;o.includes(`&`)&&(o=i.replace(/&/g,t||``)),e<n.length-1&&(o=a(e+1,o)),r.push(o)}return r.join(`, `)}function o(){i.length&&(r.push(a(0)+` {`),r.push(...i),r.push(`}`),i=[])}for(;t.length;){let e=t.shift();e===`}`?(o(),n.pop()):(t[0]===`{`&&(o(),n.push(e.split(/\s*,\s*/)),t.shift()),t[0]===`;`&&i.push(` `+e+`;`))}return r.join(`
|
|
15
|
+
`)}function nf(e,t){let n=document.createElement(`style`);n.textContent=tf(t),$d[e]=n}function rf(e){let t=$d[e];t.setAttribute(`component`,e),document.head.appendChild(t)}function af({strikethrough:e,underline:t}){return!e&&!t?`none`:`${e?`line-through`:``} ${t?`underline`:``}`}function of(e){let t=sf(e);return e&&e.fillColor&&(t.background=e.fillColor),t}function sf(e){let t={};if(!e)return t;if(e.bold&&(t[`font-weight`]=`bold`),e.italic&&(t[`font-style`]=`italic`),e.strikethrough||e.underline){let n=e.strikethrough?`line-through`:``;n=e.underline?n+` underline`:n,t[`text-decoration`]=n}return e.textColor&&(t.color=e.textColor),t}function H(e){let t=``;for(let n in e)e[n]&&(t+=`${n}:${e[n]}; `);return t}function cf(e){let t=window.getComputedStyle(e);return{top:parseInt(t.marginTop,10)||0,bottom:parseInt(t.marginBottom,10)||0,left:parseInt(t.marginLeft,10)||0,right:parseInt(t.marginRight,10)||0}}let lf=new g;function uf(){return!!window.Chart.registry.plugins.get(`chartShowValuesPlugin`)}function df(){if(!(!window.Chart||uf()))for(let e of lf.getAll())e.register(window.Chart)}function ff(){if(window.Chart)for(let e of lf.getAll())e.unregister(window.Chart)}var pf=class extends Xd{mutators=[`disableAnimationForChart`,`enableAnimationForChart`];animationPlayed={};disableAnimationForChart(e,t){return this.animationPlayed[e]=t,`noStateChange`}enableAnimationForChart(e){return this.animationPlayed[e]=void 0,`noStateChange`}};function mf(){return class extends window.Chart.BarController{static id=`funnel`;static defaults={...window.Chart?.BarController.defaults,dataElementType:`funnel`,animation:{duration:e=>e.type===`data`?1e3*(e.raw[1]/Math.max(...e.dataset.data.map(e=>e[1]))):1e3}};updateElements(e,t,n,r){super.updateElements(e,t,n,r);for(let i=t;i<t+n;i++){let t=e[i];this.updateElement(t,i,{nextElement:e[i+1]},r)}}}}function hf(){return class extends window.Chart.BarElement{static id=`funnel`;draw(e){e.save();let{x:t,y:n,height:r,nextElement:i,base:a,options:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=gf(this),c=(s-(i?gf(i):0))/2,l=Math.min(t,a),u=n-r/2;e.fillStyle=o.backgroundColor,e.beginPath(),e.moveTo(l,u),e.lineTo(l+s,u),e.lineTo(l+s-c,u+r),e.lineTo(l+c,u+r),e.closePath(),e.fill(),o.borderWidth&&(e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,e.stroke()),e.restore()}inRange(e,t){let{x:n,y:r,height:i,nextElement:a,base:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=gf(this),c=a?gf(a):0,l=Math.min(n,o),u=r-i/2;if(t<u||t>u+i)return!1;let d=(s-c)/2,f=l+d*(t-u)/i,p=l+s-d*(t-u)/i;return!(e<f||e>p)}}}function gf(e){let{x:t,base:n}=e.getProps([`x`,`base`]);return Math.max(t,n)-Math.min(t,n)}let _f=function(e){if(!e.length)return{x:0,y:0};let{x:t,y:n,base:r,width:i,height:a}=e[0].element.getProps([`x`,`y`,`width`,`height`,`base`]),o=Math.min(t,r),s=n-a/2;return{x:o+i*2/3,y:s+a/2}},vf=`000000`,yf={arrows:`3Arrows`,smiley:`3Symbols`,dots:`3TrafficLights1`},bf={styleSheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,sst:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,Relationships:`http://schemas.openxmlformats.org/package/2006/relationships`,Types:`http://schemas.openxmlformats.org/package/2006/content-types`,worksheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,workbook:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,drawing:`http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing`,table:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,revision:`http://schemas.microsoft.com/office/spreadsheetml/2014/revision`,revision3:`http://schemas.microsoft.com/office/spreadsheetml/2016/revision3`,markupCompatibility:`http://schemas.openxmlformats.org/markup-compatibility/2006`},xf=`http://schemas.openxmlformats.org/drawingml/2006/main`,Sf=`http://schemas.openxmlformats.org/drawingml/2006/chart`,Cf={workbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml`,macroEnabledWorkbook:`application/vnd.ms-excel.sheet.macroEnabled.main+xml`,templateWorkbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml`,macroEnabledTemplateWorkbook:`application/vnd.ms-excel.template.macroEnabled.main+xml`,excelAddInWorkbook:`application/vnd.ms-excel.addin.macroEnabled.main+xml`,sheet:`application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml`,metadata:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml`,sharedStrings:`application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml`,styles:`application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml`,drawing:`application/vnd.openxmlformats-officedocument.drawing+xml`,chart:`application/vnd.openxmlformats-officedocument.drawingml.chart+xml`,themes:`application/vnd.openxmlformats-officedocument.theme+xml`,table:`application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml`,pivot:`application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml`,externalLink:`application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml`},wf={document:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument`,sheet:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet`,metadata:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata`,sharedStrings:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings`,styles:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles`,drawing:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing`,chart:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart`,theme:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme`,table:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/table`,hyperlink:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink`,image:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/image`},Tf=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,Ef=.75,Df=.143,Of=8.43,kf=12.75,Af={FLOOR:[{type:`NUMBER`,value:1}],CEILING:[{type:`NUMBER`,value:1}],ROUND:[{type:`NUMBER`,value:0}],ROUNDUP:[{type:`NUMBER`,value:0}],ROUNDDOWN:[{type:`NUMBER`,value:0}]},jf=`ACOT,ACOTH,AGGREGATE,ARABIC,BASE,BETA.DIST,BETA.INV,BINOM.DIST,BINOM.DIST.RANGE,BINOM.INV,BITAND,BITLSHIFT,BITOR,BITRSHIFT,BITXOR,BYCOL,BYROW,CEILING.MATH,CEILING.PRECISE,CHISQ.DIST,CHISQ.DIST.RT,CHISQ.INV,CHISQ.INV.RT,CHISQ.TEST,CHOOSECOLS,CHOOSEROWS,COMBINA,CONCAT,CONFIDENCE.NORM,CONFIDENCE.T,COT,COTH,COVARIANCE.P,COVARIANCE.S,CSC,CSCH,DAYS,DECIMAL,DROP,ERF.PRECISE,ERFC.PRECISE,EXPAND,EXPON.DIST,F.DIST,F.DIST.RT,F.INV,F.INV.RT,F.TEST,FIELDVALUE,FILTERXML,FLOOR.MATH,FLOOR.PRECISE,FORECAST.ETS,FORECAST.ETS.CONFINT,FORECAST.ETS.SEASONALITY,FORECAST.ETS.STAT,FORECAST.LINEAR,FORMULATEXT,GAMMA,GAMMA.DIST,GAMMA.INV,GAMMALN.PRECISE,GAUSS,HSTACK,HYPGEOM.DIST,IFNA,IFS,IMCOSH,IMCOT,IMCSC,IMCSCH,IMSEC,IMSECH,IMSINH,IMTAN,ISFORMULA,ISOMITTED,ISOWEEKNUM,LAMBDA,LET,LOGNORM.DIST,LOGNORM.INV,MAKEARRAY,MAP,MAXIFS,MINIFS,MODE.MULT,MODE.SNGL,MUNIT,NEGBINOM.DIST,NORM.DIST,NORM.INV,NORM.S.DIST,NORM.S.INV,NUMBERVALUE,PDURATION,PERCENTILE.EXC,PERCENTILE.INC,PERCENTRANK.EXC,PERCENTRANK.INC,PERMUTATIONA,PHI,POISSON.DIST,PQSOURCE,PYTHON_STR,PYTHON_TYPE,PYTHON_TYPENAME,QUARTILE.EXC,QUARTILE.INC,QUERYSTRING,RANDARRAY,RANK.AVG,RANK.EQ,REDUCE,RRI,SCAN,SEC,SECH,SEQUENCE,SHEET,SHEETS,SKEW.P,SORTBY,STDEV.P,STDEV.S,SWITCH,T.DIST,T.DIST.2T,T.DIST.RT,T.INV,T.INV.2T,T.TEST,TAKE,TEXTAFTER,TEXTBEFORE,TEXTJOIN,TEXTSPLIT,TOCOL,TOROW,UNICHAR,UNICODE,UNIQUE,VAR.P,VAR.S,VSTACK,WEBSERVICE,WEIBULL.DIST,WRAPCOLS,WRAPROWS,XLOOKUP,XOR,Z.TEST`.split(`,`),Mf=/(.*?)\((.*?)\)(.*)/,Nf=[`ANY`,`BOOLEAN`,`DATE`,`NUMBER`,`STRING`,`RANGE`,`RANGE<BOOLEAN>`,`RANGE<DATE>`,`RANGE<NUMBER>`,`RANGE<STRING>`,`META`];function U(e,t=``){return Pf(e,t)}function Pf(e,t){let n=e.match(Mf),r=n[1].trim();if(!r)throw Error(`Function argument definition is missing a name: '${e}'.`);let i=[],a=!1,o=!1,s;for(let e of n[2].split(`,`)){let t=e.trim().toUpperCase(),n=Nf.find(e=>t===e);n?i.push(n):t===`RANGE<ANY>`?i.push(`RANGE`):t===`OPTIONAL`?a=!0:t===`REPEATING`?o=!0:t.startsWith(`DEFAULT=`)&&(s=e.trim().slice(8))}let c={name:r,description:t,type:i};return(i.includes(`ANY`)||i.includes(`RANGE`))&&(c.acceptErrors=!0),a&&(c.optional=!0),o&&(c.repeating=!0),s!==void 0&&(c.default=!0,c.defaultValue=s),i.some(e=>e.startsWith(`RANGE`))&&(c.acceptMatrix=!0),i.every(e=>e.startsWith(`RANGE`))&&(c.acceptMatrixOnly=!0),c}function Ff(e,t){let n=0,r=0,i=0,a=0;for(let e of t.args)n++,!e.optional&&!e.repeating&&!e.default&&r++,e.repeating&&i++,(e.optional||e.default)&&a++;let o=t;return o.minArgRequired=r,o.maxArgPossible=i?1/0:n,o.nbrArgRepeating=i,o.nbrArgOptional=a,o.hidden=t.hidden||!1,o.name=e,o}let If={};function Lf(e,t){let n=e.name;return If[n]?.[t]||(If[n]||(If[n]={}),If[n][t]||(If[n][t]=Rf(e,t)),If[n][t])}function Rf(e,t){let n={},r=e.nbrArgRepeating?Math.floor((t-e.minArgRequired)/e.nbrArgRepeating):0,i=e.nbrArgRepeating*r,a=t-e.minArgRequired-i,o=0,s=0;for(let t=0;t<e.args.length;t++){let i=e.args[t];if(i.optional||i.default){s<a&&(n[o]=t,o++),s++;continue}if(i.repeating){for(let i=0;i<r;i++)for(let r=0;r<e.nbrArgRepeating;r++)n[o]=t+r,o++;t+=e.nbrArgRepeating-1;continue}n[o]=t,o++}return e=>n[e]}function zf(e){if(e.nbrArgRepeating&&e.nbrArgOptional>=e.nbrArgRepeating)throw Error(`Function ${e.name} has more optional arguments than repeatable ones.`);let t=!1,n=!1;for(let r of e.args){if(r.type.includes(`META`)&&r.type.length>1)throw Error(`Function ${e.name} has an argument that has been declared with more than one type whose type 'META'. The 'META' type can only be declared alone.`);if(r.repeating){if(!n&&t)throw Error(`Function ${e.name} has non-consecutive repeating arguments. All repeating arguments must be declared consecutively.`);t=!0,n=!0}else n=!1}}var Bf=l({ARRAY_CONSTRAIN:()=>Vf,CHOOSECOLS:()=>Hf,CHOOSEROWS:()=>Uf,EXPAND:()=>Wf,FLATTEN:()=>Gf,FREQUENCY:()=>Kf,HSTACK:()=>qf,MDETERM:()=>Jf,MINVERSE:()=>Yf,MMULT:()=>Xf,SUMPRODUCT:()=>Zf,SUMX2MY2:()=>$f,SUMX2PY2:()=>ep,SUMXMY2:()=>tp,TOCOL:()=>ip,TOROW:()=>ap,TRANSPOSE:()=>op,VSTACK:()=>sp,WRAPCOLS:()=>cp,WRAPROWS:()=>lp});let Vf={description:E(`Returns a result array constrained to a specific width and height.`),args:[U(`input_range (any, range<any>)`,E(`The range to constrain.`)),U(`rows (number)`,E(`The number of rows in the constrained array.`)),U(`columns (number)`,E(`The number of columns in the constrained array.`))],compute:function(e,t,n){let r=I(e),i=ta(t?.value,this.locale),a=ta(n?.value,this.locale);if(i<=0)return new A(E(`The rows argument (%s) must be strictly positive.`,i.toString()));if(a<=0)return new A(E(`The columns argument (%s) must be strictly positive.`,a.toString()));let o=Math.min(i,r[0].length);return ma(Math.min(a,r.length),o,(e,t)=>r[e][t])},isExported:!1},Hf={description:E(`Creates a new array from the selected columns in the existing range.`),args:[U(`array (any, range<any>)`,E(`The array that contains the columns to be returned.`)),U(`col_num (number, range<number>)`,E(`The first column index of the columns to be returned.`)),U(`col_num2 (number, range<number>, repeating)`,E(`The columns indexes of the columns to be returned.`))],compute:function(e,...t){let n=I(e),r=Aa(t,e=>ta(e?.value,this.locale)),i=r.filter(e=>e===0||n.length<Math.abs(e));if(i.length!==0)return new A(E(`The columns arguments must be between -%s and %s (got %s), excluding 0.`,n.length.toString(),n.length.toString(),i.join(`,`)));let a=Array(r.length);for(let e=0;e<r.length;e++)r[e]>0?a[e]=n[r[e]-1]:a[e]=n[n.length+r[e]];return a},isExported:!0},Uf={description:E(`Creates a new array from the selected rows in the existing range.`),args:[U(`array (any, range<any>)`,E(`The array that contains the rows to be returned.`)),U(`row_num (number, range<number>)`,E(`The first row index of the rows to be returned.`)),U(`row_num2 (number, range<number>, repeating)`,E(`The rows indexes of the rows to be returned.`))],compute:function(e,...t){let n=I(e),r=Aa(t,e=>ta(e?.value,this.locale)),i=n.length,a=r.filter(e=>e===0||n[0].length<Math.abs(e));return a.length===0?ma(i,r.length,(e,t)=>r[t]>0?n[e][r[t]-1]:n[e][n[e].length+r[t]]):new A(E(`The rows arguments must be between -%s and %s (got %s), excluding 0.`,n[0].length.toString(),n[0].length.toString(),a.join(`,`)))},isExported:!0},Wf={description:E(`Expands or pads an array to specified row and column dimensions.`),args:[U(`array (any, range<any>)`,E(`The array to expand.`)),U(`rows (number)`,E(`The number of rows in the expanded array. If missing, rows will not be expanded.`)),U(`columns (number, optional)`,E(`The number of columns in the expanded array. If missing, columns will not be expanded.`)),U(`pad_with (any, default=0)`,E(`The value with which to pad.`))],compute:function(e,t,n,r={value:0}){let i=I(e),a=ta(t?.value,this.locale),o=n===void 0?i.length:ta(n.value,this.locale);return a<i[0].length?new A(E(`The rows arguments (%s) must be greater or equal than the number of rows of the array.`,a.toString())):o<i.length?new A(E(`The columns arguments (%s) must be greater or equal than the number of columns of the array.`,o.toString())):ma(o,a,(e,t)=>e>=i.length||t>=i[e].length?r:i[e][t])},isExported:!0},Gf={description:E(`Flattens all the values from one or more ranges into a single column.`),args:[U(`range (any, range<any>)`,E(`The first range to flatten.`)),U(`range2 (any, range<any>, repeating)`,E(`Additional ranges to flatten.`))],compute:function(...e){return[Aa(e,e=>e===void 0?{value:``}:e)]},isExported:!1},Kf={description:E(`Calculates the frequency distribution of a range.`),args:[U(`data (range<number>)`,E(`The array of ranges containing the values to be counted.`)),U(`classes (number, range<number>)`,E(`The range containing the set of classes.`))],compute:function(e,t){let n=Aa([e],e=>e.value).filter(e=>typeof e==`number`),r=Aa([t],e=>e.value).filter(e=>typeof e==`number`).map((e,t)=>({initialIndex:t,value:e,count:0})).sort((e,t)=>e.value-t.value);r.push({initialIndex:r.length,value:1/0,count:0});let i=n.sort((e,t)=>e-t),a=0;for(let e of i){for(;e>r[a].value&&a<r.length-1;)a++;r[a].count++}return[r.sort((e,t)=>e.initialIndex-t.initialIndex).map(e=>e.count)]},isExported:!0},qf={description:E(`Appends ranges horizontally and in sequence to return a larger array.`),args:[U(`range1 (any, range<any>)`,E(`The first range to be appended.`)),U(`range2 (any, range<any>, repeating)`,E(`Additional ranges to add to range1.`))],compute:function(...e){let t=Math.max(...e.map(e=>e?.[0]?.length??0)),n=[];for(let r of e){let e=I(r);for(let r=0;r<e.length;r++){let i=Array(t).fill({value:null});for(let t=0;t<e[r].length;t++)i[t]=e[r][t];n.push(i)}}return n},isExported:!0},Jf={description:E(`Returns the matrix determinant of a square matrix.`),args:[U(`square_matrix (number, range<number>)`,E(`An range with an equal number of rows and columns representing a matrix whose determinant will be calculated.`))],compute:function(e){let t=$i(e,`square_matrix`);return yu(t)?Su(t).determinant:new A(E(`The argument square_matrix must have the same number of columns and rows.`))},isExported:!0},Yf={description:E(`Returns the multiplicative inverse of a square matrix.`),args:[U(`square_matrix (number, range<number>)`,E(`An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated.`))],compute:function(e){let t=$i(e,`square_matrix`);if(!yu(t))return new A(E(`The argument square_matrix must have the same number of columns and rows.`));let{inverted:n}=Su(t);return n||new A(E(`The matrix is not invertible.`))},isExported:!0},Xf={description:E(`Calculates the matrix product of two matrices.`),args:[U(`matrix1 (number, range<number>)`,E(`The first matrix in the matrix multiplication operation.`)),U(`matrix2 (number, range<number>)`,E(`The second matrix in the matrix multiplication operation.`))],compute:function(e,t){let n=$i(e,`matrix1`),r=$i(t,`matrix2`);return n.length===0||r.length===0?new A(E(`The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.`)):n.length===r[0].length?wu(n,r):new A(E(`In [[FUNCTION_NAME]], the number of columns of the first matrix (%s) must be equal to the number of rows of the second matrix (%s).`,n.length.toString(),r[0].length.toString()))},isExported:!0},Zf={description:E(`Calculates the sum of the products of corresponding entries in equal-sized ranges.`),args:[U(`range1 (number, range<number>)`,E(`The first range whose entries will be multiplied with corresponding entries in the other ranges.`)),U(`range2 (number, range<number>, repeating)`,E(`The other range whose entries will be multiplied with corresponding entries in the other ranges.`))],compute:function(...e){if(!vu(...e))return new A(E(`All the ranges must have the same dimensions.`));let t=e.map(I),n=0;for(let e=0;e<t[0].length;e++)for(let r=0;r<t[0][e].length;r++){if(!t.every(t=>typeof t[e][r].value==`number`))continue;let i=1;for(let n of t)i*=M(n[e][r],this.locale);n+=i}return n},isExported:!0};function Qf(e,t,n){if(!vu(e,t))return new A(E(`The arguments array_x and array_y must have the same dimensions.`));let r=I(e),i=I(t),a=!1,o=0;for(let e in r)for(let t in r[e]){let s=r[e][t].value,c=i[e][t].value;typeof s!=`number`||typeof c!=`number`||(a=!0,o+=n(s,c))}return a?o:new A(E(`The arguments array_x and array_y must contain at least one pair of numbers.`))}let $f={description:E(`Calculates the sum of the difference of the squares of the values in two array.`),args:[U(`array_x (number, range<number>)`,E(`The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.`)),U(`array_y (number, range<number>)`,E(`The array or range of values whose squares will be subtracted from the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return Qf(e,t,(e,t)=>e**2-t**2)},isExported:!0},ep={description:E(`Calculates the sum of the sum of the squares of the values in two array.`),args:[U(`array_x (number, range<number>)`,E(`The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.`)),U(`array_y (number, range<number>)`,E(`The array or range of values whose squares will be added to the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return Qf(e,t,(e,t)=>e**2+t**2)},isExported:!0},tp={description:E(`Calculates the sum of squares of the differences of values in two array.`),args:[U(`array_x (number, range<number>)`,E(`The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.`)),U(`array_y (number, range<number>)`,E(`The array or range of values that will be subtracted from corresponding entries in array_x, the result squared, and all such results added together.`))],compute:function(e,t){return Qf(e,t,(e,t)=>(e-t)**2)},isExported:!0},np=[U(`array (any, range<any>)`,E(`The array which will be transformed.`)),U(`ignore (number, default=0)`,E(`The control to ignore blanks and errors. 0 (default) is to keep all values, 1 is to ignore blanks, 2 is to ignore errors, and 3 is to ignore blanks and errors.`)),U(`scan_by_column (number, default=false)`,E(`Whether the array should be scanned by column. True scans the array by column and false (default) scans the array by row.`))];function rp(e){let t=Math.trunc(e);if(t===0)return()=>!0;if(t===1)return e=>e.value!==null;if(t===2)return e=>!j(e.value);if(t===3)return e=>e.value!==null&&!j(e.value);throw new A(E(`Argument ignore must be between 0 and 3`))}let ip={description:E(`Transforms a range of cells into a single column.`),args:np,compute:function(e,t={value:0},n={value:!1}){let r=I(e),i=M(t.value,this.locale),a=(P(n.value)?r:_a(r)).flat().filter(rp(i));return a.length===0?new Hi(E(`No results for the given arguments of TOCOL.`)):[a]},isExported:!0},ap={description:E(`Transforms a range of cells into a single row.`),args:np,compute:function(e,t={value:0},n={value:!1}){let r=I(e),i=M(t.value,this.locale),a=(P(n.value)?r:_a(r)).flat().filter(rp(i)).map(e=>[e]);return a.length===0||a[0].length===0?new Hi(E(`No results for the given arguments of TOROW.`)):a},isExported:!0},op={description:E(`Transposes the rows and columns of a range.`),args:[U(`range (any, range<any>)`,E(`The range to be transposed.`))],compute:function(e){let t=I(e),n=t[0].length,r=t.length;return ma(n,r,(e,n)=>t[n][e])},isExported:!0},sp={description:E(`Appends ranges vertically and in sequence to return a larger array.`),args:[U(`range1 (any, range<any>)`,E(`The first range to be appended.`)),U(`range2 (any, range<any>, repeating)`,E(`Additional ranges to add to range1.`))],compute:function(...e){let t=Math.max(...e.map(e=>I(e).length)),n=e.reduce((e,t)=>e+I(t)[0].length,0),r=Array(t).fill([]).map(()=>Array(n).fill({value:0})),i=0;for(let t of e){let e=I(t);for(let t=0;t<e.length;t++)for(let n=0;n<e[t].length;n++)r[t][i+n]=e[t][n];i+=e[0].length}return r},isExported:!0},cp={description:E(`Wraps the provided row or column of cells by columns after a specified number of elements to form a new array.`),args:[U(`range (any, range<any>)`,E(`The range to wrap.`)),U(`wrap_count (number)`,E(`The maximum number of cells for each column, rounded down to the nearest whole number.`)),U(`pad_with (any, default=0)`,E(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=I(e),i=ta(t?.value,this.locale);if(!_u(r))return new A(E(`Argument range must be a single row or column.`));let a=r.flat();return ma(Math.ceil(a.length/i),i,(e,t)=>{let r=e*i+t;return r<a.length?a[r]:n})},isExported:!0},lp={description:E(`Wraps the provided row or column of cells by rows after a specified number of elements to form a new array.`),args:[U(`range (any, range<any>)`,E(`The range to wrap.`)),U(`wrap_count (number)`,E(`The maximum number of cells for each row, rounded down to the nearest whole number.`)),U(`pad_with (any, default=0)`,E(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=I(e),i=ta(t?.value,this.locale);if(!_u(r))return new A(E(`Argument range must be a single row or column.`));let a=r.flat();return ma(i,Math.ceil(a.length/i),(e,t)=>{let r=t*i+e;return r<a.length?a[r]:n})},isExported:!0};var up=l({FORMAT_LARGE_NUMBER:()=>dp});let dp={description:E(`Apply a large number format`),args:[U(`value (number)`,E(`The number.`)),U(`unit (string, optional)`,E(`The formatting unit. Use 'k', 'm', or 'b' to force the unit`))],compute:function(e,t){return{value:M(e,this.locale),format:Io(e,t,this.locale)}}};var fp=l({ABS:()=>mp,ACOS:()=>hp,ACOSH:()=>gp,ACOT:()=>_p,ACOTH:()=>vp,ASIN:()=>yp,ASINH:()=>bp,ATAN:()=>xp,ATAN2:()=>Sp,ATANH:()=>Cp,CEILING:()=>wp,CEILING_MATH:()=>Ep,CEILING_PRECISE:()=>Dp,COS:()=>Op,COSH:()=>kp,COT:()=>Ap,COTH:()=>jp,COUNTBLANK:()=>Mp,COUNTIF:()=>Np,COUNTIFS:()=>Pp,COUNTUNIQUE:()=>Fp,COUNTUNIQUEIFS:()=>Ip,CSC:()=>Lp,CSCH:()=>Rp,DECIMAL:()=>zp,DEGREES:()=>Bp,EXP:()=>Vp,FLOOR:()=>Hp,FLOOR_MATH:()=>Wp,FLOOR_PRECISE:()=>Gp,INT:()=>Cm,ISEVEN:()=>Kp,ISODD:()=>Jp,ISO_CEILING:()=>qp,LN:()=>Yp,LOG:()=>Xp,MOD:()=>Qp,MUNIT:()=>$p,ODD:()=>em,PI:()=>tm,POWER:()=>nm,PRODUCT:()=>rm,RAND:()=>im,RANDARRAY:()=>am,RANDBETWEEN:()=>om,ROUND:()=>sm,ROUNDDOWN:()=>cm,ROUNDUP:()=>lm,SEC:()=>um,SECH:()=>dm,SEQUENCE:()=>fm,SIN:()=>pm,SINH:()=>mm,SQRT:()=>hm,SUM:()=>gm,SUMIF:()=>_m,SUMIFS:()=>vm,TAN:()=>ym,TANH:()=>bm,TRUNC:()=>Sm});let pp=/^-?[a-z0-9]+$/i,mp={description:E(`Absolute value of a number.`),args:[U(`value (number)`,E(`The number of which to return the absolute value.`))],compute:function(e){return Math.abs(M(e,this.locale))},isExported:!0},hp={description:E(`Inverse cosine of a value, in radians.`),args:[U(`value (number)`,E(`The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=M(e,this.locale);return Math.abs(t)>1?new A(E(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.acos(t)},isExported:!0},gp={description:E(`Inverse hyperbolic cosine of a number.`),args:[U(`value (number)`,E(`The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.`))],compute:function(e){let t=M(e,this.locale);return t<1?new A(E(`The value (%s) must be greater than or equal to 1.`,t)):Math.acosh(t)},isExported:!0},_p={description:E(`Inverse cotangent of a value.`),args:[U(`value (number)`,E(`The value for which to calculate the inverse cotangent.`))],compute:function(e){let t=M(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},vp={description:E(`Inverse hyperbolic cotangent of a value.`),args:[U(`value (number)`,E(`The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.`))],compute:function(e){let t=M(e,this.locale);return Math.abs(t)<=1?new A(E(`The value (%s) cannot be between -1 and 1 inclusive.`,t)):Math.log((t+1)/(t-1))/2},isExported:!0},yp={description:E(`Inverse sine of a value, in radians.`),args:[U(`value (number)`,E(`The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=M(e,this.locale);return Math.abs(t)>1?new A(E(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.asin(t)},isExported:!0},bp={description:E(`Inverse hyperbolic sine of a number.`),args:[U(`value (number)`,E(`The value for which to calculate the inverse hyperbolic sine.`))],compute:function(e){return Math.asinh(M(e,this.locale))},isExported:!0},xp={description:E(`Inverse tangent of a value, in radians.`),args:[U(`value (number)`,E(`The value for which to calculate the inverse tangent.`))],compute:function(e){return Math.atan(M(e,this.locale))},isExported:!0},Sp={description:E(`Angle from the X axis to a point (x,y), in radians.`),args:[U(`x (number)`,E(`The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`)),U(`y (number)`,E(`The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`))],compute:function(e,t){let n=M(e,this.locale),r=M(t,this.locale);return n===0&&r===0?new Gi(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):Math.atan2(r,n)},isExported:!0},Cp={description:E(`Inverse hyperbolic tangent of a number.`),args:[U(`value (number)`,E(`The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.`))],compute:function(e){let t=M(e,this.locale);return Math.abs(t)>=1?new A(E(`The value (%s) must be between -1 and 1 exclusive.`,t)):Math.atanh(t)},isExported:!0},wp={description:E(`Rounds number up to nearest multiple of factor.`),args:[U(`value (number)`,E(`The value to round up to the nearest integer multiple of factor.`)),U(`factor (number, default=1)`,E(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=M(e,this.locale),r=M(t,this.locale);return r<0&&n>0?new A(E(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.ceil(n/r)*r:0,format:e?.format}},isExported:!0};function Tp(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.ceil(e/t)*t:n===0?-Math.floor(Math.abs(e)/t)*t:-Math.ceil(Math.abs(e)/t)*t)}let Ep={description:E(`Rounds number up to nearest multiple of factor.`),args:[U(`number (number)`,E(`The value to round up to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),U(`mode (number, default=0)`,E(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.`))],compute:function(e,t={value:1},n={value:0}){let r=M(t,this.locale);return{value:Tp(M(e,this.locale),r,M(n,this.locale)),format:e?.format}},isExported:!0},Dp={description:E(`Rounds number up to nearest multiple of factor.`),args:[U(`number (number)`,E(`The value to round up to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=M(t,this.locale);return{value:Tp(M(e,this.locale),n),format:e?.format}},isExported:!0},Op={description:E(`Cosine of an angle provided in radians.`),args:[U(`angle (number)`,E(`The angle to find the cosine of, in radians.`))],compute:function(e){return Math.cos(M(e,this.locale))},isExported:!0},kp={description:E(`Hyperbolic cosine of any real number.`),args:[U(`value (number)`,E(`Any real value to calculate the hyperbolic cosine of.`))],compute:function(e){return Math.cosh(M(e,this.locale))},isExported:!0},Ap={description:E(`Cotangent of an angle provided in radians.`),args:[U(`angle (number)`,E(`The angle to find the cotangent of, in radians.`))],compute:function(e){let t=M(e,this.locale);return t===0?new Gi(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tan(t)},isExported:!0},jp={description:E(`Hyperbolic cotangent of any real number.`),args:[U(`value (number)`,E(`Any real value to calculate the hyperbolic cotangent of.`))],compute:function(e){let t=M(e,this.locale);return t===0?new Gi(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tanh(t)},isExported:!0},Mp={description:E(`Number of empty values.`),args:[U(`value1 (any, range)`,E(`The first value or range in which to count the number of blanks.`)),U(`value2 (any, range, repeating)`,E(`Additional values or ranges in which to count the number of blanks.`))],compute:function(...e){return da(e,(e,t)=>t===void 0||t.value===null||t.value===``?e+1:e,0)},isExported:!0},Np={description:E(`A conditional count across a range.`),args:[U(`range (range)`,E(`The range that is tested against criterion.`)),U(`criterion (string)`,E(`The pattern or test to apply to range.`))],compute:function(...e){let t=0;return wa(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},Pp={description:E(`Count values depending on multiple criteria.`),args:[U(`criteria_range1 (range)`,E(`The range to check against criterion1.`)),U(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1.`)),U(`criteria_range2 (any, range, repeating)`,E(`Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.`)),U(`criterion2 (string, repeating)`,E(`Additional criteria to check.`))],compute:function(...e){let t=0;return wa(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},Fp={description:E(`Counts number of unique values in a range.`),args:[U(`value1 (any, range)`,E(`The first value or range to consider for uniqueness.`)),U(`value2 (any, range, repeating)`,E(`Additional values or ranges to consider for uniqueness.`))],compute:function(...e){return mu(e)}},Ip={description:E(`Counts number of unique values in a range, filtered by a set of criteria.`),args:[U(`range (range)`,E(`The range of cells from which the number of unique values will be counted.`)),U(`criteria_range1 (range)`,E(`The range of cells over which to evaluate criterion1.`)),U(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.`)),U(`criteria_range2 (any, range, repeating)`,E(`Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.`)),U(`criterion2 (string, repeating)`,E(`The pattern or test to apply to criteria_range2.`))],compute:function(e,...t){let n=new Set;return wa(t,(t,r)=>{let i=e[t]?.[r];ja(i)&&n.add(i.value)},this.locale),n.size}},Lp={description:E(`Cosecant of an angle provided in radians.`),args:[U(`angle (number)`,E(`The angle to find the cosecant of, in radians.`))],compute:function(e){let t=M(e,this.locale);return t===0?new Gi(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sin(t)},isExported:!0},Rp={description:E(`Hyperbolic cosecant of any real number.`),args:[U(`value (number)`,E(`Any real value to calculate the hyperbolic cosecant of.`))],compute:function(e){let t=M(e,this.locale);return t===0?new Gi(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sinh(t)},isExported:!0},zp={description:E(`Converts from another base to decimal.`),args:[U(`value (string)`,E(`The number to convert.`)),U(`base (number)`,E(`The base to convert the value from.`))],compute:function(e,t){let n=M(t,this.locale);if(n=Math.floor(n),2>n||n>36)return new A(E(`The base (%s) must be between 2 and 36 inclusive.`,n));let r=N(e);if(r===``)return 0;if(!pp.test(r))return new A(E(`The value (%s) must be a valid base %s representation.`,r,n));let i=parseInt(r,n);return isNaN(i)?new A(E(`The value (%s) must be a valid base %s representation.`,r,n)):i},isExported:!0},Bp={description:E(`Converts an angle value in radians to degrees.`),args:[U(`angle (number)`,E(`The angle to convert from radians to degrees.`))],compute:function(e){return M(e,this.locale)*180/Math.PI},isExported:!0},Vp={description:E(`Euler's number, e (~2.718) raised to a power.`),args:[U(`value (number)`,E(`The exponent to raise e.`))],compute:function(e){return Math.exp(M(e,this.locale))},isExported:!0},Hp={description:E(`Rounds number down to nearest multiple of factor.`),args:[U(`value (number)`,E(`The value to round down to the nearest integer multiple of factor.`)),U(`factor (number, default=1)`,E(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=M(e,this.locale),r=M(t,this.locale);return r<0&&n>0?new A(E(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.floor(n/r)*r:0,format:e?.format}},isExported:!0};function Up(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.floor(e/t)*t:n===0?-Math.ceil(Math.abs(e)/t)*t:-Math.floor(Math.abs(e)/t)*t)}let Wp={description:E(`Rounds number down to nearest multiple of factor.`),args:[U(`number (number)`,E(`The value to round down to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),U(`mode (number, default=0)`,E(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.`))],compute:function(e,t={value:1},n={value:0}){let r=M(t,this.locale);return{value:Up(M(e,this.locale),r,M(n,this.locale)),format:e?.format}},isExported:!0},Gp={description:E(`Rounds number down to nearest multiple of factor.`),args:[U(`number (number)`,E(`The value to round down to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=M(t,this.locale);return{value:Up(M(e,this.locale),n),format:e?.format}},isExported:!0},Kp={description:E(`Whether the provided value is even.`),args:[U(`value (number)`,E(`The value to be verified as even.`))],compute:function(e){let t=ea(e,this.locale);return!(Math.floor(Math.abs(t))&1)},isExported:!0},qp={description:E(`Rounds number up to nearest multiple of factor.`),args:[U(`number (number)`,E(`The value to round up to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){return{value:Tp(M(e,this.locale),M(t,this.locale)),format:e?.format}},isExported:!0},Jp={description:E(`Whether the provided value is even.`),args:[U(`value (number)`,E(`The value to be verified as even.`))],compute:function(e){let t=ea(e,this.locale);return!!(Math.floor(Math.abs(t))&1)},isExported:!0},Yp={description:E(`The logarithm of a number, base e (euler's number).`),args:[U(`value (number)`,E(`The value for which to calculate the logarithm, base e.`))],compute:function(e){let t=M(e,this.locale);return t<=0?new A(E(`The value (%s) must be strictly positive.`,t)):Math.log(t)},isExported:!0},Xp={description:E(`The logarithm of a number, for a given base.`),args:[U(`value (number)`,E(`The value for which to calculate the logarithm.`)),U(`base (number, default=10)`,E(`The base of the logarithm.`))],compute:function(e,t={value:10}){let n=M(e,this.locale),r=M(t,this.locale);return n<=0?new A(E(`The value (%s) must be strictly positive.`,n)):r<=0?new A(E(`The base (%s) must be strictly positive.`,r)):r===1?new A(E(`The base must be different from 1.`)):Math.log10(n)/Math.log10(r)},isExported:!0};function Zp(e,t){gu(t,E(`The divisor must be different from 0.`));let n=e%t;return n>0&&t<0||n<0&&t>0?n+t:n}let Qp={description:E(`Modulo (remainder) operator.`),args:[U(`dividend (number)`,E(`The number to be divided to find the remainder.`)),U(`divisor (number)`,E(`The number to divide by.`))],compute:function(e,t){let n=M(t,this.locale);return{value:Zp(M(e,this.locale),n),format:e?.format}},isExported:!0},$p={description:E(`Returns a n x n unit matrix, where n is the input dimension.`),args:[U(`dimension (number)`,E(`An integer specifying the dimension size of the unit matrix. It must be positive.`))],compute:function(e){let t=ta(e,this.locale);return t<1?new A(E(`The argument dimension must be positive`)):xu(t)},isExported:!0},em={description:E(`Rounds a number up to the nearest odd integer.`),args:[U(`value (number)`,E(`The value to round to the next greatest odd number.`))],compute:function(e){let t=M(e,this.locale),n=Math.ceil(Math.abs(t));return n=n&1?n:n+1,{value:t<0?-n:n,format:e?.format}},isExported:!0},tm={description:E(`The number pi.`),args:[],compute:function(){return Math.PI},isExported:!0},nm={description:E(`A number raised to a power.`),args:[U(`base (number)`,E(`The number to raise to the exponent power.`)),U(`exponent (number)`,E(`The exponent to raise base to.`))],compute:function(e,t){let n=M(e,this.locale),r=M(t,this.locale);return n<0&&!Number.isInteger(r)?new A(E(`The exponent (%s) must be an integer when the base is negative.`,r)):{value:n**+r,format:e?.format}},isExported:!0},rm={description:E(`Result of multiplying a series of numbers together.`),args:[U(`factor1 (number, range<number>)`,E(`The first number or range to calculate for the product.`)),U(`factor2 (number, range<number>, repeating)`,E(`More numbers or ranges to calculate for the product.`))],compute:function(...e){let t=0,n=1;for(let r of e)if(Or(r))for(let e of r)for(let r of e){let e=r.value;if(typeof e==`number`&&(n*=e,t+=1),j(e))return r}else r!==void 0&&r.value!==null&&(n*=ea(r,this.locale),t+=1);return{value:t===0?0:n,format:qi(e[0])}},isExported:!0},im={description:E(`A random number between 0 inclusive and 1 exclusive.`),args:[],compute:function(){return Math.random()},isExported:!0},am={description:E(`Returns a grid of random numbers between 0 inclusive and 1 exclusive.`),args:[U(`rows (number, default=1)`,E(`The number of rows to be returned.`)),U(`columns (number, default=1)`,E(`The number of columns to be returned.`)),U(`min (number, default=0)`,E(`The minimum number you would like returned.`)),U(`max (number, default=1)`,E(`The maximum number you would like returned.`)),U(`whole_number (number, default=FALSE)`,E(`Return a whole number or a decimal value.`))],compute:function(e={value:1},t={value:1},n={value:0},r={value:1},i={value:!1}){let a=ta(t,this.locale),o=ta(e,this.locale),s=M(n,this.locale),c=M(r,this.locale),l=P(i);if(a<1)return new A(E(`The number of columns (%s) must be positive.`,a));if(o<1)return new A(E(`The number of rows (%s) must be positive.`,o));if(s>c)return new A(E(`The maximum (%s) must be greater than or equal to the minimum (%s).`,c,s));if(l&&(!Number.isInteger(s)||!Number.isInteger(c)))return new A(E(`The maximum (%s) and minimum (%s) must be integers when whole_number is TRUE.`,c.toString(),s.toString()));let u=Array(a);for(let e=0;e<a;e++){u[e]=Array(o);for(let t=0;t<o;t++)l?u[e][t]=Math.floor(Math.random()*(c-s+1)+s):u[e][t]=s+Math.random()*(c-s)}return u},isExported:!0},om={description:E(`Random integer between two values, inclusive.`),args:[U(`low (number)`,E(`The low end of the random range.`)),U(`high (number)`,E(`The high end of the random range.`))],compute:function(e,t){let n=M(e,this.locale);Number.isInteger(n)||(n=Math.ceil(n));let r=M(t,this.locale);return Number.isInteger(r)||(r=Math.floor(r)),n>r?new A(E(`The high (%s) must be greater than or equal to the low (%s).`,r,n)):{value:n+Math.ceil((r-n+1)*Math.random())-1,format:e?.format}},isExported:!0},sm={description:E(`Rounds a number according to standard rules.`),args:[U(`value (number)`,E(`The value to round to places number of places.`)),U(`places (number, default=0)`,E(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=M(e,this.locale),r=M(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.round(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.round(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},cm={description:E(`Rounds down a number.`),args:[U(`value (number)`,E(`The value to round to places number of places, always rounding down.`)),U(`places (number, default=0)`,E(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=M(e,this.locale),r=M(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.floor(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.floor(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},lm={description:E(`Rounds up a number.`),args:[U(`value (number)`,E(`The value to round to places number of places, always rounding up.`)),U(`places (number, default=0)`,E(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=M(e,this.locale),r=M(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.ceil(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.ceil(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},um={description:E(`Secant of an angle provided in radians.`),args:[U(`angle (number)`,E(`The angle to find the secant of, in radians.`))],compute:function(e){return 1/Math.cos(M(e,this.locale))},isExported:!0},dm={description:E(`Hyperbolic secant of any real number.`),args:[U(`value (number)`,E(`Any real value to calculate the hyperbolic secant of.`))],compute:function(e){return 1/Math.cosh(M(e,this.locale))},isExported:!0},fm={description:E(`Returns a sequence of numbers.`),args:[U(`rows (number)`,E(`The number of rows to return`)),U(`columns (number, optional, default=1)`,E(`The number of columns to return`)),U(`start (number, optional, default=1)`,E(`The first number in the sequence`)),U(`step (number, optional, default=1)`,E(`The amount to increment each value in the sequence`))],compute:function(e,t={value:1},n={value:1},r={value:1}){let i=M(n,this.locale),a=M(r,this.locale),o=ta(e,this.locale),s=ta(t,this.locale);return s<1?new A(E(`The number of columns (%s) must be positive.`,s)):o<1?new A(E(`The number of rows (%s) must be positive.`,o)):ma(s,o,(e,t)=>({value:i+t*s*a+e*a}))},isExported:!0},pm={description:E(`Sine of an angle provided in radians.`),args:[U(`angle (number)`,E(`The angle to find the sine of, in radians.`))],compute:function(e){return Math.sin(M(e,this.locale))},isExported:!0},mm={description:E(`Hyperbolic sine of any real number.`),args:[U(`value (number)`,E(`Any real value to calculate the hyperbolic sine of.`))],compute:function(e){return Math.sinh(M(e,this.locale))},isExported:!0},hm={description:E(`Positive square root of a positive number.`),args:[U(`value (number)`,E(`The number for which to calculate the positive square root.`))],compute:function(e){let t=M(e,this.locale);return t<0?new A(E(`The value (%s) must be positive or null.`,t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},gm={description:E(`Sum of a series of numbers and/or cells.`),args:[U(`value1 (number, range<number>)`,E(`The first number or range to add together.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional numbers or ranges to add to value1.`))],compute:function(...e){let t=e[0];return{value:pu(e,this.locale),format:qi(t)}},isExported:!0},_m={description:E(`A conditional sum across a range.`),args:[U(`criteria_range (range)`,E(`The range which is tested against criterion.`)),U(`criterion (string)`,E(`The pattern or test to apply to range.`)),U(`sum_range (range, default=criteria_range)`,E(`The range to be summed, if different from range.`))],compute:function(e,t,n){n===void 0&&(n=e);let r=0;return wa([e,t],(e,t)=>{let i=n[e]?.[t]?.value;typeof i==`number`&&(r+=i)},this.locale),r},isExported:!0},vm={description:E(`Sums a range depending on multiple criteria.`),args:[U(`sum_range (range)`,E(`The range to sum.`)),U(`criteria_range1 (range)`,E(`The range to check against criterion1.`)),U(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1.`)),U(`criteria_range2 (any, range, repeating)`,E(`Additional ranges to check.`)),U(`criterion2 (string, repeating)`,E(`Additional criteria to check.`))],compute:function(e,...t){let n=0;return wa(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n+=i)},this.locale),n},isExported:!0},ym={description:E(`Tangent of an angle provided in radians.`),args:[U(`angle (number)`,E(`The angle to find the tangent of, in radians.`))],compute:function(e){return Math.tan(M(e,this.locale))},isExported:!0},bm={description:E(`Hyperbolic tangent of any real number.`),args:[U(`value (number)`,E(`Any real value to calculate the hyperbolic tangent of.`))],compute:function(e){return Math.tanh(M(e,this.locale))},isExported:!0};function xm(e,t){return t===0?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*10**t)/10**t)}let Sm={description:E(`Truncates a number.`),args:[U(`value (number)`,E(`The value to be truncated.`)),U(`places (number, default=0)`,E(`The number of significant digits to the right of the decimal point to retain.`))],compute:function(e,t={value:0}){return{value:xm(M(e,this.locale),M(t,this.locale)),format:e?.format}},isExported:!0},Cm={description:E(`Rounds a number down to the nearest integer that is less than or equal to it.`),args:[U(`value (number)`,E(`The number to round down to the nearest integer.`))],compute:function(e){return Math.floor(M(e,this.locale))},isExported:!0};var wm=l({AVEDEV:()=>km,AVERAGE:()=>Am,AVERAGEA:()=>Pm,AVERAGEIF:()=>Fm,AVERAGEIFS:()=>Im,AVERAGE_WEIGHTED:()=>Nm,CORREL:()=>ih,COUNT:()=>Lm,COUNTA:()=>Rm,COVAR:()=>zm,COVARIANCE_P:()=>Bm,COVARIANCE_S:()=>Vm,FORECAST:()=>Hm,GROWTH:()=>Um,INTERCEPT:()=>Wm,LARGE:()=>Gm,LINEST:()=>Km,LOGEST:()=>qm,MATTHEWS:()=>Jm,MAX:()=>Ym,MAXA:()=>Xm,MAXIFS:()=>Zm,MEDIAN:()=>Qm,MIN:()=>$m,MINA:()=>eh,MINIFS:()=>th,PEARSON:()=>rh,PERCENTILE:()=>ah,PERCENTILE_EXC:()=>oh,PERCENTILE_INC:()=>sh,POLYFIT_COEFFS:()=>ch,POLYFIT_FORECAST:()=>lh,QUARTILE:()=>uh,QUARTILE_EXC:()=>dh,QUARTILE_INC:()=>fh,RANK:()=>ph,RSQ:()=>mh,SLOPE:()=>hh,SMALL:()=>gh,SPEARMAN:()=>_h,STDEV:()=>vh,STDEVA:()=>xh,STDEVP:()=>Sh,STDEVPA:()=>Ch,STDEV_P:()=>yh,STDEV_S:()=>bh,STEYX:()=>wh,TREND:()=>Th,VAR:()=>Eh,VARA:()=>kh,VARP:()=>Ah,VARPA:()=>jh,VAR_P:()=>Dh,VAR_S:()=>Oh});function Tm(e,t){let n=[],r=[],i=0,a=0;ca([e],e=>{n.push(e),i+=1}),ca([t],e=>{r.push(e),a+=1}),hu(i===a,E(`[[FUNCTION_NAME]] has mismatched argument count %s vs %s.`,i,a));let o=[],s=[];for(let e=0;e<i;e++){let t=n[e]?.value,i=r[e]?.value;typeof t==`number`&&typeof i==`number`&&(s.push(t),o.push(i))}return{flatDataX:o,flatDataY:s}}function Em(e,t,n){let{flatDataX:r,flatDataY:i}=Tm(e,t),a=i.length;gu(a),n&&gu(a-1);let o=0,s=0;for(let e=0;e<a;e++)o+=i[e],s+=r[e];let c=o/a,l=s/a,u=0;for(let e=0;e<a;e++)u+=(i[e]-c)*(r[e]-l);return u/(a-+!!n)}function Dm(e,t,n,r){let i=0,a=n?pa:fa,o=a(e,(e,t)=>(i+=1,e+t),0,r);gu(i),t&&gu(i-1);let s=o/i;return a(e,(e,t)=>e+(t-s)**2,0,r)/(i-+!!t)}function Om(e,t,n,r){let i=M(t,r);hu(n?0<=i&&i<=1:0<i&&i<1,E(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`));let a=[],o,s=0;return ca(e,e=>{let t=e?.value;typeof t==`number`&&(o=Ta(a,e,`nextSmaller`,`asc`,a.length,(e,t)=>e[t]),a.splice(o+1,0,t),s++)}),hu(s!==0,Ma),n||hu(1/(s+1)<=i&&i<=s/(s+1),E(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`)),Li(a,i,n)}let km={description:E(`Average magnitude of deviations from mean.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){let t=0,n=fa(e,(e,n)=>(t+=1,e+n),0,this.locale);if(t===0)return new Gi(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`));let r=n/t;return fa(e,(e,t)=>e+Math.abs(r-t),0,this.locale)/t},isExported:!0},Am={description:E(`Numerical average value in a dataset, ignoring text.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the average value.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the average value.`))],compute:function(...e){return{value:ku(e,this.locale),format:qi(e[0])}},isExported:!0},jm=E(`[[FUNCTION_NAME]] has mismatched range sizes.`),Mm=E(`[[FUNCTION_NAME]] expects the weight to be positive or equal to 0.`),Nm={description:E(`Weighted average.`),args:[U(`values (number, range<number>)`,E(`Values to average.`)),U(`weights (number, range<number>)`,E(`Weights for each corresponding value.`)),U(`additional_values (number, range<number>, repeating)`,E(`Additional values to average.`)),U(`additional_weights (number, range<number>, repeating)`,E(`Additional weights.`))],compute:function(...e){let t=0,n=0;for(let r=0;r<e.length-1;r+=2){let i=e[r],a=e[r+1];if(!vu(i,a))return new A(jm);if(Or(i))for(let e=0;e<i.length;e++)for(let r=0;r<i[0].length;r++){let o=i[e][r].value,s=Or(a)?a?.[e][r].value:M(a,this.locale),c=typeof o==`number`,l=typeof s==`number`;if(c&&l){if(s<0)return new A(Mm);t+=o*s,n+=s;continue}if(c!==l)return new A(E(`[[FUNCTION_NAME]] expects number values.`))}else{let e=M(i,this.locale),r=Or(a)?a?.[0][0].value:M(a,this.locale);if(typeof r==`number`){if(r<0)return new A(Mm);t+=e*r,n+=r}}}return n===0?new Gi(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:t/n,format:qi(e[0])}}},Pm={description:E(`Numerical average value in a dataset.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the average value.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the average value.`))],compute:function(...e){let t=0,n=pa(e,(e,n)=>(t+=1,e+n),0,this.locale);return t===0?new Gi(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:n/t,format:qi(e[0])}},isExported:!0},Fm={description:E(`Average of values depending on criteria.`),args:[U(`criteria_range (number, range<number>)`,E(`The range to check against criterion.`)),U(`criterion (string)`,E(`The pattern or test to apply to criteria_range.`)),U(`average_range (number, range<number>, default=criteria_range)`,E(`The range to average. If not included, criteria_range is used for the average instead.`))],compute:function(e,t,n){let r=I(n===void 0?e:n),i=0,a=0;return wa([e,t],(e,t)=>{let n=r[e]?.[t]?.value;typeof n==`number`&&(i+=1,a+=n)},this.locale),i===0?new Gi(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):a/i},isExported:!0},Im={description:E(`Average of values depending on multiple criteria.`),args:[U(`average_range (range)`,E(`The range to average.`)),U(`criteria_range1 (range)`,E(`The range to check against criterion1.`)),U(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1.`)),U(`criteria_range2 (any, range, repeating)`,E(`Additional criteria_range and criterion to check.`)),U(`criterion2 (string, repeating)`,E(`The pattern or test to apply to criteria_range2.`))],compute:function(e,...t){let n=I(e),r=0,i=0;return wa(t,(e,t)=>{let a=n[e]?.[t]?.value;typeof a==`number`&&(r+=1,i+=a)},this.locale),r===0?new Gi(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):i/r},isExported:!0},Lm={description:E(`The number of numeric values in dataset.`),args:[U(`value1 (number, any, range<number>)`,E(`The first value or range to consider when counting.`)),U(`value2 (number, any, range<number>, repeating)`,E(`Additional values or ranges to consider when counting.`))],compute:function(...e){return Au(e,this.locale)},isExported:!0},Rm={description:E(`The number of values in a dataset.`),args:[U(`value1 (any, range)`,E(`The first value or range to consider when counting.`)),U(`value2 (any, range, repeating)`,E(`Additional values or ranges to consider when counting.`))],compute:function(...e){return ju(e)},isExported:!0},zm={description:E(`The covariance of a dataset.`),args:[U(`data_y (any, range)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (any, range)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return Em(e,t,!1)},isExported:!0},Bm={description:E(`The covariance of a dataset.`),args:[U(`data_y (any, range)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (any, range)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return Em(e,t,!1)},isExported:!0},Vm={description:E(`The sample covariance of a dataset.`),args:[U(`data_y (any, range)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (any, range)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return Em(e,t,!0)},isExported:!0},Hm={description:E(`Calculates the expected y-value for a specified x based on a linear regression of a dataset.`),args:[U(`x (number, range<number>)`,E(`The value(s) on the x-axis to forecast.`)),U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t,n){let{flatDataX:r,flatDataY:i}=Tm(t,n);return r.length===0||i.length===0?new Hi(Ma):Vu([i],[r],ha(I(e),e=>M(e,this.locale)),!0)},isExported:!0},Um={description:E(`Fits points to exponential growth trend.`),args:[U(`known_data_y (range<number>)`,E(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.`)),U(`known_data_x (range<number>, default={1;2;3;...})`,E(`The values of the independent variable(s) corresponding with known_data_y.`)),U(`new_data_x (any, range, default=known_data_x)`,E(`The data points to return the y values for on the ideal curve fit.`)),U(`b (boolean, default=TRUE)`,E(`Given a general exponential form of y = b*m^x for a curve fit, calculates b if TRUE or forces b to be 1 and only calculates the m values if FALSE.`))],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new A(Na(`known_data_y`)):zu(Vu(Bu($i(e,`known_data_y`)),$i(t,`known_data_x`),$i(n,`new_data_y`),P(r)))}},Wm={description:E(`Compute the intercept of the linear regression.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=Tm(e,t);if(n.length===0||r.length===0)return new Hi(Ma);let[[],[i]]=Fu([n],[r]);return i},isExported:!0},Gm={description:E(`Nth largest element from a data set.`),args:[U(`data (any, range)`,E(`Array or range containing the dataset to consider.`)),U(`n (number)`,E(`The rank from largest to smallest of the element to return.`))],compute:function(e,t){let n=Math.trunc(M(t?.value,this.locale)),r=[],i,a=0;ca([e],e=>{typeof e?.value==`number`&&(i=Ta(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.shift(),a--))});let o=r.shift();return o===void 0?new A(Ma):a<n?new A(E(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},Km={description:E(`Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>, default={1;2;3;...})`,E(`The range representing the array or matrix of independent data.`)),U(`calculate_b (boolean, default=TRUE)`,E(`A flag specifying wheter to compute the slope or not`)),U(`verbose (boolean, default=FALSE)`,E(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`))],compute:function(e,t=[[]],n={value:!0},r={value:!1}){return e.length===0||e[0].length===0?new A(Na(`data_y`)):Fu($i(t,`data_x`),$i(e,`data_y`),P(n),P(r))},isExported:!0},qm={description:E(`Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>, optional, default={1;2;3;...})`,E(`The range representing the array or matrix of independent data.`)),U(`calculate_b (boolean, default=TRUE)`,E(`A flag specifying wheter to compute the slope or not`)),U(`verbose (boolean, default=FALSE)`,E(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`))],compute:function(e,t=[[]],n={value:!0},r={value:!1}){if(e.length===0||e[0].length===0)return new A(Na(`data_y`));let i=Fu($i(t,`data_x`),Bu($i(e,`data_y`)),P(n),P(r));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},Jm={description:E(`Compute the Matthews correlation coefficient of a dataset.`),args:[U(`data_x (range)`,E(`The range representing the array or matrix of observed data.`)),U(`data_y (range)`,E(`The range representing the array or matrix of predicted data.`))],compute:function(e,t){let n=e.flat(),r=t.flat();if(Ou(n,r),n.length===0||r.length===0)return new Hi(Ma);let i=n.length,a=0,o=0,s=0,c=0;for(let e=0;e<i;++e){let t=P(n[e]);t===P(r[e])?t?o++:a++:t?c++:s++}return(o*a-s*c)/Math.sqrt((o+s)*(o+c)*(a+s)*(a+c))},isExported:!1},Ym={description:E(`Maximum value in a numeric dataset.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the maximum value.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the maximum value.`))],compute:function(...e){return Mu(e,this.locale)},isExported:!0},Xm={description:E(`Maximum numeric value in a dataset.`),args:[U(`value1 (any, range)`,E(`The first value or range to consider when calculating the maximum value.`)),U(`value2 (any, range, repeating)`,E(`Additional values or ranges to consider when calculating the maximum value.`))],compute:function(...e){let t=pa(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:qi(e[0])}},isExported:!0},Zm={description:E(`Returns the maximum value in a range of cells, filtered by a set of criteria.`),args:[U(`range (range)`,E(`The range of cells from which the maximum will be determined.`)),U(`criteria_range1 (range)`,E(`The range of cells over which to evaluate criterion1.`)),U(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.`)),U(`criteria_range2 (any, range, repeating)`,E(`Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.`)),U(`criterion2 (string, repeating)`,E(`The pattern or test to apply to criteria_range2.`))],compute:function(e,...t){let n=-1/0;return wa(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n<i?i:n)},this.locale),n===-1/0?0:n},isExported:!0},Qm={description:E(`Median value in a numeric dataset.`),args:[U(`value1 (any, range)`,E(`The first value or range to consider when calculating the median value.`)),U(`value2 (any, range, repeating)`,E(`Additional values or ranges to consider when calculating the median value.`))],compute:function(...e){let t=[];return la(e,e=>{t.push(e)},this.locale),{value:Om(t,{value:.5},!0,this.locale),format:qi(t[0])}},isExported:!0},$m={description:E(`Minimum value in a numeric dataset.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the minimum value.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the minimum value.`))],compute:function(...e){return Nu(e,this.locale)},isExported:!0},eh={description:E(`Minimum numeric value in a dataset.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the minimum value.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the minimum value.`))],compute:function(...e){let t=pa(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:qi(e[0])}},isExported:!0},th={description:E(`Returns the minimum value in a range of cells, filtered by a set of criteria.`),args:[U(`range (range)`,E(`The range of cells from which the minimum will be determined.`)),U(`criteria_range1 (range)`,E(`The range of cells over which to evaluate criterion1.`)),U(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.`)),U(`criteria_range2 (any, range, repeating)`,E(`Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.`)),U(`criterion2 (string, repeating)`,E(`The pattern or test to apply to criteria_range2.`))],compute:function(e,...t){let n=1/0;return wa(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n>i?i:n)},this.locale),n===1/0?0:n},isExported:!0};function nh(e,t){let{flatDataX:n,flatDataY:r}=Tm(e,t);if(n.length===0||r.length===0)return new Hi(Ma);let i=n.length,a=0,o=0,s=0,c=0,l=0;for(let e=0;e<i;e++){let t=n[e],i=r[e];a+=t,o+=i,s+=t*i,c+=t*t,l+=i*i}return(i*s-a*o)/Math.sqrt((i*c-a*a)*(i*l-o*o))}let rh={description:E(`Compute the Pearson product-moment correlation coefficient of a dataset.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return nh(e,t)},isExported:!0},ih=rh,ah={description:E(`Value at a given percentile of a dataset.`),args:[U(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),U(`percentile (number)`,E(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return sh.compute.bind(this)(e,t)},isExported:!0},oh={description:E(`Value at a given percentile of a dataset exclusive of 0 and 1.`),args:[U(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),U(`percentile (number)`,E(`The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.`))],compute:function(e,t){return{value:Om([e],t,!1,this.locale),format:qi(e)}},isExported:!0},sh={description:E(`Value at a given percentile of a dataset.`),args:[U(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),U(`percentile (number)`,E(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return{value:Om([e],t,!0,this.locale),format:qi(e)}},isExported:!0},ch={description:E(`Compute the coefficients of polynomial regression of the dataset.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`)),U(`order (number)`,E(`The order of the polynomial to fit the data, between 1 and 6.`)),U(`intercept (boolean, default=TRUE)`,E(`A flag specifying whether to compute the intercept or not.`))],compute:function(e,t,n,r={value:!0}){let{flatDataX:i,flatDataY:a}=Tm(e,t);return i.length===0||a.length===0?new Hi(Ma):Iu(a,i,M(n,this.locale),P(r))},isExported:!1},lh={description:E(`Predict value by computing a polynomial regression of the dataset.`),args:[U(`x (number, range<number>)`,E(`The value(s) on the x-axis to forecast.`)),U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`)),U(`order (number)`,E(`The order of the polynomial to fit the data, between 1 and 6.`)),U(`intercept (boolean, default=TRUE)`,E(`A flag specifying whether to compute the intercept or not.`))],compute:function(e,t,n,r,i={value:!0}){let a=M(r,this.locale),{flatDataX:o,flatDataY:s}=Tm(t,n);if(o.length===0||s.length===0)return new Hi(Ma);let c=Iu(s,o,a,P(i)).flat();return ha(I(e),e=>Ru(c,M(e,this.locale),a))},isExported:!1},uh={description:E(`Value nearest to a specific quartile of a dataset.`),args:[U(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),U(`quartile_number (number)`,E(`Which quartile value to return.`))],compute:function(e,t){return fh.compute.bind(this)(e,t)},isExported:!0},dh={description:E(`Value nearest to a specific quartile of a dataset exclusive of 0 and 4.`),args:[U(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),U(`quartile_number (number)`,E(`Which quartile value, exclusive of 0 and 4, to return.`))],compute:function(e,t){let n={value:.25*Math.trunc(M(t,this.locale))};return{value:Om([e],n,!1,this.locale),format:qi(e)}},isExported:!0},fh={description:E(`Value nearest to a specific quartile of a dataset.`),args:[U(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),U(`quartile_number (number)`,E(`Which quartile value to return.`))],compute:function(e,t){let n={value:.25*Math.trunc(M(t,this.locale))};return{value:Om([e],n,!0,this.locale),format:qi(e)}},isExported:!0},ph={description:E(`Returns the rank of a specified value in a dataset.`),args:[U(`value (number)`,E(`The value whose rank will be determined.`)),U(`data (range)`,E(`The range containing the dataset to consider.`)),U(`is_ascending (boolean, default=FALSE)`,E(`Whether to consider the values in data in descending or ascending order.`))],compute:function(e,t,n={value:!1}){let r=P(n),i=M(e,this.locale),a=1,o=!1;for(let e of t)for(let t of e){if(typeof t.value!=`number`)continue;let e=M(t,this.locale);e===i?o=!0:e>i!==r&&a++}return o?a:new Hi(E(`Value not found in the given data.`))},isExported:!0},mh={description:E(`Compute the square of r, the Pearson product-moment correlation coefficient of a dataset.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let n=nh(e,t);if(n instanceof Error)throw n;return n**2},isExported:!0},hh={description:E(`Compute the slope of the linear regression.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=Tm(e,t);if(n.length===0||r.length===0)return new Hi(Ma);let[[i]]=Fu([n],[r]);return i},isExported:!0},gh={description:E(`Nth smallest element in a data set.`),args:[U(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),U(`n (number)`,E(`The rank from smallest to largest of the element to return.`))],compute:function(e,t){let n=Math.trunc(M(t?.value,this.locale)),r=[],i,a=0;ca([e],e=>{typeof e?.value==`number`&&(i=Ta(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.pop(),a--))});let o=r.pop();return o===void 0?new A(Ma):a<n?new A(E(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},_h={description:E(`Compute the Spearman rank correlation coefficient of a dataset.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=Tm(t,e);if(n.length===0||r.length===0)return new Hi(Ma);let i=n.length,a=n.map((e,t)=>[e,r[t]]);a.sort((e,t)=>e[0]-t[0]);for(let e=0;e<i;++e)a[e][0]=e;a.sort((e,t)=>e[1]-t[1]);let o=0;for(let e=0;e<i;++e)o+=(a[e][0]-e)**2;return 1-6*o/(i**3-i)},isExported:!1},vh={description:E(`Standard deviation.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Math.sqrt(Eh.compute.bind(this)(...e))},isExported:!0},yh={description:E(`Standard deviation of entire population.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Math.sqrt(Dh.compute.bind(this)(...e))},isExported:!0},bh={description:E(`Standard deviation.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Math.sqrt(Oh.compute.bind(this)(...e))},isExported:!0},xh={description:E(`Standard deviation of sample (text as 0).`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Math.sqrt(kh.compute.bind(this)(...e))},isExported:!0},Sh={description:E(`Standard deviation of entire population.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Math.sqrt(Ah.compute.bind(this)(...e))},isExported:!0},Ch={description:E(`Standard deviation of entire population (text as 0).`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Math.sqrt(jh.compute.bind(this)(...e))},isExported:!0},wh={description:E(`Calculates the standard error of the predicted y-value for each x in the regression of a dataset.`),args:[U(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=Tm(e,t);return n.length===0||r.length===0?new Hi(Ma):Fu([n],[r],!0,!0)[1][2]},isExported:!0},Th={description:E(`Fits points to linear trend derived via least-squares.`),args:[U(`known_data_y (number, range<number>)`,E(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.`)),U(`known_data_x (number, range<number>, optional, default={1;2;3;...})`,E(`The values of the independent variable(s) corresponding with known_data_y.`)),U(`new_data_x (number, range<number>, optional, default=known_data_x)`,E(`The data points to return the y values for on the ideal curve fit.`)),U(`b (boolean, optional, default=TRUE)`,E(`Given a general linear form of y = m*x+b for a curve fit, calculates b if TRUE or forces b to be 0 and only calculates the m values if FALSE, i.e. forces the curve fit to pass through the origin.`))],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new A(Na(`known_data_y`)):Vu($i(e,`known_data_y`),$i(t,`known_data_x`),$i(n,`new_data_y`),P(r))}},Eh={description:E(`Variance.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Dm(e,!0,!1,this.locale)},isExported:!0},Dh={description:E(`Variance of entire population.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Dm(e,!1,!1,this.locale)},isExported:!0},Oh={description:E(`Variance.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Dm(e,!0,!1,this.locale)},isExported:!0},kh={description:E(`Variance of sample (text as 0).`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Dm(e,!0,!0,this.locale)},isExported:!0},Ah={description:E(`Variance of entire population.`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Dm(e,!1,!1,this.locale)},isExported:!0},jh={description:E(`Variance of entire population (text as 0).`),args:[U(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),U(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Dm(e,!1,!0,this.locale)},isExported:!0};var Mh=l({DAVERAGE:()=>Fh,DCOUNT:()=>Ih,DCOUNTA:()=>Lh,DGET:()=>Rh,DMAX:()=>zh,DMIN:()=>Bh,DPRODUCT:()=>Vh,DSTDEV:()=>Hh,DSTDEVP:()=>Uh,DSUM:()=>Wh,DVAR:()=>Gh,DVARP:()=>Kh});function Nh(e,t,n,r){let i=new Map,a=e.length;for(let t=a-1;t>=0;t--)i.set(N(e[t][0]).toUpperCase(),t);let o=t?.value;if(typeof o!=`number`&&typeof o!=`string`)throw new A(E(`The field must be a number or a string`));let s;if(typeof o==`number`){if(s=Math.trunc(o)-1,s<0||a-1<s)throw new A(E(`The field (%(fieldValue)s) must be one of %(dimRowDB)s or must be a number between 1 and %s inclusive.`,{fieldValue:o.toString(),dimRowDB:a.toString()}))}else{let e=N(t).toUpperCase();if(s=i.get(e)??-1,s===-1)throw new A(E(`The field (%s) must be one of %s.`,N(t),[...i.keys()].toString()))}let c=n[0].length;if(c<2)throw new A(E(`The criteria range contains %s row, it must be at least 2 rows.`,c.toString()));let l=new Set,u=e[0].length;for(let t=1;t<c;t++){let a=[],o=!0;for(let r=0;r<n.length;r++){let s=N(n[r][0]).toUpperCase(),c=i.get(s),l=n[r][t];if(l.value!==null)if(c!==void 0)a.push([e[c].slice(1,u)]),a.push(l);else{o=!1;break}}if(o)if(a.length>0)wa(a,(e,t)=>{l.add(t)},r,!0);else{l=new Set(Array(u-1).keys());break}}let d=e[s];return[...l].map(e=>d[e+1])}let Ph=[U(`database (range)`,E(`The array or range containing the data to consider, structured in such a way that the first row contains the labels for each column's values.`)),U(`field (number, string)`,E(`Indicates which column in database contains the values to be extracted and operated on.`)),U(`criteria (range)`,E(`An array or range containing zero or more criteria to filter the database values by before operating.`))],Fh={description:E(`Average of a set of values from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return Am.compute.bind(this)([r])},isExported:!0},Ih={description:E(`Counts values from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return Lm.compute.bind(this)([r])},isExported:!0},Lh={description:E(`Counts values and text from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return Rm.compute.bind(this)([r])},isExported:!0},Rh={description:E(`Single value from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return r.length===1?r[0]:new A(E(`More than one match found in DGET evaluation.`))},isExported:!0},zh={description:E(`Maximum of values from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return Ym.compute.bind(this)([r])},isExported:!0},Bh={description:E(`Minimum of values from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return $m.compute.bind(this)([r])},isExported:!0},Vh={description:E(`Product of values from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return rm.compute.bind(this)([r])},isExported:!0},Hh={description:E(`Standard deviation of population sample from table.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return vh.compute.bind(this)([r])},isExported:!0},Uh={description:E(`Standard deviation of entire population from table.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return Sh.compute.bind(this)([r])},isExported:!0},Wh={description:E(`Sum of values from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return gm.compute.bind(this)([r])},isExported:!0},Gh={description:E(`Variance of population sample from table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return Eh.compute.bind(this)([r])},isExported:!0},Kh={description:E(`Variance of a population from a table-like range.`),args:Ph,compute:function(e,t,n){let r=Nh(e,t,n,this.locale);return Ah.compute.bind(this)([r])},isExported:!0};var qh=l({DATE:()=>Yh,DATEDIF:()=>Xh,DATEVALUE:()=>Zh,DAY:()=>Qh,DAYS:()=>$h,DAYS360:()=>eg,EDATE:()=>tg,EOMONTH:()=>ng,HOUR:()=>rg,ISOWEEKNUM:()=>ig,MINUTE:()=>ag,MONTH:()=>og,MONTH_END:()=>Sg,MONTH_START:()=>xg,NETWORKDAYS:()=>sg,NETWORKDAYS_INTL:()=>lg,NOW:()=>ug,QUARTER:()=>Cg,QUARTER_END:()=>Tg,QUARTER_START:()=>wg,SECOND:()=>dg,TIME:()=>fg,TIMEVALUE:()=>pg,TODAY:()=>mg,WEEKDAY:()=>hg,WEEKNUM:()=>gg,WORKDAY:()=>_g,WORKDAY_INTL:()=>vg,YEAR:()=>yg,YEARFRAC:()=>bg,YEAR_END:()=>Dg,YEAR_START:()=>Eg}),Jh=function(e){return e.WHOLE_YEARS=`Y`,e.WHOLE_MONTHS=`M`,e.WHOLE_DAYS=`D`,e.DAYS_WITHOUT_WHOLE_MONTHS=`MD`,e.MONTH_WITHOUT_WHOLE_YEARS=`YM`,e.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR=`YD`,e}(Jh||{});let Yh={description:E(`Converts year/month/day into a date.`),args:[U(`year (number)`,E(`The year component of the date.`)),U(`month (number)`,E(`The month component of the date.`)),U(`day (number)`,E(`The day component of the date.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=Math.trunc(M(n,this.locale));if(r<0||r>9999)return new A(E(`The year (%s) must be between 0 and 9999 inclusive.`,r.toString()));r<1900&&(r+=1900);let o=hi(new O(r,i-1,a));return o<0?new A(E(`The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.`)):{value:o,format:this.locale.dateFormat}},isExported:!0},Xh={description:E(`Calculates the number of days, months, or years between two dates.`),args:[U(`start_date (date)`,E(`The start date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),U(`end_date (date)`,E(`The end date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),U(`unit (string)`,E(`A text abbreviation for unit of time. Accepted values are "Y" (the number of whole years between start_date and end_date), "M" (the number of whole months between start_date and end_date), "D" (the number of days between start_date and end_date), "MD" (the number of days between start_date and end_date after subtracting whole months), "YM" (the number of whole months between start_date and end_date after subtracting whole years), "YD" (the number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart).`))],compute:function(e,t,n){let r=N(n).toUpperCase();if(!Object.values(Jh).includes(r))return new A(Zi(Object.values(Jh),N(n)));let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=mi(i),s=mi(a);if(a<i)return new A(E(`start_date (%s) should be on or before end_date (%s).`,o.toLocaleDateString(),s.toLocaleDateString()));switch(r){case`Y`:return wi(o,s);case`M`:return Si(o,s);case`D`:return Ci(o,s);case`YM`:return Si(o,s)-wi(o,s)*12;case`MD`:let e=s.getDate()-o.getDate();return e<0&&(e=_i(new O(s.getFullYear(),s.getMonth()-1,1))-Math.abs(e)),e;case`YD`:{if(Ti(i,a))return Ci(o,s);let e=new O(o.getFullYear(),s.getMonth(),s.getDate()),t=Ci(o,e);return t<0&&(e.setFullYear(o.getFullYear()+1),t=Ci(o,e)),t}}},isExported:!0},Zh={description:E(`Converts a date string to a date value.`),args:[U(`date_string (string)`,E(`The string representing the date.`))],compute:function(e){let t=N(e),n=ii(t,this.locale);return n===null?new A(E(`The date_string (%s) cannot be parsed to date/time.`,t.toString())):Math.trunc(n.value)},isExported:!0},Qh={description:E(`Day of the month that a specific date falls on.`),args:[U(`date (string)`,E(`The date from which to extract the day.`))],compute:function(e){return F(e,this.locale).getDate()},isExported:!0},$h={description:E(`Number of days between two dates.`),args:[U(`end_date (date)`,E(`The end of the date range.`)),U(`start_date (date)`,E(`The start of the date range.`))],compute:function(e,t){let n=F(e,this.locale),r=F(t,this.locale),i=n.getTime()-r.getTime();return Math.round(i/Wr)},isExported:!0},eg={description:E(`Number of days between two dates on a 360-day year (months of 30 days).`),args:[U(`start_date (date)`,E(`The start date to consider in the calculation.`)),U(`end_date (date)`,E(`The end date to consider in the calculation.`)),U(`method (number, default=0)`,E(`An indicator of what day count method to use. (0) US NASD method (1) European method`))],compute:function(e,t,n={value:0}){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=xi(r,i,P(n)?4:0);return Math.sign(i-r)*Math.round(a*360)},isExported:!0},tg={description:E(`Date a number of months before/after another date.`),args:[U(`start_date (date)`,E(`The date from which to calculate the result.`)),U(`months (number)`,E(`The number of months before (negative) or after (positive) 'start_date' to calculate.`))],compute:function(e,t){return{value:hi(yi(F(e,this.locale),Math.trunc(M(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},ng={description:E(`Last day of a month before or after a date.`),args:[U(`start_date (date)`,E(`The date from which to calculate the result.`)),U(`months (number)`,E(`The number of months before (negative) or after (positive) 'start_date' to consider.`))],compute:function(e,t){let n=F(e,this.locale),r=Math.trunc(M(t,this.locale));return{value:hi(new O(n.getFullYear(),n.getMonth()+r+1,0)),format:this.locale.dateFormat}},isExported:!0},rg={description:E(`Hour component of a specific time.`),args:[U(`time (date)`,E(`The time from which to calculate the hour component.`))],compute:function(e){return F(e,this.locale).getHours()},isExported:!0},ig={description:E(`ISO week number of the year.`),args:[U(`date (date)`,E(`The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`))],compute:function(e){let t=F(e,this.locale),n=t.getFullYear(),r=1;for(;new O(n,0,r).getDay()!==4;)r+=1;let i=new O(n,0,r-3),a=31;for(;new O(n,11,a).getDay()!==4;)--a;let o=new O(n,11,a+3),s;s=i.getTime()<=t.getTime()?t.getTime()<=o.getTime()?0:1:-1;let c;switch(s){case 0:c=i;break;case 1:c=new O(n,11,a+3+1);break;case-1:let e=1;for(;new O(n-1,0,e).getDay()!==4;)e+=1;c=new O(n-1,0,e-3);break}let l=(t.getTime()-c.getTime())/Wr;return Math.floor(l/7)+1},isExported:!0},ag={description:E(`Minute component of a specific time.`),args:[U(`time (date)`,E(`The time from which to calculate the minute component.`))],compute:function(e){return F(e,this.locale).getMinutes()},isExported:!0},og={description:E(`Month of the year a specific date falls in`),args:[U(`date (date)`,E(`The date from which to extract the month.`))],compute:function(e){return F(e,this.locale).getMonth()+1},isExported:!0},sg={description:E(`Net working days between two provided days.`),args:[U(`start_date (date)`,E(`The start date of the period from which to calculate the number of net working days.`)),U(`end_date (date)`,E(`The end date of the period from which to calculate the number of net working days.`)),U(`holidays (date, range<date>, optional)`,E(`A range or array constant containing the date serial numbers to consider holidays.`))],compute:function(e,t,n){return lg.compute.bind(this)(e,t,{value:1},n)},isExported:!0};function cg(e){let t=e?.value;if(typeof t==`string`){hu(t.length===7&&[...t].every(e=>e===`0`||e===`1`),E(`When weekend is a string (%s) it must be composed of "0" or "1".`,t));let e=[];for(let n=0;n<7;n++)t[n]===`1`&&e.push((n+1)%7);return e}if(typeof t==`number`)return hu(1<=t&&t<=7||11<=t&&t<=17,E(`The weekend (%s) must be a string or a number in the range 1-7 or 11-17.`,t.toString())),t<=7?[t-2==-1?6:t-2,t-1]:[t-11];throw new A(E(`The weekend must be a number or a string.`))}let lg={description:E(`Net working days between two dates (specifying weekends).`),args:[U(`start_date (date)`,E(`The start date of the period from which to calculate the number of net working days.`)),U(`end_date (date)`,E(`The end date of the period from which to calculate the number of net working days.`)),U(`weekend (any, default=1)`,E(`A number or string representing which days of the week are considered weekends.`)),U(`holidays (date, range<date>, optional)`,E(`A range or array constant containing the dates to consider as holidays.`))],compute:function(e,t,n={value:1},r){let i=F(e,this.locale),a=F(t,this.locale),o=cg(n),s=new Set;r!==void 0&&ca([r],e=>{let t=F(e,this.locale);s.add(t.getTime())});let c=i.getTime()>a.getTime(),l=O.fromTimestamp((c?i:a).getTime()),u=O.fromTimestamp((c?a:i).getTime()),d=l.getTime(),f=u.getTime(),p=0;for(;f<=d;)!o.includes(u.getDay())&&!s.has(f)&&(p+=1),u.setDate(u.getDate()+1),f=u.getTime();return c?-p:p},isExported:!0},ug={description:E(`Current date and time as a date value.`),args:[],compute:function(){let e=O.now(),t=e.getTime()-Ur.getTime(),n=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/Wr)+n,format:uu(this.locale)}},isExported:!0},dg={description:E(`Minute component of a specific time.`),args:[U(`time (date)`,E(`The time from which to calculate the second component.`))],compute:function(e){return F(e,this.locale).getSeconds()},isExported:!0},fg={description:E(`Converts hour/minute/second into a time.`),args:[U(`hour (number)`,E(`The hour component of the time.`)),U(`minute (number)`,E(`The minute component of the time.`)),U(`second (number)`,E(`The second component of the time.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=Math.trunc(M(n,this.locale));return i+=Math.floor(a/60),a=a%60+(a<0?60:0),r+=Math.floor(i/60),i=i%60+(i<0?60:0),r%=24,r<0?new A(E(`The function [[FUNCTION_NAME]] result cannot be negative`)):{value:r/24+i/1440+a/(1440*60),format:this.locale.timeFormat}},isExported:!0},pg={description:E(`Converts a time string into its serial number representation.`),args:[U(`time_string (string)`,E(`The string that holds the time representation.`))],compute:function(e){let t=N(e),n=ii(t,this.locale);if(n===null)return new A(E(`The time_string (%s) cannot be parsed to date/time.`,t));let r=n.value-Math.trunc(n.value);return r<0?1+r:r},isExported:!0},mg={description:E(`Current date as a date value.`),args:[],compute:function(){let e=O.now();return{value:hi(new O(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},hg={description:E(`Day of the week of the date provided (as number).`),args:[U(`date (date)`,E(`The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),U(`type (number, default=1)`,E(`A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.`))],compute:function(e,t={value:1}){let n=F(e,this.locale),r=Math.round(M(t,this.locale)),i=n.getDay();return[1,2,3].includes(r)?r===1?i+1:r===2?i===0?7:i:i===0?6:i-1:new A(E(`The type (%s) must be 1, 2 or 3.`,r))},isExported:!0},gg={description:E(`Week number of the year.`),args:[U(`date (date)`,E(`The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),U(`type (number, default=1)`,E(`A number representing the day that a week starts on. Sunday = 1.`))],compute:function(e,t={value:1}){let n=F(e,this.locale),r=Math.round(M(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(r))return new A(E(`The type (%s) is out of range.`,r.toString()));if(r===21)return ig.compute.bind(this)(e);let i;i=r===1||r===2?r-1:r-10==7?0:r-10;let a=n.getFullYear(),o=1,s=new O(a,0,o);for(;s.getDay()!==i;)o+=1,s=new O(a,0,o);let c=(n.getTime()-s.getTime())/Wr;return c<0?1:Math.floor(c/7)+(o===1?1:2)},isExported:!0},_g={description:E(`Date after a number of workdays.`),args:[U(`start_date (date)`,E(`The date from which to begin counting.`)),U(`num_days (number)`,E(`The number of working days to advance from start_date. If negative, counts backwards.`)),U(`holidays (date, range<date>, optional)`,E(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:null}){return vg.compute.bind(this)(e,t,{value:1},n)},isExported:!0},vg={description:E(`Date after a number of workdays (specifying weekends).`),args:[U(`start_date (date)`,E(`The date from which to begin counting.`)),U(`num_days (number)`,E(`The number of working days to advance from start_date. If negative, counts backwards.`)),U(`weekend (any, default=1)`,E(`A number or string representing which days of the week are considered weekends.`)),U(`holidays (date, range<date>, optional)`,E(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:1},r){let i=F(e,this.locale),a=Math.trunc(M(t,this.locale));if(n.value===`1111111`)return new A(E(`The weekend must be different from '1111111'.`));let o=cg(n),s=new Set;r!==void 0&&ca([r],e=>{let t=F(e,this.locale);s.add(t.getTime())});let c=O.fromTimestamp(i.getTime()),l=c.getTime(),u=Math.sign(a),d=Math.abs(a);for(;d>0;)c.setDate(c.getDate()+u),l=c.getTime(),!o.includes(c.getDay())&&!s.has(l)&&--d;let f=l-Ur.getTime();return{value:Math.round(f/Wr),format:this.locale.dateFormat}},isExported:!0},yg={description:E(`Year specified by a given date.`),args:[U(`date (date)`,E(`The date from which to extract the year.`))],compute:function(e){return F(e,this.locale).getFullYear()},isExported:!0},bg={description:E(`Exact number of years between two dates.`),args:[U(`start_date (date)`,E(`The start date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),U(`end_date (date)`,E(`The end date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),U(`day_count_convention (number, default=0)`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n={value:0}){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=Math.trunc(M(n,this.locale));return r<0?new A(E(`The start_date (%s) must be positive or null.`,r)):i<0?new A(E(`The end_date (%s) must be positive or null.`,i)):0>a||a>4?new A(E(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,a)):xi(r,i,a)}},xg={description:E(`First day of the month preceding a date.`),args:[U(`date (date)`,E(`The date from which to calculate the result.`))],compute:function(e){let t=F(e,this.locale);return{value:hi(new O(t.getFullYear(),t.getMonth(),1)),format:this.locale.dateFormat}}},Sg={description:E(`Last day of the month following a date.`),args:[U(`date (date)`,E(`The date from which to calculate the result.`))],compute:function(e){return ng.compute.bind(this)(e,{value:0})}},Cg={description:E(`Quarter of the year a specific date falls in`),args:[U(`date (date)`,E(`The date from which to extract the quarter.`))],compute:function(e){return Math.ceil((F(e,this.locale).getMonth()+1)/3)}},wg={description:E(`First day of the quarter of the year a specific date falls in.`),args:[U(`date (date)`,E(`The date from which to calculate the start of quarter.`))],compute:function(e){let t=Cg.compute.bind(this)(e);return{value:hi(new O(yg.compute.bind(this)(e),(t-1)*3,1)),format:this.locale.dateFormat}}},Tg={description:E(`Last day of the quarter of the year a specific date falls in.`),args:[U(`date (date)`,E(`The date from which to calculate the end of quarter.`))],compute:function(e){let t=Cg.compute.bind(this)(e);return{value:hi(new O(yg.compute.bind(this)(e),t*3,0)),format:this.locale.dateFormat}}},Eg={description:E(`First day of the year a specific date falls in.`),args:[U(`date (date)`,E(`The date from which to calculate the start of the year.`))],compute:function(e){return{value:hi(new O(yg.compute.bind(this)(e),0,1)),format:this.locale.dateFormat}}},Dg={description:E(`Last day of the year a specific date falls in.`),args:[U(`date (date)`,E(`The date from which to calculate the end of the year.`))],compute:function(e){return{value:hi(new O(yg.compute.bind(this)(e)+1,0,0)),format:this.locale.dateFormat}}};var Og=l({DELTA:()=>kg});let kg={description:E(`Compare two numeric values, returning 1 if they're equal.`),args:[U(`number1 (number)`,E(`The first number to compare.`)),U(`number2 (number, default=0)`,E(`The second number to compare.`))],compute:function(e,t={value:0}){return+(M(e,this.locale)===M(t,this.locale))},isExported:!0},Ag=[`number`,`error`,`text`,`boolean`];function jg(e){let t=e===`asc`?1:-1;return(e,n)=>{if(e.type===`empty`)return n.type===`empty`?0:1;if(n.type===`empty`)return-1;let r=Ag.indexOf(e.type)-Ag.indexOf(n.type);return r===0&&(r=e.type===`text`||e.type===`error`?e.value.localeCompare(n.value):e.value-n.value),t*r}}function Mg(e,t,n){let r=e.map((e,t)=>({index:t,type:e.type,value:e.value}));return(n?r.map(e=>e.type===`empty`?{...e,type:`number`,value:0}:e):r).sort(jg(t))}function Ng(e,t,n,r,i){let a=r.right>r.left;if(e.model.getters.doesIntersectMerge(t,r)){a=!1;let n;for(let i=r.top;i<=r.bottom;i++){n=[];for(let a=r.left;a<=r.right;a++){let r=e.model.getters.getMerge({sheetId:t,col:a,row:i});r&&!n.includes(r.id.toString())&&n.push(r.id.toString())}if(n.length>=2){a=!0;break}}}if(a){Pg(e,t,n,r,i);return}let o=e.model.getters.getContiguousZone(t,r);Es(o,r)?Pg(e,t,n,r,i):e.askConfirmation(E(`We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?`),()=>Pg(e,t,n,o,i),()=>Pg(e,t,n,r,i))}function Pg(e,t,n,r,i,a){let o=e.model.dispatch(`SORT_CELLS`,{sheetId:t,col:n.col,row:n.row,zone:r,sortDirection:i,sortOptions:a});if(o.isCancelledBecause(`InvalidSortZone`)){let{col:t,row:i}=n;e.model.selection.selectZone({cell:{col:t,row:i},zone:r}),e.raiseError(E(`Cannot sort. To sort, select only cells or only merges that have the same size.`))}if(o.isCancelledBecause(`SortZoneWithArrayFormulas`)){let{col:t,row:i}=n;e.model.selection.selectZone({cell:{col:t,row:i},zone:r}),e.raiseError(E(`Cannot sort a zone with array formulas.`))}}var Fg=l({FILTER:()=>Lg,SORT:()=>Rg,SORTN:()=>zg,UNIQUE:()=>Bg});function Ig(e,t,...n){for(let e=0;e<n.length;e++){let t=e%2==0?`sort_column`:`is_ascending`;hu(n[e]!==void 0,E(`Value for parameter %s is missing in [[FUNCTION_NAME]].`,t))}let r=[],i=[],a=e.length;for(let o=0;o<n.length;o+=2){r.push(P(Tu(n[o+1])?.value)?`asc`:`desc`);let s=n[o];if(Or(s)&&(s.length>1||s[0].length>1))hu(s.length===1&&s[0].length===a,E(`Wrong size for %s. Expected a range of size 1x%s. Got %sx%s.`,`sort_column${o+1}`,a,s.length,s[0].length)),i.push(s.flat().map(e=>e.value));else{let n=M(Tu(s)?.value,t);if(n<1||n>e[0].length)return e;i.push(e.map(e=>e[n-1].value))}}if(i.length===0)for(let t=0;t<e[0].length;t++)i.push(e.map(e=>e[t].value)),r.push(`asc`);let o={desc:jg(`desc`),asc:jg(`asc`)},s=S(0,e.length);return s.sort((e,t)=>{for(let[n,a]of i.entries()){let i=a[e],s=a[t],c={value:i,type:i===null?`empty`:typeof i==`string`?`text`:typeof i},l={value:s,type:s===null?`empty`:typeof s==`string`?`text`:typeof s},u=o[r[n]](c,l);if(u!==0)return u}return 0}),s.map(t=>e[t])}let Lg={description:E(`Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions.`),args:[U(`range (any, range<any>)`,E(`The data to be filtered.`)),U(`condition1 (boolean, range<boolean>)`,E(`A column or row containing true or false values corresponding to the first column or row of range.`)),U(`condition2 (boolean, range<boolean>, repeating)`,E(`Additional column or row containing true or false values.`))],compute:function(e,...t){let n=I(e),r=t.map(e=>ha(I(e),e=>e.value));for(let e of r)if(!_u(e))return new A(E(`The arguments condition must be a single column or row.`));if(!vu(...t))return new A(E(`The arguments conditions must have the same dimensions.`));let i=r.map(e=>e.flat()),a=r[0].length===1?`row`:`col`;if(n=a===`row`?_a(n):n,i.some(e=>e.length!==n.length))return new A(E(`FILTER has mismatched sizes on the range and conditions.`));let o=[];for(let e=0;e<n.length;e++){let t=n[e];i.every(t=>(typeof t[e]==`boolean`||typeof t[e]==`number`)&&t[e])&&o.push(t)}return o.length?a===`row`?_a(o):o:new Hi(E(`No match found in FILTER evaluation`))},isExported:!1},Rg={description:E(`Sorts the rows of a given array or range by the values in one or more columns.`),args:[U(`range (range)`,E(`The data to be sorted.`)),U(`sort_column (any, range<number>, repeating)`,E(`The index of the column in range or a range outside of range containing the values by which to sort.`)),U(`is_ascending (boolean, repeating)`,E(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`))],compute:function(e,...t){return _a(Ig(_a(e),this.locale,...t))},isExported:!0},zg={description:E(`Returns the first n items in a data set after performing a sort.`),args:[U(`range (range)`,E(`The data to be sorted.`)),U(`n (number)`,E(`The number of items to return.`)),U(`display_ties_mode (number, default=0)`,E(`A number representing the way to display ties.`)),U(`sort_column (number, range<number>, repeating)`,E(`The index of the column in range or a range outside of range containing the values by which to sort.`)),U(`is_ascending (boolean, repeating)`,E(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`))],compute:function(e,t,...n){let r=M(t?.value??1,this.locale),i=n.length%2==0?0:M(n[0]?.value,this.locale),a=n.length%2==0?n:n.slice(1);if(r<0)return new A(E(`Wrong value of 'n'. Expected a positive number. Got %s.`,r));if(i<0||i>3)return new A(E(`Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.`,i));let o=Ig(_a(e),this.locale,...a),s=(e,t)=>JSON.stringify(o[e].map(e=>e.value))===JSON.stringify(o[t].map(e=>e.value));switch(i){case 0:return _a(o.slice(0,r));case 1:for(let e=r;e<o.length;e++)if(!s(e,r-1))return _a(o.slice(0,e));return _a(o);case 2:{let e=[o[0]];for(let t=1;t<o.length;t++)for(let n=0;n<t&&!s(t,n);n++)n===t-1&&e.push(o[t]);return _a(e.slice(0,r))}case 3:{let e=[o[0]],t=1;for(let n=1;n<o.length&&(s(n,n-1)||t++,!(t>r));n++)e.push(o[n]);return _a(e)}}},isExported:!1},Bg={description:E(`Unique rows in the provided source range.`),args:[U(`range (any, range<any>)`,E(`The data to filter by unique entries.`)),U(`by_column (boolean, default=FALSE)`,E(`Whether to filter the data by columns or by rows.`)),U(`exactly_once (boolean, default=FALSE)`,E(`Whether to return only entries with no duplicates.`))],compute:function(e={value:``},t,n){if(!Or(e))return[[e]];let r=P(t?.value)||!1,i=P(n?.value)||!1;r||(e=_a(e));let a=new Map;for(let t of e){let e=JSON.stringify(t.map(e=>e.value)),n=a.get(e);n?n.count++:a.set(e,{data:t,count:1})}let o=[];for(let e of a.values())i&&e.count>1||o.push(e.data);return o.length?r?o:_a(o):new A(E(`No unique values found`))},isExported:!0},Vg=E(`The cashflow_amounts and cashflow_dates ranges must have the same dimensions.`),Hg=E(`There must be both positive and negative values in cashflow_amounts.`),Ug=e=>E(`The cost (%s) must be positive or null.`,e),Wg=e=>E(`The cost (%s) must be strictly positive.`,e),Gg=e=>E(`The frequency (%s) must be one of %s`,e,[1,2,4].toString()),Kg=e=>E(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,e),qg=e=>E(`The depreciation factor (%s) must be strictly positive.`,e),Jg=e=>E(`The discount (%s) must be different from -1.`,e),Yg=e=>E(`The discount (%s) must be strictly positive.`,e),Xg=e=>E(`The discount (%s) must be smaller than 1.`,e),Zg=e=>E(`The effective_rate (%s) must be strictly positive.`,e),Qg=e=>E(`The end_period (%s) must be positive or null.`,e),$g=(e,t)=>E(`The end_period (%(end)s) must be smaller or equal to the life (%(life)s).`,{end:e,life:t}),e_=e=>E(`All the dates should be greater or equal to the first date in cashflow_dates (%s).`,e),t_=(e,t)=>E(`The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).`,{first:e,last:t}),n_=e=>E(`The first_period (%s) must be strictly positive.`,e),r_=e=>E(`The future_value (%s) must be strictly positive.`,e),i_=e=>E(`The investment (%s) must be strictly positive.`,e),a_=e=>E(`The issue (%s) must be positive or null.`,e),o_=(e,t)=>E(`The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).`,{last:e,nPeriods:t}),s_=e=>E(`The last_period (%s) must be strictly positive.`,e),c_=e=>E(`The life (%s) must be strictly positive.`,e),l_=(e,t)=>E(`The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).`,{maturity:t,settlement:e}),u_=e=>E(`The month (%s) must be between 1 and 12 inclusive.`,e),d_=e=>E(`The nominal_rate (%s) must be strictly positive.`,e),f_=e=>E(`The number_of_periods (%s) must be different from zero.`,e),p_=e=>E(`The number_of_periods (%s) must be strictly positive.`,e),m_=e=>E(`The period must be between 1 and number_of_periods (%s)`,e),h_=(e,t)=>E(`The period (%(period)s) must be less than or equal to %(lifeLimit)s.`,{period:e,lifeLimit:t}),g_=e=>E(`The period (%s) must be positive or null.`,e),__=e=>E(`The periods_by_year (%s) must be strictly positive.`,e),v_=(e,t)=>E(`The period (%(period)s) must be less than or equal life (%(life)s).`,{period:e,life:t}),y_=e=>E(`The period (%s) must be strictly positive.`,e),b_=e=>E(`The present_value (%s) must be strictly positive.`,e),x_=e=>E(`The price (%s) must be strictly positive.`,e),S_=(e,t)=>E(`The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).`,{purchaseDate:e,firstPeriodEnd:t}),C_=e=>E(`The purchase_date (%s) must be positive or null.`,e),w_=e=>E(`The rate_guess (%s) must be strictly greater than -1.`,e),T_=e=>E(`The rate (%s) must be positive or null.`,e),E_=e=>E(`The rate (%s) must be strictly positive.`,e),D_=e=>E(`The redemption (%s) must be strictly positive.`,e),O_=e=>E(`The salvage (%s) must be positive or null.`,e),k_=(e,t)=>E(`The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).`,{salvage:e,cost:t}),A_=(e,t)=>E(`The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).`,{settlement:e,issue:t}),j_=(e,t)=>E(`The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).`,{settlement:e,maturity:t}),M_=(e,t)=>E(`The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).`,{settlement:e,issue:t}),N_=e=>E(`The start_period (%s) must be positive or null.`,e),P_=(e,t)=>E(`The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).`,{start:e,end:t}),F_=e=>E(`The unit (%s) must be strictly positive.`,e),I_=e=>E(`The yield (%s) must be positive or null.`,e);function L_(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function R_(e){return![0,1,2,3,4].includes(e)}function z_(e){return![1,2,4].includes(e)}function B_(e,t,n){let r=F(e,n),i=F(t,n),a=F(e,n);return a.setFullYear(r.getFullYear()+1),i.getTime()<=a.getTime()}var V_=l({ACCRINTM:()=>W_,AMORLINC:()=>G_,COUPDAYBS:()=>q_,COUPDAYS:()=>K_,COUPDAYSNC:()=>J_,COUPNCD:()=>Y_,COUPNUM:()=>X_,COUPPCD:()=>Z_,CUMIPMT:()=>Q_,CUMPRINC:()=>$_,DB:()=>ev,DDB:()=>nv,DISC:()=>rv,DOLLARDE:()=>iv,DOLLARFR:()=>av,DURATION:()=>ov,EFFECT:()=>sv,FV:()=>lv,FVSCHEDULE:()=>uv,INTRATE:()=>dv,IPMT:()=>pv,IRR:()=>hv,ISPMT:()=>gv,MDURATION:()=>_v,MIRR:()=>vv,NOMINAL:()=>yv,NPER:()=>bv,NPV:()=>Sv,PDURATION:()=>Cv,PMT:()=>Tv,PPMT:()=>Dv,PRICE:()=>kv,PRICEDISC:()=>Av,PRICEMAT:()=>jv,PV:()=>Ov,RATE:()=>Nv,RECEIVED:()=>Pv,RRI:()=>Fv,SLN:()=>Iv,SYD:()=>Lv,TBILLEQ:()=>Bv,TBILLPRICE:()=>zv,TBILLYIELD:()=>Vv,VDB:()=>Hv,XIRR:()=>Uv,XNPV:()=>Wv,YIELD:()=>Gv,YIELDDISC:()=>Kv,YIELDMAT:()=>qv});let H_=[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))];function U_(e,t,n,r,i=1e-10,a){let o=n,s,c,l,u=!1,d=0,f;do{if(l=e(o),isNaN(l)){hu(d<r&&a!==void 0,E(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++,o=a(f),f=o;continue}s=o-l/t(o),c=Math.abs(s-o),o=s,u=c<i||Math.abs(l)<i,hu(d<r,E(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++}while(!u);return o}let W_={description:E(`Accrued interest of security paying at maturity.`),args:[U(`issue (date)`,E(`The date the security was initially issued.`)),U(`maturity (date)`,E(`The maturity date of the security.`)),U(`rate (number)`,E(`The annualized rate of interest.`)),U(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(r,this.locale),c=M(n,this.locale),l=Math.trunc(M(i,this.locale));if(a<0)return new A(a_(a));if(a>=o)return new A(l_(a,o));if(R_(l))return new A(Kg(l));if(s<=0)return new A(D_(s));if(c<=0)return new A(E_(c));let u=xi(a,o,l);return s*c*u},isExported:!0},G_={description:E(`Depreciation for an accounting period.`),args:[U(`cost (number)`,E(`The initial cost of the asset.`)),U(`purchase_date (date)`,E(`The date the asset was purchased.`)),U(`first_period_end (date)`,E(`The date the first period ended.`)),U(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),U(`period (number)`,E(`The single period within life for which to calculate depreciation.`)),U(`rate (number)`,E(`The deprecation rate.`)),U(`day_count_convention (number, optional)`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=M(e,this.locale),c=Math.trunc(M(t,this.locale)),l=Math.trunc(M(n,this.locale)),u=M(r,this.locale),d=M(i,this.locale),f=M(a,this.locale),p=Math.trunc(M(o,this.locale));if(s<=0)return new A(Wg(s));if(c<0)return new A(C_(c));if(u<0)return new A(O_(u));if(u>s)return new A(k_(u,s));if(d<0)return new A(g_(d));if(f<=0)return new A(E_(f));if(R_(p))return new A(Kg(p));if(c>l)return new A(S_(c,l));let m=d<1&&d>0?1:Math.trunc(d),h=s*f,g=xi(c,l,p),_=c===l?h:h*g,v=s-_-h*m;return v>=u?m===0?_:h:u-v<h?h-(u-v):0},isExported:!0},K_={description:E(`Days in coupon period containing settlement date.`),args:H_,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A(l_(i,a));if(z_(o))return new A(Gg(o));if(R_(s))return new A(Kg(s));if(s===1){let i=Z_.compute.bind(this)(e,t,n,r).value,a=Y_.compute.bind(this)(e,t,n,r).value;return M(a,this.locale)-M(i,this.locale)}return(s===3?365:360)/o},isExported:!0},q_={description:E(`Days from settlement until next coupon.`),args:H_,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A(l_(i,a));if(z_(o))return new A(Gg(o));if(R_(s))return new A(Kg(s));let c=Z_.compute.bind(this)(e,t,n,r).value,l=M(c,this.locale);if([1,2,3].includes(s))return i-l;if(s===4){let e=xi(l,i,s);return Math.round(e*360)}let u=F(i,this.locale),d=F(l,this.locale),f=d.getFullYear(),p=u.getFullYear(),m=d.getMonth()+1,h=u.getMonth()+1,g=d.getDate(),_=u.getDate();return m===2&&h===2&&vi(d)&&vi(u)&&(_=30),_===31&&(g===30||g===31)&&(_=30),m===2&&vi(d)&&(g=30),g===31&&(g=30),(p-f)*360+(h-m)*30+(_-g)},isExported:!0},J_={description:E(`Days from settlement until next coupon.`),args:H_,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A(l_(i,a));if(z_(o))return new A(Gg(o));if(R_(s))return new A(Kg(s));let c=Y_.compute.bind(this)(e,t,n,r).value,l=M(c,this.locale);if([1,2,3].includes(s))return l-i;if(s===4){let e=xi(i,l,s);return Math.round(e*360)}let u=q_.compute.bind(this)(e,t,n,r);return M(K_.compute.bind(this)(e,t,n,r),this.locale)-M(u,this.locale)},isExported:!0},Y_={description:E(`Next coupon date after the settlement date.`),args:H_,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A(l_(i,a));if(z_(o))return new A(Gg(o));if(R_(s))return new A(Kg(s));let c=12/o,l=X_.compute.bind(this)(e,t,n,r);return{value:hi(yi(F(a,this.locale),-(M(l,this.locale)-1)*c,!0)),format:this.locale.dateFormat}},isExported:!0},X_={description:E(`Number of coupons between settlement and maturity.`),args:H_,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A(l_(i,a));if(z_(o))return new A(Gg(o));if(R_(s))return new A(Kg(s));let c=1,l=a,u=12/o;for(;l>i;)l=hi(yi(F(l,this.locale),-u,!1)),c++;return c-1},isExported:!0},Z_={description:E(`Last coupon date prior to or on the settlement date.`),args:H_,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A(l_(i,a));if(z_(o))return new A(Gg(o));if(R_(s))return new A(Kg(s));let c=12/o,l=X_.compute.bind(this)(e,t,n,r);return{value:hi(yi(F(a,this.locale),-l*c,!0)),format:this.locale.dateFormat}},isExported:!0},Q_={description:E(`Cumulative interest paid over a set of periods.`),args:[U(`rate (number)`,E(`The interest rate.`)),U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`present_value (number)`,E(`The current value of the annuity.`)),U(`first_period (number)`,E(`The number of the payment period to begin the cumulative calculation.`)),U(`last_period (number)`,E(`The number of the payment period to end the cumulative calculation.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`))],compute:function(e,t,n,r,i,a={value:0}){let o=M(r,this.locale),s=M(i,this.locale),c=M(e,this.locale),l=M(n,this.locale),u=M(t,this.locale),d=+!!P(a);if(u<=0)return new A(p_(u));if(o<=0)return new A(n_(o));if(s<=0)return new A(s_(s));if(o>s)return new A(t_(o,s));if(s>u)return new A(o_(s,u));if(c<=0)return new A(E_(c));if(l<=0)return new A(b_(l));let f=0;for(let e=o;e<=s;e++)f+=fv(c,e,u,l,0,d);return f},isExported:!0},$_={description:E(`Cumulative principal paid over a set of periods.`),args:[U(`rate (number)`,E(`The interest rate.`)),U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`present_value (number)`,E(`The current value of the annuity.`)),U(`first_period (number)`,E(`The number of the payment period to begin the cumulative calculation.`)),U(`last_period (number)`,E(`The number of the payment period to end the cumulative calculation.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`))],compute:function(e,t,n,r,i,a={value:0}){let o=M(r,this.locale),s=M(i,this.locale),c=M(e,this.locale),l=M(n,this.locale),u=M(t,this.locale),d=+!!P(a);if(u<=0)return new A(p_(u));if(o<=0)return new A(n_(o));if(s<=0)return new A(s_(s));if(o>s)return new A(t_(o,s));if(s>u)return new A(o_(s,u));if(c<=0)return new A(E_(c));if(l<=0)return new A(b_(l));let f=0;for(let e=o;e<=s;e++)f+=Ev(c,e,u,l,0,d);return f},isExported:!0},ev={description:E(`Depreciation via declining balance method.`),args:[U(`cost (number)`,E(`The initial cost of the asset.`)),U(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),U(`life (number)`,E(`The number of periods over which the asset is depreciated.`)),U(`period (number)`,E(`The single period within life for which to calculate depreciation.`)),U(`month (number, optional)`,E(`The number of months in the first year of depreciation.`))],compute:function(e,t,n,r,...i){let a=M(e,this.locale),o=M(t,this.locale),s=M(n,this.locale),c=Math.trunc(M(r,this.locale)),l=i.length?Math.trunc(M(i[0],this.locale)):12,u=s+(l===12?0:1);if(a<0)return new A(Ug(a));if(o<0)return new A(O_(o));if(c<=0)return new A(y_(c));if(s<=0)return new A(c_(s));if(1>l||l>12)return new A(u_(l));if(c>u)return new A(h_(c,u));let d=l/12,f=1-(o/a)**(1/s);f=Math.round(f*1e3)/1e3;let p=a,m=a*(1-f*d);for(let e=1;e<c;e++)p=m,m=p*(1-f),e===s&&(m=p*(1-f*(1-d)));return{value:p-m,format:`#,##0.00`}},isExported:!0},tv=`#,##0.00`,nv={description:E(`Depreciation via double-declining balance method.`),args:[U(`cost (number)`,E(`The initial cost of the asset.`)),U(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),U(`life (number)`,E(`The number of periods over which the asset is depreciated.`)),U(`period (number)`,E(`The single period within life for which to calculate depreciation.`)),U(`factor (number, default=2)`,E(`The factor by which depreciation decreases.`))],compute:function(e,t,n,r,i={value:2}){let a=M(e,this.locale),o=M(t,this.locale),s=M(n,this.locale),c=M(r,this.locale),l=M(i,this.locale);if(a<0)return new A(Ug(a));if(o<0)return new A(O_(o));if(c<=0)return new A(y_(c));if(s<=0)return new A(c_(s));if(c>s)return new A(v_(c,s));if(l<=0)return new A(qg(l));if(a===0||o>=a)return{value:0,format:tv};let u=l/s;if(u>1)return{value:c===1?a-o:0,format:tv};if(c<=1)return{value:a*u,format:tv};let d=a*(1-u)**(c-1),f=a*(1-u)**c,p=f<o?d-o:d-f;return{value:Math.max(p,0),format:tv}},isExported:!0},rv={description:E(`Discount rate of a security based on price.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`price (number)`,E(`The price at which the security is bought per 100 face value.`)),U(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(n,this.locale),c=M(r,this.locale),l=Math.trunc(M(i,this.locale));if(a>=o)return new A(l_(a,o));if(R_(l))return new A(Kg(l));if(s<=0)return new A(x_(s));if(c<=0)return new A(D_(c));let u=xi(a,o,l);return(c-s)/c/u},isExported:!0},iv={description:E(`Convert a decimal fraction to decimal value.`),args:[U(`fractional_price (number)`,E(`The price quotation given using fractional decimal conventions.`)),U(`unit (number)`,E(`The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=M(e,this.locale),r=Math.trunc(M(t,this.locale));if(r<=0)return new A(F_(r));let i=Math.trunc(n);return i+(n-i)*(10**Math.ceil(Math.log10(r))/r)},isExported:!0},av={description:E(`Convert a decimal value to decimal fraction.`),args:[U(`decimal_price (number)`,E(`The price quotation given as a decimal value.`)),U(`unit (number)`,E(`The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=M(e,this.locale),r=Math.trunc(M(t,this.locale));if(r<=0)return new A(F_(r));let i=Math.trunc(n);return i+(n-i)*(r/10**Math.ceil(Math.log10(r)))},isExported:!0},ov={description:E(`Number of periods for an investment to reach a value.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`rate (number)`,E(`The annualized rate of interest.`)),U(`yield (number)`,E(`The expected annual yield of the security.`)),U(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){let o=Math.trunc(M(e,this.locale)),s=Math.trunc(M(t,this.locale)),c=M(n,this.locale),l=M(r,this.locale),u=Math.trunc(M(i,this.locale)),d=Math.trunc(M(a,this.locale));if(o>=s)return new A(l_(o,s));if(z_(u))return new A(Gg(u));if(R_(d))return new A(Kg(d));if(c<0)return new A(T_(c));if(l<0)return new A(I_(l));let f=xi(o,s,d),p=f-Math.trunc(f)||1/u,m=Math.ceil(f*u),h=c/u,g=l/u,_=0,v=0;for(let e=1;e<=m;e++){let t=(h+ +(e===m))/(1+g)**e;v+=(p+(e-1)/u)*t,_+=t}return _===0?0:v/_},isExported:!0},sv={description:E(`Annual effective interest rate.`),args:[U(`nominal_rate (number)`,E(`The nominal interest rate per year.`)),U(`periods_per_year (number)`,E(`The number of compounding periods per year.`))],compute:function(e,t){let n=M(e,this.locale),r=Math.trunc(M(t,this.locale));return n<=0?new A(d_(n)):r<=0?new A(__(r)):(1+n/r)**+r-1},isExported:!0};function cv(e,t,n,r,i){return e===0?-(r+n*t):-r*(1+e)**t-n*(1+e*i)*((1+e)**t-1)/e}let lv={description:E(`Future value of an annuity investment.`),args:[U(`rate (number)`,E(`The interest rate.`)),U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`payment_amount (number)`,E(`The amount per period to be paid.`)),U(`present_value (number, default=0)`,E(`The current value of the annuity.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`))],compute:function(e,t,n,r={value:0},i={value:0}){return r||=0,i||=0,{value:cv(M(e,this.locale),M(t,this.locale),M(n,this.locale),M(r,this.locale),+!!P(i)),format:`#,##0.00`}},isExported:!0},uv={description:E(`Future value of principal from series of rates.`),args:[U(`principal (number)`,E(`The amount of initial capital or value to compound against.`)),U(`rate_schedule (number, range<number>)`,E(`A series of interest rates to compound against the principal.`))],compute:function(e,t){let n=M(e,this.locale);return da([t],(e,t)=>e*(1+M(t,this.locale)),n)},isExported:!0},dv={description:E(`Calculates effective interest rate.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`investment (number)`,E(`The amount invested in the security.`)),U(`redemption (number)`,E(`The amount to be received at maturity.`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(r,this.locale),c=M(n,this.locale),l=Math.trunc(M(i,this.locale));if(a>=o)return new A(l_(a,o));if(c<=0)return new A(i_(c));if(s<=0)return new A(D_(s));if(R_(l))return new A(Kg(l));let u=xi(a,o,l);return(s-c)/c/u},isExported:!0};function fv(e,t,n,r,i,a){return wv(e,n,r,i,a)-Ev(e,t,n,r,i,a)}let pv={description:E(`Payment on the principal of an investment.`),args:[U(`rate (number)`,E(`The annualized rate of interest.`)),U(`period (number)`,E(`The amortization period, in terms of number of periods.`)),U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`present_value (number)`,E(`The current value of the annuity.`)),U(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`))],compute:function(e,t,n,r,i={value:0},a={value:0}){return{value:fv(M(e,this.locale),M(t,this.locale),M(n,this.locale),M(r,this.locale),M(i,this.locale),+!!P(a)),format:`#,##0.00`}},isExported:!0},mv=.1,hv={description:E(`Internal rate of return given periodic cashflows.`),args:[U(`cashflow_amounts (number, range<number>)`,E(`An array or range containing the income or payments associated with the investment.`)),U(`rate_guess (number, default=${mv})`,E(`An estimate for what the internal rate of return will be.`))],compute:function(e,t={value:mv}){let n=M(t,this.locale);if(n<=-1)return new A(w_(n));let r=!1,i=!1,a=[];if(la([e],({value:e})=>{e>0&&(r=!0),e<0&&(i=!0),a.push(e)},this.locale),!r||!i)return new A(Hg);let o=a.shift();function s(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*e**(r-i)),t*e**r)}function c(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*(r-i)*e**(r-i-1)),t*r*e**(r-1))}function l(e){return s(e,o,a)}function u(e){return c(e,o,a)}return{value:U_(l,u,n+1,20,1e-5)-1,format:`0%`}},isExported:!0},gv={description:E(`Returns the interest paid at a particular period of an investment.`),args:[U(`rate (number)`,E(`The interest rate.`)),U(`period (number)`,E(`The period for which you want to view the interest payment.`)),U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`present_value (number)`,E(`The current value of the annuity.`))],compute:function(e,t,n,r){let i=M(e,this.locale),a=M(t,this.locale),o=M(n,this.locale),s=M(r,this.locale);return o===0?new A(f_(o)):-1*(s-a/o*s)*i},isExported:!0},_v={description:E(`Modified Macaulay duration.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`rate (number)`,E(`The annualized rate of interest.`)),U(`yield (number)`,E(`The expected annual yield of the security.`)),U(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){let o=ov.compute.bind(this)(e,t,n,r,i,a),s=M(r,this.locale),c=Math.trunc(M(i,this.locale));return M(o,this.locale)/(1+s/c)},isExported:!0},vv={description:E(`Modified internal rate of return.`),args:[U(`cashflow_amounts (range<number>)`,E(`A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.`)),U(`financing_rate (number)`,E(`The interest rate paid on funds invested.`)),U(`reinvestment_return_rate (number)`,E(`The return (as a percentage) earned on reinvestment of income received from the investment.`))],compute:function(e,t,n){let r=M(t,this.locale),i=M(n,this.locale),a=_a(e).flat().filter(e=>e.value!==null).map(e=>M(e,this.locale)),o=a.length,s=0,c=0;for(let e of S(0,o)){let t=a[e];t>=0?s+=t*(i+1)**(o-e-1):c+=t/(r+1)**e}if(c===0||s===0)return new A(Hg);let l=1/(o-1);return(-s/c)**l-1},isExported:!0},yv={description:E(`Annual nominal interest rate.`),args:[U(`effective_rate (number)`,E(`The effective interest rate per year.`)),U(`periods_per_year (number)`,E(`The number of compounding periods per year.`))],compute:function(e,t){let n=M(e,this.locale),r=Math.trunc(M(t,this.locale));return n<=0?new A(Zg(n)):r<=0?new A(__(r)):((n+1)**(1/r)-1)*r},isExported:!0},bv={description:E(`Number of payment periods for an investment.`),args:[U(`rate (number)`,E(`The interest rate.`)),U(`payment_amount (number)`,E(`The amount of each payment made.`)),U(`present_value (number)`,E(`The current value of the annuity.`)),U(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`))],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=M(e,this.locale),o=M(t,this.locale),s=M(n,this.locale),c=M(r,this.locale),l=+!!P(i);if(a===0)return-(c+s)/o;let u=o*(1+a*l)/a;return Math.log((u-c)/(s+u))/Math.log(1+a)},isExported:!0};function xv(e,t,n,r){let i=0;return fa(n,(t,n)=>(i++,t+n/(1+e)**i),t,r)}let Sv={description:E(`The net present value of an investment based on a series of periodic cash flows and a discount rate.`),args:[U(`discount (number)`,E(`The discount rate of the investment over one period.`)),U(`cashflow1 (number, range<number>)`,E(`The first future cash flow.`)),U(`cashflow2 (number, range<number>, repeating)`,E(`Additional future cash flows.`))],compute:function(e,...t){let n=M(e,this.locale);return n===-1?new A(Jg(n)):{value:xv(n,0,t,this.locale),format:`#,##0.00`}},isExported:!0},Cv={description:E(`Computes the number of periods needed for an investment to reach a value.`),args:[U(`rate (number)`,E(`The rate at which the investment grows each period.`)),U(`present_value (number)`,E(`The investment's current value.`)),U(`future_value (number)`,E(`The investment's desired future value.`))],compute:function(e,t,n){let r=M(e,this.locale),i=M(t,this.locale),a=M(n,this.locale);return r<=0?new A(E_(r)):i<=0?new A(b_(i)):a<=0?new A(r_(a)):(Math.log(a)-Math.log(i))/Math.log(1+r)},isExported:!0};function wv(e,t,n,r,i){if(t<=0)throw new A(p_(t));if(e===0)return-(r+n)/t;let a=-(n*(1+e)**t+r);return a=a*e/((1+e*i)*((1+e)**t-1)),a}let Tv={description:E(`Periodic payment for an annuity investment.`),args:[U(`rate (number)`,E(`The annualized rate of interest.`)),U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`present_value (number)`,E(`The current value of the annuity.`)),U(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`))],compute:function(e,t,n,r={value:0},i={value:0}){let a=M(t,this.locale),o=M(e,this.locale),s=+!!P(i),c=M(r,this.locale);return{value:wv(o,a,M(n,this.locale),c,s),format:`#,##0.00`}},isExported:!0};function Ev(e,t,n,r,i,a){if(n<=0)throw new A(p_(n));if(t<=0||t>n)throw new A(m_(n));let o=wv(e,n,r,i,a);return a===1&&t===1?o:o+-cv(e,a===0?t-1:t-2,o,r+o*a,0)*e}let Dv={description:E(`Payment on the principal of an investment.`),args:[U(`rate (number)`,E(`The annualized rate of interest.`)),U(`period (number)`,E(`The amortization period, in terms of number of periods.`)),U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`present_value (number)`,E(`The current value of the annuity.`)),U(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`))],compute:function(e,t,n,r,i={value:0},a={value:0}){let o=M(n,this.locale),s=M(e,this.locale),c=M(t,this.locale),l=+!!P(a),u=M(i,this.locale);return{value:Ev(s,c,o,M(r,this.locale),u,l),format:`#,##0.00`}},isExported:!0},Ov={description:E(`Present value of an annuity investment.`),args:[U(`rate (number)`,E(`The interest rate.`)),U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`payment_amount (number)`,E(`The amount per period to be paid.`)),U(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`))],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=M(e,this.locale),o=M(t,this.locale),s=M(n,this.locale),c=M(r,this.locale),l=+!!P(i);return{value:a?-(s*(1+a*l)*((1+a)**o-1)/a+c)/(1+a)**o:-(c+s*o),format:`#,##0.00`}},isExported:!0},kv={description:E(`Price of a security paying periodic interest.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`rate (number)`,E(`The annualized rate of interest.`)),U(`yield (number)`,E(`The expected annual yield of the security.`)),U(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),U(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(M(e,this.locale)),c=Math.trunc(M(t,this.locale)),l=M(n,this.locale),u=M(r,this.locale),d=M(i,this.locale),f=Math.trunc(M(a,this.locale)),p=Math.trunc(M(o,this.locale));if(s>=c)return new A(l_(s,c));if(z_(f))return new A(Gg(f));if(R_(p))return new A(Kg(p));if(l<0)return new A(T_(l));if(u<0)return new A(I_(u));if(d<=0)return new A(D_(d));let m=xi(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=1+u/f,v=100*l/f;if(h===1)return(v+d)/(g*u/f+1)-v*(1-g);let y=0;for(let e=1;e<=h;e++)y+=v/_**(e-1+g);return d/_**(h-1+g)+y-v*(1-g)},isExported:!0},Av={description:E(`Price of a discount security.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`discount (number)`,E(`The discount rate of the security at time of purchase.`)),U(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(n,this.locale),c=M(r,this.locale),l=Math.trunc(M(i,this.locale));if(a>=o)return new A(l_(a,o));if(R_(l))return new A(Kg(l));if(s<=0)return new A(Yg(s));if(c<=0)return new A(D_(c));let u=xi(a,o,l);return c-s*c*u},isExported:!0},jv={description:E(`Calculates the price of a security paying interest at maturity, based on expected yield.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`issue (date)`,E(`The date the security was initially issued.`)),U(`rate (number)`,E(`The annualized rate of interest.`)),U(`yield (number)`,E(`The expected annual yield of the security.`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(M(e,this.locale)),s=Math.trunc(M(t,this.locale)),c=Math.trunc(M(n,this.locale)),l=M(r,this.locale),u=M(i,this.locale),d=Math.trunc(M(a,this.locale));if(o<=c)return new A(M_(o,c));if(o>=s)return new A(l_(o,s));if(R_(d))return new A(Kg(d));if(l<0)return new A(T_(l));if(u<0)return new A(I_(u));let f=xi(o,s,d),p=xi(o,c,d),m=100+xi(c,s,d)*l*100,h=1+f*u,g=p*l*100;return m/h-g},isExported:!0},Mv=.1,Nv={description:E(`Interest rate of an annuity investment.`),args:[U(`number_of_periods (number)`,E(`The number of payments to be made.`)),U(`payment_per_period (number)`,E(`The amount per period to be paid.`)),U(`present_value (number)`,E(`The current value of the annuity.`)),U(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,E(`Whether payments are due at the end (0) or beginning (1) of each period.`)),U(`rate_guess (number, default=${Mv})`,E(`An estimate for what the interest rate will be.`))],compute:function(e,t,n,r={value:0},i={value:0},a={value:Mv}){let o=M(e,this.locale),s=M(t,this.locale),c=+!!P(i),l=M(a,this.locale)||Mv,u=M(r,this.locale),d=M(n,this.locale);return o<=0?new A(p_(o)):L_([s,d,u])?l<=-1?new A(w_(l)):(u-=s*c,d+=s*c,{value:U_(e=>{let t=(1+e)**+o,n=(t-1)/e;return u+d*t+s*n},e=>{let t=(1+e)**(o-1),n=((1+e)**+o-1)/e,r=o*t/e-n/e;return d*o*t+s*r},l,40,1e-5),format:`0%`}):new A(E(`There must be both positive and negative values in [payment_amount, present_value, future_value].`))},isExported:!0},Pv={description:E(`Amount received at maturity for a security.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`investment (number)`,E(`The amount invested (irrespective of face value of each security).`)),U(`discount (number)`,E(`The discount rate of the security invested in.`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(n,this.locale),c=M(r,this.locale),l=Math.trunc(M(i,this.locale));return a>=o?new A(l_(a,o)):R_(l)?new A(Kg(l)):s<=0?new A(i_(s)):c<=0?new A(Yg(c)):s/(1-c*xi(a,o,l))},isExported:!0},Fv={description:E(`Computes the rate needed for an investment to reach a specific value within a specific number of periods.`),args:[U(`number_of_periods (number)`,E(`The number of periods.`)),U(`present_value (number)`,E(`The present value of the investment.`)),U(`future_value (number)`,E(`The future value of the investment.`))],compute:function(e,t,n){let r=M(e,this.locale),i=M(t,this.locale),a=M(n,this.locale);return r<=0?new A(p_(r)):(a/i)**(1/r)-1},isExported:!0},Iv={description:E(`Depreciation of an asset using the straight-line method.`),args:[U(`cost (number)`,E(`The initial cost of the asset.`)),U(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),U(`life (number)`,E(`The number of periods over which the asset is depreciated.`))],compute:function(e,t,n){let r=M(e,this.locale),i=M(t,this.locale),a=M(n,this.locale);return{value:(r-i)/a,format:`#,##0.00`}},isExported:!0},Lv={description:E(`Depreciation via sum of years digit method.`),args:[U(`cost (number)`,E(`The initial cost of the asset.`)),U(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),U(`life (number)`,E(`The number of periods over which the asset is depreciated.`)),U(`period (number)`,E(`The single period within life for which to calculate depreciation.`))],compute:function(e,t,n,r){let i=M(e,this.locale),a=M(t,this.locale),o=M(n,this.locale),s=M(r,this.locale);if(s<=0)return new A(y_(s));if(o<=0)return new A(c_(o));if(s>o)return new A(v_(s,o));let c=o*(o+1)/2,l=o-s+1;return{value:(i-a)*(l/c),format:`#,##0.00`}},isExported:!0};function Rv(e,t,n){return 100*(1-n*xi(e,t,2))}let zv={description:E(`Price of a US Treasury bill.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`discount (number)`,E(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=M(n,this.locale);return r>=i?new A(l_(r,i)):B_(r,i,this.locale)?a<=0?new A(Yg(a)):a>=1?new A(Xg(a)):Rv(r,i,a):new A(j_(r,i))},isExported:!0},Bv={description:E(`Equivalent rate of return for a US Treasury bill.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`discount (number)`,E(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=M(n,this.locale);if(r>=i)return new A(l_(r,i));if(!B_(r,i,this.locale))return new A(j_(r,i));if(a<=0)return new A(Yg(a));if(a>=1)return new A(Xg(a));let o=$h.compute.bind(this)({value:i},{value:r});if(o<=182)return 365*a/(360-a*o);let s=Rv(r,i,a)/100,c=o/(o===366?366:365);return(-2*c+2*Math.sqrt(c**2-(2*c-1)*(1-1/s)))/(2*c-1)},isExported:!0},Vv={description:E(`The yield of a US Treasury bill based on price.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`price (number)`,E(`The price at which the security is bought per 100 face value.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=M(n,this.locale);if(r>=i)return new A(l_(r,i));if(!B_(r,i,this.locale))return new A(j_(r,i));if(a<=0)return new A(x_(a));let o=xi(r,i,2);return(100-a)/a*(1/o)},isExported:!0},Hv={description:E(`Variable declining balance. WARNING : does not handle decimal periods.`),args:[U(`cost (number)`,E(`The initial cost of the asset.`)),U(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),U(`life (number)`,E(`The number of periods over which the asset is depreciated.`)),U(`start (number)`,E(`Starting period to calculate depreciation.`)),U(`end (number)`,E(`Ending period to calculate depreciation.`)),U(`factor (number, default=2)`,E(`The number of months in the first year of depreciation.`)),U(`no_switch (number, default=false)`,E(`Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.`))],compute:function(e,t,n,r,i,a={value:2},o={value:!1}){a||=0;let s=M(e,this.locale),c=M(t,this.locale),l=M(n,this.locale),u=Math.trunc(M(r,this.locale)),d=Math.trunc(M(i,this.locale)),f=M(a,this.locale),p=P(o);if(s<0)return new A(Ug(s));if(c<0)return new A(O_(c));if(l<=0)return new A(c_(l));if(u<0)return new A(N_(u));if(d<0)return new A(Qg(d));if(u>d)return new A(P_(u,d));if(d>l)return new A($g(d,l));if(f<=0)return new A(qg(f));if(s===0)return 0;if(c>=s)return u<1?s-c:0;let m=f/l;if(m>=1)return u<1?s-c:0;let h=s,g=0,_=0,v=!1;for(let e=0;e<d;e++){if(!v||p){let t=h*m,n=l-e,r=(h-c)/n;!p&&r>t?(v=!0,g=r):g=t}let t=Math.max(h-g,c);e>=u&&(_+=h-t),h=t}return _},isExported:!0},Uv={description:E(`Internal rate of return given non-periodic cash flows.`),args:[U(`cashflow_amounts (range<number>)`,E(`An range containing the income or payments associated with the investment.`)),U(`cashflow_dates (range<number>)`,E(`An range with dates corresponding to the cash flows in cashflow_amounts.`)),U(`rate_guess (number, default=${Mv})`,E(`An estimate for what the internal rate of return will be.`))],compute:function(e,t,n={value:Mv}){let r=M(n,this.locale);if(!vu(e,t))return new A(Vg);let i=e.flat().map(e=>M(e,this.locale)),a=t.flat().map(e=>M(e,this.locale));if(!L_(i))return new A(Hg);if(a.some(e=>e<a[0]))return new A(e_(a[0]));if(r<=-1)return new A(w_(r));let o=new Map;for(let e of S(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e));return U_(e=>{let t=c[0];for(let n of S(1,c.length)){let r=(s[0]-s[n])/365;t+=c[n]*(1+e)**r}return t},e=>{let t=0;for(let n of S(1,c.length)){let r=(s[0]-s[n])/365;t+=r*c[n]*(1+e)**(r-1)}return t},r,40,1e-5,e=>e?e/10-.9:-.9)},isExported:!0},Wv={description:E(`Net present value given to non-periodic cash flows..`),args:[U(`discount (number)`,E(`The discount rate of the investment over one period.`)),U(`cashflow_amounts (number, range<number>)`,E(`An range containing the income or payments associated with the investment.`)),U(`cashflow_dates (number, range<number>)`,E(`An range with dates corresponding to the cash flows in cashflow_amounts.`))],compute:function(e,t,n){let r=M(e,this.locale);if(!vu(t,n))return new A(Vg);let i=I(t).flat().map(e=>ea(e,this.locale)),a=I(n).flat().map(e=>ea(e,this.locale));if(a.some(e=>e<a[0]))return new A(e_(a[0]));if(r<=0)return new A(E_(r));if(i.length===1)return i[0];let o=new Map;for(let e of S(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e)),l=c[0];for(let e of S(1,c.length)){let t=(s[0]-s[e])/365;l+=c[e]*(1+r)**t}return l},isExported:!0},Gv={description:E(`Annual yield of a security paying periodic interest.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`rate (number)`,E(`The annualized rate of interest.`)),U(`price (number)`,E(`The price at which the security is bought per 100 face value.`)),U(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),U(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(M(e,this.locale)),c=Math.trunc(M(t,this.locale)),l=M(n,this.locale),u=M(r,this.locale),d=M(i,this.locale),f=Math.trunc(M(a,this.locale)),p=Math.trunc(M(o,this.locale));if(s>=c)return new A(l_(s,c));if(z_(f))return new A(Gg(f));if(R_(p))return new A(Kg(p));if(l<0)return new A(T_(l));if(u<=0)return new A(x_(u));if(d<=0)return new A(D_(d));let m=xi(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=100*l/f;if(h===1){let e=u+_*(1-g);return(d+_-e)*f*(1/g)/e}function v(e,t,n,r,i,a){let o=a-(e+i*(1-t))*r**(n-1+t);for(let e=1;e<=n;e++)o+=i*r**(e-1);return o}function y(e,t,n,r,i){let a=-(e+i*(1-t))*(n-1+t)*r**(n-2+t);for(let e=1;e<=n;e++)a+=i*(e-1)*r**(e-2);return a}function ee(e){return v(u,g,h,e,_,d)}function te(e){return y(u,g,h,e,_)}return(U_(ee,te,1+(l+1)/f,100,1e-5)-1)*f},isExported:!0},Kv={description:E(`Annual yield of a discount security.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`price (number)`,E(`The price at which the security is bought per 100 face value.`)),U(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(n,this.locale),c=M(r,this.locale),l=Math.trunc(M(i,this.locale));if(a>=o)return new A(l_(a,o));if(R_(l))return new A(Kg(l));if(s<=0)return new A(x_(s));if(c<=0)return new A(D_(c));let u=xi(a,o,l);return(c/s-1)/u},isExported:!0},qv={description:E(`Annual yield of a security paying interest at maturity.`),args:[U(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`issue (date)`,E(`The date the security was initially issued.`)),U(`rate (number)`,E(`The annualized rate of interest.`)),U(`price (number)`,E(`The price at which the security is bought.`)),U(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(M(e,this.locale)),s=Math.trunc(M(t,this.locale)),c=Math.trunc(M(n,this.locale)),l=M(r,this.locale),u=M(i,this.locale),d=Math.trunc(M(a,this.locale));if(o>=s)return new A(l_(o,s));if(R_(d))return new A(Kg(d));if(o<c)return new A(A_(o,c));if(l<0)return new A(T_(l));if(u<=0)return new A(x_(u));let f=xi(c,s,d),p=xi(c,o,d),m=xi(o,s,d);return(100*(1+l*f)/(u+100*l*p)-1)/m},isExported:!0},Jv=(e,t=()=>!0)=>[{goTo:e,guard:t}],Yv=(e,t=()=>!0)=>({goTo:e,guard:t}),Xv={0:{REFERENCE:Jv(2),NUMBER:Jv(4),SYMBOL:[Yv(3,e=>pc(e.value)),Yv(4,e=>mc(e.value))]},3:{SPACE:Jv(3),OPERATOR:Jv(5,e=>e.value===`:`)},4:{SPACE:Jv(4),OPERATOR:Jv(6,e=>e.value===`:`)},2:{SPACE:Jv(2),OPERATOR:Jv(1,e=>e.value===`:`)},1:{SPACE:Jv(1),NUMBER:Jv(7),REFERENCE:Jv(7,e=>_c(e.value)),SYMBOL:Jv(7,e=>hc(e.value)||gc(e.value))},5:{SPACE:Jv(5),SYMBOL:Jv(7,e=>hc(e.value)),REFERENCE:Jv(7,e=>_c(e.value))},6:{SPACE:Jv(6),NUMBER:Jv(7),REFERENCE:Jv(7,e=>_c(e.value)),SYMBOL:Jv(7,e=>gc(e.value))},7:{}};function Zv(e){let t=0,n=Xv[0],r=``;for(;n!==void 0;){let i=e[t++];if(!i)return null;let a=n[i.type]?.find(e=>e.guard(i)),o=a?a.goTo:void 0;switch(o){case void 0:return null;case 7:return r+=i.value,e.splice(0,t),{type:`REFERENCE`,value:r};default:n=Xv[o],r+=i.value;break}}return null}function Qv(e,t=D){let n=jl(e,t),r=[];for(;n.length;)r.push(Zv(n)||n.shift());return r}let $v=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,ey=[`-`,`+`],ty=[`%`],ny=[`*`,`+`,`&`];var ry=class{tokens;currentIndex=0;current;length;constructor(e){this.tokens=e,this.current=e[0],this.length=e.length}shift(){let e=this.tokens[this.currentIndex];return this.current=this.tokens[++this.currentIndex],e}get next(){return this.tokens[this.currentIndex+1]}};let iy={"^":30,"%":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function ay(e){let t=e.shift();if(!t)throw new zi;switch(t.type){case`DEBUGGER`:let n=ly(e,1e3);return n.debug=!0,n;case`NUMBER`:return{type:`NUMBER`,value:Ii(t.value,D),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`STRING`:return{type:`STRING`,value:it(t.value),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`INVALID_REFERENCE`:return{type:`REFERENCE`,value:k.InvalidReference,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`REFERENCE`:if(e.current?.value===`:`&&e.next?.type===`REFERENCE`){e.shift();let n=e.shift();return{type:`REFERENCE`,value:`${t.value}:${n?.value}`,tokenStartIndex:t.tokenIndex,tokenEndIndex:n.tokenIndex}}return{type:`REFERENCE`,value:t.value,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`SYMBOL`:let r=t.value;if(e.current?.type===`LEFT_PAREN`&&$v.test(t.value)&&r===lt(r,`'`)){let{args:n,rightParen:i}=oy(e);return{type:`FUNCALL`,value:r,args:n,tokenStartIndex:t.tokenIndex,tokenEndIndex:i.tokenIndex}}let i=r.toUpperCase();return i===`TRUE`||i===`FALSE`?{type:`BOOLEAN`,value:i===`TRUE`,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:{type:`SYMBOL`,value:lt(t.value,`'`),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`LEFT_PAREN`:let a=ly(e),o=cy(e,`RIGHT_PAREN`,E(`Missing closing parenthesis`));return{...a,tokenStartIndex:t.tokenIndex,tokenEndIndex:o.tokenIndex};case`OPERATOR`:let s=t.value;if(ey.includes(s)){let n=ly(e,iy[s]);return{type:`UNARY_OPERATION`,value:s,operand:n,tokenStartIndex:t.tokenIndex,tokenEndIndex:n.tokenEndIndex}}throw new zi(E(`Unexpected token: %s`,t.value));default:throw new zi(E(`Unexpected token: %s`,t.value))}}function oy(e){if(cy(e,`LEFT_PAREN`,E(`Missing opening parenthesis`)),e.current?.type===`RIGHT_PAREN`)return{args:[],rightParen:cy(e,`RIGHT_PAREN`)};let t=[];for(t.push(sy(e));e.current?.type!==`RIGHT_PAREN`;)cy(e,`ARG_SEPARATOR`,E(`Wrong function call`)),t.push(sy(e));return{args:t,rightParen:cy(e,`RIGHT_PAREN`)}}function sy(e){let t=e.current;return t?.type===`ARG_SEPARATOR`||t?.type===`RIGHT_PAREN`?{type:`EMPTY`,value:``,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:ly(e)}function cy(e,t,n){let r=e.shift();if(!r||r.type!==t)throw new zi(n);return r}function ly(e,t=0){if(e.length===0)throw new zi;let n=ay(e);for(;e.current?.type===`OPERATOR`&&iy[e.current.value]>t;){let t=e.shift(),r=t.value;if(ty.includes(r))n={type:`UNARY_OPERATION`,value:r,operand:n,postfix:!0,tokenStartIndex:n.tokenStartIndex,tokenEndIndex:t.tokenIndex};else{let t=ly(e,iy[r]);n={type:`BIN_OPERATION`,value:r,left:n,right:t,tokenStartIndex:n.tokenStartIndex,tokenEndIndex:t.tokenEndIndex}}}return n}function uy(e){return dy(Qv(e))}function dy(e){let t=new ry(e.map((e,t)=>({type:e.type,value:e.value,tokenIndex:t})).filter(e=>e.type!==`SPACE`));t.current?.value===`=`&&t.shift();let n=ly(t);if(t.current)throw new zi;return n}function fy(e,t,n){return hy(e,e=>e.type===t?n(e):e)}function py(e){return Array.from(my(e))}function*my(e){switch(yield e,e.type){case`FUNCALL`:for(let t of e.args)yield*my(t);break;case`UNARY_OPERATION`:yield*my(e.operand);break;case`BIN_OPERATION`:yield*my(e.left),yield*my(e.right);break}}function hy(e,t){switch(e=t(e),e.type){case`FUNCALL`:return{...e,args:e.args.map(e=>hy(e,t))};case`UNARY_OPERATION`:return{...e,operand:hy(e.operand,t)};case`BIN_OPERATION`:return{...e,right:hy(e.right,t),left:hy(e.left,t)};default:return e}}function gy(e){switch(e.type){case`FUNCALL`:let t=e.args.map(e=>gy(e));return`${e.value}(${t.join(`,`)})`;case`NUMBER`:return e.value.toString();case`REFERENCE`:return e.value;case`STRING`:return`"${e.value}"`;case`BOOLEAN`:return e.value?`TRUE`:`FALSE`;case`UNARY_OPERATION`:return e.postfix?_y(e)+e.value:e.value+vy(e);case`BIN_OPERATION`:return _y(e)+e.value+vy(e);default:return e.value}}function _y(e){let t=e.value,n=`left`in e?e.left:e.operand,r=n.value;return n.type===`BIN_OPERATION`&&iy[r]<iy[t]?`(${gy(n)})`:gy(n)}function vy(e){let t=e.value,n=`right`in e?e.right:e.operand,r=iy[n.value],i=iy[t],a=!1;return n.type===`BIN_OPERATION`?(r<i||r===i&&!ny.includes(t))&&(a=!0):a=!1,a?`(${gy(n)})`:gy(n)}function yy(e){let t=0;return e.map(e=>{let n=e.value.toString().length,r=Object.assign({},e,{start:t,end:t+n,length:n});return t=r.end,r})}function by(e){let t=[],n=0;return e.map((r,i)=>{if(r.type===`LEFT_PAREN`){t.push(n+1),n=0;for(let n=i-1;n>=0;n--){if(e[n].type===`SPACE`){e[n].parenthesesCode=t.join(`:`);continue}e[n].type===`SYMBOL`&&(e[n].parenthesesCode=t.join(`:`));break}}return r.parenthesesCode=t.join(`:`),r.type===`RIGHT_PAREN`&&t.length&&(n=t.pop()),r})}function xy(e){let t=[],n=``;function r(e){if(t.length===0)return;let n=t.at(-1);if(n&&n.argsTokens){let{argsTokens:t,argPosition:r}=n;t[r]||(t[r]=[]),t[r].push({value:e.value,type:e.type})}}return e.map((e,i)=>{switch([`SPACE`,`LEFT_PAREN`].includes(e.type)||(n=``),e.type){case`SYMBOL`:r(e),n=e.value;break;case`LEFT_PAREN`:t.push({parent:n,argPosition:0,argsTokens:[],args:[]}),r(e),n=``;break;case`RIGHT_PAREN`:t.pop()?.argsTokens?.flat().forEach(r),r(e);break;case`ARG_SEPARATOR`:t.length&&t[t.length-1].argPosition++,r(e);break;default:r(e);break}if(t.length){let n=t[t.length-1];n.parent&&(e.functionContext=Object.assign({},n))}return e})}function Sy(e){for(let t of e)if(t.functionContext){let{argsTokens:e,args:n}=t.functionContext;if(delete t.functionContext.argsTokens,n.length||!e)continue;e[0]?.[0]?.type===`LEFT_PAREN`&&(e[0]=e[0].slice(1));for(let t of e){let e=t;e.at(0)?.type===`ARG_SEPARATOR`&&(e=e.slice(1));try{n.push(dy(e))}catch{n.push(void 0)}}}return e}function Cy(e,t){return Sy(xy(by(yy(Qv(e,t)))))}function wy(e){if(e.type!==`REFERENCE`)return e;let{xc:t,sheetName:n}=vc(e.value),[r,i]=t.split(`:`),a=Ty(r),o=i?`:${Ty(i)}`:``;return{...e,value:yc(n,a+o)}}function Ty(e){switch(Oy(e)){case`none`:e=Ey(e,`colrow`);break;case`colrow`:e=Ey(e,`row`);break;case`row`:e=Ey(e,`col`);break;case`col`:e=Ey(e,`none`);break}return e}function Ey(e,t){let n;({sheetName:n,xc:e}=vc(e)),n=n?ut(n)+`!`:``,e=e.replace(/\$/g,``);let r=e.indexOf(`:`);return r>=0?`${n}${Dy(e.slice(0,r),t)}:${Dy(e.slice(r+1),t)}`:n+Dy(e,t)}function Dy(e,t){let n=e.search(/[0-9]/),r=n!==0,i=n>=0;switch(t){case`col`:return r?`$`+e:e;case`row`:return i?e.slice(0,n)+`$`+e.slice(n):e;case`colrow`:return!i||!r?`$`+e:`$`+e.slice(0,n)+`$`+e.slice(n);case`none`:return e}}function Oy(e){return jy(e)?`colrow`:ky(e)?`col`:Ay(e)?`row`:`none`}function ky(e){return e.startsWith(`$`)}function Ay(e){return e.includes(`$`,1)}function jy(e){return e.startsWith(`$`)&&e.length>1&&e.slice(1).includes(`$`)}function My(e,t,n){let r=(t.startsWith(`=`)?Cy(t,n):[]).filter(t=>t.start<=e.start&&t.end>=e.start||t.start>=e.start&&t.start<e.end),i=r.filter(e=>e.type===`REFERENCE`);if(i.length===0)return;let a=r.map(wy).map(e=>e.value).join(``),o=r[0].start,s=r[r.length-1].end,c=t.slice(0,o)+a+t.slice(s),l=c.length-t.length,u={start:i[0].start,end:i[i.length-1].end+l};return i.length===1&&e.start===e.end&&(u.start=u.end),{content:c,selection:u}}var Ny=l({CELL:()=>Fy,ISBLANK:()=>Uy,ISERR:()=>Iy,ISERROR:()=>Ly,ISLOGICAL:()=>Ry,ISNA:()=>zy,ISNONTEXT:()=>By,ISNUMBER:()=>Vy,ISTEXT:()=>Hy,NA:()=>Wy});let Py=[`address`,`col`,`contents`,`format`,`row`,`type`],Fy={description:E(`Gets information about a cell.`),args:[U(`info_type (string)`,E(`The type of information requested. Can be one of %s`,Py.join(`, `))),U(`reference (meta)`,E(`The reference to the cell.`))],compute:function(e,t){let n=N(e).toLowerCase();if(!Py.includes(n))return new A(E(`The info_type should be one of %s.`,Py.join(`, `)));let r=this.__originSheetId,i=N(t),{sheetName:a,xc:o}=vc(i.includes(`:`)?i.split(`:`)[0]:i);a=a===this.getters.getSheetName(r)?void 0:a;let s=yc(a,Ey(o,`colrow`)),c=this.getters.getRangeFromSheetXC(r,s);switch(n){case`address`:return this.getters.getRangeString(c,r);case`col`:return c.zone.left+1;case`contents`:{let e={sheetId:c.sheetId,col:c.zone.left,row:c.zone.top};return this.getters.getEvaluatedCell(e).value}case`format`:{let e={sheetId:c.sheetId,col:c.zone.left,row:c.zone.top};return this.getters.getEvaluatedCell(e).format||``}case`row`:return c.zone.top+1;case`type`:{let e={sheetId:c.sheetId,col:c.zone.left,row:c.zone.top},t=this.getters.getEvaluatedCell(e).type;return t===`empty`?`b`:t===`text`?`l`:`v`}}return``},isExported:!0},Iy={description:E(`Whether a value is an error other than #N/A.`),args:[U(`value (any)`,E(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return j(t)&&t!==k.NotAvailable},isExported:!0},Ly={description:E(`Whether a value is an error.`),args:[U(`value (any)`,E(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return j(t)},isExported:!0},Ry={description:E("Whether a value is `true` or `false`."),args:[U(`value (any)`,E(`The value to be verified as a logical TRUE or FALSE.`))],compute:function(e){return typeof e?.value==`boolean`},isExported:!0},zy={description:E(`Whether a value is the error #N/A.`),args:[U(`value (any)`,E(`The value to be verified as an error type.`))],compute:function(e){return e?.value===k.NotAvailable},isExported:!0},By={description:E(`Whether a value is non-textual.`),args:[U(`value (any)`,E(`The value to be checked.`))],compute:function(e){return!Hy.compute.bind(this)(e)},isExported:!0},Vy={description:E(`Whether a value is a number.`),args:[U(`value (any)`,E(`The value to be verified as a number.`))],compute:function(e){return typeof e?.value==`number`},isExported:!0},Hy={description:E(`Whether a value is text.`),args:[U(`value (any)`,E(`The value to be verified as text.`))],compute:function(e){return typeof e?.value==`string`&&j(e?.value)===!1},isExported:!0},Uy={description:E(`Whether the referenced cell is empty`),args:[U(`value (any)`,E(`Reference to the cell that will be checked for emptiness.`))],compute:function(e){return e?.value===null},isExported:!0},Wy={description:E(`Returns the error value #N/A.`),args:[],compute:function(){return{value:k.NotAvailable}},isExported:!0};var Gy=l({AND:()=>Ky,FALSE:()=>qy,IF:()=>Jy,IFERROR:()=>Yy,IFNA:()=>Xy,IFS:()=>Zy,NOT:()=>Qy,OR:()=>$y,SWITCH:()=>eb,TRUE:()=>tb,XOR:()=>nb});let Ky={description:E("Logical `and` operator."),args:[U(`logical_expression1 (boolean, range<boolean>)`,E(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.`)),U(`logical_expression2 (boolean, range<boolean>, repeating)`,E(`More expressions that represent logical values.`))],compute:function(...e){let{result:t,foundBoolean:n}=du(e);return n?t:new A(Ma)},isExported:!0},qy={description:E("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},Jy={description:E(`Returns value depending on logical expression.`),args:[U(`logical_expression (boolean, range<boolean>)`,E(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.`)),U(`value_if_true (any, range)`,E(`The value the function returns if logical_expression is TRUE.`)),U(`value_if_false (any, range, default=FALSE)`,E(`The value the function returns if logical_expression is FALSE.`))],compute:function(e,t,n){return Du(e)?va(Jy.compute,[e,t,n]):(P(Tu(e))?t:n)??{value:0}},isExported:!0},Yy={description:E(`Value if it is not an error, otherwise 2nd argument.`),args:[U(`value (any, range)`,E(`The value to return if value itself is not an error.`)),U(`value_if_error (any, range, default="empty")`,E(`The value the function returns if value is an error.`))],compute:function(e,t){return Du(e)?va(Yy.compute,[e,t]):(j(Tu(e)?.value)?t:e)??{value:0}},isExported:!0},Xy={description:E(`Value if it is not an #N/A error, otherwise 2nd argument.`),args:[U(`value (any, range)`,E(`The value to return if value itself is not #N/A an error.`)),U(`value_if_error (any, range, default="empty")`,E(`The value the function returns if value is an #N/A error.`))],compute:function(e,t){return Du(e)?va(Xy.compute,[e,t]):(Tu(e)?.value===k.NotAvailable?t:e)??{value:0}},isExported:!0},Zy={description:E(`Returns a value depending on multiple logical expressions.`),args:[U(`condition1 (boolean, range<boolean>)`,E(`The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.`)),U(`value1 (any, range)`,E(`The returned value if condition1 is TRUE.`)),U(`condition2 (boolean, any, range, repeating)`,E(`Additional conditions to be evaluated if the previous ones are FALSE.`)),U(`value2 (any, range, repeating)`,E(`Additional values to be returned if their corresponding conditions are TRUE.`))],compute:function(...e){if(e.length%2!=0)return new A(E(`Wrong number of arguments. Expected an even number of arguments.`));for(;e.length>0;){if(Du(e[0]))return va(Zy.compute,e);let t=P(Tu(e.shift())),n=e.shift();if(t)return n??{value:0}}return new A(E(`No match.`))},isExported:!0},Qy={description:E(`Returns opposite of provided logical value.`),args:[U(`logical_expression (boolean)`,E(`An expression or reference to a cell holding an expression that represents some logical value.`))],compute:function(e){return!P(e)},isExported:!0},$y={description:E("Logical `or` operator."),args:[U(`logical_expression1 (boolean, range<boolean>)`,E(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.`)),U(`logical_expression2 (boolean, range<boolean>, repeating)`,E(`More expressions that evaluate to logical values.`))],compute:function(...e){let{result:t,foundBoolean:n}=fu(e);return n?t:new A(Ma)},isExported:!0},eb={description:E(`Returns a value by comparing cases to an expression.`),args:[U(`expression (number, boolean, string)`,E(`The value to be checked.`)),U(`case1 (number, boolean, string)`,E(`The first case to be checked against expression.`)),U(`value1 (any)`,E(`The corresponding value to be returned if case1 matches expression.`)),U(`case2 (any, repeating)`,E(`Additional cases to try if the previous ones don't match expression.`)),U(`value2 (any, repeating)`,E(`Additional values to be returned if their corresponding cases match expression.`)),U(`default (any, default="empty")`,E(`An optional default value to be returned if none of the cases match expression.`))],compute:function(e,...t){let n=t.length%2==0?Ji(e):t.pop();for(let n=0;n<t.length;n+=2){let r=t[n];if(r&&j(r.value))return r;if(e?.value===r?.value)return t[n+1]||{value:0}}return n||{value:0}},isExported:!0},tb={description:E("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},nb={description:E("Logical `xor` operator."),args:[U(`logical_expression1 (boolean, range<boolean>)`,E(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.`)),U(`logical_expression2 (boolean, range<boolean>, repeating)`,E(`More expressions that evaluate to logical values.`))],compute:function(...e){let t=!1,n=!1;return ba(e,e=>(t=!0,n=n?!e:e,!0)),t?n:new A(Ma)},isExported:!0};function rb(e,t){let n=t.getPivotId(e);if(!n)throw new A(E(`There is no pivot with id "%s"`,e));return n}function ib(e,t,n){let{measures:r}=n.getPivotCoreDefinition(e);if(!r.find(e=>e.id===t))throw new A(E(`The argument %s is not a valid measure. Here are the measures: %s`,t,`(${r.map(e=>e.id).join(`, `)})`))}function ab(e){if(e.length%2!=0)throw new A(E(`Function PIVOT takes an even number of arguments.`))}function ob(e,t,n){let r=[],i=e.getters.getPivotCoreDefinition(t);if(i.type===`SPREADSHEET`&&i.dataSet){let{sheetId:t,zone:n}=i.dataSet,a=vs(n),o=e.getters.getRangeFromSheetXC(t,a);if(o===void 0||o.invalidXc||o.invalidSheetName)throw new Vi;if(e.__originCellPosition&&o.sheetId===e.__originSheetId&&As(z(e.__originCellPosition),n))throw new Bi;r.push(o)}for(let i of n)i.computedBy&&r.push(...e.getters.getMeasureFullDependencies(t,i));let a=e.__originCellPosition;a&&r.length&&(e.updateDependencies?.(a),e.addDependencies?.(a,r))}var sb=l({ADDRESS:()=>cb,COLUMN:()=>lb,COLUMNS:()=>ub,HLOOKUP:()=>db,INDEX:()=>fb,INDIRECT:()=>pb,LOOKUP:()=>mb,MATCH:()=>hb,OFFSET:()=>wb,PIVOT:()=>Cb,PIVOT_HEADER:()=>Sb,PIVOT_VALUE:()=>xb,ROW:()=>gb,ROWS:()=>_b,VLOOKUP:()=>vb,XLOOKUP:()=>bb});let cb={description:E(`Returns a cell reference as a string. `),args:[U(`row (number)`,E(`The row number of the cell reference. `)),U(`column (number)`,E(`The column number (not name) of the cell reference. A is column number 1. `)),U(`absolute_relative_mode (number, default=1)`,E(`An indicator of whether the reference is row/column absolute. 1 is row and column absolute (e.g. $A$1), 2 is row absolute and column relative (e.g. A$1), 3 is row relative and column absolute (e.g. $A1), and 4 is row and column relative (e.g. A1).`)),U(`use_a1_notation (boolean, default=TRUE)`,E(`A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).`)),U(`sheet (string, optional)`,E(`A string indicating the name of the sheet into which the address points.`))],compute:function(e,t,n={value:1},r={value:!0},i){let a=na(e,this.locale),o=na(t,this.locale);if(a<1)return new A(bu(a));if(o<1)return new A(bu(o));let s=na(n,this.locale);if(![1,2,3,4].includes(s))return new A(Xi(1,4,s));let c=P(r),l;if(c){let e={rowFixed:[1,2].includes(s),colFixed:[1,3].includes(s)};l=T(o-1,a-1,e)}else l=([1,2].includes(s)?`R${a}`:`R[${a}]`)+([1,3].includes(s)?`C${o}`:`C[${o}]`);return i===void 0?l:yc(N(i),l)},isExported:!0},lb={description:E(`Column number of a specified cell.`),args:[U(`cell_reference (meta, default='this cell')`,E(`The cell whose column number will be returned. Column A corresponds to 1. By default, the function use the cell in which the formula is entered.`))],compute:function(e){if(j(e?.value))return e;if(e===void 0)return this.__originCellPosition?.col===void 0?new A(E(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.col+1;let t=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),e.value).zone;return t.left===t.right?t.left+1:ma(t.right-t.left+1,1,(e,n)=>({value:t.left+e+1}))},isExported:!0},ub={description:E(`Number of columns in a specified array or range.`),args:[U(`range (meta)`,E(`The range whose column count will be returned.`))],compute:function(e){if(j(e?.value))return e;let t=ps(e.value);return t.right-t.left+1},isExported:!0},db={description:E(`Horizontal lookup`),args:[U(`search_key (string, number, boolean)`,E(`The value to search for. For example, 42, 'Cats', or I24.`)),U(`range (any, range)`,E(`The range to consider for the search. The first row in the range is searched for the key specified in search_key.`)),U(`index (number)`,E(`The row index of the value to be returned, where the first row in range is numbered 1.`)),U(`is_sorted (boolean, default=true)`,E(`Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned.`))],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(M(n?.value,this.locale)),a=I(t);if(1>i||i>a[0].length)return new A(E(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[t][0].value,s=a[P(r.value)?Ta(a,e,`nextSmaller`,`asc`,a.length,o):Ea(a,e,`wildcard`,a.length,o,this.lookupCaches)];return s===void 0?Ji(e):s[i-1]},isExported:!0},fb={description:E(`Returns the content of a cell, specified by row and column offset.`),args:[U(`reference (any, range)`,E(`The range of cells from which the values are returned.`)),U(`row (number, default=0)`,E(`The index of the row to be returned from within the reference range of cells.`)),U(`column (number, default=0)`,E(`The index of the column to be returned from within the reference range of cells.`))],compute:function(e,t={value:0},n={value:0}){let r=I(e),i=M(t.value,this.locale),a=M(n.value,this.locale);return a<0||a-1>=r.length||i<0||i-1>=r[0].length?new A(E(`Index out of range.`)):i===0&&a===0?r:i===0?[r[a-1]]:a===0?r.map(e=>[e[i-1]]):r[a-1][i-1]},isExported:!0},pb={description:E(`Returns the content of a cell, specified by a string.`),args:[U(`reference (string)`,E(`The range of cells from which the values are returned.`)),U(`use_a1_notation (boolean, default=TRUE)`,E(`A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).`))],compute:function(e,t={value:!0}){let n=e?.value?.toString();if(!n)return new Vi(E(`Reference should be defined.`));if(!P(t))return new A(E(`R1C1 notation is not supported.`));let r=this.__originSheetId,i=this.__originCellPosition;i&&this.updateDependencies?.(i);let a=this.getters.getRangeFromSheetXC(r,n);if(a===void 0||a.invalidXc||a.invalidSheetName)return new Vi;i&&this.addDependencies?.(i,[a]);let o=[];for(let e=a.zone.left;e<=a.zone.right;e++){let t=[];for(let n=a.zone.top;n<=a.zone.bottom;n++){let r={sheetId:a.sheetId,col:e,row:n};t.push(this.getters.getEvaluatedCell(r))}o.push(t)}return o.length===1&&o[0].length===1?o[0][0]:o},isExported:!0},mb={description:E(`Look up a value.`),args:[U(`search_key (string, number, boolean)`,E(`The value to search for. For example, 42, 'Cats', or I24.`)),U(`search_array (any, range)`,E(`One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.`)),U(`result_range (any, range, optional)`,E(`The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method.`))],compute:function(e,t,n){let r=I(t),i=I(n),a=r.length,o=r[0].length,s=o>=a,c=Ta(r,e,`nextSmaller`,`asc`,s?o:a,s?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value);return c===-1||s&&r[0][c]===void 0||!s&&r[c][o-1]===void 0?Ji(e):i[0].length===0?s?r[a-1][c]:r[c][o-1]:(a=i.length,o=i[0].length,a!==1&&o!==1?new A(E(`The result_range must be a single row or a single column.`)):a>1?c>a-1?new A(E(`[[FUNCTION_NAME]] evaluates to an out of range row value %s.`,c+1)):i[c][0]:c>o-1?new A(E(`[[FUNCTION_NAME]] evaluates to an out of range column value %s.`,c+1)):i[0][c])},isExported:!0},hb={description:E(`Position of item in range that matches value.`),args:[U(`search_key (string, number, boolean)`,E(`The value to search for. For example, 42, 'Cats', or I24.`)),U(`range (any, range)`,E(`The one-dimensional array to be searched.`)),U(`search_type (number, default=1)`,E(`The search method. 1 (default) finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order.`))],compute:function(e,t,n={value:1}){let r=M(n,this.locale),i=I(t),a=i.length,o=i[0].length;if(a!==1&&o!==1)return new A(E(`The range must be a single row or a single column.`));let s=-1,c=a===1?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,l=a===1?i[0].length:i.length;switch(r=Math.sign(r),r){case 1:s=Ta(i,e,`nextSmaller`,`asc`,l,c);break;case 0:s=Ea(i,e,`wildcard`,l,c,this.lookupCaches);break;case-1:s=Ta(i,e,`nextGreater`,`desc`,l,c);break}return a===1&&i[0][s]===void 0||a!==1&&i[s]===void 0?Ji(e):s+1},isExported:!0},gb={description:E(`Row number of a specified cell.`),args:[U(`cell_reference (meta, default='this cell')`,E(`The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered.`))],compute:function(e){if(j(e?.value))return e;if(e===void 0)return this.__originCellPosition?.row===void 0?new A(E(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.row+1;let t=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),e.value).zone;return t.top===t.bottom?t.top+1:ma(1,t.bottom-t.top+1,(e,n)=>({value:t.top+n+1}))},isExported:!0},_b={description:E(`Number of rows in a specified array or range.`),args:[U(`range (meta)`,E(`The range whose row count will be returned.`))],compute:function(e){if(j(e?.value))return e;let t=ps(e.value);return t.bottom-t.top+1},isExported:!0},vb={description:E(`Vertical lookup.`),args:[U(`search_key (string, number, boolean)`,E(`The value to search for. For example, 42, 'Cats', or I24.`)),U(`range (any, range)`,E(`The range to consider for the search. The first column in the range is searched for the key specified in search_key.`)),U(`index (number)`,E(`The column index of the value to be returned, where the first column in range is numbered 1.`)),U(`is_sorted (boolean, default=true)`,E(`Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned.`))],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(M(n?.value,this.locale)),a=I(t);if(1>i||i>a.length)return new A(E(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[0][t].value,s=P(r.value)?Ta(a,e,`nextSmaller`,`asc`,a[0].length,o):Ea(a,e,`wildcard`,a[0].length,o,this.lookupCaches),c=a[i-1][s];return c===void 0?Ji(e):c},isExported:!0},yb={0:`strict`,1:`nextGreater`,"-1":`nextSmaller`,2:`wildcard`},bb={description:E(`Search a range for a match and return the corresponding item from a second range.`),args:[U(`search_key (string,number,boolean)`,E(`The value to search for.`)),U(`lookup_range (any, range)`,E(`The range to consider for the search. Should be a single column or a single row.`)),U(`return_range (any, range)`,E(`The range containing the return value. Should have the same dimensions as lookup_range.`)),U(`if_not_found (any, optional)`,E(`If a valid match is not found, return this value.`)),U(`match_mode (any, default=0)`,E(`(0) Exact match. (-1) Return next smaller item if no match. (1) Return next greater item if no match. (2) Wildcard match.`)),U(`search_mode (any, default=1)`,E(`(1) Search starting at first item. (-1) Search starting at last item. (2) Perform a binary search that relies on lookup_array being sorted in ascending order. If not sorted, invalid results will be returned. (-2) Perform a binary search that relies on lookup_array being sorted in descending order. If not sorted, invalid results will be returned. `))],compute:function(e,t,n,r,i={value:0},a={value:1}){let o=Math.trunc(M(i.value,this.locale)),s=Math.trunc(M(a.value,this.locale)),c=I(t),l=I(n);if(c.length!==1&&c[0].length!==1)return new A(E(`lookup_range should be either a single row or single column.`));if(![1,-1,2,-2].includes(s))return new A(E(`search_mode should be a value in [-1, 1, -2, 2].`));if(![-1,0,1,2].includes(o))return new A(E(`match_mode should be a value in [-1, 0, 1, 2].`));let u=c.length===1?`col`:`row`;if(o===2&&[-2,2].includes(s))return new A(E(`The search and match mode combination is not supported for XLOOKUP evaluation.`));if(u===`col`?l[0].length!==c[0].length:l.length!==c.length)return new A(E(`return_range should have the same dimensions as lookup_range.`));let d=u===`col`?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,f=u===`col`?c[0].length:c.length,p=yb[o],m=s===-1,h=s===2||s===-2?Ta(c,e,p,s===2?`asc`:`desc`,f,d):Ea(c,e,p,f,d,this.lookupCaches,m);return h===-1?r===void 0?Ji(e):[[r]]:u===`col`?l.map(e=>[e[h]]):[l[h]]},isExported:!0},xb={description:E(`Get the value from a pivot.`),args:[U(`pivot_id (number,string)`,E(`ID of the pivot.`)),U(`measure_name (string)`,E(`Name of the measure.`)),U(`domain_field_name (string,repeating)`,E(`Field name.`)),U(`domain_value (number,string,boolean,repeating)`,E(`Value.`))],compute:function(e,t,...n){let r=N(e),i=N(t),a=rb(r,this.getters);ib(a,i,this.getters),ab(n);let o=this.getters.getPivot(a),s=this.getters.getPivotCoreDefinition(a);ob(this,a,s.measures.filter(e=>e.id===i)),o.init({reload:o.needsReevaluation});let c=o.assertIsValid({throwOnError:!1});if(c)return c;if(!o.areDomainArgsFieldsValid(n)){let e=E(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${r})`);return{value:k.GenericError,message:E(`Dimensions don't match the pivot definition`)+`. `+e}}let l=o.parseArgsToPivotDomain(n);return this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(a)?.trackValue(i,l),o.getPivotCellValueAndFormat(i,l)}},Sb={description:E(`Get the header of a pivot.`),args:[U(`pivot_id (number,string)`,E(`ID of the pivot.`)),U(`domain_field_name (string,repeating)`,E(`Field name.`)),U(`domain_value (number,string,value,repeating)`,E(`Value.`))],compute:function(e,...t){let n=N(e),r=rb(n,this.getters);ab(t);let i=this.getters.getPivot(r);ob(this,r,[]),i.init({reload:i.needsReevaluation});let a=i.assertIsValid({throwOnError:!1});if(a)return a;if(!i.areDomainArgsFieldsValid(t)){let e=E(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${n})`);return{value:k.GenericError,message:E(`Dimensions don't match the pivot definition`)+`. `+e}}let o=i.parseArgsToPivotDomain(t);this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(r)?.trackHeader(o);let s=o.at(-1);if(s?.field===`measure`)return i.getPivotMeasureValue(N(s.value),o);let{value:c,format:l}=i.getPivotHeaderValueAndFormat(o);return{value:c,format:!s||s.field===`measure`||s.value===`false`?void 0:l}}},Cb={description:E(`Get a pivot table.`),args:[U(`pivot_id (string)`,E(`ID of the pivot.`)),U(`row_count (number, optional)`,E(`number of rows`)),U(`include_total (boolean, default=TRUE)`,E(`Whether to include total/sub-totals or not.`)),U(`include_column_titles (boolean, default=TRUE)`,E(`Whether to include the column titles or not.`)),U(`column_count (number, optional)`,E(`number of columns`)),U(`include_measure_titles (boolean, default=TRUE)`,E(`Whether to include the measure titles row or not.`))],compute:function(e,t={value:1e4},n={value:!0},r={value:!0},i={value:Number.MAX_VALUE},a={value:!0}){let o=N(e),s=M(t,this.locale);if(s<0)return new A(E(`The number of rows must be positive.`));let c=M(i,this.locale);if(c<0)return new A(E(`The number of columns must be positive.`));let l={displayColumnHeaders:P(r),displayTotals:P(n),displayMeasuresRow:P(a)},u=rb(o,this.getters),d=this.getters.getPivot(u),f=this.getters.getPivotCoreDefinition(u);ob(this,u,f.measures),d.init({reload:d.needsReevaluation});let p=d.assertIsValid({throwOnError:!1});if(p)return p;let m=d.getCollapsedTableStructure(),h=m.getPivotCells(l),g=0;l.displayColumnHeaders&&(g=m.columns.length-1),l.displayMeasuresRow&&g++;let _=this.getters.getPivotName(u),v=Math.min(g+s,h[0].length);if(v===0)return[[{value:_}]];let y=Math.min(1+c,h.length),ee=[];for(let e of S(0,y)){ee[e]=[];for(let t of S(0,v)){let n=h[e][t];switch(n.type){case`EMPTY`:ee[e].push({value:``});break;case`HEADER`:let t=d.getPivotHeaderValueAndFormat(n.domain);ee[e].push(Cd(n.domain,t));break;case`MEASURE_HEADER`:ee[e].push(d.getPivotMeasureValue(n.measure,n.domain));break;case`VALUE`:ee[e].push(d.getPivotCellValueAndFormat(n.measure,n.domain));break}}}return(l.displayColumnHeaders||l.displayMeasuresRow)&&(ee[0][0]={value:_}),ee}},wb={description:E(`Returns a range reference shifted by a specified number of rows and columns from a starting cell reference.`),args:[U(`cell_reference (meta)`,E(`The starting point from which to count the offset rows and columns.`)),U(`offset_rows (number)`,E(`The number of rows to offset by.`)),U(`offset_columns (number)`,E(`The number of columns to offset by.`)),U(`height (number, default='height of cell_reference')`,E(`The number of rows of the range to return starting at the offset target.`)),U(`width (number, default='width of cell_reference')`,E(`The number of columns of the range to return starting at the offset target.`))],compute:function(e,t,n,r,i){if(j(e?.value))return e;let a=e?.value;if(!a)return new A(`In this context, the function OFFSET needs to have a cell or range in parameter.`);let o=ps(a),s=o.bottom-o.top+1,c=o.right-o.left+1;if(r){let e=M(r,this.locale);if(e<1)return new A(E(`Height value is %(_height)s. It should be greater than or equal to 1.`,{_height:e}));s=e}if(i){let e=M(i,this.locale);if(e<1)return new A(E(`Width value is %(_width)s. It should be greater than or equal to 1.`,{_width:e}));c=e}let{sheetName:l}=vc(a),u=l&&this.getters.getSheetIdByName(l)||this.getters.getActiveSheetId(),d=M(t,this.locale),f=M(n,this.locale),p=this.__originCellPosition;p&&this.updateDependencies?.(p);let m=o.left+f,h=o.top+d;if(m<0||h<0)return new Vi(E(`OFFSET evaluates to an out of bounds range.`));let g={left:m,top:h,right:m+c-1,bottom:h+s-1},_=this.getters.getRangeFromZone(u,g);return _.invalidXc||_.invalidSheetName?new Vi:(p&&this.addDependencies?.(p,[_]),ma(c,s,(e,t)=>this.getters.getEvaluatedCell({sheetId:u,col:m+e,row:h+t})))}};var Tb=l({ADD:()=>Eb,CONCAT:()=>Db,DIVIDE:()=>Ob,EQ:()=>Mb,GT:()=>Pb,GTE:()=>Fb,LT:()=>Ib,LTE:()=>Lb,MINUS:()=>Rb,MULTIPLY:()=>zb,NE:()=>Bb,POW:()=>Vb,UMINUS:()=>Hb,UNARY_PERCENT:()=>Ub,UPLUS:()=>Wb});let Eb={description:E(`Sum of two numbers.`),args:[U(`value1 (number)`,E(`The first addend.`)),U(`value2 (number)`,E(`The second addend.`))],compute:function(e,t){return{value:M(e,this.locale)+M(t,this.locale),format:e?.format||t?.format}}},Db={description:E(`Concatenation of two values.`),args:[U(`value1 (string)`,E(`The value to which value2 will be appended.`)),U(`value2 (string)`,E(`The value to append to value1.`))],compute:function(e,t){return N(e)+N(t)},isExported:!0},Ob={description:E(`One number divided by another.`),args:[U(`dividend (number)`,E(`The number to be divided.`)),U(`divisor (number)`,E(`The number to divide by.`))],compute:function(e,t){let n=M(t,this.locale);return n===0?new Gi(E(`The divisor must be different from zero.`)):{value:M(e,this.locale)/n,format:e?.format||t?.format}}};function kb(e){return e===void 0||e.value===null}let Ab={number:0,string:``,boolean:!1};function jb(e,t,n=2e-16){return Math.abs(e-t)<n}let Mb={description:E(`Equal.`),args:[U(`value1 (string, number, boolean)`,E(`The first value.`)),U(`value2 (string, number, boolean)`,E(`The value to test against value1 for equality.`))],compute:function(e,t){if(j(e?.value))return e;if(j(t?.value))return t;let n=kb(e)?Ab[typeof t?.value]:e?.value,r=kb(t)?Ab[typeof e?.value]:t?.value;return typeof n==`string`&&(n=n.toUpperCase()),typeof r==`string`&&(r=r.toUpperCase()),typeof n==`number`&&typeof r==`number`?{value:jb(n,r)}:{value:n===r}}};function Nb(e,t,n){if(j(e?.value))return e;if(j(t?.value))return t;let r=kb(e)?Ab[typeof t?.value]:e?.value,i=kb(t)?Ab[typeof e?.value]:t?.value;typeof r!=`number`&&(r=N(r).toUpperCase()),typeof i!=`number`&&(i=N(i).toUpperCase());let a=typeof r,o=typeof i;return a===`string`&&o===`number`?{value:!0}:o===`string`&&a===`number`?{value:!1}:{value:n(r,i)}}let Pb={description:E(`Strictly greater than.`),args:[U(`value1 (number, string, boolean)`,E(`The value to test as being greater than value2.`)),U(`value2 (number, string, boolean)`,E(`The second value.`))],compute:function(e,t){return Nb(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?!jb(e,t)&&e>t:e>t)}},Fb={description:E(`Greater than or equal to.`),args:[U(`value1 (number, string, boolean)`,E(`The value to test as being greater than or equal to value2.`)),U(`value2 (number, string, boolean)`,E(`The second value.`))],compute:function(e,t){return Nb(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?jb(e,t)||e>t:e>=t)}},Ib={description:E(`Less than.`),args:[U(`value1 (number, string, boolean)`,E(`The value to test as being less than value2.`)),U(`value2 (number, string, boolean)`,E(`The second value.`))],compute:function(e,t){let n=Fb.compute.bind(this)(e,t);return j(n.value)?n:{value:!n.value}}},Lb={description:E(`Less than or equal to.`),args:[U(`value1 (number, string, boolean)`,E(`The value to test as being less than or equal to value2.`)),U(`value2 (number, string, boolean)`,E(`The second value.`))],compute:function(e,t){let n=Pb.compute.bind(this)(e,t);return j(n.value)?n:{value:!n.value}}},Rb={description:E(`Difference of two numbers.`),args:[U(`value1 (number)`,E(`The minuend, or number to be subtracted from.`)),U(`value2 (number)`,E(`The subtrahend, or number to subtract from value1.`))],compute:function(e,t){return{value:M(e,this.locale)-M(t,this.locale),format:e?.format||t?.format}}},zb={description:E(`Product of two numbers`),args:[U(`factor1 (number)`,E(`The first multiplicand.`)),U(`factor2 (number)`,E(`The second multiplicand.`))],compute:function(e,t){return{value:M(e,this.locale)*M(t,this.locale),format:e?.format||t?.format}}},Bb={description:E(`Not equal.`),args:[U(`value1 (string, number, boolean)`,E(`The first value.`)),U(`value2 (string, number, boolean)`,E(`The value to test against value1 for inequality.`))],compute:function(e,t){let n=Mb.compute.bind(this)(e,t);return j(n.value)?n:{value:!n.value}}},Vb={description:E(`A number raised to a power.`),args:[U(`base (number)`,E(`The number to raise to the exponent power.`)),U(`exponent (number)`,E(`The exponent to raise base to.`))],compute:function(e,t){return nm.compute.bind(this)(e,t)}},Hb={description:E(`A number with the sign reversed.`),args:[U(`value (number)`,E(`The number to have its sign reversed. Equivalently, the number to multiply by -1.`))],compute:function(e){return{value:-M(e,this.locale),format:e?.format}}},Ub={description:E(`Value interpreted as a percentage.`),args:[U(`percentage (number)`,E(`The value to interpret as a percentage.`))],compute:function(e){return M(e,this.locale)/100}},Wb={description:E(`A specified number, unchanged.`),args:[U(`value (any)`,E(`The number to return.`))],compute:function(e={value:null}){return e}},W=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),Gb={transform:e=>e,inverseTransform:e=>e},Kb=1e-10,qb=.0254,Jb=qb/72,Yb=.3048,Xb=.9144,Zb=1609.34,Qb=1852,$b=946073047258e4,ex={g:{...Gb,category:`weight`},u:{...W(166053e-29),category:`weight`},grain:{...W(.0647989),category:`weight`},ozm:{...W(28.3495),category:`weight`},lbm:{...W(453.592),category:`weight`},stone:{...W(6350.29),category:`weight`},sg:{...W(14593.90294),category:`weight`},cwt:{...W(45359.237),category:`weight`},uk_cwt:{...W(50802.3),category:`weight`},ton:{...W(907184.74),category:`weight`},uk_ton:{...W(1016046.9),category:`weight`},m:{...Gb,category:`distance`},km:{...W(1e3),category:`distance`},ang:{...W(Kb),category:`distance`},Picapt:{...W(Jb),category:`distance`},pica:{...W(qb/6),category:`distance`},in:{...W(qb),category:`distance`},ft:{...W(Yb),category:`distance`},yd:{...W(Xb),category:`distance`},ell:{...W(1.143),category:`distance`},mi:{...W(Zb),category:`distance`},survey_mi:{...W(1609.34),category:`distance`},Nmi:{...W(Qb),category:`distance`},ly:{...W($b),category:`distance`},parsec:{...W(0x6da012f95c9fd0),category:`distance`},sec:{...Gb,category:`time`},min:{...W(60),category:`time`},hr:{...W(3600),category:`time`},day:{...W(86400),category:`time`},yr:{...W(31556952),category:`time`},Pa:{...Gb,category:`pressure`},bar:{...W(1e5),category:`pressure`},mmHg:{...W(133.322),category:`pressure`},Torr:{...W(133.322),category:`pressure`},psi:{...W(6894.76),category:`pressure`},atm:{...W(101325),category:`pressure`},N:{...Gb,category:`force`},dyn:{...W(1e-5),category:`force`},pond:{...W(.00980665),category:`force`},lbf:{...W(4.44822),category:`force`},J:{...Gb,category:`energy`},eV:{...W(160218e-24),category:`energy`},e:{...W(1e-7),category:`energy`},flb:{...W(1.3558179483),category:`energy`},c:{...W(4.184),category:`energy`},cal:{...W(4.1868),category:`energy`},BTU:{...W(1055.06),category:`energy`},Wh:{...W(3600),category:`energy`},HPh:{...W(2684520),category:`energy`},W:{...Gb,category:`power`},PS:{...W(735.499),category:`power`},HP:{...W(745.7),category:`power`},T:{...Gb,category:`magnetism`},ga:{...W(1e-4),category:`magnetism`},K:{...Gb,category:`temperature`},C:{transform:e=>e+273.15,inverseTransform:e=>e-273.15,category:`temperature`},F:{transform:e=>(e-32)*5/9+273.15,inverseTransform:e=>(e-273.15)*9/5+32,category:`temperature`},Rank:{...W(5/9),category:`temperature`},Reau:{transform:e=>e*1.25+273.15,inverseTransform:e=>(e-273.15)/1.25,category:`temperature`},"m^3":{...Gb,category:`volume`,order:3},"ang^3":{...W(Kb**3),category:`volume`,order:3},"Picapt^3":{...W(Jb**3),category:`volume`,order:3},tsp:{...W(492892e-11),category:`volume`},tspm:{...W(5e-6),category:`volume`},tbs:{...W(14786764825785619e-21),category:`volume`},"in^3":{...W(qb**3),category:`volume`,order:3},oz:{...W(295735295625e-16),category:`volume`},cup:{...W(237e-6),category:`volume`},pt:{...W(.0004731765),category:`volume`},uk_pt:{...W(568261e-9),category:`volume`},qt:{...W(.0009463529),category:`volume`},l:{...W(.001),category:`volume`},uk_qt:{...W(.0011365225),category:`volume`},gal:{...W(.0037854118),category:`volume`},uk_gal:{...W(.00454609),category:`volume`},"ft^3":{...W(Yb**3),category:`volume`,order:3},bushel:{...W(.0352390704),category:`volume`},barrel:{...W(.158987295),category:`volume`},"yd^3":{...W(Xb**3),category:`volume`,order:3},MTON:{...W(1.13267386368),category:`volume`},GRT:{...W(2.83168),category:`volume`},"mi^3":{...W(Zb**3),category:`volume`,order:3},"Nmi^3":{...W(Qb**3),category:`volume`,order:3},"ly^3":{...W($b**3),category:`volume`,order:3},"m^2":{...Gb,category:`area`,order:2},"ang^2":{...W(Kb**2),category:`area`,order:2},"Picapt^2":{...W(Jb**2),category:`area`,order:2},"in^2":{...W(qb**2),category:`area`,order:2},"ft^2":{...W(Yb**2),category:`area`,order:2},"yd^2":{...W(Xb**2),category:`area`,order:2},ar:{...W(100),category:`area`},Morgen:{...W(2500),category:`area`},uk_acre:{...W(4046.8564224),category:`area`},us_acre:{...W(4046.8726098743),category:`area`},ha:{...W(1e4),category:`area`},"mi^2":{...W(Zb**2),category:`area`,order:2},"Nmi^2":{...W(Qb**2),category:`area`,order:2},"ly^2":{...W($b**2),category:`area`,order:2},bit:{...Gb,category:`information`},byte:{...W(8),category:`information`},"m/s":{...Gb,category:`speed`},"m/hr":{...W(1/3600),category:`speed`},"km/hr":{...W(1/3.6),category:`speed`},mph:{...W(.44704),category:`speed`},kn:{...W(.5144444444),category:`speed`},admkn:{...W(.5147733333),category:`speed`}},tx={shweight:`cwt`,lcwt:`uk_cwt`,hweight:`uk_cwt`,LTON:`uk_ton`,brton:`uk_ton`,pc:`parsec`,Pica:`Picapt`,d:`day`,mn:`min`,s:`sec`,p:`Pa`,at:`atm`,dy:`dyn`,ev:`eV`,hh:`HPh`,wh:`Wh`,btu:`BTU`,h:`HP`,cel:`C`,fah:`F`,kel:`K`,us_pt:`pt`,L:`l`,lt:`l`,ang3:`ang^3`,ft3:`ft^3`,in3:`in^3`,ly3:`ly^3`,m3:`m^3`,mi3:`mi^3`,yd3:`yd^3`,Nmi3:`Nmi^3`,Picapt3:`Picapt^3`,"Pica^3":`Picapt^3`,Pica3:`Picapt^3`,regton:`GRT`,ang2:`ang^2`,ft2:`ft^2`,in2:`in^2`,ly2:`ly^2`,m2:`m^2`,mi2:`mi^2`,Nmi2:`Nmi^2`,Picapt2:`Picapt^2`,"Pica^2":`Picapt^2`,Pica2:`Picapt^2`,yd2:`yd^2`,"m/h":`m/hr`,"m/sec":`m/s`},nx={"":1,Y:1e24,Z:1e21,E:0xde0b6b3a7640000,P:0x38d7ea4c68000,T:0xe8d4a51000,G:1e9,M:1e6,k:1e3,h:100,da:10,e:10,d:.1,c:.01,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15,a:1e-18,z:1e-21,y:1e-21,Yi:2**80,Zi:2**70,Ei:2**60,Pi:2**50,Ti:2**40,Gi:2**30,Mi:2**20,ki:2**10},rx={weight:E(`Weight`),distance:E(`Distance`),time:E(`Time`),pressure:E(`Pressure`),force:E(`Force`),energy:E(`Energy`),power:E(`Power`),magnetism:E(`Magnetism`),temperature:E(`Temperature`),volume:E(`Volume`),area:E(`Area`),information:E(`Information`),speed:E(`Speed`)};function ix(e){return rx[e]??``}function ax(e){for(let[t,n]of Object.entries(nx)){if(t&&!e.startsWith(t))continue;let r=e.slice(t.length),i=ex[r];if(!i&&tx[r]&&(i=ex[tx[r]]),i)return{...i,factor:i.order?n**+i.order:n}}}var ox=l({CONVERT:()=>sx});let sx={description:E(`Converts a numeric value to a different unit of measure.`),args:[U(`value (number)`,E(`the numeric value in start_unit to convert to end_unit`)),U(`start_unit (string)`,E(`The starting unit, the unit currently assigned to value`)),U(`end_unit (string)`,E(`The unit of measure into which to convert value`))],compute:function(e,t,n){let r=M(e,this.locale),i=N(t),a=N(n),o=ax(i),s=ax(a);return o?s?o.category===s.category?{value:s.inverseTransform(o.factor*o.transform(r))/s.factor,format:e?.format}:{value:k.GenericError,message:E(`Incompatible units of measure ('%s' vs '%s')`,ix(o.category),ix(s.category))}:{value:k.GenericError,message:E(`Invalid units of measure ('%s')`,a)}:{value:k.GenericError,message:E(`Invalid units of measure ('%s')`,i)}},isExported:!0};var cx=l({CHAR:()=>ux,CLEAN:()=>dx,CONCATENATE:()=>fx,EXACT:()=>px,FIND:()=>mx,JOIN:()=>hx,LEFT:()=>gx,LEN:()=>_x,LOWER:()=>vx,MID:()=>yx,PROPER:()=>bx,REPLACE:()=>xx,RIGHT:()=>Sx,SEARCH:()=>Cx,SPLIT:()=>wx,SUBSTITUTE:()=>Tx,TEXT:()=>Ax,TEXTJOIN:()=>Ex,TEXTSPLIT:()=>Dx,TRIM:()=>Ox,UPPER:()=>kx,VALUE:()=>jx});let lx=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,ux={description:E(`Gets character associated with number.`),args:[U(`table_number (number)`,E(`The number of the character to look up from the current Unicode table in decimal format.`))],compute:function(e){let t=Math.trunc(M(e,this.locale));return t<1?new A(E(`The table_number (%s) is out of range.`,t)):String.fromCharCode(t)},isExported:!0},dx={description:E(`Remove non-printable characters from a piece of text.`),args:[U(`text (string)`,E(`The text whose non-printable characters are to be removed.`))],compute:function(e){let t=N(e),n=``;for(let e of t)e&&e.charCodeAt(0)>31&&(n+=e);return n},isExported:!0},fx={description:E(`Appends strings to one another.`),args:[U(`string1 (string, range<string>)`,E(`The initial string.`)),U(`string2 (string, range<string>, repeating)`,E(`More strings to append in sequence.`))],compute:function(...e){return da(e,(e,t)=>e+N(t),``)},isExported:!0},px={description:E(`Tests whether two strings are identical.`),args:[U(`string1 (string)`,E(`The first string to compare.`)),U(`string2 (string)`,E(`The second string to compare.`))],compute:function(e,t){return N(e)===N(t)},isExported:!0},mx={description:E(`First position of string found in text, case-sensitive.`),args:[U(`search_for (string)`,E(`The string to look for within text_to_search.`)),U(`text_to_search (string)`,E(`The text to search for the first occurrence of search_for.`)),U(`starting_at (number, default=1)`,E(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=N(e),i=N(t),a=M(n,this.locale);if(i===``)return new A(E(`The text_to_search must be non-empty.`));if(a<1)return new A(E(`The starting_at (%s) must be greater than or equal to 1.`,a));let o=i.indexOf(r,a-1);return o===-1?new A(E(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)):o+1},isExported:!0},hx={description:E(`Concatenates elements of arrays with delimiter.`),args:[U(`delimiter (string)`,E(`The character or string to place between each concatenated value.`)),U(`value_or_array1 (string, range<string>)`,E(`The value or values to be appended using delimiter.`)),U(`value_or_array2 (string, range<string>, repeating)`,E(`More values to be appended using delimiter.`))],compute:function(e,...t){let n=N(e);return da(t,(e,t)=>(e?e+n:``)+N(t),``)}},gx={description:E(`Substring from beginning of specified string.`),args:[U(`text (string)`,E(`The string from which the left portion will be returned.`)),U(`number_of_characters (number, optional)`,E(`The number of characters to return from the left side of string.`))],compute:function(e,...t){let n=t.length?M(t[0],this.locale):1;return n<0?new A(E(`The number_of_characters (%s) must be positive or null.`,n)):N(e).substring(0,n)},isExported:!0},_x={description:E(`Length of a string.`),args:[U(`text (string)`,E(`The string whose length will be returned.`))],compute:function(e){return N(e).length},isExported:!0},vx={description:E(`Converts a specified string to lowercase.`),args:[U(`text (string)`,E(`The string to convert to lowercase.`))],compute:function(e){return N(e).toLowerCase()},isExported:!0},yx={description:E(`A segment of a string.`),args:[U(`text (string)`,E(`The string to extract a segment from.`)),U(`starting_at (number)`,E(`The index from the left of string from which to begin extracting. The first character in string has the index 1.`)),U(`extract_length (number)`,E(`The length of the segment to extract.`))],compute:function(e,t,n){let r=N(e),i=M(t,this.locale),a=M(n,this.locale);return i<1?new A(E(`The starting_at argument (%s) must be positive greater than one.`,i.toString())):a<0?new A(E(`The extract_length argument (%s) must be positive or null.`,a)):r.slice(i-1,i+a-1)},isExported:!0},bx={description:E(`Capitalizes each word in a specified string.`),args:[U(`text_to_capitalize (string)`,E(`The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase.`))],compute:function(e){return N(e).replace(lx,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},xx={description:E(`Replaces part of a text string with different text.`),args:[U(`text (string)`,E(`The text, a part of which will be replaced.`)),U(`position (number)`,E(`The position where the replacement will begin (starting from 1).`)),U(`length (number)`,E(`The number of characters in the text to be replaced.`)),U(`new_text (string)`,E(`The text which will be inserted into the original text.`))],compute:function(e,t,n,r){let i=M(t,this.locale);if(i<1)return new A(E(`The position (%s) must be greater than or equal to 1.`,i));let a=N(e),o=M(n,this.locale),s=N(r);return a.substring(0,i-1)+s+a.substring(i-1+o)},isExported:!0},Sx={description:E(`A substring from the end of a specified string.`),args:[U(`text (string)`,E(`The string from which the right portion will be returned.`)),U(`number_of_characters (number, optional)`,E(`The number of characters to return from the right side of string.`))],compute:function(e,...t){let n=t.length?M(t[0],this.locale):1;if(n<0)return new A(E(`The number_of_characters (%s) must be positive or null.`,n));let r=N(e),i=r.length;return r.substring(i-n,i)},isExported:!0},Cx={description:E(`First position of string found in text, ignoring case.`),args:[U(`search_for (string)`,E(`The string to look for within text_to_search.`)),U(`text_to_search (string)`,E(`The text to search for the first occurrence of search_for.`)),U(`starting_at (number, default=1)`,E(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=N(e).toLowerCase(),i=N(t).toLowerCase(),a=M(n,this.locale);if(i===``)return{value:k.GenericError,message:E(`The text_to_search must be non-empty.`)};if(a<1)return{value:k.GenericError,message:E(`The starting_at (%s) must be greater than or equal to 1.`,a)};let o=i.indexOf(r,a-1);return o===-1?{value:k.GenericError,message:E(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)}:{value:o+1}},isExported:!0},wx={description:E(`Split text by specific character delimiter(s).`),args:[U(`text (string)`,E(`The text to divide.`)),U(`delimiter (string)`,E(`The character or characters to use to split text.`)),U(`split_by_each (boolean, default=true})`,E(`Whether or not to divide text around each character contained in delimiter.`)),U(`remove_empty_text (boolean, default=true)`,E(`Whether or not to remove empty text messages from the split results. The default behavior is to treat consecutive delimiters as one (if TRUE). If FALSE, empty cells values are added between consecutive delimiters.`))],compute:function(e,t,n={value:!0},r={value:!0}){let i=N(e),a=ot(N(t)),o=P(n),s=P(r);if(a.length<=0)return new A(E(`The delimiter (%s) must be not be empty.`,a));let c=o?RegExp(`[${a}]`,`g`):new RegExp(a,`g`),l=i.split(c);return s&&(l=l.filter(e=>e!==``)),_a([l])},isExported:!1},Tx={description:E(`Replaces existing text with new text in a string.`),args:[U(`text_to_search (string)`,E(`The text within which to search and replace.`)),U(`search_for (string)`,E(`The string to search for within text_to_search.`)),U(`replace_with (string)`,E(`The string that will replace search_for.`)),U(`occurrence_number (number, optional)`,E(`The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced.`))],compute:function(e,t,n,r){let i=M(r,this.locale);if(i<0)return new A(E(`The occurrenceNumber (%s) must be positive or null.`,i));let a=N(e),o=N(t);if(o===``)return a;let s=N(n),c=new RegExp(ot(o),`g`);if(i===0)return a.replace(c,s);let l=0;return a.replace(c,e=>++l===i?s:e)},isExported:!0},Ex={description:E(`Combines text from multiple strings and/or arrays.`),args:[U(`delimiter (string)`,E(` A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.`)),U(`ignore_empty (boolean)`,E(`A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.`)),U(`text1 (string, range<string>)`,E(`Any text item. This could be a string, or an array of strings in a range.`)),U(`text2 (string, range<string>, repeating)`,E(`Additional text item(s).`))],compute:function(e,t,...n){let r=N(e),i=P(t),a=0;return da(n,(e,t)=>i&&N(t)===``?e:(a++?e+r:``)+N(t),``)},isExported:!0},Dx={description:E(`Splits text into rows or columns using specified column and row delimiters.`),args:[U(`text (string)`,E(`The text to split.`)),U(`col_delimiter (string, range<string>)`,E(`Character or string to split columns by.`)),U(`row_delimiter (string, range<string>, optional)`,E(`Character or string to split rows by.`)),U(`ignore_empty (boolean, default=false)`,E(`Whether to ignore empty cells.`)),U(`match_mode (number, default=0)`,E(`Searches the text for a delimiter match. 0 = case-sensitive, 1 = case-insensitive.`)),U(`pad_with (string, default="${k.NotAvailable}")`,E(`The value to use for padding empty cells.`))],compute:function(e,t,n,r={value:!1},i={value:0},a=new Hi){let o=N(e);if(o.length<=0)return new A(E(`No text to split.`));if(t===void 0&&n===void 0)return new A(E(`At least one delimiter must be provided.`));let s=I(t).flat().map(e=>ot(N(e))),c=I(n).flat().map(e=>ot(N(e)));if(s.some(e=>e===``)||c.some(e=>e===``))return new A(E(`The delimiters cannot be empty values.`));let l=P(r),u=M(i,this.locale);if(![0,1].includes(u))return new A(E(`match_mode should be a value of 0 or 1.`));let d=[],f=u===1?`gi`:`g`,p=c.filter(e=>!s.includes(e)),m=p.length?o.split(new RegExp(p.join(`|`),f)):[o];l&&(m=m.filter(e=>e!==``));let h=new RegExp(s.join(`|`),f);for(let e of m){let t=s.length?e.split(h):[e];l&&(t=t.filter(e=>e!==``)),d.push(t.map(e=>({value:e})))}let g=Math.max(...d.map(e=>e.length));for(let e of d)for(;e.length<g;)e.push(a);return _a(d)},isExported:!0},Ox={description:E(`Removes space characters.`),args:[U(`text (string)`,E(`The text or reference to a cell containing text to be trimmed.`))],compute:function(e){return Gt(N(e))},isExported:!0},kx={description:E(`Converts a specified string to uppercase.`),args:[U(`text (string)`,E(`The string to convert to uppercase.`))],compute:function(e){return N(e).toUpperCase()},isExported:!0},Ax={description:E(`Converts a number to text according to a specified format.`),args:[U(`number (number)`,E(`The number, date or time to format.`)),U(`format (string)`,E(`The case-sensitive format of the result, enclosed in quotation marks. Examples: "0.00" rounded to 2 decimal places, "hh:mm:ss" for hour:minutes:seconds.`))],compute:function(e,t){return L(M(e,this.locale),{format:N(t),locale:this.locale})},isExported:!0},jx={description:E(`Converts a string to a numeric value.`),args:[U(`value (number)`,E(`the string to be converted`))],compute:function(e){return M(e,this.locale)},isExported:!0};var Mx=l({HYPERLINK:()=>Nx});let Nx={description:E(`Creates a hyperlink in a cell.`),args:[U(`url (string)`,E(`The full URL of the link enclosed in quotation marks.`)),U(`link_label (string, optional)`,E(`The text to display in the cell, enclosed in quotation marks.`))],compute:function(e,t){let n=N(e).trim(),r=N(t)||n;return n===``?r:yt(r,n)},isExported:!0},Px=[{name:E(`Array`),functions:Bf},{name:E(`Database`),functions:Mh},{name:E(`Date`),functions:qh},{name:E(`Filter`),functions:Fg},{name:E(`Financial`),functions:V_},{name:E(`Info`),functions:Ny},{name:E(`Lookup`),functions:sb},{name:E(`Logical`),functions:Gy},{name:E(`Math`),functions:fp},{name:E(`Misc`),functions:up},{name:E(`Operator`),functions:Tb},{name:E(`Statistical`),functions:wm},{name:E(`Text`),functions:cx},{name:E(`Engineering`),functions:Og},{name:E(`Web`),functions:Mx},{name:E(`Parser`),functions:ox}],Fx=/^[A-Z0-9\_\.]+$/,Ix=new class extends g{mapping={};add(e,t){if(e=e.toUpperCase(),e in this.content)throw Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(e,t){if(e=e.toUpperCase(),!Fx.test(e))throw Error(E(`Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)`,e));let n=Ff(e,t);return zf(n),this.mapping[e]=Lx(n),super.replace(e,n),this}};for(let e of Px){let t=e.functions;for(let n in t){let r=t[n];r.category=r.category||e.name,n=n.replace(/_/g,`.`),Ix.add(n,{isExported:!1,...r})}}function Lx(e){function t(...t){let i=[],a=Lf(e,t.length);for(let n=0;n<t.length;n++){let r=a(n)??-1,o=e.args[r],s=t[n];if(!Or(s)&&o.acceptMatrixOnly)throw new zi(E(`Function %s expects the parameter '%s' to be reference to a cell or range.`,e.name,(n+1).toString()));i.push(!o.acceptMatrix)}return n(va(r.bind(this),t,i))}function n(t){return Or(t)?ga(t,t=>Bx(t,e.name)):Bx(t,e.name),t}function r(...t){for(let n=0;n<t.length;n++){let r=t[n],i=Lf(e,t.length);if(!e.args[i(n)||n].acceptErrors&&!Or(r)&&j(r?.value))return r}try{return i.apply(this,t)}catch(t){return Rx(t,e.name)}}function i(...t){this.debug&&=!1;let n=e.compute.apply(this,t);return Or(n)?typeof n[0][0]==`object`&&n[0][0]!==null&&`value`in n[0][0]?n:ha(n,e=>({value:e})):typeof n==`object`&&n&&`value`in n?n:(e.name,{value:n})}return t}function Rx(e,t){return zx(e)&&j(e.value)?(Hx(e)&&Bx(e,t),e):(console.error(e),new A(Vx+(Hx(e)?` `+e.message:``)))}function zx(e){return e?.value!==void 0&&typeof e.value==`string`}function Bx(e,t){e.message?.includes(`[[FUNCTION_NAME]]`)&&(e.message=e.message.replace(`[[FUNCTION_NAME]]`,t))}let Vx=E(`An unexpected error occurred. Submit a support ticket at odoo.com/help.`);function Hx(e){return e?.message!==void 0&&typeof e.message==`string`}var Ux=class{scope;code=``;constructor(e=new Gx){this.scope=e}append(...e){this.code+=e.map(e=>e.toString()).join(`
|
|
16
16
|
`)+`
|
|
17
|
-
`}return(e){return new Wx(this.scope,this.code,e)}toString(){return qx(this.code)}},Wx=class{code;constructor(e,t,n){this.scope=e,this.returnExpression=n,this.code=qx(t)}toString(){return this.code}assignResultToVariable(){if(this.scope.isAlreadyDeclared(this.returnExpression))return this;let e=this.scope.nextVariableName(),t=new Ux(this.scope);return t.append(this.code),t.append(`const ${e} = ${this.returnExpression};`),t.return(e)}},Gx=class{nextId=1;declaredVariables=new Set;nextVariableName(){let e=`_${this.nextId++}`;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}};function Kx(e){return e.split(`
|
|
17
|
+
`}return(e){return new Wx(this.scope,this.code,e)}toString(){return qx(this.code)}},Wx=class{scope;returnExpression;code;constructor(e,t,n){this.scope=e,this.returnExpression=n,this.code=qx(t)}toString(){return this.code}assignResultToVariable(){if(this.scope.isAlreadyDeclared(this.returnExpression))return this;let e=this.scope.nextVariableName(),t=new Ux(this.scope);return t.append(this.code),t.append(`const ${e} = ${this.returnExpression};`),t.return(e)}},Gx=class{nextId=1;declaredVariables=new Set;nextVariableName(){let e=`_${this.nextId++}`;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}};function Kx(e){return e.split(`
|
|
18
18
|
`).map(e=>e.trim()).filter(e=>e!==``)}function qx(e){let t=``,n=0,r=Kx(e);for(let e of r)e.startsWith(`}`)&&n--,t+=` `.repeat(n)+e+`
|
|
19
19
|
`,e.endsWith(`{`)&&n++;return t.trim()}let Jx=Ix.content,Yx={"=":`EQ`,"+":`ADD`,"-":`MINUS`,"*":`MULTIPLY`,"/":`DIVIDE`,">=":`GTE`,"<>":`NE`,">":`GT`,"<=":`LTE`,"<":`LT`,"^":`POWER`,"&":`CONCATENATE`},Xx={"-":`UMINUS`,"+":`UPLUS`,"%":`UNARY.PERCENT`},Zx={};function Qx(e){return $x(Qv(e))}function $x(e){try{return eS(e)}catch(t){return{tokens:e,dependencies:[],execute:function(){return t},isBadExpression:!0,normalizedFormula:e.map(e=>e.value).join(``)}}}function eS(e){let{dependencies:t,literalValues:n,symbols:r}=nS(e),i=tS(e);if(!Zx[i]){let t=dy([...e]),n=new Gx,s=0,c=0,l=0;if(t.type===`BIN_OPERATION`&&t.value===`:`||t.type===`EMPTY`)throw new zi(E(`Invalid formula`));let u=o(t),d=new Ux;d.append(u),d.append(`return ${u.returnExpression};`),Zx[i]=Function(`deps`,`ref`,`range`,`getSymbolValue`,`ctx`,d.toString());function a(e){let{args:t}=e,n=Jx[e.value.toUpperCase()];if(!n)throw new Ui(E(`Unknown function: "%s"`,e.value));rS(e);let r=[],i=Lf(n,t.length);for(let e=0;e<t.length;e++){let a=n.args[i(e)??-1],s=t[e],c=a.type||[],l=c.includes(`META`),u=c.some(e=>iS(e));r.push(o(s,l,u))}return r}function o(e,t=!1,i=!1){let u=new Ux(n);if(e.type!==`REFERENCE`&&!(e.type===`BIN_OPERATION`&&e.value===`:`)&&t)throw new zi(E(`Argument must be a reference to a cell or range.`));switch(e.debug&&(u.append(`debugger;`),u.append(`ctx["debug"] = true;`)),e.type){case`BOOLEAN`:return u.return(`{ value: ${e.value} }`);case`NUMBER`:return u.return(`this.literalValues.numbers[${c++}]`);case`STRING`:return u.return(`this.literalValues.strings[${s++}]`);case`REFERENCE`:return!t&&e.value.includes(`:`)||i?u.return(`range(deps[${l++}])`):u.return(`ref(deps[${l++}], ${t?`true`:`false`})`);case`FUNCALL`:let n=a(e).map(e=>e.assignResultToVariable());u.append(...n);let d=e.value.toUpperCase();return u.return(`ctx['${d}'](${n.map(e=>e.returnExpression)})`);case`UNARY_OPERATION`:{let t=Xx[e.value],n=o(e.operand,!1,!1).assignResultToVariable();return u.append(n),u.return(`ctx['${t}'](${n.returnExpression})`)}case`BIN_OPERATION`:{let t=Yx[e.value],n=o(e.left,!1,!1).assignResultToVariable(),r=o(e.right,!1,!1).assignResultToVariable();return u.append(n),u.append(r),u.return(`ctx['${t}'](${n.returnExpression}, ${r.returnExpression})`)}case`SYMBOL`:let f=r.indexOf(e.value);return u.return(`getSymbolValue(this.symbols[${f}])`);case`EMPTY`:return u.return(`undefined`)}}}return{execute:Zx[i],dependencies:t,literalValues:n,symbols:r,tokens:e,isBadExpression:!1,normalizedFormula:i}}function tS(e){let t=``;for(let n of e)switch(n.type){case`STRING`:t+=`|S|`;break;case`NUMBER`:t+=`|N|`;break;case`REFERENCE`:case`INVALID_REFERENCE`:n.value.includes(`:`)?t+=`|R|`:t+=`|C|`;break;case`SPACE`:break;default:t+=n.value;break}return t}function nS(e){let t={numbers:[],strings:[]},n=[],r=[];for(let i of e)switch(i.type){case`INVALID_REFERENCE`:case`REFERENCE`:n.push(i.value);break;case`STRING`:let e=it(i.value);t.strings.push({value:e});break;case`NUMBER`:{let e=Ii(i.value,D);t.numbers.push({value:e});break}case`SYMBOL`:r.push(lt(i.value,`'`))}return{dependencies:n,literalValues:t,symbols:r}}function rS(e){let t=e.args.length,n=e.value.toUpperCase(),r=Jx[n],{nbrArgRepeating:i,minArgRequired:a}=r;if(t<a)throw new zi(E(`Invalid number of arguments for the %(functionName)s function. Expected %(minArgRequired)s minimum, but got %(nbrArgSupplied)s instead.`,{functionName:n,minArgRequired:a,nbrArgSupplied:t}));if(t>r.maxArgPossible)throw new zi(E(`Invalid number of arguments for the %(functionName)s function. Expected %(maxArgPossible)s maximum, but got %(nbrArgSupplied)s instead.`,{functionName:n,maxArgPossible:r.maxArgPossible,nbrArgSupplied:t}));if(i>1){let e=i*Math.floor((t-a)/i),o=t-a-e-r.nbrArgOptional;if(o>0)throw new zi(E(`Invalid number of arguments for the %(functionName)s function. Repeatable arguments should be supplied in groups of %(nbrArgRepeating)s, with up to %(nbrArgOptional)s optional. Got %(nbrValueRemaining)s too many.`,{functionName:n,nbrArgRepeating:i,nbrArgOptional:r.nbrArgOptional,nbrValueRemaining:o}))}}function iS(e){return e.startsWith(`RANGE`)}let aS=Ix.content;function oS(e){try{return py(dy(e)).filter(e=>e.type===`FUNCALL`&&!aS[e.value.toUpperCase()]?.isExported).length===0}catch{return!1}}function sS(e,t){if(!e.some(e=>e.type===`SYMBOL`&&t.includes(e.value.toUpperCase())))return[];let n;try{n=dy(e)}catch{return[]}return cS(n,t)}function cS(e,t){return py(e).filter(e=>e.type===`FUNCALL`&&t.includes(e.value.toUpperCase())).map(e=>({functionName:e.value.toUpperCase(),args:e.args}))}function lS(e,t,n){if(!t.startsWith(`=`))return t;let r=Qv(t);for(let t=1;t<r.length;t++){if(r[t].type!==`REFERENCE`)continue;let i=r[t].value,a=uS(e,i,n).range;i!==a&&(r[t]={value:a,type:`REFERENCE`})}return Ot(r.map(e=>e.value))}function uS(e,t,n){let r=vc(t).sheetName;if(r?!qc(r,n.sheetName.old):e!==n.sheetId)return{changeType:`NONE`,range:t};let i=pS(t,r?n.sheetId:e);if(i.invalidXc)return{changeType:`NONE`,range:t};let a=n.applyChange(i);if(a.changeType===`NONE`||a.changeType===`REMOVE`)return{changeType:a.changeType,range:t};let o=Tc(a.range,e,dS(n));return o===k.InvalidReference?{changeType:`REMOVE`,range:o}:{changeType:a.changeType,range:o}}function dS(e){return t=>t===e.sheetId?e.sheetName.current:``}function fS(e){return{numberOfRows:2**53-1,numberOfCols:2**53-1}}function pS(e,t){return fc.test(e)?xc({xc:e,sheetId:t},fS):Sc(e)}let mS=`xMovingAverage`,hS={exponential:`exp`,logarithmic:`log`,polynomial:`poly`,trailingMovingAverage:`movingAvg`};function gS(e,t,n,r){let i=!1,a=[];for(let r in n){let o=n[r];if(o.labelCell){let e=yS(o.labelCell,t);o.labelCell!==e&&(i=!0,o={...o,labelCell:e})}let s=yS(o.dataRange,t);s===void 0||e.getRangeString(s,s.sheetId)===k.InvalidReference?(i=!0,o=void 0):s!==o.dataRange&&(i=!0,o={...o,dataRange:s}),a[r]=o}let o=r,s=yS(o,t);s!==o&&(i=!0,o=s);let c=a.filter(C);return{isStale:i,dataSets:c,labelRange:o}}function _S(e,t,n){return n.map(n=>({dataRange:Ec(e,t,n.dataRange),labelCell:n.labelCell?Ec(e,t,n.labelCell):void 0}))}function vS(e,t,n){return n?Ec(e,t,n):void 0}function yS(e,t){if(!e)return;let n=t(e);switch(n.changeType){case`REMOVE`:return;default:return n.range}}function bS(e,t,n,r){let i=[];for(let a of t){let{unboundedZone:t,sheetId:o,invalidSheetName:s,invalidXc:c}=e.getRangeFromSheetXC(n,a.dataRange);if(!(s||c))if(t.left!==t.right&&t.top!==t.bottom){if(t.right===void 0)continue;for(let n=t.left;n<=t.right;n++){let s={...t,left:n,right:n};i.push({...xS(e,o,s,r?{top:s.top,bottom:s.top,left:s.left,right:s.left}:void 0),backgroundColor:a.backgroundColor,rightYAxis:a.yAxisId===`y1`,customLabel:a.label,trend:a.trend})}}else i.push({...xS(e,o,t,r?{top:t.top,bottom:t.top,left:t.left,right:t.left}:void 0),backgroundColor:a.backgroundColor,rightYAxis:a.yAxisId===`y1`,customLabel:a.label,trend:a.trend})}return i}function xS(e,t,n,r){if(n.left!==n.right&&n.top!==n.bottom)throw Error(`Zone should be a single column or row: ${vs(n)}`);if(r){let i=vs(n),a=vs(r);return{labelCell:e.getRangeFromSheetXC(t,a),dataRange:e.getRangeFromSheetXC(t,i)}}else return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,vs(n))}}function SS(e,t){let n=t.labelCell?.zone,r=t.dataRange.zone;if(n){let{numberOfRows:e,numberOfCols:t}=js(r);e===1?r={...r,left:r.left+1}:t===1&&(r={...r,top:r.top+1})}let i=bc({...t.dataRange,zone:r},e.getSheetSize),a={};t.customLabel?a={text:t.customLabel}:t.labelCell&&(a={reference:e.getRangeString(t.labelCell,`forceSheetReference`,{useBoundedReference:!0})});let o;return t.trend?.type&&(o={type:t.trend.type===`polynomial`&&t.trend.order===1?`linear`:hS[t.trend.type],color:t.trend.color,order:t.trend.order?Math.min(t.trend.order,6):void 0,window:t.trend.window||2}),{label:a,range:e.getRangeString(i,`forceSheetReference`,{useBoundedReference:!0}),backgroundColor:t.backgroundColor,rightYAxis:t.rightYAxis,trend:o}}function CS(e,t,n){if(!t)return;let r={...t.zone};n&&t.zone.bottom>t.zone.top&&(r.top+=1);let i=bc({...t,zone:r},e.getSheetSize);return e.getRangeString(i,`forceSheetReference`,{useBoundedReference:!0})}function wS(e,t,n){let r;if(t.labelRange){let{changeType:i,range:a}=uS(e,t.labelRange,n);i!==`REMOVE`&&(r=a)}let i=[];for(let r of t.dataSets){let t={...r},{changeType:a,range:o}=uS(e,r.dataRange,n);a!==`REMOVE`&&(t.dataRange=o,i.push(t))}return{...t,dataSets:i,labelRange:r}}function TS(e){return e&&fn(e)<.3?`#FFFFFF`:`#000000`}function ES(e){return e&&fn(e)<.3?`#C8C8C8`:`#666666`}function DS(e){return e.dataSets&&(e.dataSets.find(e=>!fc.test(e.dataRange))!==void 0||e.dataSets.map(e=>fs(e.dataRange)).some(e=>e.top!==e.bottom&&Hs(e)))?`InvalidDataSet`:`Success`}function OS(e){return e.labelRange&&!fc.test(e.labelRange||``)?`InvalidLabelRange`:`Success`}function kS(e,t,n){if(!n||!e)return!1;if(!t)return!0;let r=Ws(t.dataRange.zone);return!(Ws(e.zone)<r)}function AS(e,t){let{x:n,y:r}=e.getMainViewportCoordinates(),{scrollX:i,scrollY:a}=e.getActiveSheetScrollInfo(),{width:o,height:s}=e.getVisibleRect(e.getActiveMainViewport());return{x:n+i+Math.max(0,(o-t.width)/2),y:r+a+Math.max(0,(s-t.height)/2)}}function jS(e){let t=!1,n=!1;if(`horizontal`in e&&e.horizontal)return{useLeftAxis:!0,useRightAxis:!1};for(let r of e.dataSets||[])r.yAxisId===`y1`?n=!0:t=!0;return t||=!n,{useLeftAxis:t,useRightAxis:n}}function MS(e,t){return(n,r)=>{let i=e?.[r];return NS({format:i,locale:t})(n)}}function NS(e){return t=>{if(t=Number(t),isNaN(t))return t;let{locale:n,format:r}=e;return IS(L(t,{locale:n,format:!r&&Math.abs(t)>=1e3?`#,##`:r}))}}let PS=[{value:`left`,label:E(`Left`)},{value:`right`,label:E(`Right`)}];function FS(e,t){let n=[],r=Jt(t.map(e=>e.data.length));for(let t=0;t<=r;t++)n.push(e.next());return n}function IS(e){return e?e.length>20?e.substring(0,20)+`…`:e:``}function LS(e){return e===`x1`||e===`xMovingAverage`}let RS={id:`chartShowValuesPlugin`,afterDatasetsDraw(e,t,n){if(!n.showValues||!e._metasets?.[0]?.data)return;let r=e.ctx;switch(r.save(),r.textAlign=`center`,r.textBaseline=`middle`,r.miterLimit=1,e.config.type){case`pie`:case`doughnut`:HS(e,n,r);break;case`bar`:case`line`:case`radar`:n.horizontal?VS(e,n,r):BS(e,n,r);break;case`funnel`:VS(e,n,r);break}r.restore()}};function zS(e,t,n,r){r.lineWidth=3,r.strokeText(e,t,n),r.lineWidth=1,r.fillText(e,t,n)}function BS(e,t,n){let r={};for(let i of e._metasets){if(LS(i.xAxisID)||i.hidden)continue;let a=e.scales[i.yAxisID];for(let o=0;o<i._parsed.length;o++){let s=i._parsed[o],c=Number(e.config.type===`radar`?s.r:s.y);if(isNaN(c))continue;let l=i.data[o],u=l.x,d=0;if(e.config.type===`line`||e.config.type===`radar`)d=c<0?l.y+10:l.y-10;else{let e=a.getPixelForValue(0);d=Math.abs(e-l.y)<12?c<0?e+12/2:e-12/2:c<0?l.y-l.height/2:l.y+l.height/2}r[u]||(r[u]=[]);for(let e of r[u]||[])Math.abs(e-d)<13&&(d=c<0?e+13:e-13);r[u].push(d),n.fillStyle=l.options.backgroundColor,n.strokeStyle=t.background||`#ffffff`,zS(t.callback(Number(c),i,o),u,d,n)}}}function VS(e,t,n){let r={};for(let i of e._metasets){if(LS(i.xAxisID))return;let a=e.scales[i.xAxisID].getPixelForValue(0);for(let e=0;e<i._parsed.length;e++){let o=Number(i._parsed[e].x);if(isNaN(o))continue;let s=t.callback(o,i,e),c=i.data[e],l=c.y,u=$c(n,s,{fontSize:12},`px`),d=Math.abs(c.x-a),f;f=d<u?o<0?a-u/2-3:a+u/2+3:o<0?c.x+c.width/2:c.x-c.width/2,r[l]||(r[l]=[]);for(let e of r[l])Math.abs(e-f)<u&&(f=o<0?e-u-3:e+u+3);r[l].push(f),n.fillStyle=c.options.backgroundColor,n.strokeStyle=t.background||`#ffffff`,zS(s,f,l,n)}}}function HS(e,t,n){for(let r of e._metasets)for(let e=0;e<r._parsed.length;e++){let i=Number(r._parsed[e]);if(isNaN(i)||i===0)continue;let a=r.data[e],{startAngle:o,endAngle:s,innerRadius:c,outerRadius:l}=a,u=(o+s)/2,d=(c+l)/2,f=a.x+d*Math.cos(u),p=a.y+d*Math.sin(u),m=t.callback(i,r,e),h=$c(n,m,{fontSize:12},`px`),g=l-c;if(h>=g||g<12)continue;let _=s-o,v=2*d*Math.tan(_/2);_<Math.PI/2&&(h>=v||v<12)||(n.fillStyle=TS(t.background),n.strokeStyle=t.background||`#ffffff`,zS(m,f,p,n))}}let US={showHeaders:!0,headerDesign:{align:`center`,fillColor:`#808080`,bold:!0,fontSize:15},showValues:!0,showLabels:!0,valuesDesign:{align:`left`,verticalAlign:`bottom`,fontSize:12},coloringOptions:{type:`categoryColor`,colors:[],useValueBasedGradient:!0}},WS=`nullValue`;function GS(e,t){let{dataSetsValues:n}=t,r=[],i=uC(e,n.length),a=[];for(let o in n){let{label:s,data:c,hidden:l}=n[o];s=e.dataSets?.[o].label||s;let u=i.next(),d={label:s,data:c,hidden:l,borderColor:e.background||`#FFFFFF`,borderWidth:+!!e.stacked,backgroundColor:u,yAxisID:e.horizontal?`y`:e.dataSets?.[o].yAxisId||`y`,xAxisID:`x`};r.push(d);let f=e.dataSets?.[o].trend,p=t.trendDataSetsValues?.[o];!f?.display||e.horizontal||!p||a.push(cC(d,f,p))}return r.push(...a),r}function KS(e,t){let{dataSetsValues:n,labels:r}=t,i=e.negativeValuesColor||`#EA6175`,a=e.positiveValuesColor||`#4EA7F2`,o=e.subTotalValuesColor||`#AAAAAA`,s=[],c=[],l={label:``,data:c,backgroundColor:s},u=[],d=0;for(let t of n)if(!t.hidden){for(let l=0;l<t.data.length;l++){let f=t.data[l];if(u.push(r[l]),isNaN(Number(f))){c.push([d,d]),s.push(``);continue}c.push([d,f+d]);let p=f>=0?a:i;l===0&&t===n[0]&&e.firstValueAsSubtotal&&(p=o),s.push(p),d+=f}e.showSubTotals&&(u.push(E(`Subtotal`)),c.push([0,d]),s.push(o))}return{datasets:[l],labels:u}}function qS(e,t){let{dataSetsValues:n,axisType:r,labels:i}=t,a=[],o=!!e.fillArea,s=!!e.stacked,c=[],l=uC(e,n.length);for(let u=0;u<n.length;u++){let{label:d,data:f,hidden:p}=n[u];d=e.dataSets?.[u].label||d;let m=l.next();r&&[`linear`,`time`].includes(r)&&(f=f.map((e,t)=>({x:i[t]||void 0,y:e})));let h={label:d,data:f,hidden:p,tension:0,borderColor:m,backgroundColor:o?Sn(m,Je):m,pointBackgroundColor:m,fill:o?lC(u,s):!1,pointRadius:e.hideDataMarkers?0:3,yAxisID:e.dataSets?.[u].yAxisId||`y`};a.push(h);let g=e.dataSets?.[u].trend,_=t.trendDataSetsValues?.[u];!g?.display||!_||c.push(cC(h,g,_))}return a.push(...c),a}function JS(e,t){let n=qS(e,t);for(let e of n)LS(e.xAxisID)||(e.showLine=!1);return n}function YS(e,t){let{dataSetsValues:n}=t,r=[],i=FS(new In(Math.max(0,...n.map(e=>e?.data?.length??0))),n);for(let{label:t,data:a,hidden:o}of n){if(o)continue;let n={label:t,data:a,borderColor:e.background||`#FFFFFF`,backgroundColor:i,hoverOffset:10};r.push(n)}return r}function XS(e,t){let{dataSetsValues:n}=t,r=[],i=uC(e,n.length),a=[];for(let o=0;o<n.length;o++){let{label:s,data:c,hidden:l}=n[o];s=e.dataSets?.[o].label||s;let u=e.dataSets?.[o],d=i.next(),f=u?.type??`line`,p={label:s,data:c,hidden:l,borderColor:d,backgroundColor:d,yAxisID:e.dataSets?.[o].yAxisId||`y`,xAxisID:`x`,type:f,order:f===`bar`?n.length+o:o,pointRadius:e.hideDataMarkers?0:3};r.push(p);let m=e.dataSets?.[o].trend,h=t.trendDataSetsValues?.[o];!m?.display||!h||a.push(cC(p,m,h))}return r.push(...a),r}function ZS(e,t){let{dataSetsValues:n}=t,r=[],i=e.fillArea??!1,a=uC(e,n.length);for(let t=0;t<n.length;t++){let{label:o,data:s,hidden:c}=n[t];e.dataSets?.[t]?.label&&(o=e.dataSets[t].label);let l=a.next(),u={label:o,data:s,hidden:c,borderColor:l,backgroundColor:l,pointRadius:e.hideDataMarkers?0:3};i&&(u.backgroundColor=Sn(l,Je),u.fill=`start`),r.push(u)}return r}function QS(e,t){let{availableRegions:n,dataSetsValues:r,labels:i}=t,a=e.region||n[0]?.id,o=a?t.getGeoJsonFeatures(a):void 0,s={outline:o,showOutline:!!o,data:[]};if(o&&a){let e={};if(r[0])for(let n=0;n<r[0].data.length;n++){if(!i[n]||r[0].data[n]===void 0)continue;let o=t.geoFeatureNameToId(a,i[n]);o&&(e[o]={value:r[0].data[n],label:i[n]})}for(let t of o)t.id&&s.data.push({feature:{...t,properties:{name:e[t.id]?.label}},value:e[t.id]?.value})}return[s]}function $S(e,t){let n=t.dataSetsValues[0],r=t.labels;if(!n)return[];let{label:i,data:a}=n;return i=e.dataSets?.[0].label||i,[{label:i,data:a.map(e=>e<=0?[0,0]:[-e,e]),backgroundColor:eC(r,e.funnelColors),yAxisID:`y`,xAxisID:`x`,barPercentage:1,categoryPercentage:1,borderColor:e.background||`#FFFFFF`,borderWidth:3}]}function eC(e,t){let n=new In(e.length,t);return e.map(()=>n.next())}function tC(e,t){let{dataSetsValues:n,labels:r}=t,i=aC(rC(n,r)),a=i[0]||[],o=new In(a.length,e.groupColors||[]),s=a.map(e=>({label:e.label,color:o.next()})),c=[];for(let t=i.length-1;t>=0;t--){let n={groupColors:s,parsing:{key:`value`},data:i[t],borderColor:t=>{let n=t.type===`data`?t.raw:void 0;return!n||n.label===`nullValue`?_e:e.background||`#FFFFFF`},backgroundColor:e=>{let t=e.type===`data`?e.raw:void 0;if(!t||t.label===`nullValue`)return _e;let n=t.groups[0];return s.find(e=>e.label===n)?.color},hoverOffset:10};c.push(n)}return c}function nC(e,t){let n=[],r=Math.max(...e.map(e=>e.data.length));for(let i=0;i<r;i++){n[i]={};for(let t=0;t<e.length;t++){let r=e[t].data[i]===null?WS:String(e[t].data[i]);n[i][t]=r}n[i].value=Number(t[i])}return n}function rC(e,t){return iC(nC(e,t),0,e.length,[])}function iC(e,t,n,r){if(t>=n)return[];let i=Object.groupBy(e,e=>e[t]);return Object.keys(i).map(e=>{let a=i[e]?.reduce((e,t)=>e+Number(t.value),0)||0,o=[...r,e];return{label:e,value:a,children:iC(i[e]||[],t+1,n,[...r,e]),groups:o,depth:t}}).sort((e,t)=>t.value-e.value)}function aC(e){let t=[],n=[...e];for(;n.length>0;){let e=n.shift();e&&(t[e.depth]||(t[e.depth]=[]),t[e.depth].push(e),e.children&&n.push(...e.children))}return t}function oC(e,t){let{dataSetsValues:n,labels:r,locale:i,axisFormats:a}=t,o={locale:i,format:a?.y};if(n.length===0)return[];let s=rC(n,r).sort((e,t)=>t.value-e.value),c=dC(e,s),l=[],u=Math.max(...n.map(e=>e.data.length));for(let e=0;e<u;e++){l[e]={};for(let t=0;t<n.length;t++)l[e][t]=n[t].data[e]?String(n[t].data[e]):void 0;l[e].value=Number(r[e])}let d=e.showLabels??US.showLabels,f=e.showValues??US.showValues,p=e.coloringOptions||US.coloringOptions,m;return p?.type===`colorScale`&&(m=fC(s,p)),[{data:[],tree:l,labels:{display:d||f,overflow:`hidden`,...sC(e.valuesDesign,US.valuesDesign),formatter:e=>[d?e.raw.g:void 0,f?L(e.raw.v,o):void 0].filter(C)},captions:{display:e.showHeaders??US.showHeaders,padding:6,...sC(e.headerDesign,US.headerDesign)},key:`value`,groups:S(0,n.length).map(e=>String(e)),borderWidth:0,spacing:1,displayMode:`headerBoxes`,groupColors:c,backgroundColor:t=>{if(t.type!==`data`)return`transparent`;if(!t.raw.isLeaf)return e.headerDesign?.fillColor||US.headerDesign?.fillColor;if(p.type===`colorScale`)return m?.(t.raw.v)||`#FF0000`;if(p.type===`categoryColor`)return pC(t,s,p,c);throw Error(`Unsupported coloring option type}`)}}]}function sC(e,t){let n=e=>{let t=e.element.options.backgroundColor;return fn(t)>.7?`#666666`:`#FFFFFF`};return{align:e?.align??t?.align,position:e?.verticalAlign??t?.verticalAlign,color:e?.color||n,hoverColor:e?.color||n,font:{weight:e?.bold??t?.bold?`bold`:`normal`,style:e?.italic??t?.italic?`italic`:`normal`,size:e?.fontSize??t?.fontSize}}}function cC(e,t,n){let r=hn(e.backgroundColor);r.a=1;let i=t.color||Cn(mn(r),.5);return{type:`line`,xAxisID:t.type===`trailingMovingAverage`?mS:`x1`,yAxisID:e.yAxisID,label:e.label?E(`Trend line for %s`,e.label):``,data:n,order:-1,showLine:!0,pointRadius:0,backgroundColor:i,borderColor:i,borderDash:[5,5],borderWidth:void 0,fill:!1,pointBackgroundColor:i}}function lC(e,t){return t?e===0?`origin`:`-1`:`origin`}function uC(e,t){return new In(t,e.dataSets?.map(e=>e.backgroundColor)||[])}function dC(e,t){let n=e.coloringOptions?.type===`categoryColor`?e.coloringOptions.colors:[],r=new In(t.length,n);return t.map(e=>({label:e.label,color:r.next()}))}function fC(e,t){if(e.length===0)return;let n=aC(e),r=n[n.length-1],i=Math.min(...r.map(e=>e.value)),a=Math.max(...r.map(e=>e.value));if(Number.isFinite(i)&&Number.isFinite(a)){let e=[{value:i,color:t.minColor}];if(t.midColor){let n=(i+a)/2;e.push({value:n,color:t.midColor})}return e.push({value:a,color:t.maxColor}),zn(e)}}function pC(e,t,n,r){let i=e.raw._data.children[0][0],a=r.find(e=>e.label===i)?.color;if(!a||!n.useValueBasedGradient)return a||`#FF0000`;let o=t.find(e=>e.label===i);if(!o||!o.children.length)return a;let s=aC(o.children),c=s[s.length-1],l=Math.max(...c.map(e=>e.value)),u=Math.min(...c.map(e=>e.value));return u===l||!isFinite(u)||!isFinite(l)?a:Cn(a,((Number(e.raw.v)||0)-l)/(u-l)*.5)}let mC={id:`sunburstHoverPlugin`,afterEvent(e,t,n){if(!n.enabled)return;let r=e.getActiveElements(),i=r.map(e=>({datasetIndex:e.datasetIndex,index:e.index}));for(let t of r){let n=e.data.datasets[t.datasetIndex].data[t.index];for(let t=0;t<e.data.datasets.length;t++){let r=e.data.datasets[t];for(let e=0;e<r.data.length;e++){let a=r.data[e];hC(n.groups,a.groups)&&i.push({datasetIndex:t,index:e})}}}i=i.filter(t=>{let{datasetIndex:n,index:r}=t;return e.data.datasets[n].data[r].label!==WS}),e.setActiveElements(i);for(let t of e.getSortedVisibleDatasetMetas())for(let e of t.data){let t=e.$context,{datasetIndex:n,index:r,dataset:a,raw:o}=t;if(o.label===`nullValue`)continue;let s=typeof a.backgroundColor==`function`?a.backgroundColor(t):a.backgroundColor;i.length&&!i.some(e=>e.datasetIndex===n&&e.index===r)?e.options.backgroundColor=Cn(s,.5):e.options.backgroundColor=s}}};function hC(e,t){return t.length>e.length&&e.every((e,n)=>e===t[n])}let gC={id:`sunburstLabelsPlugin`,afterDatasetsDraw(e,t,n){if(!n.showValues&&!n.showLabels||e.config.type!==`doughnut`)return;let r=e.ctx;_C(e,n,r)}};function _C(e,t,n){let r=t.style,i=r.fontSize||13,a=i+3;for(let o of e._metasets)for(let s=0;s<o._dataset.data.length;s++){let c=o._dataset.data[s];if(c.label===`nullValue`)continue;let l=[t.showLabels?c.label:void 0,t.showValues?t.callback(c.value,`y`):void 0].filter(C),u=o.data[s],{startAngle:d,endAngle:f,innerRadius:p,outerRadius:m,circumference:h}=u,g=u.options.offset/4,_=g*(1-Math.sin(Math.min(Math.PI,h||0)));p+=_,m+=_;let v=(d+f)/2,y=(p+m)/2,ee=(m-p)*.9,te=f-d;if((te>=Math.PI?m:Math.sin(te/2)*p*2)<l.length*a)continue;n.save();let ne={x:Math.cos(v)*g,y:Math.sin(v)*g},re=e.chartArea.left+e.chartArea.width/2+ne.x,ie=e.chartArea.top+e.chartArea.height/2+ne.y;n.translate(re,ie);let ae;v>Math.PI/2?(n.rotate(v-Math.PI),ae=-y):(ae=y,n.rotate(v));let oe=u.options.backgroundColor,se=fn(oe)>.7?`#666666`:`#FFFFFF`;n.fillStyle=r.textColor||se,n.textAlign=`center`,n.textBaseline=`middle`,n.font=Zc(i,r.bold,r.italic);let ce=-((l.length-1)*a)/2;for(let e=0;e<l.length;e++){let t=hl(n,ee,l[e],r,`px`);n.fillText(t,ae,ce+e*a)}n.restore()}}let vC={id:`waterfallLinesPlugin`,beforeDraw(e,t,n){if(!n.showConnectorLines)return;let r=e._metasets?.[0]?.data;if(!r)return;let i=e.ctx;i.save(),i.setLineDash([3,2]);for(let e=0;e<r.length;e++){let t=r[e];if(t.height===0)continue;let n=bC(r,e);if(!n)break;let a=yC(t),o=yC(n),s=t.$context.raw,c=s[1]-s[0],l=Math.round(c<0?a.bottom-1:a.top),u=Math.round(a.right),d=Math.round(o.left);i.strokeStyle=`#999`,i.beginPath(),i.moveTo(u+1,l+.5),i.lineTo(d,l+.5),i.stroke()}i.restore()}};function yC(e){let t=e.base<e.y;return{left:e.x-e.width/2,right:e.x+e.width/2,bottom:t?e.base+e.height:e.y+e.height,top:t?e.base:e.y}}function bC(e,t){return e.find((e,n)=>n>t&&e.height!==0)}V`
|
|
20
20
|
.o-spreadsheet {
|
|
@@ -24,7 +24,7 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
24
24
|
z-index: ${1002};
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
|
-
`,lf.add(`chartShowValuesPlugin`,{register:e=>e.register(RS),unregister:e=>e.unregister(RS)}),lf.add(`waterfallLinesPlugin`,{register:e=>e.register(vC),unregister:e=>e.unregister(vC)}),lf.add(`funnelController`,{register:e=>e.register(mf()),unregister:e=>e.unregister(mf())}),lf.add(`funnelElement`,{register:e=>e.register(hf()),unregister:e=>e.unregister(hf())}),lf.add(`funnelTooltipPositioner`,{register:e=>e.Tooltip.positioners.funnelTooltipPositioner=_f,unregister:e=>e.Tooltip.positioners.funnelTooltipPositioner=void 0}),lf.add(`sunburstLabelsPlugin`,{register:e=>e.register(gC),unregister:e=>e.unregister(gC)}),lf.add(`sunburstHoverPlugin`,{register:e=>e.register(mC),unregister:e=>e.unregister(mC)});var xC=class extends t.Component{static template=`o-spreadsheet-ChartJsComponent`;static props={figureUI:Object,isFullScreen:{type:Boolean,optional:!0}};canvas=(0,t.useRef)(`graphContainer`);chart;currentRuntime;animationStore;currentDevicePixelRatio=window.devicePixelRatio;get background(){return this.chartRuntime.background}get canvasStyle(){return`background-color: ${this.background}`}get chartRuntime(){let e=this.env.model.getters.getChartRuntime(this.props.figureUI.id);if(!(`chartJsConfig`in e))throw Error(`Unsupported chart runtime`);return e}setup(){this.env.model.getters.isDashboard()&&(this.animationStore=B(pf)),(0,t.onMounted)(()=>{df();let e=this.chartRuntime;this.currentRuntime=e,this.createChart(b(e.chartJsConfig))}),(0,t.onWillUnmount)(()=>this.chart?.destroy()),(0,t.useEffect)(()=>{let e=this.chartRuntime;e===this.currentRuntime?this.currentDevicePixelRatio!==window.devicePixelRatio&&(this.currentDevicePixelRatio=window.devicePixelRatio,this.updateChartJs(b(this.currentRuntime.chartJsConfig))):(e.chartJsConfig.type===this.currentRuntime.chartJsConfig.type?this.updateChartJs(b(e.chartJsConfig)):(this.chart?.destroy(),this.createChart(b(e.chartJsConfig))),this.currentRuntime=e)})}createChart(e){if(this.env.model.getters.isDashboard()&&this.animationStore){let t=this.env.model.getters.getChart(this.props.figureUI.id)?.type;t&&this.animationStore.animationPlayed[this.animationFigureId]!==t&&(e=this.enableAnimationInChartData(e),this.animationStore.disableAnimationForChart(this.animationFigureId,t))}let t=this.canvas.el.getContext(`2d`);this.chart=new window.Chart(t,e)}updateChartJs(e){if(this.env.model.getters.isDashboard()){let t=this.env.model.getters.getChart(this.props.figureUI.id)?.type;t&&this.hasChartDataChanged()&&this.animationStore&&(e=this.enableAnimationInChartData(e),this.animationStore.disableAnimationForChart(this.animationFigureId,t))}e.data&&e.data.datasets?(this.chart.data=e.data,e.options?.plugins?.title&&(this.chart.config.options.plugins.title=e.options.plugins.title)):this.chart.data.datasets=[],this.chart.config.options=e.options,this.chart.update()}hasChartDataChanged(){return!w(this.getChartDataInRuntime(this.currentRuntime),this.getChartDataInRuntime(this.chartRuntime))}getChartDataInRuntime(e){let t=e.chartJsConfig.data;return{labels:t.labels,dataset:t.datasets.map(e=>({data:e.data,label:e.label,tree:e.tree}))}}enableAnimationInChartData(e){return{...e,options:{...e.options,animation:{animateRotate:!0}}}}get animationFigureId(){return this.props.isFullScreen?this.props.figureUI.id+`-fullscreen`:this.props.figureUI.id}},SC=class{sheetId;title;getters;constructor(e,t,n){this.title=e.title,this.sheetId=t,this.getters=n}static validateChartDefinition(e,t){throw Error(`This method should be implemented by sub class`)}static transformDefinition(e,t,n){throw Error(`This method should be implemented by sub class`)}static getDefinitionFromContextCreation(e){throw Error(`This method should be implemented by sub class`)}};function CC(e,t,n,r,i){if(!e)return``;if(n===`text`||t?.type!==`number`||e.type!==`number`)return r?Fo(e,i):e.formattedValue;let{value:a,format:o}=e;return n===`progress`?(a=t.value/a,o=`0.0%`):(a=Math.abs(t.value-a),n===`percentage`&&a!==0&&(a/=e.value),n===`percentage`&&(o=`0.0%`),o||(a=Math.round(a*100)/100)),r?Fo({value:a,format:o},i):L(a,{format:o,locale:i})}function wC(e,t,n){return e?t?Fo(e,n):e.formattedValue??String(e.value??``):``}function TC(e,t,n,r,i){if(t===`text`||t===`progress`||e?.type!==`number`||n?.type!==`number`)return;let a=n.value-e.value;if(a>0)return r;if(a<0)return i}function EC(e,t,n){if(n===`text`||e?.type!==`number`||t?.type!==`number`)return`neutral`;let r=t.value-e.value;return r>0?`up`:r<0?`down`:`neutral`}function DC(e){return e.keyValue&&!fc.test(e.keyValue)?`InvalidScorecardKeyValue`:`Success`}function OC(e){return e.baseline&&!fc.test(e.baseline)?`InvalidScorecardBaseline`:`Success`}let kC=new window.Path2D(`M8.6 4.8a.5.5 0 0 1 0 .75l-3.9 3.9a.5 .5 0 0 1 -.75 0l-3.8 -3.9a.5 .5 0 0 1 0 -.75l.4-.4a.5.5 0 0 1 .75 0l2.3 2.4v-5.7c0-.25.25-.5.5-.5h.6c.25 0 .5.25.5.5v5.8l2.3 -2.4a.5.5 0 0 1 .75 0z`),AC=new window.Path2D(`M8.7 5.5a.5.5 0 0 0 0-.75l-3.8-4a.5.5 0 0 0-.75 0l-3.8 4a.5.5 0 0 0 0 .75l.4.4a.5.5 0 0 0 .75 0l2.3-2.4v5.8c0 .25.25.5.5.5h.6c.25 0 .5-.25.5-.5v-5.8l2.2 2.4a.5.5 0 0 0 .75 0z`);var jC=class e extends SC{keyValue;keyDescr;baseline;baselineMode;baselineDescr;progressBar=!1;background;baselineColorUp;baselineColorDown;fontColor;humanize;type=`scorecard`;constructor(e,t,n){super(e,t,n),this.keyValue=Dc(n,t,e.keyValue),this.keyDescr=e.keyDescr,this.baseline=Dc(n,t,e.baseline),this.baselineMode=e.baselineMode,this.baselineDescr=e.baselineDescr,this.background=e.background,this.baselineColorUp=e.baselineColorUp??`#43C5B1`,this.baselineColorDown=e.baselineColorDown??`#EA6175`,this.humanize=e.humanize??!1}static validateChartDefinition(e,t){return e.checkValidations(t,DC,OC)}static getDefinitionFromContextCreation(e){return{background:e.background,type:`scorecard`,keyValue:e.range?.[0]?.dataRange,title:e.title||{text:``},baselineMode:Ge,baselineColorUp:Ke,baselineColorDown:qe,baseline:e.auxiliaryRange||``}}static transformDefinition(e,t,n){let r,i;if(t.baseline){let{changeType:i,range:a}=uS(e,t.baseline,n);i!==`REMOVE`&&(r=a)}if(t.keyValue){let{changeType:r,range:a}=uS(e,t.keyValue,n);r!==`REMOVE`&&(i=a)}return{...t,baseline:r,keyValue:i}}duplicateInDuplicatedSheet(t){let n=vS(this.sheetId,t,this.baseline),r=vS(this.sheetId,t,this.keyValue);return new e(this.getDefinitionWithSpecificRanges(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue)}getContextCreation(){return{...this,range:this.keyValue?[{dataRange:this.getters.getRangeString(this.keyValue,this.sheetId)}]:void 0,auxiliaryRange:this.baseline?this.getters.getRangeString(this.baseline,this.sheetId):void 0}}getDefinitionWithSpecificRanges(e,t,n){return{baselineColorDown:this.baselineColorDown,baselineColorUp:this.baselineColorUp,baselineMode:this.baselineMode,title:this.title,type:`scorecard`,background:this.background,baseline:e?this.getters.getRangeString(e,n||this.sheetId):void 0,baselineDescr:this.baselineDescr,keyValue:t?this.getters.getRangeString(t,n||this.sheetId):void 0,keyDescr:this.keyDescr,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let n=yS(this.baseline,t),r=yS(this.keyValue,t);return this.baseline===n&&this.keyValue===r?this:new e(this.getDefinitionWithSpecificRanges(n,r),this.sheetId,this.getters)}};function MC(e,t){let n=t.getContext(`2d`),r=window.devicePixelRatio||1;t.width=r*e.canvas.width,t.height=r*e.canvas.height,n.scale(r,r);let i=e.canvas.width-20;if(n.fillStyle=e.canvas.backgroundColor,n.fillRect(0,0,e.canvas.width,e.canvas.height),e.title){n.font=e.title.style.font,n.fillStyle=e.title.style.color;let t=n.textBaseline;n.textBaseline=`middle`,n.fillText(pl(n,e.title.text,i-e.title.position.x),e.title.position.x,e.title.position.y),n.textBaseline=t}if(e.baseline&&(n.font=e.baseline.style.font,n.fillStyle=e.baseline.style.color,ml(n,e.baseline.text,e.baseline.position,e.baseline.style.underline,e.baseline.style.strikethrough)),e.baselineArrow&&e.baselineArrow.style.size>0){n.save(),n.fillStyle=e.baselineArrow.style.color,n.translate(e.baselineArrow.position.x,e.baselineArrow.position.y);let t=e.baselineArrow.style.size/10;switch(n.scale(t,t),e.baselineArrow.direction){case`down`:n.fill(kC);break;case`up`:n.fill(AC);break}n.restore()}if(e.baselineDescr){let t=e.baselineDescr;n.font=t.style.font,n.fillStyle=t.style.color,n.fillText(pl(n,t.text,i-t.position.x),t.position.x,t.position.y)}if(e.key&&(n.font=e.key.style.font,n.fillStyle=e.key.style.color,ml(n,pl(n,e.key.text,i-e.key.position.x),e.key.position,e.key.style.underline,e.key.style.strikethrough)),e.keyDescr){let t=e.keyDescr;n.font=e.keyDescr?.style.font??t.style.font,n.fillStyle=t.style.color,n.fillText(pl(n,t.text,i-t.position.x),t.position.x,t.position.y)}if(e.progressBar){if(n.fillStyle=e.progressBar.style.backgroundColor,n.beginPath(),n.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width,e.progressBar.dimension.height,e.progressBar.dimension.height/2),n.fill(),n.fillStyle=e.progressBar.style.color,n.beginPath(),e.progressBar.value>0)n.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width*Math.max(0,Math.min(1,e.progressBar.value)),e.progressBar.dimension.height,e.progressBar.dimension.height/2);else{let t=e.progressBar.dimension.width*Math.max(0,Math.min(1,-e.progressBar.value));n.roundRect(e.progressBar.position.x+e.progressBar.dimension.width-t,e.progressBar.position.y,t,e.progressBar.dimension.height,e.progressBar.dimension.height/2)}n.fill()}}function NC(e,t){let n=``,r,i=t.getLocale();if(e.keyValue){let a={sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top};r=t.getEvaluatedCell(a),n=wC(r,e.humanize??!1,i)}let a,o=e.baseline;if(o){let e={sheetId:o.sheetId,col:o.zone.left,row:o.zone.top};a=t.getEvaluatedCell(e)}let{background:s,fontColor:c}=t.getStyleOfSingleCellChart(e.background,e.keyValue),l=CC(a,r,e.baselineMode,e.humanize??!1,i),u=e.baselineMode===`progress`&&Pi(l,i)?M(l,i):0;return{title:{...e.title,text:e.title.text?E(e.title.text):``},keyValue:n,keyDescr:e.keyDescr?.text?E(e.keyDescr.text):``,baselineDisplay:l,baselineArrow:EC(a,r,e.baselineMode),baselineColor:TC(a,e.baselineMode,r,e.baselineColorUp,e.baselineColorDown),baselineDescr:e.baselineMode!==`progress`&&e.baselineDescr?.text?E(e.baselineDescr.text):``,fontColor:c,background:s,baselineStyle:{...e.baselineMode!==`percentage`&&e.baselineMode!==`progress`&&o?t.getCellComputedStyle({sheetId:o.sheetId,col:o.zone.left,row:o.zone.top}):void 0,fontSize:e.baselineDescr?.fontSize,align:e.baselineDescr?.align},baselineDescrStyle:{textColor:e.baselineDescr?.color,...e.baselineDescr},keyValueStyle:{...e.keyValue?t.getCellComputedStyle({sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top}):void 0,fontSize:e.keyDescr?.fontSize,align:e.keyDescr?.align},keyValueDescrStyle:{textColor:e.keyDescr?.color,...e.keyDescr},progressBar:e.baselineMode===`progress`?{value:u,color:u>0?e.baselineColorUp:e.baselineColorDown}:void 0}}let PC=.05;function FC(e,t){let n=e||``;return t&&n?` `+n:n}function IC({width:e,height:t},n){return new LC({width:e,height:t},n).computeDesign()}var LC=class{context;width;height;constructor({width:e,height:t},n){this.runtime=n;let r=document.createElement(`canvas`);this.width=r.width=e,this.height=r.height=t,this.context=r.getContext(`2d`)}computeDesign(){let e={canvas:{width:this.width,height:this.height,backgroundColor:this.backgroundColor}},t=this.getTextStyles(),n=0;if(this.title){let r,i;switch({height:n,width:i}=this.getFullTextDimensions(this.title,t.title.font),this.runtime.title.align){case`center`:r=(this.width-i)/2;break;case`right`:r=this.width-i-20;break;default:r=20}e.title={text:this.title,style:t.title,position:{x:r,y:10+n/2}}}let r=t.baselineArrow?.size??0,{height:i,width:a}=this.getTextDimensions(this.baseline,t.baselineValue.font);this.baseline||(i=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).height);let o=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).width,s;switch(this.runtime.baselineStyle?.align){case`right`:s=this.width-20-o-a;break;case`left`:s=20+r;break;default:s=(this.width-a-o+r)/2}if(this.baseline&&(e.baseline={text:this.baseline,style:t.baselineValue,position:{x:s,y:this.keyValue?this.height*(1-PC*(this.runtime.progressBar?1:2)):this.height-(this.height-n-i)/2-10}},t.baselineArrow&&!this.runtime.progressBar&&(e.baselineArrow={direction:this.baselineArrow,style:t.baselineArrow,position:{x:e.baseline.position.x-r,y:e.baseline.position.y-(i+r)/2}})),e.baseline&&this.baselineDescr){let n={x:e.baseline.position.x+a,y:e.baseline.position.y};e.baselineDescr={text:this.baselineDescr,style:t.baselineDescr,position:n}}let c=0;this.runtime.progressBar&&(c=this.height*.05,e.progressBar={position:{x:40,y:this.height*(1-2*PC)-i-c},dimension:{height:c,width:this.width-80},value:this.runtime.progressBar.value,style:{color:this.runtime.progressBar.color,backgroundColor:this.secondaryFontColor}});let{width:l,height:u}=this.getFullTextDimensions(this.keyValue,t.keyValue.font),d=this.getTextDimensions(this.keyDescr,t.keyDescr.font).width,f;switch(this.runtime.keyValueStyle?.align){case`right`:f=this.width-20-d-l;break;case`left`:f=20;break;default:f=(this.width-l-d)/2}if(this.keyValue&&(e.key={text:this.keyValue,style:t.keyValue,position:{x:Math.max(20,f),y:this.height*(.5-PC*2)+10/2+(n+u/2)/2}}),e.key&&this.keyDescr){let n={x:e.key.position.x+l,y:e.key.position.y};e.keyDescr={text:this.keyDescr,style:t.keyDescr,position:n}}return e}get title(){return this.runtime.title.text??``}get keyValue(){return this.runtime.keyValue}get keyDescr(){return FC(this.runtime.keyDescr,this.keyValue)}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){return FC(this.runtime.baselineDescr,this.baseline)}get baselineArrow(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get secondaryFontColor(){return ES(this.backgroundColor)}getTextDimensions(e,t){this.context.font=t;let n=this.context.measureText(e);return{width:n.width,height:n.actualBoundingBoxAscent+n.actualBoundingBoxDescent}}getFullTextDimensions(e,t){this.context.font=t;let n=this.context.measureText(e);return{width:n.width,height:n.fontBoundingBoxAscent+n.fontBoundingBoxDescent}}getTextStyles(){let e=this.runtime.keyValueStyle?.fontSize??32,t=Math.floor(.9*e),n=this.runtime.baselineStyle?.fontSize??16,r=Math.floor(.9*n);return this.runtime.progressBar&&(n/=1.5),{title:{font:Zc(this.runtime.title.fontSize??14,this.runtime.title.bold,this.runtime.title.italic),color:this.runtime.title.color??this.secondaryFontColor},keyValue:{color:this.runtime.keyValueStyle?.textColor||this.runtime.fontColor,font:Zc(e,this.runtime.keyValueStyle?.bold,this.runtime.keyValueStyle?.italic),strikethrough:this.runtime.keyValueStyle?.strikethrough,underline:this.runtime.keyValueStyle?.underline},keyDescr:{color:this.runtime.keyValueDescrStyle?.textColor||this.runtime.fontColor,font:Zc(t,this.runtime.keyValueDescrStyle?.bold,this.runtime.keyValueDescrStyle?.italic),strikethrough:this.runtime.keyValueDescrStyle?.strikethrough,underline:this.runtime.keyValueDescrStyle?.underline},baselineValue:{font:Zc(n,this.runtime.baselineStyle?.bold,this.runtime.baselineStyle?.italic),strikethrough:this.runtime.baselineStyle?.strikethrough,underline:this.runtime.baselineStyle?.underline,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor},baselineDescr:{font:Zc(r,this.runtime.baselineDescrStyle?.bold,this.runtime.baselineDescrStyle?.italic),strikethrough:this.runtime.baselineDescrStyle?.strikethrough,underline:this.runtime.baselineDescrStyle?.underline,color:this.runtime.baselineDescrStyle?.textColor??this.secondaryFontColor},baselineArrow:this.baselineArrow===`neutral`||this.runtime.progressBar?void 0:{size:this.keyValue?.8*n:0,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor}}}},RC=class extends t.Component{static template=`o-spreadsheet-ScorecardChart`;static props={figureUI:Object};canvas=(0,t.useRef)(`chartContainer`);get runtime(){return this.env.model.getters.getChartRuntime(this.props.figureUI.id)}get title(){return E(this.env.model.getters.getChartDefinition(this.props.figureUI.id).title.text??``)}setup(){(0,t.useEffect)(this.createChart.bind(this),()=>{let e=this.canvas.el.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}createChart(){let e=this.canvas.el;MC(IC(e.getBoundingClientRect(),this.runtime),e)}};let zC=/Mac/i,BC=[`Shift`,`Control`,`Alt`,`Meta`];function VC(e,t){return e?!!t.target&&e.contains(t.target):!1}function HC(){let e=document.querySelector(`.o-grid-overlay`);if(e){let{top:t,left:n}=e.getBoundingClientRect();return{top:t,left:n}}throw Error(`Can't find spreadsheet position`)}function UC(e){return e.el?WC(e.el):{x:0,y:0,width:0,height:0}}function WC(e){let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function*GC(e){if(yield e,e.hasChildNodes())for(let t of e.childNodes)yield*GC(t)}function KC(){return Array.from(document.querySelectorAll(`.o-spreadsheet .o-menu`))}function qC(e){let{startElement:t,endElement:n,startSelectionOffset:r,endSelectionOffset:i}=JC(e);return{start:YC(e,t,r),end:YC(e,n,i)}}function JC(e){let t=document.getSelection();return{startElement:t.anchorNode||e,startSelectionOffset:t.anchorOffset,endElement:t.focusNode||e,endSelectionOffset:t.focusOffset}}function YC(e,t,n){let r=0,i=GC(e),a=i.next(),o=!0;for(;!a.done&&a.value!==t;)a.value.hasChildNodes()||a.value.textContent&&(r+=a.value.textContent.length),(a.value.nodeName===`P`||a.value.nodeName===`DIV`&&a.value!==e)&&(o?o=!1:r++),a=i.next();if(a.value!==t)return 0;if(!a.value.hasChildNodes())r+=n;else{let e=[...a.value.childNodes].slice(0,n);r+=e.reduce((t,n,r)=>{if(n.textContent!==null){let i=n.textContent.length;return n.nodeName===`P`&&r!==e.length-1&&i++,t+i}else return t},0)}return t.nodeName===`P`&&!o&&t.textContent===``&&r++,r}let XC=/^[a-zA-Z]$/;function ZC(e,t=`key`){let n=``;BC.includes(e.key)||($C(e)&&(n+=`Ctrl+`),e.altKey&&(n+=`Alt+`),e.shiftKey&&(n+=`Shift+`));let r=t===`key`?e.key:e.code;return n+=XC.test(r)?r.toUpperCase():r,n}function QC(){return!!zC.test(navigator.userAgent)}function $C(e){return QC()||ow()?e.metaKey:e.ctrlKey}function ew(e){return e.button===1||$C(e)&&e.button===0}async function tw(e){return new Promise((t,n)=>{let r=new Image;r.addEventListener(`load`,()=>{let e=document.createElement(`canvas`);e.width=r.width,e.height=r.height,e.getContext(`2d`)?.drawImage(r,0,0),e.toBlob(t,`image/png`)}),r.addEventListener(`error`,n),r.src=e})}function nw(e,t){let n=document.createElement(`a`);n.href=e,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n)}function rw(){return/Firefox/i.test(navigator.userAgent)}function iw(){return navigator.maxTouchPoints||1}function aw(){return/Android/i.test(navigator.userAgent)}function ow(){return/(iPad|iPhone|iPod)/i.test(navigator.userAgent)||navigator.platform===`MacIntel`&&iw()>1}function sw(){return/(webOS|BlackBerry|Windows Phone)/i.test(navigator.userAgent)}function cw(){return aw()||ow()||sw()}function lw(e){return e=sn(e).replace(`#`,``),e.length===8?e.slice(6)+e.slice(0,6):e}let uw=`#F3F2F1`;function dw(e,t){let n=e.getBoundingClientRect(),r=window.devicePixelRatio||1;e.width=r*n.width,e.height=r*n.height;let i=e.getContext(`2d`);i.scale(r,r);let a=_w(n,t,i);pw(i,a),fw(i,a),hw(i,a),mw(i,a),gw(i,a)}function fw(e,t){e.save();let n=t.gauge,r=n.rect.x+n.rect.width/2,i=n.rect.y+n.rect.height,a=n.rect.height-n.arcWidth/2;if(a<0)return;let o=n.percentage===1?0:Math.PI*(1+n.percentage);e.strokeStyle=uw,e.beginPath(),e.lineWidth=n.arcWidth,e.arc(r,i,a,o,0),e.stroke(),e.strokeStyle=n.color,e.beginPath(),e.arc(r,i,a,Math.PI,o),e.stroke(),e.restore()}function pw(e,t){e.save(),e.fillStyle=t.backgroundColor,e.fillRect(0,0,t.width,t.height),e.restore()}function mw(e,t){for(let n of[t.minLabel,t.maxLabel,t.gaugeValue])e.save(),e.textAlign=`center`,e.fillStyle=n.color,e.font=`${n.fontSize}px ${He}`,e.fillText(n.label,n.textPosition.x,n.textPosition.y),e.restore()}function hw(e,t){let{x:n,y:r,width:i,height:a}=t.gauge.rect;for(let o of t.inflectionValues){e.save(),e.translate(n+i/2-.5,r+a-.5),e.rotate(Math.PI/2-o.rotation),e.lineWidth=2,e.strokeStyle=ES(t.backgroundColor)+`aa`,e.beginPath(),e.moveTo(0,-(a-t.gauge.arcWidth)),e.lineTo(0,-a-3),e.stroke(),e.textAlign=`center`,e.font=`${o.fontSize}px ${He}`,e.fillStyle=o.color;let s=-a-6-o.offset;e.fillText(o.label,0,s),e.restore()}}function gw(e,t){e.save();let n=t.title;e.font=Zc(n.fontSize,n.bold,n.italic),e.textBaseline=`middle`,e.fillStyle=n.color,e.fillText(n.label,n.textPosition.x,n.textPosition.y),e.restore()}function _w(e,t,n){let r=t.maxValue,i=t.minValue,a=Tw(t,`animated`),o=vw(e,t.title.text),s=o.width/6,c=a?(a-i.value)/(r.value-i.value):0,l={x:e.width/2,y:o.y+o.height-o.height/12},u=80;o.height<300&&(u*=o.height/300);let d=o.width/2,f=t.gaugeValue?.label||`-`;$c(n,f,{fontSize:u},`px`)>d&&(u=ll(d,u,e=>$c(n,f,{fontSize:e},`px`)));let p={x:o.x+s/2,y:o.y+o.height+12},m={x:o.x+o.width-s/2,y:o.y+o.height+12},h=ES(t.background),g=yw(t,o,h,n),_=0,v=0,y=0;switch(t.title.text&&({width:v,height:y}=nl(n,t.title.text,{fontSize:16,...t.title},`px`)),t.title.align){case`right`:_=e.width-v-20;break;case`center`:_=(e.width-v)/2;break;default:_=20;break}return{width:e.width,height:e.height,title:{label:t.title.text??``,fontSize:t.title.fontSize??16,textPosition:{x:_,y:15+y/2},color:t.title.color??h,bold:t.title.bold,italic:t.title.italic},backgroundColor:t.background,gauge:{rect:o,arcWidth:s,percentage:x(c,0,1),color:bw(t)},inflectionValues:g,gaugeValue:{label:f,textPosition:l,fontSize:u,color:h},minLabel:{label:t.minValue.label,textPosition:p,fontSize:12,color:h},maxLabel:{label:t.maxValue.label,textPosition:m,fontSize:12,color:h}}}function vw(e,t){let n=t?25:0,r=e.height-20-n-10,i=e.width-60,a,o;return i>2*r?(a=2*r,o=r):(a=i,o=i/2),{x:30+(i-a)/2,y:n+10+(r-o)/2,width:a,height:o}}function yw(e,t,n,r){let i=e.maxValue,a=e.minValue,o={x:t.x+t.width/2,y:t.y+t.height},s={fontSize:12},c=[],l=[];for(let u of e.inflectionValues){let e=(u.value-a.value)/(i.value-a.value),d=$c(r,u.label,s,`px`),f=Math.PI-Math.PI*e,p=ww(f,t.height+6,o.x,o.y,d+2,12),m=l.some(e=>Cw(e,p))?12:0;l.push(p),c.push({rotation:f,label:u.label,fontSize:12,color:n,offset:m})}return c}function bw(e){let t=Tw(e,`final`);if(t===void 0)return uw;for(let n=0;n<e.inflectionValues.length;n++){let r=e.inflectionValues[n];if(r.operator===`<`&&t<r.value||r.operator===`<=`&&t<=r.value)return e.colors[n]}return e.colors.at(-1)}function xw(e){return[{start:e.topLeft,end:e.topRight},{start:e.topRight,end:e.bottomRight},{start:e.bottomRight,end:e.bottomLeft},{start:e.bottomLeft,end:e.topLeft}]}function Sw(e,t){let n=e.start,r=e.end,i=t.start,a=t.end;function o(e,t,n){return(n.y-e.y)*(t.x-e.x)>(t.y-e.y)*(n.x-e.x)}return o(n,i,a)!==o(r,i,a)&&o(n,r,i)!==o(n,r,a)}function Cw(e,t){let n=xw(e),r=xw(t);for(let e of n)for(let t of r)if(Sw(e,t))return!0;return!1}function ww(e,t,n,r,i,a){let o=Math.cos(e),s=Math.sin(e),c=o*t,l=s*t,u=i/2*s,d=i/2*o,f={x:c+u+n,y:r-(l-d)},p={x:c-u+n,y:r-(l+d)},m=o*(t+a),h=s*(t+a),g={x:m-u+n,y:r-(h+d)};return{bottomLeft:p,bottomRight:f,topRight:{x:m+u+n,y:r-(h-d)},topLeft:g}}function Tw(e,t){return t===`animated`&&e.animationValue!==void 0?e.animationValue:e.gaugeValue?.value}let Ew={responsive:!0,maintainAspectRatio:!1,elements:{line:{fill:!1},point:{hitRadius:15}},animation:!1,events:[`mousemove`,`mouseout`,`click`,`touchstart`,`touchmove`,`mouseup`]};function Dw(e,t,n){let r=document.createElement(`div`);r.style.width=`${t.width}px`,r.style.height=`${t.height}px`;let i=document.createElement(`canvas`);r.append(i),i.setAttribute(`width`,t.width.toString()),i.setAttribute(`height`,t.height.toString());let a;if(document.body.append(r),`chartJsConfig`in e){let t=uf();t||df();let n=b(e.chartJsConfig);n.plugins=[kw];let r=new globalThis.Chart(i,n);a=r.toBase64Image(),r.destroy(),t||ff()}else n===`scorecard`?(MC(IC(t,e),i),a=i.toDataURL()):n===`gauge`&&(dw(i,e),a=i.toDataURL());return r.remove(),a}async function Ow(e,t,n){let r=document.createElement(`div`);r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.position=`fixed`,r.style.opacity=`0`;let i=document.createElement(`canvas`);r.append(i),i.setAttribute(`width`,t.width.toString()),i.setAttribute(`height`,t.height.toString()),document.body.append(r);let a=null;if(`chartJsConfig`in e){let t=uf();t||df();let n=b(e.chartJsConfig);n.plugins=[kw];let r=new globalThis.Chart(i,n);a=await new Promise(e=>i.toBlob(e,`image/png`)),r.destroy(),t||ff()}else n===`scorecard`?(MC(IC(t,e),i),a=await new Promise(e=>i.toBlob(e,`image/png`))):n===`gauge`&&(dw(i,e),a=await new Promise(e=>i.toBlob(e,`image/png`)));return r.remove(),a?new File([a],`chart.png`,{type:`image/png`}):void 0}let kw={id:`customCanvasBackgroundColor`,beforeDraw:e=>{let{ctx:t}=e;t.save(),t.globalCompositeOperation=`destination-over`,t.fillStyle=`#ffffff`,t.fillRect(0,0,e.width,e.height),t.restore()}},Aw={Errors:{InvalidRange:E(`The range is invalid`),FirstArgMissing:E(`The argument is missing. Please provide a value`),SecondArgMissing:E(`The second argument is missing. Please provide a value`),MinNaN:E(`The minpoint must be a number`),MidNaN:E(`The midpoint must be a number`),MaxNaN:E(`The maxpoint must be a number`),ValueUpperInflectionNaN:E(`The first value must be a number`),ValueLowerInflectionNaN:E(`The second value must be a number`),MinBiggerThanMax:E(`Minimum must be smaller then Maximum`),MinBiggerThanMid:E(`Minimum must be smaller then Midpoint`),MidBiggerThanMax:E(`Midpoint must be smaller then Maximum`),LowerBiggerThanUpper:E(`Lower inflection point must be smaller than upper inflection point`),MinInvalidFormula:E(`Invalid Minpoint formula`),MaxInvalidFormula:E(`Invalid Maxpoint formula`),MidInvalidFormula:E(`Invalid Midpoint formula`),ValueUpperInvalidFormula:E(`Invalid upper inflection point formula`),ValueLowerInvalidFormula:E(`Invalid lower inflection point formula`),EmptyRange:E(`A range needs to be defined`),ValueCellIsInvalidFormula:E(`At least one of the provided values is an invalid formula`),Unexpected:E(`The rule is invalid for an unknown reason`)},ColorScale:E(`Color scale`),IconSet:E(`Icon set`),DataBar:E(`Data bar`)},jw={Series:E(`Series`),BackgroundColor:E(`Background color`),StackedBarChart:E(`Stacked bar chart`),StackedLineChart:E(`Stacked line chart`),StackedAreaChart:E(`Stacked area chart`),StackedColumnChart:E(`Stacked column chart`),CumulativeData:E(`Cumulative data`),TreatLabelsAsText:E(`Treat labels as text`),AggregatedChart:E(`Aggregate`),Errors:{Unexpected:E(`The chart definition is invalid for an unknown reason`),InvalidDataSet:E(`The dataset is invalid`),InvalidLabelRange:E(`Labels are invalid`),InvalidScorecardKeyValue:E(`The key value is invalid`),InvalidScorecardBaseline:E(`The baseline value is invalid`),InvalidGaugeDataRange:E(`The data range is invalid`),EmptyGaugeRangeMin:E(`A minimum range limit value is needed`),GaugeRangeMinNaN:E(`The minimum range limit value must be a number`),EmptyGaugeRangeMax:E(`A maximum range limit value is needed`),GaugeRangeMaxNaN:E(`The maximum range limit value must be a number`),GaugeLowerInflectionPointNaN:E(`The lower inflection point value must be a number`),GaugeUpperInflectionPointNaN:E(`The upper inflection point value must be a number`)},GeoChart:{ColorScales:{blues:E(`Blues`),cividis:E(`Cividis`),greens:E(`Greens`),greys:E(`Greys`),oranges:E(`Oranges`),purples:E(`Purples`),rainbow:E(`Rainbow`),reds:E(`Reds`),viridis:E(`Viridis`)}}},Mw={Custom:E(`Custom`)},Nw=E(`Merged cells are preventing this operation. Unmerge those cells and try again.`),Pw=E(`The header row of a table can't be moved.`),Fw={Errors:{Unexpected:E(`Cannot split the selection for an unknown reason`),NoSplitSeparatorInSelection:E(`There is no match for the selected separator in the selection`),MoreThanOneColumnSelected:E(`Only a selection from a single column can be split`),SplitWillOverwriteContent:E(`Splitting will overwrite existing content`)}},Iw={Errors:{Unexpected:E(`Cannot remove duplicates for an unknown reason`),MoreThanOneRangeSelected:E(`Please select only one range of cells`),EmptyTarget:E(`Please select a range of cells containing values.`),NoColumnsProvided:E(`Please select at latest one column to analyze.`),WillRemoveExistingMerge:E(`This operation is not possible due to a merge. Please remove the merges first than try again.`)}},G={DateIs:{today:E(`today`),yesterday:E(`yesterday`),tomorrow:E(`tomorrow`),lastWeek:E(`in the past week`),lastMonth:E(`in the past month`),lastYear:E(`in the past year`)},DateIsBefore:{today:E(`today`),yesterday:E(`yesterday`),tomorrow:E(`tomorrow`),lastWeek:E(`one week ago`),lastMonth:E(`one month ago`),lastYear:E(`one year ago`)},CriterionError:{notEmptyValue:E(`The value must not be empty`),numberValue:E(`The value must be a number`),dateValue:E(`The value must be a date`),validRange:E(`The value must be a valid range`),validFormula:E(`The formula must be valid`)},Errors:{InvalidRange:E(`The range is invalid.`),InvalidDataValidationCriterionValue:E(`One or more of the provided criteria values are invalid. Please review and correct them.`),InvalidNumberOfCriterionValues:E(`One or more of the provided criteria values are missing.`),Unexpected:E(`The rule is invalid for an unknown reason.`)}},Lw={Errors:{Unexpected:E(`The table zone is invalid for an unknown reason`),TableOverlap:E(`You cannot create overlapping tables.`),NonContinuousTargets:E(`A table can only be created on a continuous selection.`),InvalidRange:E(`The range is invalid`),TargetOutOfSheet:E(`The range is out of the sheet`)},Checkboxes:{hasFilters:E(`Filter button`),headerRow:E(`Header row(s)`),bandedRows:E(`Banded rows`),firstColumn:E(`First column`),lastColumn:E(`Last column`),bandedColumns:E(`Banded columns`),automaticAutofill:E(`Automatically autofill formulas`),totalRow:E(`Total row`),isDynamic:E(`Auto-adjust to formula result`)},Tooltips:{filterWithoutHeader:E(`Cannot have filters without a header row`),isDynamic:E(`For tables based on array formulas only`)}},Rw={labels:{no_calculations:E(`No calculations`),"%_of_grand_total":E(`% of grand total`),"%_of_col_total":E(`% of column total`),"%_of_row_total":E(`% of row total`),"%_of":E(`% of`),"%_of_parent_row_total":E(`% of parent row total`),"%_of_parent_col_total":E(`% of parent column total`),"%_of_parent_total":E(`% of parent total`),difference_from:E(`Difference from`),"%_difference_from":E(`% difference from`),running_total:E(`Running total`),"%_running_total":E(`% Running total`),rank_asc:E(`Rank smallest to largest`),rank_desc:E(`Rank largest to smallest`),index:E(`Index`)},descriptions:{"%_of_grand_total":()=>E(`Displayed as % of grand total`),"%_of_col_total":()=>E(`Displayed as % of column total`),"%_of_row_total":()=>E(`Displayed as % of row total`),"%_of":e=>E(`Displayed as % of "%s"`,e),"%_of_parent_row_total":e=>E(`Displayed as % of parent row total of "%s"`,e),"%_of_parent_col_total":()=>E(`Displayed as % of parent column total`),"%_of_parent_total":e=>E(`Displayed as % of parent "%s" total`,e),difference_from:e=>E(`Displayed as difference from "%s"`,e),"%_difference_from":e=>E(`Displayed as % difference from "%s"`,e),running_total:e=>E(`Displayed as running total based on "%s"`,e),"%_running_total":e=>E(`Displayed as % running total based on "%s"`,e),rank_asc:e=>E(`Displayed as rank from smallest to largest based on "%s"`,e),rank_desc:e=>E(`Displayed as rank largest to smallest based on "%s"`,e),index:()=>E(`Displayed as index`)},documentation:{no_calculations:E(`Displays the value that is entered in the field.`),"%_of_grand_total":E(`Displays values as a percentage of the grand total of all the values or data points in the report.`),"%_of_col_total":E(`Displays all the values in each column or series as a percentage of the total for the column or series.`),"%_of_row_total":E(`Displays the value in each row or category as a percentage of the total for the row or category.`),"%_of":E(`Displays values as a percentage of the value of the Base item in the Base field.`),"%_of_parent_row_total":E(`Calculates values as follows:
|
|
27
|
+
`,lf.add(`chartShowValuesPlugin`,{register:e=>e.register(RS),unregister:e=>e.unregister(RS)}),lf.add(`waterfallLinesPlugin`,{register:e=>e.register(vC),unregister:e=>e.unregister(vC)}),lf.add(`funnelController`,{register:e=>e.register(mf()),unregister:e=>e.unregister(mf())}),lf.add(`funnelElement`,{register:e=>e.register(hf()),unregister:e=>e.unregister(hf())}),lf.add(`funnelTooltipPositioner`,{register:e=>e.Tooltip.positioners.funnelTooltipPositioner=_f,unregister:e=>e.Tooltip.positioners.funnelTooltipPositioner=void 0}),lf.add(`sunburstLabelsPlugin`,{register:e=>e.register(gC),unregister:e=>e.unregister(gC)}),lf.add(`sunburstHoverPlugin`,{register:e=>e.register(mC),unregister:e=>e.unregister(mC)});var xC=class extends t.Component{static template=`o-spreadsheet-ChartJsComponent`;static props={figureUI:Object,isFullScreen:{type:Boolean,optional:!0}};canvas=(0,t.useRef)(`graphContainer`);chart;currentRuntime;animationStore;currentDevicePixelRatio=window.devicePixelRatio;get background(){return this.chartRuntime.background}get canvasStyle(){return`background-color: ${this.background}`}get chartRuntime(){let e=this.env.model.getters.getChartRuntime(this.props.figureUI.id);if(!(`chartJsConfig`in e))throw Error(`Unsupported chart runtime`);return e}setup(){this.env.model.getters.isDashboard()&&(this.animationStore=B(pf)),(0,t.onMounted)(()=>{df();let e=this.chartRuntime;this.currentRuntime=e,this.createChart(b(e.chartJsConfig))}),(0,t.onWillUnmount)(()=>this.chart?.destroy()),(0,t.useEffect)(()=>{let e=this.chartRuntime;e===this.currentRuntime?this.currentDevicePixelRatio!==window.devicePixelRatio&&(this.currentDevicePixelRatio=window.devicePixelRatio,this.updateChartJs(b(this.currentRuntime.chartJsConfig))):(e.chartJsConfig.type===this.currentRuntime.chartJsConfig.type?this.updateChartJs(b(e.chartJsConfig)):(this.chart?.destroy(),this.createChart(b(e.chartJsConfig))),this.currentRuntime=e)})}createChart(e){if(this.env.model.getters.isDashboard()&&this.animationStore){let t=this.env.model.getters.getChart(this.props.figureUI.id)?.type;t&&this.animationStore.animationPlayed[this.animationFigureId]!==t&&(e=this.enableAnimationInChartData(e),this.animationStore.disableAnimationForChart(this.animationFigureId,t))}let t=this.canvas.el.getContext(`2d`);this.chart=new window.Chart(t,e)}updateChartJs(e){if(this.env.model.getters.isDashboard()){let t=this.env.model.getters.getChart(this.props.figureUI.id)?.type;t&&this.hasChartDataChanged()&&this.animationStore&&(e=this.enableAnimationInChartData(e),this.animationStore.disableAnimationForChart(this.animationFigureId,t))}e.data&&e.data.datasets?(this.chart.data=e.data,e.options?.plugins?.title&&(this.chart.config.options.plugins.title=e.options.plugins.title)):this.chart.data.datasets=[],this.chart.config.options=e.options,this.chart.update()}hasChartDataChanged(){return!w(this.getChartDataInRuntime(this.currentRuntime),this.getChartDataInRuntime(this.chartRuntime))}getChartDataInRuntime(e){let t=e.chartJsConfig.data;return{labels:t.labels,dataset:t.datasets.map(e=>({data:e.data,label:e.label,tree:e.tree}))}}enableAnimationInChartData(e){return{...e,options:{...e.options,animation:{animateRotate:!0}}}}get animationFigureId(){return this.props.isFullScreen?this.props.figureUI.id+`-fullscreen`:this.props.figureUI.id}},SC=class{sheetId;title;getters;constructor(e,t,n){this.title=e.title,this.sheetId=t,this.getters=n}static validateChartDefinition(e,t){throw Error(`This method should be implemented by sub class`)}static transformDefinition(e,t,n){throw Error(`This method should be implemented by sub class`)}static getDefinitionFromContextCreation(e){throw Error(`This method should be implemented by sub class`)}};function CC(e,t,n,r,i){if(!e)return``;if(n===`text`||t?.type!==`number`||e.type!==`number`)return r?Fo(e,i):e.formattedValue;let{value:a,format:o}=e;return n===`progress`?(a=t.value/a,o=`0.0%`):(a=Math.abs(t.value-a),n===`percentage`&&a!==0&&(a/=e.value),n===`percentage`&&(o=`0.0%`),o||(a=Math.round(a*100)/100)),r?Fo({value:a,format:o},i):L(a,{format:o,locale:i})}function wC(e,t,n){return e?t?Fo(e,n):e.formattedValue??String(e.value??``):``}function TC(e,t,n,r,i){if(t===`text`||t===`progress`||e?.type!==`number`||n?.type!==`number`)return;let a=n.value-e.value;if(a>0)return r;if(a<0)return i}function EC(e,t,n){if(n===`text`||e?.type!==`number`||t?.type!==`number`)return`neutral`;let r=t.value-e.value;return r>0?`up`:r<0?`down`:`neutral`}function DC(e){return e.keyValue&&!fc.test(e.keyValue)?`InvalidScorecardKeyValue`:`Success`}function OC(e){return e.baseline&&!fc.test(e.baseline)?`InvalidScorecardBaseline`:`Success`}let kC=new window.Path2D(`M8.6 4.8a.5.5 0 0 1 0 .75l-3.9 3.9a.5 .5 0 0 1 -.75 0l-3.8 -3.9a.5 .5 0 0 1 0 -.75l.4-.4a.5.5 0 0 1 .75 0l2.3 2.4v-5.7c0-.25.25-.5.5-.5h.6c.25 0 .5.25.5.5v5.8l2.3 -2.4a.5.5 0 0 1 .75 0z`),AC=new window.Path2D(`M8.7 5.5a.5.5 0 0 0 0-.75l-3.8-4a.5.5 0 0 0-.75 0l-3.8 4a.5.5 0 0 0 0 .75l.4.4a.5.5 0 0 0 .75 0l2.3-2.4v5.8c0 .25.25.5.5.5h.6c.25 0 .5-.25.5-.5v-5.8l2.2 2.4a.5.5 0 0 0 .75 0z`);var jC=class e extends SC{keyValue;keyDescr;baseline;baselineMode;baselineDescr;progressBar=!1;background;baselineColorUp;baselineColorDown;fontColor;humanize;type=`scorecard`;constructor(e,t,n){super(e,t,n),this.keyValue=Dc(n,t,e.keyValue),this.keyDescr=e.keyDescr,this.baseline=Dc(n,t,e.baseline),this.baselineMode=e.baselineMode,this.baselineDescr=e.baselineDescr,this.background=e.background,this.baselineColorUp=e.baselineColorUp??`#43C5B1`,this.baselineColorDown=e.baselineColorDown??`#EA6175`,this.humanize=e.humanize??!1}static validateChartDefinition(e,t){return e.checkValidations(t,DC,OC)}static getDefinitionFromContextCreation(e){return{background:e.background,type:`scorecard`,keyValue:e.range?.[0]?.dataRange,title:e.title||{text:``},baselineMode:Ge,baselineColorUp:Ke,baselineColorDown:qe,baseline:e.auxiliaryRange||``}}static transformDefinition(e,t,n){let r,i;if(t.baseline){let{changeType:i,range:a}=uS(e,t.baseline,n);i!==`REMOVE`&&(r=a)}if(t.keyValue){let{changeType:r,range:a}=uS(e,t.keyValue,n);r!==`REMOVE`&&(i=a)}return{...t,baseline:r,keyValue:i}}duplicateInDuplicatedSheet(t){let n=vS(this.sheetId,t,this.baseline),r=vS(this.sheetId,t,this.keyValue);return new e(this.getDefinitionWithSpecificRanges(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue)}getContextCreation(){return{...this,range:this.keyValue?[{dataRange:this.getters.getRangeString(this.keyValue,this.sheetId)}]:void 0,auxiliaryRange:this.baseline?this.getters.getRangeString(this.baseline,this.sheetId):void 0}}getDefinitionWithSpecificRanges(e,t,n){return{baselineColorDown:this.baselineColorDown,baselineColorUp:this.baselineColorUp,baselineMode:this.baselineMode,title:this.title,type:`scorecard`,background:this.background,baseline:e?this.getters.getRangeString(e,n||this.sheetId):void 0,baselineDescr:this.baselineDescr,keyValue:t?this.getters.getRangeString(t,n||this.sheetId):void 0,keyDescr:this.keyDescr,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let n=yS(this.baseline,t),r=yS(this.keyValue,t);return this.baseline===n&&this.keyValue===r?this:new e(this.getDefinitionWithSpecificRanges(n,r),this.sheetId,this.getters)}};function MC(e,t){let n=t.getContext(`2d`),r=window.devicePixelRatio||1;t.width=r*e.canvas.width,t.height=r*e.canvas.height,n.scale(r,r);let i=e.canvas.width-20;if(n.fillStyle=e.canvas.backgroundColor,n.fillRect(0,0,e.canvas.width,e.canvas.height),e.title){n.font=e.title.style.font,n.fillStyle=e.title.style.color;let t=n.textBaseline;n.textBaseline=`middle`,n.fillText(pl(n,e.title.text,i-e.title.position.x),e.title.position.x,e.title.position.y),n.textBaseline=t}if(e.baseline&&(n.font=e.baseline.style.font,n.fillStyle=e.baseline.style.color,ml(n,e.baseline.text,e.baseline.position,e.baseline.style.underline,e.baseline.style.strikethrough)),e.baselineArrow&&e.baselineArrow.style.size>0){n.save(),n.fillStyle=e.baselineArrow.style.color,n.translate(e.baselineArrow.position.x,e.baselineArrow.position.y);let t=e.baselineArrow.style.size/10;switch(n.scale(t,t),e.baselineArrow.direction){case`down`:n.fill(kC);break;case`up`:n.fill(AC);break}n.restore()}if(e.baselineDescr){let t=e.baselineDescr;n.font=t.style.font,n.fillStyle=t.style.color,n.fillText(pl(n,t.text,i-t.position.x),t.position.x,t.position.y)}if(e.key&&(n.font=e.key.style.font,n.fillStyle=e.key.style.color,ml(n,pl(n,e.key.text,i-e.key.position.x),e.key.position,e.key.style.underline,e.key.style.strikethrough)),e.keyDescr){let t=e.keyDescr;n.font=e.keyDescr?.style.font??t.style.font,n.fillStyle=t.style.color,n.fillText(pl(n,t.text,i-t.position.x),t.position.x,t.position.y)}if(e.progressBar){if(n.fillStyle=e.progressBar.style.backgroundColor,n.beginPath(),n.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width,e.progressBar.dimension.height,e.progressBar.dimension.height/2),n.fill(),n.fillStyle=e.progressBar.style.color,n.beginPath(),e.progressBar.value>0)n.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width*Math.max(0,Math.min(1,e.progressBar.value)),e.progressBar.dimension.height,e.progressBar.dimension.height/2);else{let t=e.progressBar.dimension.width*Math.max(0,Math.min(1,-e.progressBar.value));n.roundRect(e.progressBar.position.x+e.progressBar.dimension.width-t,e.progressBar.position.y,t,e.progressBar.dimension.height,e.progressBar.dimension.height/2)}n.fill()}}function NC(e,t){let n=``,r,i=t.getLocale();if(e.keyValue){let a={sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top};r=t.getEvaluatedCell(a),n=wC(r,e.humanize??!1,i)}let a,o=e.baseline;if(o){let e={sheetId:o.sheetId,col:o.zone.left,row:o.zone.top};a=t.getEvaluatedCell(e)}let{background:s,fontColor:c}=t.getStyleOfSingleCellChart(e.background,e.keyValue),l=CC(a,r,e.baselineMode,e.humanize??!1,i),u=e.baselineMode===`progress`&&Pi(l,i)?M(l,i):0;return{title:{...e.title,text:e.title.text?E(e.title.text):``},keyValue:n,keyDescr:e.keyDescr?.text?E(e.keyDescr.text):``,baselineDisplay:l,baselineArrow:EC(a,r,e.baselineMode),baselineColor:TC(a,e.baselineMode,r,e.baselineColorUp,e.baselineColorDown),baselineDescr:e.baselineMode!==`progress`&&e.baselineDescr?.text?E(e.baselineDescr.text):``,fontColor:c,background:s,baselineStyle:{...e.baselineMode!==`percentage`&&e.baselineMode!==`progress`&&o?t.getCellComputedStyle({sheetId:o.sheetId,col:o.zone.left,row:o.zone.top}):void 0,fontSize:e.baselineDescr?.fontSize,align:e.baselineDescr?.align},baselineDescrStyle:{textColor:e.baselineDescr?.color,...e.baselineDescr},keyValueStyle:{...e.keyValue?t.getCellComputedStyle({sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top}):void 0,fontSize:e.keyDescr?.fontSize,align:e.keyDescr?.align},keyValueDescrStyle:{textColor:e.keyDescr?.color,...e.keyDescr},progressBar:e.baselineMode===`progress`?{value:u,color:u>0?e.baselineColorUp:e.baselineColorDown}:void 0}}let PC=.05;function FC(e,t){let n=e||``;return t&&n?` `+n:n}function IC({width:e,height:t},n){return new LC({width:e,height:t},n).computeDesign()}var LC=class{runtime;context;width;height;constructor({width:e,height:t},n){this.runtime=n;let r=document.createElement(`canvas`);this.width=r.width=e,this.height=r.height=t,this.context=r.getContext(`2d`)}computeDesign(){let e={canvas:{width:this.width,height:this.height,backgroundColor:this.backgroundColor}},t=this.getTextStyles(),n=0;if(this.title){let r,i;switch({height:n,width:i}=this.getFullTextDimensions(this.title,t.title.font),this.runtime.title.align){case`center`:r=(this.width-i)/2;break;case`right`:r=this.width-i-20;break;default:r=20}e.title={text:this.title,style:t.title,position:{x:r,y:10+n/2}}}let r=t.baselineArrow?.size??0,{height:i,width:a}=this.getTextDimensions(this.baseline,t.baselineValue.font);this.baseline||(i=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).height);let o=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).width,s;switch(this.runtime.baselineStyle?.align){case`right`:s=this.width-20-o-a;break;case`left`:s=20+r;break;default:s=(this.width-a-o+r)/2}if(this.baseline&&(e.baseline={text:this.baseline,style:t.baselineValue,position:{x:s,y:this.keyValue?this.height*(1-PC*(this.runtime.progressBar?1:2)):this.height-(this.height-n-i)/2-10}},t.baselineArrow&&!this.runtime.progressBar&&(e.baselineArrow={direction:this.baselineArrow,style:t.baselineArrow,position:{x:e.baseline.position.x-r,y:e.baseline.position.y-(i+r)/2}})),e.baseline&&this.baselineDescr){let n={x:e.baseline.position.x+a,y:e.baseline.position.y};e.baselineDescr={text:this.baselineDescr,style:t.baselineDescr,position:n}}let c=0;this.runtime.progressBar&&(c=this.height*.05,e.progressBar={position:{x:40,y:this.height*(1-2*PC)-i-c},dimension:{height:c,width:this.width-80},value:this.runtime.progressBar.value,style:{color:this.runtime.progressBar.color,backgroundColor:this.secondaryFontColor}});let{width:l,height:u}=this.getFullTextDimensions(this.keyValue,t.keyValue.font),d=this.getTextDimensions(this.keyDescr,t.keyDescr.font).width,f;switch(this.runtime.keyValueStyle?.align){case`right`:f=this.width-20-d-l;break;case`left`:f=20;break;default:f=(this.width-l-d)/2}if(this.keyValue&&(e.key={text:this.keyValue,style:t.keyValue,position:{x:Math.max(20,f),y:this.height*(.5-PC*2)+10/2+(n+u/2)/2}}),e.key&&this.keyDescr){let n={x:e.key.position.x+l,y:e.key.position.y};e.keyDescr={text:this.keyDescr,style:t.keyDescr,position:n}}return e}get title(){return this.runtime.title.text??``}get keyValue(){return this.runtime.keyValue}get keyDescr(){return FC(this.runtime.keyDescr,this.keyValue)}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){return FC(this.runtime.baselineDescr,this.baseline)}get baselineArrow(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get secondaryFontColor(){return ES(this.backgroundColor)}getTextDimensions(e,t){this.context.font=t;let n=this.context.measureText(e);return{width:n.width,height:n.actualBoundingBoxAscent+n.actualBoundingBoxDescent}}getFullTextDimensions(e,t){this.context.font=t;let n=this.context.measureText(e);return{width:n.width,height:n.fontBoundingBoxAscent+n.fontBoundingBoxDescent}}getTextStyles(){let e=this.runtime.keyValueStyle?.fontSize??32,t=Math.floor(.9*e),n=this.runtime.baselineStyle?.fontSize??16,r=Math.floor(.9*n);return this.runtime.progressBar&&(n/=1.5),{title:{font:Zc(this.runtime.title.fontSize??14,this.runtime.title.bold,this.runtime.title.italic),color:this.runtime.title.color??this.secondaryFontColor},keyValue:{color:this.runtime.keyValueStyle?.textColor||this.runtime.fontColor,font:Zc(e,this.runtime.keyValueStyle?.bold,this.runtime.keyValueStyle?.italic),strikethrough:this.runtime.keyValueStyle?.strikethrough,underline:this.runtime.keyValueStyle?.underline},keyDescr:{color:this.runtime.keyValueDescrStyle?.textColor||this.runtime.fontColor,font:Zc(t,this.runtime.keyValueDescrStyle?.bold,this.runtime.keyValueDescrStyle?.italic),strikethrough:this.runtime.keyValueDescrStyle?.strikethrough,underline:this.runtime.keyValueDescrStyle?.underline},baselineValue:{font:Zc(n,this.runtime.baselineStyle?.bold,this.runtime.baselineStyle?.italic),strikethrough:this.runtime.baselineStyle?.strikethrough,underline:this.runtime.baselineStyle?.underline,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor},baselineDescr:{font:Zc(r,this.runtime.baselineDescrStyle?.bold,this.runtime.baselineDescrStyle?.italic),strikethrough:this.runtime.baselineDescrStyle?.strikethrough,underline:this.runtime.baselineDescrStyle?.underline,color:this.runtime.baselineDescrStyle?.textColor??this.secondaryFontColor},baselineArrow:this.baselineArrow===`neutral`||this.runtime.progressBar?void 0:{size:this.keyValue?.8*n:0,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor}}}},RC=class extends t.Component{static template=`o-spreadsheet-ScorecardChart`;static props={figureUI:Object};canvas=(0,t.useRef)(`chartContainer`);get runtime(){return this.env.model.getters.getChartRuntime(this.props.figureUI.id)}get title(){return E(this.env.model.getters.getChartDefinition(this.props.figureUI.id).title.text??``)}setup(){(0,t.useEffect)(this.createChart.bind(this),()=>{let e=this.canvas.el.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}createChart(){let e=this.canvas.el;MC(IC(e.getBoundingClientRect(),this.runtime),e)}};let zC=/Mac/i,BC=[`Shift`,`Control`,`Alt`,`Meta`];function VC(e,t){return e?!!t.target&&e.contains(t.target):!1}function HC(){let e=document.querySelector(`.o-grid-overlay`);if(e){let{top:t,left:n}=e.getBoundingClientRect();return{top:t,left:n}}throw Error(`Can't find spreadsheet position`)}function UC(e){return e.el?WC(e.el):{x:0,y:0,width:0,height:0}}function WC(e){let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function*GC(e){if(yield e,e.hasChildNodes())for(let t of e.childNodes)yield*GC(t)}function KC(){return Array.from(document.querySelectorAll(`.o-spreadsheet .o-menu`))}function qC(e){let{startElement:t,endElement:n,startSelectionOffset:r,endSelectionOffset:i}=JC(e);return{start:YC(e,t,r),end:YC(e,n,i)}}function JC(e){let t=document.getSelection();return{startElement:t.anchorNode||e,startSelectionOffset:t.anchorOffset,endElement:t.focusNode||e,endSelectionOffset:t.focusOffset}}function YC(e,t,n){let r=0,i=GC(e),a=i.next(),o=!0;for(;!a.done&&a.value!==t;)a.value.hasChildNodes()||a.value.textContent&&(r+=a.value.textContent.length),(a.value.nodeName===`P`||a.value.nodeName===`DIV`&&a.value!==e)&&(o?o=!1:r++),a=i.next();if(a.value!==t)return 0;if(!a.value.hasChildNodes())r+=n;else{let e=[...a.value.childNodes].slice(0,n);r+=e.reduce((t,n,r)=>{if(n.textContent!==null){let i=n.textContent.length;return n.nodeName===`P`&&r!==e.length-1&&i++,t+i}else return t},0)}return t.nodeName===`P`&&!o&&t.textContent===``&&r++,r}let XC=/^[a-zA-Z]$/;function ZC(e,t=`key`){let n=``;BC.includes(e.key)||($C(e)&&(n+=`Ctrl+`),e.altKey&&(n+=`Alt+`),e.shiftKey&&(n+=`Shift+`));let r=t===`key`?e.key:e.code;return n+=XC.test(r)?r.toUpperCase():r,n}function QC(){return!!zC.test(navigator.userAgent)}function $C(e){return QC()||ow()?e.metaKey:e.ctrlKey}function ew(e){return e.button===1||$C(e)&&e.button===0}async function tw(e){return new Promise((t,n)=>{let r=new Image;r.addEventListener(`load`,()=>{let e=document.createElement(`canvas`);e.width=r.width,e.height=r.height,e.getContext(`2d`)?.drawImage(r,0,0),e.toBlob(t,`image/png`)}),r.addEventListener(`error`,n),r.src=e})}function nw(e,t){let n=document.createElement(`a`);n.href=e,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n)}function rw(){return/Firefox/i.test(navigator.userAgent)}function iw(){return navigator.maxTouchPoints||1}function aw(){return/Android/i.test(navigator.userAgent)}function ow(){return/(iPad|iPhone|iPod)/i.test(navigator.userAgent)||navigator.platform===`MacIntel`&&iw()>1}function sw(){return/(webOS|BlackBerry|Windows Phone)/i.test(navigator.userAgent)}function cw(){return aw()||ow()||sw()}function lw(e){return e=sn(e).replace(`#`,``),e.length===8?e.slice(6)+e.slice(0,6):e}let uw=`#F3F2F1`;function dw(e,t){let n=e.getBoundingClientRect(),r=window.devicePixelRatio||1;e.width=r*n.width,e.height=r*n.height;let i=e.getContext(`2d`);i.scale(r,r);let a=_w(n,t,i);pw(i,a),fw(i,a),hw(i,a),mw(i,a),gw(i,a)}function fw(e,t){e.save();let n=t.gauge,r=n.rect.x+n.rect.width/2,i=n.rect.y+n.rect.height,a=n.rect.height-n.arcWidth/2;if(a<0)return;let o=n.percentage===1?0:Math.PI*(1+n.percentage);e.strokeStyle=uw,e.beginPath(),e.lineWidth=n.arcWidth,e.arc(r,i,a,o,0),e.stroke(),e.strokeStyle=n.color,e.beginPath(),e.arc(r,i,a,Math.PI,o),e.stroke(),e.restore()}function pw(e,t){e.save(),e.fillStyle=t.backgroundColor,e.fillRect(0,0,t.width,t.height),e.restore()}function mw(e,t){for(let n of[t.minLabel,t.maxLabel,t.gaugeValue])e.save(),e.textAlign=`center`,e.fillStyle=n.color,e.font=`${n.fontSize}px ${He}`,e.fillText(n.label,n.textPosition.x,n.textPosition.y),e.restore()}function hw(e,t){let{x:n,y:r,width:i,height:a}=t.gauge.rect;for(let o of t.inflectionValues){e.save(),e.translate(n+i/2-.5,r+a-.5),e.rotate(Math.PI/2-o.rotation),e.lineWidth=2,e.strokeStyle=ES(t.backgroundColor)+`aa`,e.beginPath(),e.moveTo(0,-(a-t.gauge.arcWidth)),e.lineTo(0,-a-3),e.stroke(),e.textAlign=`center`,e.font=`${o.fontSize}px ${He}`,e.fillStyle=o.color;let s=-a-6-o.offset;e.fillText(o.label,0,s),e.restore()}}function gw(e,t){e.save();let n=t.title;e.font=Zc(n.fontSize,n.bold,n.italic),e.textBaseline=`middle`,e.fillStyle=n.color,e.fillText(n.label,n.textPosition.x,n.textPosition.y),e.restore()}function _w(e,t,n){let r=t.maxValue,i=t.minValue,a=Tw(t,`animated`),o=vw(e,t.title.text),s=o.width/6,c=a?(a-i.value)/(r.value-i.value):0,l={x:e.width/2,y:o.y+o.height-o.height/12},u=80;o.height<300&&(u*=o.height/300);let d=o.width/2,f=t.gaugeValue?.label||`-`;$c(n,f,{fontSize:u},`px`)>d&&(u=ll(d,u,e=>$c(n,f,{fontSize:e},`px`)));let p={x:o.x+s/2,y:o.y+o.height+12},m={x:o.x+o.width-s/2,y:o.y+o.height+12},h=ES(t.background),g=yw(t,o,h,n),_=0,v=0,y=0;switch(t.title.text&&({width:v,height:y}=nl(n,t.title.text,{fontSize:16,...t.title},`px`)),t.title.align){case`right`:_=e.width-v-20;break;case`center`:_=(e.width-v)/2;break;default:_=20;break}return{width:e.width,height:e.height,title:{label:t.title.text??``,fontSize:t.title.fontSize??16,textPosition:{x:_,y:15+y/2},color:t.title.color??h,bold:t.title.bold,italic:t.title.italic},backgroundColor:t.background,gauge:{rect:o,arcWidth:s,percentage:x(c,0,1),color:bw(t)},inflectionValues:g,gaugeValue:{label:f,textPosition:l,fontSize:u,color:h},minLabel:{label:t.minValue.label,textPosition:p,fontSize:12,color:h},maxLabel:{label:t.maxValue.label,textPosition:m,fontSize:12,color:h}}}function vw(e,t){let n=t?25:0,r=e.height-20-n-10,i=e.width-60,a,o;return i>2*r?(a=2*r,o=r):(a=i,o=i/2),{x:30+(i-a)/2,y:n+10+(r-o)/2,width:a,height:o}}function yw(e,t,n,r){let i=e.maxValue,a=e.minValue,o={x:t.x+t.width/2,y:t.y+t.height},s={fontSize:12},c=[],l=[];for(let u of e.inflectionValues){let e=(u.value-a.value)/(i.value-a.value),d=$c(r,u.label,s,`px`),f=Math.PI-Math.PI*e,p=ww(f,t.height+6,o.x,o.y,d+2,12),m=l.some(e=>Cw(e,p))?12:0;l.push(p),c.push({rotation:f,label:u.label,fontSize:12,color:n,offset:m})}return c}function bw(e){let t=Tw(e,`final`);if(t===void 0)return uw;for(let n=0;n<e.inflectionValues.length;n++){let r=e.inflectionValues[n];if(r.operator===`<`&&t<r.value||r.operator===`<=`&&t<=r.value)return e.colors[n]}return e.colors.at(-1)}function xw(e){return[{start:e.topLeft,end:e.topRight},{start:e.topRight,end:e.bottomRight},{start:e.bottomRight,end:e.bottomLeft},{start:e.bottomLeft,end:e.topLeft}]}function Sw(e,t){let n=e.start,r=e.end,i=t.start,a=t.end;function o(e,t,n){return(n.y-e.y)*(t.x-e.x)>(t.y-e.y)*(n.x-e.x)}return o(n,i,a)!==o(r,i,a)&&o(n,r,i)!==o(n,r,a)}function Cw(e,t){let n=xw(e),r=xw(t);for(let e of n)for(let t of r)if(Sw(e,t))return!0;return!1}function ww(e,t,n,r,i,a){let o=Math.cos(e),s=Math.sin(e),c=o*t,l=s*t,u=i/2*s,d=i/2*o,f={x:c+u+n,y:r-(l-d)},p={x:c-u+n,y:r-(l+d)},m=o*(t+a),h=s*(t+a),g={x:m-u+n,y:r-(h+d)};return{bottomLeft:p,bottomRight:f,topRight:{x:m+u+n,y:r-(h-d)},topLeft:g}}function Tw(e,t){return t===`animated`&&e.animationValue!==void 0?e.animationValue:e.gaugeValue?.value}let Ew={responsive:!0,maintainAspectRatio:!1,elements:{line:{fill:!1},point:{hitRadius:15}},animation:!1,events:[`mousemove`,`mouseout`,`click`,`touchstart`,`touchmove`,`mouseup`]};function Dw(e,t,n){let r=document.createElement(`div`);r.style.width=`${t.width}px`,r.style.height=`${t.height}px`;let i=document.createElement(`canvas`);r.append(i),i.setAttribute(`width`,t.width.toString()),i.setAttribute(`height`,t.height.toString());let a;if(document.body.append(r),`chartJsConfig`in e){let t=uf();t||df();let n=b(e.chartJsConfig);n.plugins=[kw];let r=new globalThis.Chart(i,n);a=r.toBase64Image(),r.destroy(),t||ff()}else n===`scorecard`?(MC(IC(t,e),i),a=i.toDataURL()):n===`gauge`&&(dw(i,e),a=i.toDataURL());return r.remove(),a}async function Ow(e,t,n){let r=document.createElement(`div`);r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.position=`fixed`,r.style.opacity=`0`;let i=document.createElement(`canvas`);r.append(i),i.setAttribute(`width`,t.width.toString()),i.setAttribute(`height`,t.height.toString()),document.body.append(r);let a=null;if(`chartJsConfig`in e){let t=uf();t||df();let n=b(e.chartJsConfig);n.plugins=[kw];let r=new globalThis.Chart(i,n);a=await new Promise(e=>i.toBlob(e,`image/png`)),r.destroy(),t||ff()}else n===`scorecard`?(MC(IC(t,e),i),a=await new Promise(e=>i.toBlob(e,`image/png`))):n===`gauge`&&(dw(i,e),a=await new Promise(e=>i.toBlob(e,`image/png`)));return r.remove(),a?new File([a],`chart.png`,{type:`image/png`}):void 0}let kw={id:`customCanvasBackgroundColor`,beforeDraw:e=>{let{ctx:t}=e;t.save(),t.globalCompositeOperation=`destination-over`,t.fillStyle=`#ffffff`,t.fillRect(0,0,e.width,e.height),t.restore()}},Aw={Errors:{InvalidRange:E(`The range is invalid`),FirstArgMissing:E(`The argument is missing. Please provide a value`),SecondArgMissing:E(`The second argument is missing. Please provide a value`),MinNaN:E(`The minpoint must be a number`),MidNaN:E(`The midpoint must be a number`),MaxNaN:E(`The maxpoint must be a number`),ValueUpperInflectionNaN:E(`The first value must be a number`),ValueLowerInflectionNaN:E(`The second value must be a number`),MinBiggerThanMax:E(`Minimum must be smaller then Maximum`),MinBiggerThanMid:E(`Minimum must be smaller then Midpoint`),MidBiggerThanMax:E(`Midpoint must be smaller then Maximum`),LowerBiggerThanUpper:E(`Lower inflection point must be smaller than upper inflection point`),MinInvalidFormula:E(`Invalid Minpoint formula`),MaxInvalidFormula:E(`Invalid Maxpoint formula`),MidInvalidFormula:E(`Invalid Midpoint formula`),ValueUpperInvalidFormula:E(`Invalid upper inflection point formula`),ValueLowerInvalidFormula:E(`Invalid lower inflection point formula`),EmptyRange:E(`A range needs to be defined`),ValueCellIsInvalidFormula:E(`At least one of the provided values is an invalid formula`),Unexpected:E(`The rule is invalid for an unknown reason`)},ColorScale:E(`Color scale`),IconSet:E(`Icon set`),DataBar:E(`Data bar`)},jw={Series:E(`Series`),BackgroundColor:E(`Background color`),StackedBarChart:E(`Stacked bar chart`),StackedLineChart:E(`Stacked line chart`),StackedAreaChart:E(`Stacked area chart`),StackedColumnChart:E(`Stacked column chart`),CumulativeData:E(`Cumulative data`),TreatLabelsAsText:E(`Treat labels as text`),AggregatedChart:E(`Aggregate`),Errors:{Unexpected:E(`The chart definition is invalid for an unknown reason`),InvalidDataSet:E(`The dataset is invalid`),InvalidLabelRange:E(`Labels are invalid`),InvalidScorecardKeyValue:E(`The key value is invalid`),InvalidScorecardBaseline:E(`The baseline value is invalid`),InvalidGaugeDataRange:E(`The data range is invalid`),EmptyGaugeRangeMin:E(`A minimum range limit value is needed`),GaugeRangeMinNaN:E(`The minimum range limit value must be a number`),EmptyGaugeRangeMax:E(`A maximum range limit value is needed`),GaugeRangeMaxNaN:E(`The maximum range limit value must be a number`),GaugeLowerInflectionPointNaN:E(`The lower inflection point value must be a number`),GaugeUpperInflectionPointNaN:E(`The upper inflection point value must be a number`)},GeoChart:{ColorScales:{blues:E(`Blues`),cividis:E(`Cividis`),greens:E(`Greens`),greys:E(`Greys`),oranges:E(`Oranges`),purples:E(`Purples`),rainbow:E(`Rainbow`),reds:E(`Reds`),viridis:E(`Viridis`)}}},Mw={Custom:E(`Custom`)},Nw=E(`Merged cells are preventing this operation. Unmerge those cells and try again.`),Pw=E(`The header row of a table can't be moved.`),Fw={Errors:{Unexpected:E(`Cannot split the selection for an unknown reason`),NoSplitSeparatorInSelection:E(`There is no match for the selected separator in the selection`),MoreThanOneColumnSelected:E(`Only a selection from a single column can be split`),SplitWillOverwriteContent:E(`Splitting will overwrite existing content`)}},Iw={Errors:{Unexpected:E(`Cannot remove duplicates for an unknown reason`),MoreThanOneRangeSelected:E(`Please select only one range of cells`),EmptyTarget:E(`Please select a range of cells containing values.`),NoColumnsProvided:E(`Please select at latest one column to analyze.`),WillRemoveExistingMerge:E(`This operation is not possible due to a merge. Please remove the merges first than try again.`)}},G={DateIs:{today:E(`today`),yesterday:E(`yesterday`),tomorrow:E(`tomorrow`),lastWeek:E(`in the past week`),lastMonth:E(`in the past month`),lastYear:E(`in the past year`)},DateIsBefore:{today:E(`today`),yesterday:E(`yesterday`),tomorrow:E(`tomorrow`),lastWeek:E(`one week ago`),lastMonth:E(`one month ago`),lastYear:E(`one year ago`)},CriterionError:{notEmptyValue:E(`The value must not be empty`),numberValue:E(`The value must be a number`),dateValue:E(`The value must be a date`),validRange:E(`The value must be a valid range`),validFormula:E(`The formula must be valid`)},Errors:{InvalidRange:E(`The range is invalid.`),InvalidDataValidationCriterionValue:E(`One or more of the provided criteria values are invalid. Please review and correct them.`),InvalidNumberOfCriterionValues:E(`One or more of the provided criteria values are missing.`),Unexpected:E(`The rule is invalid for an unknown reason.`)}},Lw={Errors:{Unexpected:E(`The table zone is invalid for an unknown reason`),TableOverlap:E(`You cannot create overlapping tables.`),NonContinuousTargets:E(`A table can only be created on a continuous selection.`),InvalidRange:E(`The range is invalid`),TargetOutOfSheet:E(`The range is out of the sheet`)},Checkboxes:{hasFilters:E(`Filter button`),headerRow:E(`Header row(s)`),bandedRows:E(`Banded rows`),firstColumn:E(`First column`),lastColumn:E(`Last column`),bandedColumns:E(`Banded columns`),automaticAutofill:E(`Automatically autofill formulas`),totalRow:E(`Total row`),isDynamic:E(`Auto-adjust to formula result`)},Tooltips:{filterWithoutHeader:E(`Cannot have filters without a header row`),isDynamic:E(`For tables based on array formulas only`)}},Rw={labels:{no_calculations:E(`No calculations`),"%_of_grand_total":E(`% of grand total`),"%_of_col_total":E(`% of column total`),"%_of_row_total":E(`% of row total`),"%_of":E(`% of`),"%_of_parent_row_total":E(`% of parent row total`),"%_of_parent_col_total":E(`% of parent column total`),"%_of_parent_total":E(`% of parent total`),difference_from:E(`Difference from`),"%_difference_from":E(`% difference from`),running_total:E(`Running total`),"%_running_total":E(`% Running total`),rank_asc:E(`Rank smallest to largest`),rank_desc:E(`Rank largest to smallest`),index:E(`Index`)},descriptions:{"%_of_grand_total":()=>E(`Displayed as % of grand total`),"%_of_col_total":()=>E(`Displayed as % of column total`),"%_of_row_total":()=>E(`Displayed as % of row total`),"%_of":e=>E(`Displayed as % of "%s"`,e),"%_of_parent_row_total":e=>E(`Displayed as % of parent row total of "%s"`,e),"%_of_parent_col_total":()=>E(`Displayed as % of parent column total`),"%_of_parent_total":e=>E(`Displayed as % of parent "%s" total`,e),difference_from:e=>E(`Displayed as difference from "%s"`,e),"%_difference_from":e=>E(`Displayed as % difference from "%s"`,e),running_total:e=>E(`Displayed as running total based on "%s"`,e),"%_running_total":e=>E(`Displayed as % running total based on "%s"`,e),rank_asc:e=>E(`Displayed as rank from smallest to largest based on "%s"`,e),rank_desc:e=>E(`Displayed as rank largest to smallest based on "%s"`,e),index:()=>E(`Displayed as index`)},documentation:{no_calculations:E(`Displays the value that is entered in the field.`),"%_of_grand_total":E(`Displays values as a percentage of the grand total of all the values or data points in the report.`),"%_of_col_total":E(`Displays all the values in each column or series as a percentage of the total for the column or series.`),"%_of_row_total":E(`Displays the value in each row or category as a percentage of the total for the row or category.`),"%_of":E(`Displays values as a percentage of the value of the Base item in the Base field.`),"%_of_parent_row_total":E(`Calculates values as follows:
|
|
28
28
|
(value for the item) / (value for the parent item on rows)`),"%_of_parent_col_total":E(`Calculates values as follows:
|
|
29
29
|
(value for the item) / (value for the parent item on columns)`),"%_of_parent_total":E(`Calculates values as follows:
|
|
30
30
|
(value for the item) / (value for the parent item of the selected Base field)`),difference_from:E(`Displays values as the difference from the value of the Base item in the Base field.`),"%_difference_from":E(`Displays values as the percentage difference from the value of the Base item in the Base field.`),running_total:E(`Displays the value for successive items in the Base field as a running total.`),"%_running_total":E(`Calculates the value as a percentage for successive items in the Base field that are displayed as a running total.`),rank_asc:E(`Displays the rank of selected values in a specific field, listing the smallest item in the field as 1, and each larger value with a higher rank value.`),rank_desc:E(`Displays the rank of selected values in a specific field, listing the largest item in the field as 1, and each smaller value with a higher rank value.`),index:E(`Calculates values as follows:
|
|
@@ -75,7 +75,7 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
75
75
|
`),r=t?.content?.textLines?.join(`
|
|
76
76
|
`);return!!(n&&!r)},updateAnimation:function(e,t,n,r){let i=1-DE[this.easingFn](e),a={...n.style};delete a.fillColor,t.textOpacity=i,t.content=n.content,t.clipRect=n.clipRect,Object.assign(t.style,a)}}),EE.add(`iconFadeIn`,{id:`iconFadeIn`,easingFn:`easeInCubic`,hasAnimation:(e,t)=>!!(!e?.icons?.left&&t?.icons?.left||!e?.icons?.right&&t?.icons?.right||!e?.icons?.center&&t?.icons?.center),updateAnimation:function(e,t,n,r){let i=DE[this.easingFn](e);t.icons.left&&r.icons.left&&!n.icons.left&&(t.icons.left.opacity=i),t.icons.right&&r.icons.right&&!n.icons.right&&(t.icons.right.opacity=i),t.icons.center&&r.icons.center&&!n.icons.center&&(t.icons.center.opacity=i)}}),EE.add(`iconFadeOut`,{id:`iconFadeOut`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>!!(e?.icons?.left&&!t?.icons?.left||e?.icons?.right&&!t?.icons?.right||e?.icons?.center&&!t?.icons?.center),updateAnimation:function(e,t,n,r){let i=1-DE[this.easingFn](e);t.icons||={},n.icons.left&&!r.icons.left&&(t.icons.left={...n.icons.left,opacity:i}),n.icons.right&&!r.icons.right&&(t.icons.right={...n.icons.right,opacity:i}),n.icons.center&&!r.icons.center&&(t.icons.center={...n.icons.center,opacity:i})}}),EE.add(`textChange`,{id:`textChange`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>{let n=e?.content?.textLines?.join(`
|
|
77
77
|
`),r=t?.content?.textLines?.join(`
|
|
78
|
-
`);return!!(n&&r&&(n!==r||AE(t,e)))},updateAnimation:function(e,t,n,r){let i=DE[this.easingFn](e),a=r.y+(i-1)*r.height,o=r.y+i*r.height,s=AE(r,n),c={id:r.id+`-text-slide-in`,x:r.x,y:a,width:r.width,height:r.height,style:{...r.style},skipCellGridLines:!0,content:r.content?{...r.content}:void 0,clipRect:r.clipRect||{...r,x:Math.max(0,r.x-(r.content?.width||0)),width:r.width+(r.content?.width||0)*2},icons:s?kE(r.icons,r):OE(r.icons)},l={id:n.id+`-text-slide-out`,x:r.x,y:o,width:r.width,height:r.height,style:{...n.style},skipCellGridLines:!0,content:n.content?{...n.content}:void 0,clipRect:n.clipRect||{...r,x:Math.max(0,r.x-(n.content?.width||0)),width:r.width+(n.content?.width||0)*2},icons:s?kE(n.icons,r):OE(n.icons)};if(r.content&&n.content&&c.content&&l.content){let e=r.content.y+(i-1)*r.height,t=r.content.y+i*r.height;c.content.y=e,l.content.y=t}return l.style.fillColor=c.style.fillColor=void 0,t.content=void 0,t.icons=s?{}:t.icons,{newBoxes:[c,l]}}}),EE.add(`borderFadeIn`,{id:`borderFadeIn`,easingFn:`easeInCubic`,hasAnimation:(e,t)=>!!(!e?.border?.bottom&&t?.border?.bottom||!e?.border?.top&&t?.border?.top||!e?.border?.left&&t?.border?.left||!e?.border?.right&&t?.border?.right),updateAnimation:function(e,t,n,r){let i=DE[this.easingFn](e);t.border?.top&&r.border?.top&&!n.border?.top&&(t.border.top.opacity=i),t.border?.bottom&&r.border?.bottom&&!n.border?.bottom&&(t.border.bottom.opacity=i),t.border?.left&&r.border?.left&&!n.border?.left&&(t.border.left.opacity=i),t.border?.right&&r.border?.right&&!n.border?.right&&(t.border.right.opacity=i)}}),EE.add(`borderFadeOut`,{id:`borderFadeOut`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>!!(e?.border?.bottom&&!t?.border?.bottom||e?.border?.top&&!t?.border?.top||e?.border?.left&&!t?.border?.left||e?.border?.right&&!t?.border?.right),updateAnimation:function(e,t,n,r){let i=1-DE[this.easingFn](e);t.border||={},n.border?.top&&!r.border?.top&&(t.border.top={...n.border.top,opacity:i}),n.border?.bottom&&!r.border?.bottom&&(t.border.bottom={...n.border.bottom,opacity:i}),n.border?.left&&!r.border?.left&&(t.border.left={...n.border.left,opacity:i}),n.border?.right&&!r.border?.right&&(t.border.right={...n.border.right,opacity:i})}}),EE.add(`borderColorChange`,{id:`borderColorChange`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>{let n=e?.border,r=t?.border;return!n||!r?!1:n.bottom?.color!==r.bottom?.color||n.top?.color!==r.top?.color||n.left?.color!==r.left?.color||n.right?.color!==r.right?.color},updateAnimation:function(e,t,n,r){let i=i=>{let a=n?.border?.[i],o=r?.border?.[i],s=t.border?.[i];a&&o&&s&&(s.color=zn([{value:0,color:a.color||`#000000`},{value:1,color:o.color||`#000000`}])(DE[this.easingFn](e)))};i(`top`),i(`bottom`),i(`left`),i(`right`)}}),EE.add(`iconChange`,{id:`iconChange`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>!AE(t,e)&&(e?.icons?.center?.svg?.name!==t?.icons?.center?.svg?.name||e?.icons?.left?.svg?.name!==t?.icons?.left?.svg?.name||e?.icons?.right?.svg?.name!==t?.icons?.right?.svg?.name),updateAnimation:function(e,t,n,r){let i=DE[this.easingFn](e),a=r.y+(i-1)*r.height,o=r.y+i*r.height,s=[],c=e=>{let i=n.icons?.[e],c=r.icons?.[e],l={id:`${r.id}-icon-${e}-slide-in`,style:{verticalAlign:r.style.verticalAlign},x:r.x,y:a,width:r.width,height:r.height,skipCellGridLines:!0,icons:{[e]:{...c,clipRect:r}}},u={id:`${r.id}-icon-${e}-slide-out`,style:{verticalAlign:n.style.verticalAlign},x:r.x,y:o,width:r.width,height:r.height,skipCellGridLines:!0,icons:{[e]:{...i,clipRect:r}}};t.icons[e]=OE(r.icons)[e],s.push(l,u)};return c(`left`),c(`right`),c(`center`),{newBoxes:s}}});let DE={linear:e=>e,easeInCubic:e=>e*e*e,easeOutCubic:e=>--e*e*e+1,easeInOutCubic:e=>(e/=.5)<1?.5*e*e*e:.5*((e-=2)*e*e+2),easeOutQuart:e=>-(--e*e*e*e-1)};function OE(e){return{left:e.left?{...e.left,svg:void 0}:void 0,right:e.right?{...e.right,svg:void 0}:void 0,center:e.center?{...e.center,svg:void 0}:void 0}}function kE(e,t){return{left:e.left?{...e.left,clipRect:t}:void 0,right:e.right?{...e.right,clipRect:t}:void 0,center:e.center?{...e.center,clipRect:t}:void 0}}function AE(e,t){let n=(e,t)=>t&&e?!!(e.horizontalAlign!==t.horizontalAlign||e.size!==t.size||e.margin!==t.margin||e.svg&&!t.svg||!e.svg&&t.svg):!!(e&&!t||!e&&t);return n(e?.icons.left,t?.icons.left)||n(e?.icons.right,t?.icons.right)||n(e?.icons.center,t?.icons.center)}var jE=class extends t.Component{static template=`o-spreadsheet-GaugeChartComponent`;static props={figureUI:Object,isFullScreen:{type:Boolean,optional:!0}};canvas=(0,t.useRef)(`chartContainer`);animationStore;get runtime(){return this.env.model.getters.getChartRuntime(this.props.figureUI.id)}setup(){this.env.model.getters.isDashboard()&&(this.animationStore=B(pf));let e=null,n;(0,t.useEffect)(()=>(this.env.isDashboard()&&n===void 0&&this.animationStore?.animationPlayed[this.animationFigureId]!==`gauge`||this.env.isDashboard()&&n!==void 0&&!w(this.runtime,n)?(e=this.drawGaugeWithAnimation(),this.animationStore?.disableAnimationForChart(this.animationFigureId,`gauge`)):dw(this.canvasEl,this.runtime),n=this.runtime,()=>e?.stop()),()=>{let e=this.canvasEl.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}drawGaugeWithAnimation(){dw(this.canvasEl,{...this.runtime,animationValue:0});let e=this.runtime.gaugeValue?.value||0,t=this.runtime.maxValue.value,n=Math.sign(e)*Math.min(Math.abs(e),Math.abs(t));if(n===0)return null;let r=this.runtime.minValue.value,i=new ME(r,n,1e3,e=>dw(this.canvasEl,{...this.runtime,animationValue:e}));return i.start(),i}get canvasEl(){return this.canvas.el}get animationFigureId(){return this.props.isFullScreen?this.props.figureUI.id+`-fullscreen`:this.props.figureUI.id}},ME=class{startTime=void 0;animationFrameId=null;constructor(e,t,n,r){this.startValue=e,this.endValue=t,this.duration=n,this.callback=r}start(){this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}stop(){this.animationFrameId&&=(cancelAnimationFrame(this.animationFrameId),null)}animate(e){this.startTime||=e;let t=e-this.startTime,n=Math.min(t/this.duration,1),r=this.startValue+(this.endValue-this.startValue)*DE.easeOutQuart(n);this.callback(r),n<1?this.animationFrameId=requestAnimationFrame(this.animate.bind(this)):this.stop()}},NE=class e extends SC{dataSets;labelRange;background;legendPosition;aggregated;dataSetsHaveTitle;dataSetDesign;axesDesign;type=`combo`;showValues;hideDataMarkers;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId),type:this.dataSetDesign?.[t]?.type??(t?`line`:`bar`)});return{type:`combo`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers}}getDefinitionForExcel(){let e=this.dataSets.map(e=>SS(this.getters,e)).filter(e=>e.range!==``&&e.range!==k.InvalidReference),t=CS(this.getters,this.labelRange,kS(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:lw(this.background||`#FFFFFF`),fontColor:lw(TS(this.background)),dataSets:e,labelRange:t,verticalAxis:jS(n)}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}static getDefinitionFromContextCreation(e){let t=(e.range??[]).map((e,t)=>({...e,type:t?`line`:`bar`}));return{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},labelRange:e.auxiliaryRange||void 0,type:`combo`,axesDesign:e.axesDesign,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}};function PE(e,t){let n=e.getDefinition(),r=Kw(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`bar`,data:{labels:r.labels,datasets:XS(n,r)},options:{...Ew,layout:OT(n,r),scales:BT(n,r),plugins:{title:oE(n),legend:PT(n,r),tooltip:uE(n,r),chartShowValuesPlugin:tE(n,r)}}},background:e.background||`#FFFFFF`}}var FE=class e extends SC{dataSets;labelRange;background;legendPosition;aggregated;type=`funnel`;dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;showValues;funnelColors;cumulative;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.horizontal=!0,this.funnelColors=e.funnelColors,this.cumulative=e.cumulative}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:`none`,title:e.title||{text:``},type:`funnel`,labelRange:e.auxiliaryRange||void 0,showValues:e.showValues,axesDesign:e.axesDesign,funnelColors:e.funnelColors,horizontal:!0,cumulative:e.cumulative}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`funnel`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,horizontal:this.horizontal,axesDesign:this.axesDesign,showValues:this.showValues,funnelColors:this.funnelColors,cumulative:this.cumulative}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function IE(e,t){let n=e.getDefinition(),r=Qw(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`funnel`,data:{labels:r.labels,datasets:$S(n,r)},options:{...Ew,indexAxis:`y`,layout:OT(n,r),scales:qT(n,r),plugins:{title:oE(n),legend:{display:!1},tooltip:_E(n,r),chartShowValuesPlugin:tE(n,r)}}},background:e.background||`#FFFFFF`}}function LE(e){return e.dataRange&&!fc.test(e.dataRange)?`InvalidGaugeDataRange`:`Success`}function RE(e,t){return t(t=>t.sectionRule?e(t.sectionRule.rangeMin,`rangeMin`):`Success`,t=>t.sectionRule?e(t.sectionRule.rangeMax,`rangeMax`):`Success`)}function zE(e,t){return t(t=>t.sectionRule?e(t.sectionRule.lowerInflectionPoint.value,`lowerInflectionPointValue`):`Success`,t=>t.sectionRule?e(t.sectionRule.upperInflectionPoint.value,`upperInflectionPointValue`):`Success`)}function BE(e,t){if(e===``)switch(t){case`rangeMin`:return`EmptyGaugeRangeMin`;case`rangeMax`:return`EmptyGaugeRangeMax`}return`Success`}function VE(e,t){if(e.startsWith(`=`))return`Success`;if(isNaN(e))switch(t){case`rangeMin`:return`GaugeRangeMinNaN`;case`rangeMax`:return`GaugeRangeMaxNaN`;case`lowerInflectionPointValue`:return`GaugeLowerInflectionPointNaN`;case`upperInflectionPointValue`:return`GaugeUpperInflectionPointNaN`}return`Success`}var HE=class e extends SC{dataRange;sectionRule;background;type=`gauge`;constructor(e,t,n){super(e,t,n),this.dataRange=Dc(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,LE,e.chainValidations(RE(BE,e.batchValidations),RE(VE,e.batchValidations)),e.chainValidations(zE(VE,e.batchValidations)))}static transformDefinition(e,t,n){let r;if(t.dataRange){let{changeType:i,range:a}=uS(e,t.dataRange,n);i!==`REMOVE`&&(r=a)}let i=qE(t.sectionRule,t=>lS(e,t,n));return{...t,dataRange:r,sectionRule:i}}static getDefinitionFromContextCreation(e){return{background:e.background,title:e.title||{text:``},type:`gauge`,dataRange:e.range?.[0]?.dataRange,sectionRule:{colors:{lowerColor:`#EA6175`,middleColor:`#FFD86D`,upperColor:`#43C5B1`},rangeMin:`0`,rangeMax:`100`,lowerInflectionPoint:{type:`percentage`,value:`15`,operator:`<=`},upperInflectionPoint:{type:`percentage`,value:`40`,operator:`<=`}}}}duplicateInDuplicatedSheet(t){let n=vS(this.sheetId,t,this.dataRange),r=qE(this.sectionRule,e=>this.getters.copyFormulaStringForSheet(this.sheetId,t,e,`moveReference`));return new e(this.getDefinitionWithSpecificRanges(n,r,t),t,this.getters)}copyInSheetId(t){let n=qE(this.sectionRule,e=>this.getters.copyFormulaStringForSheet(this.sheetId,t,e,`keepSameReference`));return new e(this.getDefinitionWithSpecificRanges(this.dataRange,n,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.dataRange,this.sectionRule)}getDefinitionWithSpecificRanges(e,t,n){return{background:this.background,sectionRule:t,title:this.title,type:`gauge`,dataRange:e?this.getters.getRangeString(e,n||this.sheetId):void 0}}getDefinitionForExcel(){}getContextCreation(){return{...this,range:this.dataRange?[{dataRange:this.getters.getRangeString(this.dataRange,this.sheetId)}]:void 0}}updateRanges({applyChange:t,adaptFormulaString:n}){let r=yS(this.dataRange,t),i=qE(this.sectionRule,e=>n(this.sheetId,e));return new e(this.getDefinitionWithSpecificRanges(r,i),this.sheetId,this.getters)}};function UE(e,t){let n=t.getLocale(),r=e.sectionRule.colors,i,a,o,s=e.dataRange;if(s!==void 0){let e=t.getEvaluatedCell({sheetId:s.sheetId,col:s.zone.left,row:s.zone.top});e.type===`number`&&(i=e.value,a=e.formattedValue,o=e.format)}let c=GE(e.sheetId,e.sectionRule.rangeMin,t),l=GE(e.sheetId,e.sectionRule.rangeMax,t);if(c===void 0||l===void 0)return KE(e,t);l<c&&([c,l]=[l,c]);let u=e.sectionRule.lowerInflectionPoint,d=e.sectionRule.upperInflectionPoint,f=WE(e.sheetId,e.sectionRule.lowerInflectionPoint,c,l,t),p=WE(e.sheetId,e.sectionRule.upperInflectionPoint,c,l,t),m=[],h=[];return f!==void 0&&(m.push({value:f,label:L(f,{locale:n,format:o}),operator:u.operator}),h.push(r.lowerColor)),p!==void 0&&p!==f&&(m.push({value:p,label:L(p,{locale:n,format:o}),operator:d.operator}),h.push(r.middleColor)),p!==void 0&&f!==void 0&&f>p&&(m.reverse(),h.reverse()),h.push(r.upperColor),{background:t.getStyleOfSingleCellChart(e.background,s).background,title:{...e.title,text:E(e.title.text??``)},minValue:{value:c,label:L(c,{locale:n,format:o})},maxValue:{value:l,label:L(l,{locale:n,format:o})},gaugeValue:i!==void 0&&a?{value:i,label:a}:void 0,inflectionValues:m,colors:h}}function WE(e,t,n,r,i){let a=GE(e,t.value,i);if(a!==void 0)return x(t.type===`number`?a:n+(r-n)*a/100,n,r)}function GE(e,t,n){let r=n.evaluateFormula(e,t);return Du(r)?void 0:Qi(Tu(r),n.getLocale())}function KE(e,t){return{background:t.getStyleOfSingleCellChart(e.background,e.dataRange).background,title:e.title??{text:``},minValue:{value:0,label:``},maxValue:{value:100,label:``},gaugeValue:{value:0,label:k.GenericError},inflectionValues:[],colors:[]}}function qE(e,t){return{...e,rangeMin:t(e.rangeMin),rangeMax:t(e.rangeMax),lowerInflectionPoint:{...e.lowerInflectionPoint,value:t(e.lowerInflectionPoint.value)},upperInflectionPoint:{...e.upperInflectionPoint,value:t(e.upperInflectionPoint.value)}}}var JE=class e extends SC{dataSets;labelRange;background;legendPosition;type=`geo`;dataSetsHaveTitle;dataSetDesign;colorScale;missingValueColor;region;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.colorScale=e.colorScale,this.missingValueColor=e.missingValueColor,this.region=e.region}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`geo`,labelRange:e.auxiliaryRange||void 0}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`geo`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,colorScale:this.colorScale,missingValueColor:this.missingValueColor,region:this.region}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function YE(e,t){let n=e.getDefinition(),r=Zw(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`choropleth`,data:{datasets:QS(n,r)},options:{...Ew,layout:OT(n,r),scales:KT(n,r),plugins:{title:oE(n),tooltip:gE(n,r),legend:{display:!1}}}},background:e.background||`#FFFFFF`}}var XE=class e extends SC{dataSets;labelRange;background;legendPosition;labelsAsText;stacked;aggregated;type=`line`;dataSetsHaveTitle;cumulative;dataSetDesign;axesDesign;fillArea;showValues;hideDataMarkers;constructor(e,t,n){super(e,t,n),this.dataSets=bS(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(this.getters,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.cumulative=e.cumulative,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.fillArea=e.fillArea,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static transformDefinition(e,t,n){return wS(e,t,n)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`line`,labelRange:e.auxiliaryRange||void 0,stacked:e.stacked??!1,aggregated:e.aggregated??!1,cumulative:e.cumulative??!1,axesDesign:e.axesDesign,fillArea:e.fillArea,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`line`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,stacked:this.stacked,aggregated:this.aggregated,cumulative:this.cumulative,axesDesign:this.axesDesign,fillArea:this.fillArea,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}getDefinitionForExcel(){let e=this.dataSets.map(e=>SS(this.getters,e)).filter(e=>e.range!==``&&e.range!==k.InvalidReference),t=CS(this.getters,this.labelRange,kS(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:lw(this.background||`#FFFFFF`),fontColor:lw(TS(this.background)),dataSets:e,labelRange:t,verticalAxis:jS(n)}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}};function ZE(e,t){let n=e.getDefinition(),r=Jw(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`line`,data:{labels:r.labels,datasets:qS(n,r)},options:{...Ew,layout:OT(n,r),scales:VT(n,r),plugins:{title:oE(n),legend:jT(n,r),tooltip:dE(n,r),chartShowValuesPlugin:tE(n,r)}}},background:e.background||`#FFFFFF`}}var QE=class e extends SC{dataSets;labelRange;background;legendPosition;type=`pie`;aggregated;dataSetsHaveTitle;isDoughnut;showValues;pieHolePercentage;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.isDoughnut=e.isDoughnut,this.showValues=e.showValues,this.pieHolePercentage=e.pieHolePercentage}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pie`,labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,isDoughnut:!1,showValues:e.showValues}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){return{...this,range:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)})),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinitionWithSpecificDataSets(e,t,n){return{type:`pie`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,n||this.sheetId)})),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,isDoughnut:this.isDoughnut,showValues:this.showValues,pieHolePercentage:this.pieHolePercentage}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinitionForExcel(){let e=this.dataSets.map(e=>SS(this.getters,e)).filter(e=>e.range!==``&&e.range!==k.InvalidReference),t=CS(this.getters,this.labelRange,kS(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:lw(this.background||`#FFFFFF`),fontColor:lw(TS(this.background)),dataSets:e,labelRange:t}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function $E(e,t){let n=e.getDefinition(),r=Yw(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:e.isDoughnut?`doughnut`:`pie`,data:{labels:r.labels,datasets:YS(n,r)},options:{...Ew,cutout:e.isDoughnut&&n.pieHolePercentage!==void 0?n.pieHolePercentage+`%`:void 0,layout:OT(n,r),plugins:{title:oE(n),legend:MT(n,r),tooltip:fE(n,r),chartShowValuesPlugin:tE(n,r)}}},background:e.background||`#FFFFFF`}}var eD=class e extends SC{dataSets;labelRange;background;legendPosition;aggregated;type=`pyramid`;dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;stacked=!0;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pyramid`,labelRange:e.auxiliaryRange||void 0,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`pyramid`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,horizontal:!0,stacked:!0,showValues:this.showValues}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function tD(e,t){let n=e.getDefinition(),r=qw(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`bar`,data:{labels:r.labels,datasets:GS(n,r)},options:{...Ew,indexAxis:`y`,layout:OT(n,r),scales:WT(n,r),plugins:{title:oE(n),legend:AT(n,r),tooltip:mE(n,r),chartShowValuesPlugin:rE(n,r)}}},background:e.background||`#FFFFFF`}}var nD=class e extends SC{dataSets;labelRange;background;legendPosition;stacked;aggregated;type=`radar`;dataSetsHaveTitle;dataSetDesign;fillArea;showValues;hideDataMarkers;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.fillArea=e.fillArea,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`radar`,labelRange:e.auxiliaryRange||void 0,fillArea:e.fillArea??!1,showValues:e.showValues??!1,hideDataMarkers:e.hideDataMarkers}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`radar`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated,fillArea:this.fillArea,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers}}getDefinitionForExcel(){let e=this.dataSets.map(e=>SS(this.getters,e)).filter(e=>e.range!==``&&e.range!==k.InvalidReference),t=CS(this.getters,this.labelRange,kS(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:lw(this.background||`#FFFFFF`),fontColor:lw(TS(this.background)),dataSets:e,labelRange:t}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function rD(e,t){let n=e.getDefinition(),r=Xw(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`radar`,data:{labels:r.labels,datasets:ZS(n,r)},options:{...Ew,layout:OT(n,r),scales:GT(n,r),plugins:{title:oE(n),legend:IT(n,r),tooltip:hE(n,r),chartShowValuesPlugin:tE(n,r)}}},background:e.background||`#FFFFFF`}}var iD=class e extends SC{dataSets;labelRange;background;legendPosition;labelsAsText;aggregated;type=`scatter`;dataSetsHaveTitle;dataSetDesign;axesDesign;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=bS(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(this.getters,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static transformDefinition(e,t,n){return wS(e,t,n)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`scatter`,labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`scatter`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}getDefinitionForExcel(){let e=this.dataSets.map(e=>SS(this.getters,e)).filter(e=>e.range!==``),t=CS(this.getters,this.labelRange,kS(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:lw(this.background||`#FFFFFF`),fontColor:lw(TS(this.background)),dataSets:e,labelRange:t,verticalAxis:jS(n)}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}};function aD(e,t){let n=e.getDefinition(),r=Jw(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`line`,data:{labels:r.labels,datasets:JS(n,r)},options:{...Ew,layout:OT(n,r),scales:HT(n,r),plugins:{title:oE(n),legend:NT(n,r),tooltip:dE(n,r),chartShowValuesPlugin:tE(n,r)}}},background:e.background||`#FFFFFF`}}var oD=class e extends SC{dataSets;labelRange;background;legendPosition;type=`sunburst`;dataSetsHaveTitle;showValues;showLabels;valuesDesign;groupColors;pieHolePercentage;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showValues=e.showValues,this.showLabels=e.showLabels,this.valuesDesign=e.valuesDesign,this.groupColors=e.groupColors,this.pieHolePercentage=e.pieHolePercentage}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static getDefinitionFromContextCreation(e){let t=[];return e.hierarchicalRanges?.length?t.push(...e.hierarchicalRanges):e.auxiliaryRange&&t.push({...e.range?.[0],dataRange:e.auxiliaryRange}),{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`sunburst`,labelRange:e.range?.[0]?.dataRange,showValues:e.showValues,showLabels:e.showLabels,valuesDesign:e.valuesDesign,groupColors:e.groupColors}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){let e=this.dataSets.at(-1)?.dataRange;return{...this,range:this.labelRange?[{dataRange:this.getters.getRangeString(this.labelRange,this.sheetId)}]:[],auxiliaryRange:e?this.getters.getRangeString(e,this.sheetId):void 0,hierarchicalRanges:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))}}getDefinitionWithSpecificDataSets(e,t,n){return{type:`sunburst`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,n||this.sheetId)})),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,showValues:this.showValues,showLabels:this.showLabels,valuesDesign:this.valuesDesign,groupColors:this.groupColors,pieHolePercentage:this.pieHolePercentage}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function sD(e,t){let n=e.getDefinition(),r=$w(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`doughnut`,data:{datasets:tC(n,r)},options:{cutout:e.pieHolePercentage===void 0?`25%`:`${e.pieHolePercentage}%`,...Ew,layout:OT(n,r),plugins:{title:oE(n),legend:LT(n,r),tooltip:vE(n,r),sunburstLabelsPlugin:nE(n,r),sunburstHoverPlugin:{enabled:!0}}}},background:e.background||`#FFFFFF`}}var cD=class e extends SC{static defaults={background:oe,legendPosition:`top`,dataSetsHaveTitle:!1,showHeaders:!0,headersColor:`#000000`};dataSets;labelRange;background;legendPosition;type=`treemap`;dataSetsHaveTitle;showHeaders;headerDesign;showValues;showLabels;valuesDesign;coloringOptions;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showHeaders=e.showHeaders,this.headerDesign=e.headerDesign,this.showValues=e.showValues,this.showLabels=e.showLabels,this.valuesDesign=e.valuesDesign,this.coloringOptions=e.coloringOptions}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static getDefinitionFromContextCreation(e){let t=[];return e.hierarchicalRanges?.length?t.push(...e.hierarchicalRanges):e.auxiliaryRange&&t.push({...e.range?.[0],dataRange:e.auxiliaryRange}),{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`treemap`,labelRange:e.range?.[0]?.dataRange,showValues:e.showValues,showHeaders:e.showHeaders,headerDesign:e.headerDesign,showLabels:e.showLabels,valuesDesign:e.valuesDesign,coloringOptions:e.treemapColoringOptions}}getContextCreation(){let e=this.dataSets.at(-1)?.dataRange;return{...this,range:this.labelRange?[{dataRange:this.getters.getRangeString(this.labelRange,this.sheetId)}]:[],auxiliaryRange:e?this.getters.getRangeString(e,this.sheetId):void 0,hierarchicalRanges:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,n||this.sheetId)}));return{type:`treemap`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,showValues:this.showValues,showHeaders:this.showHeaders,headerDesign:this.headerDesign,showLabels:this.showLabels,valuesDesign:this.valuesDesign,coloringOptions:this.coloringOptions}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function lD(e,t){let n=e.getDefinition(),r=$w(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`treemap`,data:{labels:r.labels,datasets:oC(n,r)},options:{...Ew,layout:OT(n,r),plugins:{title:oE(n),legend:{display:!1},tooltip:yE(n,r)}}},background:e.background||`#FFFFFF`}}var uD=class e extends SC{dataSets;labelRange;background;verticalAxisPosition;legendPosition;aggregated;type=`waterfall`;dataSetsHaveTitle;showSubTotals;firstValueAsSubtotal;showConnectorLines;positiveValuesColor;negativeValuesColor;subTotalValuesColor;dataSetDesign;axesDesign;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showSubTotals=e.showSubTotals,this.showConnectorLines=e.showConnectorLines,this.positiveValuesColor=e.positiveValuesColor,this.negativeValuesColor=e.negativeValuesColor,this.subTotalValuesColor=e.subTotalValuesColor,this.firstValueAsSubtotal=e.firstValueAsSubtotal,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`waterfall`,verticalAxisPosition:`left`,labelRange:e.auxiliaryRange||void 0,showSubTotals:e.showSubTotals??!1,showConnectorLines:e.showConnectorLines??!0,firstValueAsSubtotal:e.firstValueAsSubtotal??!1,axesDesign:e.axesDesign,showValues:e.showValues}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`waterfall`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,showSubTotals:this.showSubTotals,showConnectorLines:this.showConnectorLines,positiveValuesColor:this.positiveValuesColor,negativeValuesColor:this.negativeValuesColor,subTotalValuesColor:this.subTotalValuesColor,firstValueAsSubtotal:this.firstValueAsSubtotal,axesDesign:this.axesDesign,showValues:this.showValues}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function dD(e,t){let n=e.getDefinition(),r=Kw(n,e.dataSets,e.labelRange,t),{labels:i,datasets:a}=KS(n,r);return{chartJsConfig:{type:`bar`,data:{labels:i,datasets:a},options:{...Ew,layout:OT(n,r),scales:UT(n,r),plugins:{title:oE(n),legend:FT(n,r),tooltip:pE(n,r),chartShowValuesPlugin:iE(n,r),waterfallLinesPlugin:{showConnectorLines:n.showConnectorLines}}}},background:e.background||`#FFFFFF`}}let fD=new g;fD.add(`bar`,{match:e=>e===`bar`,createChart:(e,t,n)=>new wE(e,t,n),getChartRuntime:TE,validateChartDefinition:wE.validateChartDefinition,transformDefinition:wE.transformDefinition,getChartDefinitionFromContextCreation:wE.getDefinitionFromContextCreation,sequence:10}),fD.add(`combo`,{match:e=>e===`combo`,createChart:(e,t,n)=>new NE(e,t,n),getChartRuntime:PE,validateChartDefinition:NE.validateChartDefinition,transformDefinition:NE.transformDefinition,getChartDefinitionFromContextCreation:NE.getDefinitionFromContextCreation,sequence:15}),fD.add(`line`,{match:e=>e===`line`,createChart:(e,t,n)=>new XE(e,t,n),getChartRuntime:ZE,validateChartDefinition:XE.validateChartDefinition,transformDefinition:XE.transformDefinition,getChartDefinitionFromContextCreation:XE.getDefinitionFromContextCreation,sequence:20}),fD.add(`pie`,{match:e=>e===`pie`,createChart:(e,t,n)=>new QE(e,t,n),getChartRuntime:$E,validateChartDefinition:QE.validateChartDefinition,transformDefinition:QE.transformDefinition,getChartDefinitionFromContextCreation:QE.getDefinitionFromContextCreation,sequence:30}),fD.add(`scorecard`,{match:e=>e===`scorecard`,createChart:(e,t,n)=>new jC(e,t,n),getChartRuntime:NC,validateChartDefinition:jC.validateChartDefinition,transformDefinition:jC.transformDefinition,getChartDefinitionFromContextCreation:jC.getDefinitionFromContextCreation,sequence:40}),fD.add(`gauge`,{match:e=>e===`gauge`,createChart:(e,t,n)=>new HE(e,t,n),getChartRuntime:UE,validateChartDefinition:HE.validateChartDefinition,transformDefinition:HE.transformDefinition,getChartDefinitionFromContextCreation:HE.getDefinitionFromContextCreation,sequence:50}),fD.add(`scatter`,{match:e=>e===`scatter`,createChart:(e,t,n)=>new iD(e,t,n),getChartRuntime:aD,validateChartDefinition:iD.validateChartDefinition,transformDefinition:iD.transformDefinition,getChartDefinitionFromContextCreation:iD.getDefinitionFromContextCreation,sequence:60}),fD.add(`waterfall`,{match:e=>e===`waterfall`,createChart:(e,t,n)=>new uD(e,t,n),getChartRuntime:dD,validateChartDefinition:uD.validateChartDefinition,transformDefinition:uD.transformDefinition,getChartDefinitionFromContextCreation:uD.getDefinitionFromContextCreation,sequence:70}),fD.add(`pyramid`,{match:e=>e===`pyramid`,createChart:(e,t,n)=>new eD(e,t,n),getChartRuntime:tD,validateChartDefinition:eD.validateChartDefinition,transformDefinition:eD.transformDefinition,getChartDefinitionFromContextCreation:eD.getDefinitionFromContextCreation,sequence:80,dataSeriesLimit:2}),fD.add(`radar`,{match:e=>e===`radar`,createChart:(e,t,n)=>new nD(e,t,n),getChartRuntime:rD,validateChartDefinition:nD.validateChartDefinition,transformDefinition:nD.transformDefinition,getChartDefinitionFromContextCreation:nD.getDefinitionFromContextCreation,sequence:80}),fD.add(`geo`,{match:e=>e===`geo`,createChart:(e,t,n)=>new JE(e,t,n),getChartRuntime:YE,validateChartDefinition:JE.validateChartDefinition,transformDefinition:JE.transformDefinition,getChartDefinitionFromContextCreation:JE.getDefinitionFromContextCreation,sequence:90,dataSeriesLimit:1}),fD.add(`funnel`,{match:e=>e===`funnel`,createChart:(e,t,n)=>new FE(e,t,n),getChartRuntime:IE,validateChartDefinition:FE.validateChartDefinition,transformDefinition:FE.transformDefinition,getChartDefinitionFromContextCreation:FE.getDefinitionFromContextCreation,sequence:100,dataSeriesLimit:1}),fD.add(`sunburst`,{match:e=>e===`sunburst`,createChart:(e,t,n)=>new oD(e,t,n),getChartRuntime:sD,validateChartDefinition:oD.validateChartDefinition,transformDefinition:oD.transformDefinition,getChartDefinitionFromContextCreation:oD.getDefinitionFromContextCreation,sequence:30}),fD.add(`treemap`,{match:e=>e===`treemap`,createChart:(e,t,n)=>new cD(e,t,n),getChartRuntime:lD,validateChartDefinition:cD.validateChartDefinition,transformDefinition:cD.transformDefinition,getChartDefinitionFromContextCreation:cD.getDefinitionFromContextCreation,sequence:100});let pD=new g;pD.add(`line`,xC),pD.add(`bar`,xC),pD.add(`combo`,xC),pD.add(`pie`,xC),pD.add(`gauge`,jE),pD.add(`scatter`,xC),pD.add(`scorecard`,RC),pD.add(`waterfall`,xC),pD.add(`pyramid`,xC),pD.add(`radar`,xC),pD.add(`geo`,xC),pD.add(`funnel`,xC),pD.add(`sunburst`,xC),pD.add(`treemap`,xC);let mD={line:E(`Line`),column:E(`Column`),bar:E(`Bar`),area:E(`Area`),pie:E(`Pie`),hierarchical:E(`Hierarchical`),misc:E(`Miscellaneous`)},hD=new g;hD.add(`line`,{matcher:e=>e.type===`line`&&!e.stacked&&!e.fillArea,displayName:E(`Line`),chartType:`line`,chartSubtype:`line`,subtypeDefinition:{stacked:!1,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.LINE_CHART`}).add(`stacked_line`,{matcher:e=>e.type===`line`&&!e.fillArea&&!!e.stacked,displayName:E(`Stacked Line`),chartType:`line`,chartSubtype:`stacked_line`,subtypeDefinition:{stacked:!0,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.STACKED_LINE_CHART`}).add(`area`,{matcher:e=>e.type===`line`&&!e.stacked&&!!e.fillArea,displayName:E(`Area`),chartType:`line`,chartSubtype:`area`,subtypeDefinition:{stacked:!1,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.AREA_CHART`}).add(`stacked_area`,{matcher:e=>e.type===`line`&&e.stacked&&!!e.fillArea,displayName:E(`Stacked Area`),chartType:`line`,chartSubtype:`stacked_area`,subtypeDefinition:{stacked:!0,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.STACKED_AREA_CHART`}).add(`scatter`,{displayName:E(`Scatter`),chartType:`scatter`,chartSubtype:`scatter`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCATTER_CHART`}).add(`column`,{matcher:e=>e.type===`bar`&&!e.stacked&&!e.horizontal,displayName:E(`Column`),chartType:`bar`,chartSubtype:`column`,subtypeDefinition:{stacked:!1,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.COLUMN_CHART`}).add(`stacked_column`,{matcher:e=>e.type===`bar`&&e.stacked&&!e.horizontal,displayName:E(`Stacked Column`),chartType:`bar`,chartSubtype:`stacked_column`,subtypeDefinition:{stacked:!0,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.STACKED_COLUMN_CHART`}).add(`bar`,{matcher:e=>e.type===`bar`&&!e.stacked&&!!e.horizontal,displayName:E(`Bar`),chartType:`bar`,chartSubtype:`bar`,subtypeDefinition:{horizontal:!0,stacked:!1},category:`bar`,preview:`o-spreadsheet-ChartPreview.BAR_CHART`}).add(`stacked_bar`,{matcher:e=>e.type===`bar`&&e.stacked&&!!e.horizontal,displayName:E(`Stacked Bar`),chartType:`bar`,chartSubtype:`stacked_bar`,subtypeDefinition:{horizontal:!0,stacked:!0},category:`bar`,preview:`o-spreadsheet-ChartPreview.STACKED_BAR_CHART`}).add(`combo`,{displayName:E(`Combo`),chartSubtype:`combo`,chartType:`combo`,category:`line`,preview:`o-spreadsheet-ChartPreview.COMBO_CHART`}).add(`pie`,{matcher:e=>e.type===`pie`&&!e.isDoughnut,displayName:E(`Pie`),chartSubtype:`pie`,chartType:`pie`,subtypeDefinition:{isDoughnut:!1},category:`pie`,preview:`o-spreadsheet-ChartPreview.PIE_CHART`}).add(`doughnut`,{matcher:e=>e.type===`pie`&&!!e.isDoughnut,displayName:E(`Doughnut`),chartSubtype:`doughnut`,chartType:`pie`,subtypeDefinition:{isDoughnut:!0},category:`pie`,preview:`o-spreadsheet-ChartPreview.DOUGHNUT_CHART`}).add(`gauge`,{displayName:E(`Gauge`),chartSubtype:`gauge`,chartType:`gauge`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GAUGE_CHART`}).add(`scorecard`,{displayName:E(`Scorecard`),chartSubtype:`scorecard`,chartType:`scorecard`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCORECARD_CHART`}).add(`waterfall`,{displayName:E(`Waterfall`),chartSubtype:`waterfall`,chartType:`waterfall`,category:`misc`,preview:`o-spreadsheet-ChartPreview.WATERFALL_CHART`}).add(`pyramid`,{displayName:E(`Population Pyramid`),chartSubtype:`pyramid`,chartType:`pyramid`,category:`misc`,preview:`o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART`}).add(`radar`,{matcher:e=>e.type===`radar`&&!e.fillArea,displayName:E(`Radar`),chartSubtype:`radar`,chartType:`radar`,subtypeDefinition:{fillArea:!1},category:`misc`,preview:`o-spreadsheet-ChartPreview.RADAR_CHART`}).add(`filled_radar`,{matcher:e=>e.type===`radar`&&!!e.fillArea,displayName:E(`Filled Radar`),chartType:`radar`,chartSubtype:`filled_radar`,subtypeDefinition:{fillArea:!0},category:`misc`,preview:`o-spreadsheet-ChartPreview.FILLED_RADAR_CHART`}).add(`geo`,{displayName:E(`Geo Chart`),chartSubtype:`geo`,chartType:`geo`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GEO_CHART`}).add(`funnel`,{displayName:E(`Funnel`),chartSubtype:`funnel`,chartType:`funnel`,category:`misc`,preview:`o-spreadsheet-ChartPreview.FUNNEL_CHART`}).add(`sunburst`,{matcher:e=>e.type===`sunburst`,displayName:E(`Sunburst`),chartSubtype:`sunburst`,chartType:`sunburst`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.SUNBURST_CHART`}).add(`treemap`,{matcher:e=>e.type===`treemap`,displayName:E(`Tree Map`),chartType:`treemap`,chartSubtype:`treemap`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.TREE_MAP_CHART`});function gD(e){let t=fD.getAll().sort((e,t)=>e.sequence-t.sequence);function n(n,r,i){let a=t.find(e=>e.match(r.type));if(!a)throw Error(`No builder for this chart: ${r.type}`);return a.createChart(r,i,e)}return n}function _D(e){let t=fD.getAll().sort((e,t)=>e.sequence-t.sequence);function n(n){let r=t.find(e=>e.match(n.type));if(!r)throw Error(`No runtime builder for this chart.`);return r.getChartRuntime(n,e)}return n}function vD(e,t){let n=fD.getAll().find(e=>e.match(t.type));if(!n)throw Error(`Unknown chart type.`);return n.validateChartDefinition(e,t)}function yD(e,t,n){let r=fD.getAll().find(e=>e.match(t.type));if(!r)throw Error(`Unknown chart type.`);return r.transformDefinition(e,t,n)}function bD(e,t){let n=xD(t,e);if(n)return n;let r=t.getActiveSheetId(),i=e,a=js(e).numberOfCols===1;a||(i={...e,left:e.left+1});let o=vs(t.getUnboundedZone(r,i)),s=[{dataRange:o,yAxisId:`y`}],c=t.getCell({sheetId:r,col:e.left,row:e.top});if(Ws(e)===1&&c?.content)return{type:`scorecard`,title:{},background:c.style?.fillColor||void 0,keyValue:vs(e),baselineMode:Ge,baselineColorUp:Ke,baselineColorDown:qe};let l=!!t.getEvaluatedCellsInZone(r,{...i,bottom:i.top}).find(e=>e.type!==`empty`&&e.type!==`number`),u;a||(u=vs(t.getUnboundedZone(r,{...e,right:e.left})));let d=i.right===i.left?`none`:`top`,f={title:{},dataSets:s,labelsAsText:!1,stacked:!1,aggregated:!1,cumulative:!1,labelRange:u,type:`line`,dataSetsHaveTitle:l,legendPosition:d},p=new XE(f,r,t);if(sT(f,p.dataSets,p.labelRange,t))return f;let m=bS(t,s,r,l);return a&&hT(t,m[0]).every(e=>typeof e==`string`&&!j(e))?{title:{},dataSets:[{dataRange:o}],aggregated:!0,labelRange:o,type:`pie`,legendPosition:`top`,dataSetsHaveTitle:!1}:{title:{},dataSets:s,labelRange:u,type:`bar`,stacked:!1,aggregated:!1,dataSetsHaveTitle:l,legendPosition:d}}function xD(e,t){let n=e.getActiveSheetId(),r=js(t).numberOfCols;if(t.top===t.bottom||r<=2)return;let i=e.getEvaluatedCell({sheetId:n,col:t.right,row:t.top}).type!==`number`,a=r=>{let a=e.getEvaluatedCellsInZone(n,{...t,left:r,right:r,top:t.top+ +!!i});if(a.every(e=>e.type!==`number`))return`string`;if(a.every(e=>e.type!==`text`))return`number`};for(let e=t.left;e<t.right;e++){let n=a(e);if(e!==t.right&&n!==`string`||e===t.right&&n!==`number`)return}let o={...t,right:t.right-1},s={...t,left:t.right};return{title:{},dataSets:[{dataRange:vs(o)}],type:`sunburst`,legendPosition:`none`,labelRange:vs(s),dataSetsHaveTitle:i}}var SD=l({AbstractChart:()=>SC,BarChart:()=>wE,CHART_AXIS_CHOICES:()=>PS,CHART_COMMON_OPTIONS:()=>Ew,GaugeChart:()=>HE,LineChart:()=>XE,MOVING_AVERAGE_TREND_LINE_XAXIS_ID:()=>mS,PieChart:()=>QE,SPREADSHEET_TO_EXCEL_TRENDLINE_TYPE_MAPPING:()=>hS,ScorecardChart:()=>jC,TREND_LINE_XAXIS_ID:()=>`x1`,WaterfallChart:()=>uD,adaptChartRange:()=>yS,chartFactory:()=>gD,chartFontColor:()=>TS,chartMutedFontColor:()=>ES,chartRuntimeFactory:()=>_D,chartToImageFile:()=>Ow,chartToImageUrl:()=>Dw,checkDataset:()=>DS,checkLabelRange:()=>OS,createBarChartRuntime:()=>TE,createDataSets:()=>bS,createGaugeChartRuntime:()=>UE,createLineChartRuntime:()=>ZE,createPieChartRuntime:()=>$E,createScorecardChartRuntime:()=>NC,createWaterfallChartRuntime:()=>dD,drawScoreChart:()=>MC,duplicateDataSetsInDuplicatedSheet:()=>_S,duplicateLabelRangeInDuplicatedSheet:()=>vS,formatChartDatasetValue:()=>MS,formatTickValue:()=>NS,getChartPositionAtCenterOfViewport:()=>AS,getDefinedAxis:()=>jS,getPieColors:()=>FS,getSmartChartDefinition:()=>bD,isTrendLineAxis:()=>LS,shouldRemoveFirstLabel:()=>kS,toExcelDataset:()=>SS,toExcelLabelRange:()=>CS,transformChartDefinitionWithDataSetsWithZone:()=>wS,transformDefinition:()=>yD,truncateLabel:()=>IS,updateChartRangesWithDataSets:()=>gS,validateChartDefinition:()=>vD});function CD(e,t){let{scrollX:n,scrollY:r}=e.getActiveSheetScrollInfo(),i=e.getSheetViewDimension(),a=n+Math.max(0,(i.width-t.width)/2),o=r+Math.max(0,(i.height-t.height)/2);return e.getPositionAnchorOffset({x:a,y:o})}function wD(e,t){let n=b(t),r=e.getSheetViewDimension(),i=r.width,a=r.height;if(n.width>i){let e=i/n.width;n.width=i,n.height*=e}if(n.height>a){let e=a/n.height;n.height=a,n.width*=e}return n}var TD=class{constructor(e){this.xmlString=e}toString(){return this.xmlString}};let ED=[`areaChart`,`area3DChart`,`lineChart`,`line3DChart`,`stockChart`,`radarChart`,`scatterChart`,`pieChart`,`pie3DChart`,`doughnutChart`,`barChart`,`bar3DChart`,`ofPieChart`,`surfaceChart`,`surface3DChart`,`bubbleChart`,`comboChart`,`radarChart`];function DD(e,t,n){return{content:new XMLSerializer().serializeToString(e),path:t,contentType:n}}function OD(e){return String(e).replace(/\&/g,`&`).replace(/\</g,`<`).replace(/\>/g,`>`).replace(/\"/g,`"`).replace(/\'/g,`'`).replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,``)}function K(e){return new TD(e.map(([e,t])=>`${e}="${OD(t)}"`).join(` `))}function kD(e,t=`text/xml`){let n=new DOMParser().parseFromString(e.toString(),t),r=n.querySelector(`parsererror`);if(r){let t=r.innerHTML,n=parseInt(t.split(`:`)[0],10),i=e.toString().trim().split(`
|
|
78
|
+
`);return!!(n&&r&&(n!==r||AE(t,e)))},updateAnimation:function(e,t,n,r){let i=DE[this.easingFn](e),a=r.y+(i-1)*r.height,o=r.y+i*r.height,s=AE(r,n),c={id:r.id+`-text-slide-in`,x:r.x,y:a,width:r.width,height:r.height,style:{...r.style},skipCellGridLines:!0,content:r.content?{...r.content}:void 0,clipRect:r.clipRect||{...r,x:Math.max(0,r.x-(r.content?.width||0)),width:r.width+(r.content?.width||0)*2},icons:s?kE(r.icons,r):OE(r.icons)},l={id:n.id+`-text-slide-out`,x:r.x,y:o,width:r.width,height:r.height,style:{...n.style},skipCellGridLines:!0,content:n.content?{...n.content}:void 0,clipRect:n.clipRect||{...r,x:Math.max(0,r.x-(n.content?.width||0)),width:r.width+(n.content?.width||0)*2},icons:s?kE(n.icons,r):OE(n.icons)};if(r.content&&n.content&&c.content&&l.content){let e=r.content.y+(i-1)*r.height,t=r.content.y+i*r.height;c.content.y=e,l.content.y=t}return l.style.fillColor=c.style.fillColor=void 0,t.content=void 0,t.icons=s?{}:t.icons,{newBoxes:[c,l]}}}),EE.add(`borderFadeIn`,{id:`borderFadeIn`,easingFn:`easeInCubic`,hasAnimation:(e,t)=>!!(!e?.border?.bottom&&t?.border?.bottom||!e?.border?.top&&t?.border?.top||!e?.border?.left&&t?.border?.left||!e?.border?.right&&t?.border?.right),updateAnimation:function(e,t,n,r){let i=DE[this.easingFn](e);t.border?.top&&r.border?.top&&!n.border?.top&&(t.border.top.opacity=i),t.border?.bottom&&r.border?.bottom&&!n.border?.bottom&&(t.border.bottom.opacity=i),t.border?.left&&r.border?.left&&!n.border?.left&&(t.border.left.opacity=i),t.border?.right&&r.border?.right&&!n.border?.right&&(t.border.right.opacity=i)}}),EE.add(`borderFadeOut`,{id:`borderFadeOut`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>!!(e?.border?.bottom&&!t?.border?.bottom||e?.border?.top&&!t?.border?.top||e?.border?.left&&!t?.border?.left||e?.border?.right&&!t?.border?.right),updateAnimation:function(e,t,n,r){let i=1-DE[this.easingFn](e);t.border||={},n.border?.top&&!r.border?.top&&(t.border.top={...n.border.top,opacity:i}),n.border?.bottom&&!r.border?.bottom&&(t.border.bottom={...n.border.bottom,opacity:i}),n.border?.left&&!r.border?.left&&(t.border.left={...n.border.left,opacity:i}),n.border?.right&&!r.border?.right&&(t.border.right={...n.border.right,opacity:i})}}),EE.add(`borderColorChange`,{id:`borderColorChange`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>{let n=e?.border,r=t?.border;return!n||!r?!1:n.bottom?.color!==r.bottom?.color||n.top?.color!==r.top?.color||n.left?.color!==r.left?.color||n.right?.color!==r.right?.color},updateAnimation:function(e,t,n,r){let i=i=>{let a=n?.border?.[i],o=r?.border?.[i],s=t.border?.[i];a&&o&&s&&(s.color=zn([{value:0,color:a.color||`#000000`},{value:1,color:o.color||`#000000`}])(DE[this.easingFn](e)))};i(`top`),i(`bottom`),i(`left`),i(`right`)}}),EE.add(`iconChange`,{id:`iconChange`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>!AE(t,e)&&(e?.icons?.center?.svg?.name!==t?.icons?.center?.svg?.name||e?.icons?.left?.svg?.name!==t?.icons?.left?.svg?.name||e?.icons?.right?.svg?.name!==t?.icons?.right?.svg?.name),updateAnimation:function(e,t,n,r){let i=DE[this.easingFn](e),a=r.y+(i-1)*r.height,o=r.y+i*r.height,s=[],c=e=>{let i=n.icons?.[e],c=r.icons?.[e],l={id:`${r.id}-icon-${e}-slide-in`,style:{verticalAlign:r.style.verticalAlign},x:r.x,y:a,width:r.width,height:r.height,skipCellGridLines:!0,icons:{[e]:{...c,clipRect:r}}},u={id:`${r.id}-icon-${e}-slide-out`,style:{verticalAlign:n.style.verticalAlign},x:r.x,y:o,width:r.width,height:r.height,skipCellGridLines:!0,icons:{[e]:{...i,clipRect:r}}};t.icons[e]=OE(r.icons)[e],s.push(l,u)};return c(`left`),c(`right`),c(`center`),{newBoxes:s}}});let DE={linear:e=>e,easeInCubic:e=>e*e*e,easeOutCubic:e=>--e*e*e+1,easeInOutCubic:e=>(e/=.5)<1?.5*e*e*e:.5*((e-=2)*e*e+2),easeOutQuart:e=>-(--e*e*e*e-1)};function OE(e){return{left:e.left?{...e.left,svg:void 0}:void 0,right:e.right?{...e.right,svg:void 0}:void 0,center:e.center?{...e.center,svg:void 0}:void 0}}function kE(e,t){return{left:e.left?{...e.left,clipRect:t}:void 0,right:e.right?{...e.right,clipRect:t}:void 0,center:e.center?{...e.center,clipRect:t}:void 0}}function AE(e,t){let n=(e,t)=>t&&e?!!(e.horizontalAlign!==t.horizontalAlign||e.size!==t.size||e.margin!==t.margin||e.svg&&!t.svg||!e.svg&&t.svg):!!(e&&!t||!e&&t);return n(e?.icons.left,t?.icons.left)||n(e?.icons.right,t?.icons.right)||n(e?.icons.center,t?.icons.center)}var jE=class extends t.Component{static template=`o-spreadsheet-GaugeChartComponent`;static props={figureUI:Object,isFullScreen:{type:Boolean,optional:!0}};canvas=(0,t.useRef)(`chartContainer`);animationStore;get runtime(){return this.env.model.getters.getChartRuntime(this.props.figureUI.id)}setup(){this.env.model.getters.isDashboard()&&(this.animationStore=B(pf));let e=null,n;(0,t.useEffect)(()=>(this.env.isDashboard()&&n===void 0&&this.animationStore?.animationPlayed[this.animationFigureId]!==`gauge`||this.env.isDashboard()&&n!==void 0&&!w(this.runtime,n)?(e=this.drawGaugeWithAnimation(),this.animationStore?.disableAnimationForChart(this.animationFigureId,`gauge`)):dw(this.canvasEl,this.runtime),n=this.runtime,()=>e?.stop()),()=>{let e=this.canvasEl.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}drawGaugeWithAnimation(){dw(this.canvasEl,{...this.runtime,animationValue:0});let e=this.runtime.gaugeValue?.value||0,t=this.runtime.maxValue.value,n=Math.sign(e)*Math.min(Math.abs(e),Math.abs(t));if(n===0)return null;let r=this.runtime.minValue.value,i=new ME(r,n,1e3,e=>dw(this.canvasEl,{...this.runtime,animationValue:e}));return i.start(),i}get canvasEl(){return this.canvas.el}get animationFigureId(){return this.props.isFullScreen?this.props.figureUI.id+`-fullscreen`:this.props.figureUI.id}},ME=class{startValue;endValue;duration;callback;startTime=void 0;animationFrameId=null;constructor(e,t,n,r){this.startValue=e,this.endValue=t,this.duration=n,this.callback=r}start(){this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}stop(){this.animationFrameId&&=(cancelAnimationFrame(this.animationFrameId),null)}animate(e){this.startTime||=e;let t=e-this.startTime,n=Math.min(t/this.duration,1),r=this.startValue+(this.endValue-this.startValue)*DE.easeOutQuart(n);this.callback(r),n<1?this.animationFrameId=requestAnimationFrame(this.animate.bind(this)):this.stop()}},NE=class e extends SC{dataSets;labelRange;background;legendPosition;aggregated;dataSetsHaveTitle;dataSetDesign;axesDesign;type=`combo`;showValues;hideDataMarkers;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId),type:this.dataSetDesign?.[t]?.type??(t?`line`:`bar`)});return{type:`combo`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers}}getDefinitionForExcel(){let e=this.dataSets.map(e=>SS(this.getters,e)).filter(e=>e.range!==``&&e.range!==k.InvalidReference),t=CS(this.getters,this.labelRange,kS(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:lw(this.background||`#FFFFFF`),fontColor:lw(TS(this.background)),dataSets:e,labelRange:t,verticalAxis:jS(n)}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}static getDefinitionFromContextCreation(e){let t=(e.range??[]).map((e,t)=>({...e,type:t?`line`:`bar`}));return{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},labelRange:e.auxiliaryRange||void 0,type:`combo`,axesDesign:e.axesDesign,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}};function PE(e,t){let n=e.getDefinition(),r=Kw(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`bar`,data:{labels:r.labels,datasets:XS(n,r)},options:{...Ew,layout:OT(n,r),scales:BT(n,r),plugins:{title:oE(n),legend:PT(n,r),tooltip:uE(n,r),chartShowValuesPlugin:tE(n,r)}}},background:e.background||`#FFFFFF`}}var FE=class e extends SC{dataSets;labelRange;background;legendPosition;aggregated;type=`funnel`;dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;showValues;funnelColors;cumulative;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.horizontal=!0,this.funnelColors=e.funnelColors,this.cumulative=e.cumulative}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:`none`,title:e.title||{text:``},type:`funnel`,labelRange:e.auxiliaryRange||void 0,showValues:e.showValues,axesDesign:e.axesDesign,funnelColors:e.funnelColors,horizontal:!0,cumulative:e.cumulative}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`funnel`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,horizontal:this.horizontal,axesDesign:this.axesDesign,showValues:this.showValues,funnelColors:this.funnelColors,cumulative:this.cumulative}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function IE(e,t){let n=e.getDefinition(),r=Qw(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`funnel`,data:{labels:r.labels,datasets:$S(n,r)},options:{...Ew,indexAxis:`y`,layout:OT(n,r),scales:qT(n,r),plugins:{title:oE(n),legend:{display:!1},tooltip:_E(n,r),chartShowValuesPlugin:tE(n,r)}}},background:e.background||`#FFFFFF`}}function LE(e){return e.dataRange&&!fc.test(e.dataRange)?`InvalidGaugeDataRange`:`Success`}function RE(e,t){return t(t=>t.sectionRule?e(t.sectionRule.rangeMin,`rangeMin`):`Success`,t=>t.sectionRule?e(t.sectionRule.rangeMax,`rangeMax`):`Success`)}function zE(e,t){return t(t=>t.sectionRule?e(t.sectionRule.lowerInflectionPoint.value,`lowerInflectionPointValue`):`Success`,t=>t.sectionRule?e(t.sectionRule.upperInflectionPoint.value,`upperInflectionPointValue`):`Success`)}function BE(e,t){if(e===``)switch(t){case`rangeMin`:return`EmptyGaugeRangeMin`;case`rangeMax`:return`EmptyGaugeRangeMax`}return`Success`}function VE(e,t){if(e.startsWith(`=`))return`Success`;if(isNaN(e))switch(t){case`rangeMin`:return`GaugeRangeMinNaN`;case`rangeMax`:return`GaugeRangeMaxNaN`;case`lowerInflectionPointValue`:return`GaugeLowerInflectionPointNaN`;case`upperInflectionPointValue`:return`GaugeUpperInflectionPointNaN`}return`Success`}var HE=class e extends SC{dataRange;sectionRule;background;type=`gauge`;constructor(e,t,n){super(e,t,n),this.dataRange=Dc(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,LE,e.chainValidations(RE(BE,e.batchValidations),RE(VE,e.batchValidations)),e.chainValidations(zE(VE,e.batchValidations)))}static transformDefinition(e,t,n){let r;if(t.dataRange){let{changeType:i,range:a}=uS(e,t.dataRange,n);i!==`REMOVE`&&(r=a)}let i=qE(t.sectionRule,t=>lS(e,t,n));return{...t,dataRange:r,sectionRule:i}}static getDefinitionFromContextCreation(e){return{background:e.background,title:e.title||{text:``},type:`gauge`,dataRange:e.range?.[0]?.dataRange,sectionRule:{colors:{lowerColor:`#EA6175`,middleColor:`#FFD86D`,upperColor:`#43C5B1`},rangeMin:`0`,rangeMax:`100`,lowerInflectionPoint:{type:`percentage`,value:`15`,operator:`<=`},upperInflectionPoint:{type:`percentage`,value:`40`,operator:`<=`}}}}duplicateInDuplicatedSheet(t){let n=vS(this.sheetId,t,this.dataRange),r=qE(this.sectionRule,e=>this.getters.copyFormulaStringForSheet(this.sheetId,t,e,`moveReference`));return new e(this.getDefinitionWithSpecificRanges(n,r,t),t,this.getters)}copyInSheetId(t){let n=qE(this.sectionRule,e=>this.getters.copyFormulaStringForSheet(this.sheetId,t,e,`keepSameReference`));return new e(this.getDefinitionWithSpecificRanges(this.dataRange,n,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.dataRange,this.sectionRule)}getDefinitionWithSpecificRanges(e,t,n){return{background:this.background,sectionRule:t,title:this.title,type:`gauge`,dataRange:e?this.getters.getRangeString(e,n||this.sheetId):void 0}}getDefinitionForExcel(){}getContextCreation(){return{...this,range:this.dataRange?[{dataRange:this.getters.getRangeString(this.dataRange,this.sheetId)}]:void 0}}updateRanges({applyChange:t,adaptFormulaString:n}){let r=yS(this.dataRange,t),i=qE(this.sectionRule,e=>n(this.sheetId,e));return new e(this.getDefinitionWithSpecificRanges(r,i),this.sheetId,this.getters)}};function UE(e,t){let n=t.getLocale(),r=e.sectionRule.colors,i,a,o,s=e.dataRange;if(s!==void 0){let e=t.getEvaluatedCell({sheetId:s.sheetId,col:s.zone.left,row:s.zone.top});e.type===`number`&&(i=e.value,a=e.formattedValue,o=e.format)}let c=GE(e.sheetId,e.sectionRule.rangeMin,t),l=GE(e.sheetId,e.sectionRule.rangeMax,t);if(c===void 0||l===void 0)return KE(e,t);l<c&&([c,l]=[l,c]);let u=e.sectionRule.lowerInflectionPoint,d=e.sectionRule.upperInflectionPoint,f=WE(e.sheetId,e.sectionRule.lowerInflectionPoint,c,l,t),p=WE(e.sheetId,e.sectionRule.upperInflectionPoint,c,l,t),m=[],h=[];return f!==void 0&&(m.push({value:f,label:L(f,{locale:n,format:o}),operator:u.operator}),h.push(r.lowerColor)),p!==void 0&&p!==f&&(m.push({value:p,label:L(p,{locale:n,format:o}),operator:d.operator}),h.push(r.middleColor)),p!==void 0&&f!==void 0&&f>p&&(m.reverse(),h.reverse()),h.push(r.upperColor),{background:t.getStyleOfSingleCellChart(e.background,s).background,title:{...e.title,text:E(e.title.text??``)},minValue:{value:c,label:L(c,{locale:n,format:o})},maxValue:{value:l,label:L(l,{locale:n,format:o})},gaugeValue:i!==void 0&&a?{value:i,label:a}:void 0,inflectionValues:m,colors:h}}function WE(e,t,n,r,i){let a=GE(e,t.value,i);if(a!==void 0)return x(t.type===`number`?a:n+(r-n)*a/100,n,r)}function GE(e,t,n){let r=n.evaluateFormula(e,t);return Du(r)?void 0:Qi(Tu(r),n.getLocale())}function KE(e,t){return{background:t.getStyleOfSingleCellChart(e.background,e.dataRange).background,title:e.title??{text:``},minValue:{value:0,label:``},maxValue:{value:100,label:``},gaugeValue:{value:0,label:k.GenericError},inflectionValues:[],colors:[]}}function qE(e,t){return{...e,rangeMin:t(e.rangeMin),rangeMax:t(e.rangeMax),lowerInflectionPoint:{...e.lowerInflectionPoint,value:t(e.lowerInflectionPoint.value)},upperInflectionPoint:{...e.upperInflectionPoint,value:t(e.upperInflectionPoint.value)}}}var JE=class e extends SC{dataSets;labelRange;background;legendPosition;type=`geo`;dataSetsHaveTitle;dataSetDesign;colorScale;missingValueColor;region;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.colorScale=e.colorScale,this.missingValueColor=e.missingValueColor,this.region=e.region}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`geo`,labelRange:e.auxiliaryRange||void 0}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`geo`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,colorScale:this.colorScale,missingValueColor:this.missingValueColor,region:this.region}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function YE(e,t){let n=e.getDefinition(),r=Zw(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`choropleth`,data:{datasets:QS(n,r)},options:{...Ew,layout:OT(n,r),scales:KT(n,r),plugins:{title:oE(n),tooltip:gE(n,r),legend:{display:!1}}}},background:e.background||`#FFFFFF`}}var XE=class e extends SC{dataSets;labelRange;background;legendPosition;labelsAsText;stacked;aggregated;type=`line`;dataSetsHaveTitle;cumulative;dataSetDesign;axesDesign;fillArea;showValues;hideDataMarkers;constructor(e,t,n){super(e,t,n),this.dataSets=bS(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(this.getters,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.cumulative=e.cumulative,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.fillArea=e.fillArea,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static transformDefinition(e,t,n){return wS(e,t,n)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`line`,labelRange:e.auxiliaryRange||void 0,stacked:e.stacked??!1,aggregated:e.aggregated??!1,cumulative:e.cumulative??!1,axesDesign:e.axesDesign,fillArea:e.fillArea,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`line`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,stacked:this.stacked,aggregated:this.aggregated,cumulative:this.cumulative,axesDesign:this.axesDesign,fillArea:this.fillArea,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}getDefinitionForExcel(){let e=this.dataSets.map(e=>SS(this.getters,e)).filter(e=>e.range!==``&&e.range!==k.InvalidReference),t=CS(this.getters,this.labelRange,kS(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:lw(this.background||`#FFFFFF`),fontColor:lw(TS(this.background)),dataSets:e,labelRange:t,verticalAxis:jS(n)}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}};function ZE(e,t){let n=e.getDefinition(),r=Jw(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`line`,data:{labels:r.labels,datasets:qS(n,r)},options:{...Ew,layout:OT(n,r),scales:VT(n,r),plugins:{title:oE(n),legend:jT(n,r),tooltip:dE(n,r),chartShowValuesPlugin:tE(n,r)}}},background:e.background||`#FFFFFF`}}var QE=class e extends SC{dataSets;labelRange;background;legendPosition;type=`pie`;aggregated;dataSetsHaveTitle;isDoughnut;showValues;pieHolePercentage;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.isDoughnut=e.isDoughnut,this.showValues=e.showValues,this.pieHolePercentage=e.pieHolePercentage}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pie`,labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,isDoughnut:!1,showValues:e.showValues}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){return{...this,range:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)})),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinitionWithSpecificDataSets(e,t,n){return{type:`pie`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,n||this.sheetId)})),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,isDoughnut:this.isDoughnut,showValues:this.showValues,pieHolePercentage:this.pieHolePercentage}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinitionForExcel(){let e=this.dataSets.map(e=>SS(this.getters,e)).filter(e=>e.range!==``&&e.range!==k.InvalidReference),t=CS(this.getters,this.labelRange,kS(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:lw(this.background||`#FFFFFF`),fontColor:lw(TS(this.background)),dataSets:e,labelRange:t}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function $E(e,t){let n=e.getDefinition(),r=Yw(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:e.isDoughnut?`doughnut`:`pie`,data:{labels:r.labels,datasets:YS(n,r)},options:{...Ew,cutout:e.isDoughnut&&n.pieHolePercentage!==void 0?n.pieHolePercentage+`%`:void 0,layout:OT(n,r),plugins:{title:oE(n),legend:MT(n,r),tooltip:fE(n,r),chartShowValuesPlugin:tE(n,r)}}},background:e.background||`#FFFFFF`}}var eD=class e extends SC{dataSets;labelRange;background;legendPosition;aggregated;type=`pyramid`;dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;stacked=!0;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pyramid`,labelRange:e.auxiliaryRange||void 0,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`pyramid`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,horizontal:!0,stacked:!0,showValues:this.showValues}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function tD(e,t){let n=e.getDefinition(),r=qw(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`bar`,data:{labels:r.labels,datasets:GS(n,r)},options:{...Ew,indexAxis:`y`,layout:OT(n,r),scales:WT(n,r),plugins:{title:oE(n),legend:AT(n,r),tooltip:mE(n,r),chartShowValuesPlugin:rE(n,r)}}},background:e.background||`#FFFFFF`}}var nD=class e extends SC{dataSets;labelRange;background;legendPosition;stacked;aggregated;type=`radar`;dataSetsHaveTitle;dataSetDesign;fillArea;showValues;hideDataMarkers;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.fillArea=e.fillArea,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`radar`,labelRange:e.auxiliaryRange||void 0,fillArea:e.fillArea??!1,showValues:e.showValues??!1,hideDataMarkers:e.hideDataMarkers}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`radar`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated,fillArea:this.fillArea,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers}}getDefinitionForExcel(){let e=this.dataSets.map(e=>SS(this.getters,e)).filter(e=>e.range!==``&&e.range!==k.InvalidReference),t=CS(this.getters,this.labelRange,kS(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:lw(this.background||`#FFFFFF`),fontColor:lw(TS(this.background)),dataSets:e,labelRange:t}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function rD(e,t){let n=e.getDefinition(),r=Xw(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`radar`,data:{labels:r.labels,datasets:ZS(n,r)},options:{...Ew,layout:OT(n,r),scales:GT(n,r),plugins:{title:oE(n),legend:IT(n,r),tooltip:hE(n,r),chartShowValuesPlugin:tE(n,r)}}},background:e.background||`#FFFFFF`}}var iD=class e extends SC{dataSets;labelRange;background;legendPosition;labelsAsText;aggregated;type=`scatter`;dataSetsHaveTitle;dataSetDesign;axesDesign;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=bS(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(this.getters,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static transformDefinition(e,t,n){return wS(e,t,n)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`scatter`,labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`scatter`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}getDefinitionForExcel(){let e=this.dataSets.map(e=>SS(this.getters,e)).filter(e=>e.range!==``),t=CS(this.getters,this.labelRange,kS(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:lw(this.background||`#FFFFFF`),fontColor:lw(TS(this.background)),dataSets:e,labelRange:t,verticalAxis:jS(n)}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}};function aD(e,t){let n=e.getDefinition(),r=Jw(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`line`,data:{labels:r.labels,datasets:JS(n,r)},options:{...Ew,layout:OT(n,r),scales:HT(n,r),plugins:{title:oE(n),legend:NT(n,r),tooltip:dE(n,r),chartShowValuesPlugin:tE(n,r)}}},background:e.background||`#FFFFFF`}}var oD=class e extends SC{dataSets;labelRange;background;legendPosition;type=`sunburst`;dataSetsHaveTitle;showValues;showLabels;valuesDesign;groupColors;pieHolePercentage;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showValues=e.showValues,this.showLabels=e.showLabels,this.valuesDesign=e.valuesDesign,this.groupColors=e.groupColors,this.pieHolePercentage=e.pieHolePercentage}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static getDefinitionFromContextCreation(e){let t=[];return e.hierarchicalRanges?.length?t.push(...e.hierarchicalRanges):e.auxiliaryRange&&t.push({...e.range?.[0],dataRange:e.auxiliaryRange}),{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`sunburst`,labelRange:e.range?.[0]?.dataRange,showValues:e.showValues,showLabels:e.showLabels,valuesDesign:e.valuesDesign,groupColors:e.groupColors}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){let e=this.dataSets.at(-1)?.dataRange;return{...this,range:this.labelRange?[{dataRange:this.getters.getRangeString(this.labelRange,this.sheetId)}]:[],auxiliaryRange:e?this.getters.getRangeString(e,this.sheetId):void 0,hierarchicalRanges:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))}}getDefinitionWithSpecificDataSets(e,t,n){return{type:`sunburst`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,n||this.sheetId)})),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,showValues:this.showValues,showLabels:this.showLabels,valuesDesign:this.valuesDesign,groupColors:this.groupColors,pieHolePercentage:this.pieHolePercentage}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function sD(e,t){let n=e.getDefinition(),r=$w(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`doughnut`,data:{datasets:tC(n,r)},options:{cutout:e.pieHolePercentage===void 0?`25%`:`${e.pieHolePercentage}%`,...Ew,layout:OT(n,r),plugins:{title:oE(n),legend:LT(n,r),tooltip:vE(n,r),sunburstLabelsPlugin:nE(n,r),sunburstHoverPlugin:{enabled:!0}}}},background:e.background||`#FFFFFF`}}var cD=class e extends SC{static defaults={background:oe,legendPosition:`top`,dataSetsHaveTitle:!1,showHeaders:!0,headersColor:`#000000`};dataSets;labelRange;background;legendPosition;type=`treemap`;dataSetsHaveTitle;showHeaders;headerDesign;showValues;showLabels;valuesDesign;coloringOptions;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showHeaders=e.showHeaders,this.headerDesign=e.headerDesign,this.showValues=e.showValues,this.showLabels=e.showLabels,this.valuesDesign=e.valuesDesign,this.coloringOptions=e.coloringOptions}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static getDefinitionFromContextCreation(e){let t=[];return e.hierarchicalRanges?.length?t.push(...e.hierarchicalRanges):e.auxiliaryRange&&t.push({...e.range?.[0],dataRange:e.auxiliaryRange}),{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`treemap`,labelRange:e.range?.[0]?.dataRange,showValues:e.showValues,showHeaders:e.showHeaders,headerDesign:e.headerDesign,showLabels:e.showLabels,valuesDesign:e.valuesDesign,coloringOptions:e.treemapColoringOptions}}getContextCreation(){let e=this.dataSets.at(-1)?.dataRange;return{...this,range:this.labelRange?[{dataRange:this.getters.getRangeString(this.labelRange,this.sheetId)}]:[],auxiliaryRange:e?this.getters.getRangeString(e,this.sheetId):void 0,hierarchicalRanges:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,n||this.sheetId)}));return{type:`treemap`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,showValues:this.showValues,showHeaders:this.showHeaders,headerDesign:this.headerDesign,showLabels:this.showLabels,valuesDesign:this.valuesDesign,coloringOptions:this.coloringOptions}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function lD(e,t){let n=e.getDefinition(),r=$w(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`treemap`,data:{labels:r.labels,datasets:oC(n,r)},options:{...Ew,layout:OT(n,r),plugins:{title:oE(n),legend:{display:!1},tooltip:yE(n,r)}}},background:e.background||`#FFFFFF`}}var uD=class e extends SC{dataSets;labelRange;background;verticalAxisPosition;legendPosition;aggregated;type=`waterfall`;dataSetsHaveTitle;showSubTotals;firstValueAsSubtotal;showConnectorLines;positiveValuesColor;negativeValuesColor;subTotalValuesColor;dataSetDesign;axesDesign;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=bS(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Dc(n,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showSubTotals=e.showSubTotals,this.showConnectorLines=e.showConnectorLines,this.positiveValuesColor=e.positiveValuesColor,this.negativeValuesColor=e.negativeValuesColor,this.subTotalValuesColor=e.subTotalValuesColor,this.firstValueAsSubtotal=e.firstValueAsSubtotal,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues}static transformDefinition(e,t,n){return wS(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,DS,OS)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`waterfall`,verticalAxisPosition:`left`,labelRange:e.auxiliaryRange||void 0,showSubTotals:e.showSubTotals??!1,showConnectorLines:e.showConnectorLines??!0,firstValueAsSubtotal:e.firstValueAsSubtotal??!1,axesDesign:e.axesDesign,showValues:e.showValues}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=_S(this.sheetId,t,this.dataSets),r=vS(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`waterfall`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,showSubTotals:this.showSubTotals,showConnectorLines:this.showConnectorLines,positiveValuesColor:this.positiveValuesColor,negativeValuesColor:this.negativeValuesColor,subTotalValuesColor:this.subTotalValuesColor,firstValueAsSubtotal:this.firstValueAsSubtotal,axesDesign:this.axesDesign,showValues:this.showValues}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=gS(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function dD(e,t){let n=e.getDefinition(),r=Kw(n,e.dataSets,e.labelRange,t),{labels:i,datasets:a}=KS(n,r);return{chartJsConfig:{type:`bar`,data:{labels:i,datasets:a},options:{...Ew,layout:OT(n,r),scales:UT(n,r),plugins:{title:oE(n),legend:FT(n,r),tooltip:pE(n,r),chartShowValuesPlugin:iE(n,r),waterfallLinesPlugin:{showConnectorLines:n.showConnectorLines}}}},background:e.background||`#FFFFFF`}}let fD=new g;fD.add(`bar`,{match:e=>e===`bar`,createChart:(e,t,n)=>new wE(e,t,n),getChartRuntime:TE,validateChartDefinition:wE.validateChartDefinition,transformDefinition:wE.transformDefinition,getChartDefinitionFromContextCreation:wE.getDefinitionFromContextCreation,sequence:10}),fD.add(`combo`,{match:e=>e===`combo`,createChart:(e,t,n)=>new NE(e,t,n),getChartRuntime:PE,validateChartDefinition:NE.validateChartDefinition,transformDefinition:NE.transformDefinition,getChartDefinitionFromContextCreation:NE.getDefinitionFromContextCreation,sequence:15}),fD.add(`line`,{match:e=>e===`line`,createChart:(e,t,n)=>new XE(e,t,n),getChartRuntime:ZE,validateChartDefinition:XE.validateChartDefinition,transformDefinition:XE.transformDefinition,getChartDefinitionFromContextCreation:XE.getDefinitionFromContextCreation,sequence:20}),fD.add(`pie`,{match:e=>e===`pie`,createChart:(e,t,n)=>new QE(e,t,n),getChartRuntime:$E,validateChartDefinition:QE.validateChartDefinition,transformDefinition:QE.transformDefinition,getChartDefinitionFromContextCreation:QE.getDefinitionFromContextCreation,sequence:30}),fD.add(`scorecard`,{match:e=>e===`scorecard`,createChart:(e,t,n)=>new jC(e,t,n),getChartRuntime:NC,validateChartDefinition:jC.validateChartDefinition,transformDefinition:jC.transformDefinition,getChartDefinitionFromContextCreation:jC.getDefinitionFromContextCreation,sequence:40}),fD.add(`gauge`,{match:e=>e===`gauge`,createChart:(e,t,n)=>new HE(e,t,n),getChartRuntime:UE,validateChartDefinition:HE.validateChartDefinition,transformDefinition:HE.transformDefinition,getChartDefinitionFromContextCreation:HE.getDefinitionFromContextCreation,sequence:50}),fD.add(`scatter`,{match:e=>e===`scatter`,createChart:(e,t,n)=>new iD(e,t,n),getChartRuntime:aD,validateChartDefinition:iD.validateChartDefinition,transformDefinition:iD.transformDefinition,getChartDefinitionFromContextCreation:iD.getDefinitionFromContextCreation,sequence:60}),fD.add(`waterfall`,{match:e=>e===`waterfall`,createChart:(e,t,n)=>new uD(e,t,n),getChartRuntime:dD,validateChartDefinition:uD.validateChartDefinition,transformDefinition:uD.transformDefinition,getChartDefinitionFromContextCreation:uD.getDefinitionFromContextCreation,sequence:70}),fD.add(`pyramid`,{match:e=>e===`pyramid`,createChart:(e,t,n)=>new eD(e,t,n),getChartRuntime:tD,validateChartDefinition:eD.validateChartDefinition,transformDefinition:eD.transformDefinition,getChartDefinitionFromContextCreation:eD.getDefinitionFromContextCreation,sequence:80,dataSeriesLimit:2}),fD.add(`radar`,{match:e=>e===`radar`,createChart:(e,t,n)=>new nD(e,t,n),getChartRuntime:rD,validateChartDefinition:nD.validateChartDefinition,transformDefinition:nD.transformDefinition,getChartDefinitionFromContextCreation:nD.getDefinitionFromContextCreation,sequence:80}),fD.add(`geo`,{match:e=>e===`geo`,createChart:(e,t,n)=>new JE(e,t,n),getChartRuntime:YE,validateChartDefinition:JE.validateChartDefinition,transformDefinition:JE.transformDefinition,getChartDefinitionFromContextCreation:JE.getDefinitionFromContextCreation,sequence:90,dataSeriesLimit:1}),fD.add(`funnel`,{match:e=>e===`funnel`,createChart:(e,t,n)=>new FE(e,t,n),getChartRuntime:IE,validateChartDefinition:FE.validateChartDefinition,transformDefinition:FE.transformDefinition,getChartDefinitionFromContextCreation:FE.getDefinitionFromContextCreation,sequence:100,dataSeriesLimit:1}),fD.add(`sunburst`,{match:e=>e===`sunburst`,createChart:(e,t,n)=>new oD(e,t,n),getChartRuntime:sD,validateChartDefinition:oD.validateChartDefinition,transformDefinition:oD.transformDefinition,getChartDefinitionFromContextCreation:oD.getDefinitionFromContextCreation,sequence:30}),fD.add(`treemap`,{match:e=>e===`treemap`,createChart:(e,t,n)=>new cD(e,t,n),getChartRuntime:lD,validateChartDefinition:cD.validateChartDefinition,transformDefinition:cD.transformDefinition,getChartDefinitionFromContextCreation:cD.getDefinitionFromContextCreation,sequence:100});let pD=new g;pD.add(`line`,xC),pD.add(`bar`,xC),pD.add(`combo`,xC),pD.add(`pie`,xC),pD.add(`gauge`,jE),pD.add(`scatter`,xC),pD.add(`scorecard`,RC),pD.add(`waterfall`,xC),pD.add(`pyramid`,xC),pD.add(`radar`,xC),pD.add(`geo`,xC),pD.add(`funnel`,xC),pD.add(`sunburst`,xC),pD.add(`treemap`,xC);let mD={line:E(`Line`),column:E(`Column`),bar:E(`Bar`),area:E(`Area`),pie:E(`Pie`),hierarchical:E(`Hierarchical`),misc:E(`Miscellaneous`)},hD=new g;hD.add(`line`,{matcher:e=>e.type===`line`&&!e.stacked&&!e.fillArea,displayName:E(`Line`),chartType:`line`,chartSubtype:`line`,subtypeDefinition:{stacked:!1,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.LINE_CHART`}).add(`stacked_line`,{matcher:e=>e.type===`line`&&!e.fillArea&&!!e.stacked,displayName:E(`Stacked Line`),chartType:`line`,chartSubtype:`stacked_line`,subtypeDefinition:{stacked:!0,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.STACKED_LINE_CHART`}).add(`area`,{matcher:e=>e.type===`line`&&!e.stacked&&!!e.fillArea,displayName:E(`Area`),chartType:`line`,chartSubtype:`area`,subtypeDefinition:{stacked:!1,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.AREA_CHART`}).add(`stacked_area`,{matcher:e=>e.type===`line`&&e.stacked&&!!e.fillArea,displayName:E(`Stacked Area`),chartType:`line`,chartSubtype:`stacked_area`,subtypeDefinition:{stacked:!0,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.STACKED_AREA_CHART`}).add(`scatter`,{displayName:E(`Scatter`),chartType:`scatter`,chartSubtype:`scatter`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCATTER_CHART`}).add(`column`,{matcher:e=>e.type===`bar`&&!e.stacked&&!e.horizontal,displayName:E(`Column`),chartType:`bar`,chartSubtype:`column`,subtypeDefinition:{stacked:!1,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.COLUMN_CHART`}).add(`stacked_column`,{matcher:e=>e.type===`bar`&&e.stacked&&!e.horizontal,displayName:E(`Stacked Column`),chartType:`bar`,chartSubtype:`stacked_column`,subtypeDefinition:{stacked:!0,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.STACKED_COLUMN_CHART`}).add(`bar`,{matcher:e=>e.type===`bar`&&!e.stacked&&!!e.horizontal,displayName:E(`Bar`),chartType:`bar`,chartSubtype:`bar`,subtypeDefinition:{horizontal:!0,stacked:!1},category:`bar`,preview:`o-spreadsheet-ChartPreview.BAR_CHART`}).add(`stacked_bar`,{matcher:e=>e.type===`bar`&&e.stacked&&!!e.horizontal,displayName:E(`Stacked Bar`),chartType:`bar`,chartSubtype:`stacked_bar`,subtypeDefinition:{horizontal:!0,stacked:!0},category:`bar`,preview:`o-spreadsheet-ChartPreview.STACKED_BAR_CHART`}).add(`combo`,{displayName:E(`Combo`),chartSubtype:`combo`,chartType:`combo`,category:`line`,preview:`o-spreadsheet-ChartPreview.COMBO_CHART`}).add(`pie`,{matcher:e=>e.type===`pie`&&!e.isDoughnut,displayName:E(`Pie`),chartSubtype:`pie`,chartType:`pie`,subtypeDefinition:{isDoughnut:!1},category:`pie`,preview:`o-spreadsheet-ChartPreview.PIE_CHART`}).add(`doughnut`,{matcher:e=>e.type===`pie`&&!!e.isDoughnut,displayName:E(`Doughnut`),chartSubtype:`doughnut`,chartType:`pie`,subtypeDefinition:{isDoughnut:!0},category:`pie`,preview:`o-spreadsheet-ChartPreview.DOUGHNUT_CHART`}).add(`gauge`,{displayName:E(`Gauge`),chartSubtype:`gauge`,chartType:`gauge`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GAUGE_CHART`}).add(`scorecard`,{displayName:E(`Scorecard`),chartSubtype:`scorecard`,chartType:`scorecard`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCORECARD_CHART`}).add(`waterfall`,{displayName:E(`Waterfall`),chartSubtype:`waterfall`,chartType:`waterfall`,category:`misc`,preview:`o-spreadsheet-ChartPreview.WATERFALL_CHART`}).add(`pyramid`,{displayName:E(`Population Pyramid`),chartSubtype:`pyramid`,chartType:`pyramid`,category:`misc`,preview:`o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART`}).add(`radar`,{matcher:e=>e.type===`radar`&&!e.fillArea,displayName:E(`Radar`),chartSubtype:`radar`,chartType:`radar`,subtypeDefinition:{fillArea:!1},category:`misc`,preview:`o-spreadsheet-ChartPreview.RADAR_CHART`}).add(`filled_radar`,{matcher:e=>e.type===`radar`&&!!e.fillArea,displayName:E(`Filled Radar`),chartType:`radar`,chartSubtype:`filled_radar`,subtypeDefinition:{fillArea:!0},category:`misc`,preview:`o-spreadsheet-ChartPreview.FILLED_RADAR_CHART`}).add(`geo`,{displayName:E(`Geo Chart`),chartSubtype:`geo`,chartType:`geo`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GEO_CHART`}).add(`funnel`,{displayName:E(`Funnel`),chartSubtype:`funnel`,chartType:`funnel`,category:`misc`,preview:`o-spreadsheet-ChartPreview.FUNNEL_CHART`}).add(`sunburst`,{matcher:e=>e.type===`sunburst`,displayName:E(`Sunburst`),chartSubtype:`sunburst`,chartType:`sunburst`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.SUNBURST_CHART`}).add(`treemap`,{matcher:e=>e.type===`treemap`,displayName:E(`Tree Map`),chartType:`treemap`,chartSubtype:`treemap`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.TREE_MAP_CHART`});function gD(e){let t=fD.getAll().sort((e,t)=>e.sequence-t.sequence);function n(n,r,i){let a=t.find(e=>e.match(r.type));if(!a)throw Error(`No builder for this chart: ${r.type}`);return a.createChart(r,i,e)}return n}function _D(e){let t=fD.getAll().sort((e,t)=>e.sequence-t.sequence);function n(n){let r=t.find(e=>e.match(n.type));if(!r)throw Error(`No runtime builder for this chart.`);return r.getChartRuntime(n,e)}return n}function vD(e,t){let n=fD.getAll().find(e=>e.match(t.type));if(!n)throw Error(`Unknown chart type.`);return n.validateChartDefinition(e,t)}function yD(e,t,n){let r=fD.getAll().find(e=>e.match(t.type));if(!r)throw Error(`Unknown chart type.`);return r.transformDefinition(e,t,n)}function bD(e,t){let n=xD(t,e);if(n)return n;let r=t.getActiveSheetId(),i=e,a=js(e).numberOfCols===1;a||(i={...e,left:e.left+1});let o=vs(t.getUnboundedZone(r,i)),s=[{dataRange:o,yAxisId:`y`}],c=t.getCell({sheetId:r,col:e.left,row:e.top});if(Ws(e)===1&&c?.content)return{type:`scorecard`,title:{},background:c.style?.fillColor||void 0,keyValue:vs(e),baselineMode:Ge,baselineColorUp:Ke,baselineColorDown:qe};let l=!!t.getEvaluatedCellsInZone(r,{...i,bottom:i.top}).find(e=>e.type!==`empty`&&e.type!==`number`),u;a||(u=vs(t.getUnboundedZone(r,{...e,right:e.left})));let d=i.right===i.left?`none`:`top`,f={title:{},dataSets:s,labelsAsText:!1,stacked:!1,aggregated:!1,cumulative:!1,labelRange:u,type:`line`,dataSetsHaveTitle:l,legendPosition:d},p=new XE(f,r,t);if(sT(f,p.dataSets,p.labelRange,t))return f;let m=bS(t,s,r,l);return a&&hT(t,m[0]).every(e=>typeof e==`string`&&!j(e))?{title:{},dataSets:[{dataRange:o}],aggregated:!0,labelRange:o,type:`pie`,legendPosition:`top`,dataSetsHaveTitle:!1}:{title:{},dataSets:s,labelRange:u,type:`bar`,stacked:!1,aggregated:!1,dataSetsHaveTitle:l,legendPosition:d}}function xD(e,t){let n=e.getActiveSheetId(),r=js(t).numberOfCols;if(t.top===t.bottom||r<=2)return;let i=e.getEvaluatedCell({sheetId:n,col:t.right,row:t.top}).type!==`number`,a=r=>{let a=e.getEvaluatedCellsInZone(n,{...t,left:r,right:r,top:t.top+ +!!i});if(a.every(e=>e.type!==`number`))return`string`;if(a.every(e=>e.type!==`text`))return`number`};for(let e=t.left;e<t.right;e++){let n=a(e);if(e!==t.right&&n!==`string`||e===t.right&&n!==`number`)return}let o={...t,right:t.right-1},s={...t,left:t.right};return{title:{},dataSets:[{dataRange:vs(o)}],type:`sunburst`,legendPosition:`none`,labelRange:vs(s),dataSetsHaveTitle:i}}var SD=l({AbstractChart:()=>SC,BarChart:()=>wE,CHART_AXIS_CHOICES:()=>PS,CHART_COMMON_OPTIONS:()=>Ew,GaugeChart:()=>HE,LineChart:()=>XE,MOVING_AVERAGE_TREND_LINE_XAXIS_ID:()=>mS,PieChart:()=>QE,SPREADSHEET_TO_EXCEL_TRENDLINE_TYPE_MAPPING:()=>hS,ScorecardChart:()=>jC,TREND_LINE_XAXIS_ID:()=>`x1`,WaterfallChart:()=>uD,adaptChartRange:()=>yS,chartFactory:()=>gD,chartFontColor:()=>TS,chartMutedFontColor:()=>ES,chartRuntimeFactory:()=>_D,chartToImageFile:()=>Ow,chartToImageUrl:()=>Dw,checkDataset:()=>DS,checkLabelRange:()=>OS,createBarChartRuntime:()=>TE,createDataSets:()=>bS,createGaugeChartRuntime:()=>UE,createLineChartRuntime:()=>ZE,createPieChartRuntime:()=>$E,createScorecardChartRuntime:()=>NC,createWaterfallChartRuntime:()=>dD,drawScoreChart:()=>MC,duplicateDataSetsInDuplicatedSheet:()=>_S,duplicateLabelRangeInDuplicatedSheet:()=>vS,formatChartDatasetValue:()=>MS,formatTickValue:()=>NS,getChartPositionAtCenterOfViewport:()=>AS,getDefinedAxis:()=>jS,getPieColors:()=>FS,getSmartChartDefinition:()=>bD,isTrendLineAxis:()=>LS,shouldRemoveFirstLabel:()=>kS,toExcelDataset:()=>SS,toExcelLabelRange:()=>CS,transformChartDefinitionWithDataSetsWithZone:()=>wS,transformDefinition:()=>yD,truncateLabel:()=>IS,updateChartRangesWithDataSets:()=>gS,validateChartDefinition:()=>vD});function CD(e,t){let{scrollX:n,scrollY:r}=e.getActiveSheetScrollInfo(),i=e.getSheetViewDimension(),a=n+Math.max(0,(i.width-t.width)/2),o=r+Math.max(0,(i.height-t.height)/2);return e.getPositionAnchorOffset({x:a,y:o})}function wD(e,t){let n=b(t),r=e.getSheetViewDimension(),i=r.width,a=r.height;if(n.width>i){let e=i/n.width;n.width=i,n.height*=e}if(n.height>a){let e=a/n.height;n.height=a,n.width*=e}return n}var TD=class{xmlString;constructor(e){this.xmlString=e}toString(){return this.xmlString}};let ED=[`areaChart`,`area3DChart`,`lineChart`,`line3DChart`,`stockChart`,`radarChart`,`scatterChart`,`pieChart`,`pie3DChart`,`doughnutChart`,`barChart`,`bar3DChart`,`ofPieChart`,`surfaceChart`,`surface3DChart`,`bubbleChart`,`comboChart`,`radarChart`];function DD(e,t,n){return{content:new XMLSerializer().serializeToString(e),path:t,contentType:n}}function OD(e){return String(e).replace(/\&/g,`&`).replace(/\</g,`<`).replace(/\>/g,`>`).replace(/\"/g,`"`).replace(/\'/g,`'`).replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,``)}function K(e){return new TD(e.map(([e,t])=>`${e}="${OD(t)}"`).join(` `))}function kD(e,t=`text/xml`){let n=new DOMParser().parseFromString(e.toString(),t),r=n.querySelector(`parsererror`);if(r){let t=r.innerHTML,n=parseInt(t.split(`:`)[0],10),i=e.toString().trim().split(`
|
|
79
79
|
`),a=i.slice(Math.max(n-3,0),Math.min(n+2,i.length)).join(`
|
|
80
80
|
`);throw Error(`XML string could not be parsed: ${t}\n${a}`)}return n}function AD(e){if(e)return{style:e.style,color:{rgb:e.color}}}function jD(e){let t=[{},...Object.values(e.borders).map(e=>({left:AD(e.left),right:AD(e.right),bottom:AD(e.bottom),top:AD(e.top)}))];return{relsFiles:[],sharedStrings:[],styles:[{fontId:0,fillId:0,numFmtId:0,borderId:0,alignment:{}}],fonts:[{size:Ve,family:2,color:{rgb:`000000`},name:`Arial`}],fills:[{reservedAttribute:`none`},{reservedAttribute:`gray125`}],borders:t,numFmts:[],dxfs:[]}}function MD(e,t){return J`
|
|
81
81
|
<Override ContentType="${t}" PartName="${e}" />
|
|
@@ -140,7 +140,7 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
140
140
|
width: fit-content;
|
|
141
141
|
height: fit-content;
|
|
142
142
|
}
|
|
143
|
-
`;var $D=class extends t.Component{static template=`o-spreadsheet-Popover`;static props={anchorRect:Object,containerRect:{type:Object,optional:!0},positioning:{type:String,optional:!0},maxWidth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},verticalOffset:{type:Number,optional:!0},onMouseWheel:{type:Function,optional:!0},onPopoverHidden:{type:Function,optional:!0},onPopoverMoved:{type:Function,optional:!0},zIndex:{type:Number,optional:!0},class:{type:String,optional:!0},slots:Object};static defaultProps={positioning:`bottom-left`,verticalOffset:0,onMouseWheel:()=>{},onPopoverMoved:()=>{},onPopoverHidden:()=>{},zIndex:35};popoverRef=(0,t.useRef)(`popover`);popoverContentRef=(0,t.useRef)(`popoverContent`);currentPosition=void 0;currentDisplayValue=void 0;spreadsheetRect=ZD();containerRect;setup(){this.containerRect=QD();let e=new ResizeObserver(this.computePopoverPosition.bind(this));(0,t.onMounted)(()=>{e.observe(this.popoverContentRef.el)}),(0,t.onWillUnmount)(()=>{e.disconnect()}),(0,t.useEffect)(this.computePopoverPosition.bind(this))}get popoverStyle(){return H({"z-index":`${this.props.zIndex}`})}computePopoverPosition(){if(!this.containerRect)throw Error(`Popover container is not defined`);let e=this.popoverRef.el,t=this.popoverContentRef.el,n=KD(this.props.anchorRect,this.containerRect),r=n?`block`:`none`;if(this.currentDisplayValue!==`none`&&r===`none`&&this.props.onPopoverHidden?.(),e.style.display=r,this.currentDisplayValue=r,!n)return;let i={width:this.props.maxWidth,height:this.props.maxHeight},a={width:t.getBoundingClientRect().width,height:t.getBoundingClientRect().height},o=this.spreadsheetRect,s=this.props.positioning===`bottom-left`?new tO(n,this.containerRect,i,o,this.currentPosition):new nO(n,this.containerRect,i,o,this.currentPosition);e.style[`max-height`]=s.getMaxHeight(a.height)+`px`,e.style[`max-width`]=s.getMaxWidth(a.width)+`px`,a={width:e.getBoundingClientRect().width,height:e.getBoundingClientRect().height};let c=s.getCss(a,this.props.verticalOffset);for(let t of Object.keys(c))e.style[t]=c[t];let l=s.getCurrentPosition(a);this.currentPosition&&l!==this.currentPosition&&this.props.onPopoverMoved?.(),this.currentPosition=l}},eO=class{constructor(e,t,n,r,i){this.anchorRect=e,this.containerRect=t,this.propsMaxSize=n,this.spreadsheetOffset=r,this.lastPosition=i}shouldRenderAtBottom(e){return this.lastPosition===`top-left`||this.lastPosition===`top-right`?!(e<=this.availableHeightUp||this.availableHeightUp>=this.availableHeightDown):e<=this.availableHeightDown||this.availableHeightDown>=this.availableHeightUp}shouldRenderAtRight(e){return this.lastPosition===`bottom-left`||this.lastPosition===`top-left`?!(e<=this.availableWidthLeft||this.availableWidthLeft>=this.availableWidthRight):e<=this.availableWidthRight||this.availableWidthRight>=this.availableWidthLeft}getMaxHeight(e){let t=this.shouldRenderAtBottom(e)?this.availableHeightDown:this.availableHeightUp;return this.propsMaxSize.height?Math.min(t,this.propsMaxSize.height):t}getMaxWidth(e){let t=this.shouldRenderAtRight(e)?this.availableWidthRight:this.availableWidthLeft;return this.propsMaxSize.width?Math.min(t,this.propsMaxSize.width):t}getCss(e,t){let n=this.getMaxHeight(e.height),r=this.getMaxWidth(e.width),i=Math.min(n,e.height),a=Math.min(r,e.width),o=this.shouldRenderAtBottom(e.height),s=this.shouldRenderAtRight(e.width);return t=o?t:-t,{top:this.getTopCoordinate(i,o)-this.spreadsheetOffset.y-t+`px`,left:this.getLeftCoordinate(a,s)-this.spreadsheetOffset.x+`px`}}getCurrentPosition(e){let t=this.shouldRenderAtBottom(e.height),n=this.shouldRenderAtRight(e.width);return t&&n?`bottom-right`:t&&!n?`bottom-left`:!t&&n?`top-right`:`top-left`}},tO=class extends eO{get availableHeightUp(){return this.anchorRect.y-this.containerRect.y}get availableHeightDown(){return this.containerRect.height-this.availableHeightUp-this.anchorRect.height}get availableWidthRight(){return this.containerRect.x+this.containerRect.width-this.anchorRect.x}get availableWidthLeft(){return this.anchorRect.x+this.anchorRect.width-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y+this.anchorRect.height:this.anchorRect.y-e}getLeftCoordinate(e,t){return t?this.anchorRect.x:this.anchorRect.x+this.anchorRect.width-e}},nO=class extends eO{get availableHeightUp(){return this.anchorRect.y+this.anchorRect.height-this.containerRect.y}get availableHeightDown(){return this.containerRect.y+this.containerRect.height-this.anchorRect.y}get availableWidthRight(){return this.containerRect.width-this.anchorRect.width-this.availableWidthLeft}get availableWidthLeft(){return this.anchorRect.x-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y:this.anchorRect.y+this.anchorRect.height-e}getLeftCoordinate(e,t){return t?this.anchorRect.x+this.anchorRect.width:this.anchorRect.x-e}};V`
|
|
143
|
+
`;var $D=class extends t.Component{static template=`o-spreadsheet-Popover`;static props={anchorRect:Object,containerRect:{type:Object,optional:!0},positioning:{type:String,optional:!0},maxWidth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},verticalOffset:{type:Number,optional:!0},onMouseWheel:{type:Function,optional:!0},onPopoverHidden:{type:Function,optional:!0},onPopoverMoved:{type:Function,optional:!0},zIndex:{type:Number,optional:!0},class:{type:String,optional:!0},slots:Object};static defaultProps={positioning:`bottom-left`,verticalOffset:0,onMouseWheel:()=>{},onPopoverMoved:()=>{},onPopoverHidden:()=>{},zIndex:35};popoverRef=(0,t.useRef)(`popover`);popoverContentRef=(0,t.useRef)(`popoverContent`);currentPosition=void 0;currentDisplayValue=void 0;spreadsheetRect=ZD();containerRect;setup(){this.containerRect=QD();let e=new ResizeObserver(this.computePopoverPosition.bind(this));(0,t.onMounted)(()=>{e.observe(this.popoverContentRef.el)}),(0,t.onWillUnmount)(()=>{e.disconnect()}),(0,t.useEffect)(this.computePopoverPosition.bind(this))}get popoverStyle(){return H({"z-index":`${this.props.zIndex}`})}computePopoverPosition(){if(!this.containerRect)throw Error(`Popover container is not defined`);let e=this.popoverRef.el,t=this.popoverContentRef.el,n=KD(this.props.anchorRect,this.containerRect),r=n?`block`:`none`;if(this.currentDisplayValue!==`none`&&r===`none`&&this.props.onPopoverHidden?.(),e.style.display=r,this.currentDisplayValue=r,!n)return;let i={width:this.props.maxWidth,height:this.props.maxHeight},a={width:t.getBoundingClientRect().width,height:t.getBoundingClientRect().height},o=this.spreadsheetRect,s=this.props.positioning===`bottom-left`?new tO(n,this.containerRect,i,o,this.currentPosition):new nO(n,this.containerRect,i,o,this.currentPosition);e.style[`max-height`]=s.getMaxHeight(a.height)+`px`,e.style[`max-width`]=s.getMaxWidth(a.width)+`px`,a={width:e.getBoundingClientRect().width,height:e.getBoundingClientRect().height};let c=s.getCss(a,this.props.verticalOffset);for(let t of Object.keys(c))e.style[t]=c[t];let l=s.getCurrentPosition(a);this.currentPosition&&l!==this.currentPosition&&this.props.onPopoverMoved?.(),this.currentPosition=l}},eO=class{anchorRect;containerRect;propsMaxSize;spreadsheetOffset;lastPosition;constructor(e,t,n,r,i){this.anchorRect=e,this.containerRect=t,this.propsMaxSize=n,this.spreadsheetOffset=r,this.lastPosition=i}shouldRenderAtBottom(e){return this.lastPosition===`top-left`||this.lastPosition===`top-right`?!(e<=this.availableHeightUp||this.availableHeightUp>=this.availableHeightDown):e<=this.availableHeightDown||this.availableHeightDown>=this.availableHeightUp}shouldRenderAtRight(e){return this.lastPosition===`bottom-left`||this.lastPosition===`top-left`?!(e<=this.availableWidthLeft||this.availableWidthLeft>=this.availableWidthRight):e<=this.availableWidthRight||this.availableWidthRight>=this.availableWidthLeft}getMaxHeight(e){let t=this.shouldRenderAtBottom(e)?this.availableHeightDown:this.availableHeightUp;return this.propsMaxSize.height?Math.min(t,this.propsMaxSize.height):t}getMaxWidth(e){let t=this.shouldRenderAtRight(e)?this.availableWidthRight:this.availableWidthLeft;return this.propsMaxSize.width?Math.min(t,this.propsMaxSize.width):t}getCss(e,t){let n=this.getMaxHeight(e.height),r=this.getMaxWidth(e.width),i=Math.min(n,e.height),a=Math.min(r,e.width),o=this.shouldRenderAtBottom(e.height),s=this.shouldRenderAtRight(e.width);return t=o?t:-t,{top:this.getTopCoordinate(i,o)-this.spreadsheetOffset.y-t+`px`,left:this.getLeftCoordinate(a,s)-this.spreadsheetOffset.x+`px`}}getCurrentPosition(e){let t=this.shouldRenderAtBottom(e.height),n=this.shouldRenderAtRight(e.width);return t&&n?`bottom-right`:t&&!n?`bottom-left`:!t&&n?`top-right`:`top-left`}},tO=class extends eO{get availableHeightUp(){return this.anchorRect.y-this.containerRect.y}get availableHeightDown(){return this.containerRect.height-this.availableHeightUp-this.anchorRect.height}get availableWidthRight(){return this.containerRect.x+this.containerRect.width-this.anchorRect.x}get availableWidthLeft(){return this.anchorRect.x+this.anchorRect.width-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y+this.anchorRect.height:this.anchorRect.y-e}getLeftCoordinate(e,t){return t?this.anchorRect.x:this.anchorRect.x+this.anchorRect.width-e}},nO=class extends eO{get availableHeightUp(){return this.anchorRect.y+this.anchorRect.height-this.containerRect.y}get availableHeightDown(){return this.containerRect.y+this.containerRect.height-this.anchorRect.y}get availableWidthRight(){return this.containerRect.width-this.anchorRect.width-this.availableWidthLeft}get availableWidthLeft(){return this.anchorRect.x-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y:this.anchorRect.y+this.anchorRect.height-e}getLeftCoordinate(e,t){return t?this.anchorRect.x+this.anchorRect.width:this.anchorRect.x-e}};V`
|
|
144
144
|
.o-menu-wrapper {
|
|
145
145
|
padding: ${6}px 0px;
|
|
146
146
|
background-color: white;
|
|
@@ -420,7 +420,7 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
420
420
|
`;var qO=class extends t.Component{static template=`o-spreadsheet-Composer`;static props={focus:{validate:e=>[`inactive`,`cellFocus`,`contentFocus`].includes(e)},inputStyle:{type:String,optional:!0},rect:{type:Object,optional:!0},delimitation:{type:Object,optional:!0},onComposerCellFocused:{type:Function,optional:!0},onComposerContentFocused:Function,isDefaultFocus:{type:Boolean,optional:!0},onInputContextMenu:{type:Function,optional:!0},composerStore:Object,placeholder:{type:String,optional:!0},inputMode:{type:String,optional:!0},showAssistant:{type:Boolean,optional:!0}};static components={TextValueProvider:wO,FunctionDescriptionProvider:jO,SpeechBubble:MO};static defaultProps={inputStyle:``,isDefaultFocus:!1,inputMode:`text`,showAssistant:!0};DOMFocusableElementStore;composerRef=(0,t.useRef)(`o_composer`);contentHelper=new TO(this.composerRef.el);composerState=(0,t.useState)({positionStart:0,positionEnd:0,hoveredRect:void 0});functionDescriptionState=(0,t.useState)({showDescription:!1,functionDescription:{},argsToFocus:[]});assistant=(0,t.useState)({forcedClosed:!1});compositionActive=!1;spreadsheetRect=ZD();lastHoveredTokenIndex=void 0;debouncedHover=Et((e,t)=>{let n=this.contentHelper.getCurrentSelection();if(n.start!==n.end)return;let r=this.props.composerStore.hoveredTokens;this.props.composerStore.hoverToken(e),w(r,this.props.composerStore.hoveredTokens)||(this.composerState.hoveredRect=t)},120);get assistantStyleProperties(){let e=this.composerRef.el.getBoundingClientRect(),t={};t[`min-width`]=`${Math.min(this.props.rect?.width||1/0,300)}px`;let n=this.props.composerStore.autoCompleteProposals?.some(e=>e.description);if((this.functionDescriptionState.showDescription||n)&&(t.width=`300px`),this.props.delimitation&&this.props.rect){let{x:e,y:n,height:r}=this.props.rect,i=this.props.delimitation.height-(n+r);t[`max-height`]=`${i}px`,n>i&&(t[`max-height`]=`${n-9}px`,t.top=`-3px`,t.transform=`translate(0, -100%)`),e+300>this.props.delimitation.width&&(t.right=`0px`)}else t[`max-height`]=`${this.spreadsheetRect.height-e.bottom-1}px`,e.left+300+15+9>this.spreadsheetRect.width&&(t.right=`9px`);return t}get assistantStyle(){let e=this.assistantStyleProperties;return H({"max-height":e[`max-height`],width:e.width,"min-width":e[`min-width`]})}get assistantContainerStyle(){let e=this.assistantStyleProperties;return H({top:e.top,right:e.right,transform:e.transform})}shouldProcessInputEvents=!1;tokens=[];keyMapping={Enter:e=>this.processEnterKey(e,`down`),"Shift+Enter":e=>this.processEnterKey(e,`up`),"Alt+Enter":this.processNewLineEvent,"Ctrl+Enter":this.processNewLineEvent,Escape:this.processEscapeKey,F2:e=>this.toggleEditionMode(e),F4:e=>this.processF4Key(e),Tab:e=>this.processTabKey(e,`right`),"Shift+Tab":e=>this.processTabKey(e,`left`)};keyCodeMapping={NumpadDecimal:this.processNumpadDecimal};setup(){this.DOMFocusableElementStore=B(xO),(0,t.onMounted)(()=>{let e=this.composerRef.el;this.props.isDefaultFocus&&this.DOMFocusableElementStore.setFocusableElement(e),this.contentHelper.updateEl(e)}),(0,t.onWillUnmount)(()=>{this.debouncedHover.stopDebounce()}),(0,t.useEffect)(()=>{this.processContent(),document.activeElement===this.contentHelper.el&&this.props.composerStore.editionMode===`inactive`&&!this.props.isDefaultFocus&&this.DOMFocusableElementStore.focus()}),(0,t.useEffect)(()=>{this.processTokenAtCursor()},()=>[this.props.composerStore.editionMode!==`inactive`]),(0,t.useEffect)(()=>{this.contentHelper.scrollSelectionIntoView()},()=>[this.props.composerStore.composerSelection.start,this.props.composerStore.composerSelection.end])}processArrowKeys(e){let t=this.props.composerStore.tokenAtCursor;if((this.props.composerStore.isSelectingRange||this.props.composerStore.editionMode===`inactive`)&&!([`ArrowUp`,`ArrowDown`].includes(e.key)&&this.props.composerStore.isAutoCompleteDisplayed&&t?.type!==`REFERENCE`)){this.functionDescriptionState.showDescription=!1,this.props.composerStore.hideHelp(),e.preventDefault(),e.stopPropagation(),CO(e,this.env.model.selection);return}let n=this.props.composerStore.currentContent;if(this.props.focus===`cellFocus`&&!this.props.composerStore.isAutoCompleteDisplayed&&!en(n)){this.props.composerStore.stopEdition();return}e.stopPropagation(),this.handleArrowKeysForAutocomplete(e)}handleArrowKeysForAutocomplete(e){[`ArrowUp`,`ArrowDown`].includes(e.key)&&this.props.composerStore.isAutoCompleteDisplayed&&(e.preventDefault(),this.props.composerStore.moveAutoCompleteSelection(e.key===`ArrowDown`?`next`:`previous`))}processTabKey(e,t){e.preventDefault(),e.stopPropagation(),this.props.composerStore.autoCompleteOrStop(t,this.assistant.forcedClosed)}processEnterKey(e,t){e.preventDefault(),e.stopPropagation(),this.props.composerStore.autoCompleteOrStop(t,this.assistant.forcedClosed)}processNewLineEvent(e){e.preventDefault(),e.stopPropagation();let t=this.contentHelper.getText(),n=this.contentHelper.getCurrentSelection(),r=Math.min(n.start,n.end),i=Math.max(n.start,n.end);this.props.composerStore.stopComposerRangeSelection(),this.props.composerStore.setCurrentContent(t.slice(0,r)+`
|
|
421
421
|
`+t.slice(i),{start:r+1,end:r+1}),this.processContent()}processEscapeKey(e){this.props.composerStore.cancelEdition(),e.stopPropagation(),e.preventDefault()}processF4Key(e){e.stopPropagation(),this.props.composerStore.cycleReferences(),this.processContent()}toggleEditionMode(e){e.stopPropagation(),this.props.composerStore.toggleEditionMode(),this.processContent()}processNumpadDecimal(e){e.stopPropagation(),e.preventDefault();let t=this.env.model.getters.getLocale(),n=this.contentHelper.getCurrentSelection(),r=this.props.composerStore.currentContent,i=r.slice(0,n.start)+t.decimalSeparator+r.slice(n.end);this.props.composerStore.setCurrentContent(i,{start:n.start+1,end:n.start+1}),this.processContent()}onCompositionStart(){this.compositionActive=!0}onCompositionEnd(){this.compositionActive=!1}onKeydown(e){if(this.props.composerStore.editionMode===`inactive`)return;if(e.key.startsWith(`Arrow`)){this.processArrowKeys(e);return}let t=this.keyMapping[ZC(e)]||this.keyCodeMapping[ZC(e,`code`)];t?t.call(this,e):e.stopPropagation()}onPaste(e){this.props.composerStore.editionMode===`inactive`?e.preventDefault():e.stopPropagation()}onInput(e){if(!this.shouldProcessInputEvents)return;e.stopPropagation();let t;if(t=this.props.composerStore.editionMode===`inactive`?e.data||``:this.contentHelper.getText(),this.props.focus===`inactive`)return this.props.onComposerCellFocused?.(t);let n=this.contentHelper.getCurrentSelection();this.props.composerStore.stopComposerRangeSelection(),this.props.composerStore.setCurrentContent(t,n),this.processTokenAtCursor()}onKeyup(e){if(this.contentHelper.el===document.activeElement){if(this.props.composerStore.isAutoCompleteDisplayed&&[`ArrowUp`,`ArrowDown`].includes(e.key)||this.props.composerStore.isSelectingRange&&e.key?.startsWith(`Arrow`))return;let{start:t,end:n}=this.props.composerStore.composerSelection,{start:r,end:i}=this.contentHelper.getCurrentSelection();(r!==t||i!==n)&&this.props.composerStore.changeComposerCursorSelection(r,i),this.processTokenAtCursor()}}onBlur(e){if(this.props.composerStore.editionMode===`inactive`)return;let t=e.relatedTarget;if(!t||!(t instanceof HTMLElement)){this.props.composerStore.stopEdition();return}if(t.attributes.getNamedItem(`composerFocusableElement`)){this.contentHelper.el.focus();return}t.classList.contains(`o-composer`)||this.props.composerStore.stopEdition()}onMousedown(e){e.button>0||this.env.isMobile()&&!ow()||(this.debouncedHover.stopDebounce(),this.contentHelper.removeSelection())}onMouseup(){if(this.env.model.getters.isReadonly())return;let e=this.contentHelper.getCurrentSelection();e.start!==e.end&&this.props.composerStore.hoverToken(void 0)}onClick(){if(this.env.model.getters.isReadonly())return;let e=this.contentHelper.getCurrentSelection();this.props.onComposerContentFocused(),this.props.composerStore.changeComposerCursorSelection(e.start,e.end),this.processTokenAtCursor()}onDblClick(){if(this.env.model.getters.isReadonly())return;let e=this.props.composerStore.currentContent;if(en(e)){let t=this.props.composerStore.currentTokens,n=this.contentHelper.getCurrentSelection();if(n.start===n.end)return;let r=e.substring(n.start,n.end),i=t.filter(e=>e.value.includes(r)&&e.start<=n.start&&e.end>=n.end)[0];if(!i)return;i.type===`REFERENCE`&&this.props.composerStore.changeComposerCursorSelection(i.start,i.end)}}onContextMenu(e){this.props.composerStore.editionMode===`inactive`&&this.props.onInputContextMenu?.(e)}closeAssistant(){this.props.composerStore.canBeToggled&&(this.assistant.forcedClosed=!0)}openAssistant(){this.props.composerStore.canBeToggled&&(this.assistant.forcedClosed=!1)}onWheel(e){this.composerRef.el&&this.composerRef.el.scrollHeight>this.composerRef.el.clientHeight&&e.stopPropagation()}processContent(){if(this.compositionActive)return;this.shouldProcessInputEvents=!1,this.props.focus!==`inactive`&&document.activeElement!==this.contentHelper.el&&this.contentHelper.el.focus();let e=this.getContentLines();if(this.contentHelper.setText(e),e.length!==0&&e.length[0]!==0&&this.props.focus!==`inactive`){let{start:e,end:t}=this.props.composerStore.composerSelection;this.contentHelper.selectRange(e,t)}this.shouldProcessInputEvents=!0}getContentLines(){let e=this.props.composerStore.currentContent,t=en(e);return e===``?[]:t&&this.props.focus!==`inactive`?this.splitHtmlContentIntoLines(this.getHtmlContentFromTokens()):this.splitHtmlContentIntoLines([{value:e,classes:[]}])}getHtmlContentFromTokens(){let e=this.props.composerStore.currentTokens,t=[],{end:n,start:r}=this.props.composerStore.composerSelection;for(let i=0;i<e.length;i++){let a=e[i],o=a.color||`#000000`;a.isBlurred&&(o=Sn(o,.5));let s=[];a.type===`REFERENCE`&&this.props.composerStore.tokenAtCursor===a&&this.props.composerStore.editionMode===`selecting`&&s.push(`text-decoration-underline`),n===r&&a.isParenthesisLinkedToCursor&&s.push(GO),a.isInHoverContext&&s.push(KO),this.props.composerStore.showSelectionIndicator&&n===r&&n===a.end&&s.push(WO),t.push({value:a.value,color:o,classes:s,onHover:e=>this.onTokenHover(i,e),onStopHover:()=>this.onTokenHover(void 0)})}return t}onTokenHover(e,t){this.lastHoveredTokenIndex!==e&&(this.lastHoveredTokenIndex=e,this.debouncedHover(e,t))}splitHtmlContentIntoLines(e){let t=[],n=[];for(let r of e)if(r.value.includes(`
|
|
422
422
|
`)){let e=r.value.split(`
|
|
423
|
-
`),i=e.pop();for(let i of e)n.push({color:r.color,value:i}),t.push(n),n=[];n.push({...r,value:i})}else n.push(r);n.length&&t.push(n);let r=[];for(let e of t)e.every(this.isContentEmpty)?r.push([e[0]]):r.push(e.filter(e=>!this.isContentEmpty(e)));return r}isContentEmpty(e){return!(e.value||e.classes?.length)}processTokenAtCursor(){let e=this.props.composerStore;this.functionDescriptionState.showDescription=!1;let t=this.props.composerStore.tokenAtCursor;if(en(e.currentContent)&&t&&t.type!==`SYMBOL`){let e=t.functionContext,n=e?.parent.toUpperCase();if(e&&n&&n in UO&&t.type!==`UNKNOWN`){let r=UO[n],i=e.argPosition,a=e.args.length;this.functionDescriptionState.functionDescription=r;let o=this.props.composerStore.currentTokens.some(e=>e.type===`RIGHT_PAREN`&&e.parenthesesCode===t.parenthesesCode);this.functionDescriptionState.argsToFocus=this.getArgsToFocus(o,r,a,i),this.functionDescriptionState.showDescription=!0}}}getArgsToFocus(e,t,n,r){let{nbrArgRepeating:i,minArgRequired:a,nbrArgOptional:o,maxArgPossible:s}=t;if(e){let e=Lf(t,Math.max(Math.min(s,n),a))(r);return e===void 0?[]:[e]}let c=Math.max(n,a),l=i?a+Math.ceil((c-a)/i)*i+o:s,u=[];for(let e=c;e<=l;e++){let n=Lf(t,e)(r);n!==void 0&&u.push(n)}return[...new Set(u)]}autoComplete(e){!e||this.assistant.forcedClosed&&this.props.composerStore.canBeToggled||(this.props.composerStore.insertAutoCompleteValue(e),this.processTokenAtCursor())}get displaySpeechBubble(){return!!(this.props.focus!==`inactive`&&this.composerState.hoveredRect&&this.props.composerStore.hoveredContentEvaluation)}},JO=class extends HO{constructor(e,t){super(e),this.args=t,this._currentContent=this.getComposerContent()}getAutoCompleteProviders(){let e=super.getAutoCompleteProviders(),t=this.args().contextualAutocomplete;return t&&e.push(t),e}getZoneReference(e){let t=super.getZoneReference(e);return this.args().defaultStatic?Ey(t,`colrow`):t}getComposerContent(){let e=this._currentContent;if(this.editionMode===`inactive`){let t=this.args().defaultRangeSheetId;e=Qv(this.args().content).map(e=>{if(e.type===`REFERENCE`){let n=this.getters.getRangeFromSheetXC(t,e.value);return this.getters.getRangeString(n,this.getters.getActiveSheetId())}return e.value}).join(``)}return Xl(e,this.getters.getLocale())}stopEdition(){this._stopEdition()}confirmEdition(e){this.args().onConfirm(e)}getTokenColor(e){if(e.type===`SYMBOL`){let t=this.args().getContextualColoredSymbolToken?.(e);if(t)return t}return super.getTokenColor(e)}hoverToken(){}};V`
|
|
423
|
+
`),i=e.pop();for(let i of e)n.push({color:r.color,value:i}),t.push(n),n=[];n.push({...r,value:i})}else n.push(r);n.length&&t.push(n);let r=[];for(let e of t)e.every(this.isContentEmpty)?r.push([e[0]]):r.push(e.filter(e=>!this.isContentEmpty(e)));return r}isContentEmpty(e){return!(e.value||e.classes?.length)}processTokenAtCursor(){let e=this.props.composerStore;this.functionDescriptionState.showDescription=!1;let t=this.props.composerStore.tokenAtCursor;if(en(e.currentContent)&&t&&t.type!==`SYMBOL`){let e=t.functionContext,n=e?.parent.toUpperCase();if(e&&n&&n in UO&&t.type!==`UNKNOWN`){let r=UO[n],i=e.argPosition,a=e.args.length;this.functionDescriptionState.functionDescription=r;let o=this.props.composerStore.currentTokens.some(e=>e.type===`RIGHT_PAREN`&&e.parenthesesCode===t.parenthesesCode);this.functionDescriptionState.argsToFocus=this.getArgsToFocus(o,r,a,i),this.functionDescriptionState.showDescription=!0}}}getArgsToFocus(e,t,n,r){let{nbrArgRepeating:i,minArgRequired:a,nbrArgOptional:o,maxArgPossible:s}=t;if(e){let e=Lf(t,Math.max(Math.min(s,n),a))(r);return e===void 0?[]:[e]}let c=Math.max(n,a),l=i?a+Math.ceil((c-a)/i)*i+o:s,u=[];for(let e=c;e<=l;e++){let n=Lf(t,e)(r);n!==void 0&&u.push(n)}return[...new Set(u)]}autoComplete(e){!e||this.assistant.forcedClosed&&this.props.composerStore.canBeToggled||(this.props.composerStore.insertAutoCompleteValue(e),this.processTokenAtCursor())}get displaySpeechBubble(){return!!(this.props.focus!==`inactive`&&this.composerState.hoveredRect&&this.props.composerStore.hoveredContentEvaluation)}},JO=class extends HO{args;constructor(e,t){super(e),this.args=t,this._currentContent=this.getComposerContent()}getAutoCompleteProviders(){let e=super.getAutoCompleteProviders(),t=this.args().contextualAutocomplete;return t&&e.push(t),e}getZoneReference(e){let t=super.getZoneReference(e);return this.args().defaultStatic?Ey(t,`colrow`):t}getComposerContent(){let e=this._currentContent;if(this.editionMode===`inactive`){let t=this.args().defaultRangeSheetId;e=Qv(this.args().content).map(e=>{if(e.type===`REFERENCE`){let n=this.getters.getRangeFromSheetXC(t,e.value);return this.getters.getRangeString(n,this.getters.getActiveSheetId())}return e.value}).join(``)}return Xl(e,this.getters.getLocale())}stopEdition(){this._stopEdition()}confirmEdition(e){this.args().onConfirm(e)}getTokenColor(e){if(e.type===`SYMBOL`){let t=this.args().getContextualColoredSymbolToken?.(e);if(t)return t}return super.getTokenColor(e)}hoverToken(){}};V`
|
|
424
424
|
.o-spreadsheet {
|
|
425
425
|
.o-standalone-composer {
|
|
426
426
|
min-height: 24px;
|
|
@@ -629,7 +629,7 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
629
629
|
color: #666666;
|
|
630
630
|
cursor: pointer;
|
|
631
631
|
}
|
|
632
|
-
`;var ik=class extends hO{static template=`o-spreadsheet-ListCriterionForm`;static components={CriterionInput:XO,RoundColorPicker:rk};state=(0,t.useState)({items:[]});setup(){super.setup();let e=this.props.criterion.values||[],n=this.props.criterion.colors||{};this.state.items=Array.from({length:Math.max(e.length,2)},(t,r)=>{let i=e[r]??``;return{value:i,color:i?n[i]:void 0}});let r=e=>{e.criterion.displayStyle===void 0&&this.updateCriterion({displayStyle:`chip`})};(0,t.onWillUpdateProps)(r),(0,t.onWillStart)(()=>r(this.props))}syncCriterion(){let e=this.state.items.map(e=>e.value),t={};for(let{value:e,color:n}of this.state.items)e?.trim()!==``&&n&&(t[e]=n);this.updateCriterion({values:e,colors:t})}onValueChanged(e,t){this.state.items[e].value=t,this.syncCriterion()}onColorChanged(e,t){this.state.items[e].color=t,this.syncCriterion()}onAddAnotherValue(){this.state.items.push({value:``})}removeItem(e){this.state.items.splice(e,1),this.syncCriterion()}onChangedDisplayStyle(e){let t=e.target.value;this.updateCriterion({displayStyle:t})}onKeyDown(e,t){(e.key===`Enter`||e.key===`Tab`)&&t===this.state.items.length-1?(this.onAddAnotherValue(),this.state.focusedValueIndex=t+1,e.preventDefault()):e.key===`Enter`&&(this.state.focusedValueIndex=t+1)}onBlurInput(){this.state.focusedValueIndex=void 0}};function ak(){let e,n=document.body.style.cursor,r=[],i=()=>{e=void 0,document.body.style.cursor=n,r.forEach(e=>e()),r=[]},a=(t,a)=>{let s=()=>{document.body.style.cursor=`move`,e&&(Object.assign(o.itemsStyle,e.getItemStyles()),a.onChange?.())};o.cancel=()=>{o.draggedItemId=void 0,o.itemsStyle={},document.body.style.cursor=n,a.onCancel?.(),i()};let c=(e,t)=>{o.draggedItemId=void 0,o.itemsStyle={},document.body.style.cursor=n,a.onDragEnd?.(e,t),i()};document.body.style.cursor=`move`,o.draggedItemId=a.draggedItemId;let l=t===`horizontal`?new lk(a.scrollableContainerEl):new ck(a.scrollableContainerEl);e=new ok({...a,container:l,onChange:s,onDragEnd:c,onCancel:o.cancel});let u=tk(e.onMouseMove.bind(e),e.onMouseUp.bind(e));r.push(u);let d=e.onScroll.bind(e);a.scrollableContainerEl.addEventListener(`scroll`,d),r.push(()=>a.scrollableContainerEl.removeEventListener(`scroll`,d)),r.push(e.destroy.bind(e))};(0,t.onWillUnmount)(()=>{i()});let o=(0,t.useState)({itemsStyle:{},draggedItemId:void 0,start:a,cancel:()=>{}});return o}var ok=class{draggedItemId;items;container;initialMousePosition;currentMousePosition;initialScroll;minPosition;maxPosition;edgeScrollIntervalId;onChange;onCancel;onDragEnd;deadZone;constructor(e){this.items=e.items.map(e=>({...e,positionAtStart:e.position})),this.draggedItemId=e.draggedItemId,this.container=e.container,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onDragEnd=e.onDragEnd,this.initialMousePosition=e.initialMousePosition,this.currentMousePosition=e.initialMousePosition,this.initialScroll=this.container.scroll,this.minPosition=this.items[0].position,this.maxPosition=this.items[this.items.length-1].position+this.items[this.items.length-1].size}getItemStyles(){let e={};for(let t of this.items)e[t.id]=this.getItemStyle(t.id);return e}getItemStyle(e){let t=this.container.cssPositionProperty,n={};return n.position=`relative`,n[t]=(this.getItemsPositions()[e]||0)+`px`,n.transition=`${t} 0.5s`,n[`pointer-events`]=`none`,this.draggedItemId===e&&(n.transition=`${t} 0s`,n[`z-index`]=`1000`),H(n)}onScroll(){this.moveDraggedItemToPosition(this.currentMousePosition+this.scrollOffset)}onMouseMove(e){if(e.button>1){this.onCancel();return}let t=this.container.getMousePosition(e);if(this.currentMousePosition=t,t<this.container.start||t>this.container.end){this.startEdgeScroll(t<this.container.start?-1:1);return}else this.stopEdgeScroll();this.moveDraggedItemToPosition(t+this.scrollOffset)}moveDraggedItemToPosition(e){let t=this.getHoveredItemIndex(e,this.items),n=this.items.findIndex(e=>e.id===this.draggedItemId),r=this.items[n];if(this.deadZone&&this.isInZone(e,this.deadZone)){this.onChange(this.getItemsPositions());return}else this.isInZone(e,{start:r.position,end:r.position+r.size})&&(this.deadZone=void 0);if(n===t){this.onChange(this.getItemsPositions());return}let i=Math.min(n,t),a=Math.max(n,t),o=Math.sign(t-n),s=0;for(let e=i;e<=a;e++)e!==n&&(this.items[e].position-=o*r.size,s+=this.items[e].size);r.position+=o*s,this.items.sort((e,t)=>e.position-t.position),this.deadZone=o>0?{start:e,end:r.position}:{start:r.position+r.size,end:e},this.onChange(this.getItemsPositions())}onMouseUp(e){e.button!==0&&this.onCancel(),e.stopPropagation(),e.preventDefault();let t=this.items.findIndex(e=>e.id===this.draggedItemId);return this.onDragEnd(this.draggedItemId,t),this.stopEdgeScroll(),!1}startEdgeScroll(e){this.edgeScrollIntervalId||=window.setInterval(()=>{let t=e*3;this.container.scroll+=t},5)}stopEdgeScroll(){window.clearInterval(this.edgeScrollIntervalId),this.edgeScrollIntervalId=void 0}getHoveredItemIndex(e,t){return e<=this.minPosition?0:e>=this.maxPosition?t.length-1:t.findIndex(t=>t.position+t.size>=e)}getItemsPositions(){let e={};for(let t of this.items){if(t.id!==this.draggedItemId){e[t.id]=t.position-t.positionAtStart;continue}let n=this.currentMousePosition-this.initialMousePosition+this.scrollOffset;n=Math.max(this.minPosition-t.positionAtStart,n),n=Math.min(this.maxPosition-t.positionAtStart-t.size,n),e[t.id]=n}return e}isInZone(e,t){return e>=t.start&&e<=t.end}get scrollOffset(){return this.container.scroll-this.initialScroll}destroy(){this.stopEdgeScroll()}},sk=class{constructor(e){this.el=e}get containerRect(){return this.el.getBoundingClientRect()}},ck=class extends sk{get start(){return this.containerRect.top}get end(){return this.containerRect.bottom}get cssPositionProperty(){return`top`}get scroll(){return this.el.scrollTop}set scroll(e){this.el.scrollTop=e}getMousePosition(e){return e.clientY}},lk=class extends sk{get start(){return this.containerRect.left}get end(){return this.containerRect.right}get cssPositionProperty(){return`left`}get scroll(){return this.el.scrollLeft}set scroll(e){this.el.scrollLeft=e}getMousePosition(e){return e.clientX}},uk=class{mutators=[`focus`,`unfocus`];focusedElement=null;focus(e){this.focusedElement=e}unfocus(e){this.focusedElement&&this.focusedElement===e&&(this.focusedElement=null)}},dk=class extends Xd{mutators=[`resetWithRanges`,`focusById`,`unfocus`,`addEmptyRange`,`removeRange`,`changeRange`,`reset`,`confirm`,`updateColors`,`updateDisabledRanges`];ranges=[];focusedRangeIndex=null;inputSheetId;focusStore=this.get(uk);highlightStore=this.get(IO);constructor(e,t=[],n=!1,r=[],i=[]){if(super(e),this.initialRanges=t,this.inputHasSingleRange=n,this.colors=r,this.disabledRanges=i,n&&t.length>1)throw Error(`Input with a single range cannot be instantiated with several range references.`);this.inputSheetId=this.getters.getActiveSheetId(),this.resetWithRanges(t),this.highlightStore.register(this),this.onDispose(()=>{this.unfocus(),this.highlightStore.unRegister(this)})}handleEvent(e){if(this.focusedRangeIndex===null)return;let t=this.inputSheetId,n=this.getters.getActiveSheetId(),r=e.options.unbounded?this.getters.getUnboundedZone(n,e.anchor.zone):e.anchor.zone,i=this.getters.getRangeFromZone(n,r);if(e.mode===`newAnchor`&&!this.inputHasSingleRange&&this.ranges[this.focusedRangeIndex].xc.trim()!==``){let e=this.getters.getSelectionRangeString(i,t);this.insertNewRange(this.ranges.length,[e]),this.focusLast()}else{let e=i.parts,n=this.ranges[this.focusedRangeIndex].xc.trim();n&&(e=this.getters.getRangeFromSheetXC(t,n).parts);let r={...i,parts:e},a=this.getters.getSelectionRangeString(r,t);this.setRange(this.focusedRangeIndex,[a])}}handle(e){switch(e.type){case`ACTIVATE_SHEET`:if(e.sheetIdFrom!==e.sheetIdTo){let{col:t,row:n}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),r=this.getters.expandZone(e.sheetIdTo,z({col:t,row:n}));this.model.selection.resetAnchor(this,{cell:{col:t,row:n},zone:r})}break;case`START_CHANGE_HIGHLIGHT`:let t=this.getters.getActiveSheetId(),n=this.getters.expandZone(t,e.zone),r=this.ranges.findIndex(e=>{let{xc:r,sheetName:i}=vc(e.xc),a=i||this.getters.getSheetName(this.inputSheetId);if(this.getters.getSheetName(t)!==a)return!1;let o=this.getters.getRangeFromSheetXC(t,r);return Es(this.getters.expandZone(t,o.zone),n)});if(r!==-1){this.focus(r);let{left:e,top:t}=n;this.model.selection.resetAnchor(this,{cell:{col:e,row:t},zone:n})}break}}changeRange(e,t){if(this.inputHasSingleRange&&t.split(`,`).length>1)return;let n=this.getIndex(e);if(n!==null&&this.focusedRangeIndex!==n&&this.focus(n),n!==null){let e=t.replace(/^,+/,``).split(`,`).map(e=>e.trim());this.setRange(n,e),this.captureSelection()}}addEmptyRange(){this.inputHasSingleRange&&this.ranges.length===1||(this.insertNewRange(this.ranges.length,[``]),this.focusLast())}removeRange(e){if(this.ranges.length===1)return;let t=this.getIndex(e);t!==null&&this.removeRangeByIndex(t)}updateColors(e){this.colors=e;let t=new In(this.ranges.length,this.colors);this.ranges=this.ranges.map(e=>({...e,color:t.next()}))}updateDisabledRanges(e){this.disabledRanges=e}confirm(){for(let e of this.selectionInputs)e.xc===``&&this.removeRange(e.id);let e=this.getters.getActiveSheetId();this.inputSheetId!==e&&this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e,sheetIdTo:this.inputSheetId}),this.selectionInputValues.join()!==this.initialRanges.join()&&this.resetWithRanges(this.selectionInputValues),this.initialRanges=this.selectionInputValues,this.unfocus()}reset(){this.resetWithRanges(this.initialRanges),this.confirm()}get selectionInputValues(){return this.cleanInputs(this.ranges.map(e=>e.xc?e.xc:``))}get selectionInputs(){return this.ranges.map((e,t)=>Object.assign({},e,{color:this.hasMainFocus&&this.focusedRangeIndex!==null&&this.getters.isRangeValid(e.xc)?e.color:null,isFocused:this.hasMainFocus&&this.focusedRangeIndex===t,isValidRange:e.xc===``||this.getters.isRangeValid(e.xc),disabled:this.disabledRanges?.[t]}))}get isResettable(){return this.initialRanges.join()!==this.ranges.map(e=>e.xc).join()}get isConfirmable(){return this.selectionInputs.every(e=>e.isValidRange)}get hasFocus(){return this.selectionInputs.some(e=>e.isFocused)}get hasMainFocus(){let e=this.focusStore.focusedElement;return!!e&&e===this}get highlights(){return this.hasMainFocus?this.ranges.map(e=>this.inputToHighlights(e)).flat():[]}focusById(e){this.focus(this.getIndex(e))}focus(e){this.focusStore.focus(this),this.focusedRangeIndex=e,this.captureSelection()}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null,this.focusStore.unfocus(this),this.model.selection.release(this)}captureSelection(){if(this.focusedRangeIndex===null)return;let e=this.ranges[this.focusedRangeIndex],t=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(t,e?.xc||`A1`).zone;this.model.selection.capture(this,{cell:{col:n.left,row:n.top},zone:n},{handleEvent:this.handleEvent.bind(this),release:this.unfocus.bind(this)})}resetWithRanges(e){e.length&&e.every(e=>this.getters.isRangeValid(e))&&(this.initialRanges=e),this.ranges=[],this.insertNewRange(0,e),this.ranges.length===0&&(this.insertNewRange(this.ranges.length,[``]),this.focusLast())}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){let n=Math.max(0,...this.ranges.map(e=>Number(e.id))),r=new In(this.ranges.length,this.colors);for(let t=0;t<e;t++)r.next();this.ranges.splice(e,0,...t.map((e,t)=>({xc:e,id:n+t+1,color:r.next()})))}setRange(e,t){let[,...n]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,n),n.length&&this.focus(e+n.length)}removeRangeByIndex(e){this.ranges.splice(e,1),this.focusedRangeIndex!==null&&this.focusLast()}inputToHighlights({xc:e,color:t}){return this.cleanInputs([e]).filter(e=>this.getters.isRangeValid(e)).filter(e=>this.shouldBeHighlighted(this.inputSheetId,e)).map(e=>{let{sheetName:n}=vc(e),r=n&&this.getters.getSheetIdByName(n)||this.inputSheetId;return{range:this.getters.getRangeFromSheetXC(r,e),color:t,interactive:!0}})}cleanInputs(e){return e.map(e=>e.split(`,`)).flat().map(e=>e.trim()).filter(e=>e!==``)}shouldBeHighlighted(e,t){let{sheetName:n}=vc(t),r=this.getters.getSheetIdByName(n),i=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(r===i||r===void 0&&i===e)}getIndex(e){let t=this.ranges.findIndex(t=>t.id===e);return t>=0?t:null}};V`
|
|
632
|
+
`;var ik=class extends hO{static template=`o-spreadsheet-ListCriterionForm`;static components={CriterionInput:XO,RoundColorPicker:rk};state=(0,t.useState)({items:[]});setup(){super.setup();let e=this.props.criterion.values||[],n=this.props.criterion.colors||{};this.state.items=Array.from({length:Math.max(e.length,2)},(t,r)=>{let i=e[r]??``;return{value:i,color:i?n[i]:void 0}});let r=e=>{e.criterion.displayStyle===void 0&&this.updateCriterion({displayStyle:`chip`})};(0,t.onWillUpdateProps)(r),(0,t.onWillStart)(()=>r(this.props))}syncCriterion(){let e=this.state.items.map(e=>e.value),t={};for(let{value:e,color:n}of this.state.items)e?.trim()!==``&&n&&(t[e]=n);this.updateCriterion({values:e,colors:t})}onValueChanged(e,t){this.state.items[e].value=t,this.syncCriterion()}onColorChanged(e,t){this.state.items[e].color=t,this.syncCriterion()}onAddAnotherValue(){this.state.items.push({value:``})}removeItem(e){this.state.items.splice(e,1),this.syncCriterion()}onChangedDisplayStyle(e){let t=e.target.value;this.updateCriterion({displayStyle:t})}onKeyDown(e,t){(e.key===`Enter`||e.key===`Tab`)&&t===this.state.items.length-1?(this.onAddAnotherValue(),this.state.focusedValueIndex=t+1,e.preventDefault()):e.key===`Enter`&&(this.state.focusedValueIndex=t+1)}onBlurInput(){this.state.focusedValueIndex=void 0}};function ak(){let e,n=document.body.style.cursor,r=[],i=()=>{e=void 0,document.body.style.cursor=n,r.forEach(e=>e()),r=[]},a=(t,a)=>{let s=()=>{document.body.style.cursor=`move`,e&&(Object.assign(o.itemsStyle,e.getItemStyles()),a.onChange?.())};o.cancel=()=>{o.draggedItemId=void 0,o.itemsStyle={},document.body.style.cursor=n,a.onCancel?.(),i()};let c=(e,t)=>{o.draggedItemId=void 0,o.itemsStyle={},document.body.style.cursor=n,a.onDragEnd?.(e,t),i()};document.body.style.cursor=`move`,o.draggedItemId=a.draggedItemId;let l=t===`horizontal`?new lk(a.scrollableContainerEl):new ck(a.scrollableContainerEl);e=new ok({...a,container:l,onChange:s,onDragEnd:c,onCancel:o.cancel});let u=tk(e.onMouseMove.bind(e),e.onMouseUp.bind(e));r.push(u);let d=e.onScroll.bind(e);a.scrollableContainerEl.addEventListener(`scroll`,d),r.push(()=>a.scrollableContainerEl.removeEventListener(`scroll`,d)),r.push(e.destroy.bind(e))};(0,t.onWillUnmount)(()=>{i()});let o=(0,t.useState)({itemsStyle:{},draggedItemId:void 0,start:a,cancel:()=>{}});return o}var ok=class{draggedItemId;items;container;initialMousePosition;currentMousePosition;initialScroll;minPosition;maxPosition;edgeScrollIntervalId;onChange;onCancel;onDragEnd;deadZone;constructor(e){this.items=e.items.map(e=>({...e,positionAtStart:e.position})),this.draggedItemId=e.draggedItemId,this.container=e.container,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onDragEnd=e.onDragEnd,this.initialMousePosition=e.initialMousePosition,this.currentMousePosition=e.initialMousePosition,this.initialScroll=this.container.scroll,this.minPosition=this.items[0].position,this.maxPosition=this.items[this.items.length-1].position+this.items[this.items.length-1].size}getItemStyles(){let e={};for(let t of this.items)e[t.id]=this.getItemStyle(t.id);return e}getItemStyle(e){let t=this.container.cssPositionProperty,n={};return n.position=`relative`,n[t]=(this.getItemsPositions()[e]||0)+`px`,n.transition=`${t} 0.5s`,n[`pointer-events`]=`none`,this.draggedItemId===e&&(n.transition=`${t} 0s`,n[`z-index`]=`1000`),H(n)}onScroll(){this.moveDraggedItemToPosition(this.currentMousePosition+this.scrollOffset)}onMouseMove(e){if(e.button>1){this.onCancel();return}let t=this.container.getMousePosition(e);if(this.currentMousePosition=t,t<this.container.start||t>this.container.end){this.startEdgeScroll(t<this.container.start?-1:1);return}else this.stopEdgeScroll();this.moveDraggedItemToPosition(t+this.scrollOffset)}moveDraggedItemToPosition(e){let t=this.getHoveredItemIndex(e,this.items),n=this.items.findIndex(e=>e.id===this.draggedItemId),r=this.items[n];if(this.deadZone&&this.isInZone(e,this.deadZone)){this.onChange(this.getItemsPositions());return}else this.isInZone(e,{start:r.position,end:r.position+r.size})&&(this.deadZone=void 0);if(n===t){this.onChange(this.getItemsPositions());return}let i=Math.min(n,t),a=Math.max(n,t),o=Math.sign(t-n),s=0;for(let e=i;e<=a;e++)e!==n&&(this.items[e].position-=o*r.size,s+=this.items[e].size);r.position+=o*s,this.items.sort((e,t)=>e.position-t.position),this.deadZone=o>0?{start:e,end:r.position}:{start:r.position+r.size,end:e},this.onChange(this.getItemsPositions())}onMouseUp(e){e.button!==0&&this.onCancel(),e.stopPropagation(),e.preventDefault();let t=this.items.findIndex(e=>e.id===this.draggedItemId);return this.onDragEnd(this.draggedItemId,t),this.stopEdgeScroll(),!1}startEdgeScroll(e){this.edgeScrollIntervalId||=window.setInterval(()=>{let t=e*3;this.container.scroll+=t},5)}stopEdgeScroll(){window.clearInterval(this.edgeScrollIntervalId),this.edgeScrollIntervalId=void 0}getHoveredItemIndex(e,t){return e<=this.minPosition?0:e>=this.maxPosition?t.length-1:t.findIndex(t=>t.position+t.size>=e)}getItemsPositions(){let e={};for(let t of this.items){if(t.id!==this.draggedItemId){e[t.id]=t.position-t.positionAtStart;continue}let n=this.currentMousePosition-this.initialMousePosition+this.scrollOffset;n=Math.max(this.minPosition-t.positionAtStart,n),n=Math.min(this.maxPosition-t.positionAtStart-t.size,n),e[t.id]=n}return e}isInZone(e,t){return e>=t.start&&e<=t.end}get scrollOffset(){return this.container.scroll-this.initialScroll}destroy(){this.stopEdgeScroll()}},sk=class{el;constructor(e){this.el=e}get containerRect(){return this.el.getBoundingClientRect()}},ck=class extends sk{get start(){return this.containerRect.top}get end(){return this.containerRect.bottom}get cssPositionProperty(){return`top`}get scroll(){return this.el.scrollTop}set scroll(e){this.el.scrollTop=e}getMousePosition(e){return e.clientY}},lk=class extends sk{get start(){return this.containerRect.left}get end(){return this.containerRect.right}get cssPositionProperty(){return`left`}get scroll(){return this.el.scrollLeft}set scroll(e){this.el.scrollLeft=e}getMousePosition(e){return e.clientX}},uk=class{mutators=[`focus`,`unfocus`];focusedElement=null;focus(e){this.focusedElement=e}unfocus(e){this.focusedElement&&this.focusedElement===e&&(this.focusedElement=null)}},dk=class extends Xd{initialRanges;inputHasSingleRange;colors;disabledRanges;mutators=[`resetWithRanges`,`focusById`,`unfocus`,`addEmptyRange`,`removeRange`,`changeRange`,`reset`,`confirm`,`updateColors`,`updateDisabledRanges`];ranges=[];focusedRangeIndex=null;inputSheetId;focusStore=this.get(uk);highlightStore=this.get(IO);constructor(e,t=[],n=!1,r=[],i=[]){if(super(e),this.initialRanges=t,this.inputHasSingleRange=n,this.colors=r,this.disabledRanges=i,n&&t.length>1)throw Error(`Input with a single range cannot be instantiated with several range references.`);this.inputSheetId=this.getters.getActiveSheetId(),this.resetWithRanges(t),this.highlightStore.register(this),this.onDispose(()=>{this.unfocus(),this.highlightStore.unRegister(this)})}handleEvent(e){if(this.focusedRangeIndex===null)return;let t=this.inputSheetId,n=this.getters.getActiveSheetId(),r=e.options.unbounded?this.getters.getUnboundedZone(n,e.anchor.zone):e.anchor.zone,i=this.getters.getRangeFromZone(n,r);if(e.mode===`newAnchor`&&!this.inputHasSingleRange&&this.ranges[this.focusedRangeIndex].xc.trim()!==``){let e=this.getters.getSelectionRangeString(i,t);this.insertNewRange(this.ranges.length,[e]),this.focusLast()}else{let e=i.parts,n=this.ranges[this.focusedRangeIndex].xc.trim();n&&(e=this.getters.getRangeFromSheetXC(t,n).parts);let r={...i,parts:e},a=this.getters.getSelectionRangeString(r,t);this.setRange(this.focusedRangeIndex,[a])}}handle(e){switch(e.type){case`ACTIVATE_SHEET`:if(e.sheetIdFrom!==e.sheetIdTo){let{col:t,row:n}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),r=this.getters.expandZone(e.sheetIdTo,z({col:t,row:n}));this.model.selection.resetAnchor(this,{cell:{col:t,row:n},zone:r})}break;case`START_CHANGE_HIGHLIGHT`:let t=this.getters.getActiveSheetId(),n=this.getters.expandZone(t,e.zone),r=this.ranges.findIndex(e=>{let{xc:r,sheetName:i}=vc(e.xc),a=i||this.getters.getSheetName(this.inputSheetId);if(this.getters.getSheetName(t)!==a)return!1;let o=this.getters.getRangeFromSheetXC(t,r);return Es(this.getters.expandZone(t,o.zone),n)});if(r!==-1){this.focus(r);let{left:e,top:t}=n;this.model.selection.resetAnchor(this,{cell:{col:e,row:t},zone:n})}break}}changeRange(e,t){if(this.inputHasSingleRange&&t.split(`,`).length>1)return;let n=this.getIndex(e);if(n!==null&&this.focusedRangeIndex!==n&&this.focus(n),n!==null){let e=t.replace(/^,+/,``).split(`,`).map(e=>e.trim());this.setRange(n,e),this.captureSelection()}}addEmptyRange(){this.inputHasSingleRange&&this.ranges.length===1||(this.insertNewRange(this.ranges.length,[``]),this.focusLast())}removeRange(e){if(this.ranges.length===1)return;let t=this.getIndex(e);t!==null&&this.removeRangeByIndex(t)}updateColors(e){this.colors=e;let t=new In(this.ranges.length,this.colors);this.ranges=this.ranges.map(e=>({...e,color:t.next()}))}updateDisabledRanges(e){this.disabledRanges=e}confirm(){for(let e of this.selectionInputs)e.xc===``&&this.removeRange(e.id);let e=this.getters.getActiveSheetId();this.inputSheetId!==e&&this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e,sheetIdTo:this.inputSheetId}),this.selectionInputValues.join()!==this.initialRanges.join()&&this.resetWithRanges(this.selectionInputValues),this.initialRanges=this.selectionInputValues,this.unfocus()}reset(){this.resetWithRanges(this.initialRanges),this.confirm()}get selectionInputValues(){return this.cleanInputs(this.ranges.map(e=>e.xc?e.xc:``))}get selectionInputs(){return this.ranges.map((e,t)=>Object.assign({},e,{color:this.hasMainFocus&&this.focusedRangeIndex!==null&&this.getters.isRangeValid(e.xc)?e.color:null,isFocused:this.hasMainFocus&&this.focusedRangeIndex===t,isValidRange:e.xc===``||this.getters.isRangeValid(e.xc),disabled:this.disabledRanges?.[t]}))}get isResettable(){return this.initialRanges.join()!==this.ranges.map(e=>e.xc).join()}get isConfirmable(){return this.selectionInputs.every(e=>e.isValidRange)}get hasFocus(){return this.selectionInputs.some(e=>e.isFocused)}get hasMainFocus(){let e=this.focusStore.focusedElement;return!!e&&e===this}get highlights(){return this.hasMainFocus?this.ranges.map(e=>this.inputToHighlights(e)).flat():[]}focusById(e){this.focus(this.getIndex(e))}focus(e){this.focusStore.focus(this),this.focusedRangeIndex=e,this.captureSelection()}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null,this.focusStore.unfocus(this),this.model.selection.release(this)}captureSelection(){if(this.focusedRangeIndex===null)return;let e=this.ranges[this.focusedRangeIndex],t=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(t,e?.xc||`A1`).zone;this.model.selection.capture(this,{cell:{col:n.left,row:n.top},zone:n},{handleEvent:this.handleEvent.bind(this),release:this.unfocus.bind(this)})}resetWithRanges(e){e.length&&e.every(e=>this.getters.isRangeValid(e))&&(this.initialRanges=e),this.ranges=[],this.insertNewRange(0,e),this.ranges.length===0&&(this.insertNewRange(this.ranges.length,[``]),this.focusLast())}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){let n=Math.max(0,...this.ranges.map(e=>Number(e.id))),r=new In(this.ranges.length,this.colors);for(let t=0;t<e;t++)r.next();this.ranges.splice(e,0,...t.map((e,t)=>({xc:e,id:n+t+1,color:r.next()})))}setRange(e,t){let[,...n]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,n),n.length&&this.focus(e+n.length)}removeRangeByIndex(e){this.ranges.splice(e,1),this.focusedRangeIndex!==null&&this.focusLast()}inputToHighlights({xc:e,color:t}){return this.cleanInputs([e]).filter(e=>this.getters.isRangeValid(e)).filter(e=>this.shouldBeHighlighted(this.inputSheetId,e)).map(e=>{let{sheetName:n}=vc(e),r=n&&this.getters.getSheetIdByName(n)||this.inputSheetId;return{range:this.getters.getRangeFromSheetXC(r,e),color:t,interactive:!0}})}cleanInputs(e){return e.map(e=>e.split(`,`)).flat().map(e=>e.trim()).filter(e=>e!==``)}shouldBeHighlighted(e,t){let{sheetName:n}=vc(t),r=this.getters.getSheetIdByName(n),i=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(r===i||r===void 0&&i===e)}getIndex(e){let t=this.ranges.findIndex(t=>t.id===e);return t>=0?t:null}};V`
|
|
633
633
|
.o-selection {
|
|
634
634
|
.o-selection-input {
|
|
635
635
|
padding: 2px 0px;
|
|
@@ -1677,7 +1677,7 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
1677
1677
|
width: 24px;
|
|
1678
1678
|
}
|
|
1679
1679
|
}
|
|
1680
|
-
`;let EB=f([SL,CL,wL,TL,EL,DL,OL,kL,AL,hL,gL,_L,vL,yL,bL]);var DB=class extends t.Component{static template=`o-spreadsheet-MoreFormatsPanel`;static props={onCloseSidePanel:Function};get dateFormatsActions(){return EB}},OB=class extends Xd{mutators=[`cancelMeasureDisplayEdition`,`updateMeasureDisplayType`,`updateMeasureDisplayField`,`updateMeasureDisplayValue`];measureDisplay;constructor(e,t,n){super(e),this.pivotId=t,this.initialMeasure=n,this.measureDisplay=n.display||{type:`no_calculations`}}updateMeasureDisplayType(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(e,this.measureDisplay.fieldNameWithGranularity,this.measureDisplay.value))}updateMeasureDisplayField(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(this.measureDisplay.type,e,this.measureDisplay.value))}updateMeasureDisplayValue(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(this.measureDisplay.type,this.measureDisplay.fieldNameWithGranularity,e))}updatePivotMeasureDisplay(e){let t=b(this.model.getters.getPivotCoreDefinition(this.pivotId)),n=this.getMeasureIndex(this.initialMeasure.id,t),r={...t.measures[n],display:e};t.measures[n]=r,this.model.dispatch(`UPDATE_PIVOT`,{pivot:t,pivotId:this.pivotId}).isSuccessful&&(this.measureDisplay=e)}getMeasureDisplay(e,t,n){switch(e){case`no_calculations`:case`%_of_grand_total`:case`%_of_col_total`:case`%_of_row_total`:case`%_of_parent_row_total`:case`%_of_parent_col_total`:case`index`:return{type:e};case`%_of_parent_total`:case`running_total`:case`%_running_total`:case`rank_asc`:case`rank_desc`:return t||=this.fields[0]?.nameWithGranularity,{type:e,fieldNameWithGranularity:t};case`%_of`:case`difference_from`:case`%_difference_from`:t||=this.fields[0]?.nameWithGranularity;let r=this.getPossibleValues(t);return(n===void 0||!r.find(e=>e.value===n))&&(n=vI),{type:e,fieldNameWithGranularity:t,value:n??`(previous)`}}}getMeasureIndex(e,t){let n=t.measures.findIndex(t=>t.id===e);if(n===-1)throw Error(`Measure with id ${e} not found in pivot.`);return n}get doesDisplayNeedsField(){return[`%_of_parent_total`,`running_total`,`%_running_total`,`rank_asc`,`rank_desc`].includes(this.measureDisplay.type)||this.doesDisplayNeedsValue}get fields(){let e=this.getters.getPivot(this.pivotId).definition;return[...e.columns,...e.rows].map(e=>({...e,displayName:Sd(e)}))}get doesDisplayNeedsValue(){return this.isDisplayValueDependant(this.measureDisplay)}isDisplayValueDependant(e){return[`%_of`,`difference_from`,`%_difference_from`].includes(e.type)}get values(){let e=this.measureDisplay;return this.isDisplayValueDependant(e)?this.getPossibleValues(e.fieldNameWithGranularity):[]}getPossibleValues(e){let t=[{value:vI,label:E(`(previous)`)},{value:`(next)`,label:E(`(next)`)}],n=this.fields.find(t=>t.nameWithGranularity===e);if(!n)return[];let r=this.getters.getPivot(this.pivotId).getPossibleFieldValues(n);return[...t,...r]}cancelMeasureDisplayEdition(){let e=b(this.model.getters.getPivotCoreDefinition(this.pivotId)),t=this.getMeasureIndex(this.initialMeasure.id,e);e.measures[t]={...e.measures[t],display:this.initialMeasure.display},this.model.dispatch(`UPDATE_PIVOT`,{pivot:e,pivotId:this.pivotId})}};V`
|
|
1680
|
+
`;let EB=f([SL,CL,wL,TL,EL,DL,OL,kL,AL,hL,gL,_L,vL,yL,bL]);var DB=class extends t.Component{static template=`o-spreadsheet-MoreFormatsPanel`;static props={onCloseSidePanel:Function};get dateFormatsActions(){return EB}},OB=class extends Xd{pivotId;initialMeasure;mutators=[`cancelMeasureDisplayEdition`,`updateMeasureDisplayType`,`updateMeasureDisplayField`,`updateMeasureDisplayValue`];measureDisplay;constructor(e,t,n){super(e),this.pivotId=t,this.initialMeasure=n,this.measureDisplay=n.display||{type:`no_calculations`}}updateMeasureDisplayType(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(e,this.measureDisplay.fieldNameWithGranularity,this.measureDisplay.value))}updateMeasureDisplayField(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(this.measureDisplay.type,e,this.measureDisplay.value))}updateMeasureDisplayValue(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(this.measureDisplay.type,this.measureDisplay.fieldNameWithGranularity,e))}updatePivotMeasureDisplay(e){let t=b(this.model.getters.getPivotCoreDefinition(this.pivotId)),n=this.getMeasureIndex(this.initialMeasure.id,t),r={...t.measures[n],display:e};t.measures[n]=r,this.model.dispatch(`UPDATE_PIVOT`,{pivot:t,pivotId:this.pivotId}).isSuccessful&&(this.measureDisplay=e)}getMeasureDisplay(e,t,n){switch(e){case`no_calculations`:case`%_of_grand_total`:case`%_of_col_total`:case`%_of_row_total`:case`%_of_parent_row_total`:case`%_of_parent_col_total`:case`index`:return{type:e};case`%_of_parent_total`:case`running_total`:case`%_running_total`:case`rank_asc`:case`rank_desc`:return t||=this.fields[0]?.nameWithGranularity,{type:e,fieldNameWithGranularity:t};case`%_of`:case`difference_from`:case`%_difference_from`:t||=this.fields[0]?.nameWithGranularity;let r=this.getPossibleValues(t);return(n===void 0||!r.find(e=>e.value===n))&&(n=vI),{type:e,fieldNameWithGranularity:t,value:n??`(previous)`}}}getMeasureIndex(e,t){let n=t.measures.findIndex(t=>t.id===e);if(n===-1)throw Error(`Measure with id ${e} not found in pivot.`);return n}get doesDisplayNeedsField(){return[`%_of_parent_total`,`running_total`,`%_running_total`,`rank_asc`,`rank_desc`].includes(this.measureDisplay.type)||this.doesDisplayNeedsValue}get fields(){let e=this.getters.getPivot(this.pivotId).definition;return[...e.columns,...e.rows].map(e=>({...e,displayName:Sd(e)}))}get doesDisplayNeedsValue(){return this.isDisplayValueDependant(this.measureDisplay)}isDisplayValueDependant(e){return[`%_of`,`difference_from`,`%_difference_from`].includes(e.type)}get values(){let e=this.measureDisplay;return this.isDisplayValueDependant(e)?this.getPossibleValues(e.fieldNameWithGranularity):[]}getPossibleValues(e){let t=[{value:vI,label:E(`(previous)`)},{value:`(next)`,label:E(`(next)`)}],n=this.fields.find(t=>t.nameWithGranularity===e);if(!n)return[];let r=this.getters.getPivot(this.pivotId).getPossibleFieldValues(n);return[...t,...r]}cancelMeasureDisplayEdition(){let e=b(this.model.getters.getPivotCoreDefinition(this.pivotId)),t=this.getMeasureIndex(this.initialMeasure.id,e);e.measures[t]={...e.measures[t],display:this.initialMeasure.display},this.model.dispatch(`UPDATE_PIVOT`,{pivot:e,pivotId:this.pivotId})}};V`
|
|
1681
1681
|
.o-sidePanel {
|
|
1682
1682
|
.o-pivot-measure-display-field,
|
|
1683
1683
|
.o-pivot-measure-display-value {
|
|
@@ -1770,7 +1770,7 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
1770
1770
|
.add-calculated-measure {
|
|
1771
1771
|
cursor: pointer;
|
|
1772
1772
|
}
|
|
1773
|
-
`;var WB=class extends t.Component{static template=`o-spreadsheet-PivotLayoutConfigurator`;static components={AddDimensionButton:FB,PivotDimension:RB,PivotDimensionOrder:BB,PivotDimensionGranularity:zB,PivotMeasureEditor:HB,PivotSortSection:UB};static props={definition:Object,onDimensionsUpdated:Function,unusedGroupableFields:Array,measureFields:Array,unusedGranularities:Object,dateGranularities:Array,datetimeGranularities:Array,getScrollableContainerEl:{type:Function,optional:!0},pivotId:String};dimensionsRef=(0,t.useRef)(`pivot-dimensions`);dragAndDrop=ak();AGGREGATORS=od;composerFocus;isDateOrDatetimeField=fd;setup(){this.composerFocus=B(Qd)}startDragAndDrop(e,t){if(t.button!==0||t.target.tagName===`SELECT`)return;let n=this.getDimensionElementsRects(),{columns:r,rows:i}=this.props.definition,a=[...r.map(e=>e.nameWithGranularity),`__rows_title__`,...i.map(e=>e.nameWithGranularity)],o=r.concat(i),s=a.map((e,t)=>({id:e,size:n[t+1].height,position:n[t+1].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:s,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=a.findIndex(t=>t===e);if(n===t)return;let r=[...a];r.splice(n,1),r.splice(t,0,e);let i=r.slice(0,r.indexOf(`__rows_title__`)),s=r.slice(r.indexOf(`__rows_title__`)+1);this.props.onDimensionsUpdated({columns:i.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(C),rows:s.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(C)})}})}getGranularitiesFor(e){return fd(e)?e.type===`date`?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(t.button!==0||t.target.tagName===`SELECT`||t.target.tagName===`INPUT`||this.composerFocus.focusMode!==`inactive`)return;let n=this.getDimensionElementsRects(),{measures:r,columns:i,rows:a}=this.props.definition,o=r.map(e=>e.id),s=3+i.length+a.length,c=o.map((e,t)=>({id:e,size:n[t+s].height,position:n[t+s].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=o.findIndex(t=>t===e);if(n===t)return;let i=[...o];i.splice(n,1),i.splice(t,0,e),this.props.onDimensionsUpdated({measures:i.map(e=>r.find(t=>t.id===e)).filter(C)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{let t=getComputedStyle(e),n=e.getBoundingClientRect();return{x:n.x,y:n.y,width:n.width+parseInt(t.marginLeft||`0`)+parseInt(t.marginRight||`0`),height:n.height+parseInt(t.marginTop||`0`)+parseInt(t.marginBottom||`0`)}})}removeDimension(e){let{columns:t,rows:n}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:n.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){let{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){let{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:`asc`}])})}addRowDimension(e){let{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:`asc`}])})}addMeasureDimension(e){let{measures:t}=this.props.definition,n=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,n),fieldName:e,aggregator:n}])})}updateMeasure(e,t){let{measures:n}=this.props.definition,r={measures:n.map(n=>n.id===e.id?t:n)};this.props.definition.sortedColumn?.measure===e.id&&(r.sortedColumn={...this.props.definition.sortedColumn,measure:t.id}),this.props.onDimensionsUpdated(r)}getMeasureId(e,t){let n=e.replaceAll(`'`,``)+(t?`:${t}`:``),r=n,i=2;for(;this.props.definition.measures.some(e=>e.id===r);)r=`${n}:${i}`,i++;return r}getDefaultMeasureAggregator(e){let t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:`count`}addCalculatedMeasure(){let{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t,`sum`),fieldName:t,aggregator:`sum`,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:`=0`}}])})}updateOrder(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n)})}updateGranularity(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n)})}getMeasureDescription(e){let t=e.display;if(!t||t.type===`no_calculations`)return``;let n=this.env.model.getters.getPivot(this.props.pivotId),r=[...n.definition.columns,...n.definition.rows].find(e=>e.nameWithGranularity===t.fieldNameWithGranularity),i=r?Sd(r):``;return Rw.descriptions[t.type](i)}},GB=class extends t.Component{static template=`o-spreadsheet-PivotTitleSection`;static components={CogWheelMenu:LB,Section:X,TextInput:IB};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:E(`Flip axes`),icon:`o-spreadsheet-Icon.EXCHANGE`,execute:this.props.flipAxis},{name:E(`Duplicate`),icon:`o-spreadsheet-Icon.COPY`,execute:()=>this.duplicatePivot()},{name:E(`Delete`),icon:`o-spreadsheet-Icon.TRASH`,execute:()=>this.delete()}]}get name(){return this.env.model.getters.getPivotName(this.props.pivotId)}get displayName(){return this.env.model.getters.getPivotDisplayName(this.props.pivotId)}duplicatePivot(){let e=this.env.model.uuidGenerator.smallUuid(),t=this.env.model.uuidGenerator.smallUuid(),n=this.env.model.dispatch(`DUPLICATE_PIVOT_IN_NEW_SHEET`,{pivotId:this.props.pivotId,newPivotId:e,newSheetId:t}),r;r=n.isSuccessful?E(`Pivot duplicated.`):n.isCancelledBecause(`PivotInError`)?E(`Cannot duplicate a pivot in error.`):E(`Pivot duplication failed.`);let i=n.isSuccessful?`success`:`danger`;this.env.notifyUser({text:r,sticky:!1,type:i}),n.isSuccessful&&this.env.openSidePanel(`PivotSidePanel`,{pivotId:e})}delete(){this.env.askConfirmation(E(`Are you sure you want to delete this pivot?`),()=>{this.env.model.dispatch(`REMOVE_PIVOT`,{pivotId:this.props.pivotId})})}onNameChanged(e){let t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.props.pivotId,pivot:{...t,name:e}})}};let KB=[`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`];function qB(e,t){let n=`"${t?`${e.name}:${t}`:e.name}"`,r=e.string===e.name?n:e.string+n;return{text:n,description:e.string+(e.help?` (${e.help})`:``),htmlContent:[{value:n,color:VO.STRING}],fuzzySearchKey:r}}function JB(e){let t=`"${e.id}"`,n=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:VO.STRING}],fuzzySearchKey:n}}function YB(e,t){let n=e.end,r=e.end;e.type!==`ARG_SEPARATOR`&&(n=e.start),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}function XB(e,t){let n=e.end,r=e.end;e.type!==`LEFT_PAREN`&&(n=e.start),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}function ZB(e){let t=e.functionContext?.args[0];if(!(!t||![`STRING`,`NUMBER`].includes(t.type)))return t.value}function QB(e){return sS(e,KB)[0]}function $B(e){return sS(e,KB).length}var eV=class{measures;columns;rows;sortedColumn;collapsedDomains;constructor(e,t){this.measures=e.measures.map(e=>tV(t,e)),this.columns=e.columns.map(e=>nV(t,e)),this.rows=e.rows.map(e=>nV(t,e)),this.sortedColumn=e.sortedColumn,this.collapsedDomains=e.collapsedDomains}getDimension(e){let t=this.columns.find(t=>t.nameWithGranularity===e)||this.rows.find(t=>t.nameWithGranularity===e);if(!t)throw new A(E(`Dimension %s does not exist`,e));return t}getMeasure(e){let t=this.measures.find(t=>t.id===e);if(!t)throw new A(E(`Field %s is not a measure`,e));return t}};function tV(e,t){let n=t.fieldName,r=n===`__count`?{name:`__count`,string:E(`Count`),type:`integer`,aggregator:`sum`}:e[n],i=t.aggregator;return{id:t.id,get displayName(){return t.userDefinedName??r?.string??t.fieldName},userDefinedName:t.userDefinedName,fieldName:n,aggregator:i,type:n===`__count`?`integer`:r?.type??`integer`,isValid:!!(r||t.computedBy),isHidden:t.isHidden,format:t.format,computedBy:t.computedBy,display:t.display}}function nV(e,t){let n=e[t.fieldName],r=n?.type??`integer`,i=n&&fd(n)?t.granularity:void 0;return{displayName:n?.string??t.fieldName,nameWithGranularity:t.fieldName+(i?`:${i}`:``),fieldName:t.fieldName,granularity:i,type:r,order:t.order,isValid:!!n}}var rV=class extends eV{range;constructor(e,t,n){if(super(e,t),e.dataSet){let{sheetId:t,zone:r}=e.dataSet;this.range=n.getRangeFromZone(t,r)}}},iV=class{columns;rows;measures;fieldsType;maxIndent;pivotCells={};rowTree;colTree;isSorted=!1;constructor(e,t,n,r,i={COL:[],ROW:[]}){this.measures=n,this.fieldsType=r,i.COL.length&&(e=this.removeCollapsedColumns(e,n,i.COL)),this.columns=e.map(e=>{let t=1;return e.map(e=>(e={...e,offset:t},t+=e.width,e))}),this.rows=t.filter(e=>!this.isParentCollapsed(i.ROW,e)),this.maxIndent=Math.max(...this.rows.map(e=>e.indent)),this.rowTree=kt(()=>this.buildRowsTree()),this.colTree=kt(()=>this.buildColumnsTree())}removeCollapsedColumns(e,t,n){let r=(n,r)=>{let i=this.getDomain(n),a=e[r],o=a.findIndex(e=>LI(this.getDomain(e),i)),s=a.findLastIndex(e=>LI(this.getDomain(e),i)),c=r===e.length-1,l=t.map(e=>({fields:c?[...n.fields,`measure`]:[],values:c?[...n.values,e]:[],width:1,offset:0,collapsedHeader:!c}));a.splice(o,s-o+1,...l)};return e.map((i,a)=>{for(let o of i){if(a>=e.length-2)return i;let s=this.getDomain(o);if(n.some(e=>w(s,e))){o.width=t.length;for(let t=a+1;t<e.length;t++)r(o,t)}}return i})}isParentCollapsed(e,t){let n=this.getDomain(t);return e.some(e=>LI(n,e))}getNumberOfDataColumns(){return this.columns.at(-1)?.length||0}getSkippedRows(e){let t=new Set;if(!e.displayColumnHeaders)for(let e=0;e<this.columns.length-1;e++)t.add(e);return e.displayMeasuresRow||t.add(this.columns.length-1),t}getPivotCells(e={displayColumnHeaders:!0,displayTotals:!0,displayMeasuresRow:!0}){let t=JSON.stringify(e);if(!this.pivotCells[t]){let{displayTotals:n}=e,r=this.rows.length,i=this.getNumberOfDataColumns(),a=this.columns.length+r,o=1+i;!n&&r!==1&&--a,!n&&i!==this.measures.length&&(o-=this.measures.length);let s=[],c=this.getSkippedRows(e);for(let e=0;e<o;e++){s.push([]);for(let t=0;t<a;t++)c.has(t)||s[e].push(this.getPivotCell(e,t,n))}this.pivotCells[t]=s}return this.pivotCells[t]}getRowTree(){return this.rowTree()}getColTree(){return this.colTree()}isTotalRow(e){return this.rows[e].indent!==this.maxIndent}getPivotCell(e,t,n=!0){let r=this.columns.length;if(e>0&&t===r-1){let n=this.getColHeaderDomain(e,t);if(!n)return aV;let r=n.at(-1)?.value?.toString()||``;return{type:`MEASURE_HEADER`,domain:n.slice(0,-1),measure:r}}else if(t<=r-1){let n=this.getColHeaderDomain(e,t);return n?{type:`HEADER`,domain:n,dimension:`COL`}:aV}else if(e===0){let e=t-r;return{type:`HEADER`,domain:this.getDomain(this.rows[e]),dimension:`ROW`}}else{let i=t-r;return!n&&this.isTotalRow(i)?aV:{type:`VALUE`,domain:[...this.getDomain(this.rows[i]),...this.getColDomain(e)],measure:this.getColMeasure(e)}}}getColHeaderDomain(e,t){if(e===0)return;let n=this.columns[t].find(t=>t.offset===e);if(!(!n||n.collapsedHeader))return this.getDomain(n)}getDomain(e){return e.fields.map((t,n)=>{if(t===`measure`)return{type:`char`,field:t,value:gd({displayName:`measure`,type:`char`},e.values[n])};{let{fieldName:r,granularity:i}=dd(t),a=this.fieldsType[r]||`char`;return{type:a,field:t,value:gd({displayName:r,type:a,granularity:i},e.values[n])}}})}getColDomain(e){let t=this.getColHeaderDomain(e,this.columns.length-1);return t?t.slice(0,-1):[]}getColMeasure(e){let t=this.getColHeaderDomain(e,this.columns.length-1)?.at(-1)?.value;if(t==null)throw Error(`Measure is missing`);return t.toString()}buildRowsTree(){let e=[],t=0,n={};n[0]=e;for(let r of this.rows){if(r.fields.length===0||r.values.length===0)return e;let i=r.fields.length-1,a=r.fields[i],{fieldName:o,granularity:s}=dd(a),c=gd({displayName:o,type:this.fieldsType[o]??`char`,granularity:s},r.values[i]);if(i>t){t=i,n[t]=[];let e=n[t-1].at(-1);e&&(e.children=n[t])}t=i;let l={value:c,field:r.fields[i],children:[],type:this.fieldsType[o]||`char`,width:0};n[t].push(l)}return e}buildColumnsTree(){let e=[],t=this.columns.at(-2)||[],n={};n[0]=e;for(let e of t)for(let t=0;t<e.fields.length;t++){let r=e.fields[t],{fieldName:i,granularity:a}=dd(r),o=gd({displayName:i,type:this.fieldsType[i]??`char`,granularity:a},e.values[t]),s={value:o,field:e.fields[t],children:[],width:e.width,type:this.fieldsType[i]||`char`};n[t]?.at(-1)?.value!==o&&(n[t+1]=[],s.children=n[t+1],n[t].push(s))}return e}export(){return{cols:this.columns,rows:this.rows,measures:this.measures,fieldsType:this.fieldsType}}sort(e,t,n){if(this.isSorted)return;let r=(e,t)=>{let r=n(e,t).value;return typeof r==`number`?r:-1/0},i=t.domain,a=II(this.rowTree(),[],(n,a)=>{let o=r(e,[...n,...i]),s=r(e,[...a,...i]);return t.order===`asc`?o-s:s-o});this.rowTree=kt(a),this.rows=[...this.rowTreeToRows(a),this.rows[this.rows.length-1]],this.isSorted=!0}rowTreeToRows(e,t){return e.flatMap(e=>{let n={indent:t?t.indent+1:1,fields:[...t?.fields||[],e.field],values:[...t?.values||[],e.value]};return[n,...this.rowTreeToRows(e.children,n)]})}};let aV={type:`EMPTY`};function oV(e,t,n){let r=t.measures.filter(e=>!e.isHidden).map(e=>e.id),i=cV(e,t.columns,0);lV(i,r.length);let a=uV(i,t),o=sV(e,0,t.rows,[],[]);o.push({fields:[],values:[],indent:0});let s={};for(let e of t.columns)s[e.fieldName]=e.type;for(let e of t.rows)s[e.fieldName]=e.type;return new iV(a,o,r,s,n===`collapsed`?t.collapsedDomains:void 0)}function sV(e,t,n,r,i){if(t>=n.length)return[];let a=n[t],o=a.nameWithGranularity,s=dV(e,a),c=pV(s,a),l=[],u=r.concat(o);for(let e of c){let r=i.concat(e);l.push({fields:u,values:r,indent:t+1});let a=s[e];a&&l.push(...sV(a,t+1,n,u,r))}return l}function cV(e,t,n){if(n>=t.length)return[];let r=t[n],i=t[n].nameWithGranularity,a=dV(e,r);return pV(a,t[n]).map(e=>({value:a[e]?.[0]?.[r.nameWithGranularity]?.value??null,field:i,children:cV(a[e]||[],t,n+1),type:r.type,width:0}))}function lV(e,t){for(let n in e){let r=e[n];r.children.length===0?r.width=t:(lV(r.children,t),r.width=r.children.reduce((e,t)=>e+t.width,0))}}function uV(e,t){let n=t.columns.map(e=>e.nameWithGranularity),r=n.length,i=t.measures.filter(e=>!e.isHidden),a=i.length,o=Array(r).fill(0).map(()=>[]);function s(e,t,i){let a=o[t];for(let o of e){let e=i.concat([o.value]),c={fields:n.slice(0,t+1),values:e,width:o.width,offset:0};a.push(c),t<=r-1&&s(o.children,t+1,e)}}s(e,0,[]);let c=n.length>0,l=[];return c&&o[o.length-1].forEach(e=>{i.forEach(t=>{let n={fields:[...e.fields,`measure`],values:[...e.values,t.id],width:1,offset:0};l.push(n)})}),i.forEach(e=>{let t={fields:[`measure`],values:[e.id],width:1,offset:0};l.push(t)}),o.push(l),o.length===1&&o.unshift([]),o[o.length-2].push({fields:[],values:[],width:a,offset:0}),o}function dV(e,t){return Object.groupBy(e,fV(t))}function fV(e){let t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}function pV(e,t){return t.order?Object.keys(e).sort((e,n)=>mV(t,e,n)):Object.keys(e)}function mV(e,t,n){return t===`null`?e.order===`asc`?1:-1:n===`null`?e.order===`asc`?-1:1:e.type===`integer`||e.type===`datetime`?e.order===`asc`?M(t,D)-M(n,D):M(n,D)-M(t,D):e.order===`asc`?t.localeCompare(n):n.localeCompare(t)}let hV=Symbol(`NULL`);function gV(e,t,n){let r=e.granularity||`month`;if(!(r in _V))throw Error(`Unknown date granularity: ${r}`);let i=typeof t==`number`||typeof t==`string`?t:hV;if(!_V[r].set.has(t)){_V[r].set.add(t);let a=null;if(typeof t==`number`||typeof t==`string`){let e=F(t,n);switch(r){case`year`:a=e.getFullYear();break;case`quarter_number`:a=Math.floor(e.getMonth()/3)+1;break;case`month_number`:a=e.getMonth()+1;break;case`month`:a=Math.floor(M(t,n));break;case`iso_week_number`:a=e.getIsoWeek();break;case`day_of_month`:a=e.getDate();break;case`day`:a=Math.floor(M(t,n));break;case`day_of_week`:a=(e.getDay()+7-n.weekStart)%7+1;break;case`hour_number`:a=e.getHours();break;case`minute_number`:a=e.getMinutes();break;case`second_number`:a=e.getSeconds();break}}_V[r].values[i]=gd(e,a)}return _V[r].values[i]}let _V={year:{set:new Set,values:{}},quarter_number:{set:new Set,values:{}},month_number:{set:new Set,values:{}},month:{set:new Set,values:{}},iso_week_number:{set:new Set,values:{}},day_of_month:{set:new Set,values:{}},day:{set:new Set,values:{}},day_of_week:{set:new Set,values:{}},hour_number:{set:new Set,values:{}},minute_number:{set:new Set,values:{}},second_number:{set:new Set,values:{}}};function vV(){for(let e in _V)_V[e].set.clear(),_V[e].values={}}var yV=class{type=`SPREADSHEET`;getters;_definition;coreDefinition;metaData={fields:{},fieldKeys:[]};dataEntries=[];collapsedTable;expandedTable;invalidRangeError;needsReevaluation=!0;constructor(e,t){this.getters=t.getters,this.coreDefinition=t.definition}init(e={}){(!this._definition||e.reload)&&(this.reload(4),this.needsReevaluation=!1)}reload(e){e===4&&(this.metaData=this.loadMetaData()),e>=3&&(this._definition=this.loadRuntimeDefinition()),e>=2&&(this.dataEntries=this.loadData()),e>=1&&(this.collapsedTable=void 0,this.expandedTable=void 0)}onDefinitionChange(e){let t=this.coreDefinition;if(this.coreDefinition=e,this._definition){let n=Math.max(this.computeShouldReload(t,e),0);this.reload(n)}}computeShouldReload(e,t){return w(e.dataSet,t.dataSet)?3:4}get isInvalidRange(){return!!this.invalidRangeError}get invalidRangeMessage(){return this.invalidRangeError?.message}get definition(){if(this._definition||this.init(),!this._definition)throw Error(`Pivot definition should be defined at this point.`);return this._definition}isValid(){if(this.invalidRangeError||!this.definition)return!1;for(let e of this.definition.measures)if(!e.isValid)return!1;for(let e of this.definition.columns)if(!e.isValid)return!1;for(let e of this.definition.rows)if(!e.isValid)return!1;return!0}assertIsValid({throwOnError:e}){if(!this.isValid()){if(e)throw this.invalidRangeError?this.invalidRangeError:new A(E(`At least one measure and/or dimension is not correct.`));return{value:k.GenericError,message:this.invalidRangeError?.message??E(`At least one measure and/or dimension is not correct.`)}}}areDomainArgsFieldsValid(e){let t=e.filter((e,t)=>t%2==0).map(N);return t.length&&t.at(-1)===`measure`&&(t=t.slice(0,-1)),md(t,this.definition)}parseArgsToPivotDomain(e){let t=[];for(let n=0;n<e.length-1;n+=2){let r=N(e[n]),i=this.getTypeOfDimension(r),a=r===`measure`?N(e[n+1]):gd(this.getDimension(r),e[n+1]);t.push({field:r,value:a,type:i})}return t}markAsDirtyForEvaluation(){this.needsReevaluation=!0}getMeasure(e){return this.definition.getMeasure(e)}getPivotMeasureValue(e){return{value:this.getMeasure(e).displayName}}getPivotHeaderValueAndFormat(e){let t=e.at(-1);if(!t)return{value:E(`Total`)};let n=this.getDimension(t.field),r=this.filterDataEntriesFromDomain(this.dataEntries,e)[0]?.[n.nameWithGranularity];return n.type===`datetime`?Wu(n.granularity||`month`).toValueAndFormat(t.value,this.getters.getLocale()):r?r.value===null?{value:E(`(Undefined)`)}:r:{value:``}}getPivotCellValueAndFormat(e,t){let n=this.filterDataEntriesFromDomain(this.dataEntries,t);if(n.length===0)return{value:``};let r=this.getMeasure(e),i=n.map(e=>e[r.fieldName]).filter(C),a=i.filter(e=>e.type!==`empty`),o=r.aggregator,s=sd[o];if(!s)throw Error(`Aggregator ${o} does not exist`);try{let e=s([i],this.getters.getLocale());return a.length===0?{...e,value:``}:e}catch(e){return Rx(e,o.toUpperCase())}}getPossibleFieldValues(e){let t=[],n=dV(this.dataEntries,e),r=pV(n,e);for(let i of r)t.push({value:n[i]?.[0]?.[e.nameWithGranularity]?.value??``,label:n[i]?.[0]?.[e.nameWithGranularity]?.formattedValue||``});return t}getCollapsedTableStructure(){if(!this.isValid())throw Error(`Pivot is not valid !`);return this.collapsedTable||=oV(this.dataEntries,this.definition,`collapsed`),this.collapsedTable}getExpandedTableStructure(){if(!this.isValid())throw Error(`Pivot is not valid !`);return this.expandedTable||=oV(this.dataEntries,this.definition,`expanded`),this.expandedTable}getFields(){return this.metaData.fields}get fields(){return this.getFields()}loadMetaData(){if(this.invalidRangeError=void 0,this.coreDefinition.dataSet){let{zone:e,sheetId:t}=this.coreDefinition.dataSet,n=this.getters.getRangeFromZone(t,e);try{return this.extractFieldsFromRange(n)}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}else return this.invalidRangeError=new A(E(`The pivot cannot be created because the dataset is missing.`)),{fields:{},fieldKeys:[]}}loadRuntimeDefinition(){return new rV(this.coreDefinition,this.fields,this.getters)}loadData(){let e=this._definition?.range;return this.isValid()&&e?this.extractDataEntriesFromRange(e):[]}getTypeOfDimension(e){if(e===`measure`)return`char`;let{fieldName:t}=dd(e),n=this.fields[t]?.type;if(!n)throw Error(`Field ${t} does not exist`);return n}filterDataEntriesFromDomain(e,t){return t.reduce((e,t)=>this.filterDataEntriesFromDomainNode(e,t),e)}filterDataEntriesFromDomainNode(e,t){let{field:n,value:r,type:i}=t,{nameWithGranularity:a}=this.getDimension(n);return e.filter(e=>{let t=e[a]?.value;return i===`char`?String(t)===String(r):t===r})}getDimension(e){return this.definition.getDimension(e)}getTypeFromZone(e,t){let n=this.getters.getEvaluatedCellsInZone(e,t).filter(e=>!(e.type===`empty`||e.value===``));return n.length===0?`integer`:n.every(e=>e.type===`number`&&e.format&&So(e.format))?`datetime`:n.every(e=>e.type===`boolean`)?`boolean`:n.every(e=>e.type===`number`)?`integer`:`char`}assertCellIsValidField(e,t,n){if(n.type===`error`)throw new A(E(`The pivot cannot be created because cell %s contains an error`,T(e,t)));if(n.type===`empty`||n.value===``)throw new A(E(`The pivot cannot be created because cell %s is empty`,T(e,t)));if(n.value===`__count`)throw new A(E(`The pivot cannot be created because cell %s contains a reserved value`,T(e,t)))}extractFieldsFromRange(e){let t={},n=[],r=e.sheetId,i=e.zone.top;for(let a=e.zone.left;a<=e.zone.right;a++){let o=this.getters.getEvaluatedCell({sheetId:r,col:a,row:i});this.assertCellIsValidField(a,i,o);let s=o.value?.toString();if(s){let i=this.getTypeFromZone(r,{top:e.zone.top+1,left:a,bottom:e.zone.bottom,right:a}),o=this.findName(s,t);t[o]={name:o,type:i,string:o,aggregator:i===`integer`?`sum`:`count`},n.push(o)}}return{fields:t,fieldKeys:n}}findName(e,t){return $t(e,Object.keys(t),{compute:(e,t)=>`${e}${t}`,start:2})}extractDataEntriesFromRange(e){let t=[];for(let n=e.zone.top+1;n<=e.zone.bottom;n++){let r={top:n,bottom:n,left:e.zone.left,right:e.zone.right},i=this.getters.getEvaluatedCellsInZone(e.sheetId,r),a={};for(let e in i){let t=i[e],n=this.fields[this.metaData.fieldKeys[e]];if(!n)throw Error(`Field ${this.metaData.fieldKeys[e]} does not exist`);t.value===``?a[n.name]={value:null,type:`empty`,formattedValue:``}:a[n.name]=t}a.__count={value:1,type:`number`,formattedValue:`1`},t.push(a)}let n=this.definition.columns.concat(this.definition.rows).filter(e=>e.type===`datetime`);if(n.length){let e=this.getters.getLocale();for(let r of t)for(let t of n){let n=gV(t,r[t.fieldName]?.value||null,this.getters.getLocale()),{format:i,value:a}=Wu(t.granularity||`month`).toValueAndFormat(n,e);r[t.nameWithGranularity]={value:n,type:r[t.fieldName]?.type||`empty`,format:r[t.fieldName]?.format,formattedValue:L(a,{locale:e,format:i})}}}return t}};let bV=new g,xV=[`year`,`quarter_number`,`month_number`,`month`,`iso_week_number`,`day_of_month`,`day`,`day_of_week`],SV=[...xV,`hour_number`,`minute_number`,`second_number`];bV.add(`SPREADSHEET`,{ui:yV,definition:rV,dateGranularities:[...xV],isMeasureCandidate:e=>e.type!==`boolean`,datetimeGranularities:[...SV],isGroupable:()=>!0,adaptRanges:(e,t,n)=>{if(t.type!==`SPREADSHEET`||!t.dataSet)return t;let{sheetId:r,zone:i}=t.dataSet,a=e.getRangeFromZone(r,i),o=CV(a,n);if(o===a)return t;let s=o&&{sheetId:o.sheetId,zone:o.zone};return{...t,dataSet:s}}});function CV(e,t){if(!e)return;let n=t(e);switch(n.changeType){case`REMOVE`:return;default:return n.range}}var wV=class extends Xd{mutators=[`reset`,`deferUpdates`,`applyUpdate`,`discardPendingUpdate`,`update`];updatesAreDeferred;draft=null;notification=this.get(LO);alreadyNotified=!1;constructor(e,t){super(e),this.pivotId=t,this.updatesAreDeferred=this.getters.getPivotCoreDefinition(this.pivotId).deferUpdates??!1}handle(e){switch(e.type){case`UPDATE_PIVOT`:e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){let e=bV.get(this.pivot.type).definition;return this.draft?new e(this.draft,this.fields,this.getters):this.pivot.definition}get isDirty(){return!!this.draft}get measureFields(){let e=[{name:`__count`,string:E(`Count`),type:`integer`,aggregator:`sum`}],t=this.fields;for(let n in t){let r=t[n];r&&bV.get(this.pivot.type).isMeasureCandidate(r)&&e.push(r)}return e.sort((e,t)=>e.string.localeCompare(t.string))}get unusedGroupableFields(){let e=[],t=this.fields;for(let n in t){let r=t[n];r&&bV.get(this.pivot.type).isGroupable(r)&&e.push(r)}let{columns:n,rows:r,measures:i}=this.definition,a=i.concat(r).concat(n).map(e=>e.fieldName),o=this.unusedGranularities;return e.filter(e=>fd(e)?!a.includes(e.name)||o[e.name].size>0:!a.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get datetimeGranularities(){return bV.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return bV.get(this.pivot.type).dateGranularities}get unusedGranularities(){return this.getUnusedGranularities(this.fields,this.draft??this.getters.getPivotCoreDefinition(this.pivotId))}reset(e){this.pivotId=e,this.updatesAreDeferred=!0,this.draft=null}deferUpdates(e){e===!1&&this.draft?(this.draft.deferUpdates=!1,this.applyUpdate()):this.update({deferUpdates:e}),this.updatesAreDeferred=e}applyUpdate(){if(this.draft&&(this.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&this.isUpdatedPivotVisibleInViewportOnlyAsStaticPivot())){let e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:`info`,text:E(`Pivot updates only work with dynamic pivot tables. Use the formula '%s' or re-insert the static pivot from the Data menu.`,e),sticky:!0})}}discardPendingUpdate(){this.draft=null}update(e){let t=this.getters.getPivotCoreDefinition(this.pivotId),n={...t,...this.draft,...e},r={...n,columns:n.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:n.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:n.measures.map(e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display})),sortedColumn:this.shouldKeepSortedColumn(n)?n.sortedColumn:void 0};if(r.collapsedDomains){let{COL:e,ROW:t}=r.collapsedDomains;r.collapsedDomains={COL:e.filter(e=>this.areDomainFieldsValid(e,r.columns)),ROW:t.filter(e=>this.areDomainFieldsValid(e,r.rows))}}if(!this.draft&&w(t,r))return;let i=this.addDefaultDateTimeGranularity(this.fields,r);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0,t=this.getters.getPivotFormulaId(this.pivotId);for(let n of this.getters.getVisibleCellPositions()){let r=this.getters.getCell(n);if(r?.isFormula){let n=QB(r.compiledFormula.tokens),i=n?.args[0]?.value;if(n&&t===i.toString()){if(n.functionName===`PIVOT`)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){let{columns:n,rows:r}=t,i=b(n),a=b(r),o=this.getUnusedGranularities(e,t);for(let t of i.concat(a)){let n=e[t.fieldName]?.type;if((n===`date`||n===`datetime`)&&!t.granularity){let e=o[t.fieldName]?.values().next().value;o[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:a}}getUnusedGranularities(e,t){let{columns:n,rows:r,measures:i}=t,a=n.concat(r).concat(i).filter(t=>{let n=e[t.fieldName]?.type;return n===`date`||n===`datetime`}),o={};for(let t of a)o[t.fieldName]=new Set(e[t.fieldName]?.type===`date`?this.dateGranularities:this.datetimeGranularities);for(let e of a)o[e.fieldName].delete(e.granularity);return o}shouldKeepSortedColumn(e){let{sortedColumn:t}=e;if(!t)return!0;let n=this.getters.getPivotCoreDefinition(this.pivotId);return e.measures.find(e=>e.id===t.measure)&&w(n.columns,e.columns)}areDomainFieldsValid(e,t){let n=t.map(({fieldName:e,granularity:t})=>e+(t?`:${t}`:``));for(let t=0;t<e.length;t++)if(e[t].field!==n[t])return!1;return!0}},TV=class extends t.Component{static template=`o-spreadsheet-PivotSpreadsheetSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:WB,Section:X,SelectionInput:fk,Checkbox:vk,PivotDeferUpdate:MB,PivotTitleSection:GB};store;state;pivotSidePanelRef=(0,t.useRef)(`pivotSidePanel`);setup(){this.store=Wd(wV,this.props.pivotId),this.state=(0,t.useState)({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return this.store.isDirty&&this.state.rangeHasChanged?!1:this.pivot.isInvalidRange}get ranges(){return this.state.range?[this.state.range]:this.definition.range?[this.env.model.getters.getRangeString(this.definition.range,`forceSheetReference`)]:[]}get pivot(){return this.store.pivot}get definition(){return this.store.definition}getScrollableContainerEl(){return this.pivotSidePanelRef.el}onSelectionChanged(e){this.state.rangeHasChanged=!0,this.state.range=e[0]}onSelectionConfirmed(){if(this.state.range){let e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;let t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){let{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}};let EV=new g;EV.add(`SPREADSHEET`,{editor:TV});var DV=class extends t.Component{static template=`o-spreadsheet-PivotSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:WB,Section:X};setup(){pB(this)}get sidePanelEditor(){let e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw Error(`pivotId does not correspond to a pivot.`);return EV.get(e.type).editor}get highlights(){return AB(this.env.model.getters,this.props.pivotId)}};V`
|
|
1773
|
+
`;var WB=class extends t.Component{static template=`o-spreadsheet-PivotLayoutConfigurator`;static components={AddDimensionButton:FB,PivotDimension:RB,PivotDimensionOrder:BB,PivotDimensionGranularity:zB,PivotMeasureEditor:HB,PivotSortSection:UB};static props={definition:Object,onDimensionsUpdated:Function,unusedGroupableFields:Array,measureFields:Array,unusedGranularities:Object,dateGranularities:Array,datetimeGranularities:Array,getScrollableContainerEl:{type:Function,optional:!0},pivotId:String};dimensionsRef=(0,t.useRef)(`pivot-dimensions`);dragAndDrop=ak();AGGREGATORS=od;composerFocus;isDateOrDatetimeField=fd;setup(){this.composerFocus=B(Qd)}startDragAndDrop(e,t){if(t.button!==0||t.target.tagName===`SELECT`)return;let n=this.getDimensionElementsRects(),{columns:r,rows:i}=this.props.definition,a=[...r.map(e=>e.nameWithGranularity),`__rows_title__`,...i.map(e=>e.nameWithGranularity)],o=r.concat(i),s=a.map((e,t)=>({id:e,size:n[t+1].height,position:n[t+1].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:s,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=a.findIndex(t=>t===e);if(n===t)return;let r=[...a];r.splice(n,1),r.splice(t,0,e);let i=r.slice(0,r.indexOf(`__rows_title__`)),s=r.slice(r.indexOf(`__rows_title__`)+1);this.props.onDimensionsUpdated({columns:i.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(C),rows:s.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(C)})}})}getGranularitiesFor(e){return fd(e)?e.type===`date`?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(t.button!==0||t.target.tagName===`SELECT`||t.target.tagName===`INPUT`||this.composerFocus.focusMode!==`inactive`)return;let n=this.getDimensionElementsRects(),{measures:r,columns:i,rows:a}=this.props.definition,o=r.map(e=>e.id),s=3+i.length+a.length,c=o.map((e,t)=>({id:e,size:n[t+s].height,position:n[t+s].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=o.findIndex(t=>t===e);if(n===t)return;let i=[...o];i.splice(n,1),i.splice(t,0,e),this.props.onDimensionsUpdated({measures:i.map(e=>r.find(t=>t.id===e)).filter(C)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{let t=getComputedStyle(e),n=e.getBoundingClientRect();return{x:n.x,y:n.y,width:n.width+parseInt(t.marginLeft||`0`)+parseInt(t.marginRight||`0`),height:n.height+parseInt(t.marginTop||`0`)+parseInt(t.marginBottom||`0`)}})}removeDimension(e){let{columns:t,rows:n}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:n.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){let{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){let{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:`asc`}])})}addRowDimension(e){let{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:`asc`}])})}addMeasureDimension(e){let{measures:t}=this.props.definition,n=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,n),fieldName:e,aggregator:n}])})}updateMeasure(e,t){let{measures:n}=this.props.definition,r={measures:n.map(n=>n.id===e.id?t:n)};this.props.definition.sortedColumn?.measure===e.id&&(r.sortedColumn={...this.props.definition.sortedColumn,measure:t.id}),this.props.onDimensionsUpdated(r)}getMeasureId(e,t){let n=e.replaceAll(`'`,``)+(t?`:${t}`:``),r=n,i=2;for(;this.props.definition.measures.some(e=>e.id===r);)r=`${n}:${i}`,i++;return r}getDefaultMeasureAggregator(e){let t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:`count`}addCalculatedMeasure(){let{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t,`sum`),fieldName:t,aggregator:`sum`,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:`=0`}}])})}updateOrder(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n)})}updateGranularity(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n)})}getMeasureDescription(e){let t=e.display;if(!t||t.type===`no_calculations`)return``;let n=this.env.model.getters.getPivot(this.props.pivotId),r=[...n.definition.columns,...n.definition.rows].find(e=>e.nameWithGranularity===t.fieldNameWithGranularity),i=r?Sd(r):``;return Rw.descriptions[t.type](i)}},GB=class extends t.Component{static template=`o-spreadsheet-PivotTitleSection`;static components={CogWheelMenu:LB,Section:X,TextInput:IB};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:E(`Flip axes`),icon:`o-spreadsheet-Icon.EXCHANGE`,execute:this.props.flipAxis},{name:E(`Duplicate`),icon:`o-spreadsheet-Icon.COPY`,execute:()=>this.duplicatePivot()},{name:E(`Delete`),icon:`o-spreadsheet-Icon.TRASH`,execute:()=>this.delete()}]}get name(){return this.env.model.getters.getPivotName(this.props.pivotId)}get displayName(){return this.env.model.getters.getPivotDisplayName(this.props.pivotId)}duplicatePivot(){let e=this.env.model.uuidGenerator.smallUuid(),t=this.env.model.uuidGenerator.smallUuid(),n=this.env.model.dispatch(`DUPLICATE_PIVOT_IN_NEW_SHEET`,{pivotId:this.props.pivotId,newPivotId:e,newSheetId:t}),r;r=n.isSuccessful?E(`Pivot duplicated.`):n.isCancelledBecause(`PivotInError`)?E(`Cannot duplicate a pivot in error.`):E(`Pivot duplication failed.`);let i=n.isSuccessful?`success`:`danger`;this.env.notifyUser({text:r,sticky:!1,type:i}),n.isSuccessful&&this.env.openSidePanel(`PivotSidePanel`,{pivotId:e})}delete(){this.env.askConfirmation(E(`Are you sure you want to delete this pivot?`),()=>{this.env.model.dispatch(`REMOVE_PIVOT`,{pivotId:this.props.pivotId})})}onNameChanged(e){let t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.props.pivotId,pivot:{...t,name:e}})}};let KB=[`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`];function qB(e,t){let n=`"${t?`${e.name}:${t}`:e.name}"`,r=e.string===e.name?n:e.string+n;return{text:n,description:e.string+(e.help?` (${e.help})`:``),htmlContent:[{value:n,color:VO.STRING}],fuzzySearchKey:r}}function JB(e){let t=`"${e.id}"`,n=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:VO.STRING}],fuzzySearchKey:n}}function YB(e,t){let n=e.end,r=e.end;e.type!==`ARG_SEPARATOR`&&(n=e.start),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}function XB(e,t){let n=e.end,r=e.end;e.type!==`LEFT_PAREN`&&(n=e.start),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}function ZB(e){let t=e.functionContext?.args[0];if(!(!t||![`STRING`,`NUMBER`].includes(t.type)))return t.value}function QB(e){return sS(e,KB)[0]}function $B(e){return sS(e,KB).length}var eV=class{measures;columns;rows;sortedColumn;collapsedDomains;constructor(e,t){this.measures=e.measures.map(e=>tV(t,e)),this.columns=e.columns.map(e=>nV(t,e)),this.rows=e.rows.map(e=>nV(t,e)),this.sortedColumn=e.sortedColumn,this.collapsedDomains=e.collapsedDomains}getDimension(e){let t=this.columns.find(t=>t.nameWithGranularity===e)||this.rows.find(t=>t.nameWithGranularity===e);if(!t)throw new A(E(`Dimension %s does not exist`,e));return t}getMeasure(e){let t=this.measures.find(t=>t.id===e);if(!t)throw new A(E(`Field %s is not a measure`,e));return t}};function tV(e,t){let n=t.fieldName,r=n===`__count`?{name:`__count`,string:E(`Count`),type:`integer`,aggregator:`sum`}:e[n],i=t.aggregator;return{id:t.id,get displayName(){return t.userDefinedName??r?.string??t.fieldName},userDefinedName:t.userDefinedName,fieldName:n,aggregator:i,type:n===`__count`?`integer`:r?.type??`integer`,isValid:!!(r||t.computedBy),isHidden:t.isHidden,format:t.format,computedBy:t.computedBy,display:t.display}}function nV(e,t){let n=e[t.fieldName],r=n?.type??`integer`,i=n&&fd(n)?t.granularity:void 0;return{displayName:n?.string??t.fieldName,nameWithGranularity:t.fieldName+(i?`:${i}`:``),fieldName:t.fieldName,granularity:i,type:r,order:t.order,isValid:!!n}}var rV=class extends eV{range;constructor(e,t,n){if(super(e,t),e.dataSet){let{sheetId:t,zone:r}=e.dataSet;this.range=n.getRangeFromZone(t,r)}}},iV=class{columns;rows;measures;fieldsType;maxIndent;pivotCells={};rowTree;colTree;isSorted=!1;constructor(e,t,n,r,i={COL:[],ROW:[]}){this.measures=n,this.fieldsType=r,i.COL.length&&(e=this.removeCollapsedColumns(e,n,i.COL)),this.columns=e.map(e=>{let t=1;return e.map(e=>(e={...e,offset:t},t+=e.width,e))}),this.rows=t.filter(e=>!this.isParentCollapsed(i.ROW,e)),this.maxIndent=Math.max(...this.rows.map(e=>e.indent)),this.rowTree=kt(()=>this.buildRowsTree()),this.colTree=kt(()=>this.buildColumnsTree())}removeCollapsedColumns(e,t,n){let r=(n,r)=>{let i=this.getDomain(n),a=e[r],o=a.findIndex(e=>LI(this.getDomain(e),i)),s=a.findLastIndex(e=>LI(this.getDomain(e),i)),c=r===e.length-1,l=t.map(e=>({fields:c?[...n.fields,`measure`]:[],values:c?[...n.values,e]:[],width:1,offset:0,collapsedHeader:!c}));a.splice(o,s-o+1,...l)};return e.map((i,a)=>{for(let o of i){if(a>=e.length-2)return i;let s=this.getDomain(o);if(n.some(e=>w(s,e))){o.width=t.length;for(let t=a+1;t<e.length;t++)r(o,t)}}return i})}isParentCollapsed(e,t){let n=this.getDomain(t);return e.some(e=>LI(n,e))}getNumberOfDataColumns(){return this.columns.at(-1)?.length||0}getSkippedRows(e){let t=new Set;if(!e.displayColumnHeaders)for(let e=0;e<this.columns.length-1;e++)t.add(e);return e.displayMeasuresRow||t.add(this.columns.length-1),t}getPivotCells(e={displayColumnHeaders:!0,displayTotals:!0,displayMeasuresRow:!0}){let t=JSON.stringify(e);if(!this.pivotCells[t]){let{displayTotals:n}=e,r=this.rows.length,i=this.getNumberOfDataColumns(),a=this.columns.length+r,o=1+i;!n&&r!==1&&--a,!n&&i!==this.measures.length&&(o-=this.measures.length);let s=[],c=this.getSkippedRows(e);for(let e=0;e<o;e++){s.push([]);for(let t=0;t<a;t++)c.has(t)||s[e].push(this.getPivotCell(e,t,n))}this.pivotCells[t]=s}return this.pivotCells[t]}getRowTree(){return this.rowTree()}getColTree(){return this.colTree()}isTotalRow(e){return this.rows[e].indent!==this.maxIndent}getPivotCell(e,t,n=!0){let r=this.columns.length;if(e>0&&t===r-1){let n=this.getColHeaderDomain(e,t);if(!n)return aV;let r=n.at(-1)?.value?.toString()||``;return{type:`MEASURE_HEADER`,domain:n.slice(0,-1),measure:r}}else if(t<=r-1){let n=this.getColHeaderDomain(e,t);return n?{type:`HEADER`,domain:n,dimension:`COL`}:aV}else if(e===0){let e=t-r;return{type:`HEADER`,domain:this.getDomain(this.rows[e]),dimension:`ROW`}}else{let i=t-r;return!n&&this.isTotalRow(i)?aV:{type:`VALUE`,domain:[...this.getDomain(this.rows[i]),...this.getColDomain(e)],measure:this.getColMeasure(e)}}}getColHeaderDomain(e,t){if(e===0)return;let n=this.columns[t].find(t=>t.offset===e);if(!(!n||n.collapsedHeader))return this.getDomain(n)}getDomain(e){return e.fields.map((t,n)=>{if(t===`measure`)return{type:`char`,field:t,value:gd({displayName:`measure`,type:`char`},e.values[n])};{let{fieldName:r,granularity:i}=dd(t),a=this.fieldsType[r]||`char`;return{type:a,field:t,value:gd({displayName:r,type:a,granularity:i},e.values[n])}}})}getColDomain(e){let t=this.getColHeaderDomain(e,this.columns.length-1);return t?t.slice(0,-1):[]}getColMeasure(e){let t=this.getColHeaderDomain(e,this.columns.length-1)?.at(-1)?.value;if(t==null)throw Error(`Measure is missing`);return t.toString()}buildRowsTree(){let e=[],t=0,n={};n[0]=e;for(let r of this.rows){if(r.fields.length===0||r.values.length===0)return e;let i=r.fields.length-1,a=r.fields[i],{fieldName:o,granularity:s}=dd(a),c=gd({displayName:o,type:this.fieldsType[o]??`char`,granularity:s},r.values[i]);if(i>t){t=i,n[t]=[];let e=n[t-1].at(-1);e&&(e.children=n[t])}t=i;let l={value:c,field:r.fields[i],children:[],type:this.fieldsType[o]||`char`,width:0};n[t].push(l)}return e}buildColumnsTree(){let e=[],t=this.columns.at(-2)||[],n={};n[0]=e;for(let e of t)for(let t=0;t<e.fields.length;t++){let r=e.fields[t],{fieldName:i,granularity:a}=dd(r),o=gd({displayName:i,type:this.fieldsType[i]??`char`,granularity:a},e.values[t]),s={value:o,field:e.fields[t],children:[],width:e.width,type:this.fieldsType[i]||`char`};n[t]?.at(-1)?.value!==o&&(n[t+1]=[],s.children=n[t+1],n[t].push(s))}return e}export(){return{cols:this.columns,rows:this.rows,measures:this.measures,fieldsType:this.fieldsType}}sort(e,t,n){if(this.isSorted)return;let r=(e,t)=>{let r=n(e,t).value;return typeof r==`number`?r:-1/0},i=t.domain,a=II(this.rowTree(),[],(n,a)=>{let o=r(e,[...n,...i]),s=r(e,[...a,...i]);return t.order===`asc`?o-s:s-o});this.rowTree=kt(a),this.rows=[...this.rowTreeToRows(a),this.rows[this.rows.length-1]],this.isSorted=!0}rowTreeToRows(e,t){return e.flatMap(e=>{let n={indent:t?t.indent+1:1,fields:[...t?.fields||[],e.field],values:[...t?.values||[],e.value]};return[n,...this.rowTreeToRows(e.children,n)]})}};let aV={type:`EMPTY`};function oV(e,t,n){let r=t.measures.filter(e=>!e.isHidden).map(e=>e.id),i=cV(e,t.columns,0);lV(i,r.length);let a=uV(i,t),o=sV(e,0,t.rows,[],[]);o.push({fields:[],values:[],indent:0});let s={};for(let e of t.columns)s[e.fieldName]=e.type;for(let e of t.rows)s[e.fieldName]=e.type;return new iV(a,o,r,s,n===`collapsed`?t.collapsedDomains:void 0)}function sV(e,t,n,r,i){if(t>=n.length)return[];let a=n[t],o=a.nameWithGranularity,s=dV(e,a),c=pV(s,a),l=[],u=r.concat(o);for(let e of c){let r=i.concat(e);l.push({fields:u,values:r,indent:t+1});let a=s[e];a&&l.push(...sV(a,t+1,n,u,r))}return l}function cV(e,t,n){if(n>=t.length)return[];let r=t[n],i=t[n].nameWithGranularity,a=dV(e,r);return pV(a,t[n]).map(e=>({value:a[e]?.[0]?.[r.nameWithGranularity]?.value??null,field:i,children:cV(a[e]||[],t,n+1),type:r.type,width:0}))}function lV(e,t){for(let n in e){let r=e[n];r.children.length===0?r.width=t:(lV(r.children,t),r.width=r.children.reduce((e,t)=>e+t.width,0))}}function uV(e,t){let n=t.columns.map(e=>e.nameWithGranularity),r=n.length,i=t.measures.filter(e=>!e.isHidden),a=i.length,o=Array(r).fill(0).map(()=>[]);function s(e,t,i){let a=o[t];for(let o of e){let e=i.concat([o.value]),c={fields:n.slice(0,t+1),values:e,width:o.width,offset:0};a.push(c),t<=r-1&&s(o.children,t+1,e)}}s(e,0,[]);let c=n.length>0,l=[];return c&&o[o.length-1].forEach(e=>{i.forEach(t=>{let n={fields:[...e.fields,`measure`],values:[...e.values,t.id],width:1,offset:0};l.push(n)})}),i.forEach(e=>{let t={fields:[`measure`],values:[e.id],width:1,offset:0};l.push(t)}),o.push(l),o.length===1&&o.unshift([]),o[o.length-2].push({fields:[],values:[],width:a,offset:0}),o}function dV(e,t){return Object.groupBy(e,fV(t))}function fV(e){let t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}function pV(e,t){return t.order?Object.keys(e).sort((e,n)=>mV(t,e,n)):Object.keys(e)}function mV(e,t,n){return t===`null`?e.order===`asc`?1:-1:n===`null`?e.order===`asc`?-1:1:e.type===`integer`||e.type===`datetime`?e.order===`asc`?M(t,D)-M(n,D):M(n,D)-M(t,D):e.order===`asc`?t.localeCompare(n):n.localeCompare(t)}let hV=Symbol(`NULL`);function gV(e,t,n){let r=e.granularity||`month`;if(!(r in _V))throw Error(`Unknown date granularity: ${r}`);let i=typeof t==`number`||typeof t==`string`?t:hV;if(!_V[r].set.has(t)){_V[r].set.add(t);let a=null;if(typeof t==`number`||typeof t==`string`){let e=F(t,n);switch(r){case`year`:a=e.getFullYear();break;case`quarter_number`:a=Math.floor(e.getMonth()/3)+1;break;case`month_number`:a=e.getMonth()+1;break;case`month`:a=Math.floor(M(t,n));break;case`iso_week_number`:a=e.getIsoWeek();break;case`day_of_month`:a=e.getDate();break;case`day`:a=Math.floor(M(t,n));break;case`day_of_week`:a=(e.getDay()+7-n.weekStart)%7+1;break;case`hour_number`:a=e.getHours();break;case`minute_number`:a=e.getMinutes();break;case`second_number`:a=e.getSeconds();break}}_V[r].values[i]=gd(e,a)}return _V[r].values[i]}let _V={year:{set:new Set,values:{}},quarter_number:{set:new Set,values:{}},month_number:{set:new Set,values:{}},month:{set:new Set,values:{}},iso_week_number:{set:new Set,values:{}},day_of_month:{set:new Set,values:{}},day:{set:new Set,values:{}},day_of_week:{set:new Set,values:{}},hour_number:{set:new Set,values:{}},minute_number:{set:new Set,values:{}},second_number:{set:new Set,values:{}}};function vV(){for(let e in _V)_V[e].set.clear(),_V[e].values={}}var yV=class{type=`SPREADSHEET`;getters;_definition;coreDefinition;metaData={fields:{},fieldKeys:[]};dataEntries=[];collapsedTable;expandedTable;invalidRangeError;needsReevaluation=!0;constructor(e,t){this.getters=t.getters,this.coreDefinition=t.definition}init(e={}){(!this._definition||e.reload)&&(this.reload(4),this.needsReevaluation=!1)}reload(e){e===4&&(this.metaData=this.loadMetaData()),e>=3&&(this._definition=this.loadRuntimeDefinition()),e>=2&&(this.dataEntries=this.loadData()),e>=1&&(this.collapsedTable=void 0,this.expandedTable=void 0)}onDefinitionChange(e){let t=this.coreDefinition;if(this.coreDefinition=e,this._definition){let n=Math.max(this.computeShouldReload(t,e),0);this.reload(n)}}computeShouldReload(e,t){return w(e.dataSet,t.dataSet)?3:4}get isInvalidRange(){return!!this.invalidRangeError}get invalidRangeMessage(){return this.invalidRangeError?.message}get definition(){if(this._definition||this.init(),!this._definition)throw Error(`Pivot definition should be defined at this point.`);return this._definition}isValid(){if(this.invalidRangeError||!this.definition)return!1;for(let e of this.definition.measures)if(!e.isValid)return!1;for(let e of this.definition.columns)if(!e.isValid)return!1;for(let e of this.definition.rows)if(!e.isValid)return!1;return!0}assertIsValid({throwOnError:e}){if(!this.isValid()){if(e)throw this.invalidRangeError?this.invalidRangeError:new A(E(`At least one measure and/or dimension is not correct.`));return{value:k.GenericError,message:this.invalidRangeError?.message??E(`At least one measure and/or dimension is not correct.`)}}}areDomainArgsFieldsValid(e){let t=e.filter((e,t)=>t%2==0).map(N);return t.length&&t.at(-1)===`measure`&&(t=t.slice(0,-1)),md(t,this.definition)}parseArgsToPivotDomain(e){let t=[];for(let n=0;n<e.length-1;n+=2){let r=N(e[n]),i=this.getTypeOfDimension(r),a=r===`measure`?N(e[n+1]):gd(this.getDimension(r),e[n+1]);t.push({field:r,value:a,type:i})}return t}markAsDirtyForEvaluation(){this.needsReevaluation=!0}getMeasure(e){return this.definition.getMeasure(e)}getPivotMeasureValue(e){return{value:this.getMeasure(e).displayName}}getPivotHeaderValueAndFormat(e){let t=e.at(-1);if(!t)return{value:E(`Total`)};let n=this.getDimension(t.field),r=this.filterDataEntriesFromDomain(this.dataEntries,e)[0]?.[n.nameWithGranularity];return n.type===`datetime`?Wu(n.granularity||`month`).toValueAndFormat(t.value,this.getters.getLocale()):r?r.value===null?{value:E(`(Undefined)`)}:r:{value:``}}getPivotCellValueAndFormat(e,t){let n=this.filterDataEntriesFromDomain(this.dataEntries,t);if(n.length===0)return{value:``};let r=this.getMeasure(e),i=n.map(e=>e[r.fieldName]).filter(C),a=i.filter(e=>e.type!==`empty`),o=r.aggregator,s=sd[o];if(!s)throw Error(`Aggregator ${o} does not exist`);try{let e=s([i],this.getters.getLocale());return a.length===0?{...e,value:``}:e}catch(e){return Rx(e,o.toUpperCase())}}getPossibleFieldValues(e){let t=[],n=dV(this.dataEntries,e),r=pV(n,e);for(let i of r)t.push({value:n[i]?.[0]?.[e.nameWithGranularity]?.value??``,label:n[i]?.[0]?.[e.nameWithGranularity]?.formattedValue||``});return t}getCollapsedTableStructure(){if(!this.isValid())throw Error(`Pivot is not valid !`);return this.collapsedTable||=oV(this.dataEntries,this.definition,`collapsed`),this.collapsedTable}getExpandedTableStructure(){if(!this.isValid())throw Error(`Pivot is not valid !`);return this.expandedTable||=oV(this.dataEntries,this.definition,`expanded`),this.expandedTable}getFields(){return this.metaData.fields}get fields(){return this.getFields()}loadMetaData(){if(this.invalidRangeError=void 0,this.coreDefinition.dataSet){let{zone:e,sheetId:t}=this.coreDefinition.dataSet,n=this.getters.getRangeFromZone(t,e);try{return this.extractFieldsFromRange(n)}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}else return this.invalidRangeError=new A(E(`The pivot cannot be created because the dataset is missing.`)),{fields:{},fieldKeys:[]}}loadRuntimeDefinition(){return new rV(this.coreDefinition,this.fields,this.getters)}loadData(){let e=this._definition?.range;return this.isValid()&&e?this.extractDataEntriesFromRange(e):[]}getTypeOfDimension(e){if(e===`measure`)return`char`;let{fieldName:t}=dd(e),n=this.fields[t]?.type;if(!n)throw Error(`Field ${t} does not exist`);return n}filterDataEntriesFromDomain(e,t){return t.reduce((e,t)=>this.filterDataEntriesFromDomainNode(e,t),e)}filterDataEntriesFromDomainNode(e,t){let{field:n,value:r,type:i}=t,{nameWithGranularity:a}=this.getDimension(n);return e.filter(e=>{let t=e[a]?.value;return i===`char`?String(t)===String(r):t===r})}getDimension(e){return this.definition.getDimension(e)}getTypeFromZone(e,t){let n=this.getters.getEvaluatedCellsInZone(e,t).filter(e=>!(e.type===`empty`||e.value===``));return n.length===0?`integer`:n.every(e=>e.type===`number`&&e.format&&So(e.format))?`datetime`:n.every(e=>e.type===`boolean`)?`boolean`:n.every(e=>e.type===`number`)?`integer`:`char`}assertCellIsValidField(e,t,n){if(n.type===`error`)throw new A(E(`The pivot cannot be created because cell %s contains an error`,T(e,t)));if(n.type===`empty`||n.value===``)throw new A(E(`The pivot cannot be created because cell %s is empty`,T(e,t)));if(n.value===`__count`)throw new A(E(`The pivot cannot be created because cell %s contains a reserved value`,T(e,t)))}extractFieldsFromRange(e){let t={},n=[],r=e.sheetId,i=e.zone.top;for(let a=e.zone.left;a<=e.zone.right;a++){let o=this.getters.getEvaluatedCell({sheetId:r,col:a,row:i});this.assertCellIsValidField(a,i,o);let s=o.value?.toString();if(s){let i=this.getTypeFromZone(r,{top:e.zone.top+1,left:a,bottom:e.zone.bottom,right:a}),o=this.findName(s,t);t[o]={name:o,type:i,string:o,aggregator:i===`integer`?`sum`:`count`},n.push(o)}}return{fields:t,fieldKeys:n}}findName(e,t){return $t(e,Object.keys(t),{compute:(e,t)=>`${e}${t}`,start:2})}extractDataEntriesFromRange(e){let t=[];for(let n=e.zone.top+1;n<=e.zone.bottom;n++){let r={top:n,bottom:n,left:e.zone.left,right:e.zone.right},i=this.getters.getEvaluatedCellsInZone(e.sheetId,r),a={};for(let e in i){let t=i[e],n=this.fields[this.metaData.fieldKeys[e]];if(!n)throw Error(`Field ${this.metaData.fieldKeys[e]} does not exist`);t.value===``?a[n.name]={value:null,type:`empty`,formattedValue:``}:a[n.name]=t}a.__count={value:1,type:`number`,formattedValue:`1`},t.push(a)}let n=this.definition.columns.concat(this.definition.rows).filter(e=>e.type===`datetime`);if(n.length){let e=this.getters.getLocale();for(let r of t)for(let t of n){let n=gV(t,r[t.fieldName]?.value||null,this.getters.getLocale()),{format:i,value:a}=Wu(t.granularity||`month`).toValueAndFormat(n,e);r[t.nameWithGranularity]={value:n,type:r[t.fieldName]?.type||`empty`,format:r[t.fieldName]?.format,formattedValue:L(a,{locale:e,format:i})}}}return t}};let bV=new g,xV=[`year`,`quarter_number`,`month_number`,`month`,`iso_week_number`,`day_of_month`,`day`,`day_of_week`],SV=[...xV,`hour_number`,`minute_number`,`second_number`];bV.add(`SPREADSHEET`,{ui:yV,definition:rV,dateGranularities:[...xV],isMeasureCandidate:e=>e.type!==`boolean`,datetimeGranularities:[...SV],isGroupable:()=>!0,adaptRanges:(e,t,n)=>{if(t.type!==`SPREADSHEET`||!t.dataSet)return t;let{sheetId:r,zone:i}=t.dataSet,a=e.getRangeFromZone(r,i),o=CV(a,n);if(o===a)return t;let s=o&&{sheetId:o.sheetId,zone:o.zone};return{...t,dataSet:s}}});function CV(e,t){if(!e)return;let n=t(e);switch(n.changeType){case`REMOVE`:return;default:return n.range}}var wV=class extends Xd{pivotId;mutators=[`reset`,`deferUpdates`,`applyUpdate`,`discardPendingUpdate`,`update`];updatesAreDeferred;draft=null;notification=this.get(LO);alreadyNotified=!1;constructor(e,t){super(e),this.pivotId=t,this.updatesAreDeferred=this.getters.getPivotCoreDefinition(this.pivotId).deferUpdates??!1}handle(e){switch(e.type){case`UPDATE_PIVOT`:e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){let e=bV.get(this.pivot.type).definition;return this.draft?new e(this.draft,this.fields,this.getters):this.pivot.definition}get isDirty(){return!!this.draft}get measureFields(){let e=[{name:`__count`,string:E(`Count`),type:`integer`,aggregator:`sum`}],t=this.fields;for(let n in t){let r=t[n];r&&bV.get(this.pivot.type).isMeasureCandidate(r)&&e.push(r)}return e.sort((e,t)=>e.string.localeCompare(t.string))}get unusedGroupableFields(){let e=[],t=this.fields;for(let n in t){let r=t[n];r&&bV.get(this.pivot.type).isGroupable(r)&&e.push(r)}let{columns:n,rows:r,measures:i}=this.definition,a=i.concat(r).concat(n).map(e=>e.fieldName),o=this.unusedGranularities;return e.filter(e=>fd(e)?!a.includes(e.name)||o[e.name].size>0:!a.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get datetimeGranularities(){return bV.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return bV.get(this.pivot.type).dateGranularities}get unusedGranularities(){return this.getUnusedGranularities(this.fields,this.draft??this.getters.getPivotCoreDefinition(this.pivotId))}reset(e){this.pivotId=e,this.updatesAreDeferred=!0,this.draft=null}deferUpdates(e){e===!1&&this.draft?(this.draft.deferUpdates=!1,this.applyUpdate()):this.update({deferUpdates:e}),this.updatesAreDeferred=e}applyUpdate(){if(this.draft&&(this.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&this.isUpdatedPivotVisibleInViewportOnlyAsStaticPivot())){let e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:`info`,text:E(`Pivot updates only work with dynamic pivot tables. Use the formula '%s' or re-insert the static pivot from the Data menu.`,e),sticky:!0})}}discardPendingUpdate(){this.draft=null}update(e){let t=this.getters.getPivotCoreDefinition(this.pivotId),n={...t,...this.draft,...e},r={...n,columns:n.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:n.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:n.measures.map(e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display})),sortedColumn:this.shouldKeepSortedColumn(n)?n.sortedColumn:void 0};if(r.collapsedDomains){let{COL:e,ROW:t}=r.collapsedDomains;r.collapsedDomains={COL:e.filter(e=>this.areDomainFieldsValid(e,r.columns)),ROW:t.filter(e=>this.areDomainFieldsValid(e,r.rows))}}if(!this.draft&&w(t,r))return;let i=this.addDefaultDateTimeGranularity(this.fields,r);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0,t=this.getters.getPivotFormulaId(this.pivotId);for(let n of this.getters.getVisibleCellPositions()){let r=this.getters.getCell(n);if(r?.isFormula){let n=QB(r.compiledFormula.tokens),i=n?.args[0]?.value;if(n&&t===i.toString()){if(n.functionName===`PIVOT`)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){let{columns:n,rows:r}=t,i=b(n),a=b(r),o=this.getUnusedGranularities(e,t);for(let t of i.concat(a)){let n=e[t.fieldName]?.type;if((n===`date`||n===`datetime`)&&!t.granularity){let e=o[t.fieldName]?.values().next().value;o[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:a}}getUnusedGranularities(e,t){let{columns:n,rows:r,measures:i}=t,a=n.concat(r).concat(i).filter(t=>{let n=e[t.fieldName]?.type;return n===`date`||n===`datetime`}),o={};for(let t of a)o[t.fieldName]=new Set(e[t.fieldName]?.type===`date`?this.dateGranularities:this.datetimeGranularities);for(let e of a)o[e.fieldName].delete(e.granularity);return o}shouldKeepSortedColumn(e){let{sortedColumn:t}=e;if(!t)return!0;let n=this.getters.getPivotCoreDefinition(this.pivotId);return e.measures.find(e=>e.id===t.measure)&&w(n.columns,e.columns)}areDomainFieldsValid(e,t){let n=t.map(({fieldName:e,granularity:t})=>e+(t?`:${t}`:``));for(let t=0;t<e.length;t++)if(e[t].field!==n[t])return!1;return!0}},TV=class extends t.Component{static template=`o-spreadsheet-PivotSpreadsheetSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:WB,Section:X,SelectionInput:fk,Checkbox:vk,PivotDeferUpdate:MB,PivotTitleSection:GB};store;state;pivotSidePanelRef=(0,t.useRef)(`pivotSidePanel`);setup(){this.store=Wd(wV,this.props.pivotId),this.state=(0,t.useState)({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return this.store.isDirty&&this.state.rangeHasChanged?!1:this.pivot.isInvalidRange}get ranges(){return this.state.range?[this.state.range]:this.definition.range?[this.env.model.getters.getRangeString(this.definition.range,`forceSheetReference`)]:[]}get pivot(){return this.store.pivot}get definition(){return this.store.definition}getScrollableContainerEl(){return this.pivotSidePanelRef.el}onSelectionChanged(e){this.state.rangeHasChanged=!0,this.state.range=e[0]}onSelectionConfirmed(){if(this.state.range){let e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;let t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){let{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}};let EV=new g;EV.add(`SPREADSHEET`,{editor:TV});var DV=class extends t.Component{static template=`o-spreadsheet-PivotSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:WB,Section:X};setup(){pB(this)}get sidePanelEditor(){let e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw Error(`pivotId does not correspond to a pivot.`);return EV.get(e.type).editor}get highlights(){return AB(this.env.model.getters,this.props.pivotId)}};V`
|
|
1774
1774
|
.o-checkbox-selection {
|
|
1775
1775
|
max-height: 300px;
|
|
1776
1776
|
}
|
|
@@ -1944,13 +1944,13 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
1944
1944
|
background: #e7f2f6;
|
|
1945
1945
|
}
|
|
1946
1946
|
}
|
|
1947
|
-
`;var eH=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:vk};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getExpandedTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(N(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${pd(e,i).join(`,`)})`,value:L(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{let{value:r,format:o}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${pd(e,i).join(`,`)})`,value:L(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}n.push(t)}let r=n[n.length-1];return n[n.length-1]=r.map(e=>(e.isMissing||(e.style=`color: #756f6f;`),e)),n}_buildRowHeaders(e,t){let n=[];for(let r of t.rows){let t=[];for(let e=0;e<r.fields.length;e++)t.push({value:r.fields[e]},{value:r.values[e]});let i=this.pivot.parseArgsToPivotDomain(t),{value:a,format:o}=this.pivot.getPivotHeaderValueAndFormat(i),s=this.env.model.getters.getLocale(),c={formula:`=PIVOT.HEADER(${pd(e,i).join(`,`)})`,value:L(a,{format:o,locale:s}),isMissing:!this.tracker?.isHeaderPresent(i)};r.indent>1&&(c.style=`padding-left: ${r.indent-10}px`),n.push(c)}return n}_buildValues(e,t){let n=[];for(let r of t.columns.at(-1)||[]){let i=[],a=N(r.values[r.values.length-1]);for(let n of t.rows){let t=[];for(let e=0;e<n.fields.length;e++)t.push({value:n.fields[e]},{value:n.values[e]});for(let e=0;e<r.fields.length-1;e++)t.push({value:r.fields[e]},{value:r.values[e]});let o=this.pivot.parseArgsToPivotDomain(t),{value:s,format:c}=this.pivot.getPivotCellValueAndFormat(a,o),l=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${pd(e,o,a).join(`,`)})`,value:L(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},tH=class{static getters=[];history;constructor(e){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}})}exportForExcel(e){}allowDispatch(e){return`Success`}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map(e=>e.call(this,t)).flat()}chainValidations(...e){return t=>{for(let n of e){let e=n.call(this,t);Array.isArray(e)||(e=[e]);let r=e.filter(e=>e!==`Success`);if(r.length)return r}return`Success`}}checkValidations(e,...t){return this.batchValidations(...t)(e)}},nH=class extends tH{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i}){super(t),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=r,this.canDispatch=i}import(e){}export(e){}adaptRanges(e,t,n){}garbageCollectExternalResources(){}},rH=class extends nH{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return`Success`}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>b(e)));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Ue.style,color:e.border.color||Ue.color})}break;case`CLEAR_FORMATTING`:this.clearBorders(e.sheetId,e.target);break;case`REMOVE_COLUMNS_ROWS`:let r=[...e.elements].sort((e,t)=>t-e);for(let t of ft(r))if(e.dimension===`COL`){let n=this.getters.getColsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{let n=this.getters.getRowsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r=this.borders[e]?.[t]?.[n];return r?.top||r?.bottom||r?.left||r?.right?b(r):null}getBordersColors(e){let t=[],n=this.borders[e];if(n){for(let e of n.filter(C))for(let n of e)if(n)for(let e of[`top`,`bottom`,`left`,`right`]){let r=n[e]?.color;r&&t.push(r)}}return t}ensureColumnBorderContinuity(e,t,n){let r=S(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=S(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&w(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(C);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?S(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n){this.borders[e]&&this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfColumn(e,t,n)})}shiftBordersVertically(e,t,n){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfRow(e,t,n)}))}moveBordersOfRow(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getColumnsWithBorders(e).forEach(a=>{let o=i[a]?.[t+n],s=i[a]?.[t];this.history.update(`borders`,e,a,t+n,r?s:s||o),this.history.update(`borders`,e,a,t,void 0)})}moveBordersOfColumn(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getRowsRange(e).forEach(a=>{let o=i[t+n]?.[a],s=i[t]?.[a];this.history.update(`borders`,e,t+n,a,r?s:s||o),r&&this.history.update(`borders`,e,t,a,void 0)})}setBorder(e,t,n,r,i=!0){let a=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;(i||!this.borders[e]?.[t]?.[n]?.left)&&(this.history.update(`borders`,e,t,n,`left`,r?.left),r?.left&&t>0&&!w(this.borders[e]?.[t-1]?.[n]?.right,r?.left)&&this.history.update(`borders`,e,t-1,n,`right`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.top)&&(this.history.update(`borders`,e,t,n,`top`,r?.top),r?.top&&n>0&&!w(this.borders[e]?.[t]?.[n-1]?.bottom,r?.top)&&this.history.update(`borders`,e,t,n-1,`bottom`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.right)&&(this.history.update(`borders`,e,t,n,`right`,r?.right),r?.right&&t<a&&!w(this.borders[e]?.[t+1]?.[n]?.left,r?.right)&&this.history.update(`borders`,e,t+1,n,`left`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.bottom)&&(this.history.update(`borders`,e,t,n,`bottom`,r?.bottom),r?.bottom&&n<o&&!w(this.borders[e]?.[t]?.[n+1]?.top,r?.bottom)&&this.history.update(`borders`,e,t,n+1,`top`,void 0))}clearBorders(e,t,n=!1){let r=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;for(let a of R(t))for(let t=a.top;t<=a.bottom;t++){n&&(a.left>0&&this.history.update(`borders`,e,a.left-1,t,`right`,void 0),a.right<r&&this.history.update(`borders`,e,a.right+1,t,`left`,void 0));for(let r=a.left;r<=a.right;r++)this.history.update(`borders`,e,r,t,void 0),n&&(a.top>0&&this.history.update(`borders`,e,r,a.top-1,`bottom`,void 0),a.bottom<i&&this.history.update(`borders`,e,r,a.bottom+1,`top`,void 0))}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t,!0);for(let i of R(t)){if(n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r,right:r,bottom:r,left:r});if(n===`h`||n===`hv`){if(i.top===i.bottom)continue;for(let t=i.left;t<=i.right;t++){this.addBorder(e,t,i.top,{bottom:r});for(let n=i.top+1;n<i.bottom;n++)this.addBorder(e,t,n,{top:r,bottom:r});this.addBorder(e,t,i.bottom,{top:r})}}if(n===`v`||n===`hv`){if(i.left===i.right)continue;for(let t=i.top;t<=i.bottom;t++){this.addBorder(e,i.left,t,{right:r});for(let n=i.left+1;n<i.right;n++)this.addBorder(e,n,t,{left:r,right:r});this.addBorder(e,i.right,t,{left:r})}}if(n===`left`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right,t,{right:r});if(n===`top`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom,{bottom:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||w(t,e.border)?`NoChanges`:`Success`}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let[n,r]of rc(t.id,t.borders)){let{sheetId:t,col:i,row:a}=n,o=e.borders[r];this.setBorder(t,i,a,o,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,ps(e))}export(e){let t={};for(let n of e.sheets){let e={};for(let r=0;r<n.colNumber;r++)for(let i=0;i<n.rowNumber;i++){let a=this.getCellBorder({sheetId:n.id,col:r,row:i});if(a){let o=tc(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=nc(e)}e.borders=t}exportForExcel(e){this.export(e)}},iH=class extends nH{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellStyle`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges({applyChange:e},t,n){for(let r of Object.keys(this.cells))for(let i of Object.values(this.cells[r]||{}))if(i.isFormula){for(let a of i.compiledFormula.dependencies)if(a.sheetId===t||a.invalidSheetName===n.old){let t=e(a);t.changeType!==`NONE`&&this.history.update(`cells`,r,i.id,`compiledFormula`,`dependencies`,i.compiledFormula.dependencies.indexOf(a),t.range)}}}allowDispatch(e){switch(e.type){case`UPDATE_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case`CLEAR_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case`UPDATE_CELL_POSITION`:return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?`Success`:`InvalidCellId`;default:return`Success`}}handle(e){switch(e.type){case`SET_FORMATTING`:`style`in e&&this.setStyle(e.sheetId,e.target,e.style),`format`in e&&e.format!==void 0&&this.setFormatter(e.sheetId,e.target,e.format);break;case`CLEAR_FORMATTING`:this.clearFormatting(e.sheetId,e.target);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,style:null,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of R(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n=this.getters.getCell({sheetId:e,col:t,row:r});(n?.isFormula||n?.content)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}}setFormatter(e,t,n){for(let r of R(t))for(let t=r.top;t<=r.bottom;t++)for(let i=r.left;i<=r.right;i++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:i,row:t,format:n})}clearFormatting(e,t){for(let n of R(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,style:null,format:``})}clearCells(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:``,style:null,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=S(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=S(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){for(let t of e.sheets){let n=t.id,r=new SP;for(let e in t.cells)if(t.cells[e]){let{col:n,row:i}=Zn(e),a={sheetId:t.id,col:n,row:i};r.set(a,{content:t.cells[e]})}for(let[e,n]of[[`style`,t.styles],[`format`,t.formats]])for(let[i,a]of rc(t.id,n)){let t=r.get(i);t?t[e]=a:r.set(i,{[e]:a})}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format||n?.style){let r=this.importCell(t.id,n?.content,n?.style?e.styles[n?.style]:void 0,n?.format?e.formats[n?.format]:void 0);this.history.update(`cells`,t.id,r.id,r),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:r.id,...i})}}}}export(e){let t={},n={};for(let r of e.sheets){let e=[],i=[],a={},o=Object.keys(this.cells[r.id]||{}).map(e=>this.getters.getCellPosition(e)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let r of o){let o=this.getters.getCell(r),s=T(r.col,r.row),c=this.extractCustomStyle(o);if(Object.keys(c).length){let n=tc(c,t);e[n]??=[],e[n].push(r)}if(o.format){let e=tc(o.format,n);i[e]??=[],i[e].push(r)}o.content&&(a[s]=o.content)}r.styles=nc(e),r.formats=nc(i),r.cells=a}e.styles=t,e.formats=n}importCell(e,t,n,r){let i=this.getNextUid();return this.createCell(i,t||``,r,n,e)}exportForExcel(e){this.export(e);let t=[];for(let n in e.formats||[])Uo(e.formats[n])||(t.push(Number(n)),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.formats){let r=n.formats[e];r&&t.includes(r)&&delete n.formats[e]}}extractCustomStyle(e){let t={...e.style},n=Pi(e.content,D)?Re:Le;for(let r in t)(r!==`align`||!e.isFormula)&&t[r]===n[r]&&delete t[r];return t}getCells(e){return this.cells[e]||{}}getCellById(e){let t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,n,r=!1){if(!n.length)return Ot(t.map(e=>e.value));let i=0;return Ot(t.map(t=>{if(t.type===`REFERENCE`){let t=n[i++];return this.getters.getRangeString(t,e,{useBoundedReference:r})}return t.value}))}getTranslatedCellFormula(e,t,n,r){let i=this.getters.createAdaptedRanges($x(r).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t,n){let r=$x(n).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),i=this.getters.removeRangesSheetPrefix(t,r);return this.getFormulaString(t,n,i)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=T(t.left,t.top,n[0]),i=T(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}setStyle(e,t,n){for(let r of R(t))for(let t=r.left;t<=r.right;t++)for(let i=r.top;i<=r.bottom;i++){let r=this.getters.getCell({sheetId:e,col:t,row:i});this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:i,style:n?{...r?.style,...n}:void 0})}}copyColumnStyle(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowStyle(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:r,row:t,...i})}}getFormat(e,t,n){let r={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.getters.getCell(i);return a&&(a.style&&(r.style=a.style),a.format&&(r.format=a.format)),r}getNextUid(){let e=this.nextId.toString();return this.history.update(`nextId`,this.nextId+1),e}updateCell(e,t,n,r){let i=this.getters.getCell({sheetId:e,col:t,row:n}),a=r.content!==void 0||`formula`in r,o=a?zt(r?.content||void 0):i?.content||``,s;s=r.style===void 0?i?i.style:void 0:r.style||void 0;let c=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||i.content===``))&&!s&&!c){i&&(this.history.update(`cells`,e,i.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let l=i?.id||this.getNextUid(),u=this.createCell(l,o,c,s,e);this.history.update(`cells`,e,u.id,u),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:u.id,col:t,row:n,sheetId:e})}createCell(e,t,n,r,i){return t.startsWith(`=`)?this.createFormulaCell(e,t,n,r,i):this.createLiteralCell(e,t,n,r)}createLiteralCell(e,t,n,r){let i=this.getters.getLocale(),a=Ko(t,i);return n||=typeof a==`number`?Do(t,i)||Oo(t):void 0,!Wo(n)&&!j(t)&&(t=N(a)),{id:e,content:t,style:r,format:n,isFormula:!1,parsedValue:a}}createFormulaCell(e,t,n,r,i){let a=Qx(t);return a.dependencies.length?this.createFormulaCellWithDependencies(e,a,n,r,i):{id:e,content:t,style:r,format:n,isFormula:!0,compiledFormula:{...a,dependencies:[]}}}createFormulaCellWithDependencies(e,t,n,r,i){let a=[];for(let e of t.dependencies)a.push(this.getters.getRangeFromSheetXC(i,e));return new aH(e,t,n,r,a,i,this.getters.getRangeString)}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?ks(n,r,this.getters.getSheetZone(t))?`Success`:`TargetOutOfSheet`:`InvalidSheetId`}checkUselessClearCell(e){let t=this.getters.getCell(e);return!t||!t.content&&!t.style&&!t.format?`NoChanges`:`Success`}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=`format`in e;return(!n||t?.content===e.content)&&(!r||w(t?.style,e.style))&&(!i||t?.format===e.format)?`NoChanges`:`Success`}},aH=class{isFormula=!0;compiledFormula;constructor(e,t,n,r,i,a,o){this.id=e,this.format=n,this.style=r,this.sheetId=a,this.getRangeString=o;let s=0,c=t.tokens.map(e=>e.type===`REFERENCE`?new oH(i,s++,this.sheetId,this.getRangeString):e);this.compiledFormula={...t,dependencies:i,tokens:c}}get content(){return Ot(this.compiledFormula.tokens.map(e=>e.value))}get contentWithFixedReferences(){let e=0;return Ot(this.compiledFormula.tokens.map(t=>{if(t.type===`REFERENCE`){let t=e++;return this.getRangeString(this.compiledFormula.dependencies[t],this.sheetId,{useBoundedReference:!0})}return t.value}))}},oH=class{type=`REFERENCE`;constructor(e,t,n,r){this.ranges=e,this.rangeIndex=t,this.sheetId=n,this.getRangeString=r}get value(){let e=this.ranges[this.rangeIndex];return this.getRangeString(e,this.sheetId)}},sH=class extends nH{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getContextCreationChart`];charts={};createChart=gD(this.getters);validateChartDefinition=e=>vD(this,e.definition);adaptRanges(e){for(let[t,n]of Object.entries(this.charts))this.history.update(`charts`,t,n?.updateRanges(e))}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case`UPDATE_CHART`:return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists,this.checkChartChanged));default:return`Success`}}handle(e){switch(e.type){case`CREATE_CHART`:this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.addChart(e.figureId,e.definition);break;case`UPDATE_CHART`:this.addChart(e.figureId,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`chart`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.charts[n.id]?.duplicateInDuplicatedSheet(e.sheetIdTo);i&&this.dispatch(`CREATE_CHART`,{figureId:r,col:n.col,row:n.row,offset:n.offset,size:{width:n.width,height:n.height},definition:i.getDefinition(),sheetId:e.sheetIdTo})}break}case`DELETE_FIGURE`:this.history.update(`charts`,e.figureId,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){let t=this.charts[e]?.type;if(!t)throw Error(`Chart not defined.`);return t}isChartDefined(e){return e in this.charts&&this.charts!==void 0}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.getDefinition();if(!t)throw Error(`There is no chart with the given figureId: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)e.tag===`chart`&&(this.charts[e.id]=this.createChart(e.id,e.data,t.id))}export(e){if(e.sheets)for(let t of e.sheets){let e=this.getters.getFigures(t.id),n=[];for(let t of e){let e=t;if(e&&e.tag===`chart`){let t=this.charts[e.id]?.getDefinition();t&&(e.data=t,n.push(e))}else n.push(e)}t.figures=n}}addFigure(e,t,n,r,i,a={width:536,height:335}){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`chart`})}addChart(e,t){let n=this.getters.getFigureSheetId(e);n&&this.history.update(`charts`,e,this.createChart(e,t,n))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.figureId)?`DuplicatedChartId`:`Success`}checkChartExists(e){return this.isChartDefined(e.figureId)?`Success`:`ChartDoesNotExist`}checkChartChanged(e){return w(this.getChartDefinition(e.figureId),e.definition)?`NoChanges`:`Success`}};function cH(e){return e===``?NaN:Number(e)}var lH=class extends nH{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};adaptCFFormulas({applyChange:e,adaptFormulaString:t}){for(let n in this.cfRules)for(let r of this.cfRules[n])if(r.rule.type===`DataBarRule`&&r.rule.rangeValues){let t=e(r.rule.rangeValues);switch(t.changeType){case`REMOVE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,t.range);break}}else if(r.rule.type===`CellIsRule`)for(let e=0;e<r.rule.values.length;e++)this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`values`,e,t(n,r.rule.values[e]));else if(r.rule.type===`IconSetRule`)for(let e of[`lowerInflectionPoint`,`upperInflectionPoint`])r.rule[e].type===`formula`&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,r.rule[e].value));else if(r.rule.type===`ColorScaleRule`)for(let e of[`minimum`,`maximum`,`midpoint`]){let i=r.rule[e];i?.type===`formula`&&i?.value&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,i.value))}}adaptCFRanges(e,{applyChange:t}){for(let n of this.cfRules[e])for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}adaptRanges(e,t){let n=t?[t]:Object.keys(this.cfRules);for(let t of n)this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)ks(t,n,e.zone)&&r.push(i);return new Set(r.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,n,r){if(n.length===0&&r.length===0)return;let i=this.getters.getConditionalFormats(e),a=i.findIndex(e=>e.id===t.id),o=[];a>-1&&(o=i[a].ranges.map(fs));let s=R(o,r);return R([...n,...s],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:n}={useBoundedReference:!1}){let r=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:n}));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:n})},ranges:r}:{...t,rule:{...t.rule},ranges:r}}mapToConditionalFormatInternal(e,t){let n=t.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:n}:{...t,rule:{...t.rule},ranges:n}}addConditionalFormatting(e,t){let n=this.cfRules[t].slice(),r=n.findIndex(t=>t.id===e.id),i=this.mapToConditionalFormatInternal(t,e);r>-1?n.splice(r,1,i):n.push(i),this.history.update(`cfRules`,t,n)}checkValidPriorityChange(e,t,n){if(!this.cfRules[n])return`InvalidSheetId`;let r=this.cfRules[n].findIndex(t=>t.id===e);if(r===-1)return`InvalidConditionalFormatId`;let i=r-t;return i<0||i>=this.cfRules[n].length?`InvalidConditionalFormatId`:`Success`}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}checkCFRule(e){let t=e.cf.rule;switch(t.type){case`CellIsRule`:return wr.has(t.operator)?this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues):`InvalidConditionalFormatType`;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return`Success`}return`InvalidConditionalFormatType`}checkCFHasChanged(e){let t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))}),n=this.cfRules[e.sheetId]?.find(t=>t.id===e.cf.id);return n&&w(t,n)?`NoChanges`:`Success`}checkOperatorArgsNumber(e){let t=Y.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(t===void 0||t>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);let n=[],r=e=>e===void 0||e===``;return t>=1&&r(e.values[0])&&n.push(`FirstArgMissing`),t>=2&&r(e.values[1])&&n.push(`SecondArgMissing`),n.length?n:`Success`}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return`MinNaN`;case`max`:return`MaxNaN`;case`mid`:return`MidNaN`;case`upperInflectionPoint`:return`ValueUpperInflectionNaN`;case`lowerInflectionPoint`:return`ValueLowerInflectionNaN`}return`Success`}checkFormulaCompilation(e,t){if(e.type!==`formula`)return`Success`;if(Qx(e.value||``).isBadExpression)switch(t){case`min`:return`MinInvalidFormula`;case`max`:return`MaxInvalidFormula`;case`mid`:return`MidInvalidFormula`;case`upperInflectionPoint`:return`ValueUpperInvalidFormula`;case`lowerInflectionPoint`:return`ValueLowerInvalidFormula`}return`Success`}checkThresholds(e){return this.batchValidations(t=>e(t.minimum,`min`),t=>e(t.maximum,`max`),t=>t.midpoint?e(t.midpoint,`mid`):`Success`)}checkInflectionPoints(e){return this.batchValidations(t=>e(t.lowerInflectionPoint,`lowerInflectionPoint`),t=>e(t.upperInflectionPoint,`upperInflectionPoint`))}checkLowerBiggerThanUpper(e){let t=e.lowerInflectionPoint.value,n=e.upperInflectionPoint.value;return[`number`,`percentage`,`percentile`].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(n)?`LowerBiggerThanUpper`:`Success`}checkMinBiggerThanMax(e){let t=e.minimum.value,n=e.maximum.value;return[`number`,`percentage`,`percentile`].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&cH(t)>=cH(n)?`MinBiggerThanMax`:`Success`}checkMidBiggerThanMax(e){let t=e.midpoint?.value,n=e.maximum.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&cH(t)>=cH(n)?`MidBiggerThanMax`:`Success`}checkMinBiggerThanMid(e){let t=e.minimum.value,n=e.midpoint?.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&cH(t)>=cH(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&Qx(t||``).isBadExpression)return`ValueCellIsInvalidFormula`;return`Success`}removeConditionalFormatting(e,t){let n=this.cfRules[t].findIndex(t=>t.id===e);if(n!==-1){let e=this.cfRules[t].slice();e.splice(n,1),this.history.update(`cfRules`,t,e)}}changeCFPriority(e,t,n){let r=this.cfRules[n].findIndex(t=>t.id===e),i=this.cfRules[n][r],a=r-t,o=[...this.cfRules[n]];o.splice(r,1),o.splice(a,0,i),this.history.update(`cfRules`,n,o)}},uH=class extends nH{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e,t){this.adaptDVRanges(t,e),this.adaptDVFormulas(e)}adaptDVFormulas({adaptFormulaString:e}){for(let t in this.rules){let n=this.rules[t];for(let r=n.length-1;r>=0;r--){let n=this.rules[t][r];for(let i=0;i<n.criterion.values.length;i++){let a=e(t,n.criterion.values[i]);this.history.update(`rules`,t,r,`criterion`,`values`,i,a)}}}}adaptDVRanges(e,{applyChange:t}){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return!this.getters.tryGetSheet(e.sheetId)||e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid));case`REMOVE_DATA_VALIDATION_RULE`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;if(!this.rules[e.sheetId].find(t=>t.id===e.id))return`UnknownDataValidationRule`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=b(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>Ec(e.sheetId,e.sheetIdTo,t))}));this.history.update(`rules`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.rules};delete t[e.sheetId],this.history.update(`rules`,t);break}case`REMOVE_DATA_VALIDATION_RULE`:this.removeDataValidationRule(e.sheetId,e.id);break;case`ADD_DATA_VALIDATION_RULE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case`DELETE_CONTENT`:{let t=R(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(e&&(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!this.getters.getCell({sheetId:n,col:r,row:t})?.content)){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,T(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(ks(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&(t.criterion.displayStyle===`arrow`||t.criterion.displayStyle===`chip`):!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=b(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of Oc(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:e?.style?.align??`center`,verticalAlign:e?.style?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...b(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return Y.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=Y.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=Y.get(t.type);return t.values.some(e=>n.allowedValues===`onlyFormulas`&&!e.startsWith(`=`)?!0:e.startsWith(`=`)?n.allowedValues===`onlyLiterals`||Qx(e).isBadExpression:!n.isCriterionValueValid(e))?`InvalidDataValidationCriterionValue`:`Success`}checkValidRange(e){return e.ranges.map(e=>this.getters.getRangeFromRangeData(e)).map(t=>this.getters.getRangeString(t,e.sheetId)).some(e=>!this.getters.isRangeValid(e))?`InvalidRange`:`Success`}},dH=class extends nH{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];adaptRanges({applyChange:e},t){for(let n of this.getFigures(t)){let r=e(this.getters.getRangeFromZone(t,{left:n.col,right:n.col,top:n.row,bottom:n.row}));if(r.changeType===`MOVE`)this.history.update(`figures`,t,n.id,`col`,r.range.zone.right),this.history.update(`figures`,t,n.id,`row`,r.range.zone.bottom);else if(r.changeType===`REMOVE`){let r=e(this.getters.getRangeFromZone(t,{left:0,right:n.col-1,top:0,bottom:n.row-1})),{offset:i,col:a,row:o}=n;r.changeType!==`NONE`&&(a=r.range.zone.right+1,o=r.range.zone.bottom+1),{offset:i,col:a,row:o}=this.getPositionInSheet(t,{...n,col:a,row:o}),this.history.update(`figures`,t,n.id,`offset`,i),this.history.update(`figures`,t,n.id,`col`,a),this.history.update(`figures`,t,n.id,`row`,o)}}}allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case`UPDATE_FIGURE`:return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case`DELETE_FIGURE`:return this.checkFigureExists(e);default:return`Success`}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{figureId:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:let t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case`UPDATE_FIGURE`:this.updateFigure(e);break;case`DELETE_FIGURE`:this.removeFigure(e.figureId,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break}}onColRemove(e){let t=this.getters.getNumberCols(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+this.getters.getColSize(e,r);for(let t of this.getFigures(e))if(t.offset.x+t.width>n[t.col]){let r=t.offset.x,i=t.col;for(r=Math.min(r,n[i]-t.width);r<0&&i>0;)i--,r=n[i]-t.width;r!==t.offset.x&&this.history.update(`figures`,e,t.id,`offset`,{x:Math.max(r,0),y:t.offset.y}),i!==t.col&&this.history.update(`figures`,e,t.id,`col`,i)}}onRowRemove(e){let t=this.getters.getNumberRows(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+(this.getters.getUserRowSize(e,r)??23);for(let t of this.getFigures(e))if(t.offset.y+t.height>n[t.row]){let r=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??23;t<r;t=this.getters.getUserRowSize(e,i)??23)i+=1,r-=t;for(r=Math.min(r,n[i]-t.height);r<0&&i>0;)i--,r=n[i]-t.height;r!==t.offset.y&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(0,r)}),i!==t.row&&this.history.update(`figures`,e,t.id,`row`,i)}else t.offset.y+t.height>n[0]&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(n[0]-t.height,0)})}getPositionInSheet(e,t){let{numberOfRows:n,numberOfCols:r}=this.getters.getSheetSize(e),i=0,a=0,o,s,{col:c,row:l}=t,u={...t.offset};for(o=n;i<t.height&&o>0;o--)i+=this.getters.getUserRowSize(e,o-1)??23;for(l>o?(l=o,u.y=Math.max(i-t.height,0)):l===o&&(u.y=x(u.y,0,Math.max(i-t.height,0))),s=r;a<t.width&&s>0;s--)a+=this.getters.getColSize(e,s-1);return c>s?(c=s,u.x=Math.max(a-t.width,0)):s===c&&(u.x=x(u.x,0,Math.max(a-t.width,0))),{col:c,row:l,offset:u}}updateFigure(e){if(!(`figureId`in e)||!(`sheetId`in e))return;let{figureId:t,sheetId:n,...r}=e,i={...this.getFigure(n,t),...r};for(let[e,t]of Object.entries(r))switch(e){case`offset`:this.history.update(`figures`,n,i.id,e,t);break;case`col`:case`row`:case`width`:case`height`:t!==void 0&&this.history.update(`figures`,n,i.id,e,t);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e){return this.figures[e.sheetId]?.[e.figureId]===void 0?`FigureDoesNotExist`:`Success`}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e.figureId])?`DuplicatedFigureId`:`Success`}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?`WrongSheetPosition`:`Success`}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){return this.export(e)}},fH=class extends nH{static getters=[`getUserRowSize`,`getColSize`];sizes={};handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`sizes`,e.sheetId,{COL:Array(this.getters.getNumberCols(e.sheetId)).fill(void 0),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(void 0)});break;case`DUPLICATE_SHEET`:this.history.update(`sizes`,e.sheetIdTo,b(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ht(t,e.elements);this.history.update(`sizes`,e.sheetId,e.dimension,n);break}case`ADD_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=jt(e.position,e.base),r=t[e.base],i=Ut(t,Array(e.quantity).fill(r),n);this.history.update(`sizes`,e.sheetId,e.dimension,i);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of S(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of S(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},pH=class extends nH{static getters=[`checkElementsIncludeAllVisibleHeaders`,`getHiddenColsGroups`,`getHiddenRowsGroups`,`isHeaderHiddenByUser`,`isRowHiddenByUser`,`isColHiddenByUser`];hiddenHeaders={};allowDispatch(e){switch(e.type){case`HIDE_COLUMNS_ROWS`:{if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=e.dimension===`COL`?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),n=e.dimension===`COL`?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=n?`TooManyHiddenElements`:Yt(e.elements)<0||Jt(e.elements)>n?`InvalidHeaderIndex`:`Success`}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`:`InvalidSheetId`}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,b(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=jt(e.position,e.base),n=Ut([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,n);break}case`HIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!0);break;case`UNHIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!1);break}}checkElementsIncludeAllVisibleHeaders(e,t,n){return Nt(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=S(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...S(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},mH=class extends nH{static getters=[`getImage`,`getImagePath`,`getImageSize`];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){switch(e.type){case`CREATE_IMAGE`:return this.getters.getFigure(e.sheetId,e.figureId)?`InvalidFigureId`:`Success`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_IMAGE`:this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:b(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}garbageCollectExternalResources(){let e=new Set(this.getAllImages().map(e=>e.path));for(let t of this.syncedImages)e.has(t)||this.fileStore?.delete(t)}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,n,r,i,a){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`image`})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:b(e)})}t.images=[...t.images,...n]}}getAllImages(){let e=[];for(let t in this.images)e.push(...Object.values(this.images[t]||{}).filter(C));return e}},hH=class extends nH{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`getSelectionRangeString`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(C))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e,t){this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(C)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(C)}getSelectionRangeString(e,t){let n=this.getters.expandZone(e.sheetId,e.zone),r=bc({...e,zone:{...n,bottom:Cc(e)?void 0:n.bottom,right:wc(e)?void 0:n.right}},this.getters.getSheetSize),i=this.getters.getRangeString(r,t);if(this.isSingleCellOrMerge(e.sheetId,e.zone)){let{sheetName:e,xc:t}=vc(i);return yc(e,t.split(`:`)[0])}return i}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(Ds(t,n))return!0;return!1}doesColumnsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(r.id,t,i,n,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(r.id,i,t,i,n))return!0;return!1}expandZone(e,t){let{left:n,right:r,top:i,bottom:a}=t,o={left:n,right:r,top:i,bottom:a};for(let t in this.merges[e]){let n=this.getMergeById(e,parseInt(t));n&&Ds(n,o)&&(o=Cs(n,o))}return Es(o,t)?o:this.expandZone(e,o)}isInSameMerge(e,t,n,r,i){let a=this.getMerge({sheetId:e,col:t,row:n}),o=this.getMerge({sheetId:e,col:r,row:i});return!a||!o?!1:Es(a,o)}isInMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e];return r?t in r&&!!r[t]?.[n]:!1}getMainCellPosition(e){let t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){let n=this.getters.getHiddenColsGroups(e),r=this.getters.getHiddenRowsGroups(e);for(let e of n)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of r)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){let n=this.getMerge({sheetId:e,col:t.left,row:t.top});if(n)return Es(t,n);let{numberOfCols:r,numberOfRows:i}=js(t);return r===1&&i===1}isMainCellPosition(e){return w(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=x(r,0,this.getters.getNumberCols(e)-1),a=x(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&n.content!==``)return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:_H(t,n)}checkDestructiveMerge({sheetId:e,target:t}){return this.getters.tryGetSheet(e)&&t.some(t=>this.isMergeDestructive(e,t))?`MergeIsDestructive`:`Success`}checkOverlap({target:e}){for(let t of e)for(let n of e)if(t!==n&&Ds(t,n))return`MergeOverlap`;return`Success`}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return`Success`;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);return Ks(t,n,r)?`FrozenPaneOverlap`:`Success`}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return`Success`;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?`Success`:`CellIsMerged`}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!Es(e,i))return`InvalidTarget`}return`Success`}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=x(r,0,this.getters.getNumberCols(e)-1),a=x(a,0,this.getters.getNumberRows(e)-1),T(n,i)===T(r,a))return;let o=this.getters.getCell({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,vs({left:n,top:i,right:r,bottom:a})));let c=new Set;for(let t=i;t<=a;t++)for(let a=n;a<=r;a++){(a!==n||t!==i)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:t,style:o?o.style:null,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&c.add(r.id),this.history.update(`mergeCellMap`,e,a,t,s)}for(let t of c){let{top:n,bottom:r,left:i,right:a}=this.getMergeById(e,t);for(let t=n;t<=r;t++)for(let n=i;n<=a;n++){let r={sheetId:e,col:n,row:t},i=this.getMerge(r);(!i||i.id!==s)&&(this.history.update(`mergeCellMap`,e,n,t,void 0),this.dispatch(`CLEAR_CELL`,r))}this.history.update(`merges`,e,t,void 0)}}removeMerge(e,t){let{left:n,top:r,bottom:i,right:a}=t,o=this.getMerge({sheetId:e,col:n,row:r});if(!(o===void 0||!Es(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,{applyChange:t}){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=js(a.range.zone);t===1&&i===1?this.removeMerge(e,n):this.history.update(`merges`,e,parseInt(r,10),a.range);break}}this.history.update(`mergeCellMap`,e,{});for(let t of this.getMerges(e))for(let{col:n,row:r}of Fs(t))this.history.update(`mergeCellMap`,e,n,r,t.id)}import(e){let t=e.sheets||[];for(let e of t)this.history.update(`merges`,e.id,{}),this.history.update(`mergeCellMap`,e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let n of t)this.addMerge(e,ps(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...gH(e))}}exportForExcel(e){this.export(e)}};function gH(e){return Object.entries(e).map(([e,t])=>t?_H(parseInt(e,10),t):void 0).filter(C).map(e=>T(e.left,e.top)+`:`+T(e.right,e.bottom))}function _H(e,t){return{...t.zone,id:e}}var vH=class{getters;providers=[];isAdaptingRanges=!1;constructor(e){this.getters=e}static getters=[`copyFormulaStringForSheet`,`extendRange`,`getRangeString`,`getRangeFromSheetXC`,`createAdaptedRanges`,`getRangeData`,`getRangeDataFromXc`,`getRangeDataFromZone`,`getRangeFromRangeData`,`getRangeFromZone`,`getRangesUnion`,`recomputeRanges`,`isRangeValid`,`removeRangesSheetPrefix`];allowDispatch(e){return e.type===`MOVE_RANGES`?e.target.length===1?`Success`:`InvalidZones`:`Success`}beforeHandle(e){}handle(e){if(this.isAdaptingRanges)throw Error(`Plugins cannot dispatch commands during adaptRanges phase`);let t=jc(e);t&&this.executeOnAllRanges(t)}finalize(){}verifyRangeRemoved(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!gs(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}executeOnAllRanges(e){this.isAdaptingRanges=!0;let t={applyChange:this.verifyRangeRemoved(e.applyChange),adaptRangeString:(t,n)=>uS(t,n,e),adaptFormulaString:(t,n)=>lS(t,n,e)};for(let n of this.providers)n(t,e.sheetId,e.sheetName);this.isAdaptingRanges=!1}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,n,r){return e.map(e=>{if(!gs(e.zone))return e;let i=e.prefixSheet?e.sheetId:r,a=wc(e),o=Cc(e),s={...e.unboundedZone,left:a&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:a?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:o&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:n),bottom:o?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:n)};return Ac(bc({...e,sheetId:i,zone:s},this.getters.getSheetSize))})}removeRangesSheetPrefix(e,t){return t.map(t=>t.prefixSheet&&t.sheetId===e?{...t,prefixSheet:!1}:t)}extendRange(e,t,n){let r=t===`COL`?e.zone.right+n:e.zone.right,i=t===`ROW`?e.zone.bottom+n:e.zone.bottom,a={left:e.zone.left,top:e.zone.top,right:wc(e)?void 0:r,bottom:Cc(e)?void 0:i};return bc({...e,zone:a},this.getters.getSheetSize)}getRangeFromSheetXC(e,t){if(!fc.test(t)||!this.getters.tryGetSheet(e))return Sc(t);let{sheetName:n}=vc(t);return xc({xc:t,sheetId:this.getters.getSheetIdByName(n)||e,invalidSheetName:n&&!this.getters.getSheetIdByName(n)?n:void 0},this.getters.getSheetSize)}getRangeString(e,t,n={useBoundedReference:!1,useFixedReference:!1}){return e?e.invalidXc?e.invalidXc:this.getters.tryGetSheet(e.sheetId)?Tc(e,t,this.getters.getSheetName,n):k.InvalidReference:k.InvalidReference}getRangeDataFromXc(e,t){let n=this.getters.getRangeFromSheetXC(e,t);return this.getRangeDataFromZone(n.sheetId,n.unboundedZone)}getRangeDataFromZone(e,t){return t=this.getters.getUnboundedZone(e,t),{_sheetId:e,_zone:t}}getRangeData(e){return this.getRangeDataFromZone(e.sheetId,e.unboundedZone)}getRangeFromZone(e,t){return bc({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){return R(e.map(e=>e.unboundedZone),t.map(e=>e.unboundedZone)).map(t=>this.getRangeFromZone(e[0].sheetId,t))}getRangeFromRangeData(e){return this.getters.tryGetSheet(e._sheetId)?bc({prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]},this.getters.getSheetSize):Sc(k.InvalidReference)}isRangeValid(e){if(!e)return!1;let{xc:t,sheetName:n}=vc(e);return t.match(fc)!==null&&(!n||this.getters.getSheetIdByName(n)!==void 0)}getRangesUnion(e){let t=ws(...e.map(e=>e.unboundedZone));return this.getRangeFromZone(e[0].sheetId,t)}copyFormulaStringForSheet(e,t,n,r){if(!n.startsWith(`=`))return n;let i=Qx(n),a=i.dependencies.map(n=>{let i=this.getters.getRangeFromSheetXC(e,n);return r===`keepSameReference`?i:Ec(e,t,i)});return this.getters.getFormulaString(t,i.tokens,a)}},yH=class extends nH{static getters=`getSheetName.tryGetSheetName.getSheet.tryGetSheet.getSheetIdByName.getSheetIds.getVisibleSheetIds.isSheetVisible.doesHeaderExist.doesHeadersExist.getCell.getCellPosition.getColsZone.getRowCells.getRowsZone.getNumberCols.getNumberRows.getNumberHeaders.getGridLinesVisibility.getNextSheetName.getSheetSize.getSheetZone.getPaneDivisions.checkZonesExistInSheet.getCommandZones.getUnboundedZone.checkElementsIncludeAllNonFrozenHeaders.getDuplicateSheetName`.split(`.`);sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){let t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if(t!==`Success`)return t;switch(e.type){case`HIDE_SHEET`:return this.getVisibleSheetIds().length===1?`NotEnoughSheets`:`Success`;case`CREATE_SHEET`:return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case`DUPLICATE_SHEET`:return this.sheets[e.sheetIdTo]?`DuplicatedSheetId`:this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?`DuplicatedSheetName`:`Success`;case`MOVE_SHEET`:try{let t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),`Success`}catch{return`WrongSheetMove`}case`RENAME_SHEET`:return this.isRenameAllowed(e);case`COLOR_SHEET`:return!e.color||cn(e.color)?`Success`:`InvalidColor`;case`DELETE_SHEET`:return this.getVisibleSheetIds().length>1?`Success`:`NotEnoughSheets`;case`ADD_COLUMNS_ROWS`:return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?`InvalidQuantity`:`Success`:`InvalidHeaderIndex`;case`REMOVE_COLUMNS_ROWS`:{let t=Yt(e.elements),n=Jt(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,n)?`InvalidHeaderIndex`:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`}case`FREEZE_ROWS`:return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case`FREEZE_COLUMNS`:return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return`Success`}}handle(e){switch(e.type){case`SET_GRID_LINES_VISIBILITY`:this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case`CREATE_SHEET`:let t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update(`sheetIdsMapName`,t.name,t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.newName);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case`UPDATE_CELL_POSITION`:this.updateCellPosition(e);break;case`FREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,e.quantity,`COL`);break;case`FREEZE_ROWS`:this.setPaneDivisions(e.sheetId,e.quantity,`ROW`);break;case`UNFREEZE_ROWS`:this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`UNFREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,0,`COL`);break;case`UNFREEZE_COLUMNS_ROWS`:this.setPaneDivisions(e.sheetId,0,`COL`),this.setPaneDivisions(e.sheetId,0,`ROW`)}}import(e){for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let t of e.sheets){let e=t.name||`Sheet`+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:Hc(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(C).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e){let t=ct(e);for(let e in this.sheetIdsMapName)if(qc(e,t))return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(C)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return Gc(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(t.bottom===void 0||t.right===void 0)return t;let n=t.left===0&&t.right===this.getNumberCols(e)-1,r=t.top===0&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:r?void 0:t.bottom,right:n&&!r?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,n){let r={...this.getPaneDivisions(e)};n===`COL`?r.xSplit=t:n===`ROW`&&(r.ySplit=t),this.history.update(`sheets`,e,`panes`,r)}checkElementsIncludeAllNonFrozenHeaders(e,t,n){let r=this.getters.getPaneDivisions(e),i=t===`ROW`?r.ySplit:r.xSplit,a=this.getters.getNumberHeaders(e,t);return i?Nt(n,S(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&e.col!==void 0&&`row`in e&&e.row!==void 0&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(gs))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>As(e,n))?`Success`:`TargetOutOfSheet`}return`Success`}updateCellPosition(e){let{sheetId:t,cellId:n,col:r,row:i}=e;n?this.setNewPosition(n,t,r,i):this.clearPosition(t,r,i)}setNewPosition(e,t,n,r){let i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update(`cellPosition`,e,{row:r,col:n,sheetId:t}),this.history.update(`sheets`,t,`rows`,r,`cells`,n,e)}clearPosition(e,t,n){let r=this.sheets[e]?.rows[n].cells[t];r&&(this.history.update(`cellPosition`,r,void 0),this.history.update(`sheets`,e,`rows`,n,`cells`,t,void 0))}setGridLinesVisibility(e,t){this.history.update(`sheets`,e,`areGridLinesVisible`,t)}createSheet(e,t,n,r,i){let a={id:e,name:t,numberOfCols:n,rows:Hc(r),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},o=this.orderedSheetIds.slice();o.splice(i,0,a.id);let s=this.sheets;return this.history.update(`orderedSheetIds`,o),this.history.update(`sheets`,Object.assign({},s,{[a.id]:a})),a}moveSheet(e,t){let n=this.orderedSheetIds.slice(),r=n.findIndex(t=>t===e),i=n.splice(r,1),a=this.findIndexOfTargetSheet(r,t);n.splice(a,0,i[0]),this.history.update(`orderedSheetIds`,n)}findIndexOfTargetSheet(e,t){for(;t!==0&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(t===0)return e;throw Error(`There is not enough visible sheets`)}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId),n=e.type===`RENAME_SHEET`?e.newName:e.name;if(t!==void 0&&n===t)return`UnchangedSheetName`;let{orderedSheetIds:r,sheets:i}=this,a=n&&n.trim().toLowerCase();return r.find(t=>qc(i[t]?.name,a)&&t!==e.sheetId)?`DuplicatedSheetName`:Xe.test(a)?`ForbiddenCharactersInSheetName`:`Success`}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?`WrongSheetPosition`:`Success`}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return`MergeOverlap`;return`Success`}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return`MergeOverlap`;return`Success`}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):`MissingSheetName`}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[n],r[t]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=b(this.getSheet(e));r.id=t,r.name=n;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{col:e,row:n}=this.getCellPosition(t.id);this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:e,row:n,content:t.content,format:t.format,style:t.style})}let o=Object.assign({},this.sheetIdsMapName);o[r.name]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return Kc(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){let t=e.name,n=Object.assign({},this.sheets);delete n[e.id],this.history.update(`sheets`,n);let r=this.orderedSheetIds.slice(),i=r.indexOf(e.id);r.splice(i,1),this.history.update(`orderedSheetIds`,r);let a=Object.assign({},this.sheetIdsMapName);delete a[t],this.history.update(`sheetIdsMapName`,a)}removeColumns(e,t){t.sort((e,t)=>t-e);for(let n of t)this.moveCellOnColumnsDeletion(e,n);let n=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,n-t.length);let r=t.filter(t=>t<e.panes.xSplit).length;r&&this.setPaneDivisions(e.id,e.panes.xSplit-r,`COL`)}removeRows(e,t){t.sort((e,t)=>t-e);for(let n of ft(t)){let t=n[n.length-1],r=n[0];this.moveCellOnRowsDeletion(e,t,r),this.updateRowsStructureOnDeletion(e,t,r)}let n=t.filter(t=>t<e.panes.ySplit).length;n&&this.setPaneDivisions(e.id,e.panes.ySplit-n,`ROW`)}addColumns(e,t,n,r){let i=n===`before`?t:t+1;this.moveCellsOnAddition(e,i,r,`columns`);let a=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,a+r),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+r,`COL`)}addRows(e,t,n,r){let i=n===`before`?t:t+1;this.addEmptyRows(e,r),this.moveCellsOnAddition(e,i,r,`rows`),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+r,`ROW`)}moveCellOnColumnsDeletion(e,t){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let n=0;n<e.rows.length;n++){let r=e.rows[n];for(let i in r.cells){let a=Number(i),o=r.cells[i];o&&a>t&&this.setNewPosition(o,e.id,a-1,n)}}}moveCellsOnAddition(e,t,n,r){let i=[];for(let a=0;a<e.rows.length;a++){let o=e.rows[a];if(r!==`rows`||a>=t)for(let s in o.cells){let c=Number(s),l=o.cells[s];l&&(r===`rows`||c>=t)&&i.push({sheetId:e.id,cellId:l,col:c+(r===`columns`?n:0),row:a+(r===`rows`?n:0),type:`UPDATE_CELL_POSITION`})}}for(let e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,n){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:n}]});let r=n-t+1;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(t>n)for(let n in i.cells){let a=Number(n),o=i.cells[n];o&&this.setNewPosition(o,e.id,a,t-r)}}}updateRowsStructureOnDeletion(e,t,n){let r=[],i=e.rows.map(e=>e.cells).reverse();for(let a in e.rows){let e=Number(a);e>=t&&e<=n||r.push({cells:i.pop()})}this.history.update(`sheets`,e.id,`rows`,r)}addEmptyRows(e,t){let n=e.rows.slice();for(let e=0;e<t;e++)n.push({cells:{}});this.history.update(`sheets`,e.id,`rows`,n)}getImportedSheetSize(e){let t=Object.keys(e.cells).map(Zn),n=e.rowNumber,r=e.colNumber;for(let{col:e,row:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?`InvalidSheetId`:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?`DuplicatedSheetId`:`Success`}checkZonesAreInSheet(e){return`sheetId`in e?`ranges`in e&&e.ranges.some(e=>e._sheetId!==``&&!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},bH=class extends nH{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};nextTableId=1;adaptRanges({applyChange:e},t){for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return`InvalidSheetId`;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return Js(t)?this.checkValidations(e,e=>this.getTablesOverlappingZones(e.sheetId,t).length?`TableOverlap`:`Success`,e=>this.checkTableConfigUpdateIsValid(e.config)):`NonContinuousTargets`;case`UPDATE_TABLE`:return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,e=>this.checkTableConfigUpdateIsValid(e.config)):`TableNotFound`;case`ADD_MERGE`:for(let t of this.getCoreTables(e.sheetId)){let n=t.range.zone;for(let t of e.target)if(Ds(n,t))return`MergeInTable`}break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{});break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.consumeNextId(),a=e.config||Rk,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!Ts(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t);break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>As(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(C):[]}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>ks(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>Ds(e.range.zone,t)))}extendTableDown(e,t){let n=this.getters.extendRange(t.range,`ROW`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}extendTableRight(e,t){let n=this.getters.extendRange(t.range,`COL`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:n,row:r},i){if(!e)return`none`;let a=i.range.zone,o=`none`;if(a.bottom+1===r&&n>=a.left&&n<=a.right?o=`down`:a.right+1===n&&r>=a.top&&r<=a.bottom&&(o=`right`),o===`none`)return`none`;let s=o===`down`?{...a,bottom:a.bottom+1,top:a.bottom+1}:{...a,right:a.right+1,left:a.right+1};for(let e=s.top;e<=s.bottom;e++)for(let n=s.left;n<=s.right;n++){let r={sheetId:t,col:n,row:e};if(this.getters.getCell(r)?.content||this.getters.isInMerge(r)||this.getTablesOverlappingZones(t,[z(r)]).length)return`none`}return o}getCoreTableMatchingTopLeft(e,t){for(let n of this.getCoreTables(e)){let e=n.range.zone;if(e.left===t.left&&e.top===t.top)return n}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return`Success`;let t=this.getters.getRangeFromRangeData(e.newTableRange).zone,n=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if(n!==`Success`)return n;let r=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);return r?this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==r.id).length?`TableOverlap`:`Success`:`TableNotFound`}checkTableConfigUpdateIsValid(e){return e&&(e.numberOfHeaders!==void 0&&e.numberOfHeaders<0||e.hasFilters&&e.numberOfHeaders===0)?`InvalidTableConfig`:`Success`}createStaticTable(e,t,n,r,i){let a=n.zone;if(!i){i=[];for(let e of S(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.consumeNextId();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=Vs(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of S(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.consumeNextId();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,Vs(t.zone)):e.range,i=n||e.config;return{...e,range:r,config:i}}updateTableConfig(e,t){if(!e)return t;let n={...t,...e};return e.numberOfHeaders===0?n.hasFilters=!1:e.hasFilters===!0&&(n.numberOfHeaders||=1),n}createFilterFromZone(e,t,n,r){return tF(e,this.getters.getRangeFromZone(t,n),r,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone),r=t.filters.map(n=>{let r=this.getters.getRangeFromZone(e,n.rangeWithHeaders.zone);return tF(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:b(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:b(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=tF(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<js(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.consumeNextId(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}consumeNextId(){let e=`${this.nextTableId}`;return this.history.update(`nextTableId`,this.nextTableId+1),e}import(e){for(let t of e.sheets)for(let e of t.tables||[]){let n=this.consumeNextId(),r=e.config||Rk,i=this.getters.getRangeFromSheetXC(t.id,e.range),a=e.type||`static`,o=a===`dynamic`?this.createDynamicTable(n,i,r):this.createStaticTable(n,a,i,r);this.history.update(`tables`,t.id,o.id,o)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:vs(e.range.zone),type:e.type};w(e.config,Rk)||(n.config=e.config),t.tables.push(n)}}exportForExcel(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n=vs(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},xH=class extends nH{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return`HeaderGroupAlreadyExists`;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return`UnknownHeaderGroup`;if(S(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return`NotEnoughElements`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=b(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=jt(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&S(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Bt([t.end,e]))t.end++;else{let t={start:e,end:e};s[n].push(t)}}}for(let e of s)for(let t of e)t.isFolded=i[this.getGroupId(t)];return s}groupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}unGroupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,-1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}moveGroupsOnHeaderInsertion(e,t,n,r){let i=this.groups[e][t];for(let a=0;a<i.length;a++){let o=i[a],[s,c]=Uc(n,r,[o.start,o.end]);(s!==o.start||c!==o.end)&&this.history.update(`groups`,e,t,a,{...o,start:s,end:c})}}moveGroupsOnHeaderDeletion(e,t,n){let r=this.getHeaderGroups(e,t),i=[];for(let e of r){let t=Wc(n,S(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=OA(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=OA(t,e,n.end+1);r.collapsed=!0}}}}}},SH=class extends nH{static getters=[`getPivotCoreDefinition`,`getPivotDisplayName`,`getPivotId`,`getPivotFormulaId`,`getPivotIds`,`getMeasureCompiledFormula`,`getPivotName`,`isExistingPivot`,`getMeasureFullDependencies`];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case`ADD_PIVOT`:return this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?w(e.pivot,this.pivots[e.pivotId]?.definition)?`NoChanges`:e.pivot.name===``?`EmptyName`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures):`PivotIdNotFound`;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;if(e.name===``)return`EmptyName`;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;break;case`DUPLICATE_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`}return`Success`}handle(e){switch(e.type){case`ADD_PIVOT`:{let{pivotId:t,pivot:n}=e;this.addPivot(t,n);break}case`INSERT_PIVOT`:{let{sheetId:t,col:n,row:r,pivotId:i,table:a}=e,o={sheetId:t,col:n,row:r},{cols:s,rows:c,measures:l,fieldsType:u}=a,d=new iV(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=b(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,b(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break}}adaptRanges({applyChange:e,adaptFormulaString:t}){for(let t in this.pivots){let n=b(this.pivots[t]?.definition);if(!n)continue;let r=bV.get(n.type)?.adaptRanges?.(this.getters,n,e);r&&!w(n,r)&&this.history.update(`pivots`,t,`definition`,r)}for(let n in this.compiledMeasureFormulas)for(let r in this.compiledMeasureFormulas[n]){let i=this.pivots[n]?.definition.measures.find(e=>e.id===r);if(!i||!i.computedBy)continue;let a=i.computedBy.sheetId,{formula:o,dependencies:s}=this.compiledMeasureFormulas[n][r];this.history.update(`compiledMeasureFormulas`,n,r,`formula`,`dependencies`,o.dependencies.map(t=>e(t).range)),this.history.update(`compiledMeasureFormulas`,n,i.id,`dependencies`,s.map(t=>e(t).range));let c=i.computedBy.formula,l=t(a,c);l!==c&&this.replaceMeasureFormula(n,i,l)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:b(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=this.compileMeasureFormula(n.computedBy.sheetId,n.computedBy.formula);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.tokens){if(o.type!==`SYMBOL`)continue;let a=i.measures.find(e=>ut(e.id)===o.value&&t.id!==e.id);!a||n.has(a.id)||!a.computedBy||r.push(...this.computeMeasureFullDependencies(e,a,n))}return r.push(...a.dependencies.filter(e=>!e.invalidXc)),r}insertPivot(e,t,n){this.resizeSheet(e.sheetId,e,n);let r=n.getPivotCells();for(let n=0;n<r.length;n++)for(let i=0;i<r[n].length;i++){let a=r[n][i];this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col+n,row:e.row+i,content:hd(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}compileMeasureFormula(e,t){let n=Qx(t),r=n.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return{...n,dependencies:r}}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId})}checkSortedColumnInMeasures(e){let t=e.measures.map(e=>e.id);return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?`InvalidDefinition`:`Success`}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?`Success`:`InvalidDefinition`}import(e){if(e.pivots)for(let[t,n]of Object.entries(e.pivots))this.addPivot(t,n,n.formulaId);this.history.update(`nextFormulaId`,e.pivotNextId||cd(this.pivots)+1)}export(e){e.pivots={};for(let t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}},CH=class extends nH{static getters=[`getLocale`];locale=D;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return ql(e.locale)?`Success`:`InvalidLocale`}return`Success`}handle(e){switch(e.type){case`UPDATE_LOCALE`:let t=this.locale,n=e.locale;this.history.update(`locale`,n),this.changeCellsDateFormatWithLocale(t,n);break}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(let n of this.getters.getSheetIds())for(let[r,i]of Object.entries(this.getters.getCells(n))){let n;if(i.format===e.dateFormat&&(n=t.dateFormat),i.format===e.timeFormat&&(n=t.timeFormat),i.format===uu(e)&&(n=uu(t)),n){let{col:e,row:t,sheetId:i}=this.getters.getCellPosition(r);this.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:i,format:n})}}}import(e){this.locale=e.settings?.locale??D}export(e){e.settings={locale:this.locale}}},wH=class extends nH{allowDispatch(e){switch(e.type){case`ADD_PIVOT`:case`UPDATE_PIVOT`:let t=e.pivot;return this.checkDataSetValidity(t)}return`Success`}checkDataSetValidity(e){if(e.type===`SPREADSHEET`&&e.dataSet){let{zone:t,sheetId:n}=e.dataSet;return!n||!this.getters.tryGetSheet(n)||!t||!gs(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},TH=class extends nH{static getters=[`getNewCustomTableStyleName`,`getTableStyle`,`getTableStyles`,`isTableStyleEditable`];styles={};allowDispatch(e){switch(e.type){case`CREATE_TABLE`:case`UPDATE_TABLE`:if(e.config?.styleId&&!this.styles[e.config.styleId])return`InvalidTableConfig`;break;case`CREATE_TABLE_STYLE`:if(!$k[e.templateName])return`InvalidTableStyle`;try{sn(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=eA(e.tableStyleName,e.templateName,e.primaryColor);this.history.update(`styles`,e.tableStyleId,t);break;case`REMOVE_TABLE_STYLE`:let n={...this.styles};delete n[e.tableStyleId],this.history.update(`styles`,n);for(let t of this.getters.getSheetIds())for(let n of this.getters.getCoreTables(t))n.config.styleId===e.tableStyleId&&this.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{styleId:Rk.styleId}});break}}getTableStyle(e){if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return $t(E(`Custom Table Style`),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!Qk[e]}import(e){for(let e in Qk)this.styles[e]=Qk[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=eA(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)Qk[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},EH=class extends tH{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}};let DH=new g;DH.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let OH=Ix.mapping;function kH(e,t,n){return new AH(e,t,n).getParameters()}var AH=class{evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(OH),e,{getters:this.getters,locale:this.getters.getLocale()})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e,t){let n=this.getRangeError(e);if(n)return n;if(t)return{value:yc(this.getters.getSheetName(e.sheetId),vs(e.zone))};let r={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};return this.computeCell(r)}range(e){let t=this.getRangeError(e);if(t)return[[t]];let n=e.sheetId,r=e.zone,i=Ts(r,this.getters.getSheetZone(n));if(!i)return[[]];let{top:a,left:o,bottom:s,right:c}=r,l=`${n}-${a}-${o}-${s}-${c}`;if(l in this.rangeCache)return this.rangeCache[l];let u=i.bottom-i.top+1,d=i.right-i.left+1,f=Array(d);for(let e=i.left;e<=i.right;e++){let t=e-i.left;f[t]=Array(u);for(let r=i.top;r<=i.bottom;r++){let a=r-i.top;f[t][a]=this.computeCell({sheetId:n,col:e,row:r})}}return this.rangeCache[l]=f,f}getRangeError(e){if(!gs(e.zone))return new Vi;if(e.invalidSheetName)return new A(E(`Invalid sheet name: %s`,e.invalidSheetName))}},jH=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n||=self).RBush=r()})(e,function(){"use strict";function e(e,r,i,a,o){(function e(n,r,i,a,o){for(;a>i;){if(a-i>600){var s=a-i+1,c=r-i+1,l=Math.log(s),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(s-u)/s)*(c-s/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-c*u/s+d)),Math.min(a,Math.floor(r+(s-c)*u/s+d)),o)}var f=n[r],p=i,m=a;for(t(n,i,r),o(n[a],f)>0&&t(n,i,a);p<m;){for(t(n,p,m),p++,m--;o(n[p],f)<0;)p++;for(;o(n[m],f)>0;)m--}o(n[i],f)===0?t(n,i,m):t(n,++m,a),m<=r&&(i=m+1),r<=m&&(a=m-1)}})(e,r,i||0,a||e.length-1,o||n)}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:+(e>t)}var r=function(e){e===void 0&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function i(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1}function a(e,t){o(e,0,e.children.length,t,e)}function o(e,t,n,r,i){i||=m(null),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(var a=t;a<n;a++){var o=e.children[a];s(i,e.leaf?r(o):o)}return i}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function c(e,t){return e.minX-t.minX}function l(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function d(e){return e.maxX-e.minX+(e.maxY-e.minY)}function f(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function p(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function m(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function h(t,n,r,i,a){for(var o=[n,r];o.length;)if(!((r=o.pop())-(n=o.pop())<=i)){var s=n+Math.ceil((r-n)/i/2)*i;e(t,s,n,r,a),o.push(n,s,s,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(e){var t=this.data,n=[];if(!p(e,t))return n;for(var r=this.toBBox,i=[];t;){for(var a=0;a<t.children.length;a++){var o=t.children[a],s=t.leaf?r(o):o;p(e,s)&&(t.leaf?n.push(o):f(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n},r.prototype.collides=function(e){var t=this.data;if(!p(e,t))return!1;for(var n=[];t;){for(var r=0;r<t.children.length;r++){var i=t.children[r],a=t.leaf?this.toBBox(i):i;if(p(e,a)){if(t.leaf||f(e,a))return!0;n.push(i)}}t=n.pop()}return!1},r.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){var r=this.data;this.data=n,n=r}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this},r.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},r.prototype.clear=function(){return this.data=m([]),this},r.prototype.remove=function(e,t){if(!e)return this;for(var n,r,a,o=this.data,s=this.toBBox(e),c=[],l=[];o||c.length;){if(o||(o=c.pop(),r=c[c.length-1],n=l.pop(),a=!0),o.leaf){var u=i(e,o.children,t);if(u!==-1)return o.children.splice(u,1),c.push(o),this._condense(c),this}a||o.leaf||!f(o,s)?r?(n++,o=r.children[n],a=!1):o=null:(c.push(o),l.push(n),n=0,r=o,o=o.children[0])}return this},r.prototype.toBBox=function(e){return e},r.prototype.compareMinX=function(e,t){return e.minX-t.minX},r.prototype.compareMinY=function(e,t){return e.minY-t.minY},r.prototype.toJSON=function(){return this.data},r.prototype.fromJSON=function(e){return this.data=e,this},r.prototype._all=function(e,t){for(var n=[];e;)e.leaf?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},r.prototype._build=function(e,t,n,r){var i,o=n-t+1,s=this._maxEntries;if(o<=s)return a(i=m(e.slice(t,n+1)),this.toBBox),i;r||(r=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/s**(r-1))),(i=m([])).leaf=!1,i.height=r;var c=Math.ceil(o/s),l=c*Math.ceil(Math.sqrt(s));h(e,t,n,l,this.compareMinX);for(var u=t;u<=n;u+=l){var d=Math.min(u+l-1,n);h(e,u,d,c,this.compareMinY);for(var f=u;f<=d;f+=c){var p=Math.min(f+c-1,d);i.children.push(this._build(e,f,p,r-1))}}return a(i,this.toBBox),i},r.prototype._chooseSubtree=function(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){for(var i=1/0,a=1/0,o=void 0,s=0;s<t.children.length;s++){var c=t.children[s],l=u(c),d=(f=e,p=c,(Math.max(p.maxX,f.maxX)-Math.min(p.minX,f.minX))*(Math.max(p.maxY,f.maxY)-Math.min(p.minY,f.minY))-l);d<a?(a=d,i=l<i?l:i,o=c):d===a&&l<i&&(i=l,o=c)}t=o||t.children[0]}var f,p;return t},r.prototype._insert=function(e,t,n){var r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),s(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)},r.prototype._split=function(e,t){var n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=m(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,a(n,this.toBBox),a(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)},r.prototype._splitRoot=function(e,t){this.data=m([e,t]),this.data.height=e.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(e,t,n){for(var r,i,a,s,c,l,d,f=1/0,p=1/0,m=t;m<=n-t;m++){var h=o(e,0,m,this.toBBox),g=o(e,m,n,this.toBBox),_=(i=h,a=g,s=void 0,c=void 0,l=void 0,d=void 0,s=Math.max(i.minX,a.minX),c=Math.max(i.minY,a.minY),l=Math.min(i.maxX,a.maxX),d=Math.min(i.maxY,a.maxY),Math.max(0,l-s)*Math.max(0,d-c)),v=u(h)+u(g);_<f?(f=_,r=m,p=v<p?v:p):_===f&&v<p&&(p=v,r=m)}return r||n-t},r.prototype._chooseSplitAxis=function(e,t,n){var r=e.leaf?this.compareMinX:c,i=e.leaf?this.compareMinY:l;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)},r.prototype._allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=this.toBBox,a=o(e,0,t,i),c=o(e,n-t,n,i),l=d(a)+d(c),u=t;u<n-t;u++){var f=e.children[u];s(a,e.leaf?i(f):f),l+=d(a)}for(var p=n-t-1;p>=t;p--){var m=e.children[p];s(c,e.leaf?i(m):m),l+=d(c)}return l},r.prototype._adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)s(t[r],e)},r.prototype._condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)e[t].children.length===0?t>0?(n=e[t-1].children).splice(n.indexOf(e[t]),1):this.clear():a(e[t],this.toBBox)},r})}))(),1),MH=class{rTrees={};constructor(e=[]){let t={};for(let n of e){let e=n.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(n)}for(let e in t)this.rTrees[e]=new NH,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new NH),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&w(e.data,t.data)}},NH=class extends jH.default{toBBox({boundingBox:e}){let t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}},PH=class{dependencies=new SP;rTree;constructor(e,t=[]){this.createEmptyPositionSet=e,this.rTree=new MH(t)}removeAllDependencies(e){let t=this.dependencies.get(e);if(t){for(let e of t)this.rTree.remove(e);this.dependencies.delete(e)}}addDependencies(e,t){let n=t.map(({sheetId:t,zone:n})=>({data:e,boundingBox:{zone:n,sheetId:t}}));for(let e of n)this.rTree.insert(e);let r=this.dependencies.get(e);r?r.push(...n):this.dependencies.set(e,n)}getCellsDependingOn(e,t){let n=this.createEmptyPositionSet(),r=Array.from(e).reverse();for(;r.length>0;){let e=r.pop(),i=e.zone,a=e.sheetId;for(let e=i.left;e<=i.right;e++)for(let t=i.top;t<=i.bottom;t++)n.add({sheetId:a,col:e,row:t});let o=this.rTree.search(e).map(e=>e.data),s={};for(let e of o)!n.has(e)&&!t.has(e)&&(s[e.sheetId]||(s[e.sheetId]=[]),s[e.sheetId].push(z(e)));for(let e in s){let t=R(s[e],[]);r.push(...t.map(t=>({sheetId:e,zone:t})))}}for(let t of e){let e=t.zone,r=t.sheetId;for(let t=e.left;t<=e.right;t++)for(let i=e.top;i<=e.bottom;i++)n.delete({sheetId:r,col:t,row:i})}return n}},FH=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=IH(t),r=e<<n>>5,i=new this(r+1);return i.columnOffset=n,i.cols=t,i.rows=e,i}getValue(e){let[t,n]=this.getCoordinates(e);return this[t]>>n&1}setValue(e,t){let[n,r]=this.getCoordinates(e),i=(this[n]>>r&1)==0&&t===1;return this[n]=this[n]&~(1<<r)|t<<r,i}isEmpty(){return!this.some(e=>e!==0)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){let{row:t,col:n}=e,r=(t<<this.columnOffset)+n,i=r>>5;return[i,r-(i<<5)]}};function IH(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var LH=class{sheets={};insertions=[];maxSize=0;constructor(e){for(let t in e){let n=e[t].cols,r=e[t].rows;this.maxSize+=n*r,this.sheets[t]=FH.create(r,n)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(let t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(let t of e)this.delete(t)}has(e){return this.sheets[e.sheetId].getValue(e)===1}clear(){let e=[...this];this.insertions=[];for(let e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(this.insertions.length===0)return!0;for(let e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=Array(this.maxSize);let e=0;for(let t in this.sheets){let n=this.sheets[t];n.fillAllPositions();for(let r=0;r<n.rows;r++)for(let i=0;i<n.cols;i++)this.insertions[e++]={sheetId:t,row:r,col:i}}}*[Symbol.iterator](){for(let e of this.insertions)this.sheets[e.sheetId].getValue(e)===1&&(yield e)}},RH=class{resultsToArrayFormulas=new MH;arrayFormulasToResults=new SP;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||zH}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){let t=this.arrayFormulasToResults.get(e);t&&(this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.delete(e))}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}};let zH=[],BH=Object.freeze(qo(new Bi)),VH=Object.freeze(qo({value:null}));var HH=class{getters;compilationParams;evaluatedCells=new SP;formulaDependencies=kt(new PH(this.createEmptyPositionSet.bind(this)));blockedArrayFormulas=new LH({});spreadingRelations=new RH;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=kH(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||VH}getSpreadZone(e,t={ignoreSpillError:!1}){let n=this.spreadingRelations.getArrayResultZone(e);if(!n)return;let r=this.evaluatedCells.get(e);return r?.type===`error`&&!(t.ignoreSpillError&&r?.value===k.SpilledBlocked)?z(e):Cs(z(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type===`empty`)return;let t=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,z(e));return Array.from(t).find(e=>!this.blockedArrayFormulas.has(e))}isArrayFormulaSpillBlocked(e){return this.blockedArrayFormulas.has(e)}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);let t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t);for(let e of t)this.compilationParams.ensureRange(e)}updateCompilationParametersForIsolatedFormula(e){this.compilationParams=kH(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.updateDependencies=void 0,this.compilationParams.evalContext.addDependencies=void 0,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParameters(){this.compilationParams=kH(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){let e={};for(let t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new LH(e)}evaluateCells(e){let t=performance.now(),n=this.createEmptyPositionSet();n.addMany(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(e)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=this.createEmptyPositionSet();for(let n of e){let e=this.getters.getCell(n)?.content,r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.add(r),e||t.add(n)}let n=Ps(t);for(let e in n)for(let r of n[e])t.addMany(this.getArrayFormulasBlockedBy(e,r));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new RH,this.formulaDependencies=kt(()=>{let e=[...this.getAllCells()].flatMap(e=>this.getDirectDependencies(e).filter(e=>!e.invalidSheetName&&!e.invalidXc).map(t=>({data:e,boundingBox:{zone:t.zone,sheetId:t.sheetId}})));return new PH(this.createEmptyPositionSet.bind(this),e)})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new SP,this.evaluate(this.getAllCells()),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=Qx(t),i=r.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return this.updateCompilationParametersForIsolatedFormula(n),this.evaluateCompiledFormula(e,{...r,dependencies:i})}evaluateCompiledFormula(e,t,n){try{let r=GH(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return Or(r)?ha(r,WH):WH(r)}catch(e){return Rx(e,``)}}getAllCells(){let e=this.createEmptyPositionSet();return e.fillAllPositions(),e}getArrayFormulasBlockedBy(e,t){let n=this.createEmptyPositionSet(),r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addMany(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteMany(i),n.addMany(this.getCellsDependingOn(n)),n}nextPositionsToUpdate=new LH({});cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextPositionsToUpdate=e;let t=0;for(;!this.nextPositionsToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();let e=this.nextPositionsToUpdate.clear();for(let t=0;t<e.length;++t)this.evaluatedCells.delete(e[t]);for(let t=0;t<e.length;++t){let n=e[t];if(this.nextPositionsToUpdate.has(n))continue;let r=this.computeCell(n);r!==VH&&this.evaluatedCells.set(n,r)}DH.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}computeCell(e){let t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);let n=this.getters.getCell(e);if(n===void 0)return VH;let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?BH:(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):Go(n,i))}catch(e){return e.value=e?.value||k.GenericError,e.message=e?.message||Vx,e.errorOriginPosition=e?.errorOriginPosition,qo(e)}finally{this.cellsBeingComputed.delete(r)}}computeAndSave(e){let t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){let n=GH(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!Or(n)){let r=qo(WH(n),this.getters.getLocale(),t);return r.type===`error`&&(r.errorOriginPosition=n.errorOriginPosition??e),r}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return qo({value:0},this.getters.getLocale(),t);if(i===1&&r===1)return qo(WH(n[0][0]),this.getters.getLocale(),t);let a={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+r-1};return this.spreadingRelations.addRelation({resultZone:a,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),UH(r,i,this.checkCollision(e)),UH(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),qo(WH(n[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){let n=this.formulaDependencies().getCellsDependingOn(Ns(t).map(t=>({sheetId:e,zone:t})),this.nextPositionsToUpdate);n.delete({sheetId:e,col:t.left,row:t.top}),this.nextPositionsToUpdate.addMany(n)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:n},r){let i=this.getters.getNumberCols(e),a=this.getters.getNumberRows(e),o=t+r.length<=i,s=n+r[0].length<=a;if(!(o&&s))throw o?new Wi(E(`Result couldn't be automatically expanded. Please insert more rows.`)):s?new Wi(E(`Result couldn't be automatically expanded. Please insert more columns.`)):new Wi(E(`Result couldn't be automatically expanded. Please insert more columns and rows.`))}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:n},r){if(this.getters.getMergesInZone(e,{top:n,bottom:n+r[0].length-1,left:t,right:t+r.length-1}).length!==0)throw new Wi(E(`Merged cells found in the spill zone. Please unmerge cells before using array formulas.`))}checkCollision(e){let{sheetId:t,col:n,row:r}=e;return(i,a)=>{let o={sheetId:t,col:i+n,row:a+r};if(this.getters.getCell(o)?.content||this.getters.getEvaluatedCell(o).type!==`empty`)throw this.blockedArrayFormulas.add(e),new Wi(E(`Array result was not expanded because it would overwrite data.`),o);this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=qo(WH(r[i][a]),this.getters.getLocale(),s);c.type===`error`&&(c.errorOriginPosition=r[i][a].errorOriginPosition??o),this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r};this.getters.getCell(t)?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextPositionsToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return BH;this.symbolsBeingComputed.add(t);try{return e?.(t)||new zi(E(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.dependencies:[]}getCellsDependingOn(e){let t=[],n=Ps(e);for(let e in n)t.push(...n[e].map(t=>({sheetId:e,zone:t})));return this.formulaDependencies().getCellsDependingOn(t,this.nextPositionsToUpdate)}};function UH(e,t,n){for(let r=0;r<e;++r)for(let e=0;e<t;++e)r===0&&e===0||n(r,e)}function WH(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function GH(e,t,n,r,i){let a=t.evalContext,o=a.__originCellPosition,s=a.__originSheetId;a.__originCellPosition=i,a.__originSheetId=n;let c=e.execute(e.dependencies,t.referenceDenormalizer,t.ensureRange,r,a);return a.__originCellPosition=o,a.__originSheetId=s,c}var KH=class extends EH{static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getRangeFormattedValues`,`getRangeValues`,`getRangeFormats`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new HH(e.custom,this.getters)}beforeHandle(e){(fr.has(e.type)||mr.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case`UPDATE_CELL`:if(!(`content`in e||`format`in e)||this.shouldRebuildDependenciesGraph)return;let t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),`content`in e&&this.evaluator.updateDependencies(t);break;case`EVALUATE_CELLS`:this.evaluator.evaluateAllCells();break}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t,n){let r=this.evaluateFormulaResult(e,t,n);return Or(r)?ha(r,e=>e.value):r.value}evaluateFormulaResult(e,t,n){return this.evaluator.evaluateFormulaResult(e,t,n)}evaluateCompiledFormula(e,t,n){return this.evaluator.evaluateCompiledFormula(e,t,n)}getRangeFormattedValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).formattedValue)}getRangeValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).value)}getRangeFormats(e){let t=this.getters.tryGetSheet(e.sheetId);return t===void 0?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map(e=>e.format)}getEvaluatedCell(e){return this.evaluator.getEvaluatedCell(e)}getEvaluatedCells(e){return this.evaluator.getEvaluatedPositionsInSheet(e).map(e=>this.getEvaluatedCell(e))}getEvaluatedCellsPositions(e){return this.evaluator.getEvaluatedPositionsInSheet(e)}getEvaluatedCellsInZone(e,t){return Fs(t).map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return Fs(t).map(({col:t,row:n})=>this.getEvaluatedCell({sheetId:e,col:t,row:n})).every(e=>e.type===`empty`)}mapVisiblePositions(e,t){let{sheetId:n,zone:r}=e;return Fs(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=T(t.col,t.row),i=n.value,a=!1,o,s=!0,c=e.sheets.find(e=>e.id===t.sheetId),l=this.getCorrespondingFormulaCell(t);if(l){let u=this.getters.getCell(t);if(s=oS(l.compiledFormula.tokens),a=s&&u?.content===l.content,!s&&i!==``){o=(i??``).toString();let t=n.format;if(t){let n=tc(t,e.formats);c.formats[r]=n}}}let u=c.cells[r],d;d=s&&a&&l instanceof aH?l.contentWithFixedReferences:s?u:o,c.cells[r]=d,c.cellValues[r]=i===k.BadExpression?void 0:i;let f=this.getSpreadZone(t);f&&(c.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,f),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let qH=/"(#[0-9a-fA-F]{6})"/g;function JH(e){let t=[{leadColor:dn(255,0,0),colors:[]},{leadColor:dn(255,128,0),colors:[]},{leadColor:dn(128,128,0),colors:[]},{leadColor:dn(128,255,0),colors:[]},{leadColor:dn(0,255,0),colors:[]},{leadColor:dn(0,255,128),colors:[]},{leadColor:dn(0,255,255),colors:[]},{leadColor:dn(0,127,255),colors:[]},{leadColor:dn(0,0,255),colors:[]},{leadColor:dn(127,0,255),colors:[]},{leadColor:dn(128,0,128),colors:[]},{leadColor:dn(255,0,128),colors:[]}];for(let n of e.map(hn)){let e=500,r=0;t.forEach((t,i)=>{let a=YH(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>_n(e).s-_n(t).s)).flat().map(mn)}function YH(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var XH=class extends EH{customColors={};shouldUpdateColors=!0;static getters=[`getCustomColors`];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds())for(let t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));break;case`UPDATE_CHART`:case`CREATE_CHART`:this.tryToAddColors(this.getChartColors(e.figureId));break;case`UPDATE_CELL`:case`ADD_CONDITIONAL_FORMAT`:case`SET_BORDER`:case`SET_ZONE_BORDERS`:case`SET_FORMATTING`:case`CREATE_TABLE`:case`UPDATE_TABLE`:this.history.update(`shouldUpdateColors`,!0);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return JH(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(let t of this.getters.getSheetIds())e=e.concat(this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=new Set;for(let e of t)e.style?.textColor&&n.add(e.style.textColor),e.style?.fillColor&&n.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))n.add(t);return[...n]}getFormattingColors(e){let t=this.getters.getConditionalFormats(e),n=[];for(let e of t){let t=e.rule;t.type===`CellIsRule`?(n.push(t.style.textColor),n.push(t.style.fillColor)):t.type===`ColorScaleRule`&&(n.push(an(t.minimum.color)),n.push(t.midpoint?an(t.midpoint.color):void 0),n.push(an(t.maximum.color)))}return n.filter(C)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getDefinition()).matchAll(qH)].map(e=>e[1])}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(C):[]}tryToAddColors(e){for(let t of e){if(!cn(t))continue;let e=sn(t);t&&!Ie.includes(e)&&this.history.update(`customColors`,e,!0)}}},ZH=class extends EH{static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};createRuntimeChart=_D(this.getters);handle(e){if(fr.has(e.type)||hr.has(e.type)||pr.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:case`DELETE_FIGURE`:this.charts[e.figureId]=void 0;break;case`DELETE_SHEET`:for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0);break}}getChartRuntime(e){if(!this.charts[e]){let t=this.getters.getChart(e);if(!t)throw Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:TS(e)};if(!t)return{background:oe,fontColor:TS(oe)};let n=t.zone.left,r=t.zone.top,i=t.sheetId,a=this.getters.getCellComputedStyle({sheetId:i,col:n,row:r}),o=a.fillColor||`#FFFFFF`;return{background:o,fontColor:a.textColor||TS(o)}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let r of e){if(!r||r.tag!==`chart`)continue;let e=r.id,i=this.getters.getChart(e)?.getDefinitionForExcel();if(i)n.push({...r,data:i});else{if(!this.getters.getChart(e))continue;let n=this.getters.getChartType(e),i=Dw(this.getters.getChartRuntime(e),r,n);i&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:i,size:{width:r.width,height:r.height}}})}}t.charts=n}}},QH=class extends EH{static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(fr.has(e.type)||hr.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(let e of this.getters.getSheetIds())this.computedStyles[e]=kt(()=>this.getComputedStyles(e)),this.computedIcons[e]=kt(()=>this.getComputedIcons(e)),this.computedDataBars[e]=kt(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){let{sheetId:t,col:n,row:r}=e,i=this.computedStyles[t]();return i&&i[n]?.[r]}getConditionalIcon({sheetId:e,col:t,row:n}){let r=this.computedIcons[e]();return r&&r[t]?.[n]}getConditionalDataBar({sheetId:e,col:t,row:n}){let r=this.computedDataBars[e]();return r&&r[t]?.[n]}getComputedStyles(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())switch(n.rule.type){case`ColorScaleRule`:for(let r of n.ranges)this.applyColorScale(e,r,n.rule,t);break;case`CellIsRule`:let r=n.rule.values.map(e=>e.startsWith(`=`)?Qx(e):void 0);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let s={sheetId:e,col:o,row:i},c=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s.tokens):t});this.getRuleResultForTarget(s,{...n.rule,values:c})&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getEvaluatedCellsInZone(e,this.getters.getRangeFromSheetXC(e,t).zone).filter(e=>e.type===`number`).map(e=>e.value);switch(n.type){case`value`:return r===`max`?Jt(i):Yt(i);case`number`:return Number(n.value);case`percentage`:let t=Yt(i);return t+(Jt(i)-t)*Number(n.value)/100;case`percentile`:return Li(i,Number(n.value)/100,!0);case`formula`:let a=n.value&&this.getters.evaluateFormula(e,n.value);return typeof a==`number`?a:null;default:return null}}applyIcon(e,t,n,r){let i=this.parsePoint(e,t,n.lowerInflectionPoint),a=this.parsePoint(e,t,n.upperInflectionPoint);if(i===null||a===null||i>a)return;let o=this.getters.getRangeFromSheetXC(e,t).zone,s=[n.icons.upper,n.icons.middle,n.icons.lower];for(let t=o.top;t<=o.bottom;t++)for(let c=o.left;c<=o.right;c++){let o=this.getters.getEvaluatedCell({sheetId:e,col:c,row:t});if(o.type!==`number`)continue;let l=this.computeIcon(o.value,a,n.upperInflectionPoint.operator,i,n.lowerInflectionPoint.operator,s);r[c]||(r[c]=[]),r[c][t]=l}}computeIcon(e,t,n,r,i,a){return n===`ge`&&e>=t||n===`gt`&&e>t?a[0]:i===`ge`&&e>=r||i===`gt`&&e>r?a[1]:a[2]}applyDataBar(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,n.rangeValues||t),a=Jt(this.getters.getEvaluatedCellsInZone(e,i.zone).filter(e=>e.type===`number`).map(e=>e.value));if(a<=0)return;let o=n.color,s=this.getters.getRangeFromSheetXC(e,t).zone,c=i.zone;for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let i=n-s.left+c.left,l=t-s.top+c.top,u=this.getters.getEvaluatedCell({sheetId:e,col:i,row:l});!ks(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:an(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[{value:i,color:n.minimum.color}];n.midpoint&&a&&c.push({value:a,color:n.midpoint.color}),c.push({value:o,color:n.maximum.color});let l=zn(c);for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let a=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(a.type===`number`){let e=x(a.value,i,o);r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=l(e)}}}getRuleResultForTarget(e,t){let n=this.getters.getEvaluatedCell(e);if(n.type===`error`)return!1;let{sheetId:r}=e,i=Y.get(t.operator),a=t.values.map(e=>e.startsWith(`=`)?this.getters.evaluateFormula(r,e)??``:Ko(e,D));if(a.some(Du))return!1;let o={type:t.operator,values:a.map(Tu)};return i.isValueValid(n.value??``,o,this.getters,r)}};let $H={isValid:!0};var eU=class extends EH{static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`getDataValidationRangeValues`,`isCellValidCheckbox`,`getDataValidationCellStyle`,`getDataValidationChipStyle`,`isDataValidationInvalid`];validationResults={};handle(e){if(fr.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:`#E7E9ED`}}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=Y.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?E(`The value must not be a formula`):this.isValidFormula(t)?void 0:G.CriterionError.validFormula:n.allowedValues===`onlyFormulas`?E(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}getDataValidationRangeValues(e,t){let n=this.getters.getRangeFromSheetXC(e,String(t.values[0])),r=[],i=new Set;for(let e of Fs(n.zone)){let t=this.getters.getEvaluatedCell({...e,sheetId:n.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),r.push({label:t.formattedValue,value:t.value?.toString()||``}))}return r}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return $H;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:$H}hasChip(e){let t=this.getters.getValidationRuleForCell(e);return(t?.criterion.type===`isValueInList`||t?.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`chip`}getDataValidationStyle(e){let t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;let n=this.getters.getEvaluatedCell(e),r=this.getValueColor(t,n.value);if(r)return{fillColor:r,textColor:Tn(r)}}getValueColor(e,t){if(!(e.criterion.type!==`isValueInList`&&e.criterion.type!==`isValueInRange`)){for(let n in e.criterion.colors)if(n.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[n]}}isValidFormula(e){return!Qx(e).isBadExpression}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||$H}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of Oc(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=kt(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?$H:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=Y.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,o,i);if(s.some(Du))return;let c={...i,values:s.map(Tu)};if(!a.isValueValid(e,c,this.getters,r))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>ks(e.col,e.row,t.zone));if(!n)throw Error(`The cell is not in any range of the rule`);return{col:e.col-n.zone.left,row:e.row-n.zone.top}}getEvaluatedCriterionValues(e,t,n){return n.values.map(n=>{if(!n.startsWith(`=`))return Ko(n,D);let r=Qx(n),i=this.getters.getTranslatedCellFormula(e,t.col,t.row,r.tokens);return this.getters.evaluateFormula(e,i)})}};let tU=new g;tU.add(`data_validation_checkbox`,(e,t)=>{if(e.isCellValidCheckbox(t)){let n=!!e.getEvaluatedCell(t).value;return{svg:n?vA:gA,hoverSvg:n?vA:_A,priority:2,horizontalAlign:`center`,size:17,margin:2,position:t,type:`data_validation_checkbox`,onClick:(e,t)=>{let r=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||r?.isFormula)return;let i=n?`FALSE`:`TRUE`;t.model.dispatch(`UPDATE_CELL`,{...e,content:i})}}}}),tU.add(`data_validation_chip_icon`,(e,t)=>{let n=e.getDataValidationChipStyle(t);if(n){let r=e.getCellComputedStyle(t);return{svg:mA(n),hoverSvg:hA(n),priority:10,horizontalAlign:`right`,size:ol(r),margin:4,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_chip_icon`}}}),tU.add(`data_validation_list_icon`,(e,t)=>{if(!e.isReadonly()&&e.cellHasListDataValidationIcon(t)){let n=e.getCellComputedStyle(t);return{svg:dA(n),hoverSvg:fA(n),priority:2,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_list_icon`}}}),tU.add(`filter_icon`,(e,t)=>{if(e.isFilterHeader(t)){let n=e.isFilterActive(t),r=fn(e.getCellComputedStyle(t).fillColor||`#fff`)<.45;return{type:`filter_icon`,svg:bA(n,r,!1),hoverSvg:bA(n,r,!0),priority:3,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let n=t.getStore(Ck),r=n.persistentCellPopover;if(r.isOpen&&r.col===e.col&&r.row===e.row&&r.type===`FilterMenu`){n.close();return}n.open(e,`FilterMenu`)}}}}),tU.add(`conditional_formatting`,(e,t)=>{let n=e.getConditionalIcon(t);if(n){let r=e.getCellStyle(t);return{type:`conditional_formatting`,svg:xA[n].svg,priority:1,horizontalAlign:`left`,size:ol(r),margin:4,position:t}}}),tU.add(`pivot_collapse`,(e,t)=>{if(!e.isSpillPivotFormula(t))return;let n=e.getPivotCellFromPosition(t),r=e.getPivotIdFromPosition(t);if(n.type===`HEADER`&&r&&n.domain.length){let i=e.getPivotCoreDefinition(r),a=e.isDashboard(),o=n.dimension===`COL`?i.columns:i.rows,s=!a&&n.domain.length!==o.length,c=(i.collapsedDomains?.[n.dimension]??[]).some(e=>w(e,n.domain)),l=n.dimension===`ROW`?(n.domain.length-1)*15:0;return{type:`pivot_collapse`,priority:4,horizontalAlign:`left`,size:s||!a&&n.dimension===`ROW`&&i.rows.length>1?12:0,margin:s?4+l:l,svg:s?yA(c,!1):void 0,hoverSvg:s?yA(c,!0):void 0,position:t,onClick:nU}}});function nU(e,t){let n=t.model.getters.getPivotCellFromPosition(e),r=t.model.getters.getPivotIdFromPosition(e);if(!r||n.type!==`HEADER`)return;let i=t.model.getters.getPivotCoreDefinition(r),a=i.collapsedDomains?.[n.dimension]?[...i.collapsedDomains[n.dimension]]:[],o=a.findIndex(e=>w(e,n.domain));o===-1?a.push(n.domain):a.splice(o,1);let s=i.collapsedDomains?{...i.collapsedDomains}:{COL:[],ROW:[]};s[n.dimension]=a,t.model.dispatch(`UPDATE_PIVOT`,{pivotId:r,pivot:{...i,collapsedDomains:s}})}var rU=class extends EH{static getters=[`doesCellHaveGridIcon`,`getCellIcons`,`getCellIconRect`];cellIconsCache={};handle(e){e.type!==`SET_VIEWPORT_OFFSET`&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){let n=e.position,r=this.getters.getCell(n);return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,r?.style?.verticalAlign),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,n){let r=e.x,i=e.x+e.width;switch(t){case`right`:return i-n.margin-n.size;case`left`:return r+n.margin;default:let e=Math.floor((i-r-n.size)/2);return i-n.size-e}}computeCellIcons(e){let t={left:void 0,right:void 0,center:void 0},n=tU.getAll();for(let r of n){let n=r(this.getters,e);n&&(!t[n.horizontalAlign]||n.priority>t[n.horizontalAlign].priority)&&(t[n.horizontalAlign]=n)}if(t.center&&(t.left||t.right)){let e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(C)}doesCellHaveGridIcon(e){return!!this.getCellIcons(e).length}},iU=class extends EH{static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(fr.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tables={};return}switch(e.type){case`CREATE_TABLE`:case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`DELETE_CONTENT`:this.tables={};break}}finalize(){for(let e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){let t=[],n=this.getters.getCoreTables(e);for(let e of n)e.type!==`dynamic`&&t.push(e);let r=[...t];for(let i of n){if(i.type!==`dynamic`)continue;let n=this.coreTableToTable(e,i),a=n.range.zone;for(let e of r){let t=e.range.zone;Ds(a,t)&&(a=t.left>a.left?{...a,right:Math.min(a.right,t.left-1)}:{...a,bottom:Math.min(a.bottom,t.top-1)})}t.push({...n,range:this.getters.getRangeFromZone(e,a)})}return t}getFilters(e){return this.getTables(e).filter(e=>e.config.hasFilters).map(e=>e.filters).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){let t=this.getTable(e);if(!(!t||!t.config.hasFilters))return t.filters.find(t=>t.col===e.col)}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:n}){return this.getTables(e).find(e=>ks(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>Ds(e.range.zone,t)))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some(e=>e.config.hasFilters)}getFilterHeaders(e){let t=[];for(let n of this.getTables(e)){if(!n.config.hasFilters)continue;let r=n.range.zone,i=r.top;for(let n=r.left;n<=r.right;n++)t.push({sheetId:e,col:n,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:n}){return this.getFilterHeaders(e).some(e=>e.col===t&&e.row===n)}canCreateDynamicTableOnZones(e,t){if(!Js(t))return!1;let n=Cs(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);if(!i){let e=this.getters.getEvaluatedCell(r);return e.value===k.SpilledBlocked&&!e.errorOriginPosition}else if(w(i,r)&&Ws(n)===1)return!0;return w(n,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=tF(this.getDynamicTableFilterId(t.id,s),this.getters.getRangeFromZone(e,c),t.config,this.getters.getRangeFromZone);r.push(l)}return r}getDynamicTableFilterId(e,t){return e+`_`+t}isTableExcelExportable(e,t){return t.type===`dynamic`?!1:!Fs(t.range.zone).some(t=>this.getters.getArrayFormulaSpreadingOn({sheetId:e,...t}))}exportForExcel(e){for(let t of e.sheets){let n=[];for(let r of t.tables){let i=ps(r.range),a={sheetId:t.id,col:i.left,row:i.top},o=this.getters.getCoreTable(a),s=this.getTable(a);if(!o||!s||this.isTableExcelExportable(t.id,o)){n.push(r);continue}t.styles=t.styles||{},t.borders=t.borders||{};for(let n of Fs(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=T(n.col,n.row);if(!Tt(i)){let n=tc(i,e.styles);t.styles[o]=n}if(a){let n=tc(a,e.borders);t.borders[o]=n}}}t.tables=n}}},aU=class extends EH{static getters=[`getRowSize`,`getHeaderSize`,`getMaxAnchorOffset`];tallestCellInRow={};ctx=document.createElement(`canvas`).getContext(`2d`);beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=jt(e.position,e.base),n=Array(e.quantity).fill(void 0),r=Ut(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=b(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=Ht(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of S(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of Fs(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getMaxAnchorOffset(e,t,n){let{numberOfRows:r,numberOfCols:i}=this.getters.getSheetSize(e),a=0;for(;a<t&&r>0;r--)a+=this.getRowSize(e,r-1);let o=0;for(;o<n&&i>0;i--)o+=this.getters.getColSize(e,i-1);return{col:i,row:r,offset:{x:o-n,y:a-t}}}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForCellChange(e,t,n){let r=this.tallestCellInRow[e]?.[t];if(r?.cell.col===n){let n=this.getRowTallestCell(e,t);this.history.update(`tallestCellInRow`,e,t,n)}let i=this.getCellHeight({sheetId:e,col:n,row:t});if(!(i<=23)&&(!r&&i>23||r&&i>r.size)){let r={cell:{sheetId:e,col:n,row:t},size:i};this.history.update(`tallestCellInRow`,e,t,r)}}initializeSheet(e){let t=[];for(let n=0;n<this.getters.getNumberRows(e);n++){let r=this.getRowTallestCell(e,n);t.push(r)}this.history.update(`tallestCellInRow`,e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return 23;let t=this.getters.getCell(e),n=this.getters.getColSize(e.sheetId,e.col);return Yc(this.ctx,t,this.getters.getLocale(),n)}isInMultiRowMerge(e){let t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(this.getters.getUserRowSize(e,t)!==void 0)return;let n=this.getters.getRowCells(e,t),r=0,i;for(let e=0;e<n.length;e++){let t=this.getters.getCellById(n[e]);if(!t)continue;let a=this.getters.getCellPosition(t.id),o=this.getCellHeight(a);o>r&&o>23&&(r=o,i={cell:a,size:o})}if(i&&i.size>23)return i}};let oU=`0.00%`;function sU(e){class t extends e{getters;pivotId;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t,n){super(t,n),this.getters=n.getters,this.pivotId=e}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){let n=`${e}-${t.map(e=>e.field+`=`+e.value).join(`,`)}`;if(this.cache[n])return this.cache[n];let r=this.getMeasure(e),i=r.computedBy?this.computeMeasure(r,t):super.getPivotCellValueAndFormat(e,t);return r.format?this.cache[n]={...i,format:r.format}:this.cache[n]=i,this.cache[n]}computeMeasure(e,t){if(!e.computedBy)return{value:0};let{columns:n,rows:r}=super.definition;if(e.aggregator&&n.length+r.length!==t.length){let n=this.getValuesToAggregate(e,t),r=sd[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return Rx(t,e.aggregator.toUpperCase())}}let i=this.getters.getMeasureCompiledFormula(this.pivotId,e),a=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,e=>{let{columns:n,rows:r}=this.definition;if(n.find(t=>t.nameWithGranularity===e)){let{colDomain:n}=xI(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Hi:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=xI(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Hi:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return Or(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=xI(this,t),i=super.getExpandedTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=gd(this.definition.getDimension(r.field),t[n]?.value);if(r.field===t[n]?.field&&r.value===e)return this.getSubTreeMatchingDomain(r.children,t,n+1)}return[]}treeToLeafDomains(e,t=[]){let n=[];for(let r of e){let e=this.definition.getDimension(r.field),i=[...t,{field:r.field,value:r.value,type:e.type}];r.children.length===0?n.push(i):n.push(...this.treeToLeafDomains(r.children,i))}return n}getMeasureDisplayValue(e,t){let n=this.getMeasure(e),r=this._getPivotCellValueAndFormat(e,t);if(!n.display||n.display.type===`no_calculations`||r.message)return r;let i=n.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:k.NotAvailable,message:E(`Field "%s" not found in pivot for measure display calculation`,i)};try{let e=n.display;switch(e.type){case`%_of_grand_total`:return this.asPercentOfGrandTotal(r,n);case`%_of_col_total`:return this.asPercentOfColumnTotal(r,n,t);case`%_of_row_total`:return this.asPercentOfRowTotal(r,n,t);case`%_of_parent_row_total`:return this.asPercentOfParentRowTotal(r,n,t);case`%_of_parent_col_total`:return this.asPercentOfParentColumnTotal(r,n,t);case`index`:return this.asIndex(r,n,t);case`%_of_parent_total`:return this.asPercentOfParentTotal(r,n,t,e);case`running_total`:return this.asRunningTotal(r,n,t,e,`running_total`);case`%_running_total`:return this.asRunningTotal(r,n,t,e,`%_running_total`);case`rank_asc`:return this.asRank(r,n,t,e,`asc`);case`rank_desc`:return this.asRank(r,n,t,e,`desc`);case`%_of`:return this.asPercentOf(r,n,t,e);case`difference_from`:return this.asDifferenceFrom(r,n,t,e);case`%_difference_from`:return this.asDifferenceFromInPercent(r,n,t,e)}return r}catch(e){return Rx(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:k.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:oU}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:k.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:oU}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:k.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:oU}}asPercentOfParentRowTotal(e,t,n){let r=yI(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:oU}}asPercentOfParentColumnTotal(e,t,n){let r=bI(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:oU}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!kI(i,n))return{value:``};let a=DI(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:oU}}asIndex(e,t,n){let r=this.measureValueToNumber(e),i=this.getRowTotal(t.id,n),a=this.getColumnTotal(t.id,n),o=this.getGrandTotal(t.id);return i===0||a===0?{value:k.DivisionByZero}:{value:r*o/(a*i),format:void 0}}asRunningTotal(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;let o=i===`running_total`?this.runningTotal:this.runningTotalInPercent,s=o[t.id]?.[a];s||(s=this.computeRunningTotal(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=xI(this,n),u=MI(l),d=MI(c);return{value:s[u]?.[d]??``,format:i===`running_total`?e.format:oU}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!kI(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:k.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:oU}:s===void 0?{value:k.NullError}:{value:s/o,format:oU}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!kI(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a)||0;return o===`sameValue`?{value:``}:{value:this.measureValueToNumber(e)-o,format:e.format}}asDifferenceFromInPercent(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!kI(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:k.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:k.NullError}:{value:(s-o)/o,format:oU}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!kI(a,n))return{value:``};let o=i===`asc`?this.rankAsc:this.rankDesc,s=o[t.id]?.[a];s||(s=this.computeRank(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=xI(this,n),u=MI(l),d=MI(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=AI(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=_a(o));for(let s of o){let o=MI(SI(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:SI(this,i,t.domain)})).filter(e=>kI(t,e.rowDomain)),l=Object.groupBy(c,e=>PI(e.rowDomain,t));for(let e in l)l[e]=Zt(l[e]||[],e=>e.value).filter(e=>e.value!==void 0).sort((e,t)=>n===`asc`?e.value-t.value:t.value-e.value);r[o]={};for(let e of c){let n=MI(SI(this,i,e.domain)),a=l[PI(e.rowDomain,t)];if(!a)continue;let s=a.findIndex(t=>t.value===e.value);s!==-1&&(r[o][n]=s+1)}}return i===`row`?r:Qt(r)}computeRunningTotal(e,t,n){let r={},i=AI(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=_a(o));for(let s of o){let o=MI(SI(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:SI(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>kI(t,e.rowDomain));for(let e of l){let n=MI(e.rowDomain),i=FI(e.rowDomain,t),a=(c[i]||0)+e.value;c[i]=a,r[o][n]=a}if(n===`%_running_total`)for(let e of l){let n=e.rowDomain,i=MI(n),a=FI(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:Qt(r)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=xI(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=xI(this,t).colDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,n,r){let i=r===`(previous)`||r===`(next)`?jI(this,t,n,r):OI(t,n,r);if(w(i,t))return`sameValue`;if(!i||!wI(this,i))throw new Hi;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){let e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){let e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;let t=this.definition.sortedColumn.measure;wd(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}return t}let cU=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function lU(e){return cU.includes(e.type)}var uU=class extends EH{static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotIdFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`];pivots={};unusedPivots;custom;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){switch(e.type){case`START`:for(let e of this.getters.getPivotIds())this.setupPivot(e)}}handle(e){if(fr.has(e.type))for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0});switch(e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.setupPivot(e.pivotId);break;case`DUPLICATE_PIVOT`:this.setupPivot(e.newPivotId);break;case`UPDATE_PIVOT`:this.setupPivot(e.pivotId,{recreate:!0});break;case`DELETE_SHEET`:case`UPDATE_CELL`:this.unusedPivots=void 0;break;case`UNDO`:case`REDO`:{this.unusedPivots=void 0;let t=e.commands.filter(lU);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:vV();break}}getPivotIdFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){let n=this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(n){let e=n.args[0]?.toString();return e&&this.getters.getPivotId(e)}}}isSpillPivotFormula(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens)?.functionName===`PIVOT`:!1}getFirstPivotFunction(e,t){let n=QB(t);if(!n)return;let{functionName:r,args:i}=n;return{functionName:r,args:i.map(t=>{if(t.type===`EMPTY`)return;if(t.type===`STRING`||t.type===`BOOLEAN`||t.type===`NUMBER`)return t.value;let n=gy(t);return this.getters.evaluateFormula(e,n)})}}getPivotCellFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||$B(t.compiledFormula.tokens)===0)return aV;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!r)return aV;let{functionName:i,args:a}=r,o=a[0];if(!o)return aV;let s=this.getters.getPivotId(o.toString());if(!s)return aV;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!t.content.replaceAll(` `,``).toUpperCase().startsWith(`=PIVOT`))return aV;try{if(i===`PIVOT`){let t=Tu(a[2]),r=t===void 0?!0:P(t),i=Tu(a[3]),o=Tu(a[5]),s=o===void 0?!0:P(o),l={displayColumnHeaders:i===void 0?!0:P(i),displayTotals:r,displayMeasuresRow:s},u=c.getCollapsedTableStructure().getPivotCells(l),d=e.col-n.col,f=e.row-n.row;return u[d][f]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>Or(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`){let e=c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})));return{type:`HEADER`,domain:e,dimension:xI(c,e).colDomain.length?`COL`:`ROW`}}let[o,...s]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(s.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return aV}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName);return $t(E(`Calculated measure 1`),t,{compute:(e,t)=>E(`Calculated measure %s`,t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){return this._getUnusedPivots().includes(e)}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=b(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=sU(bV.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivots(){if(this.unusedPivots!==void 0)return this.unusedPivots;let e=new Set(this.getters.getPivotIds());for(let t of this.getters.getSheetIds())for(let n in this.getters.getCells(t)){let t=this.getters.getCellPosition(n),r=this.getPivotIdFromPosition(t);if(r&&(e.delete(r),!e.size))return this.unusedPivots=[],[]}return this.unusedPivots=[...e],this.unusedPivots}};let dU=new g;dU.add(`ALPHANUMERIC_INCREMENT_MODIFIER`,{apply:(e,t)=>{e.current+=e.increment;let n=`${e.prefix}${e.current.toString().padStart(e.numberPostfixLength||0,`0`)}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:n},tooltip:{props:{content:n}}}}}).add(`INCREMENT_MODIFIER`,{apply:(e,t,n)=>{e.current+=e.increment;let r=e.current.toString(),i=n.getLocale(),a=L(e.current,{format:t.cell?.format,locale:i});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:a}}:void 0}}}).add(`DATE_INCREMENT_MODIFIER`,{apply:(e,t,n)=>{let r=F(e.current,n.getLocale());r.setFullYear(r.getFullYear()+e.increment.years||0),r.setMonth(r.getMonth()+e.increment.months||0),r.setDate(r.getDate()+e.increment.days||0);let i=gi(r);e.current=i;let a=n.getLocale(),o=L(i,{format:t.cell?.format,locale:a});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:o}}:void 0}}}).add(`COPY_MODIFIER`,{apply:(e,t,n)=>{let r=t.cell?.content||``,i={locale:n.getLocale(),format:t.cell?.format};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:t.cell?Go(t.cell,i).formattedValue:``}}:void 0}}}).add(`FORMULA_MODIFIER`,{apply:(e,t,n,r)=>{e.current+=e.increment;let i=0,a=0;switch(r){case`up`:i=0,a=-e.current;break;case`down`:i=0,a=e.current;break;case`left`:i=-e.current,a=0;break;case`right`:i=e.current,a=0;break}let o=t.cell;if(!o||!o.isFormula)return{cellData:{}};let s=t.sheetId,c=n.getTranslatedCellFormula(s,i,a,o.compiledFormula.tokens);return{cellData:{border:t.border,style:o.style,format:o.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});let fU=new g,pU=/(\d+)$/,mU=/^(.*\D+)/,hU=/^(.*\D+)(\d+)$/;function gU(e,t,n){let r=[],i=!1;for(let a of t){a===e&&(i=!0);let t=a===void 0||a.isFormula?void 0:Go(a,{locale:D,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function _U(e){let t=[],n=e[0];for(let r=1;r<e.length;r++){let i=e[r];t.push(i-n),n=i}return t.reduce((e,t)=>e+t,0)/t.length}function vU(e){let t=1;return e.length>=2&&(t=_U(e)*e.length),t}function yU(e){return e.length<2?e[0]||{years:0,months:0,days:0}:e.every(t=>t.years===e[0].years&&t.months===e[0].months&&t.days===e[0].days)?e[0]:void 0}function bU(e){if(e.length<2)return 1;let t=e.map(e=>F(e,D)),n=yU(xU(t));if(n===void 0)return;let r=Object.values(n).filter(e=>e!==0).length===1,i=Object.values(n).every(e=>e===0);if(!r||i){let n=t.map((e,n)=>{if(n===0)return 0;let r=t[n-1];return Math.floor(e.getTime())-Math.floor(r.getTime())}).slice(1);if(n.every(e=>e===n[0]))return e.length*(e[1]-e[0])}return{years:n.years*e.length,months:n.months*e.length,days:n.days*e.length}}fU.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&So(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&Go(e,{locale:D}).type===`text`&&hU.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(pU)[0]),i=e.content.match(mU)[0],a=e.content.length-i.length,o=gU(e,t,e=>e.type===`text`&&hU.test(e.value)).filter(e=>i===(e.value??``).toString().match(mU)[0]).map(e=>parseInt((e.value??``).toString().match(pU)[0])),s=vU(o);return[`up`,`left`].includes(n)&&o.length===1&&(s=-s),{type:`ALPHANUMERIC_INCREMENT_MODIFIER`,prefix:i,current:r,increment:s,numberPostfixLength:a}},sequence:15}).add(`copy_text`,{condition:e=>!e.isFormula&&Go(e,{locale:D}).type===`text`,generateRule:()=>({type:`COPY_MODIFIER`}),sequence:20}).add(`update_formula`,{condition:e=>e.isFormula,generateRule:(e,t)=>({type:`FORMULA_MODIFIER`,increment:t.length,current:0}),sequence:30}).add(`increment_dates`,{condition:(e,t)=>!e.isFormula&&Go(e,{locale:D}).type===`number`&&!!e.format&&So(e.format),generateRule:(e,t)=>{let n=bU(gU(e,t,e=>e.type===`number`&&!!e.format&&So(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=Go(e,{locale:D});return typeof n==`object`?{type:`DATE_INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}:{type:`INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}},sequence:25}).add(`increment_number`,{condition:e=>!e.isFormula&&Go(e,{locale:D}).type===`number`,generateRule:(e,t,n)=>{let r=gU(e,t,e=>e.type===`number`&&!So(e.format||``)).map(e=>Number(e.value)),i=vU(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=Go(e,{locale:D});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===`number`?a.value:0}},sequence:40});function xU(e){return e.length<2?[{years:0,months:0,days:0}]:e.map((t,n)=>{if(n===0)return{years:0,months:0,days:0};let r=O.fromTimestamp(e[n-1].getTime()),i=wi(r,t),a=Si(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:Ci(r,t)}}).slice(1)}var SU=class extends tH{static layers=[];getters;ui;selection;dispatch;canDispatch;constructor({getters:e,stateObserver:t,dispatch:n,canDispatch:r,uiActions:i,selection:a}){super(t),this.getters=e,this.ui=i,this.selection=a,this.dispatch=n,this.canDispatch=r}drawLayer(e,t){}},CU=class{cells;getters;index=0;direction;constructor(e,t,n){this.cells=e,this.getters=t,this.direction=n}next(){let e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:n,tooltip:r}=dU.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:n,tooltip:r,origin:{col:e.data.col,row:e.data.row}}}},wU=class extends SU{static layers=[`Autofill`];static getters=[`getAutofillTooltip`];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case`AUTOFILL_SELECT`:let t=this.getters.getActiveSheetId();return this.lastCellSelected.col=e.col===-1?this.lastCellSelected.col:x(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=e.row===-1?this.lastCellSelected.row:x(e.row,0,this.getters.getNumberRows(t)),this.lastCellSelected.col!==void 0&&this.lastCellSelected.row!==void 0?`Success`:`InvalidAutofillSelection`}return`Success`}handle(e){switch(e.type){case`AUTOFILL`:this.autofill(!0);break;case`AUTOFILL_SELECT`:this.select(e.col,e.row);break;case`AUTOFILL_AUTO`:this.autofillAuto();break}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||this.direction===void 0){this.tooltip=void 0;return}let t=this.getters.getSelectedZone(),n=this.autofillZone,r=[];switch(this.direction){case`down`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.top;n<=t.bottom;n++)i.push(T(e,n));let a=this.createGenerator(i);for(let t=n.top;t<=n.bottom;t++)r.push(this.computeNewCell(a,e,t))}break;case`up`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.bottom;n>=t.top;n--)i.push(T(e,n));let a=this.createGenerator(i);for(let t=n.bottom;t>=n.top;t--)r.push(this.computeNewCell(a,e,t))}break;case`left`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.right;n>=t.left;n--)i.push(T(n,e));let a=this.createGenerator(i);for(let t=n.right;t>=n.left;t--)r.push(this.computeNewCell(a,t,e))}break;case`right`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.left;n<=t.right;n++)i.push(T(n,e));let a=this.createGenerator(i);for(let t=n.left;t<=n.right;t++)r.push(this.computeNewCell(a,t,e))}break}if(e){let e={},t={},n={},i=this.getters.getActiveSheetId();for(let a of r)this.collectBordersData(a,e),this.autofillMerge(i,a),this.autofillCell(i,a),this.collectConditionalFormatsData(i,a,t),this.collectDataValidationsData(i,a,n);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,n),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){let n=JSON.stringify(e.border);n in t||(t[n]=[]),t[n].push(z({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s=this.getters.getRulesByCell(e,r,i),c=T(a,o);for(let e of s)e.id in n||(n[e.id]=[]),n[e.id].push(c)}collectDataValidationsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s={sheetId:e,col:r,row:i},c=this.getters.getValidationRuleForCell(s);c&&(c.id in n||(n[c.id]=[]),n[c.id].push(z({col:a,row:o})))}autofillCell(e,t){this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t.col,row:t.row,content:t.content||``,style:t.style||null,format:t.format||``}),this.dispatch(`AUTOFILL_CELL`,t)}autofillBorders(e,t){for(let n in t){let r=n===`undefined`?void 0:JSON.parse(n);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,border:r,target:R(t[n])})}}autofillConditionalFormats(e,t){for(let n in t){let r=t[n],i=this.getters.getConditionalFormats(e).find(e=>e.id===n);if(!i)continue;let a=this.getters.getAdaptedCfRanges(e,i,r.map(ps),[]);a&&this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:i.id,rule:i.rule,stopIfTrue:i.stopIfTrue},ranges:a,sheetId:e})}}autofillDataValidations(e,t){for(let n in t){let r=t[n],i=this.getters.getDataValidationRule(e,n);if(!i)continue;let a=R(i.ranges.map(e=>e.zone).concat(r),[]);this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:i,ranges:a.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}select(e,t){let n=this.getters.getSelectedZone();if(ks(e,t,n)){this.autofillZone=void 0;return}switch(this.direction=this.getDirection(e,t),this.direction){case`up`:this.saveZone(t,n.top-1,n.left,n.right),this.steps=n.top-t;break;case`down`:this.saveZone(n.bottom+1,t,n.left,n.right),this.steps=t-n.bottom;break;case`left`:this.saveZone(n.top,n.bottom,e,n.left-1),this.steps=n.left-e;break;case`right`:this.saveZone(n.top,n.bottom,n.right+1,e),this.steps=e-n.right;break}this.autofill(!1)}autofillAuto(){let e=this.getters.getActivePosition(),t=this.getters.getTable(e),n=t?t.range.zone.bottom:this.getAutofillAutoLastRow(),r=this.getters.getSelectedZone();for(let t=r.bottom+1;t<=n;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==`empty`){n=t-1;break}n>r.bottom&&(this.select(e.col,n),this.autofill(!0))}getAutofillAutoLastRow(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId(),n=e.left,r=e.bottom;if(n>0){let e={sheetId:t,col:n-1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n-1,row:r}}if(r===e.bottom&&(n=e.right,n<=this.getters.getNumberCols(t))){let e={sheetId:t,col:n+1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n+1,row:r}}return r-1}computeNewCell(e,t,n){let{cellData:r,tooltip:i,origin:a}=e.next(),{content:o,style:s,border:c,format:l}=r;return this.tooltip=i,{originCol:a.col,originRow:a.row,col:t,row:n,content:o,style:s,border:c,format:l}}getRule(e,t){let n=fU.getAll().sort((e,t)=>e.sequence-t.sequence).find(n=>n.condition(e,t));return n&&this.direction&&n.generateRule(e,t,this.direction)}createGenerator(e){let t=[],n=[],r=this.getters.getActiveSheetId();for(let t of e){let{col:e,row:i}=Zn(t),a=this.getters.getCell({sheetId:r,col:e,row:i});n.push({col:e,row:i,cell:a,sheetId:r})}let i=n.map(e=>e.cell);for(let e of n){let n={type:`COPY_MODIFIER`};e&&e.cell&&(n=this.getRule(e.cell,i)||n);let r=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:r},rule:n})}return new CU(t,this.getters,this.direction)}saveZone(e,t,n,r){this.autofillZone={top:e,bottom:t,left:n,right:r}}getDirection(e,t){let n=this.getters.getSelectedZone(),r={up:{number:n.top-t,value:`up`},down:{number:t-n.bottom,value:`down`},left:{number:n.left-e,value:`left`},right:{number:e-n.right,value:`right`}};if(Object.values(r).map(e=>+(e.number>0)).reduce((e,t)=>e+t)===1)return Object.values(r).find(e=>+(e.number>0)).value;let i=r.up.number>0?`up`:`down`,a=r.left.number>0?`left`:`right`;return Math.abs(r[i].number)>=Math.abs(r[a].number)?r[i].value:r[a].value}autofillMerge(e,t){let{originCol:n,originRow:r,col:i,row:a}=t,o={sheetId:e,col:i,row:a},s={sheetId:e,col:n,row:r};if(this.getters.isInMerge(o)&&!this.getters.isInMerge(s)){let t=this.getters.getMerge(o);t&&this.dispatch(`REMOVE_MERGE`,{sheetId:e,target:[t]})}let c=this.getters.getMerge(s);c?.left===n&&c?.top===r&&this.dispatch(`ADD_MERGE`,{sheetId:e,target:[{top:a,bottom:a+c.bottom-c.top,left:i,right:i+c.right-c.left}]})}drawLayer(e){if(!this.autofillZone)return;let{ctx:t,thinLineWidth:n}=e,{x:r,y:i,width:a,height:o}=this.getters.getVisibleRect(this.autofillZone);a>0&&o>0&&(t.strokeStyle=`black`,t.lineWidth=n,t.setLineDash([3]),t.strokeRect(r,i,a,o),t.setLineDash([]))}},TU=class extends SU{static getters=[`getAutomaticSums`];handle(e){switch(e.type){case`SUM_SELECTION`:let e=this.getters.getActiveSheetId(),{zones:t,anchor:n}=this.getters.getSelection();for(let r of t){let t=this.getAutomaticSums(e,r,n.cell);this.dispatchCellUpdates(e,t)}break}}getAutomaticSums(e,t,n){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,n):this.sumData(e,t)}sumData(e,t){let n=this.dimensionsToSum(e,t),r=this.sumDimensions(e,t,n).filter(({zone:t})=>!this.getters.isEmpty(e,t));return n.has(`ROW`)&&n.has(`COL`)&&r.push(this.sumTotal(t)),r}sumAdjacentData(e,t,n){let{col:r,row:i}=ks(n.col,n.row,t)?n:{col:t.left,row:t.top},a=this.findAdjacentData(e,r,i);return a?this.getters.isSingleCellOrMerge(e,t)||Ms(Cs(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,Cs(a,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,n){let r=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.findSuitableZoneToSum(r,i.col,i.row);if(a)return this.getters.expandZone(e,a)}findSuitableZoneToSum(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:n-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:n});if(this.isNumber(i)&&!this.isNumber(r))return this.findHorizontalZone(e,t,n);let a=this.findVerticalZone(e,t,n);if(this.isZoneValid(a))return a;let o=this.findHorizontalZone(e,t,n);if(this.isZoneValid(o))return o}findVerticalZone(e,t,n){let r={top:0,bottom:n-1,left:t,right:t},i=this.reduceZoneStart(e,r,r.bottom);return{...r,top:i}}findHorizontalZone(e,t,n){let r={top:n,bottom:n,left:0,right:t-1},i=this.reduceZoneStart(e,r,r.right);return{...r,left:i}}reduceZoneStart(e,t,n){let r=this.getters.getEvaluatedCellsInZone(e.id,t),i=S(n,-1,-1),a=Jt(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=ft(i.filter(e=>this.isNumber(r[e])))[0]||[];return Jt(o)<a?1/0:Yt(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&So(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){let n=new Set;return Ms(t)?(n.add(js(t).numberOfCols===1?`COL`:`ROW`),n):(this.lastColIsEmpty(e,t)&&n.add(`ROW`),this.lastRowIsEmpty(e,t)&&n.add(`COL`),n.size===0&&n.add(`COL`),n)}sumDimensions(e,t,n){return[...n.has(`COL`)?this.sumColumns(t,e):[],...n.has(`ROW`)?this.sumRows(t,e):[]]}sumTotal(e){let{bottom:t,right:n}=e;return{position:{col:n,row:t},zone:{...e,top:t,right:n-1}}}sumColumns(e,t){let n=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,n.bottom-1)},Fs(n).map(t=>({position:t,zone:{...e,right:t.col,left:t.col}}))}sumRows(e,t){let n=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,n.right-1)},Fs(n).map(t=>({position:t,zone:{...e,top:t.row,bottom:t.row}}))}dispatchCellUpdates(e,t){for(let n of t){let{col:t,row:r}=n.position;this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:`=SUM(${this.getters.zoneToXC(e,n.zone)})`})}}nextEmptyRow(e,t){let n=t.bottom+1,{left:r,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:n,top:n,left:r,right:i});)n++;return{...t,top:n,bottom:n}}nextEmptyCol(e,t){let n=t.right+1,{top:r,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:n,right:n,top:r,bottom:i});)n++;return{...t,left:n,right:n}}transpose(e){return new Set([...e.values()].map(e=>e===`COL`?`ROW`:`COL`))}};let EU=new class extends g{addTransformation(e,t,n){this.content[e]||(this.content[e]=new Map);for(let r of t)this.content[e].set(r,n);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}},DU=new class extends g{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};EU.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],RU),EU.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],RU),EU.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],jU),EU.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`],MU),EU.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],NU),EU.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],PU),EU.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],FU),EU.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],FU),EU.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],IU),EU.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],IU),EU.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],LU),EU.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],zU),EU.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],zU),EU.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],AU),EU.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],kU),EU.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],OU),EU.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],OU);function OU(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=Id(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function kU(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function AU(e,t){if(e.pivotId!==t.pivotId)return e}function jU(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function MU(e,t){if(e.figureId!==t.figureId)return e}function NU(e,t){return e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`}),e.name===t.name?{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,e=>(parseInt(e)+1).toString()):`${e.name}~`,position:e.position+1}:e}function PU(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!Ds(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function FU(e,t){if(e.sheetId!==t.sheetId||(e.type===`FREEZE_COLUMNS`?`COL`:`ROW`)!==t.dimension)return e;let n=e.quantity;if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);for(let t of e)n>t&&n--}if(t.type===`ADD_COLUMNS_ROWS`){let e=t.position===`before`?t.base-1:t.base;n=n>e?n+t.quantity:n}return n>0?{...e,quantity:n}:void 0}function IU(e,t){if(e.sheetId!==t.sheetId)return e;let n=Id(e.zone,t);if(!n)return;let r=e.newTableRange?Ld(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function LU(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:Rk.styleId}}:e}function RU(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=Wc(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=Uc(jt(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function zU(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n=S(e.start,e.end+1),r=[];if(t.type===`REMOVE_COLUMNS_ROWS`?r=Wc(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=Uc(jt(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}function BU(e,t){let n=e.content&&lS(e.sheetId,e.content,t);return{...e,content:n}}DU.add(`UPDATE_CELL`,BU);function VU(e,t){let n=e.cf.rule;if(e={...e,cf:{...e.cf}},n.type===`CellIsRule`)e.cf.rule={...n,values:n.values.map(n=>lS(e.sheetId,n,t))};else if(n.type===`ColorScaleRule`){let{minimum:r,maximum:i,midpoint:a}=n;e.cf.rule={...n,minimum:{...r,value:r.value&&lS(e.sheetId,r.value,t)},maximum:{...i,value:i.value&&lS(e.sheetId,i.value,t)},midpoint:a?{...a,value:lS(e.sheetId,a.value,t)}:void 0}}else if(n.type===`IconSetRule`){let{upperInflectionPoint:r,lowerInflectionPoint:i}=n;e.cf.rule={...n,upperInflectionPoint:{...r,value:lS(e.sheetId,r.value,t)},lowerInflectionPoint:{...i,value:lS(e.sheetId,i.value,t)}}}else n.type===`DataBarRule`&&(e.cf.rule={...n,rangeValues:n.rangeValues?uS(e.sheetId,n.rangeValues,t).range:void 0});return e}DU.add(`ADD_CONDITIONAL_FORMAT`,VU);function HU(e,t){return e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}},e.rule.criterion.values=e.rule.criterion.values.map(n=>lS(e.sheetId,n,t)),e}DU.add(`ADD_DATA_VALIDATION_RULE`,HU);function UU(e,t){return e=b(e),e.pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=lS(e.computedBy.sheetId,e.computedBy.formula,t))}),e}DU.add(`ADD_PIVOT`,UU),DU.add(`UPDATE_PIVOT`,UU),DU.add(`CREATE_CHART`,WU),DU.add(`UPDATE_CHART`,WU);function WU(e,t){return{...e,definition:yD(e.sheetId,e.definition,t)}}let GU=[{match:or,fn:XU},{match:cr,fn:ZU},{match:dr,fn:QU},{match:ur,fn:tW},{match:sr,fn:eW},{match:lr,fn:$U}];function KU(e,t){let n=EU.getTransformation(e.type,t.type),r=n?n(e,t):YU(e,t);return r&&qU(r,t)}function qU(e,t){let n=DU.get(e.type);if(!n)return e;let r=jc(t);return r?n(e,r):e}function JU(e,t){let n=[...e],r=new Set(EU.getKeys());for(let e of t)(r.has(e.type)||Mc.contains(e.type))&&(n=n.reduce((t,n)=>{let r=KU(n,e);return r&&t.push(r),t},[]));return n}function YU(e,t){for(let{match:n,fn:r}of GU)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function XU(e,t){if(!(`sheetId`in t))return e;let n=t.type===`DELETE_SHEET`&&t.sheetId;return e.sheetId===n?`IGNORE_COMMAND`:e.type===`CREATE_SHEET`||t.type===`CREATE_SHEET`||e.sheetId!==t.sheetId?e:`SKIP_TRANSFORMATION`}function ZU(e,t){let n=XU(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=Id(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function QU(e,t){let n=XU(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=Id(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function $U(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>Ld(e,t)).filter(C);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function eW(e,t){let n=XU(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;if(t.type!==`ADD_COLUMNS_ROWS`&&t.type!==`REMOVE_COLUMNS_ROWS`)return`SKIP_TRANSFORMATION`;if(t.dimension!==e.dimension)return e;let r=[];return t.type===`REMOVE_COLUMNS_ROWS`?r=Wc(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=Uc(jt(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function tW(e,t){let n=XU(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?nW(e,t):t.type===`ADD_MERGE`?rW(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function nW(e,t){let n=t.dimension===`COL`?`col`:`row`,r=e[n];if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);if(e.includes(r))return`IGNORE_COMMAND`;for(let t of e)r>=t&&r--}return t.type===`ADD_COLUMNS_ROWS`&&(r>t.base||r===t.base&&t.position===`before`)&&(r+=t.quantity),{...e,[n]:r}}function rW(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&ks(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var iW=class{id;clientId;_commands=[];_changes=[];constructor(e,t,n,r,i,a){this.rootCommand=r,this.timestamp=a,this.id=e,this.clientId=t,this._commands=[...n],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}},aW=class extends Error{},oW=class extends Rd{clients={};clientId=`local`;debouncedMove;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new gl;lastLocalOperation;constructor(e,t,n=We){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.debouncedMove=Et(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new iW(this.uuidGenerator.uuidv4(),this.clientId,t,e,n,Date.now());this.revisions.append(r.id,r),e.type!==`REQUEST_REDO`&&(this.lastLocalOperation=r),this.trigger(`new-local-state-update`,{id:r.id}),this.sendUpdateMessage({type:`REMOTE_REVISION`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:r.id,clientId:r.clientId,commands:r.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_UNDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:`local`,name:`local`},this.clientId=`local`),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this)),this.awaitingClientPosition&&=(this._move(this.awaitingClientPosition),void 0)}loadInitialMessages(e){let t=performance.now(),n=e.reduce((e,t)=>e+(t.type===`REMOTE_REVISION`?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(let t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug(`Replayed`,n,`commands in`,performance.now()-t,`ms`)}async leave(e){e&&Object.keys(this.clients).length===1&&this.lastRevisionMessage&&this.lastRevisionMessage?.type!==`SNAPSHOT_CREATED`&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:`CLIENT_LEFT`,clientId:this.clientId,version:1})}async snapshot(e){if(this.pendingMessages.length!==0)return;let t=this.uuidGenerator.uuidv4();await this.transportService.sendMessage({type:`SNAPSHOT`,nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getCurrentClient(){return this.getClient(this.clientId)}getClient(e){let t=this.clients[e];if(!t)throw new aW(`The client left the session`);return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(C))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return this.pendingMessages.length===0}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId]){this.awaitingClientPosition=e;return}let t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;let n=t?`CLIENT_MOVED`:`CLIENT_JOINED`,r=this.getCurrentClient();this.clients[this.clientId]={...r,position:e},this.transportService.sendMessage({type:n,version:1,client:{...r,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){if(this.isWrongServerRevisionId(e)){this.trigger(`unexpected-revision-id`);return}switch(e.type){case`CLIENT_MOVED`:this.onClientMoved(e);break;case`CLIENT_JOINED`:this.onClientJoined(e);break;case`CLIENT_LEFT`:this.onClientLeft(e);break;case`REVISION_REDONE`:this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-redone`,{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case`REVISION_UNDONE`:this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-undone`,{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case`REMOTE_REVISION`:let{clientId:t,commands:n,timestamp:r}=e,i=new iW(e.nextRevisionId,t,n,void 0,void 0,r);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);let t=this.pendingMessages.filter(e=>e.type===`REMOTE_REVISION`).map(e=>e.commands).flat();this.trigger(`remote-revision-received`,{commands:JU(n,t)})}break;case`SNAPSHOT_CREATED`:{let t=new iW(e.nextRevisionId,`server`,[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger(`snapshot`),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger(`collaborative-event-received`)}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;let t=this.clients[this.clientId];if(t){let{position:e}=t;e&&this.transportService.sendMessage({type:`CLIENT_MOVED`,version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),!this.waitingAck&&this.sendPendingMessage()}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if(e.type===`REMOTE_REVISION`){let t=this.revisions.get(e.nextRevisionId);t.commands.length===0&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.
|
|
1947
|
+
`;var eH=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:vk};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getExpandedTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(N(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${pd(e,i).join(`,`)})`,value:L(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{let{value:r,format:o}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${pd(e,i).join(`,`)})`,value:L(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}n.push(t)}let r=n[n.length-1];return n[n.length-1]=r.map(e=>(e.isMissing||(e.style=`color: #756f6f;`),e)),n}_buildRowHeaders(e,t){let n=[];for(let r of t.rows){let t=[];for(let e=0;e<r.fields.length;e++)t.push({value:r.fields[e]},{value:r.values[e]});let i=this.pivot.parseArgsToPivotDomain(t),{value:a,format:o}=this.pivot.getPivotHeaderValueAndFormat(i),s=this.env.model.getters.getLocale(),c={formula:`=PIVOT.HEADER(${pd(e,i).join(`,`)})`,value:L(a,{format:o,locale:s}),isMissing:!this.tracker?.isHeaderPresent(i)};r.indent>1&&(c.style=`padding-left: ${r.indent-10}px`),n.push(c)}return n}_buildValues(e,t){let n=[];for(let r of t.columns.at(-1)||[]){let i=[],a=N(r.values[r.values.length-1]);for(let n of t.rows){let t=[];for(let e=0;e<n.fields.length;e++)t.push({value:n.fields[e]},{value:n.values[e]});for(let e=0;e<r.fields.length-1;e++)t.push({value:r.fields[e]},{value:r.values[e]});let o=this.pivot.parseArgsToPivotDomain(t),{value:s,format:c}=this.pivot.getPivotCellValueAndFormat(a,o),l=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${pd(e,o,a).join(`,`)})`,value:L(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},tH=class{static getters=[];history;constructor(e){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}})}exportForExcel(e){}allowDispatch(e){return`Success`}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map(e=>e.call(this,t)).flat()}chainValidations(...e){return t=>{for(let n of e){let e=n.call(this,t);Array.isArray(e)||(e=[e]);let r=e.filter(e=>e!==`Success`);if(r.length)return r}return`Success`}}checkValidations(e,...t){return this.batchValidations(...t)(e)}},nH=class extends tH{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i}){super(t),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=r,this.canDispatch=i}import(e){}export(e){}adaptRanges(e,t,n){}garbageCollectExternalResources(){}},rH=class extends nH{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return`Success`}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>b(e)));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Ue.style,color:e.border.color||Ue.color})}break;case`CLEAR_FORMATTING`:this.clearBorders(e.sheetId,e.target);break;case`REMOVE_COLUMNS_ROWS`:let r=[...e.elements].sort((e,t)=>t-e);for(let t of ft(r))if(e.dimension===`COL`){let n=this.getters.getColsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{let n=this.getters.getRowsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r=this.borders[e]?.[t]?.[n];return r?.top||r?.bottom||r?.left||r?.right?b(r):null}getBordersColors(e){let t=[],n=this.borders[e];if(n){for(let e of n.filter(C))for(let n of e)if(n)for(let e of[`top`,`bottom`,`left`,`right`]){let r=n[e]?.color;r&&t.push(r)}}return t}ensureColumnBorderContinuity(e,t,n){let r=S(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=S(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&w(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(C);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?S(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n){this.borders[e]&&this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfColumn(e,t,n)})}shiftBordersVertically(e,t,n){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfRow(e,t,n)}))}moveBordersOfRow(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getColumnsWithBorders(e).forEach(a=>{let o=i[a]?.[t+n],s=i[a]?.[t];this.history.update(`borders`,e,a,t+n,r?s:s||o),this.history.update(`borders`,e,a,t,void 0)})}moveBordersOfColumn(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getRowsRange(e).forEach(a=>{let o=i[t+n]?.[a],s=i[t]?.[a];this.history.update(`borders`,e,t+n,a,r?s:s||o),r&&this.history.update(`borders`,e,t,a,void 0)})}setBorder(e,t,n,r,i=!0){let a=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;(i||!this.borders[e]?.[t]?.[n]?.left)&&(this.history.update(`borders`,e,t,n,`left`,r?.left),r?.left&&t>0&&!w(this.borders[e]?.[t-1]?.[n]?.right,r?.left)&&this.history.update(`borders`,e,t-1,n,`right`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.top)&&(this.history.update(`borders`,e,t,n,`top`,r?.top),r?.top&&n>0&&!w(this.borders[e]?.[t]?.[n-1]?.bottom,r?.top)&&this.history.update(`borders`,e,t,n-1,`bottom`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.right)&&(this.history.update(`borders`,e,t,n,`right`,r?.right),r?.right&&t<a&&!w(this.borders[e]?.[t+1]?.[n]?.left,r?.right)&&this.history.update(`borders`,e,t+1,n,`left`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.bottom)&&(this.history.update(`borders`,e,t,n,`bottom`,r?.bottom),r?.bottom&&n<o&&!w(this.borders[e]?.[t]?.[n+1]?.top,r?.bottom)&&this.history.update(`borders`,e,t,n+1,`top`,void 0))}clearBorders(e,t,n=!1){let r=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;for(let a of R(t))for(let t=a.top;t<=a.bottom;t++){n&&(a.left>0&&this.history.update(`borders`,e,a.left-1,t,`right`,void 0),a.right<r&&this.history.update(`borders`,e,a.right+1,t,`left`,void 0));for(let r=a.left;r<=a.right;r++)this.history.update(`borders`,e,r,t,void 0),n&&(a.top>0&&this.history.update(`borders`,e,r,a.top-1,`bottom`,void 0),a.bottom<i&&this.history.update(`borders`,e,r,a.bottom+1,`top`,void 0))}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t,!0);for(let i of R(t)){if(n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r,right:r,bottom:r,left:r});if(n===`h`||n===`hv`){if(i.top===i.bottom)continue;for(let t=i.left;t<=i.right;t++){this.addBorder(e,t,i.top,{bottom:r});for(let n=i.top+1;n<i.bottom;n++)this.addBorder(e,t,n,{top:r,bottom:r});this.addBorder(e,t,i.bottom,{top:r})}}if(n===`v`||n===`hv`){if(i.left===i.right)continue;for(let t=i.top;t<=i.bottom;t++){this.addBorder(e,i.left,t,{right:r});for(let n=i.left+1;n<i.right;n++)this.addBorder(e,n,t,{left:r,right:r});this.addBorder(e,i.right,t,{left:r})}}if(n===`left`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right,t,{right:r});if(n===`top`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom,{bottom:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||w(t,e.border)?`NoChanges`:`Success`}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let[n,r]of rc(t.id,t.borders)){let{sheetId:t,col:i,row:a}=n,o=e.borders[r];this.setBorder(t,i,a,o,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,ps(e))}export(e){let t={};for(let n of e.sheets){let e={};for(let r=0;r<n.colNumber;r++)for(let i=0;i<n.rowNumber;i++){let a=this.getCellBorder({sheetId:n.id,col:r,row:i});if(a){let o=tc(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=nc(e)}e.borders=t}exportForExcel(e){this.export(e)}},iH=class extends nH{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellStyle`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges({applyChange:e},t,n){for(let r of Object.keys(this.cells))for(let i of Object.values(this.cells[r]||{}))if(i.isFormula){for(let a of i.compiledFormula.dependencies)if(a.sheetId===t||a.invalidSheetName===n.old){let t=e(a);t.changeType!==`NONE`&&this.history.update(`cells`,r,i.id,`compiledFormula`,`dependencies`,i.compiledFormula.dependencies.indexOf(a),t.range)}}}allowDispatch(e){switch(e.type){case`UPDATE_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case`CLEAR_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case`UPDATE_CELL_POSITION`:return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?`Success`:`InvalidCellId`;default:return`Success`}}handle(e){switch(e.type){case`SET_FORMATTING`:`style`in e&&this.setStyle(e.sheetId,e.target,e.style),`format`in e&&e.format!==void 0&&this.setFormatter(e.sheetId,e.target,e.format);break;case`CLEAR_FORMATTING`:this.clearFormatting(e.sheetId,e.target);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,style:null,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of R(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n=this.getters.getCell({sheetId:e,col:t,row:r});(n?.isFormula||n?.content)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}}setFormatter(e,t,n){for(let r of R(t))for(let t=r.top;t<=r.bottom;t++)for(let i=r.left;i<=r.right;i++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:i,row:t,format:n})}clearFormatting(e,t){for(let n of R(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,style:null,format:``})}clearCells(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:``,style:null,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=S(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=S(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){for(let t of e.sheets){let n=t.id,r=new SP;for(let e in t.cells)if(t.cells[e]){let{col:n,row:i}=Zn(e),a={sheetId:t.id,col:n,row:i};r.set(a,{content:t.cells[e]})}for(let[e,n]of[[`style`,t.styles],[`format`,t.formats]])for(let[i,a]of rc(t.id,n)){let t=r.get(i);t?t[e]=a:r.set(i,{[e]:a})}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format||n?.style){let r=this.importCell(t.id,n?.content,n?.style?e.styles[n?.style]:void 0,n?.format?e.formats[n?.format]:void 0);this.history.update(`cells`,t.id,r.id,r),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:r.id,...i})}}}}export(e){let t={},n={};for(let r of e.sheets){let e=[],i=[],a={},o=Object.keys(this.cells[r.id]||{}).map(e=>this.getters.getCellPosition(e)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let r of o){let o=this.getters.getCell(r),s=T(r.col,r.row),c=this.extractCustomStyle(o);if(Object.keys(c).length){let n=tc(c,t);e[n]??=[],e[n].push(r)}if(o.format){let e=tc(o.format,n);i[e]??=[],i[e].push(r)}o.content&&(a[s]=o.content)}r.styles=nc(e),r.formats=nc(i),r.cells=a}e.styles=t,e.formats=n}importCell(e,t,n,r){let i=this.getNextUid();return this.createCell(i,t||``,r,n,e)}exportForExcel(e){this.export(e);let t=[];for(let n in e.formats||[])Uo(e.formats[n])||(t.push(Number(n)),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.formats){let r=n.formats[e];r&&t.includes(r)&&delete n.formats[e]}}extractCustomStyle(e){let t={...e.style},n=Pi(e.content,D)?Re:Le;for(let r in t)(r!==`align`||!e.isFormula)&&t[r]===n[r]&&delete t[r];return t}getCells(e){return this.cells[e]||{}}getCellById(e){let t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,n,r=!1){if(!n.length)return Ot(t.map(e=>e.value));let i=0;return Ot(t.map(t=>{if(t.type===`REFERENCE`){let t=n[i++];return this.getters.getRangeString(t,e,{useBoundedReference:r})}return t.value}))}getTranslatedCellFormula(e,t,n,r){let i=this.getters.createAdaptedRanges($x(r).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t,n){let r=$x(n).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),i=this.getters.removeRangesSheetPrefix(t,r);return this.getFormulaString(t,n,i)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=T(t.left,t.top,n[0]),i=T(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}setStyle(e,t,n){for(let r of R(t))for(let t=r.left;t<=r.right;t++)for(let i=r.top;i<=r.bottom;i++){let r=this.getters.getCell({sheetId:e,col:t,row:i});this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:i,style:n?{...r?.style,...n}:void 0})}}copyColumnStyle(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowStyle(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:r,row:t,...i})}}getFormat(e,t,n){let r={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.getters.getCell(i);return a&&(a.style&&(r.style=a.style),a.format&&(r.format=a.format)),r}getNextUid(){let e=this.nextId.toString();return this.history.update(`nextId`,this.nextId+1),e}updateCell(e,t,n,r){let i=this.getters.getCell({sheetId:e,col:t,row:n}),a=r.content!==void 0||`formula`in r,o=a?zt(r?.content||void 0):i?.content||``,s;s=r.style===void 0?i?i.style:void 0:r.style||void 0;let c=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||i.content===``))&&!s&&!c){i&&(this.history.update(`cells`,e,i.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let l=i?.id||this.getNextUid(),u=this.createCell(l,o,c,s,e);this.history.update(`cells`,e,u.id,u),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:u.id,col:t,row:n,sheetId:e})}createCell(e,t,n,r,i){return t.startsWith(`=`)?this.createFormulaCell(e,t,n,r,i):this.createLiteralCell(e,t,n,r)}createLiteralCell(e,t,n,r){let i=this.getters.getLocale(),a=Ko(t,i);return n||=typeof a==`number`?Do(t,i)||Oo(t):void 0,!Wo(n)&&!j(t)&&(t=N(a)),{id:e,content:t,style:r,format:n,isFormula:!1,parsedValue:a}}createFormulaCell(e,t,n,r,i){let a=Qx(t);return a.dependencies.length?this.createFormulaCellWithDependencies(e,a,n,r,i):{id:e,content:t,style:r,format:n,isFormula:!0,compiledFormula:{...a,dependencies:[]}}}createFormulaCellWithDependencies(e,t,n,r,i){let a=[];for(let e of t.dependencies)a.push(this.getters.getRangeFromSheetXC(i,e));return new aH(e,t,n,r,a,i,this.getters.getRangeString)}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?ks(n,r,this.getters.getSheetZone(t))?`Success`:`TargetOutOfSheet`:`InvalidSheetId`}checkUselessClearCell(e){let t=this.getters.getCell(e);return!t||!t.content&&!t.style&&!t.format?`NoChanges`:`Success`}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=`format`in e;return(!n||t?.content===e.content)&&(!r||w(t?.style,e.style))&&(!i||t?.format===e.format)?`NoChanges`:`Success`}},aH=class{id;format;style;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,n,r,i,a,o){this.id=e,this.format=n,this.style=r,this.sheetId=a,this.getRangeString=o;let s=0,c=t.tokens.map(e=>e.type===`REFERENCE`?new oH(i,s++,this.sheetId,this.getRangeString):e);this.compiledFormula={...t,dependencies:i,tokens:c}}get content(){return Ot(this.compiledFormula.tokens.map(e=>e.value))}get contentWithFixedReferences(){let e=0;return Ot(this.compiledFormula.tokens.map(t=>{if(t.type===`REFERENCE`){let t=e++;return this.getRangeString(this.compiledFormula.dependencies[t],this.sheetId,{useBoundedReference:!0})}return t.value}))}},oH=class{ranges;rangeIndex;sheetId;getRangeString;type=`REFERENCE`;constructor(e,t,n,r){this.ranges=e,this.rangeIndex=t,this.sheetId=n,this.getRangeString=r}get value(){let e=this.ranges[this.rangeIndex];return this.getRangeString(e,this.sheetId)}},sH=class extends nH{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getContextCreationChart`];charts={};createChart=gD(this.getters);validateChartDefinition=e=>vD(this,e.definition);adaptRanges(e){for(let[t,n]of Object.entries(this.charts))this.history.update(`charts`,t,n?.updateRanges(e))}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case`UPDATE_CHART`:return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists,this.checkChartChanged));default:return`Success`}}handle(e){switch(e.type){case`CREATE_CHART`:this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.addChart(e.figureId,e.definition);break;case`UPDATE_CHART`:this.addChart(e.figureId,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`chart`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.charts[n.id]?.duplicateInDuplicatedSheet(e.sheetIdTo);i&&this.dispatch(`CREATE_CHART`,{figureId:r,col:n.col,row:n.row,offset:n.offset,size:{width:n.width,height:n.height},definition:i.getDefinition(),sheetId:e.sheetIdTo})}break}case`DELETE_FIGURE`:this.history.update(`charts`,e.figureId,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){let t=this.charts[e]?.type;if(!t)throw Error(`Chart not defined.`);return t}isChartDefined(e){return e in this.charts&&this.charts!==void 0}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.getDefinition();if(!t)throw Error(`There is no chart with the given figureId: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)e.tag===`chart`&&(this.charts[e.id]=this.createChart(e.id,e.data,t.id))}export(e){if(e.sheets)for(let t of e.sheets){let e=this.getters.getFigures(t.id),n=[];for(let t of e){let e=t;if(e&&e.tag===`chart`){let t=this.charts[e.id]?.getDefinition();t&&(e.data=t,n.push(e))}else n.push(e)}t.figures=n}}addFigure(e,t,n,r,i,a={width:536,height:335}){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`chart`})}addChart(e,t){let n=this.getters.getFigureSheetId(e);n&&this.history.update(`charts`,e,this.createChart(e,t,n))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.figureId)?`DuplicatedChartId`:`Success`}checkChartExists(e){return this.isChartDefined(e.figureId)?`Success`:`ChartDoesNotExist`}checkChartChanged(e){return w(this.getChartDefinition(e.figureId),e.definition)?`NoChanges`:`Success`}};function cH(e){return e===``?NaN:Number(e)}var lH=class extends nH{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};adaptCFFormulas({applyChange:e,adaptFormulaString:t}){for(let n in this.cfRules)for(let r of this.cfRules[n])if(r.rule.type===`DataBarRule`&&r.rule.rangeValues){let t=e(r.rule.rangeValues);switch(t.changeType){case`REMOVE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,t.range);break}}else if(r.rule.type===`CellIsRule`)for(let e=0;e<r.rule.values.length;e++)this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`values`,e,t(n,r.rule.values[e]));else if(r.rule.type===`IconSetRule`)for(let e of[`lowerInflectionPoint`,`upperInflectionPoint`])r.rule[e].type===`formula`&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,r.rule[e].value));else if(r.rule.type===`ColorScaleRule`)for(let e of[`minimum`,`maximum`,`midpoint`]){let i=r.rule[e];i?.type===`formula`&&i?.value&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,i.value))}}adaptCFRanges(e,{applyChange:t}){for(let n of this.cfRules[e])for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}adaptRanges(e,t){let n=t?[t]:Object.keys(this.cfRules);for(let t of n)this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)ks(t,n,e.zone)&&r.push(i);return new Set(r.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,n,r){if(n.length===0&&r.length===0)return;let i=this.getters.getConditionalFormats(e),a=i.findIndex(e=>e.id===t.id),o=[];a>-1&&(o=i[a].ranges.map(fs));let s=R(o,r);return R([...n,...s],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:n}={useBoundedReference:!1}){let r=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:n}));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:n})},ranges:r}:{...t,rule:{...t.rule},ranges:r}}mapToConditionalFormatInternal(e,t){let n=t.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:n}:{...t,rule:{...t.rule},ranges:n}}addConditionalFormatting(e,t){let n=this.cfRules[t].slice(),r=n.findIndex(t=>t.id===e.id),i=this.mapToConditionalFormatInternal(t,e);r>-1?n.splice(r,1,i):n.push(i),this.history.update(`cfRules`,t,n)}checkValidPriorityChange(e,t,n){if(!this.cfRules[n])return`InvalidSheetId`;let r=this.cfRules[n].findIndex(t=>t.id===e);if(r===-1)return`InvalidConditionalFormatId`;let i=r-t;return i<0||i>=this.cfRules[n].length?`InvalidConditionalFormatId`:`Success`}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}checkCFRule(e){let t=e.cf.rule;switch(t.type){case`CellIsRule`:return wr.has(t.operator)?this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues):`InvalidConditionalFormatType`;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return`Success`}return`InvalidConditionalFormatType`}checkCFHasChanged(e){let t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))}),n=this.cfRules[e.sheetId]?.find(t=>t.id===e.cf.id);return n&&w(t,n)?`NoChanges`:`Success`}checkOperatorArgsNumber(e){let t=Y.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(t===void 0||t>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);let n=[],r=e=>e===void 0||e===``;return t>=1&&r(e.values[0])&&n.push(`FirstArgMissing`),t>=2&&r(e.values[1])&&n.push(`SecondArgMissing`),n.length?n:`Success`}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return`MinNaN`;case`max`:return`MaxNaN`;case`mid`:return`MidNaN`;case`upperInflectionPoint`:return`ValueUpperInflectionNaN`;case`lowerInflectionPoint`:return`ValueLowerInflectionNaN`}return`Success`}checkFormulaCompilation(e,t){if(e.type!==`formula`)return`Success`;if(Qx(e.value||``).isBadExpression)switch(t){case`min`:return`MinInvalidFormula`;case`max`:return`MaxInvalidFormula`;case`mid`:return`MidInvalidFormula`;case`upperInflectionPoint`:return`ValueUpperInvalidFormula`;case`lowerInflectionPoint`:return`ValueLowerInvalidFormula`}return`Success`}checkThresholds(e){return this.batchValidations(t=>e(t.minimum,`min`),t=>e(t.maximum,`max`),t=>t.midpoint?e(t.midpoint,`mid`):`Success`)}checkInflectionPoints(e){return this.batchValidations(t=>e(t.lowerInflectionPoint,`lowerInflectionPoint`),t=>e(t.upperInflectionPoint,`upperInflectionPoint`))}checkLowerBiggerThanUpper(e){let t=e.lowerInflectionPoint.value,n=e.upperInflectionPoint.value;return[`number`,`percentage`,`percentile`].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(n)?`LowerBiggerThanUpper`:`Success`}checkMinBiggerThanMax(e){let t=e.minimum.value,n=e.maximum.value;return[`number`,`percentage`,`percentile`].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&cH(t)>=cH(n)?`MinBiggerThanMax`:`Success`}checkMidBiggerThanMax(e){let t=e.midpoint?.value,n=e.maximum.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&cH(t)>=cH(n)?`MidBiggerThanMax`:`Success`}checkMinBiggerThanMid(e){let t=e.minimum.value,n=e.midpoint?.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&cH(t)>=cH(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&Qx(t||``).isBadExpression)return`ValueCellIsInvalidFormula`;return`Success`}removeConditionalFormatting(e,t){let n=this.cfRules[t].findIndex(t=>t.id===e);if(n!==-1){let e=this.cfRules[t].slice();e.splice(n,1),this.history.update(`cfRules`,t,e)}}changeCFPriority(e,t,n){let r=this.cfRules[n].findIndex(t=>t.id===e),i=this.cfRules[n][r],a=r-t,o=[...this.cfRules[n]];o.splice(r,1),o.splice(a,0,i),this.history.update(`cfRules`,n,o)}},uH=class extends nH{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e,t){this.adaptDVRanges(t,e),this.adaptDVFormulas(e)}adaptDVFormulas({adaptFormulaString:e}){for(let t in this.rules){let n=this.rules[t];for(let r=n.length-1;r>=0;r--){let n=this.rules[t][r];for(let i=0;i<n.criterion.values.length;i++){let a=e(t,n.criterion.values[i]);this.history.update(`rules`,t,r,`criterion`,`values`,i,a)}}}}adaptDVRanges(e,{applyChange:t}){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return!this.getters.tryGetSheet(e.sheetId)||e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid));case`REMOVE_DATA_VALIDATION_RULE`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;if(!this.rules[e.sheetId].find(t=>t.id===e.id))return`UnknownDataValidationRule`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=b(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>Ec(e.sheetId,e.sheetIdTo,t))}));this.history.update(`rules`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.rules};delete t[e.sheetId],this.history.update(`rules`,t);break}case`REMOVE_DATA_VALIDATION_RULE`:this.removeDataValidationRule(e.sheetId,e.id);break;case`ADD_DATA_VALIDATION_RULE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case`DELETE_CONTENT`:{let t=R(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(e&&(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!this.getters.getCell({sheetId:n,col:r,row:t})?.content)){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,T(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(ks(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&(t.criterion.displayStyle===`arrow`||t.criterion.displayStyle===`chip`):!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=b(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of Oc(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:e?.style?.align??`center`,verticalAlign:e?.style?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...b(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return Y.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=Y.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=Y.get(t.type);return t.values.some(e=>n.allowedValues===`onlyFormulas`&&!e.startsWith(`=`)?!0:e.startsWith(`=`)?n.allowedValues===`onlyLiterals`||Qx(e).isBadExpression:!n.isCriterionValueValid(e))?`InvalidDataValidationCriterionValue`:`Success`}checkValidRange(e){return e.ranges.map(e=>this.getters.getRangeFromRangeData(e)).map(t=>this.getters.getRangeString(t,e.sheetId)).some(e=>!this.getters.isRangeValid(e))?`InvalidRange`:`Success`}},dH=class extends nH{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];adaptRanges({applyChange:e},t){for(let n of this.getFigures(t)){let r=e(this.getters.getRangeFromZone(t,{left:n.col,right:n.col,top:n.row,bottom:n.row}));if(r.changeType===`MOVE`)this.history.update(`figures`,t,n.id,`col`,r.range.zone.right),this.history.update(`figures`,t,n.id,`row`,r.range.zone.bottom);else if(r.changeType===`REMOVE`){let r=e(this.getters.getRangeFromZone(t,{left:0,right:n.col-1,top:0,bottom:n.row-1})),{offset:i,col:a,row:o}=n;r.changeType!==`NONE`&&(a=r.range.zone.right+1,o=r.range.zone.bottom+1),{offset:i,col:a,row:o}=this.getPositionInSheet(t,{...n,col:a,row:o}),this.history.update(`figures`,t,n.id,`offset`,i),this.history.update(`figures`,t,n.id,`col`,a),this.history.update(`figures`,t,n.id,`row`,o)}}}allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case`UPDATE_FIGURE`:return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case`DELETE_FIGURE`:return this.checkFigureExists(e);default:return`Success`}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{figureId:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:let t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case`UPDATE_FIGURE`:this.updateFigure(e);break;case`DELETE_FIGURE`:this.removeFigure(e.figureId,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break}}onColRemove(e){let t=this.getters.getNumberCols(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+this.getters.getColSize(e,r);for(let t of this.getFigures(e))if(t.offset.x+t.width>n[t.col]){let r=t.offset.x,i=t.col;for(r=Math.min(r,n[i]-t.width);r<0&&i>0;)i--,r=n[i]-t.width;r!==t.offset.x&&this.history.update(`figures`,e,t.id,`offset`,{x:Math.max(r,0),y:t.offset.y}),i!==t.col&&this.history.update(`figures`,e,t.id,`col`,i)}}onRowRemove(e){let t=this.getters.getNumberRows(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+(this.getters.getUserRowSize(e,r)??23);for(let t of this.getFigures(e))if(t.offset.y+t.height>n[t.row]){let r=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??23;t<r;t=this.getters.getUserRowSize(e,i)??23)i+=1,r-=t;for(r=Math.min(r,n[i]-t.height);r<0&&i>0;)i--,r=n[i]-t.height;r!==t.offset.y&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(0,r)}),i!==t.row&&this.history.update(`figures`,e,t.id,`row`,i)}else t.offset.y+t.height>n[0]&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(n[0]-t.height,0)})}getPositionInSheet(e,t){let{numberOfRows:n,numberOfCols:r}=this.getters.getSheetSize(e),i=0,a=0,o,s,{col:c,row:l}=t,u={...t.offset};for(o=n;i<t.height&&o>0;o--)i+=this.getters.getUserRowSize(e,o-1)??23;for(l>o?(l=o,u.y=Math.max(i-t.height,0)):l===o&&(u.y=x(u.y,0,Math.max(i-t.height,0))),s=r;a<t.width&&s>0;s--)a+=this.getters.getColSize(e,s-1);return c>s?(c=s,u.x=Math.max(a-t.width,0)):s===c&&(u.x=x(u.x,0,Math.max(a-t.width,0))),{col:c,row:l,offset:u}}updateFigure(e){if(!(`figureId`in e)||!(`sheetId`in e))return;let{figureId:t,sheetId:n,...r}=e,i={...this.getFigure(n,t),...r};for(let[e,t]of Object.entries(r))switch(e){case`offset`:this.history.update(`figures`,n,i.id,e,t);break;case`col`:case`row`:case`width`:case`height`:t!==void 0&&this.history.update(`figures`,n,i.id,e,t);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e){return this.figures[e.sheetId]?.[e.figureId]===void 0?`FigureDoesNotExist`:`Success`}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e.figureId])?`DuplicatedFigureId`:`Success`}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?`WrongSheetPosition`:`Success`}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){return this.export(e)}},fH=class extends nH{static getters=[`getUserRowSize`,`getColSize`];sizes={};handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`sizes`,e.sheetId,{COL:Array(this.getters.getNumberCols(e.sheetId)).fill(void 0),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(void 0)});break;case`DUPLICATE_SHEET`:this.history.update(`sizes`,e.sheetIdTo,b(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ht(t,e.elements);this.history.update(`sizes`,e.sheetId,e.dimension,n);break}case`ADD_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=jt(e.position,e.base),r=t[e.base],i=Ut(t,Array(e.quantity).fill(r),n);this.history.update(`sizes`,e.sheetId,e.dimension,i);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of S(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of S(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},pH=class extends nH{static getters=[`checkElementsIncludeAllVisibleHeaders`,`getHiddenColsGroups`,`getHiddenRowsGroups`,`isHeaderHiddenByUser`,`isRowHiddenByUser`,`isColHiddenByUser`];hiddenHeaders={};allowDispatch(e){switch(e.type){case`HIDE_COLUMNS_ROWS`:{if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=e.dimension===`COL`?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),n=e.dimension===`COL`?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=n?`TooManyHiddenElements`:Yt(e.elements)<0||Jt(e.elements)>n?`InvalidHeaderIndex`:`Success`}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`:`InvalidSheetId`}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,b(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=jt(e.position,e.base),n=Ut([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,n);break}case`HIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!0);break;case`UNHIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!1);break}}checkElementsIncludeAllVisibleHeaders(e,t,n){return Nt(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=S(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...S(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},mH=class extends nH{static getters=[`getImage`,`getImagePath`,`getImageSize`];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){switch(e.type){case`CREATE_IMAGE`:return this.getters.getFigure(e.sheetId,e.figureId)?`InvalidFigureId`:`Success`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_IMAGE`:this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:b(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}garbageCollectExternalResources(){let e=new Set(this.getAllImages().map(e=>e.path));for(let t of this.syncedImages)e.has(t)||this.fileStore?.delete(t)}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,n,r,i,a){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`image`})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:b(e)})}t.images=[...t.images,...n]}}getAllImages(){let e=[];for(let t in this.images)e.push(...Object.values(this.images[t]||{}).filter(C));return e}},hH=class extends nH{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`getSelectionRangeString`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(C))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e,t){this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(C)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(C)}getSelectionRangeString(e,t){let n=this.getters.expandZone(e.sheetId,e.zone),r=bc({...e,zone:{...n,bottom:Cc(e)?void 0:n.bottom,right:wc(e)?void 0:n.right}},this.getters.getSheetSize),i=this.getters.getRangeString(r,t);if(this.isSingleCellOrMerge(e.sheetId,e.zone)){let{sheetName:e,xc:t}=vc(i);return yc(e,t.split(`:`)[0])}return i}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(Ds(t,n))return!0;return!1}doesColumnsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(r.id,t,i,n,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(r.id,i,t,i,n))return!0;return!1}expandZone(e,t){let{left:n,right:r,top:i,bottom:a}=t,o={left:n,right:r,top:i,bottom:a};for(let t in this.merges[e]){let n=this.getMergeById(e,parseInt(t));n&&Ds(n,o)&&(o=Cs(n,o))}return Es(o,t)?o:this.expandZone(e,o)}isInSameMerge(e,t,n,r,i){let a=this.getMerge({sheetId:e,col:t,row:n}),o=this.getMerge({sheetId:e,col:r,row:i});return!a||!o?!1:Es(a,o)}isInMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e];return r?t in r&&!!r[t]?.[n]:!1}getMainCellPosition(e){let t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){let n=this.getters.getHiddenColsGroups(e),r=this.getters.getHiddenRowsGroups(e);for(let e of n)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of r)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){let n=this.getMerge({sheetId:e,col:t.left,row:t.top});if(n)return Es(t,n);let{numberOfCols:r,numberOfRows:i}=js(t);return r===1&&i===1}isMainCellPosition(e){return w(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=x(r,0,this.getters.getNumberCols(e)-1),a=x(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&n.content!==``)return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:_H(t,n)}checkDestructiveMerge({sheetId:e,target:t}){return this.getters.tryGetSheet(e)&&t.some(t=>this.isMergeDestructive(e,t))?`MergeIsDestructive`:`Success`}checkOverlap({target:e}){for(let t of e)for(let n of e)if(t!==n&&Ds(t,n))return`MergeOverlap`;return`Success`}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return`Success`;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);return Ks(t,n,r)?`FrozenPaneOverlap`:`Success`}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return`Success`;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?`Success`:`CellIsMerged`}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!Es(e,i))return`InvalidTarget`}return`Success`}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=x(r,0,this.getters.getNumberCols(e)-1),a=x(a,0,this.getters.getNumberRows(e)-1),T(n,i)===T(r,a))return;let o=this.getters.getCell({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,vs({left:n,top:i,right:r,bottom:a})));let c=new Set;for(let t=i;t<=a;t++)for(let a=n;a<=r;a++){(a!==n||t!==i)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:t,style:o?o.style:null,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&c.add(r.id),this.history.update(`mergeCellMap`,e,a,t,s)}for(let t of c){let{top:n,bottom:r,left:i,right:a}=this.getMergeById(e,t);for(let t=n;t<=r;t++)for(let n=i;n<=a;n++){let r={sheetId:e,col:n,row:t},i=this.getMerge(r);(!i||i.id!==s)&&(this.history.update(`mergeCellMap`,e,n,t,void 0),this.dispatch(`CLEAR_CELL`,r))}this.history.update(`merges`,e,t,void 0)}}removeMerge(e,t){let{left:n,top:r,bottom:i,right:a}=t,o=this.getMerge({sheetId:e,col:n,row:r});if(!(o===void 0||!Es(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,{applyChange:t}){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=js(a.range.zone);t===1&&i===1?this.removeMerge(e,n):this.history.update(`merges`,e,parseInt(r,10),a.range);break}}this.history.update(`mergeCellMap`,e,{});for(let t of this.getMerges(e))for(let{col:n,row:r}of Fs(t))this.history.update(`mergeCellMap`,e,n,r,t.id)}import(e){let t=e.sheets||[];for(let e of t)this.history.update(`merges`,e.id,{}),this.history.update(`mergeCellMap`,e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let n of t)this.addMerge(e,ps(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...gH(e))}}exportForExcel(e){this.export(e)}};function gH(e){return Object.entries(e).map(([e,t])=>t?_H(parseInt(e,10),t):void 0).filter(C).map(e=>T(e.left,e.top)+`:`+T(e.right,e.bottom))}function _H(e,t){return{...t.zone,id:e}}var vH=class{getters;providers=[];isAdaptingRanges=!1;constructor(e){this.getters=e}static getters=[`copyFormulaStringForSheet`,`extendRange`,`getRangeString`,`getRangeFromSheetXC`,`createAdaptedRanges`,`getRangeData`,`getRangeDataFromXc`,`getRangeDataFromZone`,`getRangeFromRangeData`,`getRangeFromZone`,`getRangesUnion`,`recomputeRanges`,`isRangeValid`,`removeRangesSheetPrefix`];allowDispatch(e){return e.type===`MOVE_RANGES`?e.target.length===1?`Success`:`InvalidZones`:`Success`}beforeHandle(e){}handle(e){if(this.isAdaptingRanges)throw Error(`Plugins cannot dispatch commands during adaptRanges phase`);let t=jc(e);t&&this.executeOnAllRanges(t)}finalize(){}verifyRangeRemoved(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!gs(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}executeOnAllRanges(e){this.isAdaptingRanges=!0;let t={applyChange:this.verifyRangeRemoved(e.applyChange),adaptRangeString:(t,n)=>uS(t,n,e),adaptFormulaString:(t,n)=>lS(t,n,e)};for(let n of this.providers)n(t,e.sheetId,e.sheetName);this.isAdaptingRanges=!1}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,n,r){return e.map(e=>{if(!gs(e.zone))return e;let i=e.prefixSheet?e.sheetId:r,a=wc(e),o=Cc(e),s={...e.unboundedZone,left:a&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:a?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:o&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:n),bottom:o?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:n)};return Ac(bc({...e,sheetId:i,zone:s},this.getters.getSheetSize))})}removeRangesSheetPrefix(e,t){return t.map(t=>t.prefixSheet&&t.sheetId===e?{...t,prefixSheet:!1}:t)}extendRange(e,t,n){let r=t===`COL`?e.zone.right+n:e.zone.right,i=t===`ROW`?e.zone.bottom+n:e.zone.bottom,a={left:e.zone.left,top:e.zone.top,right:wc(e)?void 0:r,bottom:Cc(e)?void 0:i};return bc({...e,zone:a},this.getters.getSheetSize)}getRangeFromSheetXC(e,t){if(!fc.test(t)||!this.getters.tryGetSheet(e))return Sc(t);let{sheetName:n}=vc(t);return xc({xc:t,sheetId:this.getters.getSheetIdByName(n)||e,invalidSheetName:n&&!this.getters.getSheetIdByName(n)?n:void 0},this.getters.getSheetSize)}getRangeString(e,t,n={useBoundedReference:!1,useFixedReference:!1}){return e?e.invalidXc?e.invalidXc:this.getters.tryGetSheet(e.sheetId)?Tc(e,t,this.getters.getSheetName,n):k.InvalidReference:k.InvalidReference}getRangeDataFromXc(e,t){let n=this.getters.getRangeFromSheetXC(e,t);return this.getRangeDataFromZone(n.sheetId,n.unboundedZone)}getRangeDataFromZone(e,t){return t=this.getters.getUnboundedZone(e,t),{_sheetId:e,_zone:t}}getRangeData(e){return this.getRangeDataFromZone(e.sheetId,e.unboundedZone)}getRangeFromZone(e,t){return bc({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){return R(e.map(e=>e.unboundedZone),t.map(e=>e.unboundedZone)).map(t=>this.getRangeFromZone(e[0].sheetId,t))}getRangeFromRangeData(e){return this.getters.tryGetSheet(e._sheetId)?bc({prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]},this.getters.getSheetSize):Sc(k.InvalidReference)}isRangeValid(e){if(!e)return!1;let{xc:t,sheetName:n}=vc(e);return t.match(fc)!==null&&(!n||this.getters.getSheetIdByName(n)!==void 0)}getRangesUnion(e){let t=ws(...e.map(e=>e.unboundedZone));return this.getRangeFromZone(e[0].sheetId,t)}copyFormulaStringForSheet(e,t,n,r){if(!n.startsWith(`=`))return n;let i=Qx(n),a=i.dependencies.map(n=>{let i=this.getters.getRangeFromSheetXC(e,n);return r===`keepSameReference`?i:Ec(e,t,i)});return this.getters.getFormulaString(t,i.tokens,a)}},yH=class extends nH{static getters=`getSheetName.tryGetSheetName.getSheet.tryGetSheet.getSheetIdByName.getSheetIds.getVisibleSheetIds.isSheetVisible.doesHeaderExist.doesHeadersExist.getCell.getCellPosition.getColsZone.getRowCells.getRowsZone.getNumberCols.getNumberRows.getNumberHeaders.getGridLinesVisibility.getNextSheetName.getSheetSize.getSheetZone.getPaneDivisions.checkZonesExistInSheet.getCommandZones.getUnboundedZone.checkElementsIncludeAllNonFrozenHeaders.getDuplicateSheetName`.split(`.`);sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){let t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if(t!==`Success`)return t;switch(e.type){case`HIDE_SHEET`:return this.getVisibleSheetIds().length===1?`NotEnoughSheets`:`Success`;case`CREATE_SHEET`:return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case`DUPLICATE_SHEET`:return this.sheets[e.sheetIdTo]?`DuplicatedSheetId`:this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?`DuplicatedSheetName`:`Success`;case`MOVE_SHEET`:try{let t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),`Success`}catch{return`WrongSheetMove`}case`RENAME_SHEET`:return this.isRenameAllowed(e);case`COLOR_SHEET`:return!e.color||cn(e.color)?`Success`:`InvalidColor`;case`DELETE_SHEET`:return this.getVisibleSheetIds().length>1?`Success`:`NotEnoughSheets`;case`ADD_COLUMNS_ROWS`:return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?`InvalidQuantity`:`Success`:`InvalidHeaderIndex`;case`REMOVE_COLUMNS_ROWS`:{let t=Yt(e.elements),n=Jt(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,n)?`InvalidHeaderIndex`:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`}case`FREEZE_ROWS`:return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case`FREEZE_COLUMNS`:return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return`Success`}}handle(e){switch(e.type){case`SET_GRID_LINES_VISIBILITY`:this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case`CREATE_SHEET`:let t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update(`sheetIdsMapName`,t.name,t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.newName);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case`UPDATE_CELL_POSITION`:this.updateCellPosition(e);break;case`FREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,e.quantity,`COL`);break;case`FREEZE_ROWS`:this.setPaneDivisions(e.sheetId,e.quantity,`ROW`);break;case`UNFREEZE_ROWS`:this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`UNFREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,0,`COL`);break;case`UNFREEZE_COLUMNS_ROWS`:this.setPaneDivisions(e.sheetId,0,`COL`),this.setPaneDivisions(e.sheetId,0,`ROW`)}}import(e){for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let t of e.sheets){let e=t.name||`Sheet`+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:Hc(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(C).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e){let t=ct(e);for(let e in this.sheetIdsMapName)if(qc(e,t))return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(C)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return Gc(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(t.bottom===void 0||t.right===void 0)return t;let n=t.left===0&&t.right===this.getNumberCols(e)-1,r=t.top===0&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:r?void 0:t.bottom,right:n&&!r?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,n){let r={...this.getPaneDivisions(e)};n===`COL`?r.xSplit=t:n===`ROW`&&(r.ySplit=t),this.history.update(`sheets`,e,`panes`,r)}checkElementsIncludeAllNonFrozenHeaders(e,t,n){let r=this.getters.getPaneDivisions(e),i=t===`ROW`?r.ySplit:r.xSplit,a=this.getters.getNumberHeaders(e,t);return i?Nt(n,S(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&e.col!==void 0&&`row`in e&&e.row!==void 0&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(gs))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>As(e,n))?`Success`:`TargetOutOfSheet`}return`Success`}updateCellPosition(e){let{sheetId:t,cellId:n,col:r,row:i}=e;n?this.setNewPosition(n,t,r,i):this.clearPosition(t,r,i)}setNewPosition(e,t,n,r){let i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update(`cellPosition`,e,{row:r,col:n,sheetId:t}),this.history.update(`sheets`,t,`rows`,r,`cells`,n,e)}clearPosition(e,t,n){let r=this.sheets[e]?.rows[n].cells[t];r&&(this.history.update(`cellPosition`,r,void 0),this.history.update(`sheets`,e,`rows`,n,`cells`,t,void 0))}setGridLinesVisibility(e,t){this.history.update(`sheets`,e,`areGridLinesVisible`,t)}createSheet(e,t,n,r,i){let a={id:e,name:t,numberOfCols:n,rows:Hc(r),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},o=this.orderedSheetIds.slice();o.splice(i,0,a.id);let s=this.sheets;return this.history.update(`orderedSheetIds`,o),this.history.update(`sheets`,Object.assign({},s,{[a.id]:a})),a}moveSheet(e,t){let n=this.orderedSheetIds.slice(),r=n.findIndex(t=>t===e),i=n.splice(r,1),a=this.findIndexOfTargetSheet(r,t);n.splice(a,0,i[0]),this.history.update(`orderedSheetIds`,n)}findIndexOfTargetSheet(e,t){for(;t!==0&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(t===0)return e;throw Error(`There is not enough visible sheets`)}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId),n=e.type===`RENAME_SHEET`?e.newName:e.name;if(t!==void 0&&n===t)return`UnchangedSheetName`;let{orderedSheetIds:r,sheets:i}=this,a=n&&n.trim().toLowerCase();return r.find(t=>qc(i[t]?.name,a)&&t!==e.sheetId)?`DuplicatedSheetName`:Xe.test(a)?`ForbiddenCharactersInSheetName`:`Success`}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?`WrongSheetPosition`:`Success`}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return`MergeOverlap`;return`Success`}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return`MergeOverlap`;return`Success`}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):`MissingSheetName`}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[n],r[t]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=b(this.getSheet(e));r.id=t,r.name=n;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{col:e,row:n}=this.getCellPosition(t.id);this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:e,row:n,content:t.content,format:t.format,style:t.style})}let o=Object.assign({},this.sheetIdsMapName);o[r.name]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return Kc(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){let t=e.name,n=Object.assign({},this.sheets);delete n[e.id],this.history.update(`sheets`,n);let r=this.orderedSheetIds.slice(),i=r.indexOf(e.id);r.splice(i,1),this.history.update(`orderedSheetIds`,r);let a=Object.assign({},this.sheetIdsMapName);delete a[t],this.history.update(`sheetIdsMapName`,a)}removeColumns(e,t){t.sort((e,t)=>t-e);for(let n of t)this.moveCellOnColumnsDeletion(e,n);let n=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,n-t.length);let r=t.filter(t=>t<e.panes.xSplit).length;r&&this.setPaneDivisions(e.id,e.panes.xSplit-r,`COL`)}removeRows(e,t){t.sort((e,t)=>t-e);for(let n of ft(t)){let t=n[n.length-1],r=n[0];this.moveCellOnRowsDeletion(e,t,r),this.updateRowsStructureOnDeletion(e,t,r)}let n=t.filter(t=>t<e.panes.ySplit).length;n&&this.setPaneDivisions(e.id,e.panes.ySplit-n,`ROW`)}addColumns(e,t,n,r){let i=n===`before`?t:t+1;this.moveCellsOnAddition(e,i,r,`columns`);let a=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,a+r),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+r,`COL`)}addRows(e,t,n,r){let i=n===`before`?t:t+1;this.addEmptyRows(e,r),this.moveCellsOnAddition(e,i,r,`rows`),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+r,`ROW`)}moveCellOnColumnsDeletion(e,t){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let n=0;n<e.rows.length;n++){let r=e.rows[n];for(let i in r.cells){let a=Number(i),o=r.cells[i];o&&a>t&&this.setNewPosition(o,e.id,a-1,n)}}}moveCellsOnAddition(e,t,n,r){let i=[];for(let a=0;a<e.rows.length;a++){let o=e.rows[a];if(r!==`rows`||a>=t)for(let s in o.cells){let c=Number(s),l=o.cells[s];l&&(r===`rows`||c>=t)&&i.push({sheetId:e.id,cellId:l,col:c+(r===`columns`?n:0),row:a+(r===`rows`?n:0),type:`UPDATE_CELL_POSITION`})}}for(let e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,n){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:n}]});let r=n-t+1;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(t>n)for(let n in i.cells){let a=Number(n),o=i.cells[n];o&&this.setNewPosition(o,e.id,a,t-r)}}}updateRowsStructureOnDeletion(e,t,n){let r=[],i=e.rows.map(e=>e.cells).reverse();for(let a in e.rows){let e=Number(a);e>=t&&e<=n||r.push({cells:i.pop()})}this.history.update(`sheets`,e.id,`rows`,r)}addEmptyRows(e,t){let n=e.rows.slice();for(let e=0;e<t;e++)n.push({cells:{}});this.history.update(`sheets`,e.id,`rows`,n)}getImportedSheetSize(e){let t=Object.keys(e.cells).map(Zn),n=e.rowNumber,r=e.colNumber;for(let{col:e,row:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?`InvalidSheetId`:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?`DuplicatedSheetId`:`Success`}checkZonesAreInSheet(e){return`sheetId`in e?`ranges`in e&&e.ranges.some(e=>e._sheetId!==``&&!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},bH=class extends nH{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};nextTableId=1;adaptRanges({applyChange:e},t){for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return`InvalidSheetId`;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return Js(t)?this.checkValidations(e,e=>this.getTablesOverlappingZones(e.sheetId,t).length?`TableOverlap`:`Success`,e=>this.checkTableConfigUpdateIsValid(e.config)):`NonContinuousTargets`;case`UPDATE_TABLE`:return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,e=>this.checkTableConfigUpdateIsValid(e.config)):`TableNotFound`;case`ADD_MERGE`:for(let t of this.getCoreTables(e.sheetId)){let n=t.range.zone;for(let t of e.target)if(Ds(n,t))return`MergeInTable`}break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{});break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.consumeNextId(),a=e.config||Rk,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!Ts(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t);break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>As(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(C):[]}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>ks(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>Ds(e.range.zone,t)))}extendTableDown(e,t){let n=this.getters.extendRange(t.range,`ROW`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}extendTableRight(e,t){let n=this.getters.extendRange(t.range,`COL`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:n,row:r},i){if(!e)return`none`;let a=i.range.zone,o=`none`;if(a.bottom+1===r&&n>=a.left&&n<=a.right?o=`down`:a.right+1===n&&r>=a.top&&r<=a.bottom&&(o=`right`),o===`none`)return`none`;let s=o===`down`?{...a,bottom:a.bottom+1,top:a.bottom+1}:{...a,right:a.right+1,left:a.right+1};for(let e=s.top;e<=s.bottom;e++)for(let n=s.left;n<=s.right;n++){let r={sheetId:t,col:n,row:e};if(this.getters.getCell(r)?.content||this.getters.isInMerge(r)||this.getTablesOverlappingZones(t,[z(r)]).length)return`none`}return o}getCoreTableMatchingTopLeft(e,t){for(let n of this.getCoreTables(e)){let e=n.range.zone;if(e.left===t.left&&e.top===t.top)return n}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return`Success`;let t=this.getters.getRangeFromRangeData(e.newTableRange).zone,n=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if(n!==`Success`)return n;let r=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);return r?this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==r.id).length?`TableOverlap`:`Success`:`TableNotFound`}checkTableConfigUpdateIsValid(e){return e&&(e.numberOfHeaders!==void 0&&e.numberOfHeaders<0||e.hasFilters&&e.numberOfHeaders===0)?`InvalidTableConfig`:`Success`}createStaticTable(e,t,n,r,i){let a=n.zone;if(!i){i=[];for(let e of S(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.consumeNextId();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=Vs(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of S(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.consumeNextId();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,Vs(t.zone)):e.range,i=n||e.config;return{...e,range:r,config:i}}updateTableConfig(e,t){if(!e)return t;let n={...t,...e};return e.numberOfHeaders===0?n.hasFilters=!1:e.hasFilters===!0&&(n.numberOfHeaders||=1),n}createFilterFromZone(e,t,n,r){return tF(e,this.getters.getRangeFromZone(t,n),r,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone),r=t.filters.map(n=>{let r=this.getters.getRangeFromZone(e,n.rangeWithHeaders.zone);return tF(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:b(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:b(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=tF(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<js(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.consumeNextId(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}consumeNextId(){let e=`${this.nextTableId}`;return this.history.update(`nextTableId`,this.nextTableId+1),e}import(e){for(let t of e.sheets)for(let e of t.tables||[]){let n=this.consumeNextId(),r=e.config||Rk,i=this.getters.getRangeFromSheetXC(t.id,e.range),a=e.type||`static`,o=a===`dynamic`?this.createDynamicTable(n,i,r):this.createStaticTable(n,a,i,r);this.history.update(`tables`,t.id,o.id,o)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:vs(e.range.zone),type:e.type};w(e.config,Rk)||(n.config=e.config),t.tables.push(n)}}exportForExcel(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n=vs(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},xH=class extends nH{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return`HeaderGroupAlreadyExists`;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return`UnknownHeaderGroup`;if(S(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return`NotEnoughElements`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=b(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=jt(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&S(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Bt([t.end,e]))t.end++;else{let t={start:e,end:e};s[n].push(t)}}}for(let e of s)for(let t of e)t.isFolded=i[this.getGroupId(t)];return s}groupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}unGroupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,-1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}moveGroupsOnHeaderInsertion(e,t,n,r){let i=this.groups[e][t];for(let a=0;a<i.length;a++){let o=i[a],[s,c]=Uc(n,r,[o.start,o.end]);(s!==o.start||c!==o.end)&&this.history.update(`groups`,e,t,a,{...o,start:s,end:c})}}moveGroupsOnHeaderDeletion(e,t,n){let r=this.getHeaderGroups(e,t),i=[];for(let e of r){let t=Wc(n,S(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=OA(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=OA(t,e,n.end+1);r.collapsed=!0}}}}}},SH=class extends nH{static getters=[`getPivotCoreDefinition`,`getPivotDisplayName`,`getPivotId`,`getPivotFormulaId`,`getPivotIds`,`getMeasureCompiledFormula`,`getPivotName`,`isExistingPivot`,`getMeasureFullDependencies`];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case`ADD_PIVOT`:return this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?w(e.pivot,this.pivots[e.pivotId]?.definition)?`NoChanges`:e.pivot.name===``?`EmptyName`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures):`PivotIdNotFound`;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;if(e.name===``)return`EmptyName`;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;break;case`DUPLICATE_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`}return`Success`}handle(e){switch(e.type){case`ADD_PIVOT`:{let{pivotId:t,pivot:n}=e;this.addPivot(t,n);break}case`INSERT_PIVOT`:{let{sheetId:t,col:n,row:r,pivotId:i,table:a}=e,o={sheetId:t,col:n,row:r},{cols:s,rows:c,measures:l,fieldsType:u}=a,d=new iV(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=b(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,b(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break}}adaptRanges({applyChange:e,adaptFormulaString:t}){for(let t in this.pivots){let n=b(this.pivots[t]?.definition);if(!n)continue;let r=bV.get(n.type)?.adaptRanges?.(this.getters,n,e);r&&!w(n,r)&&this.history.update(`pivots`,t,`definition`,r)}for(let n in this.compiledMeasureFormulas)for(let r in this.compiledMeasureFormulas[n]){let i=this.pivots[n]?.definition.measures.find(e=>e.id===r);if(!i||!i.computedBy)continue;let a=i.computedBy.sheetId,{formula:o,dependencies:s}=this.compiledMeasureFormulas[n][r];this.history.update(`compiledMeasureFormulas`,n,r,`formula`,`dependencies`,o.dependencies.map(t=>e(t).range)),this.history.update(`compiledMeasureFormulas`,n,i.id,`dependencies`,s.map(t=>e(t).range));let c=i.computedBy.formula,l=t(a,c);l!==c&&this.replaceMeasureFormula(n,i,l)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:b(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=this.compileMeasureFormula(n.computedBy.sheetId,n.computedBy.formula);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.tokens){if(o.type!==`SYMBOL`)continue;let a=i.measures.find(e=>ut(e.id)===o.value&&t.id!==e.id);!a||n.has(a.id)||!a.computedBy||r.push(...this.computeMeasureFullDependencies(e,a,n))}return r.push(...a.dependencies.filter(e=>!e.invalidXc)),r}insertPivot(e,t,n){this.resizeSheet(e.sheetId,e,n);let r=n.getPivotCells();for(let n=0;n<r.length;n++)for(let i=0;i<r[n].length;i++){let a=r[n][i];this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col+n,row:e.row+i,content:hd(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}compileMeasureFormula(e,t){let n=Qx(t),r=n.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return{...n,dependencies:r}}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId})}checkSortedColumnInMeasures(e){let t=e.measures.map(e=>e.id);return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?`InvalidDefinition`:`Success`}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?`Success`:`InvalidDefinition`}import(e){if(e.pivots)for(let[t,n]of Object.entries(e.pivots))this.addPivot(t,n,n.formulaId);this.history.update(`nextFormulaId`,e.pivotNextId||cd(this.pivots)+1)}export(e){e.pivots={};for(let t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}},CH=class extends nH{static getters=[`getLocale`];locale=D;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return ql(e.locale)?`Success`:`InvalidLocale`}return`Success`}handle(e){switch(e.type){case`UPDATE_LOCALE`:let t=this.locale,n=e.locale;this.history.update(`locale`,n),this.changeCellsDateFormatWithLocale(t,n);break}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(let n of this.getters.getSheetIds())for(let[r,i]of Object.entries(this.getters.getCells(n))){let n;if(i.format===e.dateFormat&&(n=t.dateFormat),i.format===e.timeFormat&&(n=t.timeFormat),i.format===uu(e)&&(n=uu(t)),n){let{col:e,row:t,sheetId:i}=this.getters.getCellPosition(r);this.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:i,format:n})}}}import(e){this.locale=e.settings?.locale??D}export(e){e.settings={locale:this.locale}}},wH=class extends nH{allowDispatch(e){switch(e.type){case`ADD_PIVOT`:case`UPDATE_PIVOT`:let t=e.pivot;return this.checkDataSetValidity(t)}return`Success`}checkDataSetValidity(e){if(e.type===`SPREADSHEET`&&e.dataSet){let{zone:t,sheetId:n}=e.dataSet;return!n||!this.getters.tryGetSheet(n)||!t||!gs(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},TH=class extends nH{static getters=[`getNewCustomTableStyleName`,`getTableStyle`,`getTableStyles`,`isTableStyleEditable`];styles={};allowDispatch(e){switch(e.type){case`CREATE_TABLE`:case`UPDATE_TABLE`:if(e.config?.styleId&&!this.styles[e.config.styleId])return`InvalidTableConfig`;break;case`CREATE_TABLE_STYLE`:if(!$k[e.templateName])return`InvalidTableStyle`;try{sn(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=eA(e.tableStyleName,e.templateName,e.primaryColor);this.history.update(`styles`,e.tableStyleId,t);break;case`REMOVE_TABLE_STYLE`:let n={...this.styles};delete n[e.tableStyleId],this.history.update(`styles`,n);for(let t of this.getters.getSheetIds())for(let n of this.getters.getCoreTables(t))n.config.styleId===e.tableStyleId&&this.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{styleId:Rk.styleId}});break}}getTableStyle(e){if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return $t(E(`Custom Table Style`),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!Qk[e]}import(e){for(let e in Qk)this.styles[e]=Qk[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=eA(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)Qk[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},EH=class extends tH{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}};let DH=new g;DH.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let OH=Ix.mapping;function kH(e,t,n){return new AH(e,t,n).getParameters()}var AH=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(OH),e,{getters:this.getters,locale:this.getters.getLocale()})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e,t){let n=this.getRangeError(e);if(n)return n;if(t)return{value:yc(this.getters.getSheetName(e.sheetId),vs(e.zone))};let r={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};return this.computeCell(r)}range(e){let t=this.getRangeError(e);if(t)return[[t]];let n=e.sheetId,r=e.zone,i=Ts(r,this.getters.getSheetZone(n));if(!i)return[[]];let{top:a,left:o,bottom:s,right:c}=r,l=`${n}-${a}-${o}-${s}-${c}`;if(l in this.rangeCache)return this.rangeCache[l];let u=i.bottom-i.top+1,d=i.right-i.left+1,f=Array(d);for(let e=i.left;e<=i.right;e++){let t=e-i.left;f[t]=Array(u);for(let r=i.top;r<=i.bottom;r++){let a=r-i.top;f[t][a]=this.computeCell({sheetId:n,col:e,row:r})}}return this.rangeCache[l]=f,f}getRangeError(e){if(!gs(e.zone))return new Vi;if(e.invalidSheetName)return new A(E(`Invalid sheet name: %s`,e.invalidSheetName))}},jH=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n||=self).RBush=r()})(e,function(){"use strict";function e(e,r,i,a,o){(function e(n,r,i,a,o){for(;a>i;){if(a-i>600){var s=a-i+1,c=r-i+1,l=Math.log(s),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(s-u)/s)*(c-s/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-c*u/s+d)),Math.min(a,Math.floor(r+(s-c)*u/s+d)),o)}var f=n[r],p=i,m=a;for(t(n,i,r),o(n[a],f)>0&&t(n,i,a);p<m;){for(t(n,p,m),p++,m--;o(n[p],f)<0;)p++;for(;o(n[m],f)>0;)m--}o(n[i],f)===0?t(n,i,m):t(n,++m,a),m<=r&&(i=m+1),r<=m&&(a=m-1)}})(e,r,i||0,a||e.length-1,o||n)}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:+(e>t)}var r=function(e){e===void 0&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function i(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1}function a(e,t){o(e,0,e.children.length,t,e)}function o(e,t,n,r,i){i||=m(null),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(var a=t;a<n;a++){var o=e.children[a];s(i,e.leaf?r(o):o)}return i}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function c(e,t){return e.minX-t.minX}function l(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function d(e){return e.maxX-e.minX+(e.maxY-e.minY)}function f(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function p(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function m(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function h(t,n,r,i,a){for(var o=[n,r];o.length;)if(!((r=o.pop())-(n=o.pop())<=i)){var s=n+Math.ceil((r-n)/i/2)*i;e(t,s,n,r,a),o.push(n,s,s,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(e){var t=this.data,n=[];if(!p(e,t))return n;for(var r=this.toBBox,i=[];t;){for(var a=0;a<t.children.length;a++){var o=t.children[a],s=t.leaf?r(o):o;p(e,s)&&(t.leaf?n.push(o):f(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n},r.prototype.collides=function(e){var t=this.data;if(!p(e,t))return!1;for(var n=[];t;){for(var r=0;r<t.children.length;r++){var i=t.children[r],a=t.leaf?this.toBBox(i):i;if(p(e,a)){if(t.leaf||f(e,a))return!0;n.push(i)}}t=n.pop()}return!1},r.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){var r=this.data;this.data=n,n=r}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this},r.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},r.prototype.clear=function(){return this.data=m([]),this},r.prototype.remove=function(e,t){if(!e)return this;for(var n,r,a,o=this.data,s=this.toBBox(e),c=[],l=[];o||c.length;){if(o||(o=c.pop(),r=c[c.length-1],n=l.pop(),a=!0),o.leaf){var u=i(e,o.children,t);if(u!==-1)return o.children.splice(u,1),c.push(o),this._condense(c),this}a||o.leaf||!f(o,s)?r?(n++,o=r.children[n],a=!1):o=null:(c.push(o),l.push(n),n=0,r=o,o=o.children[0])}return this},r.prototype.toBBox=function(e){return e},r.prototype.compareMinX=function(e,t){return e.minX-t.minX},r.prototype.compareMinY=function(e,t){return e.minY-t.minY},r.prototype.toJSON=function(){return this.data},r.prototype.fromJSON=function(e){return this.data=e,this},r.prototype._all=function(e,t){for(var n=[];e;)e.leaf?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},r.prototype._build=function(e,t,n,r){var i,o=n-t+1,s=this._maxEntries;if(o<=s)return a(i=m(e.slice(t,n+1)),this.toBBox),i;r||(r=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/s**(r-1))),(i=m([])).leaf=!1,i.height=r;var c=Math.ceil(o/s),l=c*Math.ceil(Math.sqrt(s));h(e,t,n,l,this.compareMinX);for(var u=t;u<=n;u+=l){var d=Math.min(u+l-1,n);h(e,u,d,c,this.compareMinY);for(var f=u;f<=d;f+=c){var p=Math.min(f+c-1,d);i.children.push(this._build(e,f,p,r-1))}}return a(i,this.toBBox),i},r.prototype._chooseSubtree=function(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){for(var i=1/0,a=1/0,o=void 0,s=0;s<t.children.length;s++){var c=t.children[s],l=u(c),d=(f=e,p=c,(Math.max(p.maxX,f.maxX)-Math.min(p.minX,f.minX))*(Math.max(p.maxY,f.maxY)-Math.min(p.minY,f.minY))-l);d<a?(a=d,i=l<i?l:i,o=c):d===a&&l<i&&(i=l,o=c)}t=o||t.children[0]}var f,p;return t},r.prototype._insert=function(e,t,n){var r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),s(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)},r.prototype._split=function(e,t){var n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=m(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,a(n,this.toBBox),a(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)},r.prototype._splitRoot=function(e,t){this.data=m([e,t]),this.data.height=e.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(e,t,n){for(var r,i,a,s,c,l,d,f=1/0,p=1/0,m=t;m<=n-t;m++){var h=o(e,0,m,this.toBBox),g=o(e,m,n,this.toBBox),_=(i=h,a=g,s=void 0,c=void 0,l=void 0,d=void 0,s=Math.max(i.minX,a.minX),c=Math.max(i.minY,a.minY),l=Math.min(i.maxX,a.maxX),d=Math.min(i.maxY,a.maxY),Math.max(0,l-s)*Math.max(0,d-c)),v=u(h)+u(g);_<f?(f=_,r=m,p=v<p?v:p):_===f&&v<p&&(p=v,r=m)}return r||n-t},r.prototype._chooseSplitAxis=function(e,t,n){var r=e.leaf?this.compareMinX:c,i=e.leaf?this.compareMinY:l;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)},r.prototype._allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=this.toBBox,a=o(e,0,t,i),c=o(e,n-t,n,i),l=d(a)+d(c),u=t;u<n-t;u++){var f=e.children[u];s(a,e.leaf?i(f):f),l+=d(a)}for(var p=n-t-1;p>=t;p--){var m=e.children[p];s(c,e.leaf?i(m):m),l+=d(c)}return l},r.prototype._adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)s(t[r],e)},r.prototype._condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)e[t].children.length===0?t>0?(n=e[t-1].children).splice(n.indexOf(e[t]),1):this.clear():a(e[t],this.toBBox)},r})}))(),1),MH=class{rTrees={};constructor(e=[]){let t={};for(let n of e){let e=n.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(n)}for(let e in t)this.rTrees[e]=new NH,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new NH),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&w(e.data,t.data)}},NH=class extends jH.default{toBBox({boundingBox:e}){let t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}},PH=class{createEmptyPositionSet;dependencies=new SP;rTree;constructor(e,t=[]){this.createEmptyPositionSet=e,this.rTree=new MH(t)}removeAllDependencies(e){let t=this.dependencies.get(e);if(t){for(let e of t)this.rTree.remove(e);this.dependencies.delete(e)}}addDependencies(e,t){let n=t.map(({sheetId:t,zone:n})=>({data:e,boundingBox:{zone:n,sheetId:t}}));for(let e of n)this.rTree.insert(e);let r=this.dependencies.get(e);r?r.push(...n):this.dependencies.set(e,n)}getCellsDependingOn(e,t){let n=this.createEmptyPositionSet(),r=Array.from(e).reverse();for(;r.length>0;){let e=r.pop(),i=e.zone,a=e.sheetId;for(let e=i.left;e<=i.right;e++)for(let t=i.top;t<=i.bottom;t++)n.add({sheetId:a,col:e,row:t});let o=this.rTree.search(e).map(e=>e.data),s={};for(let e of o)!n.has(e)&&!t.has(e)&&(s[e.sheetId]||(s[e.sheetId]=[]),s[e.sheetId].push(z(e)));for(let e in s){let t=R(s[e],[]);r.push(...t.map(t=>({sheetId:e,zone:t})))}}for(let t of e){let e=t.zone,r=t.sheetId;for(let t=e.left;t<=e.right;t++)for(let i=e.top;i<=e.bottom;i++)n.delete({sheetId:r,col:t,row:i})}return n}},FH=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=IH(t),r=e<<n>>5,i=new this(r+1);return i.columnOffset=n,i.cols=t,i.rows=e,i}getValue(e){let[t,n]=this.getCoordinates(e);return this[t]>>n&1}setValue(e,t){let[n,r]=this.getCoordinates(e),i=(this[n]>>r&1)==0&&t===1;return this[n]=this[n]&~(1<<r)|t<<r,i}isEmpty(){return!this.some(e=>e!==0)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){let{row:t,col:n}=e,r=(t<<this.columnOffset)+n,i=r>>5;return[i,r-(i<<5)]}};function IH(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var LH=class{sheets={};insertions=[];maxSize=0;constructor(e){for(let t in e){let n=e[t].cols,r=e[t].rows;this.maxSize+=n*r,this.sheets[t]=FH.create(r,n)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(let t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(let t of e)this.delete(t)}has(e){return this.sheets[e.sheetId].getValue(e)===1}clear(){let e=[...this];this.insertions=[];for(let e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(this.insertions.length===0)return!0;for(let e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=Array(this.maxSize);let e=0;for(let t in this.sheets){let n=this.sheets[t];n.fillAllPositions();for(let r=0;r<n.rows;r++)for(let i=0;i<n.cols;i++)this.insertions[e++]={sheetId:t,row:r,col:i}}}*[Symbol.iterator](){for(let e of this.insertions)this.sheets[e.sheetId].getValue(e)===1&&(yield e)}},RH=class{resultsToArrayFormulas=new MH;arrayFormulasToResults=new SP;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||zH}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){let t=this.arrayFormulasToResults.get(e);t&&(this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.delete(e))}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}};let zH=[],BH=Object.freeze(qo(new Bi)),VH=Object.freeze(qo({value:null}));var HH=class{context;getters;compilationParams;evaluatedCells=new SP;formulaDependencies=kt(new PH(this.createEmptyPositionSet.bind(this)));blockedArrayFormulas=new LH({});spreadingRelations=new RH;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=kH(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||VH}getSpreadZone(e,t={ignoreSpillError:!1}){let n=this.spreadingRelations.getArrayResultZone(e);if(!n)return;let r=this.evaluatedCells.get(e);return r?.type===`error`&&!(t.ignoreSpillError&&r?.value===k.SpilledBlocked)?z(e):Cs(z(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type===`empty`)return;let t=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,z(e));return Array.from(t).find(e=>!this.blockedArrayFormulas.has(e))}isArrayFormulaSpillBlocked(e){return this.blockedArrayFormulas.has(e)}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);let t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t);for(let e of t)this.compilationParams.ensureRange(e)}updateCompilationParametersForIsolatedFormula(e){this.compilationParams=kH(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.updateDependencies=void 0,this.compilationParams.evalContext.addDependencies=void 0,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParameters(){this.compilationParams=kH(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){let e={};for(let t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new LH(e)}evaluateCells(e){let t=performance.now(),n=this.createEmptyPositionSet();n.addMany(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(e)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=this.createEmptyPositionSet();for(let n of e){let e=this.getters.getCell(n)?.content,r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.add(r),e||t.add(n)}let n=Ps(t);for(let e in n)for(let r of n[e])t.addMany(this.getArrayFormulasBlockedBy(e,r));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new RH,this.formulaDependencies=kt(()=>{let e=[...this.getAllCells()].flatMap(e=>this.getDirectDependencies(e).filter(e=>!e.invalidSheetName&&!e.invalidXc).map(t=>({data:e,boundingBox:{zone:t.zone,sheetId:t.sheetId}})));return new PH(this.createEmptyPositionSet.bind(this),e)})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new SP,this.evaluate(this.getAllCells()),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=Qx(t),i=r.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return this.updateCompilationParametersForIsolatedFormula(n),this.evaluateCompiledFormula(e,{...r,dependencies:i})}evaluateCompiledFormula(e,t,n){try{let r=GH(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return Or(r)?ha(r,WH):WH(r)}catch(e){return Rx(e,``)}}getAllCells(){let e=this.createEmptyPositionSet();return e.fillAllPositions(),e}getArrayFormulasBlockedBy(e,t){let n=this.createEmptyPositionSet(),r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addMany(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteMany(i),n.addMany(this.getCellsDependingOn(n)),n}nextPositionsToUpdate=new LH({});cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextPositionsToUpdate=e;let t=0;for(;!this.nextPositionsToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();let e=this.nextPositionsToUpdate.clear();for(let t=0;t<e.length;++t)this.evaluatedCells.delete(e[t]);for(let t=0;t<e.length;++t){let n=e[t];if(this.nextPositionsToUpdate.has(n))continue;let r=this.computeCell(n);r!==VH&&this.evaluatedCells.set(n,r)}DH.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}computeCell(e){let t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);let n=this.getters.getCell(e);if(n===void 0)return VH;let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?BH:(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):Go(n,i))}catch(e){return e.value=e?.value||k.GenericError,e.message=e?.message||Vx,e.errorOriginPosition=e?.errorOriginPosition,qo(e)}finally{this.cellsBeingComputed.delete(r)}}computeAndSave(e){let t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){let n=GH(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!Or(n)){let r=qo(WH(n),this.getters.getLocale(),t);return r.type===`error`&&(r.errorOriginPosition=n.errorOriginPosition??e),r}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return qo({value:0},this.getters.getLocale(),t);if(i===1&&r===1)return qo(WH(n[0][0]),this.getters.getLocale(),t);let a={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+r-1};return this.spreadingRelations.addRelation({resultZone:a,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),UH(r,i,this.checkCollision(e)),UH(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),qo(WH(n[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){let n=this.formulaDependencies().getCellsDependingOn(Ns(t).map(t=>({sheetId:e,zone:t})),this.nextPositionsToUpdate);n.delete({sheetId:e,col:t.left,row:t.top}),this.nextPositionsToUpdate.addMany(n)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:n},r){let i=this.getters.getNumberCols(e),a=this.getters.getNumberRows(e),o=t+r.length<=i,s=n+r[0].length<=a;if(!(o&&s))throw o?new Wi(E(`Result couldn't be automatically expanded. Please insert more rows.`)):s?new Wi(E(`Result couldn't be automatically expanded. Please insert more columns.`)):new Wi(E(`Result couldn't be automatically expanded. Please insert more columns and rows.`))}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:n},r){if(this.getters.getMergesInZone(e,{top:n,bottom:n+r[0].length-1,left:t,right:t+r.length-1}).length!==0)throw new Wi(E(`Merged cells found in the spill zone. Please unmerge cells before using array formulas.`))}checkCollision(e){let{sheetId:t,col:n,row:r}=e;return(i,a)=>{let o={sheetId:t,col:i+n,row:a+r};if(this.getters.getCell(o)?.content||this.getters.getEvaluatedCell(o).type!==`empty`)throw this.blockedArrayFormulas.add(e),new Wi(E(`Array result was not expanded because it would overwrite data.`),o);this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=qo(WH(r[i][a]),this.getters.getLocale(),s);c.type===`error`&&(c.errorOriginPosition=r[i][a].errorOriginPosition??o),this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r};this.getters.getCell(t)?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextPositionsToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return BH;this.symbolsBeingComputed.add(t);try{return e?.(t)||new zi(E(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.dependencies:[]}getCellsDependingOn(e){let t=[],n=Ps(e);for(let e in n)t.push(...n[e].map(t=>({sheetId:e,zone:t})));return this.formulaDependencies().getCellsDependingOn(t,this.nextPositionsToUpdate)}};function UH(e,t,n){for(let r=0;r<e;++r)for(let e=0;e<t;++e)r===0&&e===0||n(r,e)}function WH(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function GH(e,t,n,r,i){let a=t.evalContext,o=a.__originCellPosition,s=a.__originSheetId;a.__originCellPosition=i,a.__originSheetId=n;let c=e.execute(e.dependencies,t.referenceDenormalizer,t.ensureRange,r,a);return a.__originCellPosition=o,a.__originSheetId=s,c}var KH=class extends EH{static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getRangeFormattedValues`,`getRangeValues`,`getRangeFormats`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new HH(e.custom,this.getters)}beforeHandle(e){(fr.has(e.type)||mr.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case`UPDATE_CELL`:if(!(`content`in e||`format`in e)||this.shouldRebuildDependenciesGraph)return;let t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),`content`in e&&this.evaluator.updateDependencies(t);break;case`EVALUATE_CELLS`:this.evaluator.evaluateAllCells();break}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t,n){let r=this.evaluateFormulaResult(e,t,n);return Or(r)?ha(r,e=>e.value):r.value}evaluateFormulaResult(e,t,n){return this.evaluator.evaluateFormulaResult(e,t,n)}evaluateCompiledFormula(e,t,n){return this.evaluator.evaluateCompiledFormula(e,t,n)}getRangeFormattedValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).formattedValue)}getRangeValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).value)}getRangeFormats(e){let t=this.getters.tryGetSheet(e.sheetId);return t===void 0?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map(e=>e.format)}getEvaluatedCell(e){return this.evaluator.getEvaluatedCell(e)}getEvaluatedCells(e){return this.evaluator.getEvaluatedPositionsInSheet(e).map(e=>this.getEvaluatedCell(e))}getEvaluatedCellsPositions(e){return this.evaluator.getEvaluatedPositionsInSheet(e)}getEvaluatedCellsInZone(e,t){return Fs(t).map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return Fs(t).map(({col:t,row:n})=>this.getEvaluatedCell({sheetId:e,col:t,row:n})).every(e=>e.type===`empty`)}mapVisiblePositions(e,t){let{sheetId:n,zone:r}=e;return Fs(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=T(t.col,t.row),i=n.value,a=!1,o,s=!0,c=e.sheets.find(e=>e.id===t.sheetId),l=this.getCorrespondingFormulaCell(t);if(l){let u=this.getters.getCell(t);if(s=oS(l.compiledFormula.tokens),a=s&&u?.content===l.content,!s&&i!==``){o=(i??``).toString();let t=n.format;if(t){let n=tc(t,e.formats);c.formats[r]=n}}}let u=c.cells[r],d;d=s&&a&&l instanceof aH?l.contentWithFixedReferences:s?u:o,c.cells[r]=d,c.cellValues[r]=i===k.BadExpression?void 0:i;let f=this.getSpreadZone(t);f&&(c.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,f),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let qH=/"(#[0-9a-fA-F]{6})"/g;function JH(e){let t=[{leadColor:dn(255,0,0),colors:[]},{leadColor:dn(255,128,0),colors:[]},{leadColor:dn(128,128,0),colors:[]},{leadColor:dn(128,255,0),colors:[]},{leadColor:dn(0,255,0),colors:[]},{leadColor:dn(0,255,128),colors:[]},{leadColor:dn(0,255,255),colors:[]},{leadColor:dn(0,127,255),colors:[]},{leadColor:dn(0,0,255),colors:[]},{leadColor:dn(127,0,255),colors:[]},{leadColor:dn(128,0,128),colors:[]},{leadColor:dn(255,0,128),colors:[]}];for(let n of e.map(hn)){let e=500,r=0;t.forEach((t,i)=>{let a=YH(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>_n(e).s-_n(t).s)).flat().map(mn)}function YH(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var XH=class extends EH{customColors={};shouldUpdateColors=!0;static getters=[`getCustomColors`];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds())for(let t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));break;case`UPDATE_CHART`:case`CREATE_CHART`:this.tryToAddColors(this.getChartColors(e.figureId));break;case`UPDATE_CELL`:case`ADD_CONDITIONAL_FORMAT`:case`SET_BORDER`:case`SET_ZONE_BORDERS`:case`SET_FORMATTING`:case`CREATE_TABLE`:case`UPDATE_TABLE`:this.history.update(`shouldUpdateColors`,!0);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return JH(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(let t of this.getters.getSheetIds())e=e.concat(this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=new Set;for(let e of t)e.style?.textColor&&n.add(e.style.textColor),e.style?.fillColor&&n.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))n.add(t);return[...n]}getFormattingColors(e){let t=this.getters.getConditionalFormats(e),n=[];for(let e of t){let t=e.rule;t.type===`CellIsRule`?(n.push(t.style.textColor),n.push(t.style.fillColor)):t.type===`ColorScaleRule`&&(n.push(an(t.minimum.color)),n.push(t.midpoint?an(t.midpoint.color):void 0),n.push(an(t.maximum.color)))}return n.filter(C)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getDefinition()).matchAll(qH)].map(e=>e[1])}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(C):[]}tryToAddColors(e){for(let t of e){if(!cn(t))continue;let e=sn(t);t&&!Ie.includes(e)&&this.history.update(`customColors`,e,!0)}}},ZH=class extends EH{static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};createRuntimeChart=_D(this.getters);handle(e){if(fr.has(e.type)||hr.has(e.type)||pr.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:case`DELETE_FIGURE`:this.charts[e.figureId]=void 0;break;case`DELETE_SHEET`:for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0);break}}getChartRuntime(e){if(!this.charts[e]){let t=this.getters.getChart(e);if(!t)throw Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:TS(e)};if(!t)return{background:oe,fontColor:TS(oe)};let n=t.zone.left,r=t.zone.top,i=t.sheetId,a=this.getters.getCellComputedStyle({sheetId:i,col:n,row:r}),o=a.fillColor||`#FFFFFF`;return{background:o,fontColor:a.textColor||TS(o)}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let r of e){if(!r||r.tag!==`chart`)continue;let e=r.id,i=this.getters.getChart(e)?.getDefinitionForExcel();if(i)n.push({...r,data:i});else{if(!this.getters.getChart(e))continue;let n=this.getters.getChartType(e),i=Dw(this.getters.getChartRuntime(e),r,n);i&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:i,size:{width:r.width,height:r.height}}})}}t.charts=n}}},QH=class extends EH{static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(fr.has(e.type)||hr.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(let e of this.getters.getSheetIds())this.computedStyles[e]=kt(()=>this.getComputedStyles(e)),this.computedIcons[e]=kt(()=>this.getComputedIcons(e)),this.computedDataBars[e]=kt(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){let{sheetId:t,col:n,row:r}=e,i=this.computedStyles[t]();return i&&i[n]?.[r]}getConditionalIcon({sheetId:e,col:t,row:n}){let r=this.computedIcons[e]();return r&&r[t]?.[n]}getConditionalDataBar({sheetId:e,col:t,row:n}){let r=this.computedDataBars[e]();return r&&r[t]?.[n]}getComputedStyles(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())switch(n.rule.type){case`ColorScaleRule`:for(let r of n.ranges)this.applyColorScale(e,r,n.rule,t);break;case`CellIsRule`:let r=n.rule.values.map(e=>e.startsWith(`=`)?Qx(e):void 0);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let s={sheetId:e,col:o,row:i},c=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s.tokens):t});this.getRuleResultForTarget(s,{...n.rule,values:c})&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getEvaluatedCellsInZone(e,this.getters.getRangeFromSheetXC(e,t).zone).filter(e=>e.type===`number`).map(e=>e.value);switch(n.type){case`value`:return r===`max`?Jt(i):Yt(i);case`number`:return Number(n.value);case`percentage`:let t=Yt(i);return t+(Jt(i)-t)*Number(n.value)/100;case`percentile`:return Li(i,Number(n.value)/100,!0);case`formula`:let a=n.value&&this.getters.evaluateFormula(e,n.value);return typeof a==`number`?a:null;default:return null}}applyIcon(e,t,n,r){let i=this.parsePoint(e,t,n.lowerInflectionPoint),a=this.parsePoint(e,t,n.upperInflectionPoint);if(i===null||a===null||i>a)return;let o=this.getters.getRangeFromSheetXC(e,t).zone,s=[n.icons.upper,n.icons.middle,n.icons.lower];for(let t=o.top;t<=o.bottom;t++)for(let c=o.left;c<=o.right;c++){let o=this.getters.getEvaluatedCell({sheetId:e,col:c,row:t});if(o.type!==`number`)continue;let l=this.computeIcon(o.value,a,n.upperInflectionPoint.operator,i,n.lowerInflectionPoint.operator,s);r[c]||(r[c]=[]),r[c][t]=l}}computeIcon(e,t,n,r,i,a){return n===`ge`&&e>=t||n===`gt`&&e>t?a[0]:i===`ge`&&e>=r||i===`gt`&&e>r?a[1]:a[2]}applyDataBar(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,n.rangeValues||t),a=Jt(this.getters.getEvaluatedCellsInZone(e,i.zone).filter(e=>e.type===`number`).map(e=>e.value));if(a<=0)return;let o=n.color,s=this.getters.getRangeFromSheetXC(e,t).zone,c=i.zone;for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let i=n-s.left+c.left,l=t-s.top+c.top,u=this.getters.getEvaluatedCell({sheetId:e,col:i,row:l});!ks(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:an(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[{value:i,color:n.minimum.color}];n.midpoint&&a&&c.push({value:a,color:n.midpoint.color}),c.push({value:o,color:n.maximum.color});let l=zn(c);for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let a=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(a.type===`number`){let e=x(a.value,i,o);r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=l(e)}}}getRuleResultForTarget(e,t){let n=this.getters.getEvaluatedCell(e);if(n.type===`error`)return!1;let{sheetId:r}=e,i=Y.get(t.operator),a=t.values.map(e=>e.startsWith(`=`)?this.getters.evaluateFormula(r,e)??``:Ko(e,D));if(a.some(Du))return!1;let o={type:t.operator,values:a.map(Tu)};return i.isValueValid(n.value??``,o,this.getters,r)}};let $H={isValid:!0};var eU=class extends EH{static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`getDataValidationRangeValues`,`isCellValidCheckbox`,`getDataValidationCellStyle`,`getDataValidationChipStyle`,`isDataValidationInvalid`];validationResults={};handle(e){if(fr.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:`#E7E9ED`}}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=Y.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?E(`The value must not be a formula`):this.isValidFormula(t)?void 0:G.CriterionError.validFormula:n.allowedValues===`onlyFormulas`?E(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}getDataValidationRangeValues(e,t){let n=this.getters.getRangeFromSheetXC(e,String(t.values[0])),r=[],i=new Set;for(let e of Fs(n.zone)){let t=this.getters.getEvaluatedCell({...e,sheetId:n.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),r.push({label:t.formattedValue,value:t.value?.toString()||``}))}return r}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return $H;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:$H}hasChip(e){let t=this.getters.getValidationRuleForCell(e);return(t?.criterion.type===`isValueInList`||t?.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`chip`}getDataValidationStyle(e){let t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;let n=this.getters.getEvaluatedCell(e),r=this.getValueColor(t,n.value);if(r)return{fillColor:r,textColor:Tn(r)}}getValueColor(e,t){if(!(e.criterion.type!==`isValueInList`&&e.criterion.type!==`isValueInRange`)){for(let n in e.criterion.colors)if(n.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[n]}}isValidFormula(e){return!Qx(e).isBadExpression}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||$H}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of Oc(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=kt(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?$H:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=Y.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,o,i);if(s.some(Du))return;let c={...i,values:s.map(Tu)};if(!a.isValueValid(e,c,this.getters,r))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>ks(e.col,e.row,t.zone));if(!n)throw Error(`The cell is not in any range of the rule`);return{col:e.col-n.zone.left,row:e.row-n.zone.top}}getEvaluatedCriterionValues(e,t,n){return n.values.map(n=>{if(!n.startsWith(`=`))return Ko(n,D);let r=Qx(n),i=this.getters.getTranslatedCellFormula(e,t.col,t.row,r.tokens);return this.getters.evaluateFormula(e,i)})}};let tU=new g;tU.add(`data_validation_checkbox`,(e,t)=>{if(e.isCellValidCheckbox(t)){let n=!!e.getEvaluatedCell(t).value;return{svg:n?vA:gA,hoverSvg:n?vA:_A,priority:2,horizontalAlign:`center`,size:17,margin:2,position:t,type:`data_validation_checkbox`,onClick:(e,t)=>{let r=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||r?.isFormula)return;let i=n?`FALSE`:`TRUE`;t.model.dispatch(`UPDATE_CELL`,{...e,content:i})}}}}),tU.add(`data_validation_chip_icon`,(e,t)=>{let n=e.getDataValidationChipStyle(t);if(n){let r=e.getCellComputedStyle(t);return{svg:mA(n),hoverSvg:hA(n),priority:10,horizontalAlign:`right`,size:ol(r),margin:4,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_chip_icon`}}}),tU.add(`data_validation_list_icon`,(e,t)=>{if(!e.isReadonly()&&e.cellHasListDataValidationIcon(t)){let n=e.getCellComputedStyle(t);return{svg:dA(n),hoverSvg:fA(n),priority:2,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_list_icon`}}}),tU.add(`filter_icon`,(e,t)=>{if(e.isFilterHeader(t)){let n=e.isFilterActive(t),r=fn(e.getCellComputedStyle(t).fillColor||`#fff`)<.45;return{type:`filter_icon`,svg:bA(n,r,!1),hoverSvg:bA(n,r,!0),priority:3,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let n=t.getStore(Ck),r=n.persistentCellPopover;if(r.isOpen&&r.col===e.col&&r.row===e.row&&r.type===`FilterMenu`){n.close();return}n.open(e,`FilterMenu`)}}}}),tU.add(`conditional_formatting`,(e,t)=>{let n=e.getConditionalIcon(t);if(n){let r=e.getCellStyle(t);return{type:`conditional_formatting`,svg:xA[n].svg,priority:1,horizontalAlign:`left`,size:ol(r),margin:4,position:t}}}),tU.add(`pivot_collapse`,(e,t)=>{if(!e.isSpillPivotFormula(t))return;let n=e.getPivotCellFromPosition(t),r=e.getPivotIdFromPosition(t);if(n.type===`HEADER`&&r&&n.domain.length){let i=e.getPivotCoreDefinition(r),a=e.isDashboard(),o=n.dimension===`COL`?i.columns:i.rows,s=!a&&n.domain.length!==o.length,c=(i.collapsedDomains?.[n.dimension]??[]).some(e=>w(e,n.domain)),l=n.dimension===`ROW`?(n.domain.length-1)*15:0;return{type:`pivot_collapse`,priority:4,horizontalAlign:`left`,size:s||!a&&n.dimension===`ROW`&&i.rows.length>1?12:0,margin:s?4+l:l,svg:s?yA(c,!1):void 0,hoverSvg:s?yA(c,!0):void 0,position:t,onClick:nU}}});function nU(e,t){let n=t.model.getters.getPivotCellFromPosition(e),r=t.model.getters.getPivotIdFromPosition(e);if(!r||n.type!==`HEADER`)return;let i=t.model.getters.getPivotCoreDefinition(r),a=i.collapsedDomains?.[n.dimension]?[...i.collapsedDomains[n.dimension]]:[],o=a.findIndex(e=>w(e,n.domain));o===-1?a.push(n.domain):a.splice(o,1);let s=i.collapsedDomains?{...i.collapsedDomains}:{COL:[],ROW:[]};s[n.dimension]=a,t.model.dispatch(`UPDATE_PIVOT`,{pivotId:r,pivot:{...i,collapsedDomains:s}})}var rU=class extends EH{static getters=[`doesCellHaveGridIcon`,`getCellIcons`,`getCellIconRect`];cellIconsCache={};handle(e){e.type!==`SET_VIEWPORT_OFFSET`&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){let n=e.position,r=this.getters.getCell(n);return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,r?.style?.verticalAlign),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,n){let r=e.x,i=e.x+e.width;switch(t){case`right`:return i-n.margin-n.size;case`left`:return r+n.margin;default:let e=Math.floor((i-r-n.size)/2);return i-n.size-e}}computeCellIcons(e){let t={left:void 0,right:void 0,center:void 0},n=tU.getAll();for(let r of n){let n=r(this.getters,e);n&&(!t[n.horizontalAlign]||n.priority>t[n.horizontalAlign].priority)&&(t[n.horizontalAlign]=n)}if(t.center&&(t.left||t.right)){let e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(C)}doesCellHaveGridIcon(e){return!!this.getCellIcons(e).length}},iU=class extends EH{static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(fr.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tables={};return}switch(e.type){case`CREATE_TABLE`:case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`DELETE_CONTENT`:this.tables={};break}}finalize(){for(let e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){let t=[],n=this.getters.getCoreTables(e);for(let e of n)e.type!==`dynamic`&&t.push(e);let r=[...t];for(let i of n){if(i.type!==`dynamic`)continue;let n=this.coreTableToTable(e,i),a=n.range.zone;for(let e of r){let t=e.range.zone;Ds(a,t)&&(a=t.left>a.left?{...a,right:Math.min(a.right,t.left-1)}:{...a,bottom:Math.min(a.bottom,t.top-1)})}t.push({...n,range:this.getters.getRangeFromZone(e,a)})}return t}getFilters(e){return this.getTables(e).filter(e=>e.config.hasFilters).map(e=>e.filters).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){let t=this.getTable(e);if(!(!t||!t.config.hasFilters))return t.filters.find(t=>t.col===e.col)}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:n}){return this.getTables(e).find(e=>ks(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>Ds(e.range.zone,t)))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some(e=>e.config.hasFilters)}getFilterHeaders(e){let t=[];for(let n of this.getTables(e)){if(!n.config.hasFilters)continue;let r=n.range.zone,i=r.top;for(let n=r.left;n<=r.right;n++)t.push({sheetId:e,col:n,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:n}){return this.getFilterHeaders(e).some(e=>e.col===t&&e.row===n)}canCreateDynamicTableOnZones(e,t){if(!Js(t))return!1;let n=Cs(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);if(!i){let e=this.getters.getEvaluatedCell(r);return e.value===k.SpilledBlocked&&!e.errorOriginPosition}else if(w(i,r)&&Ws(n)===1)return!0;return w(n,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=tF(this.getDynamicTableFilterId(t.id,s),this.getters.getRangeFromZone(e,c),t.config,this.getters.getRangeFromZone);r.push(l)}return r}getDynamicTableFilterId(e,t){return e+`_`+t}isTableExcelExportable(e,t){return t.type===`dynamic`?!1:!Fs(t.range.zone).some(t=>this.getters.getArrayFormulaSpreadingOn({sheetId:e,...t}))}exportForExcel(e){for(let t of e.sheets){let n=[];for(let r of t.tables){let i=ps(r.range),a={sheetId:t.id,col:i.left,row:i.top},o=this.getters.getCoreTable(a),s=this.getTable(a);if(!o||!s||this.isTableExcelExportable(t.id,o)){n.push(r);continue}t.styles=t.styles||{},t.borders=t.borders||{};for(let n of Fs(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=T(n.col,n.row);if(!Tt(i)){let n=tc(i,e.styles);t.styles[o]=n}if(a){let n=tc(a,e.borders);t.borders[o]=n}}}t.tables=n}}},aU=class extends EH{static getters=[`getRowSize`,`getHeaderSize`,`getMaxAnchorOffset`];tallestCellInRow={};ctx=document.createElement(`canvas`).getContext(`2d`);beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=jt(e.position,e.base),n=Array(e.quantity).fill(void 0),r=Ut(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=b(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=Ht(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of S(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of Fs(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getMaxAnchorOffset(e,t,n){let{numberOfRows:r,numberOfCols:i}=this.getters.getSheetSize(e),a=0;for(;a<t&&r>0;r--)a+=this.getRowSize(e,r-1);let o=0;for(;o<n&&i>0;i--)o+=this.getters.getColSize(e,i-1);return{col:i,row:r,offset:{x:o-n,y:a-t}}}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForCellChange(e,t,n){let r=this.tallestCellInRow[e]?.[t];if(r?.cell.col===n){let n=this.getRowTallestCell(e,t);this.history.update(`tallestCellInRow`,e,t,n)}let i=this.getCellHeight({sheetId:e,col:n,row:t});if(!(i<=23)&&(!r&&i>23||r&&i>r.size)){let r={cell:{sheetId:e,col:n,row:t},size:i};this.history.update(`tallestCellInRow`,e,t,r)}}initializeSheet(e){let t=[];for(let n=0;n<this.getters.getNumberRows(e);n++){let r=this.getRowTallestCell(e,n);t.push(r)}this.history.update(`tallestCellInRow`,e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return 23;let t=this.getters.getCell(e),n=this.getters.getColSize(e.sheetId,e.col);return Yc(this.ctx,t,this.getters.getLocale(),n)}isInMultiRowMerge(e){let t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(this.getters.getUserRowSize(e,t)!==void 0)return;let n=this.getters.getRowCells(e,t),r=0,i;for(let e=0;e<n.length;e++){let t=this.getters.getCellById(n[e]);if(!t)continue;let a=this.getters.getCellPosition(t.id),o=this.getCellHeight(a);o>r&&o>23&&(r=o,i={cell:a,size:o})}if(i&&i.size>23)return i}};let oU=`0.00%`;function sU(e){class t extends e{getters;pivotId;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t,n){super(t,n),this.getters=n.getters,this.pivotId=e}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){let n=`${e}-${t.map(e=>e.field+`=`+e.value).join(`,`)}`;if(this.cache[n])return this.cache[n];let r=this.getMeasure(e),i=r.computedBy?this.computeMeasure(r,t):super.getPivotCellValueAndFormat(e,t);return r.format?this.cache[n]={...i,format:r.format}:this.cache[n]=i,this.cache[n]}computeMeasure(e,t){if(!e.computedBy)return{value:0};let{columns:n,rows:r}=super.definition;if(e.aggregator&&n.length+r.length!==t.length){let n=this.getValuesToAggregate(e,t),r=sd[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return Rx(t,e.aggregator.toUpperCase())}}let i=this.getters.getMeasureCompiledFormula(this.pivotId,e),a=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,e=>{let{columns:n,rows:r}=this.definition;if(n.find(t=>t.nameWithGranularity===e)){let{colDomain:n}=xI(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Hi:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=xI(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Hi:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return Or(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=xI(this,t),i=super.getExpandedTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=gd(this.definition.getDimension(r.field),t[n]?.value);if(r.field===t[n]?.field&&r.value===e)return this.getSubTreeMatchingDomain(r.children,t,n+1)}return[]}treeToLeafDomains(e,t=[]){let n=[];for(let r of e){let e=this.definition.getDimension(r.field),i=[...t,{field:r.field,value:r.value,type:e.type}];r.children.length===0?n.push(i):n.push(...this.treeToLeafDomains(r.children,i))}return n}getMeasureDisplayValue(e,t){let n=this.getMeasure(e),r=this._getPivotCellValueAndFormat(e,t);if(!n.display||n.display.type===`no_calculations`||r.message)return r;let i=n.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:k.NotAvailable,message:E(`Field "%s" not found in pivot for measure display calculation`,i)};try{let e=n.display;switch(e.type){case`%_of_grand_total`:return this.asPercentOfGrandTotal(r,n);case`%_of_col_total`:return this.asPercentOfColumnTotal(r,n,t);case`%_of_row_total`:return this.asPercentOfRowTotal(r,n,t);case`%_of_parent_row_total`:return this.asPercentOfParentRowTotal(r,n,t);case`%_of_parent_col_total`:return this.asPercentOfParentColumnTotal(r,n,t);case`index`:return this.asIndex(r,n,t);case`%_of_parent_total`:return this.asPercentOfParentTotal(r,n,t,e);case`running_total`:return this.asRunningTotal(r,n,t,e,`running_total`);case`%_running_total`:return this.asRunningTotal(r,n,t,e,`%_running_total`);case`rank_asc`:return this.asRank(r,n,t,e,`asc`);case`rank_desc`:return this.asRank(r,n,t,e,`desc`);case`%_of`:return this.asPercentOf(r,n,t,e);case`difference_from`:return this.asDifferenceFrom(r,n,t,e);case`%_difference_from`:return this.asDifferenceFromInPercent(r,n,t,e)}return r}catch(e){return Rx(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:k.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:oU}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:k.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:oU}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:k.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:oU}}asPercentOfParentRowTotal(e,t,n){let r=yI(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:oU}}asPercentOfParentColumnTotal(e,t,n){let r=bI(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:oU}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!kI(i,n))return{value:``};let a=DI(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:oU}}asIndex(e,t,n){let r=this.measureValueToNumber(e),i=this.getRowTotal(t.id,n),a=this.getColumnTotal(t.id,n),o=this.getGrandTotal(t.id);return i===0||a===0?{value:k.DivisionByZero}:{value:r*o/(a*i),format:void 0}}asRunningTotal(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;let o=i===`running_total`?this.runningTotal:this.runningTotalInPercent,s=o[t.id]?.[a];s||(s=this.computeRunningTotal(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=xI(this,n),u=MI(l),d=MI(c);return{value:s[u]?.[d]??``,format:i===`running_total`?e.format:oU}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!kI(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:k.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:oU}:s===void 0?{value:k.NullError}:{value:s/o,format:oU}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!kI(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a)||0;return o===`sameValue`?{value:``}:{value:this.measureValueToNumber(e)-o,format:e.format}}asDifferenceFromInPercent(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!kI(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:k.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:k.NullError}:{value:(s-o)/o,format:oU}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!kI(a,n))return{value:``};let o=i===`asc`?this.rankAsc:this.rankDesc,s=o[t.id]?.[a];s||(s=this.computeRank(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=xI(this,n),u=MI(l),d=MI(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=AI(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=_a(o));for(let s of o){let o=MI(SI(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:SI(this,i,t.domain)})).filter(e=>kI(t,e.rowDomain)),l=Object.groupBy(c,e=>PI(e.rowDomain,t));for(let e in l)l[e]=Zt(l[e]||[],e=>e.value).filter(e=>e.value!==void 0).sort((e,t)=>n===`asc`?e.value-t.value:t.value-e.value);r[o]={};for(let e of c){let n=MI(SI(this,i,e.domain)),a=l[PI(e.rowDomain,t)];if(!a)continue;let s=a.findIndex(t=>t.value===e.value);s!==-1&&(r[o][n]=s+1)}}return i===`row`?r:Qt(r)}computeRunningTotal(e,t,n){let r={},i=AI(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=_a(o));for(let s of o){let o=MI(SI(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:SI(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>kI(t,e.rowDomain));for(let e of l){let n=MI(e.rowDomain),i=FI(e.rowDomain,t),a=(c[i]||0)+e.value;c[i]=a,r[o][n]=a}if(n===`%_running_total`)for(let e of l){let n=e.rowDomain,i=MI(n),a=FI(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:Qt(r)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=xI(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=xI(this,t).colDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,n,r){let i=r===`(previous)`||r===`(next)`?jI(this,t,n,r):OI(t,n,r);if(w(i,t))return`sameValue`;if(!i||!wI(this,i))throw new Hi;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){let e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){let e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;let t=this.definition.sortedColumn.measure;wd(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}return t}let cU=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function lU(e){return cU.includes(e.type)}var uU=class extends EH{static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotIdFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`];pivots={};unusedPivots;custom;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){switch(e.type){case`START`:for(let e of this.getters.getPivotIds())this.setupPivot(e)}}handle(e){if(fr.has(e.type))for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0});switch(e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.setupPivot(e.pivotId);break;case`DUPLICATE_PIVOT`:this.setupPivot(e.newPivotId);break;case`UPDATE_PIVOT`:this.setupPivot(e.pivotId,{recreate:!0});break;case`DELETE_SHEET`:case`UPDATE_CELL`:this.unusedPivots=void 0;break;case`UNDO`:case`REDO`:{this.unusedPivots=void 0;let t=e.commands.filter(lU);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:vV();break}}getPivotIdFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){let n=this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(n){let e=n.args[0]?.toString();return e&&this.getters.getPivotId(e)}}}isSpillPivotFormula(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens)?.functionName===`PIVOT`:!1}getFirstPivotFunction(e,t){let n=QB(t);if(!n)return;let{functionName:r,args:i}=n;return{functionName:r,args:i.map(t=>{if(t.type===`EMPTY`)return;if(t.type===`STRING`||t.type===`BOOLEAN`||t.type===`NUMBER`)return t.value;let n=gy(t);return this.getters.evaluateFormula(e,n)})}}getPivotCellFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||$B(t.compiledFormula.tokens)===0)return aV;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!r)return aV;let{functionName:i,args:a}=r,o=a[0];if(!o)return aV;let s=this.getters.getPivotId(o.toString());if(!s)return aV;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!t.content.replaceAll(` `,``).toUpperCase().startsWith(`=PIVOT`))return aV;try{if(i===`PIVOT`){let t=Tu(a[2]),r=t===void 0?!0:P(t),i=Tu(a[3]),o=Tu(a[5]),s=o===void 0?!0:P(o),l={displayColumnHeaders:i===void 0?!0:P(i),displayTotals:r,displayMeasuresRow:s},u=c.getCollapsedTableStructure().getPivotCells(l),d=e.col-n.col,f=e.row-n.row;return u[d][f]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>Or(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`){let e=c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})));return{type:`HEADER`,domain:e,dimension:xI(c,e).colDomain.length?`COL`:`ROW`}}let[o,...s]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(s.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return aV}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName);return $t(E(`Calculated measure 1`),t,{compute:(e,t)=>E(`Calculated measure %s`,t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){return this._getUnusedPivots().includes(e)}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=b(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=sU(bV.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivots(){if(this.unusedPivots!==void 0)return this.unusedPivots;let e=new Set(this.getters.getPivotIds());for(let t of this.getters.getSheetIds())for(let n in this.getters.getCells(t)){let t=this.getters.getCellPosition(n),r=this.getPivotIdFromPosition(t);if(r&&(e.delete(r),!e.size))return this.unusedPivots=[],[]}return this.unusedPivots=[...e],this.unusedPivots}};let dU=new g;dU.add(`ALPHANUMERIC_INCREMENT_MODIFIER`,{apply:(e,t)=>{e.current+=e.increment;let n=`${e.prefix}${e.current.toString().padStart(e.numberPostfixLength||0,`0`)}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:n},tooltip:{props:{content:n}}}}}).add(`INCREMENT_MODIFIER`,{apply:(e,t,n)=>{e.current+=e.increment;let r=e.current.toString(),i=n.getLocale(),a=L(e.current,{format:t.cell?.format,locale:i});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:a}}:void 0}}}).add(`DATE_INCREMENT_MODIFIER`,{apply:(e,t,n)=>{let r=F(e.current,n.getLocale());r.setFullYear(r.getFullYear()+e.increment.years||0),r.setMonth(r.getMonth()+e.increment.months||0),r.setDate(r.getDate()+e.increment.days||0);let i=gi(r);e.current=i;let a=n.getLocale(),o=L(i,{format:t.cell?.format,locale:a});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:o}}:void 0}}}).add(`COPY_MODIFIER`,{apply:(e,t,n)=>{let r=t.cell?.content||``,i={locale:n.getLocale(),format:t.cell?.format};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:t.cell?Go(t.cell,i).formattedValue:``}}:void 0}}}).add(`FORMULA_MODIFIER`,{apply:(e,t,n,r)=>{e.current+=e.increment;let i=0,a=0;switch(r){case`up`:i=0,a=-e.current;break;case`down`:i=0,a=e.current;break;case`left`:i=-e.current,a=0;break;case`right`:i=e.current,a=0;break}let o=t.cell;if(!o||!o.isFormula)return{cellData:{}};let s=t.sheetId,c=n.getTranslatedCellFormula(s,i,a,o.compiledFormula.tokens);return{cellData:{border:t.border,style:o.style,format:o.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});let fU=new g,pU=/(\d+)$/,mU=/^(.*\D+)/,hU=/^(.*\D+)(\d+)$/;function gU(e,t,n){let r=[],i=!1;for(let a of t){a===e&&(i=!0);let t=a===void 0||a.isFormula?void 0:Go(a,{locale:D,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function _U(e){let t=[],n=e[0];for(let r=1;r<e.length;r++){let i=e[r];t.push(i-n),n=i}return t.reduce((e,t)=>e+t,0)/t.length}function vU(e){let t=1;return e.length>=2&&(t=_U(e)*e.length),t}function yU(e){return e.length<2?e[0]||{years:0,months:0,days:0}:e.every(t=>t.years===e[0].years&&t.months===e[0].months&&t.days===e[0].days)?e[0]:void 0}function bU(e){if(e.length<2)return 1;let t=e.map(e=>F(e,D)),n=yU(xU(t));if(n===void 0)return;let r=Object.values(n).filter(e=>e!==0).length===1,i=Object.values(n).every(e=>e===0);if(!r||i){let n=t.map((e,n)=>{if(n===0)return 0;let r=t[n-1];return Math.floor(e.getTime())-Math.floor(r.getTime())}).slice(1);if(n.every(e=>e===n[0]))return e.length*(e[1]-e[0])}return{years:n.years*e.length,months:n.months*e.length,days:n.days*e.length}}fU.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&So(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&Go(e,{locale:D}).type===`text`&&hU.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(pU)[0]),i=e.content.match(mU)[0],a=e.content.length-i.length,o=gU(e,t,e=>e.type===`text`&&hU.test(e.value)).filter(e=>i===(e.value??``).toString().match(mU)[0]).map(e=>parseInt((e.value??``).toString().match(pU)[0])),s=vU(o);return[`up`,`left`].includes(n)&&o.length===1&&(s=-s),{type:`ALPHANUMERIC_INCREMENT_MODIFIER`,prefix:i,current:r,increment:s,numberPostfixLength:a}},sequence:15}).add(`copy_text`,{condition:e=>!e.isFormula&&Go(e,{locale:D}).type===`text`,generateRule:()=>({type:`COPY_MODIFIER`}),sequence:20}).add(`update_formula`,{condition:e=>e.isFormula,generateRule:(e,t)=>({type:`FORMULA_MODIFIER`,increment:t.length,current:0}),sequence:30}).add(`increment_dates`,{condition:(e,t)=>!e.isFormula&&Go(e,{locale:D}).type===`number`&&!!e.format&&So(e.format),generateRule:(e,t)=>{let n=bU(gU(e,t,e=>e.type===`number`&&!!e.format&&So(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=Go(e,{locale:D});return typeof n==`object`?{type:`DATE_INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}:{type:`INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}},sequence:25}).add(`increment_number`,{condition:e=>!e.isFormula&&Go(e,{locale:D}).type===`number`,generateRule:(e,t,n)=>{let r=gU(e,t,e=>e.type===`number`&&!So(e.format||``)).map(e=>Number(e.value)),i=vU(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=Go(e,{locale:D});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===`number`?a.value:0}},sequence:40});function xU(e){return e.length<2?[{years:0,months:0,days:0}]:e.map((t,n)=>{if(n===0)return{years:0,months:0,days:0};let r=O.fromTimestamp(e[n-1].getTime()),i=wi(r,t),a=Si(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:Ci(r,t)}}).slice(1)}var SU=class extends tH{static layers=[];getters;ui;selection;dispatch;canDispatch;constructor({getters:e,stateObserver:t,dispatch:n,canDispatch:r,uiActions:i,selection:a}){super(t),this.getters=e,this.ui=i,this.selection=a,this.dispatch=n,this.canDispatch=r}drawLayer(e,t){}},CU=class{cells;getters;index=0;direction;constructor(e,t,n){this.cells=e,this.getters=t,this.direction=n}next(){let e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:n,tooltip:r}=dU.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:n,tooltip:r,origin:{col:e.data.col,row:e.data.row}}}},wU=class extends SU{static layers=[`Autofill`];static getters=[`getAutofillTooltip`];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case`AUTOFILL_SELECT`:let t=this.getters.getActiveSheetId();return this.lastCellSelected.col=e.col===-1?this.lastCellSelected.col:x(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=e.row===-1?this.lastCellSelected.row:x(e.row,0,this.getters.getNumberRows(t)),this.lastCellSelected.col!==void 0&&this.lastCellSelected.row!==void 0?`Success`:`InvalidAutofillSelection`}return`Success`}handle(e){switch(e.type){case`AUTOFILL`:this.autofill(!0);break;case`AUTOFILL_SELECT`:this.select(e.col,e.row);break;case`AUTOFILL_AUTO`:this.autofillAuto();break}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||this.direction===void 0){this.tooltip=void 0;return}let t=this.getters.getSelectedZone(),n=this.autofillZone,r=[];switch(this.direction){case`down`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.top;n<=t.bottom;n++)i.push(T(e,n));let a=this.createGenerator(i);for(let t=n.top;t<=n.bottom;t++)r.push(this.computeNewCell(a,e,t))}break;case`up`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.bottom;n>=t.top;n--)i.push(T(e,n));let a=this.createGenerator(i);for(let t=n.bottom;t>=n.top;t--)r.push(this.computeNewCell(a,e,t))}break;case`left`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.right;n>=t.left;n--)i.push(T(n,e));let a=this.createGenerator(i);for(let t=n.right;t>=n.left;t--)r.push(this.computeNewCell(a,t,e))}break;case`right`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.left;n<=t.right;n++)i.push(T(n,e));let a=this.createGenerator(i);for(let t=n.left;t<=n.right;t++)r.push(this.computeNewCell(a,t,e))}break}if(e){let e={},t={},n={},i=this.getters.getActiveSheetId();for(let a of r)this.collectBordersData(a,e),this.autofillMerge(i,a),this.autofillCell(i,a),this.collectConditionalFormatsData(i,a,t),this.collectDataValidationsData(i,a,n);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,n),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){let n=JSON.stringify(e.border);n in t||(t[n]=[]),t[n].push(z({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s=this.getters.getRulesByCell(e,r,i),c=T(a,o);for(let e of s)e.id in n||(n[e.id]=[]),n[e.id].push(c)}collectDataValidationsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s={sheetId:e,col:r,row:i},c=this.getters.getValidationRuleForCell(s);c&&(c.id in n||(n[c.id]=[]),n[c.id].push(z({col:a,row:o})))}autofillCell(e,t){this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t.col,row:t.row,content:t.content||``,style:t.style||null,format:t.format||``}),this.dispatch(`AUTOFILL_CELL`,t)}autofillBorders(e,t){for(let n in t){let r=n===`undefined`?void 0:JSON.parse(n);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,border:r,target:R(t[n])})}}autofillConditionalFormats(e,t){for(let n in t){let r=t[n],i=this.getters.getConditionalFormats(e).find(e=>e.id===n);if(!i)continue;let a=this.getters.getAdaptedCfRanges(e,i,r.map(ps),[]);a&&this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:i.id,rule:i.rule,stopIfTrue:i.stopIfTrue},ranges:a,sheetId:e})}}autofillDataValidations(e,t){for(let n in t){let r=t[n],i=this.getters.getDataValidationRule(e,n);if(!i)continue;let a=R(i.ranges.map(e=>e.zone).concat(r),[]);this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:i,ranges:a.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}select(e,t){let n=this.getters.getSelectedZone();if(ks(e,t,n)){this.autofillZone=void 0;return}switch(this.direction=this.getDirection(e,t),this.direction){case`up`:this.saveZone(t,n.top-1,n.left,n.right),this.steps=n.top-t;break;case`down`:this.saveZone(n.bottom+1,t,n.left,n.right),this.steps=t-n.bottom;break;case`left`:this.saveZone(n.top,n.bottom,e,n.left-1),this.steps=n.left-e;break;case`right`:this.saveZone(n.top,n.bottom,n.right+1,e),this.steps=e-n.right;break}this.autofill(!1)}autofillAuto(){let e=this.getters.getActivePosition(),t=this.getters.getTable(e),n=t?t.range.zone.bottom:this.getAutofillAutoLastRow(),r=this.getters.getSelectedZone();for(let t=r.bottom+1;t<=n;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==`empty`){n=t-1;break}n>r.bottom&&(this.select(e.col,n),this.autofill(!0))}getAutofillAutoLastRow(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId(),n=e.left,r=e.bottom;if(n>0){let e={sheetId:t,col:n-1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n-1,row:r}}if(r===e.bottom&&(n=e.right,n<=this.getters.getNumberCols(t))){let e={sheetId:t,col:n+1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n+1,row:r}}return r-1}computeNewCell(e,t,n){let{cellData:r,tooltip:i,origin:a}=e.next(),{content:o,style:s,border:c,format:l}=r;return this.tooltip=i,{originCol:a.col,originRow:a.row,col:t,row:n,content:o,style:s,border:c,format:l}}getRule(e,t){let n=fU.getAll().sort((e,t)=>e.sequence-t.sequence).find(n=>n.condition(e,t));return n&&this.direction&&n.generateRule(e,t,this.direction)}createGenerator(e){let t=[],n=[],r=this.getters.getActiveSheetId();for(let t of e){let{col:e,row:i}=Zn(t),a=this.getters.getCell({sheetId:r,col:e,row:i});n.push({col:e,row:i,cell:a,sheetId:r})}let i=n.map(e=>e.cell);for(let e of n){let n={type:`COPY_MODIFIER`};e&&e.cell&&(n=this.getRule(e.cell,i)||n);let r=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:r},rule:n})}return new CU(t,this.getters,this.direction)}saveZone(e,t,n,r){this.autofillZone={top:e,bottom:t,left:n,right:r}}getDirection(e,t){let n=this.getters.getSelectedZone(),r={up:{number:n.top-t,value:`up`},down:{number:t-n.bottom,value:`down`},left:{number:n.left-e,value:`left`},right:{number:e-n.right,value:`right`}};if(Object.values(r).map(e=>+(e.number>0)).reduce((e,t)=>e+t)===1)return Object.values(r).find(e=>+(e.number>0)).value;let i=r.up.number>0?`up`:`down`,a=r.left.number>0?`left`:`right`;return Math.abs(r[i].number)>=Math.abs(r[a].number)?r[i].value:r[a].value}autofillMerge(e,t){let{originCol:n,originRow:r,col:i,row:a}=t,o={sheetId:e,col:i,row:a},s={sheetId:e,col:n,row:r};if(this.getters.isInMerge(o)&&!this.getters.isInMerge(s)){let t=this.getters.getMerge(o);t&&this.dispatch(`REMOVE_MERGE`,{sheetId:e,target:[t]})}let c=this.getters.getMerge(s);c?.left===n&&c?.top===r&&this.dispatch(`ADD_MERGE`,{sheetId:e,target:[{top:a,bottom:a+c.bottom-c.top,left:i,right:i+c.right-c.left}]})}drawLayer(e){if(!this.autofillZone)return;let{ctx:t,thinLineWidth:n}=e,{x:r,y:i,width:a,height:o}=this.getters.getVisibleRect(this.autofillZone);a>0&&o>0&&(t.strokeStyle=`black`,t.lineWidth=n,t.setLineDash([3]),t.strokeRect(r,i,a,o),t.setLineDash([]))}},TU=class extends SU{static getters=[`getAutomaticSums`];handle(e){switch(e.type){case`SUM_SELECTION`:let e=this.getters.getActiveSheetId(),{zones:t,anchor:n}=this.getters.getSelection();for(let r of t){let t=this.getAutomaticSums(e,r,n.cell);this.dispatchCellUpdates(e,t)}break}}getAutomaticSums(e,t,n){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,n):this.sumData(e,t)}sumData(e,t){let n=this.dimensionsToSum(e,t),r=this.sumDimensions(e,t,n).filter(({zone:t})=>!this.getters.isEmpty(e,t));return n.has(`ROW`)&&n.has(`COL`)&&r.push(this.sumTotal(t)),r}sumAdjacentData(e,t,n){let{col:r,row:i}=ks(n.col,n.row,t)?n:{col:t.left,row:t.top},a=this.findAdjacentData(e,r,i);return a?this.getters.isSingleCellOrMerge(e,t)||Ms(Cs(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,Cs(a,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,n){let r=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.findSuitableZoneToSum(r,i.col,i.row);if(a)return this.getters.expandZone(e,a)}findSuitableZoneToSum(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:n-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:n});if(this.isNumber(i)&&!this.isNumber(r))return this.findHorizontalZone(e,t,n);let a=this.findVerticalZone(e,t,n);if(this.isZoneValid(a))return a;let o=this.findHorizontalZone(e,t,n);if(this.isZoneValid(o))return o}findVerticalZone(e,t,n){let r={top:0,bottom:n-1,left:t,right:t},i=this.reduceZoneStart(e,r,r.bottom);return{...r,top:i}}findHorizontalZone(e,t,n){let r={top:n,bottom:n,left:0,right:t-1},i=this.reduceZoneStart(e,r,r.right);return{...r,left:i}}reduceZoneStart(e,t,n){let r=this.getters.getEvaluatedCellsInZone(e.id,t),i=S(n,-1,-1),a=Jt(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=ft(i.filter(e=>this.isNumber(r[e])))[0]||[];return Jt(o)<a?1/0:Yt(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&So(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){let n=new Set;return Ms(t)?(n.add(js(t).numberOfCols===1?`COL`:`ROW`),n):(this.lastColIsEmpty(e,t)&&n.add(`ROW`),this.lastRowIsEmpty(e,t)&&n.add(`COL`),n.size===0&&n.add(`COL`),n)}sumDimensions(e,t,n){return[...n.has(`COL`)?this.sumColumns(t,e):[],...n.has(`ROW`)?this.sumRows(t,e):[]]}sumTotal(e){let{bottom:t,right:n}=e;return{position:{col:n,row:t},zone:{...e,top:t,right:n-1}}}sumColumns(e,t){let n=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,n.bottom-1)},Fs(n).map(t=>({position:t,zone:{...e,right:t.col,left:t.col}}))}sumRows(e,t){let n=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,n.right-1)},Fs(n).map(t=>({position:t,zone:{...e,top:t.row,bottom:t.row}}))}dispatchCellUpdates(e,t){for(let n of t){let{col:t,row:r}=n.position;this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:`=SUM(${this.getters.zoneToXC(e,n.zone)})`})}}nextEmptyRow(e,t){let n=t.bottom+1,{left:r,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:n,top:n,left:r,right:i});)n++;return{...t,top:n,bottom:n}}nextEmptyCol(e,t){let n=t.right+1,{top:r,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:n,right:n,top:r,bottom:i});)n++;return{...t,left:n,right:n}}transpose(e){return new Set([...e.values()].map(e=>e===`COL`?`ROW`:`COL`))}};let EU=new class extends g{addTransformation(e,t,n){this.content[e]||(this.content[e]=new Map);for(let r of t)this.content[e].set(r,n);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}},DU=new class extends g{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};EU.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],RU),EU.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],RU),EU.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],jU),EU.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`],MU),EU.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],NU),EU.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],PU),EU.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],FU),EU.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],FU),EU.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],IU),EU.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],IU),EU.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],LU),EU.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],zU),EU.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],zU),EU.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],AU),EU.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],kU),EU.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],OU),EU.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],OU);function OU(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=Id(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function kU(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function AU(e,t){if(e.pivotId!==t.pivotId)return e}function jU(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function MU(e,t){if(e.figureId!==t.figureId)return e}function NU(e,t){return e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`}),e.name===t.name?{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,e=>(parseInt(e)+1).toString()):`${e.name}~`,position:e.position+1}:e}function PU(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!Ds(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function FU(e,t){if(e.sheetId!==t.sheetId||(e.type===`FREEZE_COLUMNS`?`COL`:`ROW`)!==t.dimension)return e;let n=e.quantity;if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);for(let t of e)n>t&&n--}if(t.type===`ADD_COLUMNS_ROWS`){let e=t.position===`before`?t.base-1:t.base;n=n>e?n+t.quantity:n}return n>0?{...e,quantity:n}:void 0}function IU(e,t){if(e.sheetId!==t.sheetId)return e;let n=Id(e.zone,t);if(!n)return;let r=e.newTableRange?Ld(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function LU(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:Rk.styleId}}:e}function RU(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=Wc(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=Uc(jt(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function zU(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n=S(e.start,e.end+1),r=[];if(t.type===`REMOVE_COLUMNS_ROWS`?r=Wc(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=Uc(jt(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}function BU(e,t){let n=e.content&&lS(e.sheetId,e.content,t);return{...e,content:n}}DU.add(`UPDATE_CELL`,BU);function VU(e,t){let n=e.cf.rule;if(e={...e,cf:{...e.cf}},n.type===`CellIsRule`)e.cf.rule={...n,values:n.values.map(n=>lS(e.sheetId,n,t))};else if(n.type===`ColorScaleRule`){let{minimum:r,maximum:i,midpoint:a}=n;e.cf.rule={...n,minimum:{...r,value:r.value&&lS(e.sheetId,r.value,t)},maximum:{...i,value:i.value&&lS(e.sheetId,i.value,t)},midpoint:a?{...a,value:lS(e.sheetId,a.value,t)}:void 0}}else if(n.type===`IconSetRule`){let{upperInflectionPoint:r,lowerInflectionPoint:i}=n;e.cf.rule={...n,upperInflectionPoint:{...r,value:lS(e.sheetId,r.value,t)},lowerInflectionPoint:{...i,value:lS(e.sheetId,i.value,t)}}}else n.type===`DataBarRule`&&(e.cf.rule={...n,rangeValues:n.rangeValues?uS(e.sheetId,n.rangeValues,t).range:void 0});return e}DU.add(`ADD_CONDITIONAL_FORMAT`,VU);function HU(e,t){return e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}},e.rule.criterion.values=e.rule.criterion.values.map(n=>lS(e.sheetId,n,t)),e}DU.add(`ADD_DATA_VALIDATION_RULE`,HU);function UU(e,t){return e=b(e),e.pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=lS(e.computedBy.sheetId,e.computedBy.formula,t))}),e}DU.add(`ADD_PIVOT`,UU),DU.add(`UPDATE_PIVOT`,UU),DU.add(`CREATE_CHART`,WU),DU.add(`UPDATE_CHART`,WU);function WU(e,t){return{...e,definition:yD(e.sheetId,e.definition,t)}}let GU=[{match:or,fn:XU},{match:cr,fn:ZU},{match:dr,fn:QU},{match:ur,fn:tW},{match:sr,fn:eW},{match:lr,fn:$U}];function KU(e,t){let n=EU.getTransformation(e.type,t.type),r=n?n(e,t):YU(e,t);return r&&qU(r,t)}function qU(e,t){let n=DU.get(e.type);if(!n)return e;let r=jc(t);return r?n(e,r):e}function JU(e,t){let n=[...e],r=new Set(EU.getKeys());for(let e of t)(r.has(e.type)||Mc.contains(e.type))&&(n=n.reduce((t,n)=>{let r=KU(n,e);return r&&t.push(r),t},[]));return n}function YU(e,t){for(let{match:n,fn:r}of GU)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function XU(e,t){if(!(`sheetId`in t))return e;let n=t.type===`DELETE_SHEET`&&t.sheetId;return e.sheetId===n?`IGNORE_COMMAND`:e.type===`CREATE_SHEET`||t.type===`CREATE_SHEET`||e.sheetId!==t.sheetId?e:`SKIP_TRANSFORMATION`}function ZU(e,t){let n=XU(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=Id(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function QU(e,t){let n=XU(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=Id(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function $U(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>Ld(e,t)).filter(C);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function eW(e,t){let n=XU(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;if(t.type!==`ADD_COLUMNS_ROWS`&&t.type!==`REMOVE_COLUMNS_ROWS`)return`SKIP_TRANSFORMATION`;if(t.dimension!==e.dimension)return e;let r=[];return t.type===`REMOVE_COLUMNS_ROWS`?r=Wc(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=Uc(jt(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function tW(e,t){let n=XU(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?nW(e,t):t.type===`ADD_MERGE`?rW(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function nW(e,t){let n=t.dimension===`COL`?`col`:`row`,r=e[n];if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);if(e.includes(r))return`IGNORE_COMMAND`;for(let t of e)r>=t&&r--}return t.type===`ADD_COLUMNS_ROWS`&&(r>t.base||r===t.base&&t.position===`before`)&&(r+=t.quantity),{...e,[n]:r}}function rW(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&ks(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var iW=class{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,n,r,i,a){this.rootCommand=r,this.timestamp=a,this.id=e,this.clientId=t,this._commands=[...n],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}},aW=class extends Error{},oW=class extends Rd{revisions;transportService;serverRevisionId;clients={};clientId=`local`;debouncedMove;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new gl;lastLocalOperation;constructor(e,t,n=We){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.debouncedMove=Et(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new iW(this.uuidGenerator.uuidv4(),this.clientId,t,e,n,Date.now());this.revisions.append(r.id,r),e.type!==`REQUEST_REDO`&&(this.lastLocalOperation=r),this.trigger(`new-local-state-update`,{id:r.id}),this.sendUpdateMessage({type:`REMOTE_REVISION`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:r.id,clientId:r.clientId,commands:r.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_UNDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:`local`,name:`local`},this.clientId=`local`),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this)),this.awaitingClientPosition&&=(this._move(this.awaitingClientPosition),void 0)}loadInitialMessages(e){let t=performance.now(),n=e.reduce((e,t)=>e+(t.type===`REMOTE_REVISION`?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(let t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug(`Replayed`,n,`commands in`,performance.now()-t,`ms`)}async leave(e){e&&Object.keys(this.clients).length===1&&this.lastRevisionMessage&&this.lastRevisionMessage?.type!==`SNAPSHOT_CREATED`&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:`CLIENT_LEFT`,clientId:this.clientId,version:1})}async snapshot(e){if(this.pendingMessages.length!==0)return;let t=this.uuidGenerator.uuidv4();await this.transportService.sendMessage({type:`SNAPSHOT`,nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getCurrentClient(){return this.getClient(this.clientId)}getClient(e){let t=this.clients[e];if(!t)throw new aW(`The client left the session`);return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(C))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return this.pendingMessages.length===0}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId]){this.awaitingClientPosition=e;return}let t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;let n=t?`CLIENT_MOVED`:`CLIENT_JOINED`,r=this.getCurrentClient();this.clients[this.clientId]={...r,position:e},this.transportService.sendMessage({type:n,version:1,client:{...r,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){if(this.isWrongServerRevisionId(e)){this.trigger(`unexpected-revision-id`);return}switch(e.type){case`CLIENT_MOVED`:this.onClientMoved(e);break;case`CLIENT_JOINED`:this.onClientJoined(e);break;case`CLIENT_LEFT`:this.onClientLeft(e);break;case`REVISION_REDONE`:this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-redone`,{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case`REVISION_UNDONE`:this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-undone`,{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case`REMOTE_REVISION`:let{clientId:t,commands:n,timestamp:r}=e,i=new iW(e.nextRevisionId,t,n,void 0,void 0,r);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);let t=this.pendingMessages.filter(e=>e.type===`REMOTE_REVISION`).map(e=>e.commands).flat();this.trigger(`remote-revision-received`,{commands:JU(n,t)})}break;case`SNAPSHOT_CREATED`:{let t=new iW(e.nextRevisionId,`server`,[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger(`snapshot`),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger(`collaborative-event-received`)}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;let t=this.clients[this.clientId];if(t){let{position:e}=t;e&&this.transportService.sendMessage({type:`CLIENT_MOVED`,version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),!this.waitingAck&&this.sendPendingMessage()}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if(e.type===`REMOTE_REVISION`){let t=this.revisions.get(e.nextRevisionId);t.commands.length===0&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.
|
|
1948
1948
|
${JSON.stringify(e)}`);this.waitingAck=!0,this.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch((e.type===`REVISION_UNDONE`||e.type===`REVISION_REDONE`)&&(this.waitingUndoRedoAck=!1),e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`SNAPSHOT_CREATED`:this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.lastRevisionMessage=e,this.sendPendingMessage();break;case`REVISION_UNDONE`:{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId);let t=this.pendingMessages.findIndex(e=>e.type===`REMOTE_REVISION`);t!==-1&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}isAlreadyProcessed(e){if(e.type===`CLIENT_MOVED`&&e.client.id===this.clientId)return!0;switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter(({type:e})=>e!==`REVISION_REDONE`&&e!==`REVISION_UNDONE`)}},sW=class extends SU{static getters=[`getClientsToDisplay`,`getClient`,`getCurrentClient`,`getConnectedClients`,`isFullySynchronized`];static layers=[`Selection`];colors=new Rn(12);session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}getClient(e){return this.session.getClient(e)}getCurrentClient(){return this.session.getCurrentClient()}getConnectedClients(){return[...this.session.getConnectedClients()].map(e=>({...e,color:this.colors.get(e.id)}))}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getCurrentClient()}catch(e){if(e instanceof aW)return[];throw e}let e=this.getters.getActiveSheetId(),t=[];for(let n of this.getters.getConnectedClients())n.id!==this.getters.getCurrentClient().id&&n.position&&n.position.sheetId===e&&this.isPositionValid(n.position)&&t.push({...n,position:n.position});return t}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getters.getActiveSheetId();for(let e of this.getClientsToDisplay()){let{row:i,col:a}=e.position,o=this.getters.expandZone(r,{top:i,bottom:i,left:a,right:a}),{x:s,y:c,width:l,height:u}=this.getters.getVisibleRect(o);if(l<=0||u<=0)continue;let d=e.color;t.fillStyle=`${d}10`,t.lineWidth=4*n,t.strokeStyle=d,t.globalCompositeOperation=`multiply`,t.fillRect(s,c,l,u),t.globalCompositeOperation=`source-over`,t.strokeRect(s,c,l,u),t.font=`bold ${Ve+1}px ${He}`}}},cW=class extends SU{allowDispatch(e){switch(e.type){case`REMOVE_DUPLICATES`:return this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique))}return`Success`}handle(e){switch(e.type){case`REMOVE_DUPLICATES`:this.removeDuplicates(e.columns,e.hasHeader);break;case`TRIM_WHITESPACE`:this.trimWhitespace();break}}removeDuplicates(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getSelectedZone();t&&(r.top+=1);let i=this.getUniqueRowsIndexes(n,r.top,r.bottom,e),a=i.length;if(a===js(r).numberOfRows){this.notifyRowsRemovedAndRemaining(0,a);return}let o=i.map(e=>({left:r.left,top:e,right:r.right,bottom:e})),s=new Td(this.getters,this.dispatch),c=s.copy(vl(n,o),!1);if(!c)return;this.dispatch(`CLEAR_CELLS`,{target:[r],sheetId:n});let l={left:r.left,top:r.top,right:r.left,bottom:r.top};s.paste({zones:[l],sheetId:n},c,{isCutOperation:!1});let u={left:r.left,top:r.top-+!!t,right:r.right,bottom:r.top+a-1};this.selection.selectZone({cell:{col:u.left,row:u.top},zone:u});let d=r.bottom-r.top+1-a;this.notifyRowsRemovedAndRemaining(d,a)}getUniqueRowsIndexes(e,t,n,r){let i=new Map;for(let a of S(t,n+1)){let t=r.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:a}).value);Object.values(i).some(e=>w(e,t))||(i[a]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:`info`,text:E(`%s duplicate rows found and removed.
|
|
1949
1949
|
%s unique rows remain.`,e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return this.getters.getSelectedZones().length===1?`Success`:`MoreThanOneRangeSelected`}checkNoMergeInZone(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?`WillRemoveExistingMerge`:`Success`}checkRangeContainsValues(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedZone();return e.hasHeader&&(n.top+=1),this.getters.getEvaluatedCellsInZone(t,n).every(e=>e.type===`empty`)?`EmptyTarget`:`Success`}checkNoColumnProvided(e){return e.columns.length===0?`NoColumnsProvided`:`Success`}checkColumnsIncludedInZone(e){let t=this.getters.getSelectedZone();return e.columns.some(e=>e<t.left||e>t.right)?`ColumnsNotIncludedInZone`:`Success`}checkColumnsAreUnique(e){return e.columns.length===new Set(e.columns).size?`Success`:`DuplicatesColumnsSelected`}trimWhitespace(){let e=R(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(Fs).flat()){let e=this.getters.getCell({col:r,row:i,sheetId:t});if(!e)continue;let a=Gt(e.content);a!==e.content&&(n+=1,this.dispatch(`UPDATE_CELL`,{sheetId:t,col:r,row:i,content:a}))}let r=n?E(`Trimmed whitespace from %s cells.`,n):E(`No selected cells had whitespace trimmed.`);this.ui.notifyUI({type:`info`,text:r,sticky:!1})}},lW=class extends SU{handle(e){switch(e.type){case`SET_DECIMAL`:this.setDecimal(e.sheetId,e.target,e.step);break;case`SET_FORMATTING_WITH_PIVOT`:this.setContextualFormat(e.sheetId,e.target,e.format);break}}setContextualFormat(e,t,n){let r=[],i={};for(let n of R(t))for(let t=n.left;t<=n.right;t++)for(let a=n.top;a<=n.bottom;a++){let n={sheetId:e,col:t,row:a},o=this.getters.getPivotCellFromPosition(n);if(this.isSpilledPivotValueFormula(n,o)){r.push(n);let e=this.getters.getPivotIdFromPosition(n)||``;i[e]??=new Set,i[e].add(o.measure)}}let a=R(r.map(z));for(let e in i){let t=i[e],r=this.getters.getPivotCoreDefinition(e);this.dispatch(`UPDATE_PIVOT`,{pivotId:e,pivot:{...r,measures:r.measures.map(e=>t.has(e.id)?{...e,format:n}:e)}})}this.dispatch(`SET_FORMATTING`,{sheetId:e,target:a,format:``}),this.dispatch(`SET_FORMATTING`,{sheetId:e,target:R(t,a),format:n})}isSpilledPivotValueFormula(e,t){let n=this.getters.getCell(e);return t.type===`VALUE`&&!n?.isFormula}setDecimal(e,t,n){let r={};for(let i of R(t))for(let t of Fs(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=zo(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=R(r[t].map(e=>z(e)));this.setContextualFormat(e,n,t)}}getCellNumberFormat(e){for(let t of[e]){let e=this.getters.getEvaluatedCell(t);if(e.type===`number`&&!(e.format&&So(e.format)))return e.format||Eo(e.value)}}},uW=class extends SU{static getters=[`getGeoJsonFeatures`,`geoFeatureNameToId`,`getGeoChartAvailableRegions`];geoJsonService;geoJsonCache={};constructor(e){super(e),this.geoJsonService=e.external.geoJsonService}getGeoChartAvailableRegions(){return this.geoJsonService?this.geoJsonService.getAvailableRegions()||[]:(console.error(`No geoJsonService provided to the model`),[])}getGeoJsonFeatures(e){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}let t=this.geoJsonCache[e];if(!(t instanceof Promise)){if(t!==void 0)return t??void 0;this.geoJsonCache[e]=new Promise(async t=>{let n=await this.geoJsonService?.getTopoJson(e);this.geoJsonCache[e]=this.convertToGeoJson(n),this.dispatch(`EVALUATE_CHARTS`),t()})}}geoFeatureNameToId(e,t){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}return this.geoJsonService.geoFeatureNameToId(e,t)}convertToGeoJson(e){if(!e)return null;if(e.type===`Topology`){let t=window.ChartGeo.topojson.feature(e,Object.values(e.objects)[0]);return t.type===`FeatureCollection`?t.features:[t]}else if(e.type===`FeatureCollection`)return e.features;throw Error(`Invalid TopoJSON`)}},dW=class extends SU{static getters=[`getNextVisibleCellPosition`,`findVisibleHeader`,`findLastVisibleColRowIndex`,`findFirstVisibleColRowIndex`,`isRowHidden`,`isColHidden`,`isHeaderHidden`];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,n){return t===`COL`?this.isColHidden(e,n):this.isRowHidden(e,n)}getNextVisibleCellPosition({sheetId:e,col:t,row:n}){return{sheetId:e,col:this.findVisibleHeader(e,`COL`,t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,`ROW`,n,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,n,r){if(n<=r){for(let i=n;i<=r;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}if(n>r){for(let i=n;i>=r;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}}findLastVisibleColRowIndex(e,t,{last:n,first:r}){return S(n,r,-1).find(n=>!this.isHeaderHidden(e,t,n))||r}findFirstVisibleColRowIndex(e,t){let n=this.getters.getNumberHeaders(e,t);for(let r=0;r<n;r++)if(t===`COL`&&!this.isColHidden(e,r)||t===`ROW`&&!this.isRowHidden(e,r))return r}exportForExcel(e){for(let t of e.sheets)for(let[e,n]of Object.entries(t.rows))n.isHidden=this.isRowHidden(t.id,Number(e))}},fW=class extends SU{static getters=[];allowDispatch(e){switch(e.type){case`DUPLICATE_PIVOT_IN_NEW_SHEET`:if(!this.getters.isExistingPivot(e.pivotId))return`PivotIdNotFound`;if(!this.getters.getPivot(e.pivotId).isValid())return`PivotInError`;break}return`Success`}handle(e){switch(e.type){case`INSERT_NEW_PIVOT`:this.insertNewPivot(e.pivotId,e.newSheetId);break;case`DUPLICATE_PIVOT_IN_NEW_SHEET`:this.duplicatePivotInNewSheet(e.pivotId,e.newPivotId,e.newSheetId);break;case`INSERT_PIVOT_WITH_TABLE`:this.insertPivotWithTable(e.sheetId,e.col,e.row,e.pivotId,e.table,e.pivotMode);break;case`SPLIT_PIVOT_FORMULA`:this.splitPivotFormula(e.sheetId,e.col,e.row,e.pivotId)}}insertNewPivot(e,t){Ws(this.getters.getSelectedZone())===1&&this.selection.selectTableAroundSelection();let n=this.getters.getActiveSheetId();this.dispatch(`ADD_PIVOT`,{pivotId:e,pivot:{dataSet:{zone:this.getters.getSelectedZone(),sheetId:n},columns:[],rows:[],measures:[],name:E(`New pivot`),type:`SPREADSHEET`}});let r=this.getters.getSheetIds().findIndex(e=>e===n)+1,i=this.getters.getPivotFormulaId(e);this.dispatch(`CREATE_SHEET`,{sheetId:t,name:E(`Pivot #%(formulaId)s`,{formulaId:i}),position:r}),this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:n,sheetIdTo:t});let a=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,a.getCollapsedTableStructure().export(),`dynamic`)}duplicatePivotInNewSheet(e,t,n){this.dispatch(`DUPLICATE_PIVOT`,{pivotId:e,newPivotId:t,duplicatedPivotName:E(`%s (copy)`,this.getters.getPivotCoreDefinition(e).name)});let r=this.getters.getActiveSheetId(),i=this.getters.getSheetIds().indexOf(r)+1,a=this.getters.getPivotFormulaId(t),o=this.getters.getPivotName(t);if(this.dispatch(`CREATE_SHEET`,{sheetId:n,name:this.getPivotDuplicateSheetName(E(`%(newPivotName)s (Pivot #%(formulaId)s)`,{newPivotName:o,formulaId:a})),position:i}).isSuccessful){this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:r,sheetIdTo:n});let i=this.getters.getPivot(e);this.insertPivotWithTable(n,0,0,t,i.getCollapsedTableStructure().export(),`dynamic`)}}getPivotDuplicateSheetName(e){let t=this.getters.getSheetIds().map(e=>this.getters.getSheetName(e));return $t(dt(e),t)}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new iV(o,s,c,l||{}),d=u.columns.length-1;this.resizeSheet(e,t,n,u);let f=this.getters.getPivotFormulaId(r),p;a===`dynamic`?(this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:n,content:`=PIVOT(${f})`}),p={left:t,right:t,top:n,bottom:n}):(this.dispatch(`INSERT_PIVOT`,{sheetId:e,col:t,row:n,pivotId:r,table:u.export()}),p={left:t,right:t+u.getNumberOfDataColumns(),top:n,bottom:n+d+u.rows.length}),this.dispatch(`CREATE_TABLE`,{tableType:a,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,p)],config:{...tt,numberOfHeaders:d}})}resizeSheet(e,t,n,r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}splitPivotFormula(e,t,n,r){let i=this.getters.getSpreadZone({sheetId:e,col:t,row:n});if(!i)return;let a=this.getters.getPivotFormulaId(r),o=new Map;for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++){let r={sheetId:e,col:t,row:n};o.set(r,this.getters.getPivotCellFromPosition(r))}for(let[e,t]of o)this.dispatch(`UPDATE_CELL`,{...e,content:hd(a,t)});if(this.getters.getCoreTable({sheetId:e,col:t,row:n})?.type===`dynamic`){let r=z({col:t,row:n}),a=this.getters.getRangeDataFromZone(e,i);this.dispatch(`UPDATE_TABLE`,{sheetId:e,zone:r,newTableRange:a,tableType:`static`})}}},pW=class extends SU{allowDispatch(e){switch(e.type){case`SORT_CELLS`:return ks(e.col,e.row,e.zone)?this.checkValidations(e,this.checkMerge,this.checkMergeSizes,this.checkArrayFormulaInSortZone):`InvalidSortAnchor`}return`Success`}handle(e){switch(e.type){case`SORT_CELLS`:this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{});break}}checkMerge({sheetId:e,zone:t}){return this.getters.doesIntersectMerge(e,t)&&Fs(t).some(({col:t,row:n})=>!this.getters.isInMerge({sheetId:e,col:t,row:n}))?`InvalidSortZone`:`Success`}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return`Success`;let n=this.getters.getMerges(e).filter(e=>Ds(e,t)),r=js(n[0]),[i,a]=[r.numberOfCols,r.numberOfRows];return n.every(e=>{let[t,n]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&n===a})?`Success`:`InvalidSortZone`}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return Fs(t).some(({col:t,row:n})=>{let r=this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:n});return r&&!w(r,{sheetId:e,col:t,row:n})})?`SortZoneWithArrayFormulas`:`Success`}hasHeader(e,t){if(t[0].length===1)return!1;let n=t.map(t=>t.map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).type));return n[0][0]===`empty`&&(n=n.slice(1)),n.some(e=>e[0]===`empty`)?!1:!!n.some(e=>e[1]!==`empty`&&e[0]!==e[1])}sortZone(e,t,n,r,i){let[a,o]=this.mainCellsSteps(e,n),s=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,c=Object.assign({},n),l=this.mainCells(e,n);!i.sortHeaders&&this.hasHeader(e,l)&&(c.top+=o),l=this.mainCells(e,c);let u=l[s-c.left],d=Mg(u.map(e=>this.getters.getEvaluatedCell(e)),r,!!i.emptyCellAsZero).map(e=>e.index),[f,p]=[l.length,l[0].length],m=[];for(let e=0;e<f;e++)for(let t=0;t<p;t++){let{col:n,row:r,sheetId:i}=l[e][d[t]],s=this.getters.getCell({sheetId:i,col:n,row:r}),u=c.left+e*a,f=c.top+t*o,p={sheetId:i,col:u,row:f,content:``};if(s){let e=s.content;if(s.isFormula){let t=this.getters.getCellPosition(s.id);e=this.getters.getTranslatedCellFormula(i,0,f-t.row,s.compiledFormula.tokens)}p.style=s.style,p.content=e,p.format=s.format}m.push(p)}m.forEach(e=>this.dispatch(`UPDATE_CELL`,e))}mainCellsSteps(e,t){let n=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[n?n.right-n.left+1:1,n?n.bottom-n.top+1:1]}mainCells(e,t){let[n,r]=this.mainCellsSteps(e,t),i=[],a=S(t.left,t.right+1,n),o=S(t.top,t.bottom+1,r);for(let t of a){let n=[];i.push(n);for(let r of o)n.push({sheetId:e,col:t,row:r})}return i}},mW=class extends SU{static getters=[`shouldShowFormulas`];showFormulas=!1;handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.showFormulas=e.show;break}}shouldShowFormulas(){return this.showFormulas}},hW=class extends SU{static getters=[`getCellWidth`,`getTextWidth`,`getCellText`,`getCellMultiLineText`,`getContiguousZone`,`computeTextYCoordinate`];ctx=document.createElement(`canvas`).getContext(`2d`);allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case`AUTORESIZE_COLUMNS`:for(let t of e.cols){let n=this.getColMaxWidth(e.sheetId,t);n!==0&&this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:[t],dimension:`COL`,size:n,sheetId:e.sheetId})}break;case`AUTORESIZE_ROWS`:this.autoResizeRows(e.sheetId,e.rows);break;case`DELETE_UNFILTERED_CONTENT`:let t=[];for(let n of e.target){let r=ft(S(n.top,n.bottom+1).filter(t=>!this.getters.isRowFiltered(e.sheetId,t)));for(let e of r)t.push({...n,top:e[0],bottom:e[e.length-1]})}this.dispatch(`DELETE_CONTENT`,{sheetId:e.sheetId,target:t});break}}getCellWidth(e){let t=this.getters.getCellComputedStyle(e),n=0,r=this.getters.getEvaluatedCell(e).formattedValue;if(r){let e=cl(this.ctx,r,t,void 0);n+=Math.max(...e.map(e=>$c(this.ctx,e,t)))}for(let t of this.getters.getCellIcons(e))n+=t.margin+t.size;if(this.getters.getDataValidationChipStyle(e)&&(n+=10),n===0)return 0;if(n+=8,t.wrapping===`wrap`){let t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,n)}return n}getTextWidth(e,t){return $c(this.ctx,e,t)}getCellText(e,t){let n=this.getters.getCell(e),r=this.getters.getLocale();if(t?.showFormula&&n?.isFormula)return $l(n.content,r);if(t?.showFormula&&!n?.content)return``;{let i=this.getters.getEvaluatedCell(e),a=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>$c(this.ctx,e,n?.style||{})}:void 0;return L(i.value,{format:i.format,locale:r,formatWidth:a})}}getCellMultiLineText(e,t){let n=this.getters.getCellStyle(e),r=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.formatWidth});return cl(this.ctx,r,n,t.wrapText?t.maxWidth:void 0)}computeTextYCoordinate(e,t,n=ze,r=1){let i=e.y+1,a=Jc(t,r);if(e.height>a+8){if(n===`middle`)return Math.ceil(i+(e.height-a)/2);if(n===`bottom`)return i+e.height-a-4}return i+4}getContiguousZone(e,t){let n=t=>{for(let n of S(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:n,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:n,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(let n of S(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:n}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:n}))return{...t,right:t.right+1}}return t},r=!1,i=t;do{r=!1;let e=n(i);Es(i,e)||(r=!0,i=e)}while(r);return i}isCellEmpty(e){let t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===`empty`}getColMaxWidth(e,t){let n=Fs(this.getters.getColsZone(e,t,t)).map(t=>this.getCellWidth({sheetId:e,...t}));return Math.max(0,Jt(n))}checkSheetExists(e){return`sheetId`in e&&this.getters.tryGetSheet(e.sheetId)===void 0?`InvalidSheetId`:`Success`}checkZonesAreInSheet(e){let t=`sheetId`in e?e.sheetId:this.getters.tryGetActiveSheetId();if(`ranges`in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId)))return`InvalidSheetId`;let n=this.getters.getCommandZones(e);return!t&&n.length>0?`NoActiveSheet`:t&&n.length>0?this.getters.checkZonesExistInSheet(t,n):`Success`}autoResizeRows(e,t){let n=[];for(let r of t){let t=0;for(let n of this.getters.getRowCells(e,r)){let r=this.getters.getCellById(n);if(!r)continue;let i=this.getters.getCellPosition(r.id),a=this.getters.getColSize(e,i.col);if(r.isFormula||this.getters.getArrayFormulaSpreadingOn(i)){let e=this.getters.getEvaluatedCell(i).formattedValue,n=Xc(this.ctx,e,r?.style,a);n>t&&n>23&&(t=n)}else{let e=r.content,n=Xc(this.ctx,e,r?.style,a);n>=t&&n>23&&(t=0)}}n.push(t||null)}let r=new Map(n.map(e=>[e,[]]));for(let e=0;e<n.length;e++)r.get(n[e])?.push(t[e]);for(let[t,n]of r)this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:n,dimension:`ROW`,size:t,sheetId:e})}},gW=class extends SU{static getters=[`getCellTableStyle`,`getCellTableBorder`];tableStyles={};handle(e){if(fr.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(vW(e)){`sheetId`in e?delete this.tableStyles[e.sheetId]:this.tableStyles={};return}}finalize(){for(let e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(let t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}getCellTableBorder(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}computeTableStyle(e,t){return kt(()=>{let{config:n,numberOfCols:r,numberOfRows:i}=this.getTableRuntimeConfig(e,t),a=rF(n,this.getters.getTableStyle(t.config.styleId),r,i),o=this.getTableMapping(e,t),s={borders:{},styles:{}};for(let e=0;e<r;e++){let t=o.colMapping[e];s.borders[t]={},s.styles[t]={};for(let n=0;n<i;n++){let r=o.rowMapping[n];s.borders[t][r]=a.borders[e][n],s.styles[t][r]=a.styles[e][n]}}return s})}getTableRuntimeConfig(e,t){let n=t.range.zone,r={...t.config},i=n.right-n.left+1,a=n.bottom-n.top+1;for(let i=n.top;i<=n.bottom;i++)this.getters.isRowHidden(e,i)&&(a--,i-n.top<t.config.numberOfHeaders&&(r.numberOfHeaders--,r.numberOfHeaders<0&&(r.numberOfHeaders=0)),i===n.bottom&&(r.totalRow=!1));for(let t=n.left;t<=n.right;t++)this.getters.isColHidden(e,t)&&(i--,t===n.left&&(r.firstColumn=!1),t===n.right&&(r.lastColumn=!1));return{config:r,numberOfCols:i,numberOfRows:a}}getTableMapping(e,t){let n={},r={},i=0,a=0,o=t.range.zone;for(let t=o.left;t<=o.right;t++)if(!this.getters.isColHidden(e,t)){n[i]=t,i++;for(let t=o.top;t<=o.bottom;t++)this.getters.isRowHidden(e,t)||(r[a]=t,a++)}return{colMapping:n,rowMapping:r}}};let _W=new Set([`HIDE_COLUMNS_ROWS`,`UNHIDE_COLUMNS_ROWS`,`UNFOLD_HEADER_GROUP`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`FOLD_ALL_HEADER_GROUPS`,`UNFOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`CREATE_TABLE`,`UPDATE_TABLE`,`UPDATE_FILTER`,`REMOVE_TABLE`,`RESIZE_TABLE`,`CREATE_TABLE_STYLE`,`REMOVE_TABLE_STYLE`]);function vW(e){return _W.has(e.type)}var yW=class extends SU{static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles={};borders={};handle(e){if(fr.has(e.type)||e.type===`UPDATE_CELL`||e.type===`SET_FORMATTING`||e.type===`CLEAR_FORMATTING`||e.type===`ADD_DATA_VALIDATION_RULE`||e.type===`REMOVE_DATA_VALIDATION_RULE`||e.type===`EVALUATE_CELLS`){this.styles={},this.borders={};return}if(vW(e)){`sheetId`in e?(delete this.styles[e.sheetId],delete this.borders[e.sheetId]):(this.styles={},this.borders={});return}if(hr.has(e.type)){this.styles={};return}if(gr.has(e.type)){this.borders={};return}}getCellComputedBorder(e){let{sheetId:t,row:n,col:r}=e;return this.borders[t]?.[n]?.[r]===void 0?(this.borders[t]||(this.borders[t]={}),this.borders[t][n]||(this.borders[t][n]={}),this.borders[t][n][r]||(this.borders[t][n][r]=this.computeCellBorder(e)),this.borders[t][n][r]):this.borders[t][n][r]}getCellComputedStyle(e){let{sheetId:t,row:n,col:r}=e;return this.styles[t]?.[n]?.[r]===void 0?(this.styles[t]||(this.styles[t]={}),this.styles[t][n]||(this.styles[t][n]={}),this.styles[t][n][r]||(this.styles[t][n][r]=this.computeCellStyle(e)),this.styles[t][n][r]):this.styles[t][n][r]}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...Pt(this.getters.getCellTableBorder(e)||{}),...Pt(t)};return Tt(n)?null:n}computeCellStyle(e){let t=this.getters.getCell(e),n=this.getters.getCellConditionalFormatStyle(e),r=this.getters.getCellTableStyle(e),i=this.getters.getDataValidationCellStyle(e),a={...Pt(r),...Pt(i),...Pt(t?.style),...Pt(n)};return this.getters.getEvaluatedCell(e).link&&!a.textColor&&(a.textColor=le),a}},bW=class extends SU{static getters=[`hasBooleanValidationInZones`];handle(e){switch(e.type){case`TOGGLE_CHECKBOX`:this.toggleCheckbox(e.sheetId,e.target);break}}hasBooleanValidationInZones(e){let t=this.getters.getActiveSheetId();for(let n of e)for(let e=n.left;e<=n.right;e++)for(let r=n.top;r<=n.bottom;r++)if(this.getters.isCellValidCheckbox({col:e,row:r,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n={col:t,row:r,sheetId:e};if(this.getters.isCellValidCheckbox(n)){let e=this.getters.getEvaluatedCell(n).value?`FALSE`:`TRUE`;this.dispatch(`UPDATE_CELL`,{...n,content:e})}}}},xW=class extends SU{handle(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:if(e.rule.criterion.type===`isBoolean`){let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));for(let e of Oc(t)){let t=this.getters.getCell(e),n=this.getters.getEvaluatedCell(e);if(!t?.content)this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`});else if(t?.content&&n.type===`empty`){let n;if(t.content.startsWith(`=`)){let r=this.getters.evaluateFormula(e.sheetId,t.content);n=(Or(r)?r[0][0]:r)?.toString()}else n=t.content;(!n||!mt(n))&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}else n.type!==`boolean`&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}}}}};let SW=[CW,wW,EW,DW];function CW(e,t){return`sheetId`in t?{...b(t),sheetId:e.getActiveSheetId()}:t}function wW(e,t){return!(`target`in t)||!Array.isArray(t.target)?t:{...b(t),target:e.getSelectedZones()}}function TW(e,t){return`zone`in t?{...b(t),zone:e.getSelectedZone()}:t}function EW(e,t){if(!(`row`in t)||!(`col`in t))return t;let{col:n,row:r}=e.getActivePosition();return{...b(t),col:n,row:r}}function DW(e,t){return`ranges`in t?{...b(t),ranges:e.getSelectedZones().map(t=>e.getRangeDataFromZone(e.getActiveSheetId(),t))}:t}let OW=new gl;function kW(e,t){return{...CW(e,t),figureId:OW.smallUuid()}}function AW(e,t){return{...CW(e,t),figureId:OW.smallUuid()}}function jW(e,t){let n=EW(e,CW(e,t));return n.figureId=OW.smallUuid(),n}function MW(e,t){let n=b(t);n.sheetId=OW.smallUuid();let r=t.name||e.getSheet(e.getActiveSheetId()).name,i=r.match(/(.+?)\d*$/)?.[1]||r;return n.name=e.getNextSheetName(i),n}function NW(e,t){let n=e.getActivePosition();return{...CW(e,t),base:t.dimension===`COL`?n.col:n.row}}function PW(e,t){let n=e.getSelectedZone();return{...CW(e,t),elements:t.dimension===`COL`?S(n.left,n.right+1):S(n.top,n.bottom+1)}}function FW(e,t){let n=e.getSelectedZone();return{...b(t),zone:n}}function IW(e,t){let n=b(t),{top:r,bottom:i,left:a,right:o}=e.getSelectedZone();return`cols`in n?n.cols=S(a,o+1):`rows`in n&&(n.rows=S(r,i+1)),n}function LW(e,t){let n=e.getSelectedZone();return{...CW(e,t),col:n.left,row:n.top,zone:n}}function RW(e,t){return{type:`REPEAT_PASTE`,pasteOption:b(t.pasteOption),target:e.getSelectedZones()}}function zW(e,t){let n=e.getSelectedZone();return{...CW(e,t),start:t.dimension===`COL`?n.left:n.top,end:t.dimension===`COL`?n.right:n.bottom}}let BW=new g;BW.add(`UPDATE_CELL`,HW),BW.add(`CLEAR_CELL`,HW),BW.add(`CLEAR_CELLS`,HW),BW.add(`DELETE_CONTENT`,HW),BW.add(`ADD_MERGE`,HW),BW.add(`REMOVE_MERGE`,HW),BW.add(`SET_FORMATTING`,HW),BW.add(`CLEAR_FORMATTING`,HW),BW.add(`SET_BORDER`,HW),BW.add(`CREATE_TABLE`,HW),BW.add(`REMOVE_TABLE`,HW),BW.add(`HIDE_SHEET`,HW),BW.add(`ADD_COLUMNS_ROWS`,NW),BW.add(`REMOVE_COLUMNS_ROWS`,PW),BW.add(`HIDE_COLUMNS_ROWS`,PW),BW.add(`RESIZE_COLUMNS_ROWS`,PW),BW.add(`CREATE_SHEET`,MW),BW.add(`CREATE_FIGURE`,jW),BW.add(`CREATE_CHART`,kW),BW.add(`CREATE_IMAGE`,AW),BW.add(`GROUP_HEADERS`,zW),BW.add(`UNGROUP_HEADERS`,zW),BW.add(`UNFOLD_HEADER_GROUPS_IN_ZONE`,TW),BW.add(`FOLD_HEADER_GROUPS_IN_ZONE`,TW);let VW=new g;VW.add(`PASTE`,RW),VW.add(`INSERT_CELL`,FW),VW.add(`DELETE_CELL`,FW),VW.add(`AUTORESIZE_COLUMNS`,IW),VW.add(`AUTORESIZE_ROWS`,IW),VW.add(`SORT_CELLS`,LW),VW.add(`SUM_SELECTION`,HW),VW.add(`SET_DECIMAL`,HW),VW.add(`DELETE_UNFILTERED_CONTENT`,HW);function HW(e,t){let n=b(t);for(let t of SW)n=t(e,n);return n}function UW(e,t){if(t&&BW.contains(t.type))return BW.get(t.type)(e,t)}function WW(e,t,n){if(VW.contains(t.type))return VW.get(t.type)(e,t,n)}function GW(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:yr(e.rootCommand)?BW.contains(e.rootCommand.type):VW.contains(e.rootCommand.type)}function KW(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return yr(e.rootCommand)?UW(t,e.rootCommand):WW(t,e.rootCommand,e.commands)}var qW=class extends SU{static getters=[`canUndo`,`canRedo`];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on(`new-local-state-update`,this,this.onNewLocalStateUpdate),this.session.on(`snapshot`,this,()=>{this.undoStack=[],this.redoStack=[]})}allowDispatch(e){switch(e.type){case`REQUEST_UNDO`:if(!this.canUndo())return`EmptyUndoStack`;break;case`REQUEST_REDO`:if(!this.canRedo())return`EmptyRedoStack`;break}return`Success`}handle(e){switch(e.type){case`REQUEST_UNDO`:case`REQUEST_REDO`:this.requestHistoryChange(e.type===`REQUEST_UNDO`?`UNDO`:`REDO`)}}finalize(){}requestHistoryChange(e){let t=e===`UNDO`?this.undoStack.pop():this.redoStack.pop();if(!t){let e=this.getPossibleRevisionToRepeat();if(!e)return;let t=KW(e,this.getters);if(!t)return;if(!Array.isArray(t)){this.dispatch(t.type,t);return}for(let e of t)this.dispatch(e.type,e);return}e===`UNDO`?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0?!0:GW(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},JW=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,N(e.value)])}isValuePresent(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(n)}isHeaderPresent(e){let t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(n)}trackHeader(e){let t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}},YW=class extends SU{static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new JW,this.trackPresencePivotId=e.pivotId;break;case`PIVOT_STOP_PRESENCE_TRACKING`:this.trackPresencePivotId=void 0;break}}getPivotPresenceTracker(e){if(this.trackPresencePivotId===e){if(!this.tracker)throw Error(`Tracker not initialized`);return this.tracker}}},XW=class extends SU{static getters=[`getAutomaticSeparator`];allowDispatch(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:return this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e)}return`Success`}handle(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:this.splitIntoColumns(e);break}}getAutomaticSeparator(){let e=this.getters.getSelectedCells();for(let t of e)if(t.value&&t.type===`text`){let e=this.getAutoSeparatorForString(t.value);if(e)return e}return` `}getAutoSeparatorForString(e){for(let t of[`
|
|
1950
1950
|
`,`;`,`,`,` `,`.`])if(e.includes(t))return t}splitIntoColumns({separator:e,addNewColumns:t}){let n=this.getters.getSelectedZone(),r=this.getters.getActiveSheetId(),i=this.getSplittedCols(n,e);t&&this.addColsToAvoidCollisions(n,i),this.removeMergesInSplitZone(n,i),this.addColumnsToNotOverflowSheet(n,i);for(let e=0;e<i.length;e++){let t=n.top+e,a=i[e],o=n.left,s=this.getters.getCell({sheetId:r,col:o,row:t});if(!(a.length===1&&a[0]===s?.content))for(let[e,n]of a.entries())this.dispatch(`UPDATE_CELL`,{sheetId:r,col:o+e,row:t,content:Jl(n,this.getters.getLocale()),format:``,style:s?.style||null})}}getSplittedCols(e,t){if(!t)throw Error(`Separator cannot be empty`);let n=this.getters.getActiveSheetId(),r=[];for(let i of S(e.top,e.bottom+1)){let a=this.getters.getEvaluatedCell({sheetId:n,col:e.left,row:i}).formattedValue;r.push(this.splitAndRemoveTrailingEmpty(a,t))}return r}splitAndRemoveTrailingEmpty(e,t){let n=e.split(t);for(;n.length>1&&n[n.length-1]===``;)n.pop();return n}willSplittedColsOverwriteContent(e,t){let n=this.getters.getActiveSheetId();for(let r of S(e.top,e.bottom+1)){let i=t[r-e.top];for(let t=1;t<i.length;t++){let i=this.getters.getCell({sheetId:n,col:e.left+t,row:r});if(i&&i.content)return!0}}return!1}removeMergesInSplitZone(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length)),i={...e,right:e.left+r-1},a=this.getters.getMergesInZone(n,i);this.dispatch(`REMOVE_MERGE`,{sheetId:n,target:a})}addColsToAvoidCollisions(e,t){let n=this.getters.getActiveSheetId(),r=0;for(let i of S(e.top,e.bottom+1)){let a={sheetId:n,col:e.left,row:i},o=t[i-e.top],s=this.getColsToAddToAvoidCollision(a,o);r=Math.max(r,s)}r&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:e.left,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:r,position:`after`})}getColsToAddToAvoidCollision(e,t){let n=t.length;for(let t=1;t<n;t++){let r=e.col+t,i=this.getters.getCell({...e,col:r});if(i&&i.content)return n-t}return 0}addColumnsToNotOverflowSheet(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length-1)),i=this.getters.getNumberCols(n)-1;e.left+r>i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:i,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:e.left+r-i,position:`after`})}checkSingleColSelected(){return this.getters.isSingleColSelected()?`Success`:`MoreThanOneColumnSelected`}checkNonEmptySelector(e){return e.separator===``?`EmptySplitSeparator`:`Success`}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return`Success`;let t=this.getters.getSelectedZones()[0],n=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,n)?`SplitWillOverwriteContent`:`Success`}checkSeparatorInSelection({separator:e}){let t=this.getters.getSelectedCells();for(let n of t)if(n.formattedValue.includes(e))return`Success`;return`NoSplitSeparatorInSelection`}},ZW=class extends SU{handle(e){switch(e.type){case`AUTOFILL_TABLE_COLUMN`:let t=this.getters.getCoreTable(e),n=this.getters.getCell(e);if(!t?.config.automaticAutofill||t.type===`dynamic`||!n?.isFormula)return;let{col:r,row:i}=e,a=$P(t.range.zone,t.config);if(a&&ks(r,i,a)){let t=e.autofillRowStart??a.top,n=e.autofillRowEnd??a.bottom,r={...a,top:t,bottom:n};this.autofillTableZone(e,r)}break}}autofillTableZone(e,t){if(t.top===t.bottom)return;let{col:n,row:r,sheetId:i}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==r&&this.getters.getEvaluatedCell({col:n,row:e,sheetId:i}).type!==`empty`)return;let a={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.bottom}),this.dispatch(`AUTOFILL`),this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.top}),this.dispatch(`AUTOFILL`),this.selection.selectZone(a)}},QW=class extends SU{allowDispatch(e){switch(e.type){case`RESIZE_TABLE`:let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return`TableNotFound`;let n=t.range.zone,r=this.getters.getRangeFromRangeData(e.newTableRange).zone;return r.top!==n.top||r.left!==n.left?`InvalidTableResize`:this.canDispatch(`UPDATE_TABLE`,{...e}).reasons}return`Success`}handle(e){switch(e.type){case`RESIZE_TABLE`:{let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch(`UPDATE_TABLE`,{...e}),!t)return;let n=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(this.selection.selectCell(n.right,n.bottom),!t.config.automaticAutofill)return;let r=t.range.zone;if(n.bottom>=r.bottom){for(let t=n.left;t<=n.right;t++){let i={col:t,row:r.bottom,sheetId:e.sheetId};this.getters.getCell(i)?.content.startsWith(`=`)&&this.dispatch(`AUTOFILL_TABLE_COLUMN`,{...i,autofillRowStart:r.bottom,autofillRowEnd:n.bottom})}break}}}}},$W=class extends SU{static layers=[`Clipboard`];static getters=[`getClipboardTextAndImageContent`,`getClipboardId`,`getClipboardTextContent`,`isCutOperation`];status=`invisible`;originSheetId;copiedData;_isCutOperation=!1;clipboardId=new gl().uuidv4();fileStore;uuidGenerator;constructor(e){super(e),this.fileStore=e.external.fileStore,this.uuidGenerator=new gl}allowDispatch(e){switch(e.type){case`CUT`:let t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case`PASTE_FROM_OS_CLIPBOARD`:{let t=this.convertTextToClipboardData(e.clipboardContent.text??``),n=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:n,isCutOperation:!1})}case`PASTE`:{if(!this.copiedData)return`EmptyClipboard`;let t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].top===0&&e[0].bottom===0)return`InvalidCopyPasteSelection`;break}case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].left===0&&e[0].right===0)return`InvalidCopyPasteSelection`;break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}}return`Success`}handle(e){switch(e.type){case`COPY`:case`CUT`:let t=this.getters.getSelectedZones();this.status=`visible`,this.originSheetId=this.getters.getActiveSheetId(),this._isCutOperation=e.type===`CUT`,this.copiedData=this.copy(t);break;case`PASTE_FROM_OS_CLIPBOARD`:{this._isCutOperation=!1;let t=e.clipboardContent;if(t.data?.version!==oN()&&(t={...t},delete t.data),t.imageData){let n=this.getters.getActiveSheetId(),r=this.uuidGenerator.uuidv4(),i=t.imageData,a=wD(this.getters,i.size);this.dispatch(`CREATE_IMAGE`,{definition:i,size:a,col:e.target[0].left,row:e.target[0].top,offset:{x:0,y:0},sheetId:n,figureId:r})}t.data?this.copiedData=t.data:this.copiedData=this.convertTextToClipboardData(t.text??``);let n=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:n,selectTarget:!0,isCutOperation:!1}),this.status=`invisible`,this.copiedData=void 0;break}case`PASTE`:{let t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status=`invisible`,this._isCutOperation&&=(this.copiedData=void 0,!1);break}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZone(),t=e.top!==e.bottom,n={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};this.originSheetId=this.getters.getActiveSheetId();let r=this.copy([n]);this.paste([e],r,{isCutOperation:!1,selectTarget:!0})}break;case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZone(),t=e.left!==e.right,n={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};this.originSheetId=this.getters.getActiveSheetId();let r=this.copy([n]);this.paste([e],r,{isCutOperation:!1,selectTarget:!0})}break;case`CLEAN_CLIPBOARD_HIGHLIGHT`:this.status=`invisible`;break;case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!gs(t[0])){this.dispatch(`CLEAR_CELLS`,{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}let r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`ADD_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard(e.position===`before`?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case`REMOVE_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;for(let t of e.elements)if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}this.status=`invisible`;break;case`REPEAT_PASTE`:this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case`DELETE_SHEET`:if(!this._isCutOperation)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status=`invisible`);break;default:yr(e)&&(this.status=`invisible`)}}convertTextToClipboardData(e){let t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({})),n={};for(let{handlerName:r,handler:i}of t){let t=i.convertTextToClipboardData(e);n[r]=t;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])t&&e in t&&(n[e]=t[e])}return n}selectClipboardHandlers(e){let t=`figureId`in e?Fd.figureHandlers:Fd.cellHandlers;return t.getKeys().map(e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)}))}isCutAllowedOn(e){let t=this.getClipboardData(e);for(let{handler:e}of this.selectClipboardHandlers(t)){let n=e.isCutAllowed(t);if(n!==`Success`)return n}return`Success`}isPasteAllowed(e,t,n){for(let{handler:r}of this.selectClipboardHandlers(t)){let i=r.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...n});if(i!==`Success`)return i}return`Success`}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;let{zones:n}=this.copiedData;for(let r of n)if(t===`COL`&&e<=r.right||t===`ROW`&&e<=r.bottom)return!0;return!1}copy(e,t=`copyPaste`){let n={},r=this.getClipboardData(e);for(let{handlerName:e,handler:i}of this.selectClipboardHandlers(r)){let a=i.copy(r,this._isCutOperation,t);n[e]=a;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])a&&e in a&&(n[e]=a[e])}return n}paste(e,t,n){if(!t)return;let r=this.getters.getActiveSheetId(),i=this.selectClipboardHandlers(t),{target:a,zone:o,selectedZones:s}=wl(r,e,t,i,n);o!==void 0&&this.addMissingDimensions(r,o.right-o.left+1,o.bottom-o.top+1,o.left,o.top),Cl(i,t,a,n),n?.selectTarget&&Tl(this.selection,e,s)}addMissingDimensions(e,t,n,r,i){let a=n+i-this.getters.getNumberRows(e);a>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:this.getters.getNumberRows(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a,position:`after`});let o=t+r-this.getters.getNumberCols(e);o>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:this.getters.getNumberCols(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:o,position:`after`})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}async getClipboardTextAndImageContent(){let e=await this.getImageContent(),t=e?.type,n={"text/plain":this.getPlainTextContent(),"text/html":await this.getHTMLContent()};return t&&e&&(n[t]=e),n}getSheetData(){let e={version:oN(),clipboardId:this.clipboardId};return this.copiedData&&`figureId`in this.copiedData?e:{...e,...this.copiedData}}getPlainTextContent(){return this.copiedData?.cells&&this.copiedData.cells.map(e=>e.map(e=>this.getters.shouldShowFormulas()&&e?.tokens?.length?e?.content||``:e.evaluatedCell?.formattedValue||``).join(` `)).join(`
|
|
1951
1951
|
`)||` `}async getHTMLContent(){let e=``,t=this.copiedData?.cells;if(!t)if(this.copiedData?.figureId){let t=this.copiedData.figureId,n=this.getters.getFigureSheetId(t);e=this.getters.getFigure(n,t).tag===`image`?await this.craftImageHTML(t):` `}else e=` `;else if(t.length===1&&t[0].length===1)e=`${this.getters.getCellText(t[0][0].position)}`;else if(t[0][0]){let n=`<table border="1" style="border-collapse:collapse">`;for(let e of t){n+=`<tr>`;for(let t of e){if(!t)continue;let e=H(of(this.getters.getCellComputedStyle(t.position))),r=this.getters.getCellText(t.position);n+=`<td style="${e}">`+OD(r)+`</td>`}n+=`</tr>`}n+=`</table>`,e=n}else return``;return`<div data-osheet-clipboard='${OD(JSON.stringify(this.getSheetData()))}'>${e}</div>`}readFileAsDataURL(e){return new Promise(t=>{let n=new FileReader;n.onload=()=>t(n.result),n.readAsDataURL(e)})}async craftImageHTML(e){if(!this.fileStore)return` `;let t=this.getters.getImage(e).path,n=await this.fileStore?.getFile(t)||null;return n?`<img src="${OD(await this.readFileAsDataURL(n))}" />`:` `}async getImageContent(){let e=this.copiedData?.figureId;if(!e)return;let t=this.getters.getFigureSheetId(e),n=this.getters.getFigure(t,e),r;if(n.tag===`image`){if(!this.fileStore)return;let t=this.getters.getImage(e).path;if(r=await this.fileStore?.getFile(t),r.type!==`image/png`){if(r.size>5242880){this.ui.notifyUI({text:E(`The file you are trying to copy is too large (>%sMB).
|
|
1952
1952
|
It will not be added to your OS clipboard.
|
|
1953
|
-
You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=await tw(t)}}if(r)return r instanceof File?r:new File([r],`image.png`,{type:`image/png`})}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r;return r=t===`COL`?{...e,left:e.right+1,right:this.getters.getNumberCols(n)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1},{cut:[r],paste:[e]}}getInsertCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r,i;return t===`COL`?(r={...e,right:this.getters.getNumberCols(n)-1},i={...e,left:e.right+1,right:e.right+1}):(r={...e,bottom:this.getters.getNumberRows(n)-1},i={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1}),{cut:[r],paste:[i]}}getClipboardData(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedFigureId();if(n)return{figureId:n,sheetId:t};let r=vl(t,e);return this._isCutOperation||(r.rowsIndexes=r.rowsIndexes.filter(e=>!this.getters.isRowFiltered(t,e))),r}drawLayer(e){if(this.status!==`visible`||!this.copiedData)return;let{sheetId:t,zones:n}=this.copiedData;if(t!==this.getters.getActiveSheetId()||!n||!n.length)return;let{ctx:r,thinLineWidth:i}=e;r.setLineDash([8,5]),r.strokeStyle=ae,r.lineWidth=3.3*i;for(let e of n){let{x:t,y:n,width:i,height:a}=this.getters.getVisibleRect(e);i>0&&a>0&&r.strokeRect(t,n,i,a)}}};let eG={filterType:`criterion`,type:`none`,values:[]};var tG=class extends SU{static getters=[`getFilterValue`,`getFilterHiddenValues`,`getFilterCriterionValue`,`getFirstTableInSelection`,`isRowFiltered`,`isFilterActive`];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){switch(e.type){case`UPDATE_FILTER`:if(!this.getters.getFilterId(e))return`FilterNotFound`;break}return`Success`}handle(e){switch(e.type){case`UNDO`:case`REDO`:case`UPDATE_CELL`:case`EVALUATE_CELLS`:case`ACTIVATE_SHEET`:case`REMOVE_TABLE`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`UPDATE_TABLE`:this.isEvaluationDirty=!0;break;case`START`:for(let e of this.getters.getSheetIds())this.filterValues[e]={};break;case`CREATE_SHEET`:this.filterValues[e.sheetId]={};break;case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`GROUP_HEADERS`:case`UNGROUP_HEADERS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_ALL_HEADER_GROUPS`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:this.updateHiddenRows(e.sheetId);break;case`UPDATE_FILTER`:this.updateFilter(e),this.updateHiddenRows(e.sheetId);break;case`DUPLICATE_SHEET`:this.filterValues[e.sheetIdTo]=b(this.filterValues[e.sheetId]);break}}finalize(){if(this.isEvaluationDirty){for(let e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterValue(e){let t=this.getters.getFilterId(e),n=e.sheetId;return t?this.filterValues[n]?.[t]:void 0}getFilterHiddenValues(e){let t=this.getters.getFilterId(e),n=e.sheetId;if(!t||!this.filterValues[n])return[];let r=this.filterValues[n][t]||[];return r.filterType===`values`?r.hiddenValues:[]}getFilterCriterionValue(e){let t=this.getters.getFilterId(e),n=e.sheetId;if(!t||!this.filterValues[n])return eG;let r=this.filterValues[n][t];return r&&r.filterType===`criterion`?r:eG}isFilterActive(e){let t=this.getters.getFilterId(e);if(!t)return!1;let n=e.sheetId,r=this.filterValues[n]?.[t];return r?r.filterType===`values`?r.hiddenValues.length>0:r.type!==`none`:!1}getFirstTableInSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,value:n,sheetId:r}){let i=this.getters.getFilterId({sheetId:r,col:e,row:t});i&&(this.filterValues[r]||(this.filterValues[r]={}),this.filterValues[r][i]=n)}updateHiddenRows(e){let t=this.getters.getFilters(e).sort((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top),n=new Set;for(let r of t){let t=this.filterValues[e]?.[r.id],i=r.filteredRange?.zone;if(!(!t||!i||n.has(r.rangeWithHeaders.zone.top)||this.getters.isRowHiddenByUser(e,r.rangeWithHeaders.zone.top)))if(t.filterType===`values`){let a=t.hiddenValues?.map(ul);if(!a)continue;let o=new Set(a);for(let t=i.top;t<=i.bottom;t++){let i=this.getCellValueAsString(e,r.col,t);o.has(i)&&n.add(t)}}else{if(t.type===`none`)continue;let a=Y.get(t.type),o=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(e,t)??``:Ko(t,D));if(o.some(Du))continue;let s={type:t.type,values:o.map(Tu),dateValue:t.dateValue};for(let t=i.top;t<=i.bottom;t++){let i={sheetId:e,col:r.col,row:t},o=this.getters.getEvaluatedCell(i).value??``;a.isValueValid(o,s,this.getters,e)||n.add(t)}}}this.hiddenRows[e]=n}getCellValueAsString(e,t,n){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).formattedValue.toLowerCase()}exportForExcel(e){for(let t of e.sheets){let e=t.id;for(let n of t.tables){let r=ps(n.range),i=[],a=[];for(let n of S(0,js(r).numberOfCols)){let o={sheetId:t.id,col:r.left+n,row:r.top},s=this.getFilterHiddenValues(o),c=this.getters.getFilter(o),l=c?.filteredRange?Fs(c.filteredRange.zone).map(t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue):[];if(s.length){let e=l.filter(e=>e).filter(e=>!s.includes(e));i.push({colId:n,displayedValues:[...new Set(e)],displayBlanks:!s.includes(``)&&l.some(e=>!e)})}let u=this.getters.getEvaluatedCell(o).formattedValue,d=this.getUniqueColNameForExcel(n,u,a);a.push(d);let f=T(o.col,o.row);t.cells[f]=d,t.cellValues[f]=d}n.filters=i}}}getUniqueColNameForExcel(e,t,n){return t||=`Column${e}`,$t(t,n,{compute:(e,n)=>t+String(n),start:2})}},nG=class extends SU{static layers=[`Selection`];static getters=[`getActiveSheet`,`getActiveSheetId`,`getActiveSheetName`,`getActiveCell`,`getActiveCols`,`getActiveRows`,`getCurrentStyle`,`getSelectedZones`,`getSelectedZone`,`getSelectedCells`,`getSelectedFigureId`,`getSelection`,`getActivePosition`,`getSheetPosition`,`isSingleColSelected`,`getElementsFromSelection`,`tryGetActiveSheetId`,`isGridSelectionActive`,`getSelectecUnboundedZone`];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;isUnbounded;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient,this.isUnbounded=!1}allowDispatch(e){switch(e.type){case`ACTIVATE_SHEET`:try{if(!this.getters.getSheet(e.sheetIdTo).isVisible)return`SheetIsHidden`;break}catch{return`InvalidSheetId`}case`MOVE_COLUMNS_ROWS`:return this.isMoveElementAllowed(e)}return`Success`}handleEvent(e){let t=e.anchor,n=[];switch(this.isUnbounded=e.options?.unbounded||!1,e.mode){case`overrideSelection`:n=[t.zone];break;case`updateAnchor`:n=[...this.gridSelection.zones];let r=n.findIndex(t=>Es(t,e.previousAnchor.zone));r>=0&&(n[r]=t.zone);break;case`newAnchor`:n=[...this.gridSelection.zones,t.zone];break}this.setSelectionMixin(e.anchor,n),this.selection.resetDefaultAnchor(this,b(this.gridSelection.anchor));let{col:r,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:r,row:i}),this.selectedFigureId=null}handle(e){switch(e.type){case`ACTIVATE_SHEET`:this.selectedFigureId=null;break;case`DELETE_FIGURE`:this.selectedFigureId===e.figureId&&(this.selectedFigureId=null);break;case`DELETE_SHEET`:this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null);break}switch(e.type){case`START`:let t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);let{col:n,row:r}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(n,r),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case`ACTIVATE_SHEET`:this.activateSheet(e.sheetIdFrom,e.sheetIdTo);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){e.dimension===`COL`?this.onColumnsRemoved(e):this.onRowsRemoved(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`ADD_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`MOVE_COLUMNS_ROWS`:e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case`SELECT_FIGURE`:this.selectedFigureId=e.figureId;break;case`ACTIVATE_NEXT_SHEET`:this.activateNextSheet(`right`);break;case`ACTIVATE_PREVIOUS_SHEET`:this.activateNextSheet(`left`);break;case`HIDE_SHEET`:e.sheetId===this.getActiveSheetId()&&this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case`UNDO`:case`REDO`:case`DELETE_SHEET`:let i=Object.keys(this.sheetsData).filter(e=>!this.getters.tryGetSheet(e));for(let e of i)delete this.sheetsData[e];for(let e in this.sheetsData){let t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:b(t)}}this.fallbackToVisibleSheet();let a=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map(e=>this.getters.expandZone(a,e)),this.gridSelection.anchor.zone=this.getters.expandZone(a,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null;break}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,b(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveSheetName(){return this.activeSheet.name}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){let e=new Set;for(let t of this.gridSelection.zones)if(t.top===0&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let n=t.left;n<=t.right;n++)e.add(n);return e}getActiveRows(){let e=new Set,t=this.getters.getActiveSheetId();for(let n of this.gridSelection.zones)if(n.left===0&&n.right===this.getters.getNumberCols(t)-1)for(let t=n.top;t<=n.bottom;t++)e.add(t);return e}getCurrentStyle(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return b(this.gridSelection.zones)}getSelectedZone(){return b(this.gridSelection.anchor.zone)}getSelectecUnboundedZone(){return b(this.isUnbounded?this.getters.getUnboundedZone(this.activeSheet.id,this.gridSelection.anchor.zone):this.gridSelection.anchor.zone)}getSelection(){return b(this.gridSelection)}getSelectedCells(){let e=this.getters.getActiveSheetId(),t=[];for(let n of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,n));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{let t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}isSingleColSelected(){let e=this.getters.getSelectedZones();return!(e.length!==1||e[0].left!==e[0].right)}getElementsFromSelection(e){if(e===`COL`&&this.getters.getActiveCols().size===0||e===`ROW`&&this.getters.getActiveRows().size===0)return[];let t=this.getters.getSelectedZones(),n=[],r=e===`COL`?`left`:`top`,i=e===`COL`?`right`:`bottom`;for(let e of t){let t=Array.from({length:e[i]-e[r]+1},(t,n)=>e[r]+n);n=n.concat(t)}return[...new Set(n)].sort()}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:b(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,b(this.gridSelection.anchor));else{let{col:e,row:n}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,n)}let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:n,row:r})}setSelectionMixin(e,t){let{anchor:n,zones:r}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=n,this.gridSelection.zones=Rs(r)}selectCell(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.expandZone(n,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:r,cell:{col:e,row:t}},[r])}setActiveSheet(e){this.activeSheet=this.getters.getSheet(e)}activateNextSheet(e){let t=this.getters.getSheetIds(),n=(t.findIndex(e=>e===this.activeSheet.id)+(e===`left`?t.length-1:1))%t.length;this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[n]})}onColumnsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=xs(n,`left`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=xs(i,`left`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>xs(t,`left`,[...e.elements]));this.setSelectionMixin(a,o)}onRowsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=xs(n,`top`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=xs(i,`top`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>xs(t,`top`,[...e.elements]));this.setSelectionMixin(a,o)}onAddElements(e){let t=e.dimension===`COL`?`left`:`top`,n=bs(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),r=this.gridSelection.zones.map(n=>bs(n,t,e.base,e.position,e.quantity)),i={cell:{col:n.left,row:n.top},zone:n};this.setSelectionMixin(i,r)}onMoveElements(e){let t=e.elements.length,n=this.getFiguresUpdates(e);this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,base:e.base,quantity:t,position:e.position});let r=e.dimension===`COL`,i=e.elements[0],a=e.elements[t-1],o=e.base<i,s=o&&r?t:0,c=o&&!r?t:0,l=o?e.elements.map(e=>e+t):e.elements,u={};for(let t of l)u[t]=this.getters.getHeaderSize(e.sheetId,e.dimension,t);let d=[{left:r?i+s:0,right:r?a+s:this.getters.getNumberCols(e.sheetId)-1,top:r?0:i+c,bottom:r?this.getters.getNumberRows(e.sheetId)-1:a+c}],f=this.getActiveSheetId(),p=o?e.base:e.base+1,m=[{left:r?p:0,right:r?p+t-1:this.getters.getNumberCols(e.sheetId)-1,top:r?0:p,bottom:r?this.getters.getNumberRows(e.sheetId)-1:p+t-1}];for(let e of Fd.cellHandlers.getAll()){let t=new e(this.getters,this.dispatch),n=t.copy(vl(f,d),!1,`shiftCells`);n&&t.paste({zones:m,sheetId:f},n,{isCutOperation:!0})}let h=m[0],g=h.left,_=h.top;this.setSelectionMixin({zone:h,cell:{col:g,row:_}},[h]);let v=o?e.base:e.base+1,y={};for(let t of l){let n=u[t];n!==this.getters.getHeaderSize(e.sheetId,e.dimension,v)&&(y[n]??=[],y[n].push(v)),v+=1}for(let t in y)this.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,size:parseInt(t,10),elements:y[t]});this.dispatch(`REMOVE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,elements:l}),this.applyFigureUpdates(n)}getFiguresUpdates(e){let t=[],n={},r=e.elements[0]<e.base?e.base-e.elements.length+1:e.base;for(let t=0;t<e.elements.length;t++)n[e.elements[t]]=r+t;for(let r of this.getters.getFigures(e.sheetId))e.dimension===`COL`&&r.col in n&&t.push({type:`UPDATE_FIGURE`,sheetId:e.sheetId,figureId:r.id,col:n[r.col],row:r.row}),e.dimension===`ROW`&&r.row in n&&t.push({type:`UPDATE_FIGURE`,sheetId:e.sheetId,figureId:r.id,row:n[r.row],col:r.col});return t}applyFigureUpdates(e){for(let t of e)this.dispatch(t.type,{...t})}isMoveElementAllowed(e){let t=e.dimension===`COL`,n=e.elements[0],r=e.elements[e.elements.length-1],i=e.sheetId,a=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(a(i,n-1,n)||a(i,r,r+1)||a(i,e.base-1,e.base))return`WillRemoveExistingMerge`;let o=[e.base,...e.elements],s=t?this.getters.getNumberCols(i):this.getters.getNumberRows(i);return o.some(e=>e<0||e>=s)?`InvalidHeaderIndex`:!t&&!this.isTableRowMoveAllowed(i,e.elements)?`CannotMoveTableHeader`:`Success`}isTableRowMoveAllowed(e,t){let n=this.getters.getCoreTables(e);if(n.length===0)return!0;let r=new Set(t);return n.every(({range:{zone:e},config:n})=>{let{top:i,bottom:a}=e;if(n.numberOfHeaders===0)return!0;let o=i+n.numberOfHeaders-1;return t.some(e=>e>=i&&e<=o)?S(i,a+1).every(e=>r.has(e)):!0})}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){let e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){let{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);let{col:t,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:n})}}clipSelection(e,t){let n=this.getters.getNumberCols(e)-1,r=this.getters.getNumberRows(e)-1,i=t.zones.map(e=>({left:x(e.left,0,n),right:x(e.right,0,n),top:x(e.top,0,r),bottom:x(e.bottom,0,r)})),a=x(t.anchor.cell.col,0,n),o=x(t.anchor.cell.row,0,r),s={left:x(t.anchor.zone.left,0,n),right:x(t.anchor.zone.right,0,n),top:x(t.anchor.zone.top,0,r),bottom:x(t.anchor.zone.bottom,0,r)};return{zones:i,anchor:{cell:{col:a,row:o},zone:s}}}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getSelectedZones();t.fillStyle=`#f3f7fe`,t.fillStyle=r.length===1&&r[0].left===r[0].right&&r[0].top===r[0].bottom?`#f3f7fe`:`#e9f0ff`,t.strokeStyle=ae,t.lineWidth=1.5*n;for(let e of r){let{x:n,y:r,width:i,height:a}=this.getters.getVisibleRect(e);t.globalCompositeOperation=`multiply`,t.fillRect(n,r,i,a),t.globalCompositeOperation=`source-over`,t.strokeRect(n,r,i,a)}t.globalCompositeOperation=`source-over`;let i=this.getActivePosition();t.strokeStyle=ae,t.lineWidth=3*n;let a;a=this.getters.isInMerge(i)?this.getters.getMerge(i):z(i);let{x:o,y:s,width:c,height:l}=this.getters.getVisibleRect(a);c>0&&l>0&&t.strokeRect(o,s,c,l)}},rG=class{top;bottom;left;right;offsetX;offsetY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,n,r,i,a){if(this.getters=e,this.sheetId=t,this.boundaries=n,r.width<0||r.height<0)throw Error(`Viewport size cannot be negative`);this.viewportWidth=r.height&&r.width,this.viewportHeight=r.width&&r.height,this.top=n.top,this.bottom=n.bottom,this.left=n.left,this.right=n.right,this.offsetX=a.x,this.offsetY=a.y,this.canScrollVertically=i.canScrollVertically,this.canScrollHorizontally=i.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){let e=this.getters.findLastVisibleColRowIndex(this.sheetId,`COL`,{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,`ROW`,{first:this.boundaries.top,last:this.boundaries.bottom}),{end:n}=this.getters.getColDimensions(this.sheetId,e),{end:r}=this.getters.getRowDimensions(this.sheetId,t),i=n-this.offsetCorrectionX;this.canScrollHorizontally&&(i=Math.max(i,this.viewportWidth));let a=r-this.offsetCorrectionY;return this.canScrollVertically&&(a=Math.max(a,this.viewportHeight),r+46>a&&!this.getters.isReadonly()&&(a+=46)),{width:i,height:a}}getColIndex(e){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex(`COL`,e-this.offsetCorrectionX+this.snapCorrection.x,this.left)}getRowIndex(e){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex(`ROW`,e-this.offsetCorrectionY+this.snapCorrection.y,this.top)}adjustPosition(e){let t=this.sheetId,n=this.getters.getMainCellPosition({sheetId:t,...e}),{col:r,row:i}=this.getters.getNextVisibleCellPosition(n);ks(r,this.boundaries.top,this.boundaries)&&this.adjustPositionX(r),ks(this.boundaries.left,i,this.boundaries)&&this.adjustPositionY(i)}adjustPositionX(e){let t=this.sheetId,{start:n,end:r}=this.getters.getColDimensions(t,e);this.offsetX+this.viewportWidth+this.offsetCorrectionX<r?this.offsetX=r-this.viewportWidth:this.offsetX+this.offsetCorrectionX>n&&(this.offsetX=n-this.offsetCorrectionX),this.adjustViewportZoneX()}adjustPositionY(e){let t=this.sheetId,{start:n,end:r}=this.getters.getRowDimensions(t,e);this.offsetY+this.viewportHeight+this.offsetCorrectionY<r?this.offsetY=r-this.viewportHeight:this.offsetY+this.offsetCorrectionY>n&&(this.offsetY=n-this.offsetCorrectionY),this.adjustViewportZoneY()}willNewOffsetScrollViewport(e,t){return this.canScrollHorizontally&&this.offsetX!==e||this.canScrollVertically&&this.offsetY!==t}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getVisibleRect(e){let t=Ts(e,this),n=this.snapCorrection.x,r=this.snapCorrection.y;if(t)return{x:this.getters.getColRowOffset(`COL`,this.left,t.left)+this.offsetCorrectionX-(this.left===t.left?0:n),y:this.getters.getColRowOffset(`ROW`,this.top,t.top)+this.offsetCorrectionY-(this.top===t.top?0:r),width:Math.min(this.getters.getColRowOffset(`COL`,t.left,t.right+1)-(this.left===t.left?n:0),this.viewportWidth),height:Math.min(this.getters.getColRowOffset(`ROW`,t.top,t.bottom+1)-(this.top===t.top?r:0),this.viewportHeight)}}getFullRect(e){let t=Ts(e,this.boundaries),n=this.snapCorrection.x,r=this.snapCorrection.y;if(t){let t=this.getters.getColRowOffset(`COL`,this.left,e.left)+this.offsetCorrectionX,i=this.getters.getColRowOffset(`ROW`,this.top,e.top)+this.offsetCorrectionY,a=this.getters.getColRowOffset(`COL`,e.left,e.right+1),o=this.getters.getColRowOffset(`ROW`,e.top,e.bottom+1);return{x:t-n,y:i-r,width:a,height:o}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,n=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;let r=this.sheetId,i=this.getters.getNumberHeaders(r,e),a=n,o=i;for(;a<=o&&a!==i&&o!==-1;){let i=Math.floor((a+o)/2),s=this.getters.getColRowOffset(e,n,i),c=this.getters.getHeaderSize(r,e,i);if(t>=s&&t<s+c)return i;t>=s+c?a=i+1:o=i-1}return-1}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){let{width:e}=this.getMaxSize();this.viewportWidth+this.offsetX>e&&(this.offsetX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){let{height:e}=this.getMaxSize();this.viewportHeight+this.offsetY>e&&(this.offsetY=Math.max(0,e-this.viewportHeight))}this.adjustViewportZoneY()}adjustViewportZoneX(){this.left=this.searchHeaderIndex(`COL`,this.offsetX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex(`COL`,Math.max(this.viewportWidth+this.snapCorrection.x-.1),this.left)),this.viewportWidth&&(this.left===-1&&(this.left=this.boundaries.left),this.right===-1&&(this.right=this.boundaries.right))}adjustViewportZoneY(){this.top=this.searchHeaderIndex(`ROW`,this.offsetY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex(`ROW`,Math.max(this.viewportHeight+this.snapCorrection.y-.1,0),this.top)),this.viewportHeight&&(this.top===-1&&(this.top=this.boundaries.top),this.bottom===-1&&(this.bottom=this.boundaries.bottom))}get snapCorrection(){return{x:Math.abs(this.offsetX-this.getters.getColRowOffset(`COL`,this.boundaries.left,Math.max(0,this.left))),y:Math.abs(this.offsetY-this.getters.getColRowOffset(`ROW`,this.boundaries.top,Math.max(0,this.top)))}}},iG=class extends SU{static getters=`getColIndex.getRowIndex.getActiveMainViewport.getSheetViewDimension.getSheetViewDimensionWithHeaders.getMainViewportRect.isVisibleInViewport.getEdgeScrollCol.getEdgeScrollRow.getVisibleFigures.getVisibleRect.getVisibleRectWithoutHeaders.getVisibleCellPositions.getColRowOffsetInViewport.getMainViewportCoordinates.getActiveSheetScrollInfo.getSheetViewVisibleCols.getSheetViewVisibleRows.getFrozenSheetViewRatio.isPixelPositionVisible.getColDimensionsInViewport.getRowDimensionsInViewport.getAllActiveViewportsZonesAndRect.getRect.getFigureUI.getPositionAnchorOffset.getGridOffset.getMaximumSheetOffset`.split(`.`);viewports={};sheetViewWidth=Qe();sheetViewHeight=Qe();gridOffsetX=0;gridOffsetY=0;sheetsWithDirtyViewports=new Set;shouldAdjustViewports=!1;allowDispatch(e){switch(e.type){case`SET_VIEWPORT_OFFSET`:return this.chainValidations(this.checkScrollingDirection,this.checkIfViewportsWillChange)(e);case`RESIZE_SHEETVIEW`:return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return`Success`}}handleEvent(e){let t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let{col:n,row:r}=Bs(e.previousAnchor.zone,e.anchor.zone);if(e.mode===`updateAnchor`){let i=e.previousAnchor.zone,a=e.anchor.zone,{top:o,bottom:s,left:c,right:l}=this.getMainInternalViewport(t);i.left===a.left&&i.right===a.right&&(n=c>n||n>l?c:n),i.top===a.top&&i.bottom===a.bottom&&(r=o>r||r>s?o:r)}n=Math.min(n,this.getters.getNumberCols(t)-1),r=Math.min(r,this.getters.getNumberRows(t)-1),this.sheetsWithDirtyViewports.has(t)||this.refreshViewport(this.getters.getActiveSheetId(),{col:n,row:r})}}handle(e){if(fr.has(e.type))for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);switch(e.type){case`START`:this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case`UNDO`:case`REDO`:this.cleanViewports();for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);this.shouldAdjustViewports=!0;break;case`RESIZE_SHEETVIEW`:this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case`SET_VIEWPORT_OFFSET`:this.setSheetViewOffset(e.offsetX,e.offsetY);break;case`SHIFT_VIEWPORT_DOWN`:let t=this.getters.getActiveSheetId(),{top:n,viewportHeight:r,offsetCorrectionY:i}=this.getMainInternalViewport(t),a=this.getters.getRowDimensions(t,n);this.shiftVertically(a.start+r-i);break;case`SHIFT_VIEWPORT_UP`:{let e=this.getters.getActiveSheetId(),{top:t,viewportHeight:n,offsetCorrectionY:r}=this.getMainInternalViewport(e),i=this.getters.getRowDimensions(e,t);this.shiftVertically(i.end-r-n);break}case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`UPDATE_FILTER`:case`UNFREEZE_ROWS`:case`UNFREEZE_COLUMNS`:case`FREEZE_COLUMNS`:case`FREEZE_ROWS`:case`UNFREEZE_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`RESIZE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`UNGROUP_HEADERS`:case`GROUP_HEADERS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_ALL_HEADER_GROUPS`:this.sheetsWithDirtyViewports.add(e.sheetId);break;case`UPDATE_CELL`:for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);break;case`DELETE_SHEET`:this.cleanViewports(),this.sheetsWithDirtyViewports.delete(e.sheetId);break;case`ACTIVATE_SHEET`:this.sheetsWithDirtyViewports.add(e.sheetIdTo);break;case`SCROLL_TO_CELL`:this.refreshViewport(this.getters.getActiveSheetId(),{col:e.col,row:e.row});break}}finalize(){for(let e of this.sheetsWithDirtyViewports)if(this.resetViewports(e),this.shouldAdjustViewports){let t=this.getters.getSheetPosition(e);this.getSubViewports(e).forEach(e=>{e.adjustPosition(t)})}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){let e=this.getters.getSheetIds();for(let t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getColIndex(e)))}getRowIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getRowIndex(e)))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getGridOffset(){return{x:this.gridOffsetX,y:this.gridOffsetY}}getActiveMainViewport(){let e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getSheetViewVisibleCols(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>S(e.left,e.right+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`COL`,t))}getSheetViewVisibleRows(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>S(e.top,e.bottom+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`ROW`,t))}getVisibleCellPositions(){let e=this.getSheetViewVisibleCols(),t=this.getSheetViewVisibleRows(),n=this.getters.getActiveSheetId(),r=[];for(let i of e)for(let e of t){let t={sheetId:n,col:i,row:e},a=this.getters.getMainCellPosition(t);a.row!==e||a.col!==i||r.push(t)}return r}getMainViewportRect(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e),{width:i,height:a}=t.getMaxSize();return{x:this.getters.getColDimensions(e,n).start,y:this.getters.getRowDimensions(e,r).start,width:i,height:a}}getMaximumSheetOffset(){let e=this.getters.getActiveSheetId(),{width:t,height:n}=this.getMainViewportRect(),r=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-r.viewportWidth),maxOffsetY:Math.max(0,n-r.viewportHeight)}}getColRowOffsetInViewport(e,t,n){if(n<t)return-this.getColRowOffsetInViewport(e,n,t);let r=this.getters.getActiveSheetId(),i=e===`COL`?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),a=i.findIndex(e=>t>=e),o=i.findIndex(e=>n<=e);o=o===-1?i.length:o;let s=i.slice(a,o),c=0;for(let t of s)c+=this.getters.getHeaderSize(r,e,t);return c}isVisibleInViewport({sheetId:e,col:t,row:n}){return this.getSubViewports(e).some(e=>e.isVisible(t,n))}getEdgeScrollCol(e,t,n){let r=!1,i=0,a=0,{xSplit:o}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:s}=this.getSheetViewDimension(),{x:c}=this.getMainViewportCoordinates(),l=this.getActiveSheetScrollInfo().scrollX;return e>s?(r=!0,a=ac(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=ac(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=ac(e),i=`reset`),{canEdgeScroll:r,direction:i,delay:a}}getEdgeScrollRow(e,t,n){let r=!1,i=0,a=0,{ySplit:o}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:s}=this.getSheetViewDimension(),{y:c}=this.getMainViewportCoordinates(),l=this.getActiveSheetScrollInfo().scrollY;return e>s?(r=!0,a=ac(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=ac(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=ac(e),i=`reset`),{canEdgeScroll:r,direction:i,delay:a}}getVisibleRect(e){let t=this.getVisibleRectWithoutHeaders(e);return{...t,x:t.x+this.gridOffsetX,y:t.y+this.gridOffsetY}}getVisibleRectWithoutHeaders(e){let t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getVisibleRect(e))}getRect(e){let t=this.getters.getActiveSheetId(),n=this.mapViewportsToRect(t,t=>t.getFullRect(e));return{...n,x:n.x+this.gridOffsetX,y:n.y+this.gridOffsetY}}getRectWithoutHeaders(e){let t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getFullRect(e))}getMainViewportCoordinates(){let e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,n).start}}getColDimensionsInViewport(e,t){let{top:n}=this.getMainInternalViewport(e),r={left:t,right:t,top:n,bottom:n},{x:i,width:a}=this.getVisibleRect(r),o=i-this.gridOffsetX;return{start:o,size:a,end:o+a}}getRowDimensionsInViewport(e,t){let{left:n}=this.getMainInternalViewport(e),r={left:0,right:n,top:t,bottom:t},{y:i,height:a}=this.getVisibleRect(r),o=i-this.gridOffsetY;return{start:o,size:a,end:o+a}}getAllActiveViewportsZonesAndRect(){let e=this.getters.getActiveSheetId();return this.getSubViewports(e).map(e=>({zone:e,rect:{x:e.offsetCorrectionX+this.gridOffsetX,y:e.offsetCorrectionY+this.gridOffsetY,...e.getMaxSize()}}))}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(C)}checkPositiveDimension(e){return e.width<0||e.height<0?`InvalidViewportSize`:`Success`}checkValuesAreDifferent(e){let{height:t,width:n}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===n&&e.height===t?`ValuesNotChanged`:`Success`}checkScrollingDirection({offsetX:e,offsetY:t}){let n=this.getMainInternalViewport(this.getters.getActiveSheetId());return!n.canScrollHorizontally&&e>0||!n.canScrollVertically&&t>0?`InvalidScrollingDirection`:`Success`}checkIfViewportsWillChange({offsetX:e,offsetY:t}){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();return this.getSubViewports(n).some(n=>n.willNewOffsetScrollViewport(x(e,0,r),x(t,0,i)))?`Success`:`ViewportScrollLimitsReached`}getMainViewport(e){let t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){let e={};for(let t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,n=0,r=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=n,this.gridOffsetY=r,this.recomputeViewports()}recomputeViewports(){for(let e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();this.getSubViewports(n).forEach(n=>n.setViewportOffset(x(e,0,r),x(t,0,i)))}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetX||0,y:this.viewports[e]?.bottomRight.offsetY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getNumberCols(e),i=this.getters.getNumberRows(e),a=Math.min(this.getters.getColRowOffset(`COL`,0,t,e),this.sheetViewWidth),o=Math.min(this.getters.getColRowOffset(`ROW`,0,n,e),this.sheetViewHeight),s=Math.max(this.sheetViewWidth-a,0),c=Math.max(this.sheetViewHeight-o,0),{xRatio:l,yRatio:u}=this.getFrozenSheetViewRatio(e),d=l<1,f=u<1,p=this.getViewportOffset(e),m={topLeft:n&&t&&new rG(this.getters,e,{left:0,right:t-1,top:0,bottom:n-1},{width:a,height:o},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:n&&new rG(this.getters,e,{left:t,right:r-1,top:0,bottom:n-1},{width:s,height:o},{canScrollHorizontally:d,canScrollVertically:!1},{x:d?p.x:0,y:0})||void 0,bottomLeft:t&&new rG(this.getters,e,{left:0,right:t-1,top:n,bottom:i-1},{width:a,height:c},{canScrollHorizontally:!1,canScrollVertically:f},{x:0,y:f?p.y:0})||void 0,bottomRight:new rG(this.getters,e,{left:t,right:r-1,top:n,bottom:i-1},{width:s,height:c},{canScrollHorizontally:d,canScrollVertically:f},{x:d?p.x:0,y:f?p.y:0})};this.viewports[e]=m}refreshViewport(e,t){this.getSubViewports(e).forEach(e=>{e.adjustViewportZone(),e.adjustPosition(t)})}shiftVertically(e){let t=this.getters.getActiveSheetId(),{top:n}=this.getMainInternalViewport(t),{scrollX:r}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(r,e);let{anchor:i}=this.getters.getSelection();if(i.cell.row>=this.getters.getPaneDivisions(t).ySplit){let e=this.getMainInternalViewport(t).top-n;this.selection.selectCell(i.cell.col,i.cell.row+e)}}getColIndexLeftOfMainViewport(e){if(e>=0)return-1;let t=this.getters.getActiveSheetId(),n=this.getActiveMainViewport().left,r=-this.getActiveSheetScrollInfo().scrollX-this.getters.getColRowOffset(`COL`,n,0);for(;e<r;n--)r-=this.getters.getColSize(t,n-1);return Math.max(n,0)}getRowIndexTopOfMainViewport(e){if(e>=0)return-1;let t=this.getters.getActiveSheetId(),n=this.getActiveMainViewport().top,r=-this.getActiveSheetScrollInfo().scrollY-this.getters.getColRowOffset(`ROW`,n,0);for(;e<r;n--)r-=this.getters.getRowSize(t,n-1);return Math.max(n,0)}getVisibleFigures(){let e=this.getters.getActiveSheetId(),t=[],n=this.getters.getFigures(e),{scrollX:r,scrollY:i}=this.getters.getActiveSheetScrollInfo(),{x:a,y:o}=this.getMainViewportCoordinates(),{width:s,height:c}=this.getters.getSheetViewDimensionWithHeaders();for(let l of n){let n=this.getFigureUI(e,l),{x:u,y:d}=n;u>=a&&(u+l.width<r+a||u>s+r+a)||d>=o&&(d+l.height<i+o||d>c+i+o)||t.push(n)}return t}getFigureUI(e,t){let n=t.offset.x+this.getters.getColDimensions(e,t.col).start,r=t.offset.y+this.getters.getRowDimensions(e,t.row).start;return{...t,x:n,y:r}}getPositionAnchorOffset(e){let{scrollX:t,scrollY:n}=this.getters.getActiveSheetScrollInfo(),r=e.x-t,i=e.y-n,a=r>=0?this.getColIndex(r):this.getColIndexLeftOfMainViewport(r),o=i>=0?this.getRowIndex(i):this.getRowIndexTopOfMainViewport(i),{x:s,y:c}=this.getRect(z({col:a,row:o}));return{col:a,row:o,offset:{x:Math.max(r-s+this.gridOffsetX,0),y:Math.max(i-c+this.gridOffsetY,0)}}}isPixelPositionVisible(e){let{scrollX:t,scrollY:n}=this.getters.getActiveSheetScrollInfo(),{x:r,y:i}=this.getters.getMainViewportCoordinates(),{width:a,height:o}=this.getters.getSheetViewDimension();return!(e.x>=r&&(e.x<r+t||e.x>a+t+r)||e.y>=i&&(e.y<i+n||e.y>o+n+i))}getFrozenSheetViewRatio(e){let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getColDimensions(e,t).start,i=this.getters.getRowDimensions(e,n).start,a=this.sheetViewWidth+this.gridOffsetX,o=this.sheetViewHeight+this.gridOffsetY;return{xRatio:r/a,yRatio:i/o}}mapViewportsToRect(e,t){let n=1/0,r=1/0,i=0,a=0,o=!1;for(let s of this.getSubViewports(e)){let e=t(s);e&&(o=!0,n=Math.min(n,e.x),r=Math.min(r,e.y),i=Math.max(i,e.x+e.width),a=Math.max(a,e.y+e.height))}return o?{x:n,y:r,width:i-n,height:a-r}:{x:0,y:0,width:0,height:0}}},aG=class extends SU{static getters=[`getColDimensions`,`getRowDimensions`,`getColRowOffset`];headerPositions={};isDirty=!0;handle(e){switch(fr.has(e.type)&&(this.headerPositions={},this.isDirty=!0),e.type){case`START`:for(let e of this.getters.getSheetIds())this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e);break;case`UPDATE_CELL`:this.headerPositions={},this.isDirty=!0;break;case`UPDATE_FILTER`:case`UPDATE_TABLE`:case`REMOVE_TABLE`:this.headerPositions={},this.isDirty=!0;break;case`REMOVE_COLUMNS_ROWS`:case`RESIZE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_ALL_HEADER_GROUPS`:case`UNGROUP_HEADERS`:case`GROUP_HEADERS`:case`CREATE_SHEET`:this.getters.tryGetSheet(e.sheetId)&&(this.headerPositions[e.sheetId]=this.computeHeaderPositionsOfSheet(e.sheetId));break;case`DUPLICATE_SHEET`:this.headerPositions[e.sheetIdTo]=b(this.headerPositions[e.sheetId]);break}}finalize(){for(let e of this.getters.getSheetIds())(this.isDirty||!this.headerPositions[e])&&(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){let n=this.headerPositions[e].COL[t],r=this.getters.getColSize(e,t);return{start:n,size:r,end:n+(this.getters.isColHidden(e,t)?0:r)}}getRowDimensions(e,t){let n=this.headerPositions[e].ROW[t],r=this.getters.getRowSize(e,t);return{start:n,size:r,end:n+(this.getters.isRowHidden(e,t)?0:r)}}getColRowOffset(e,t,n,r=this.getters.getActiveSheetId()){let i=this.headerPositions[r][e][t];return this.headerPositions[r][e][n]-i}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,`COL`),ROW:this.computePositions(e,`ROW`)}}computePositions(e,t){let n={},r=0;for(let i=0;i<this.getters.getNumberHeaders(e,t)+1;i++)n[i]=r,!this.getters.isHeaderHidden(e,t,i)&&(r+=this.getters.getHeaderSize(e,t,i));return n}};let oG=new g().add(`settings`,CH).add(`sheet`,yH).add(`header grouping`,xH).add(`header visibility`,pH).add(`tables`,bH).add(`dataValidation`,uH).add(`cell`,iH).add(`merge`,hH).add(`headerSize`,fH).add(`borders`,rH).add(`conditional formatting`,lH).add(`figures`,dH).add(`chart`,sH).add(`image`,mH).add(`pivot_core`,SH).add(`spreadsheet_pivot_core`,wH).add(`tableStyle`,TH),sG=new g().add(`ui_sheet`,hW).add(`ui_options`,mW).add(`autofill`,wU).add(`sort`,pW).add(`automatic_sum`,TU).add(`format`,lW).add(`insert_pivot`,fW).add(`pivot_presence`,YW).add(`split_to_columns`,XW).add(`collaborative`,sW).add(`history`,qW).add(`data_cleanup`,cW).add(`table_autofill`,ZW).add(`table_ui_resize`,QW).add(`datavalidation_insert`,xW).add(`checkbox_toggle`,bW).add(`geo_features`,uW),cG=new g().add(`selection`,nG).add(`evaluation_filter`,tG).add(`header_visibility_ui`,dW).add(`cell_computed_style`,yW).add(`table_computed_style`,gW).add(`header_positions`,aG).add(`viewport`,iG).add(`clipboard`,$W),lG=new g().add(`evaluation`,KH).add(`evaluation_chart`,ZH).add(`evaluation_cf`,QH).add(`row_size`,aU).add(`data_validation_ui`,eU).add(`dynamic_tables`,iU).add(`custom_colors`,XH).add(`pivot_ui`,uU).add(`cell_icon`,rU);PO.add(`dataValidation`,{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(en(t)||!this.composer.currentEditedCell)return[];let n=this.composer.currentEditedCell,r=this.getters.getValidationRuleForCell(n);if(!r||r.criterion.type!==`isValueInList`&&r.criterion.type!==`isValueInRange`)return[];let i=this.composer.currentEditedCell.sheetId,a=r.criterion.type===`isValueInRange`?this.getters.getDataValidationRangeValues(i,r.criterion):r.criterion.values.map(e=>({label:e,value:e}));if(r.criterion.displayStyle!==`chip`)return a.map(e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]}));let o=r.criterion.colors;return a.map(e=>{let t=o?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:t?Tn(t):void 0,backgroundColor:t||`#E7E9ED`,classes:[`badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start`]}],fuzzySearchKey:e.label}})},selectProposal(e,t){this.composer.setCurrentContent(t),this.composer.stopEdition()}}),PO.add(`functions`,{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if(e.type!==`SYMBOL`)return[];let t=e.value;return en(this.composer.currentContent)?Object.entries(Ix.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:n}])=>({text:e,description:n,htmlContent:PB(t,e,ge,`o-semi-bold`)})).sort((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text)):[]},selectProposal(e,t){let n=e.end,r=e.end;[`SYMBOL`,`FUNCTION`].includes(e.type)&&(n=e.start);let i=this.composer.currentTokens;t+=`(`;let a=i.map(e=>e.start).indexOf(e.start);a+1<i.length&&i[a+1]?.type===`LEFT_PAREN`&&r++,this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}}),PO.add(`pivot_ids`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||![`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`].includes(t.parent.toUpperCase())||t.argPosition!==0)return;let n=this.getters.getPivotIds();if(!n.includes(e.value))return n.map(e=>{let t=this.getters.getPivotCoreDefinition(e),n=`${this.getters.getPivotFormulaId(e)}`;return{text:n,description:t.name,htmlContent:[{value:n,color:VO.NUMBER}],fuzzySearchKey:n+t.name,alwaysExpanded:!0}}).filter(C)},selectProposal:XB}),PO.add(`pivot_measures`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(t?.parent.toUpperCase()!==`PIVOT.VALUE`||t.argPosition!==1)return[];let n=ZB(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return[];let i=this.getters.getPivot(r);return i.init(),i.isValid()?i.definition.measures.map(e=>{if(e.fieldName===`__count`){let e=`"__count"`;return{text:e,description:E(`Count`),htmlContent:[{value:e,color:VO.STRING}],fuzzySearchKey:E(`Count`)+e}}return JB(e)}).filter(C):[]},selectProposal:YB}),PO.add(`pivot_group_fields`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!uG(e)&&!dG(e))return;let n=ZB(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);i.init();let a=i.getFields(),{columns:o,rows:s}=i.definition,c=t.args;t?.parent.toUpperCase()===`PIVOT.VALUE`?(c=c.filter((e,t)=>t%2==0),c=c.slice(1,t.argPosition)):c=c.filter((e,t)=>t%2==1);let l=c.map(e=>e?.value).filter(C),u=o.map(e=>e.nameWithGranularity),d=s.map(e=>e.nameWithGranularity),f=[],p=[`ARG_SEPARATOR`,`SPACE`].includes(e.type)?l.at(-1):l.at(-2),m=QV.get(i.type);if(m&&p?.startsWith(`#`)&&(p=p.slice(1)),p===void 0&&(f.push(u[0]),f.push(d[0])),d.includes(p)){let e=d[d.indexOf(p)+1];f.push(e),f.push(u[0])}if(u.includes(p)){let e=u[u.indexOf(p)+1];f.push(e)}let h=f.filter(C);return h.map(e=>{let[t,n]=e.split(`:`),r=a[t];return r?qB(r,n):void 0}).concat(h.map(e=>{if(!m)return;let t=a[e.split(`:`)[0]];if(!t)return;let n=`"#${e}"`;return{text:n,description:E(`%s (positional)`,t.string)+(t.help?` (${t.help})`:``),htmlContent:[{value:n,color:VO.STRING}],fuzzySearchKey:t.string+n}})).filter(C)},selectProposal:YB});function uG(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==0}function dG(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==1}PO.add(`pivot_group_values`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!e||!fG(e)&&!pG(e))return;let n=ZB(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);if(!i.isValid())return;let a=t.argPosition,o=e.functionContext?.args[a-1]?.value;if(!o)return;let s;try{s=i.definition.getDimension(o)}catch{return}return s.granularity===`month_number`?Object.values(so).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:VO.NUMBER}]})):s.granularity===`quarter_number`?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:E(`Quarter %s`,e),htmlContent:[{value:`${e}`,color:VO.NUMBER}]})):s.granularity===`day_of_month`?S(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:VO.NUMBER}]})):s.granularity===`iso_week_number`?S(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:VO.NUMBER}]})):s.granularity===`day_of_week`?S(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:VO.NUMBER}]})):s.granularity===`hour_number`?S(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:VO.NUMBER}]})):s.granularity===`minute_number`?S(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:VO.NUMBER}]})):s.granularity===`second_number`?S(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:VO.NUMBER}]})):i.getPossibleFieldValues(s).map(({value:e,label:t})=>{let n=typeof e==`string`,r=n?`"${e}"`:e.toString(),i=n?VO.STRING:VO.NUMBER,a=t===e?``:t;return{text:r,description:a,htmlContent:[{value:r,color:i}],fuzzySearchKey:r+a}})},selectProposal:YB});function fG(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==1}function pG(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==0}PO.add(`sheet_names`,{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return e.type===`SYMBOL`||e.type===`UNKNOWN`&&e.value.startsWith(`'`)?this.getters.getSheetIds().map(e=>{let t=ut(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith(`'`)?t:`'`+t}}):[]},selectProposal(e,t){let n=e.start,r=e.end;this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t+`!`)}});let mG=new g;mG.add(`link`,{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,n)=>Vr(t.model.getters.getEvaluatedCell(e).link,t,n),title:(e,t)=>{let n=t.getEvaluatedCell(e).link;return n?n.isExternal?E(`Go to url: %(url)s`,{url:n.url}):E(`Go to %(label)s`,{label:n.label}):``},sequence:5});let hG=new g().add(`ADD_COLUMNS_ROWS`,vG).add(`REMOVE_COLUMNS_ROWS`,CG).add(`ADD_MERGE`,yG).add(`REMOVE_MERGE`,bG).add(`CREATE_SHEET`,xG).add(`DELETE_SHEET`,wG).add(`DUPLICATE_SHEET`,SG).add(`CREATE_FIGURE`,TG).add(`CREATE_CHART`,EG).add(`HIDE_COLUMNS_ROWS`,DG).add(`UNHIDE_COLUMNS_ROWS`,OG).add(`CREATE_TABLE_STYLE`,kG).add(`ADD_PIVOT`,_G).add(`RENAME_SHEET`,AG);for(let e of vr.values())hG.contains(e)||hG.add(e,gG);function gG(e){return[e]}function _G(e){return[{type:`REMOVE_PIVOT`,pivotId:e.pivotId}]}function vG(e){let t=[],n=e.base;e.position===`after`&&n++;for(let r=0;r<e.quantity;r++)t.push(r+n);return[{type:`REMOVE_COLUMNS_ROWS`,dimension:e.dimension,elements:t,sheetId:e.sheetId,sheetName:e.sheetName}]}function yG(e){return[{type:`REMOVE_MERGE`,sheetId:e.sheetId,target:e.target}]}function bG(e){return[{type:`ADD_MERGE`,sheetId:e.sheetId,target:e.target}]}function xG(e){return[{type:`DELETE_SHEET`,sheetId:e.sheetId,sheetName:e.name}]}function SG(e){return[{type:`DELETE_SHEET`,sheetId:e.sheetIdTo,sheetName:``}]}function CG(e){let t=[],n=[...e.elements].sort((e,t)=>e-t);for(let r of ft(n)){let n=r[0]===0?0:r[0]-1,i=r[0]===0?`before`:`after`;t.push({type:`ADD_COLUMNS_ROWS`,dimension:e.dimension,quantity:r.length,base:n,sheetId:e.sheetId,sheetName:e.sheetName,position:i})}return t}function wG(e){return[{type:`CREATE_SHEET`,sheetId:e.sheetId,position:1,name:e.sheetName}]}function TG(e){return[{type:`DELETE_FIGURE`,figureId:e.figureId,sheetId:e.sheetId}]}function EG(e){return[{type:`DELETE_FIGURE`,figureId:e.figureId,sheetId:e.sheetId}]}function DG(e){return[{type:`UNHIDE_COLUMNS_ROWS`,sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}function OG(e){return[{type:`HIDE_COLUMNS_ROWS`,sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}function kG(e){return[{type:`REMOVE_TABLE_STYLE`,tableStyleId:e.tableStyleId}]}function AG(e){return[{type:`RENAME_SHEET`,sheetId:e.sheetId,oldName:e.newName,newName:e.oldName}]}let jG=new g;jG.add(`format_number_automatic`,{...aL,id:`format_number_automatic`,sequence:10}).add(`format_number_plain_text`,{...oL,id:`format_number_plain_text`,sequence:15,separator:!0}).add(`format_number_number`,{...sL,id:`format_number_number`,sequence:20}).add(`format_number_percent`,{...lL,id:`format_number_percent`,sequence:30,separator:!0}).add(`format_number_currency`,{...uL,id:`format_number_currency`,sequence:40}).add(`format_number_accounting`,{...fL,id:`format_number_accounting`,sequence:45}).add(`format_number_currency_rounded`,{...dL,id:`format_number_currency_rounded`,sequence:50}).add(`format_custom_currency`,{...mL,id:`format_custom_currency`,sequence:60,separator:!0}).add(`format_number_date`,{...hL,id:`format_number_date`,sequence:70}).add(`format_number_time`,{...gL,id:`format_number_time`,sequence:80}).add(`format_number_date_time`,{..._L,id:`format_number_date_time`,sequence:90}).add(`format_number_duration`,{...vL,id:`format_number_duration`,sequence:100,separator:!0}).add(`more_formats`,{...xL,id:`more_formats`,sequence:120});function MG(e){let t=new Set(jG.getAll().map(t=>typeof t.format==`function`?t.format(e):t.format)),n=new Map;for(let r of e.model.getters.getSheetIds()){let i=e.model.getters.getEvaluatedCells(r);for(let e in i){let r=i[e];if(r.format&&!n.has(r.format)&&!t.has(r.format)){let e=NG(r.format);(e===`date`||e===`currency`)&&n.set(r.format,iL({descriptionValue:e===`currency`?1e3:pL,format:r.format,name:r.format}))}}}return[...n.values()]}let NG=Vt(e=>So(e)?`date`:e.includes(`[$`)?`currency`:`number`),PG={name:E(`More formats`),icon:`o-spreadsheet-Icon.NUMBER_FORMATS`,children:[e=>{let t=MG(e).map(e=>({...e,sequence:110}));return t.length>0&&(t[t.length-1].separator=!0),f([...jG.getAll(),...t])}]};function FG(e){let t=new Pk;return t.add(`delete`,{...Dk,sequence:10}).add(`hide_sheet`,{...Nk,sequence:20}).add(`duplicate`,{...Ok,sequence:30,separator:!0}).add(`rename`,{...kk(e),sequence:40}).add(`change_color`,{...Ak(e),sequence:50,separator:!0}).add(`move_right`,{...jk,sequence:60}).add(`move_left`,{...Mk,sequence:70}),t}let IG=new Pk;IG.add(`file`,{name:E(`File`),sequence:10,isReadonlyAllowed:!0}).addChild(`settings`,[`file`],{name:E(`Settings`),sequence:200,execute:e=>e.openSidePanel(`Settings`),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.COG`}).add(`edit`,{name:E(`Edit`),sequence:20,isReadonlyAllowed:!0}).addChild(`undo`,[`edit`],{...fF,sequence:10}).addChild(`redo`,[`edit`],{...pF,sequence:20,separator:!0}).addChild(`copy`,[`edit`],{...mF,sequence:30}).addChild(`cut`,[`edit`],{...hF,sequence:40}).addChild(`paste`,[`edit`],{...gF,sequence:50}).addChild(`paste_special`,[`edit`],{..._F,sequence:60,separator:!0}).addChild(`paste_special_value`,[`edit`,`paste_special`],{...vF,sequence:10}).addChild(`paste_special_format`,[`edit`,`paste_special`],{...yF,sequence:20}).addChild(`edit_table`,[`edit`],{...MF,isVisible:fP,sequence:60}).addChild(`find_and_replace`,[`edit`],{...bF,sequence:65,separator:!0}).addChild(`delete`,[`edit`],{name:E(`Delete`),icon:`o-spreadsheet-Icon.TRASH`,sequence:70}).addChild(`edit_delete_cell_values`,[`edit`,`delete`],{...xF,sequence:10}).addChild(`edit_delete_row`,[`edit`,`delete`],{...SF,sequence:20}).addChild(`edit_delete_column`,[`edit`,`delete`],{...TF,sequence:30}).addChild(`edit_delete_cell_shift_up`,[`edit`,`delete`],{...kF,sequence:40}).addChild(`edit_delete_cell_shift_left`,[`edit`,`delete`],{...AF,sequence:50}).addChild(`edit_unhide_columns`,[`edit`],{...OP,sequence:80}).addChild(`edit_unhide_rows`,[`edit`],{...jP,sequence:80}).add(`view`,{name:E(`View`),sequence:30,isReadonlyAllowed:!0}).addChild(`unfreeze_panes`,[`view`],{...MP,sequence:4}).addChild(`freeze_panes`,[`view`],{...NP,sequence:5}).addChild(`unfreeze_rows`,[`view`,`freeze_panes`],{...PP,sequence:5}).addChild(`freeze_first_row`,[`view`,`freeze_panes`],{...FP,sequence:10}).addChild(`freeze_second_row`,[`view`,`freeze_panes`],{...IP,sequence:15}).addChild(`freeze_current_row`,[`view`,`freeze_panes`],{...LP,sequence:20,separator:!0}).addChild(`unfreeze_columns`,[`view`,`freeze_panes`],{...RP,sequence:25}).addChild(`freeze_first_col`,[`view`,`freeze_panes`],{...zP,sequence:30}).addChild(`freeze_second_col`,[`view`,`freeze_panes`],{...BP,sequence:35}).addChild(`freeze_current_col`,[`view`,`freeze_panes`],{...VP,sequence:40}).addChild(`group_headers`,[`view`],{name:E(`Group`),sequence:15,separator:!0,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,isVisible:vP}).addChild(`group_columns`,[`view`,`group_headers`],{...GP,sequence:5}).addChild(`ungroup_columns`,[`view`,`group_headers`],{...qP,isVisible:e=>ZP(e,`COL`),sequence:10}).addChild(`group_rows`,[`view`,`group_headers`],{...KP,sequence:15}).addChild(`ungroup_rows`,[`view`,`group_headers`],{...JP,isVisible:e=>ZP(e,`ROW`),sequence:20}).addChild(`show`,[`view`],{name:E(`Show`),sequence:1,icon:`o-spreadsheet-Icon.SHOW`}).addChild(`view_gridlines`,[`view`,`show`],{...HP,sequence:5}).addChild(`view_formulas`,[`view`,`show`],{...WP,sequence:10}).addChild(`view_irregularity_map`,[`view`],{...UP,sequence:40,separator:!0}).add(`insert`,{name:E(`Insert`),sequence:40,isReadonlyAllowed:!0}).addChild(`insert_row`,[`insert`],{...LF,sequence:10}).addChild(`insert_row_before`,[`insert`,`insert_row`],{...zF,sequence:10}).addChild(`insert_row_after`,[`insert`,`insert_row`],{...HF,sequence:20}).addChild(`insert_column`,[`insert`],{...UF,sequence:20}).addChild(`insert_column_before`,[`insert`,`insert_column`],{...GF,sequence:10}).addChild(`insert_column_after`,[`insert`,`insert_column`],{...JF,sequence:20}).addChild(`insert_cell`,[`insert`],{...YF,sequence:30}).addChild(`insert_cell_down`,[`insert`,`insert_cell`],{...XF,name:E(`Shift down`),sequence:10}).addChild(`insert_cell_right`,[`insert`,`insert_cell`],{...ZF,name:E(`Shift right`),sequence:20}).addChild(`insert_sheet`,[`insert`],{...mI,sequence:40,separator:!0}).addChild(`insert_chart`,[`insert`],{...QF,sequence:50}).addChild(`insert_pivot`,[`insert`],{...$F,sequence:52}).addChild(`insert_image`,[`insert`],{...eI,sequence:55}).addChild(`insert_table`,[`insert`],{...tI,sequence:57}).addChild(`insert_function`,[`insert`],{...nI,sequence:60}).addChild(`insert_function_sum`,[`insert`,`insert_function`],{...rI,sequence:0}).addChild(`insert_function_average`,[`insert`,`insert_function`],{...iI,sequence:10}).addChild(`insert_function_count`,[`insert`,`insert_function`],{...aI,sequence:20}).addChild(`insert_function_max`,[`insert`,`insert_function`],{...oI,sequence:30}).addChild(`insert_function_min`,[`insert`,`insert_function`],{...sI,sequence:40,separator:!0}).addChild(`categorie_function_all`,[`insert`,`insert_function`],{...cI,sequence:50}).addChild(`categories_function_list`,[`insert`,`insert_function`],uI).addChild(`insert_link`,[`insert`],{...dI,separator:!0,sequence:70}).addChild(`insert_checkbox`,[`insert`],{...fI,sequence:80}).addChild(`insert_dropdown`,[`insert`],{...pI,separator:!0,sequence:90}).add(`format`,{name:E(`Format`),sequence:50,isReadonlyAllowed:!0}).addChild(`format_number`,[`format`],{...PG,name:E(`Number`),sequence:10,separator:!0}).addChild(`format_bold`,[`format`],{...NL,sequence:20}).addChild(`format_italic`,[`format`],{...PL,sequence:30}).addChild(`format_underline`,[`format`],{...FL,sequence:40}).addChild(`format_strikethrough`,[`format`],{...IL,sequence:50,separator:!0}).addChild(`format_font_size`,[`format`],{...LL,sequence:60,separator:!0}).addChild(`format_alignment`,[`format`],{...RL,sequence:70}).addChild(`format_alignment_left`,[`format`,`format_alignment`],{...BL,sequence:10}).addChild(`format_alignment_center`,[`format`,`format_alignment`],{...VL,sequence:20}).addChild(`format_alignment_right`,[`format`,`format_alignment`],{...HL,sequence:30,separator:!0}).addChild(`format_alignment_top`,[`format`,`format_alignment`],{...WL,sequence:40}).addChild(`format_alignment_middle`,[`format`,`format_alignment`],{...GL,sequence:50}).addChild(`format_alignment_bottom`,[`format`,`format_alignment`],{...KL,sequence:60,separator:!0}).addChild(`format_wrapping`,[`format`],{...qL,sequence:80,separator:!0}).addChild(`format_wrapping_overflow`,[`format`,`format_wrapping`],{...YL,sequence:10}).addChild(`format_wrapping_wrap`,[`format`,`format_wrapping`],{...XL,sequence:20}).addChild(`format_wrapping_clip`,[`format`,`format_wrapping`],{...ZL,sequence:30}).addChild(`format_cf`,[`format`],{...QL,sequence:90,separator:!0}).addChild(`format_clearFormat`,[`format`],{...$L,sequence:100,separator:!0}).add(`data`,{name:E(`Data`),sequence:60,isReadonlyAllowed:!0}).addChild(`sort_range`,[`data`],{...qI,sequence:10,separator:!0}).addChild(`sort_ascending`,[`data`,`sort_range`],{...JI,sequence:10}).addChild(`sort_descending`,[`data`,`sort_range`],{...QI,sequence:20}).addChild(`data_cleanup`,[`data`],{...YI,sequence:15}).addChild(`remove_duplicates`,[`data`,`data_cleanup`],{...XI,sequence:10}).addChild(`trim_whitespace`,[`data`,`data_cleanup`],{...ZI,sequence:20}).addChild(`split_to_columns`,[`data`],{...tL,sequence:20}).addChild(`data_validation`,[`data`],{name:E(`Data Validation`),execute:e=>{e.openSidePanel(`DataValidation`)},isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.DATA_VALIDATION`,sequence:30,separator:!0}).addChild(`add_remove_data_filter`,[`data`],{...$I,sequence:40,separator:!0}).addChild(`pivot_data_sources`,[`data`],e=>{let t=e.model.getters.getPivotIds().length;return e.model.getters.getPivotIds().map((n,r)=>{let i={get highlights(){return AB(e.model.getters,n)}};return{id:`item_pivot_${e.model.getters.getPivotFormulaId(n)}`,name:e.model.getters.getPivotDisplayName(n),sequence:50+r/t,isReadonlyAllowed:!0,execute:e=>e.openSidePanel(`PivotSidePanel`,{pivotId:n}),isEnabled:e=>!e.isSmall,onStartHover:e=>e.getStore(IO).register(i),onStopHover:e=>e.getStore(IO).unRegister(i),icon:`o-spreadsheet-Icon.PIVOT`,separator:r===e.model.getters.getPivotIds().length-1,secondaryIcon:e=>e.model.getters.isPivotUnused(n)?`o-spreadsheet-Icon.UNUSED_PIVOT_WARNING`:void 0}})}).addChild(`reinsert_dynamic_pivot`,[`data`],nL).addChild(`reinsert_static_pivot`,[`data`],rL);let LG=new class extends g{mapping={};uuidGenerator=new gl;replace(e,t){let n={...t,id:this.uuidGenerator.uuidv4()};return super.replace(e,n)}getAllOrdered(){return this.getAll().sort((e,t)=>e.sequence-t.sequence)}};var RG=class{listeners=[];async sendMessage(e){for(let{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter(t=>t.id!==e)}},zG=class{fileStore;constructor(e){this.fileStore=e}async requestImage(){let e=await this.userImageUpload(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}async uploadFile(e){let t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}userImageUpload(){return new Promise((e,t)=>{let n=document.createElement(`input`);n.setAttribute(`type`,`file`),n.setAttribute(`accept`,`image/*`),n.addEventListener(`change`,async()=>{n.files===null||n.files.length!==1?t():e(n.files[0])}),n.click()})}getImageOriginalSize(e){return new Promise((t,n)=>{let r=new Image;r.addEventListener(`load`,()=>{t({width:r.width,height:r.height})}),r.addEventListener(`error`,n),r.src=e})}};let BG=[{transform:`scale(0)`},{transform:`scale(0.8)`,offset:.33},{opacity:`0`,transform:`scale(1)`,offset:1}];V`
|
|
1953
|
+
You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=await tw(t)}}if(r)return r instanceof File?r:new File([r],`image.png`,{type:`image/png`})}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r;return r=t===`COL`?{...e,left:e.right+1,right:this.getters.getNumberCols(n)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1},{cut:[r],paste:[e]}}getInsertCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r,i;return t===`COL`?(r={...e,right:this.getters.getNumberCols(n)-1},i={...e,left:e.right+1,right:e.right+1}):(r={...e,bottom:this.getters.getNumberRows(n)-1},i={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1}),{cut:[r],paste:[i]}}getClipboardData(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedFigureId();if(n)return{figureId:n,sheetId:t};let r=vl(t,e);return this._isCutOperation||(r.rowsIndexes=r.rowsIndexes.filter(e=>!this.getters.isRowFiltered(t,e))),r}drawLayer(e){if(this.status!==`visible`||!this.copiedData)return;let{sheetId:t,zones:n}=this.copiedData;if(t!==this.getters.getActiveSheetId()||!n||!n.length)return;let{ctx:r,thinLineWidth:i}=e;r.setLineDash([8,5]),r.strokeStyle=ae,r.lineWidth=3.3*i;for(let e of n){let{x:t,y:n,width:i,height:a}=this.getters.getVisibleRect(e);i>0&&a>0&&r.strokeRect(t,n,i,a)}}};let eG={filterType:`criterion`,type:`none`,values:[]};var tG=class extends SU{static getters=[`getFilterValue`,`getFilterHiddenValues`,`getFilterCriterionValue`,`getFirstTableInSelection`,`isRowFiltered`,`isFilterActive`];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){switch(e.type){case`UPDATE_FILTER`:if(!this.getters.getFilterId(e))return`FilterNotFound`;break}return`Success`}handle(e){switch(e.type){case`UNDO`:case`REDO`:case`UPDATE_CELL`:case`EVALUATE_CELLS`:case`ACTIVATE_SHEET`:case`REMOVE_TABLE`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`UPDATE_TABLE`:this.isEvaluationDirty=!0;break;case`START`:for(let e of this.getters.getSheetIds())this.filterValues[e]={};break;case`CREATE_SHEET`:this.filterValues[e.sheetId]={};break;case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`GROUP_HEADERS`:case`UNGROUP_HEADERS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_ALL_HEADER_GROUPS`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:this.updateHiddenRows(e.sheetId);break;case`UPDATE_FILTER`:this.updateFilter(e),this.updateHiddenRows(e.sheetId);break;case`DUPLICATE_SHEET`:this.filterValues[e.sheetIdTo]=b(this.filterValues[e.sheetId]);break}}finalize(){if(this.isEvaluationDirty){for(let e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterValue(e){let t=this.getters.getFilterId(e),n=e.sheetId;return t?this.filterValues[n]?.[t]:void 0}getFilterHiddenValues(e){let t=this.getters.getFilterId(e),n=e.sheetId;if(!t||!this.filterValues[n])return[];let r=this.filterValues[n][t]||[];return r.filterType===`values`?r.hiddenValues:[]}getFilterCriterionValue(e){let t=this.getters.getFilterId(e),n=e.sheetId;if(!t||!this.filterValues[n])return eG;let r=this.filterValues[n][t];return r&&r.filterType===`criterion`?r:eG}isFilterActive(e){let t=this.getters.getFilterId(e);if(!t)return!1;let n=e.sheetId,r=this.filterValues[n]?.[t];return r?r.filterType===`values`?r.hiddenValues.length>0:r.type!==`none`:!1}getFirstTableInSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,value:n,sheetId:r}){let i=this.getters.getFilterId({sheetId:r,col:e,row:t});i&&(this.filterValues[r]||(this.filterValues[r]={}),this.filterValues[r][i]=n)}updateHiddenRows(e){let t=this.getters.getFilters(e).sort((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top),n=new Set;for(let r of t){let t=this.filterValues[e]?.[r.id],i=r.filteredRange?.zone;if(!(!t||!i||n.has(r.rangeWithHeaders.zone.top)||this.getters.isRowHiddenByUser(e,r.rangeWithHeaders.zone.top)))if(t.filterType===`values`){let a=t.hiddenValues?.map(ul);if(!a)continue;let o=new Set(a);for(let t=i.top;t<=i.bottom;t++){let i=this.getCellValueAsString(e,r.col,t);o.has(i)&&n.add(t)}}else{if(t.type===`none`)continue;let a=Y.get(t.type),o=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(e,t)??``:Ko(t,D));if(o.some(Du))continue;let s={type:t.type,values:o.map(Tu),dateValue:t.dateValue};for(let t=i.top;t<=i.bottom;t++){let i={sheetId:e,col:r.col,row:t},o=this.getters.getEvaluatedCell(i).value??``;a.isValueValid(o,s,this.getters,e)||n.add(t)}}}this.hiddenRows[e]=n}getCellValueAsString(e,t,n){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).formattedValue.toLowerCase()}exportForExcel(e){for(let t of e.sheets){let e=t.id;for(let n of t.tables){let r=ps(n.range),i=[],a=[];for(let n of S(0,js(r).numberOfCols)){let o={sheetId:t.id,col:r.left+n,row:r.top},s=this.getFilterHiddenValues(o),c=this.getters.getFilter(o),l=c?.filteredRange?Fs(c.filteredRange.zone).map(t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue):[];if(s.length){let e=l.filter(e=>e).filter(e=>!s.includes(e));i.push({colId:n,displayedValues:[...new Set(e)],displayBlanks:!s.includes(``)&&l.some(e=>!e)})}let u=this.getters.getEvaluatedCell(o).formattedValue,d=this.getUniqueColNameForExcel(n,u,a);a.push(d);let f=T(o.col,o.row);t.cells[f]=d,t.cellValues[f]=d}n.filters=i}}}getUniqueColNameForExcel(e,t,n){return t||=`Column${e}`,$t(t,n,{compute:(e,n)=>t+String(n),start:2})}},nG=class extends SU{static layers=[`Selection`];static getters=[`getActiveSheet`,`getActiveSheetId`,`getActiveSheetName`,`getActiveCell`,`getActiveCols`,`getActiveRows`,`getCurrentStyle`,`getSelectedZones`,`getSelectedZone`,`getSelectedCells`,`getSelectedFigureId`,`getSelection`,`getActivePosition`,`getSheetPosition`,`isSingleColSelected`,`getElementsFromSelection`,`tryGetActiveSheetId`,`isGridSelectionActive`,`getSelectecUnboundedZone`];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;isUnbounded;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient,this.isUnbounded=!1}allowDispatch(e){switch(e.type){case`ACTIVATE_SHEET`:try{if(!this.getters.getSheet(e.sheetIdTo).isVisible)return`SheetIsHidden`;break}catch{return`InvalidSheetId`}case`MOVE_COLUMNS_ROWS`:return this.isMoveElementAllowed(e)}return`Success`}handleEvent(e){let t=e.anchor,n=[];switch(this.isUnbounded=e.options?.unbounded||!1,e.mode){case`overrideSelection`:n=[t.zone];break;case`updateAnchor`:n=[...this.gridSelection.zones];let r=n.findIndex(t=>Es(t,e.previousAnchor.zone));r>=0&&(n[r]=t.zone);break;case`newAnchor`:n=[...this.gridSelection.zones,t.zone];break}this.setSelectionMixin(e.anchor,n),this.selection.resetDefaultAnchor(this,b(this.gridSelection.anchor));let{col:r,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:r,row:i}),this.selectedFigureId=null}handle(e){switch(e.type){case`ACTIVATE_SHEET`:this.selectedFigureId=null;break;case`DELETE_FIGURE`:this.selectedFigureId===e.figureId&&(this.selectedFigureId=null);break;case`DELETE_SHEET`:this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null);break}switch(e.type){case`START`:let t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);let{col:n,row:r}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(n,r),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case`ACTIVATE_SHEET`:this.activateSheet(e.sheetIdFrom,e.sheetIdTo);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){e.dimension===`COL`?this.onColumnsRemoved(e):this.onRowsRemoved(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`ADD_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`MOVE_COLUMNS_ROWS`:e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case`SELECT_FIGURE`:this.selectedFigureId=e.figureId;break;case`ACTIVATE_NEXT_SHEET`:this.activateNextSheet(`right`);break;case`ACTIVATE_PREVIOUS_SHEET`:this.activateNextSheet(`left`);break;case`HIDE_SHEET`:e.sheetId===this.getActiveSheetId()&&this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case`UNDO`:case`REDO`:case`DELETE_SHEET`:let i=Object.keys(this.sheetsData).filter(e=>!this.getters.tryGetSheet(e));for(let e of i)delete this.sheetsData[e];for(let e in this.sheetsData){let t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:b(t)}}this.fallbackToVisibleSheet();let a=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map(e=>this.getters.expandZone(a,e)),this.gridSelection.anchor.zone=this.getters.expandZone(a,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null;break}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,b(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveSheetName(){return this.activeSheet.name}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){let e=new Set;for(let t of this.gridSelection.zones)if(t.top===0&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let n=t.left;n<=t.right;n++)e.add(n);return e}getActiveRows(){let e=new Set,t=this.getters.getActiveSheetId();for(let n of this.gridSelection.zones)if(n.left===0&&n.right===this.getters.getNumberCols(t)-1)for(let t=n.top;t<=n.bottom;t++)e.add(t);return e}getCurrentStyle(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return b(this.gridSelection.zones)}getSelectedZone(){return b(this.gridSelection.anchor.zone)}getSelectecUnboundedZone(){return b(this.isUnbounded?this.getters.getUnboundedZone(this.activeSheet.id,this.gridSelection.anchor.zone):this.gridSelection.anchor.zone)}getSelection(){return b(this.gridSelection)}getSelectedCells(){let e=this.getters.getActiveSheetId(),t=[];for(let n of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,n));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{let t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}isSingleColSelected(){let e=this.getters.getSelectedZones();return!(e.length!==1||e[0].left!==e[0].right)}getElementsFromSelection(e){if(e===`COL`&&this.getters.getActiveCols().size===0||e===`ROW`&&this.getters.getActiveRows().size===0)return[];let t=this.getters.getSelectedZones(),n=[],r=e===`COL`?`left`:`top`,i=e===`COL`?`right`:`bottom`;for(let e of t){let t=Array.from({length:e[i]-e[r]+1},(t,n)=>e[r]+n);n=n.concat(t)}return[...new Set(n)].sort()}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:b(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,b(this.gridSelection.anchor));else{let{col:e,row:n}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,n)}let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:n,row:r})}setSelectionMixin(e,t){let{anchor:n,zones:r}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=n,this.gridSelection.zones=Rs(r)}selectCell(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.expandZone(n,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:r,cell:{col:e,row:t}},[r])}setActiveSheet(e){this.activeSheet=this.getters.getSheet(e)}activateNextSheet(e){let t=this.getters.getSheetIds(),n=(t.findIndex(e=>e===this.activeSheet.id)+(e===`left`?t.length-1:1))%t.length;this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[n]})}onColumnsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=xs(n,`left`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=xs(i,`left`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>xs(t,`left`,[...e.elements]));this.setSelectionMixin(a,o)}onRowsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=xs(n,`top`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=xs(i,`top`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>xs(t,`top`,[...e.elements]));this.setSelectionMixin(a,o)}onAddElements(e){let t=e.dimension===`COL`?`left`:`top`,n=bs(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),r=this.gridSelection.zones.map(n=>bs(n,t,e.base,e.position,e.quantity)),i={cell:{col:n.left,row:n.top},zone:n};this.setSelectionMixin(i,r)}onMoveElements(e){let t=e.elements.length,n=this.getFiguresUpdates(e);this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,base:e.base,quantity:t,position:e.position});let r=e.dimension===`COL`,i=e.elements[0],a=e.elements[t-1],o=e.base<i,s=o&&r?t:0,c=o&&!r?t:0,l=o?e.elements.map(e=>e+t):e.elements,u={};for(let t of l)u[t]=this.getters.getHeaderSize(e.sheetId,e.dimension,t);let d=[{left:r?i+s:0,right:r?a+s:this.getters.getNumberCols(e.sheetId)-1,top:r?0:i+c,bottom:r?this.getters.getNumberRows(e.sheetId)-1:a+c}],f=this.getActiveSheetId(),p=o?e.base:e.base+1,m=[{left:r?p:0,right:r?p+t-1:this.getters.getNumberCols(e.sheetId)-1,top:r?0:p,bottom:r?this.getters.getNumberRows(e.sheetId)-1:p+t-1}];for(let e of Fd.cellHandlers.getAll()){let t=new e(this.getters,this.dispatch),n=t.copy(vl(f,d),!1,`shiftCells`);n&&t.paste({zones:m,sheetId:f},n,{isCutOperation:!0})}let h=m[0],g=h.left,_=h.top;this.setSelectionMixin({zone:h,cell:{col:g,row:_}},[h]);let v=o?e.base:e.base+1,y={};for(let t of l){let n=u[t];n!==this.getters.getHeaderSize(e.sheetId,e.dimension,v)&&(y[n]??=[],y[n].push(v)),v+=1}for(let t in y)this.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,size:parseInt(t,10),elements:y[t]});this.dispatch(`REMOVE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,elements:l}),this.applyFigureUpdates(n)}getFiguresUpdates(e){let t=[],n={},r=e.elements[0]<e.base?e.base-e.elements.length+1:e.base;for(let t=0;t<e.elements.length;t++)n[e.elements[t]]=r+t;for(let r of this.getters.getFigures(e.sheetId))e.dimension===`COL`&&r.col in n&&t.push({type:`UPDATE_FIGURE`,sheetId:e.sheetId,figureId:r.id,col:n[r.col],row:r.row}),e.dimension===`ROW`&&r.row in n&&t.push({type:`UPDATE_FIGURE`,sheetId:e.sheetId,figureId:r.id,row:n[r.row],col:r.col});return t}applyFigureUpdates(e){for(let t of e)this.dispatch(t.type,{...t})}isMoveElementAllowed(e){let t=e.dimension===`COL`,n=e.elements[0],r=e.elements[e.elements.length-1],i=e.sheetId,a=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(a(i,n-1,n)||a(i,r,r+1)||a(i,e.base-1,e.base))return`WillRemoveExistingMerge`;let o=[e.base,...e.elements],s=t?this.getters.getNumberCols(i):this.getters.getNumberRows(i);return o.some(e=>e<0||e>=s)?`InvalidHeaderIndex`:!t&&!this.isTableRowMoveAllowed(i,e.elements)?`CannotMoveTableHeader`:`Success`}isTableRowMoveAllowed(e,t){let n=this.getters.getCoreTables(e);if(n.length===0)return!0;let r=new Set(t);return n.every(({range:{zone:e},config:n})=>{let{top:i,bottom:a}=e;if(n.numberOfHeaders===0)return!0;let o=i+n.numberOfHeaders-1;return t.some(e=>e>=i&&e<=o)?S(i,a+1).every(e=>r.has(e)):!0})}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){let e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){let{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);let{col:t,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:n})}}clipSelection(e,t){let n=this.getters.getNumberCols(e)-1,r=this.getters.getNumberRows(e)-1,i=t.zones.map(e=>({left:x(e.left,0,n),right:x(e.right,0,n),top:x(e.top,0,r),bottom:x(e.bottom,0,r)})),a=x(t.anchor.cell.col,0,n),o=x(t.anchor.cell.row,0,r),s={left:x(t.anchor.zone.left,0,n),right:x(t.anchor.zone.right,0,n),top:x(t.anchor.zone.top,0,r),bottom:x(t.anchor.zone.bottom,0,r)};return{zones:i,anchor:{cell:{col:a,row:o},zone:s}}}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getSelectedZones();t.fillStyle=`#f3f7fe`,t.fillStyle=r.length===1&&r[0].left===r[0].right&&r[0].top===r[0].bottom?`#f3f7fe`:`#e9f0ff`,t.strokeStyle=ae,t.lineWidth=1.5*n;for(let e of r){let{x:n,y:r,width:i,height:a}=this.getters.getVisibleRect(e);t.globalCompositeOperation=`multiply`,t.fillRect(n,r,i,a),t.globalCompositeOperation=`source-over`,t.strokeRect(n,r,i,a)}t.globalCompositeOperation=`source-over`;let i=this.getActivePosition();t.strokeStyle=ae,t.lineWidth=3*n;let a;a=this.getters.isInMerge(i)?this.getters.getMerge(i):z(i);let{x:o,y:s,width:c,height:l}=this.getters.getVisibleRect(a);c>0&&l>0&&t.strokeRect(o,s,c,l)}},rG=class{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,n,r,i,a){if(this.getters=e,this.sheetId=t,this.boundaries=n,r.width<0||r.height<0)throw Error(`Viewport size cannot be negative`);this.viewportWidth=r.height&&r.width,this.viewportHeight=r.width&&r.height,this.top=n.top,this.bottom=n.bottom,this.left=n.left,this.right=n.right,this.offsetX=a.x,this.offsetY=a.y,this.canScrollVertically=i.canScrollVertically,this.canScrollHorizontally=i.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){let e=this.getters.findLastVisibleColRowIndex(this.sheetId,`COL`,{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,`ROW`,{first:this.boundaries.top,last:this.boundaries.bottom}),{end:n}=this.getters.getColDimensions(this.sheetId,e),{end:r}=this.getters.getRowDimensions(this.sheetId,t),i=n-this.offsetCorrectionX;this.canScrollHorizontally&&(i=Math.max(i,this.viewportWidth));let a=r-this.offsetCorrectionY;return this.canScrollVertically&&(a=Math.max(a,this.viewportHeight),r+46>a&&!this.getters.isReadonly()&&(a+=46)),{width:i,height:a}}getColIndex(e){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex(`COL`,e-this.offsetCorrectionX+this.snapCorrection.x,this.left)}getRowIndex(e){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex(`ROW`,e-this.offsetCorrectionY+this.snapCorrection.y,this.top)}adjustPosition(e){let t=this.sheetId,n=this.getters.getMainCellPosition({sheetId:t,...e}),{col:r,row:i}=this.getters.getNextVisibleCellPosition(n);ks(r,this.boundaries.top,this.boundaries)&&this.adjustPositionX(r),ks(this.boundaries.left,i,this.boundaries)&&this.adjustPositionY(i)}adjustPositionX(e){let t=this.sheetId,{start:n,end:r}=this.getters.getColDimensions(t,e);this.offsetX+this.viewportWidth+this.offsetCorrectionX<r?this.offsetX=r-this.viewportWidth:this.offsetX+this.offsetCorrectionX>n&&(this.offsetX=n-this.offsetCorrectionX),this.adjustViewportZoneX()}adjustPositionY(e){let t=this.sheetId,{start:n,end:r}=this.getters.getRowDimensions(t,e);this.offsetY+this.viewportHeight+this.offsetCorrectionY<r?this.offsetY=r-this.viewportHeight:this.offsetY+this.offsetCorrectionY>n&&(this.offsetY=n-this.offsetCorrectionY),this.adjustViewportZoneY()}willNewOffsetScrollViewport(e,t){return this.canScrollHorizontally&&this.offsetX!==e||this.canScrollVertically&&this.offsetY!==t}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getVisibleRect(e){let t=Ts(e,this),n=this.snapCorrection.x,r=this.snapCorrection.y;if(t)return{x:this.getters.getColRowOffset(`COL`,this.left,t.left)+this.offsetCorrectionX-(this.left===t.left?0:n),y:this.getters.getColRowOffset(`ROW`,this.top,t.top)+this.offsetCorrectionY-(this.top===t.top?0:r),width:Math.min(this.getters.getColRowOffset(`COL`,t.left,t.right+1)-(this.left===t.left?n:0),this.viewportWidth),height:Math.min(this.getters.getColRowOffset(`ROW`,t.top,t.bottom+1)-(this.top===t.top?r:0),this.viewportHeight)}}getFullRect(e){let t=Ts(e,this.boundaries),n=this.snapCorrection.x,r=this.snapCorrection.y;if(t){let t=this.getters.getColRowOffset(`COL`,this.left,e.left)+this.offsetCorrectionX,i=this.getters.getColRowOffset(`ROW`,this.top,e.top)+this.offsetCorrectionY,a=this.getters.getColRowOffset(`COL`,e.left,e.right+1),o=this.getters.getColRowOffset(`ROW`,e.top,e.bottom+1);return{x:t-n,y:i-r,width:a,height:o}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,n=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;let r=this.sheetId,i=this.getters.getNumberHeaders(r,e),a=n,o=i;for(;a<=o&&a!==i&&o!==-1;){let i=Math.floor((a+o)/2),s=this.getters.getColRowOffset(e,n,i),c=this.getters.getHeaderSize(r,e,i);if(t>=s&&t<s+c)return i;t>=s+c?a=i+1:o=i-1}return-1}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){let{width:e}=this.getMaxSize();this.viewportWidth+this.offsetX>e&&(this.offsetX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){let{height:e}=this.getMaxSize();this.viewportHeight+this.offsetY>e&&(this.offsetY=Math.max(0,e-this.viewportHeight))}this.adjustViewportZoneY()}adjustViewportZoneX(){this.left=this.searchHeaderIndex(`COL`,this.offsetX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex(`COL`,Math.max(this.viewportWidth+this.snapCorrection.x-.1),this.left)),this.viewportWidth&&(this.left===-1&&(this.left=this.boundaries.left),this.right===-1&&(this.right=this.boundaries.right))}adjustViewportZoneY(){this.top=this.searchHeaderIndex(`ROW`,this.offsetY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex(`ROW`,Math.max(this.viewportHeight+this.snapCorrection.y-.1,0),this.top)),this.viewportHeight&&(this.top===-1&&(this.top=this.boundaries.top),this.bottom===-1&&(this.bottom=this.boundaries.bottom))}get snapCorrection(){return{x:Math.abs(this.offsetX-this.getters.getColRowOffset(`COL`,this.boundaries.left,Math.max(0,this.left))),y:Math.abs(this.offsetY-this.getters.getColRowOffset(`ROW`,this.boundaries.top,Math.max(0,this.top)))}}},iG=class extends SU{static getters=`getColIndex.getRowIndex.getActiveMainViewport.getSheetViewDimension.getSheetViewDimensionWithHeaders.getMainViewportRect.isVisibleInViewport.getEdgeScrollCol.getEdgeScrollRow.getVisibleFigures.getVisibleRect.getVisibleRectWithoutHeaders.getVisibleCellPositions.getColRowOffsetInViewport.getMainViewportCoordinates.getActiveSheetScrollInfo.getSheetViewVisibleCols.getSheetViewVisibleRows.getFrozenSheetViewRatio.isPixelPositionVisible.getColDimensionsInViewport.getRowDimensionsInViewport.getAllActiveViewportsZonesAndRect.getRect.getFigureUI.getPositionAnchorOffset.getGridOffset.getMaximumSheetOffset`.split(`.`);viewports={};sheetViewWidth=Qe();sheetViewHeight=Qe();gridOffsetX=0;gridOffsetY=0;sheetsWithDirtyViewports=new Set;shouldAdjustViewports=!1;allowDispatch(e){switch(e.type){case`SET_VIEWPORT_OFFSET`:return this.chainValidations(this.checkScrollingDirection,this.checkIfViewportsWillChange)(e);case`RESIZE_SHEETVIEW`:return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return`Success`}}handleEvent(e){let t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let{col:n,row:r}=Bs(e.previousAnchor.zone,e.anchor.zone);if(e.mode===`updateAnchor`){let i=e.previousAnchor.zone,a=e.anchor.zone,{top:o,bottom:s,left:c,right:l}=this.getMainInternalViewport(t);i.left===a.left&&i.right===a.right&&(n=c>n||n>l?c:n),i.top===a.top&&i.bottom===a.bottom&&(r=o>r||r>s?o:r)}n=Math.min(n,this.getters.getNumberCols(t)-1),r=Math.min(r,this.getters.getNumberRows(t)-1),this.sheetsWithDirtyViewports.has(t)||this.refreshViewport(this.getters.getActiveSheetId(),{col:n,row:r})}}handle(e){if(fr.has(e.type))for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);switch(e.type){case`START`:this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case`UNDO`:case`REDO`:this.cleanViewports();for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);this.shouldAdjustViewports=!0;break;case`RESIZE_SHEETVIEW`:this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case`SET_VIEWPORT_OFFSET`:this.setSheetViewOffset(e.offsetX,e.offsetY);break;case`SHIFT_VIEWPORT_DOWN`:let t=this.getters.getActiveSheetId(),{top:n,viewportHeight:r,offsetCorrectionY:i}=this.getMainInternalViewport(t),a=this.getters.getRowDimensions(t,n);this.shiftVertically(a.start+r-i);break;case`SHIFT_VIEWPORT_UP`:{let e=this.getters.getActiveSheetId(),{top:t,viewportHeight:n,offsetCorrectionY:r}=this.getMainInternalViewport(e),i=this.getters.getRowDimensions(e,t);this.shiftVertically(i.end-r-n);break}case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`UPDATE_FILTER`:case`UNFREEZE_ROWS`:case`UNFREEZE_COLUMNS`:case`FREEZE_COLUMNS`:case`FREEZE_ROWS`:case`UNFREEZE_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`RESIZE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`UNGROUP_HEADERS`:case`GROUP_HEADERS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_ALL_HEADER_GROUPS`:this.sheetsWithDirtyViewports.add(e.sheetId);break;case`UPDATE_CELL`:for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);break;case`DELETE_SHEET`:this.cleanViewports(),this.sheetsWithDirtyViewports.delete(e.sheetId);break;case`ACTIVATE_SHEET`:this.sheetsWithDirtyViewports.add(e.sheetIdTo);break;case`SCROLL_TO_CELL`:this.refreshViewport(this.getters.getActiveSheetId(),{col:e.col,row:e.row});break}}finalize(){for(let e of this.sheetsWithDirtyViewports)if(this.resetViewports(e),this.shouldAdjustViewports){let t=this.getters.getSheetPosition(e);this.getSubViewports(e).forEach(e=>{e.adjustPosition(t)})}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){let e=this.getters.getSheetIds();for(let t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getColIndex(e)))}getRowIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getRowIndex(e)))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getGridOffset(){return{x:this.gridOffsetX,y:this.gridOffsetY}}getActiveMainViewport(){let e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getSheetViewVisibleCols(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>S(e.left,e.right+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`COL`,t))}getSheetViewVisibleRows(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>S(e.top,e.bottom+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`ROW`,t))}getVisibleCellPositions(){let e=this.getSheetViewVisibleCols(),t=this.getSheetViewVisibleRows(),n=this.getters.getActiveSheetId(),r=[];for(let i of e)for(let e of t){let t={sheetId:n,col:i,row:e},a=this.getters.getMainCellPosition(t);a.row!==e||a.col!==i||r.push(t)}return r}getMainViewportRect(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e),{width:i,height:a}=t.getMaxSize();return{x:this.getters.getColDimensions(e,n).start,y:this.getters.getRowDimensions(e,r).start,width:i,height:a}}getMaximumSheetOffset(){let e=this.getters.getActiveSheetId(),{width:t,height:n}=this.getMainViewportRect(),r=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-r.viewportWidth),maxOffsetY:Math.max(0,n-r.viewportHeight)}}getColRowOffsetInViewport(e,t,n){if(n<t)return-this.getColRowOffsetInViewport(e,n,t);let r=this.getters.getActiveSheetId(),i=e===`COL`?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),a=i.findIndex(e=>t>=e),o=i.findIndex(e=>n<=e);o=o===-1?i.length:o;let s=i.slice(a,o),c=0;for(let t of s)c+=this.getters.getHeaderSize(r,e,t);return c}isVisibleInViewport({sheetId:e,col:t,row:n}){return this.getSubViewports(e).some(e=>e.isVisible(t,n))}getEdgeScrollCol(e,t,n){let r=!1,i=0,a=0,{xSplit:o}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:s}=this.getSheetViewDimension(),{x:c}=this.getMainViewportCoordinates(),l=this.getActiveSheetScrollInfo().scrollX;return e>s?(r=!0,a=ac(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=ac(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=ac(e),i=`reset`),{canEdgeScroll:r,direction:i,delay:a}}getEdgeScrollRow(e,t,n){let r=!1,i=0,a=0,{ySplit:o}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:s}=this.getSheetViewDimension(),{y:c}=this.getMainViewportCoordinates(),l=this.getActiveSheetScrollInfo().scrollY;return e>s?(r=!0,a=ac(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=ac(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=ac(e),i=`reset`),{canEdgeScroll:r,direction:i,delay:a}}getVisibleRect(e){let t=this.getVisibleRectWithoutHeaders(e);return{...t,x:t.x+this.gridOffsetX,y:t.y+this.gridOffsetY}}getVisibleRectWithoutHeaders(e){let t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getVisibleRect(e))}getRect(e){let t=this.getters.getActiveSheetId(),n=this.mapViewportsToRect(t,t=>t.getFullRect(e));return{...n,x:n.x+this.gridOffsetX,y:n.y+this.gridOffsetY}}getRectWithoutHeaders(e){let t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getFullRect(e))}getMainViewportCoordinates(){let e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,n).start}}getColDimensionsInViewport(e,t){let{top:n}=this.getMainInternalViewport(e),r={left:t,right:t,top:n,bottom:n},{x:i,width:a}=this.getVisibleRect(r),o=i-this.gridOffsetX;return{start:o,size:a,end:o+a}}getRowDimensionsInViewport(e,t){let{left:n}=this.getMainInternalViewport(e),r={left:0,right:n,top:t,bottom:t},{y:i,height:a}=this.getVisibleRect(r),o=i-this.gridOffsetY;return{start:o,size:a,end:o+a}}getAllActiveViewportsZonesAndRect(){let e=this.getters.getActiveSheetId();return this.getSubViewports(e).map(e=>({zone:e,rect:{x:e.offsetCorrectionX+this.gridOffsetX,y:e.offsetCorrectionY+this.gridOffsetY,...e.getMaxSize()}}))}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(C)}checkPositiveDimension(e){return e.width<0||e.height<0?`InvalidViewportSize`:`Success`}checkValuesAreDifferent(e){let{height:t,width:n}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===n&&e.height===t?`ValuesNotChanged`:`Success`}checkScrollingDirection({offsetX:e,offsetY:t}){let n=this.getMainInternalViewport(this.getters.getActiveSheetId());return!n.canScrollHorizontally&&e>0||!n.canScrollVertically&&t>0?`InvalidScrollingDirection`:`Success`}checkIfViewportsWillChange({offsetX:e,offsetY:t}){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();return this.getSubViewports(n).some(n=>n.willNewOffsetScrollViewport(x(e,0,r),x(t,0,i)))?`Success`:`ViewportScrollLimitsReached`}getMainViewport(e){let t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){let e={};for(let t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,n=0,r=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=n,this.gridOffsetY=r,this.recomputeViewports()}recomputeViewports(){for(let e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();this.getSubViewports(n).forEach(n=>n.setViewportOffset(x(e,0,r),x(t,0,i)))}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetX||0,y:this.viewports[e]?.bottomRight.offsetY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getNumberCols(e),i=this.getters.getNumberRows(e),a=Math.min(this.getters.getColRowOffset(`COL`,0,t,e),this.sheetViewWidth),o=Math.min(this.getters.getColRowOffset(`ROW`,0,n,e),this.sheetViewHeight),s=Math.max(this.sheetViewWidth-a,0),c=Math.max(this.sheetViewHeight-o,0),{xRatio:l,yRatio:u}=this.getFrozenSheetViewRatio(e),d=l<1,f=u<1,p=this.getViewportOffset(e),m={topLeft:n&&t&&new rG(this.getters,e,{left:0,right:t-1,top:0,bottom:n-1},{width:a,height:o},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:n&&new rG(this.getters,e,{left:t,right:r-1,top:0,bottom:n-1},{width:s,height:o},{canScrollHorizontally:d,canScrollVertically:!1},{x:d?p.x:0,y:0})||void 0,bottomLeft:t&&new rG(this.getters,e,{left:0,right:t-1,top:n,bottom:i-1},{width:a,height:c},{canScrollHorizontally:!1,canScrollVertically:f},{x:0,y:f?p.y:0})||void 0,bottomRight:new rG(this.getters,e,{left:t,right:r-1,top:n,bottom:i-1},{width:s,height:c},{canScrollHorizontally:d,canScrollVertically:f},{x:d?p.x:0,y:f?p.y:0})};this.viewports[e]=m}refreshViewport(e,t){this.getSubViewports(e).forEach(e=>{e.adjustViewportZone(),e.adjustPosition(t)})}shiftVertically(e){let t=this.getters.getActiveSheetId(),{top:n}=this.getMainInternalViewport(t),{scrollX:r}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(r,e);let{anchor:i}=this.getters.getSelection();if(i.cell.row>=this.getters.getPaneDivisions(t).ySplit){let e=this.getMainInternalViewport(t).top-n;this.selection.selectCell(i.cell.col,i.cell.row+e)}}getColIndexLeftOfMainViewport(e){if(e>=0)return-1;let t=this.getters.getActiveSheetId(),n=this.getActiveMainViewport().left,r=-this.getActiveSheetScrollInfo().scrollX-this.getters.getColRowOffset(`COL`,n,0);for(;e<r;n--)r-=this.getters.getColSize(t,n-1);return Math.max(n,0)}getRowIndexTopOfMainViewport(e){if(e>=0)return-1;let t=this.getters.getActiveSheetId(),n=this.getActiveMainViewport().top,r=-this.getActiveSheetScrollInfo().scrollY-this.getters.getColRowOffset(`ROW`,n,0);for(;e<r;n--)r-=this.getters.getRowSize(t,n-1);return Math.max(n,0)}getVisibleFigures(){let e=this.getters.getActiveSheetId(),t=[],n=this.getters.getFigures(e),{scrollX:r,scrollY:i}=this.getters.getActiveSheetScrollInfo(),{x:a,y:o}=this.getMainViewportCoordinates(),{width:s,height:c}=this.getters.getSheetViewDimensionWithHeaders();for(let l of n){let n=this.getFigureUI(e,l),{x:u,y:d}=n;u>=a&&(u+l.width<r+a||u>s+r+a)||d>=o&&(d+l.height<i+o||d>c+i+o)||t.push(n)}return t}getFigureUI(e,t){let n=t.offset.x+this.getters.getColDimensions(e,t.col).start,r=t.offset.y+this.getters.getRowDimensions(e,t.row).start;return{...t,x:n,y:r}}getPositionAnchorOffset(e){let{scrollX:t,scrollY:n}=this.getters.getActiveSheetScrollInfo(),r=e.x-t,i=e.y-n,a=r>=0?this.getColIndex(r):this.getColIndexLeftOfMainViewport(r),o=i>=0?this.getRowIndex(i):this.getRowIndexTopOfMainViewport(i),{x:s,y:c}=this.getRect(z({col:a,row:o}));return{col:a,row:o,offset:{x:Math.max(r-s+this.gridOffsetX,0),y:Math.max(i-c+this.gridOffsetY,0)}}}isPixelPositionVisible(e){let{scrollX:t,scrollY:n}=this.getters.getActiveSheetScrollInfo(),{x:r,y:i}=this.getters.getMainViewportCoordinates(),{width:a,height:o}=this.getters.getSheetViewDimension();return!(e.x>=r&&(e.x<r+t||e.x>a+t+r)||e.y>=i&&(e.y<i+n||e.y>o+n+i))}getFrozenSheetViewRatio(e){let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getColDimensions(e,t).start,i=this.getters.getRowDimensions(e,n).start,a=this.sheetViewWidth+this.gridOffsetX,o=this.sheetViewHeight+this.gridOffsetY;return{xRatio:r/a,yRatio:i/o}}mapViewportsToRect(e,t){let n=1/0,r=1/0,i=0,a=0,o=!1;for(let s of this.getSubViewports(e)){let e=t(s);e&&(o=!0,n=Math.min(n,e.x),r=Math.min(r,e.y),i=Math.max(i,e.x+e.width),a=Math.max(a,e.y+e.height))}return o?{x:n,y:r,width:i-n,height:a-r}:{x:0,y:0,width:0,height:0}}},aG=class extends SU{static getters=[`getColDimensions`,`getRowDimensions`,`getColRowOffset`];headerPositions={};isDirty=!0;handle(e){switch(fr.has(e.type)&&(this.headerPositions={},this.isDirty=!0),e.type){case`START`:for(let e of this.getters.getSheetIds())this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e);break;case`UPDATE_CELL`:this.headerPositions={},this.isDirty=!0;break;case`UPDATE_FILTER`:case`UPDATE_TABLE`:case`REMOVE_TABLE`:this.headerPositions={},this.isDirty=!0;break;case`REMOVE_COLUMNS_ROWS`:case`RESIZE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_ALL_HEADER_GROUPS`:case`UNGROUP_HEADERS`:case`GROUP_HEADERS`:case`CREATE_SHEET`:this.getters.tryGetSheet(e.sheetId)&&(this.headerPositions[e.sheetId]=this.computeHeaderPositionsOfSheet(e.sheetId));break;case`DUPLICATE_SHEET`:this.headerPositions[e.sheetIdTo]=b(this.headerPositions[e.sheetId]);break}}finalize(){for(let e of this.getters.getSheetIds())(this.isDirty||!this.headerPositions[e])&&(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){let n=this.headerPositions[e].COL[t],r=this.getters.getColSize(e,t);return{start:n,size:r,end:n+(this.getters.isColHidden(e,t)?0:r)}}getRowDimensions(e,t){let n=this.headerPositions[e].ROW[t],r=this.getters.getRowSize(e,t);return{start:n,size:r,end:n+(this.getters.isRowHidden(e,t)?0:r)}}getColRowOffset(e,t,n,r=this.getters.getActiveSheetId()){let i=this.headerPositions[r][e][t];return this.headerPositions[r][e][n]-i}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,`COL`),ROW:this.computePositions(e,`ROW`)}}computePositions(e,t){let n={},r=0;for(let i=0;i<this.getters.getNumberHeaders(e,t)+1;i++)n[i]=r,!this.getters.isHeaderHidden(e,t,i)&&(r+=this.getters.getHeaderSize(e,t,i));return n}};let oG=new g().add(`settings`,CH).add(`sheet`,yH).add(`header grouping`,xH).add(`header visibility`,pH).add(`tables`,bH).add(`dataValidation`,uH).add(`cell`,iH).add(`merge`,hH).add(`headerSize`,fH).add(`borders`,rH).add(`conditional formatting`,lH).add(`figures`,dH).add(`chart`,sH).add(`image`,mH).add(`pivot_core`,SH).add(`spreadsheet_pivot_core`,wH).add(`tableStyle`,TH),sG=new g().add(`ui_sheet`,hW).add(`ui_options`,mW).add(`autofill`,wU).add(`sort`,pW).add(`automatic_sum`,TU).add(`format`,lW).add(`insert_pivot`,fW).add(`pivot_presence`,YW).add(`split_to_columns`,XW).add(`collaborative`,sW).add(`history`,qW).add(`data_cleanup`,cW).add(`table_autofill`,ZW).add(`table_ui_resize`,QW).add(`datavalidation_insert`,xW).add(`checkbox_toggle`,bW).add(`geo_features`,uW),cG=new g().add(`selection`,nG).add(`evaluation_filter`,tG).add(`header_visibility_ui`,dW).add(`cell_computed_style`,yW).add(`table_computed_style`,gW).add(`header_positions`,aG).add(`viewport`,iG).add(`clipboard`,$W),lG=new g().add(`evaluation`,KH).add(`evaluation_chart`,ZH).add(`evaluation_cf`,QH).add(`row_size`,aU).add(`data_validation_ui`,eU).add(`dynamic_tables`,iU).add(`custom_colors`,XH).add(`pivot_ui`,uU).add(`cell_icon`,rU);PO.add(`dataValidation`,{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(en(t)||!this.composer.currentEditedCell)return[];let n=this.composer.currentEditedCell,r=this.getters.getValidationRuleForCell(n);if(!r||r.criterion.type!==`isValueInList`&&r.criterion.type!==`isValueInRange`)return[];let i=this.composer.currentEditedCell.sheetId,a=r.criterion.type===`isValueInRange`?this.getters.getDataValidationRangeValues(i,r.criterion):r.criterion.values.map(e=>({label:e,value:e}));if(r.criterion.displayStyle!==`chip`)return a.map(e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]}));let o=r.criterion.colors;return a.map(e=>{let t=o?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:t?Tn(t):void 0,backgroundColor:t||`#E7E9ED`,classes:[`badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start`]}],fuzzySearchKey:e.label}})},selectProposal(e,t){this.composer.setCurrentContent(t),this.composer.stopEdition()}}),PO.add(`functions`,{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if(e.type!==`SYMBOL`)return[];let t=e.value;return en(this.composer.currentContent)?Object.entries(Ix.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:n}])=>({text:e,description:n,htmlContent:PB(t,e,ge,`o-semi-bold`)})).sort((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text)):[]},selectProposal(e,t){let n=e.end,r=e.end;[`SYMBOL`,`FUNCTION`].includes(e.type)&&(n=e.start);let i=this.composer.currentTokens;t+=`(`;let a=i.map(e=>e.start).indexOf(e.start);a+1<i.length&&i[a+1]?.type===`LEFT_PAREN`&&r++,this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}}),PO.add(`pivot_ids`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||![`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`].includes(t.parent.toUpperCase())||t.argPosition!==0)return;let n=this.getters.getPivotIds();if(!n.includes(e.value))return n.map(e=>{let t=this.getters.getPivotCoreDefinition(e),n=`${this.getters.getPivotFormulaId(e)}`;return{text:n,description:t.name,htmlContent:[{value:n,color:VO.NUMBER}],fuzzySearchKey:n+t.name,alwaysExpanded:!0}}).filter(C)},selectProposal:XB}),PO.add(`pivot_measures`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(t?.parent.toUpperCase()!==`PIVOT.VALUE`||t.argPosition!==1)return[];let n=ZB(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return[];let i=this.getters.getPivot(r);return i.init(),i.isValid()?i.definition.measures.map(e=>{if(e.fieldName===`__count`){let e=`"__count"`;return{text:e,description:E(`Count`),htmlContent:[{value:e,color:VO.STRING}],fuzzySearchKey:E(`Count`)+e}}return JB(e)}).filter(C):[]},selectProposal:YB}),PO.add(`pivot_group_fields`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!uG(e)&&!dG(e))return;let n=ZB(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);i.init();let a=i.getFields(),{columns:o,rows:s}=i.definition,c=t.args;t?.parent.toUpperCase()===`PIVOT.VALUE`?(c=c.filter((e,t)=>t%2==0),c=c.slice(1,t.argPosition)):c=c.filter((e,t)=>t%2==1);let l=c.map(e=>e?.value).filter(C),u=o.map(e=>e.nameWithGranularity),d=s.map(e=>e.nameWithGranularity),f=[],p=[`ARG_SEPARATOR`,`SPACE`].includes(e.type)?l.at(-1):l.at(-2),m=QV.get(i.type);if(m&&p?.startsWith(`#`)&&(p=p.slice(1)),p===void 0&&(f.push(u[0]),f.push(d[0])),d.includes(p)){let e=d[d.indexOf(p)+1];f.push(e),f.push(u[0])}if(u.includes(p)){let e=u[u.indexOf(p)+1];f.push(e)}let h=f.filter(C);return h.map(e=>{let[t,n]=e.split(`:`),r=a[t];return r?qB(r,n):void 0}).concat(h.map(e=>{if(!m)return;let t=a[e.split(`:`)[0]];if(!t)return;let n=`"#${e}"`;return{text:n,description:E(`%s (positional)`,t.string)+(t.help?` (${t.help})`:``),htmlContent:[{value:n,color:VO.STRING}],fuzzySearchKey:t.string+n}})).filter(C)},selectProposal:YB});function uG(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==0}function dG(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==1}PO.add(`pivot_group_values`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!e||!fG(e)&&!pG(e))return;let n=ZB(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);if(!i.isValid())return;let a=t.argPosition,o=e.functionContext?.args[a-1]?.value;if(!o)return;let s;try{s=i.definition.getDimension(o)}catch{return}return s.granularity===`month_number`?Object.values(so).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:VO.NUMBER}]})):s.granularity===`quarter_number`?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:E(`Quarter %s`,e),htmlContent:[{value:`${e}`,color:VO.NUMBER}]})):s.granularity===`day_of_month`?S(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:VO.NUMBER}]})):s.granularity===`iso_week_number`?S(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:VO.NUMBER}]})):s.granularity===`day_of_week`?S(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:VO.NUMBER}]})):s.granularity===`hour_number`?S(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:VO.NUMBER}]})):s.granularity===`minute_number`?S(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:VO.NUMBER}]})):s.granularity===`second_number`?S(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:VO.NUMBER}]})):i.getPossibleFieldValues(s).map(({value:e,label:t})=>{let n=typeof e==`string`,r=n?`"${e}"`:e.toString(),i=n?VO.STRING:VO.NUMBER,a=t===e?``:t;return{text:r,description:a,htmlContent:[{value:r,color:i}],fuzzySearchKey:r+a}})},selectProposal:YB});function fG(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==1}function pG(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==0}PO.add(`sheet_names`,{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return e.type===`SYMBOL`||e.type===`UNKNOWN`&&e.value.startsWith(`'`)?this.getters.getSheetIds().map(e=>{let t=ut(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith(`'`)?t:`'`+t}}):[]},selectProposal(e,t){let n=e.start,r=e.end;this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t+`!`)}});let mG=new g;mG.add(`link`,{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,n)=>Vr(t.model.getters.getEvaluatedCell(e).link,t,n),title:(e,t)=>{let n=t.getEvaluatedCell(e).link;return n?n.isExternal?E(`Go to url: %(url)s`,{url:n.url}):E(`Go to %(label)s`,{label:n.label}):``},sequence:5});let hG=new g().add(`ADD_COLUMNS_ROWS`,vG).add(`REMOVE_COLUMNS_ROWS`,CG).add(`ADD_MERGE`,yG).add(`REMOVE_MERGE`,bG).add(`CREATE_SHEET`,xG).add(`DELETE_SHEET`,wG).add(`DUPLICATE_SHEET`,SG).add(`CREATE_FIGURE`,TG).add(`CREATE_CHART`,EG).add(`HIDE_COLUMNS_ROWS`,DG).add(`UNHIDE_COLUMNS_ROWS`,OG).add(`CREATE_TABLE_STYLE`,kG).add(`ADD_PIVOT`,_G).add(`RENAME_SHEET`,AG);for(let e of vr.values())hG.contains(e)||hG.add(e,gG);function gG(e){return[e]}function _G(e){return[{type:`REMOVE_PIVOT`,pivotId:e.pivotId}]}function vG(e){let t=[],n=e.base;e.position===`after`&&n++;for(let r=0;r<e.quantity;r++)t.push(r+n);return[{type:`REMOVE_COLUMNS_ROWS`,dimension:e.dimension,elements:t,sheetId:e.sheetId,sheetName:e.sheetName}]}function yG(e){return[{type:`REMOVE_MERGE`,sheetId:e.sheetId,target:e.target}]}function bG(e){return[{type:`ADD_MERGE`,sheetId:e.sheetId,target:e.target}]}function xG(e){return[{type:`DELETE_SHEET`,sheetId:e.sheetId,sheetName:e.name}]}function SG(e){return[{type:`DELETE_SHEET`,sheetId:e.sheetIdTo,sheetName:``}]}function CG(e){let t=[],n=[...e.elements].sort((e,t)=>e-t);for(let r of ft(n)){let n=r[0]===0?0:r[0]-1,i=r[0]===0?`before`:`after`;t.push({type:`ADD_COLUMNS_ROWS`,dimension:e.dimension,quantity:r.length,base:n,sheetId:e.sheetId,sheetName:e.sheetName,position:i})}return t}function wG(e){return[{type:`CREATE_SHEET`,sheetId:e.sheetId,position:1,name:e.sheetName}]}function TG(e){return[{type:`DELETE_FIGURE`,figureId:e.figureId,sheetId:e.sheetId}]}function EG(e){return[{type:`DELETE_FIGURE`,figureId:e.figureId,sheetId:e.sheetId}]}function DG(e){return[{type:`UNHIDE_COLUMNS_ROWS`,sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}function OG(e){return[{type:`HIDE_COLUMNS_ROWS`,sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}function kG(e){return[{type:`REMOVE_TABLE_STYLE`,tableStyleId:e.tableStyleId}]}function AG(e){return[{type:`RENAME_SHEET`,sheetId:e.sheetId,oldName:e.newName,newName:e.oldName}]}let jG=new g;jG.add(`format_number_automatic`,{...aL,id:`format_number_automatic`,sequence:10}).add(`format_number_plain_text`,{...oL,id:`format_number_plain_text`,sequence:15,separator:!0}).add(`format_number_number`,{...sL,id:`format_number_number`,sequence:20}).add(`format_number_percent`,{...lL,id:`format_number_percent`,sequence:30,separator:!0}).add(`format_number_currency`,{...uL,id:`format_number_currency`,sequence:40}).add(`format_number_accounting`,{...fL,id:`format_number_accounting`,sequence:45}).add(`format_number_currency_rounded`,{...dL,id:`format_number_currency_rounded`,sequence:50}).add(`format_custom_currency`,{...mL,id:`format_custom_currency`,sequence:60,separator:!0}).add(`format_number_date`,{...hL,id:`format_number_date`,sequence:70}).add(`format_number_time`,{...gL,id:`format_number_time`,sequence:80}).add(`format_number_date_time`,{..._L,id:`format_number_date_time`,sequence:90}).add(`format_number_duration`,{...vL,id:`format_number_duration`,sequence:100,separator:!0}).add(`more_formats`,{...xL,id:`more_formats`,sequence:120});function MG(e){let t=new Set(jG.getAll().map(t=>typeof t.format==`function`?t.format(e):t.format)),n=new Map;for(let r of e.model.getters.getSheetIds()){let i=e.model.getters.getEvaluatedCells(r);for(let e in i){let r=i[e];if(r.format&&!n.has(r.format)&&!t.has(r.format)){let e=NG(r.format);(e===`date`||e===`currency`)&&n.set(r.format,iL({descriptionValue:e===`currency`?1e3:pL,format:r.format,name:r.format}))}}}return[...n.values()]}let NG=Vt(e=>So(e)?`date`:e.includes(`[$`)?`currency`:`number`),PG={name:E(`More formats`),icon:`o-spreadsheet-Icon.NUMBER_FORMATS`,children:[e=>{let t=MG(e).map(e=>({...e,sequence:110}));return t.length>0&&(t[t.length-1].separator=!0),f([...jG.getAll(),...t])}]};function FG(e){let t=new Pk;return t.add(`delete`,{...Dk,sequence:10}).add(`hide_sheet`,{...Nk,sequence:20}).add(`duplicate`,{...Ok,sequence:30,separator:!0}).add(`rename`,{...kk(e),sequence:40}).add(`change_color`,{...Ak(e),sequence:50,separator:!0}).add(`move_right`,{...jk,sequence:60}).add(`move_left`,{...Mk,sequence:70}),t}let IG=new Pk;IG.add(`file`,{name:E(`File`),sequence:10,isReadonlyAllowed:!0}).addChild(`settings`,[`file`],{name:E(`Settings`),sequence:200,execute:e=>e.openSidePanel(`Settings`),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.COG`}).add(`edit`,{name:E(`Edit`),sequence:20,isReadonlyAllowed:!0}).addChild(`undo`,[`edit`],{...fF,sequence:10}).addChild(`redo`,[`edit`],{...pF,sequence:20,separator:!0}).addChild(`copy`,[`edit`],{...mF,sequence:30}).addChild(`cut`,[`edit`],{...hF,sequence:40}).addChild(`paste`,[`edit`],{...gF,sequence:50}).addChild(`paste_special`,[`edit`],{..._F,sequence:60,separator:!0}).addChild(`paste_special_value`,[`edit`,`paste_special`],{...vF,sequence:10}).addChild(`paste_special_format`,[`edit`,`paste_special`],{...yF,sequence:20}).addChild(`edit_table`,[`edit`],{...MF,isVisible:fP,sequence:60}).addChild(`find_and_replace`,[`edit`],{...bF,sequence:65,separator:!0}).addChild(`delete`,[`edit`],{name:E(`Delete`),icon:`o-spreadsheet-Icon.TRASH`,sequence:70}).addChild(`edit_delete_cell_values`,[`edit`,`delete`],{...xF,sequence:10}).addChild(`edit_delete_row`,[`edit`,`delete`],{...SF,sequence:20}).addChild(`edit_delete_column`,[`edit`,`delete`],{...TF,sequence:30}).addChild(`edit_delete_cell_shift_up`,[`edit`,`delete`],{...kF,sequence:40}).addChild(`edit_delete_cell_shift_left`,[`edit`,`delete`],{...AF,sequence:50}).addChild(`edit_unhide_columns`,[`edit`],{...OP,sequence:80}).addChild(`edit_unhide_rows`,[`edit`],{...jP,sequence:80}).add(`view`,{name:E(`View`),sequence:30,isReadonlyAllowed:!0}).addChild(`unfreeze_panes`,[`view`],{...MP,sequence:4}).addChild(`freeze_panes`,[`view`],{...NP,sequence:5}).addChild(`unfreeze_rows`,[`view`,`freeze_panes`],{...PP,sequence:5}).addChild(`freeze_first_row`,[`view`,`freeze_panes`],{...FP,sequence:10}).addChild(`freeze_second_row`,[`view`,`freeze_panes`],{...IP,sequence:15}).addChild(`freeze_current_row`,[`view`,`freeze_panes`],{...LP,sequence:20,separator:!0}).addChild(`unfreeze_columns`,[`view`,`freeze_panes`],{...RP,sequence:25}).addChild(`freeze_first_col`,[`view`,`freeze_panes`],{...zP,sequence:30}).addChild(`freeze_second_col`,[`view`,`freeze_panes`],{...BP,sequence:35}).addChild(`freeze_current_col`,[`view`,`freeze_panes`],{...VP,sequence:40}).addChild(`group_headers`,[`view`],{name:E(`Group`),sequence:15,separator:!0,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,isVisible:vP}).addChild(`group_columns`,[`view`,`group_headers`],{...GP,sequence:5}).addChild(`ungroup_columns`,[`view`,`group_headers`],{...qP,isVisible:e=>ZP(e,`COL`),sequence:10}).addChild(`group_rows`,[`view`,`group_headers`],{...KP,sequence:15}).addChild(`ungroup_rows`,[`view`,`group_headers`],{...JP,isVisible:e=>ZP(e,`ROW`),sequence:20}).addChild(`show`,[`view`],{name:E(`Show`),sequence:1,icon:`o-spreadsheet-Icon.SHOW`}).addChild(`view_gridlines`,[`view`,`show`],{...HP,sequence:5}).addChild(`view_formulas`,[`view`,`show`],{...WP,sequence:10}).addChild(`view_irregularity_map`,[`view`],{...UP,sequence:40,separator:!0}).add(`insert`,{name:E(`Insert`),sequence:40,isReadonlyAllowed:!0}).addChild(`insert_row`,[`insert`],{...LF,sequence:10}).addChild(`insert_row_before`,[`insert`,`insert_row`],{...zF,sequence:10}).addChild(`insert_row_after`,[`insert`,`insert_row`],{...HF,sequence:20}).addChild(`insert_column`,[`insert`],{...UF,sequence:20}).addChild(`insert_column_before`,[`insert`,`insert_column`],{...GF,sequence:10}).addChild(`insert_column_after`,[`insert`,`insert_column`],{...JF,sequence:20}).addChild(`insert_cell`,[`insert`],{...YF,sequence:30}).addChild(`insert_cell_down`,[`insert`,`insert_cell`],{...XF,name:E(`Shift down`),sequence:10}).addChild(`insert_cell_right`,[`insert`,`insert_cell`],{...ZF,name:E(`Shift right`),sequence:20}).addChild(`insert_sheet`,[`insert`],{...mI,sequence:40,separator:!0}).addChild(`insert_chart`,[`insert`],{...QF,sequence:50}).addChild(`insert_pivot`,[`insert`],{...$F,sequence:52}).addChild(`insert_image`,[`insert`],{...eI,sequence:55}).addChild(`insert_table`,[`insert`],{...tI,sequence:57}).addChild(`insert_function`,[`insert`],{...nI,sequence:60}).addChild(`insert_function_sum`,[`insert`,`insert_function`],{...rI,sequence:0}).addChild(`insert_function_average`,[`insert`,`insert_function`],{...iI,sequence:10}).addChild(`insert_function_count`,[`insert`,`insert_function`],{...aI,sequence:20}).addChild(`insert_function_max`,[`insert`,`insert_function`],{...oI,sequence:30}).addChild(`insert_function_min`,[`insert`,`insert_function`],{...sI,sequence:40,separator:!0}).addChild(`categorie_function_all`,[`insert`,`insert_function`],{...cI,sequence:50}).addChild(`categories_function_list`,[`insert`,`insert_function`],uI).addChild(`insert_link`,[`insert`],{...dI,separator:!0,sequence:70}).addChild(`insert_checkbox`,[`insert`],{...fI,sequence:80}).addChild(`insert_dropdown`,[`insert`],{...pI,separator:!0,sequence:90}).add(`format`,{name:E(`Format`),sequence:50,isReadonlyAllowed:!0}).addChild(`format_number`,[`format`],{...PG,name:E(`Number`),sequence:10,separator:!0}).addChild(`format_bold`,[`format`],{...NL,sequence:20}).addChild(`format_italic`,[`format`],{...PL,sequence:30}).addChild(`format_underline`,[`format`],{...FL,sequence:40}).addChild(`format_strikethrough`,[`format`],{...IL,sequence:50,separator:!0}).addChild(`format_font_size`,[`format`],{...LL,sequence:60,separator:!0}).addChild(`format_alignment`,[`format`],{...RL,sequence:70}).addChild(`format_alignment_left`,[`format`,`format_alignment`],{...BL,sequence:10}).addChild(`format_alignment_center`,[`format`,`format_alignment`],{...VL,sequence:20}).addChild(`format_alignment_right`,[`format`,`format_alignment`],{...HL,sequence:30,separator:!0}).addChild(`format_alignment_top`,[`format`,`format_alignment`],{...WL,sequence:40}).addChild(`format_alignment_middle`,[`format`,`format_alignment`],{...GL,sequence:50}).addChild(`format_alignment_bottom`,[`format`,`format_alignment`],{...KL,sequence:60,separator:!0}).addChild(`format_wrapping`,[`format`],{...qL,sequence:80,separator:!0}).addChild(`format_wrapping_overflow`,[`format`,`format_wrapping`],{...YL,sequence:10}).addChild(`format_wrapping_wrap`,[`format`,`format_wrapping`],{...XL,sequence:20}).addChild(`format_wrapping_clip`,[`format`,`format_wrapping`],{...ZL,sequence:30}).addChild(`format_cf`,[`format`],{...QL,sequence:90,separator:!0}).addChild(`format_clearFormat`,[`format`],{...$L,sequence:100,separator:!0}).add(`data`,{name:E(`Data`),sequence:60,isReadonlyAllowed:!0}).addChild(`sort_range`,[`data`],{...qI,sequence:10,separator:!0}).addChild(`sort_ascending`,[`data`,`sort_range`],{...JI,sequence:10}).addChild(`sort_descending`,[`data`,`sort_range`],{...QI,sequence:20}).addChild(`data_cleanup`,[`data`],{...YI,sequence:15}).addChild(`remove_duplicates`,[`data`,`data_cleanup`],{...XI,sequence:10}).addChild(`trim_whitespace`,[`data`,`data_cleanup`],{...ZI,sequence:20}).addChild(`split_to_columns`,[`data`],{...tL,sequence:20}).addChild(`data_validation`,[`data`],{name:E(`Data Validation`),execute:e=>{e.openSidePanel(`DataValidation`)},isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.DATA_VALIDATION`,sequence:30,separator:!0}).addChild(`add_remove_data_filter`,[`data`],{...$I,sequence:40,separator:!0}).addChild(`pivot_data_sources`,[`data`],e=>{let t=e.model.getters.getPivotIds().length;return e.model.getters.getPivotIds().map((n,r)=>{let i={get highlights(){return AB(e.model.getters,n)}};return{id:`item_pivot_${e.model.getters.getPivotFormulaId(n)}`,name:e.model.getters.getPivotDisplayName(n),sequence:50+r/t,isReadonlyAllowed:!0,execute:e=>e.openSidePanel(`PivotSidePanel`,{pivotId:n}),isEnabled:e=>!e.isSmall,onStartHover:e=>e.getStore(IO).register(i),onStopHover:e=>e.getStore(IO).unRegister(i),icon:`o-spreadsheet-Icon.PIVOT`,separator:r===e.model.getters.getPivotIds().length-1,secondaryIcon:e=>e.model.getters.isPivotUnused(n)?`o-spreadsheet-Icon.UNUSED_PIVOT_WARNING`:void 0}})}).addChild(`reinsert_dynamic_pivot`,[`data`],nL).addChild(`reinsert_static_pivot`,[`data`],rL);let LG=new class extends g{mapping={};uuidGenerator=new gl;replace(e,t){let n={...t,id:this.uuidGenerator.uuidv4()};return super.replace(e,n)}getAllOrdered(){return this.getAll().sort((e,t)=>e.sequence-t.sequence)}};var RG=class{listeners=[];async sendMessage(e){for(let{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter(t=>t.id!==e)}},zG=class{fileStore;constructor(e){this.fileStore=e}async requestImage(){let e=await this.userImageUpload(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}async uploadFile(e){let t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}userImageUpload(){return new Promise((e,t)=>{let n=document.createElement(`input`);n.setAttribute(`type`,`file`),n.setAttribute(`accept`,`image/*`),n.addEventListener(`change`,async()=>{n.files===null||n.files.length!==1?t():e(n.files[0])}),n.click()})}getImageOriginalSize(e){return new Promise((t,n)=>{let r=new Image;r.addEventListener(`load`,()=>{t({width:r.width,height:r.height})}),r.addEventListener(`error`,n),r.src=e})}};let BG=[{transform:`scale(0)`},{transform:`scale(0.8)`,offset:.33},{opacity:`0`,transform:`scale(1)`,offset:1}];V`
|
|
1954
1954
|
.o-ripple {
|
|
1955
1955
|
z-index: 1;
|
|
1956
1956
|
}
|
|
@@ -2420,7 +2420,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
2420
2420
|
cursor: not-allowed;
|
|
2421
2421
|
}
|
|
2422
2422
|
}
|
|
2423
|
-
`;var bK=class extends t.Component{static template=`o-spreadsheet-TopBar`;static props={onClick:Function,dropdownMaxHeight:Number};static components={MenuPopover:rO,TopBarComposer:oK,Popover:$D};toolsCategories=yK.getCategories();state=(0,t.useState)({menuState:{isOpen:!1,anchorRect:null,menuItems:[]},invisibleToolsCategories:[],toolsPopoverState:{isOpen:!1}});isSelectingMenu=!1;openedEl=null;menus=[];toolbarMenuRegistry=yK;formatNumberMenuItemSpec=PG;isntToolbarMenu=!1;composerFocusStore;fingerprints;topBarToolStore;toolBarContainerRef=(0,t.useRef)(`toolBarContainer`);toolbarRef=(0,t.useRef)(`toolBar`);moreToolsContainerRef=(0,t.useRef)(`moreToolsContainer`);moreToolsButtonRef=(0,t.useRef)(`moreToolsButton`);spreadsheetRect=ZD();setup(){this.composerFocusStore=B(Qd),this.fingerprints=B(CP),this.topBarToolStore=B(sK),(0,t.useExternalListener)(window,`click`,this.onExternalClick),(0,t.onWillStart)(()=>this.updateCellState()),(0,t.onWillUpdateProps)(()=>this.updateCellState()),(0,t.useEffect)(()=>{this.state.toolsPopoverState.isOpen=!1,this.setVisibilityToolsGroups()},()=>[this.spreadsheetRect.width])}setVisibilityToolsGroups(){if(this.env.model.getters.isReadonly())return;let e=[],{x:t}=this.toolbarRef.el.getBoundingClientRect(),{x:n}=this.toolBarContainerRef.el.getBoundingClientRect();this.moreToolsContainerRef.el?.classList.remove(`d-none`);let r=this.moreToolsButtonRef.el?.getBoundingClientRect().width||0,i=Math.round(this.spreadsheetRect.width)-r-(t-n)-16,a=document.querySelectorAll(`.tool-container`),o=0;for(let t=0;t<a.length;t++){let n=a[t];n.classList.remove(`d-none`);let{width:r}=n.getBoundingClientRect();o+=r,o>i&&(n.classList.add(`d-none`),e.push(this.toolsCategories[t]))}this.state.invisibleToolsCategories=e,e.length||this.moreToolsContainerRef.el?.classList.add(`d-none`)}get topbarComponents(){return LG.getAllOrdered().filter(e=>!e.isVisible||e.isVisible(this.env))}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||Ve}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onClick(){this.props.onClick(),this.closeMenus()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.isntToolbarMenu&&this.openMenu(e,t)}toggleContextMenu(e,t){this.state.menuState.isOpen&&this.isntToolbarMenu?this.closeMenus():(this.openMenu(e,t),this.isntToolbarMenu=!0)}openMenu(e,t){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!0,this.state.menuState.anchorRect=WC(t.currentTarget),this.state.menuState.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.menuState.parentMenu=e,this.isSelectingMenu=!0,this.openedEl=t.target,this.composerFocusStore.activeComposer.stopEdition()}closeMenus(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){this.menus=IG.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){NN(this.env,{[e]:t}),this.onClick()}setFontSize(e){NN(this.env,{fontSize:e})}toggleMoreTools(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!this.state.toolsPopoverState.isOpen}get toolsPopoverProps(){return{anchorRect:this.moreToolsButtonRef.el?WC(this.moreToolsButtonRef.el):{x:0,y:0,width:0,height:0},positioning:`bottom-left`,verticalOffset:0,class:`rounded`,maxWidth:300}}showDivider(e){return e<this.toolsCategories.length-1||this.state.invisibleToolsCategories.length>0}};function xK(){return new SK(navigator.clipboard)}var SK=class{constructor(e){this.clipboard=e}async write(e){if(this.clipboard?.write)try{await this.clipboard?.write(this.getClipboardItems(e))}catch(t){console.log(`Failed to write on the clipboard, falling back to plain/html text. Error %s`,t);try{await this.clipboard?.write([new ClipboardItem({"text/plain":this.getBlob(e,`text/plain`),"text/html":this.getBlob(e,`text/html`)})])}catch{}}else await this.writeText(e[`text/plain`]??``)}async writeText(e){try{this.clipboard?.writeText(e)}catch{}}async read(){let e;try{e=await navigator.permissions.query({name:`clipboard-read`})}catch{}if(this.clipboard?.read)try{let e=await this.clipboard.read(),t={};for(let n of e)for(let e of n.types){let r=await n.getType(e);_l.includes(e)?t[e]=r:t[e]=await r.text()}return{status:`ok`,content:t}}catch{return{status:e?.state===`denied`?`permissionDenied`:`notImplemented`}}else return{status:`ok`,content:{"text/plain":await this.clipboard?.readText()}}}getClipboardItems(e){let t={};for(let n of Object.keys(e))t[n]=this.getBlob(e,n);return[new ClipboardItem(t)]}getBlob(e,t){let n=e[t];return n instanceof Blob||n instanceof File?n:new Blob([e[t]||``],{type:t})}};V`
|
|
2423
|
+
`;var bK=class extends t.Component{static template=`o-spreadsheet-TopBar`;static props={onClick:Function,dropdownMaxHeight:Number};static components={MenuPopover:rO,TopBarComposer:oK,Popover:$D};toolsCategories=yK.getCategories();state=(0,t.useState)({menuState:{isOpen:!1,anchorRect:null,menuItems:[]},invisibleToolsCategories:[],toolsPopoverState:{isOpen:!1}});isSelectingMenu=!1;openedEl=null;menus=[];toolbarMenuRegistry=yK;formatNumberMenuItemSpec=PG;isntToolbarMenu=!1;composerFocusStore;fingerprints;topBarToolStore;toolBarContainerRef=(0,t.useRef)(`toolBarContainer`);toolbarRef=(0,t.useRef)(`toolBar`);moreToolsContainerRef=(0,t.useRef)(`moreToolsContainer`);moreToolsButtonRef=(0,t.useRef)(`moreToolsButton`);spreadsheetRect=ZD();setup(){this.composerFocusStore=B(Qd),this.fingerprints=B(CP),this.topBarToolStore=B(sK),(0,t.useExternalListener)(window,`click`,this.onExternalClick),(0,t.onWillStart)(()=>this.updateCellState()),(0,t.onWillUpdateProps)(()=>this.updateCellState()),(0,t.useEffect)(()=>{this.state.toolsPopoverState.isOpen=!1,this.setVisibilityToolsGroups()},()=>[this.spreadsheetRect.width])}setVisibilityToolsGroups(){if(this.env.model.getters.isReadonly())return;let e=[],{x:t}=this.toolbarRef.el.getBoundingClientRect(),{x:n}=this.toolBarContainerRef.el.getBoundingClientRect();this.moreToolsContainerRef.el?.classList.remove(`d-none`);let r=this.moreToolsButtonRef.el?.getBoundingClientRect().width||0,i=Math.round(this.spreadsheetRect.width)-r-(t-n)-16,a=document.querySelectorAll(`.tool-container`),o=0;for(let t=0;t<a.length;t++){let n=a[t];n.classList.remove(`d-none`);let{width:r}=n.getBoundingClientRect();o+=r,o>i&&(n.classList.add(`d-none`),e.push(this.toolsCategories[t]))}this.state.invisibleToolsCategories=e,e.length||this.moreToolsContainerRef.el?.classList.add(`d-none`)}get topbarComponents(){return LG.getAllOrdered().filter(e=>!e.isVisible||e.isVisible(this.env))}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||Ve}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onClick(){this.props.onClick(),this.closeMenus()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.isntToolbarMenu&&this.openMenu(e,t)}toggleContextMenu(e,t){this.state.menuState.isOpen&&this.isntToolbarMenu?this.closeMenus():(this.openMenu(e,t),this.isntToolbarMenu=!0)}openMenu(e,t){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!0,this.state.menuState.anchorRect=WC(t.currentTarget),this.state.menuState.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.menuState.parentMenu=e,this.isSelectingMenu=!0,this.openedEl=t.target,this.composerFocusStore.activeComposer.stopEdition()}closeMenus(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){this.menus=IG.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){NN(this.env,{[e]:t}),this.onClick()}setFontSize(e){NN(this.env,{fontSize:e})}toggleMoreTools(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!this.state.toolsPopoverState.isOpen}get toolsPopoverProps(){return{anchorRect:this.moreToolsButtonRef.el?WC(this.moreToolsButtonRef.el):{x:0,y:0,width:0,height:0},positioning:`bottom-left`,verticalOffset:0,class:`rounded`,maxWidth:300}}showDivider(e){return e<this.toolsCategories.length-1||this.state.invisibleToolsCategories.length>0}};function xK(){return new SK(navigator.clipboard)}var SK=class{clipboard;constructor(e){this.clipboard=e}async write(e){if(this.clipboard?.write)try{await this.clipboard?.write(this.getClipboardItems(e))}catch(t){console.log(`Failed to write on the clipboard, falling back to plain/html text. Error %s`,t);try{await this.clipboard?.write([new ClipboardItem({"text/plain":this.getBlob(e,`text/plain`),"text/html":this.getBlob(e,`text/html`)})])}catch{}}else await this.writeText(e[`text/plain`]??``)}async writeText(e){try{this.clipboard?.writeText(e)}catch{}}async read(){let e;try{e=await navigator.permissions.query({name:`clipboard-read`})}catch{}if(this.clipboard?.read)try{let e=await this.clipboard.read(),t={};for(let n of e)for(let e of n.types){let r=await n.getType(e);_l.includes(e)?t[e]=r:t[e]=await r.text()}return{status:`ok`,content:t}}catch{return{status:e?.state===`denied`?`permissionDenied`:`notImplemented`}}else return{status:`ok`,content:{"text/plain":await this.clipboard?.readText()}}}getClipboardItems(e){let t={};for(let n of Object.keys(e))t[n]=this.getBlob(e,n);return[new ClipboardItem(t)]}getBlob(e,t){let n=e[t];return n instanceof Blob||n instanceof File?n:new Blob([e[t]||``],{type:t})}};V`
|
|
2424
2424
|
.o-spreadsheet {
|
|
2425
2425
|
position: relative;
|
|
2426
2426
|
display: grid;
|
|
@@ -2652,7 +2652,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
2652
2652
|
.o-spreadsheet-bottombar-wrapper {
|
|
2653
2653
|
z-index: ${16};
|
|
2654
2654
|
}
|
|
2655
|
-
`;var CK=class extends t.Component{static template=`o-spreadsheet-Spreadsheet`;static props={model:Object,notifyUser:{type:Function,optional:!0},raiseError:{type:Function,optional:!0},askConfirmation:{type:Function,optional:!0}};static components={TopBar:bK,Grid:ZV,BottomBar:JG,SmallBottomBar:aK,SidePanels:rK,SpreadsheetDashboard:XG,HeaderGroupContainer:eK,FullScreenChart:$V};sidePanel;spreadsheetRef=(0,t.useRef)(`spreadsheet`);spreadsheetRect=ZD();_focusGrid;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){let e={};return this.env.isDashboard()?e[`grid-template-rows`]=`auto`:e[`grid-template-rows`]=`min-content auto min-content`,e[`grid-template-columns`]=`auto ${this.sidePanel.mainPanel?`${this.sidePanel.totalPanelSize||350}px`:`auto`}`,H(e)}setup(){if(!(`isSmall`in this.env)){let e=tK();(0,t.useSubEnv)({get isSmall(){return e.isSmall}})}let e=Ud();e.inject(Jd,this.model);let n=this.env;e.get(KV).setSmallThreshhold(()=>n.isSmall),this.notificationStore=B(LO),this.composerFocusStore=B(Qd),this.sidePanel=B(qV);let r=this.model.config.external.fileStore;(0,t.useSubEnv)({model:this.model,imageProvider:r?new zG(r):void 0,loadCurrencies:this.model.config.external.loadCurrencies,loadLocales:this.model.config.external.loadLocales,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.sidePanel.open.bind(this.sidePanel),replaceSidePanel:this.sidePanel.replace.bind(this.sidePanel),toggleSidePanel:this.sidePanel.toggle.bind(this.sidePanel),clipboard:this.env.clipboard||xK(),startCellEdition:e=>this.composerFocusStore.focusActiveComposer({content:e}),notifyUser:e=>this.notificationStore.notifyUser(e),askConfirmation:(e,t,n)=>this.notificationStore.askConfirmation(e,t,n),raiseError:(e,t)=>this.notificationStore.raiseError(e,t),isMobile:cw}),this.notificationStore.updateNotificationCallbacks({...this.props}),(0,t.useEffect)(()=>{!this.spreadsheetRef.el.contains(document.activeElement)&&document.activeElement?.contains(this.spreadsheetRef.el)&&this.focusGrid()}),(0,t.useExternalListener)(window,`resize`,()=>this.render(!0)),(0,t.useExternalListener)(document.body,`wheel`,()=>{}),this.bindModelEvents(),(0,t.onWillUpdateProps)(e=>{if(e.model!==this.props.model)throw Error(`Changing the props model is not supported at the moment.`);(e.notifyUser!==this.props.notifyUser||e.askConfirmation!==this.props.askConfirmation||e.raiseError!==this.props.raiseError)&&this.notificationStore.updateNotificationCallbacks({...e})});let i=Dt(this.render.bind(this,!0));(0,t.onMounted)(()=>{this.checkViewportSize(),e.on(`store-updated`,this,i),a.observe(this.spreadsheetRef.el)}),(0,t.onWillUnmount)(()=>{this.unbindModelEvents(),e.off(`store-updated`,this),a.disconnect(),ff()}),(0,t.onPatched)(()=>{this.checkViewportSize()});let a=new ResizeObserver(()=>{this.sidePanel.changeSpreadsheetWidth(this.spreadsheetRect.width)})}bindModelEvents(){this.model.on(`update`,this,()=>this.render(!0)),this.model.on(`notify-ui`,this,e=>this.notificationStore.notifyUser(e)),this.model.on(`raise-error-ui`,this,({text:e})=>this.notificationStore.raiseError(e))}unbindModelEvents(){this.model.off(`update`,this),this.model.off(`notify-ui`,this),this.model.off(`raise-error-ui`,this)}checkViewportSize(){let{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(!(!isFinite(e)||!isFinite(t)))if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.notificationStore.notifyUser({text:E(`The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns.`),type:`warning`,sticky:!1}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}focusGrid(){this._focusGrid&&this._focusGrid()}get gridHeight(){return this.env.model.getters.getSheetViewDimension().height}get gridContainerStyle(){let e=21*this.rowLayers.length,t=21*this.colLayers.length;return H({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`})}get rowLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`ROW`)}get colLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`COL`)}getGridSize(){let e=this.spreadsheetRef.el;if(!e)return{width:0,height:0};let t=t=>e.querySelector(t)?.getBoundingClientRect().height||0,n=t=>e.querySelector(t)?.getBoundingClientRect().width||0,r=e.getBoundingClientRect(),i=t(`.o-spreadsheet-topbar-wrapper`),a=t(`.o-spreadsheet-bottombar-wrapper`),o=t(`.o-column-groups`),s=n(`.o-grid`);return{width:Math.max(s-15,0),height:Math.max(r.height-i-a-o-15,0)}}};function wK(e){return hG.get(e.type)(e)}var TK=class e{constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){let t=this.operations.find(t=>t.id===e);if(!t)throw Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(let n of this.operations){if(n.id===e)return e;if(n.id===t)return t}throw Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find(t=>t.id===e)}prepend(e){let t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map(e=>e.transformed(t))]}insert(e,t){let n=this.buildTransformation.with(e.data),{before:r,operation:i,after:a}=this.locateOperation(t);this.operations=[...r,i,e,...a.map(e=>e.transformed(n))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(t){let{after:n}=this.locateOperation(t);return new e(this.buildTransformation,n)}transform(e){this.operations=this.operations.map(t=>t.transformed(e))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){let{before:t,operation:n}=this.locateOperation(e);this.operations=t.concat([n])}locateOperation(e){let t=this.operations.findIndex(t=>t.id===e);if(t===-1)throw Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}},EK=class{constructor(e,t){this.id=e,this.data=t}transformed(e){return new DK(this.id,kt(()=>e(this.data)))}},DK=class e{constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(t){return new e(this.id,this.lazyData.map(t))}},OK=class e{constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(t){function*n(e,t){for(let n of e)if(yield n,n.operation.id===t)return}return new e(n(this.operations,t))}stopBefore(t){function*n(e,t){for(let n of e){if(n.operation.id===t)return;yield n}}return new e(n(this.operations,t))}startAfter(t){function*n(e,t){let n=!0;for(let r of e)n||(yield r),r.operation.id===t&&(n=!1)}return new e(n(this.operations,t))}},kK=class{branches;branchingOperationIds=new Map;constructor(e,t){this.buildTransformation=e,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new OK(pt(this._execution(e),this._execution(e)))}revertedExecution(e){return new OK(pt(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){let n=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),n&&this.insertPrevious(e,t,n)}insertOperationAfter(e,t,n){e.insert(t,n),this.updateNextWith(e,t,n),this.insertPrevious(e,t,n)}undo(e,t){let n=this.buildTransformation.without(t.data),r=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);let i=e.fork(t.id);r&&this.branchingOperationIds.set(i,r),this.insertBranchAfter(e,i),this.transform(i,n)}redo(e){let t=this.nextBranch(e);if(!t)return;let n=this.nextBranch(t);this.removeBranchFromTree(t);let r=this.branchingOperationIds.get(t);r?this.branchingOperationIds.set(e,r):this.branchingOperationIds.delete(e),n&&this.rebaseUp(n)}drop(e){for(let t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(let n of this.revertedExecution(e))if(n.operation.id===t)return n;throw Error(`Operation ${t} not found`)}rebaseUp(e){let{previousBranch:t,branchingOperation:n}=this.findPreviousBranchingOperation(e);if(!t||!n)return;let r=this.buildTransformation.without(n.data),i=t.fork(n.id);this.branchingOperationIds.set(i,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,i),i.transform(r);let a=this.nextBranch(i);a&&this.rebaseUp(a)}removeBranchFromTree(e){let t=this.branches.findIndex(t=>t===e);this.branches.splice(t,1)}insertBranchAfter(e,t){let n=this.branches.findIndex(t=>t===e);this.branches.splice(n+1,0,t)}updateNextWith(e,t,n){let r=this.branchingOperationIds.get(e),i=this.nextBranch(e);if(!(!r||!i))if(e.getFirstOperationAmong(n,r)===r){let a=this.addToNextBranch(e,i,r,t,n);this.updateNextWith(i,a,n)}else{let e=this.buildTransformation.with(t.data);this.transform(i,e)}}addToNextBranch(e,t,n,r,i){let a=r;return i===n?(a=this.getTransformedOperation(e,n,r),t.prepend(a)):t.contains(i)?(a=this.getTransformedOperation(e,n,r),t.insert(a,i)):t.append(r),a}getTransformedOperation(e,t,n){let r=e.getOperation(t),i=this.buildTransformation.without(r.data);return n.transformed(i)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);let n=this.nextBranch(e);n&&this.transform(n,t)}insertPrevious(e,t,n){let{previousBranch:r,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!r||!i)return;let a=this.buildTransformation.with(i.data),o=e.fork(n);o.transform(a),r.cutAfter(n),r.appendBranch(o);let s=t.transformed(a);this.insertPrevious(r,s,n)}findPreviousBranchingOperation(e){let t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};let n=this.branchingOperationIds.get(t);return n?{previousBranch:t,branchingOperation:t.getOperation(n)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){let t=this.branches.findIndex(t=>t===e);if(t!==-1)return this.branches[t+1]}previousBranch(e){let t=this.branches.findIndex(t=>t===e);if(t!==-1)return this.branches[t-1]}*_revertedExecution(e){let t=this.branchingOperationIds.get(e),n=!!t,r=e.getOperations();for(let i=r.length-1;i>=0;i--){let a=r[i];a.id===t&&(n=!1),n||(yield{operation:a,branch:e,isCancelled:!this.shouldExecute(e,a)})}let i=this.previousBranch(e);yield*i?this._revertedExecution(i):[]}*_execution(e){for(let t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){let t=this.nextBranch(e);yield*t?this._execution(t):[];return}if(!this.branchingOperationIds.get(e)){let t=this.nextBranch(e);yield*t?this._execution(t):[]}}},AK=class{HEAD_BRANCH;HEAD_OPERATION;tree;applyOperation;revertOperation;buildEmpty;buildTransformation;constructor(e){this.applyOperation=e.applyOperation,this.revertOperation=e.revertOperation,this.buildEmpty=e.buildEmpty,this.buildTransformation=e.buildTransformation,this.HEAD_BRANCH=new TK(this.buildTransformation),this.tree=new kK(this.buildTransformation,this.HEAD_BRANCH);let t=e.initialOperationId,n=new EK(t,this.buildEmpty(t));this.tree.insertOperationLast(this.HEAD_BRANCH,n),this.HEAD_OPERATION=n}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){let n=new EK(e,t),r=this.tree.getLastBranch();this.tree.insertOperationLast(r,n),this.HEAD_BRANCH=r,this.HEAD_OPERATION=n}insert(e,t,n){let r=new EK(e,t);this.revertTo(n),this.tree.insertOperationAfter(this.HEAD_BRANCH,r,n),this.fastForward()}undo(e,t,n){let{branch:r,operation:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(r,i),this.fastForward(),this.insert(t,this.buildEmpty(t),n)}redo(e,t,n){let{branch:r}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(r),this.fastForward(),this.insert(t,this.buildEmpty(t),n)}rebase(e){let t=this.get(e),n=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);let r=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,r);for(let{operation:e}of n)this.insert(e.id,e.data,this.HEAD_OPERATION.id)}revertBefore(e){let t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){let t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(let{next:t,operation:n,isCancelled:r}of e)r||this.revertOperation(n.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){let e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(let{operation:t,branch:n,isCancelled:r}of e)r||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=n}};function jK(e){return new AK({initialOperationId:e.initialRevisionId,applyOperation:t=>{let n=t.commands.slice(),{changes:r}=e.recordChanges(()=>{for(let t of n)e.dispatch(t)});t.setChanges(r)},revertOperation:e=>MK([e]),buildEmpty:e=>new iW(e,`empty`,[]),buildTransformation:{with:e=>t=>new iW(t.id,t.clientId,JU(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new iW(t.id,t.clientId,JU(t.commands,e.commands.map(wK).flat()),t.rootCommand,void 0,t.timestamp)}})}function MK(e){for(let t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){let n=t.changes[e];NK(n)}}function NK(e){let t=e.target,n=e.key,r=e.before;r===void 0?delete t[n]:t[n]=r}var PK=class{observers=new Map;defaultSubscription;mainSubscription;registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||=this.defaultSubscription}observe(e,t){this.observers.set(e,{owner:e,callbacks:t})}capture(e,t){if(this.observers.get(e))throw Error(`You are already subscribed forever`);this.mainSubscription?.owner&&this.mainSubscription.owner!==e&&this.mainSubscription.callbacks.release?.(),this.mainSubscription={owner:e,callbacks:t}}release(e){this.mainSubscription?.owner!==e||this.observers.get(e)||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){this.mainSubscription!==this.defaultSubscription&&(this.mainSubscription?.callbacks.release?.(),this.mainSubscription=this.defaultSubscription)}isListening(e){return this.mainSubscription?.owner===e}send(e){this.mainSubscription?.callbacks.handleEvent(e),this.observers.forEach(t=>t.callbacks.handleEvent(e))}},FK=class{stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new PK,this.anchor={cell:{col:0,row:0},zone:z({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,n){this.stream.capture(e,n),this.anchor=t}registerAsDefault(e,t,n){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,n),this.defaultAnchor=t,this.capture(e,t,n)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}modifyAnchor(e,t,n){let r=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(r,e.zone)},this.processEvent({options:n,anchor:e,mode:t})}selectZone(e,t={scrollIntoView:!0}){return this.modifyAnchor(e,`overrideSelection`,t)}selectCell(e,t){let n=z({col:e,row:t});return this.selectZone({zone:n,cell:{col:e,row:t}},{scrollIntoView:!0})}moveAnchorCell(e,t=1){if(t!==`end`&&t<=0)return new xr(`InvalidSelectionStep`);let{col:n,row:r}=this.getNextAvailablePosition(e,t);return this.selectCell(n,r)}setAnchorCorner(e,t){let n=this.getters.getActiveSheetId(),{col:r,row:i}=this.anchor.cell,a={left:Math.min(r,e),top:Math.min(i,t),right:Math.max(r,e),bottom:Math.max(i,t)},o={zone:this.getters.expandZone(n,a),cell:{col:r,row:i}};return this.processEvent({mode:`updateAnchor`,anchor:o,options:{scrollIntoView:!1}})}addCellToSelection(e,t){let n=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:n,col:e,row:t}));let r=this.getters.expandZone(n,z({col:e,row:t}));return this.processEvent({options:{scrollIntoView:!0},anchor:{zone:r,cell:{col:e,row:t}},mode:`newAnchor`})}resizeAnchorZone(e,t=1){if(t!==`end`&&t<=0)return new xr(`InvalidSelectionStep`);let n=this.getters.getActiveSheetId(),r=this.anchor,{col:i,row:a}=r.cell,{left:o,right:s,top:c,bottom:l}=r.zone,u=this.getStartingPosition(e),[d,f]=this.deltaToTarget(u,e,t);if(d===0&&f===0)return xr.Success;let p=r.zone,m=e=>{e=Is(e);let{left:t,right:r,top:i,bottom:a}=this.getters.expandZone(n,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(n)-1,r),top:Math.max(0,i),bottom:Math.min(this.getters.getNumberRows(n)-1,a)}},{cell:h,zone:g}=this.getReferenceAnchor(),{col:_,row:v}=h,y=0;for(;p!==null;){if(y++,d<0){let e=this.getNextAvailableCol(d,s-(y-1),v);p=g.right<=s-y?m({top:c,left:o,bottom:l,right:e}):null}if(d>0){let e=this.getNextAvailableCol(d,o+(y-1),v);p=o+y<=g.left?m({top:c,left:e,bottom:l,right:s}):null}if(f<0){let e=this.getNextAvailableRow(f,_,l-(y-1));p=g.bottom<=l-y?m({top:c,left:o,bottom:e,right:s}):null}if(f>0){let e=this.getNextAvailableRow(f,_,c+(y-1));p=c+y<=g.top?m({top:e,left:o,bottom:l,right:s}):null}if(p&&=Is(p),p&&!Es(p,r.zone))return this.processEvent({options:{scrollIntoView:!0},mode:`updateAnchor`,anchor:{zone:p,cell:{col:i,row:a}}})}p=m(Cs({top:a,bottom:a,left:i,right:i},Is({top:this.getNextAvailableRow(f,_,c),left:this.getNextAvailableCol(d,o,v),bottom:this.getNextAvailableRow(f,_,l),right:this.getNextAvailableCol(d,s,v)})));let ee={zone:p,cell:{col:i,row:a}};return this.processEvent({anchor:ee,mode:`updateAnchor`,options:{scrollIntoView:!0}})}selectColumn(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getNumberRows(n)-1,i={left:e,right:e,top:0,bottom:r},a=this.getters.findFirstVisibleColRowIndex(n,`ROW`),o,s;switch(t){case`overrideSelection`:case`newAnchor`:o=e,s=a;break;case`updateAnchor`:({col:o,row:s}=this.anchor.cell),i=Cs(i,{left:o,right:o,top:a,bottom:r});break}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:o,row:s}},mode:t})}selectRow(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getNumberCols(n)-1,i={top:e,bottom:e,left:0,right:r},a=this.getters.findFirstVisibleColRowIndex(n,`COL`),o,s;switch(t){case`overrideSelection`:case`newAnchor`:o=a,s=e;break;case`updateAnchor`:({col:o,row:s}=this.anchor.cell),i=Cs(i,{left:a,right:r,top:s,bottom:s});break}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:o,row:s}},mode:t})}loopSelection(){let e=this.getters.getActiveSheetId(),t=this.anchor;if(Es(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:z(t.cell)},`updateAnchor`,{scrollIntoView:!1});let n=this.getters.getContiguousZone(e,t.zone);return w(n,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:n},`updateAnchor`,{scrollIntoView:!1})}selectTableAroundSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getContiguousZone(e,this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:t},`updateAnchor`,{scrollIntoView:!1})}selectAll(){let e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({mode:`overrideSelection`,anchor:{zone:t,cell:this.anchor.cell},options:{scrollIntoView:!1}})}isListening(e){return this.stream.isListening(e)}processEvent(e){let t={...e,previousAnchor:b(this.anchor)},n=this.checkEventAnchorZone(t);return n===`Success`?(this.anchor=t.anchor,this.stream.send(t),xr.Success):new xr(n)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){let{cell:t,zone:n}=e;if(!ks(t.col,t.row,n))return`InvalidAnchorZone`;let{left:r,right:i,top:a,bottom:o}=n,s=this.getters.getActiveSheetId(),c=this.getters.findVisibleHeader(s,`COL`,r,i);return this.getters.findVisibleHeader(s,`ROW`,a,o)===void 0||c===void 0?`SelectionOutOfBound`:`Success`}checkAnchorZoneOrThrow(e){if(this.checkAnchorZone(e)===`InvalidAnchorZone`)throw Error(`The provided anchor is invalid. The cell must be part of the zone.`)}getNextAvailablePosition(e,t=1){let{col:n,row:r}=this.anchor.cell,i=this.deltaToTarget({col:n,row:r},e,t);return{col:this.getNextAvailableCol(i[0],n,r),row:this.getNextAvailableRow(i[1],n,r)}}getNextAvailableCol(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`COL`,t,i,e=>this.getters.isInSameMerge(r,t,n,e,n))}getNextAvailableRow(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`ROW`,n,i,e=>this.getters.isInSameMerge(r,t,n,t,e))}getNextAvailableHeader(e,t,n,r,i){let a=this.getters.getActiveSheetId();if(e===0)return n;let o=Math.sign(e),s=n+e;for(;i(s);)s+=o;for(;this.getters.isHeaderHidden(a,t,s);)s+=o;return s<0||s>this.getters.getNumberHeaders(a,t)-1?this.getters.isHeaderHidden(a,t,n)?this.getNextAvailableHeader(-o,t,n,r,i):n:s}getReferenceAnchor(){let e=this.getters.getActiveSheetId(),t=this.anchor,{left:n,right:r,top:i,bottom:a}=t.zone,{col:o,row:s}=t.cell,c=this.getters.isColHidden(e,o)&&this.getters.findVisibleHeader(e,`COL`,n,r)||o,l=this.getters.isRowHidden(e,s)&&this.getters.findVisibleHeader(e,`ROW`,i,a)||s,u=this.getters.expandZone(e,{left:c,right:c,top:l,bottom:l});return{cell:{col:c,row:l},zone:u}}deltaToTarget(e,t,n){switch(t){case`up`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,-1)-e.row]:[0,-n];case`down`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,1)-e.row]:[0,n];case`left`:return n===`end`?[this.getEndOfCluster(e,`cols`,-1)-e.col,0]:[-n,0];case`right`:return n===`end`?[this.getEndOfCluster(e,`cols`,1)-e.col,0]:[n,0]}}getStartingPosition(e){let{col:t,row:n}=this.getPosition(),r=this.anchor.zone;switch(e){case`down`:case`up`:n=n===r.top?r.bottom:r.top;break;case`left`:case`right`:t=t===r.right?r.left:r.right;break}return{col:t,row:n}}getEndOfCluster(e,t,n){let r=this.getters.getActiveSheetId(),i=e,a=this.getNextCellPosition(e,t,n),o=!this.isCellSkippableInCluster({...i,sheetId:r})&&!this.isCellSkippableInCluster({...a,sheetId:r})?`endOfCluster`:`nextCluster`;for(;;){let e=this.getNextCellPosition(i,t,n);if(i.col===e.col&&i.row===e.row)break;let a=this.isCellSkippableInCluster({...e,sheetId:r});if(o===`endOfCluster`&&a)break;if(o===`nextCluster`&&!a){i=e;break}i=e}return t===`cols`?i.col:i.row}getNextCellPosition(e,t,n){let r=t===`cols`?`col`:`row`,i={...e};return i[r]=t===`cols`?this.getNextAvailableCol(n,i.col,i.row):this.getNextAvailableRow(n,i.col,i.row),{col:i.col,row:i.row}}getPosition(){return{...this.anchor.cell}}isCellSkippableInCluster(e){let t=this.getters.getMainCellPosition(e),n=this.getters.getEvaluatedCell(t);return n.type===`empty`||n.type===`text`&&n.value===``}};function IK(e){if(typeof e==`string`)return{};if(typeof e==`number`)return[];throw Error(`Cannot create new node`)}var LK=class{changes;commands=[];recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){let t=e.pop(),n=e[0],r=e.at(-1),i=e.length-2;for(let t=1;t<=i;t++){let r=e[t];if(n[r]===void 0){let i=e[t+1];n[r]=IK(i)}n=n[r]}n[r]!==t&&(this.changes?.push({key:r,target:n,before:n[r]}),t===void 0?delete n[r]:n[r]=t)}};let RK=17781237,zK=17781238,BK=88853993,VK=88853994;function HK(e,t,n){let r=[[`xmlns:r`,Tf],[`xmlns:a`,xf],[`xmlns:c`,Sf]],i=UK({backgroundColor:e.data.backgroundColor,line:{color:`000000`}}),a=J``;if(e.data.title?.text){let t=lw(ES(e.data.backgroundColor)),n=e.data.title.fontSize??16;a=J`
|
|
2655
|
+
`;var CK=class extends t.Component{static template=`o-spreadsheet-Spreadsheet`;static props={model:Object,notifyUser:{type:Function,optional:!0},raiseError:{type:Function,optional:!0},askConfirmation:{type:Function,optional:!0}};static components={TopBar:bK,Grid:ZV,BottomBar:JG,SmallBottomBar:aK,SidePanels:rK,SpreadsheetDashboard:XG,HeaderGroupContainer:eK,FullScreenChart:$V};sidePanel;spreadsheetRef=(0,t.useRef)(`spreadsheet`);spreadsheetRect=ZD();_focusGrid;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){let e={};return this.env.isDashboard()?e[`grid-template-rows`]=`auto`:e[`grid-template-rows`]=`min-content auto min-content`,e[`grid-template-columns`]=`auto ${this.sidePanel.mainPanel?`${this.sidePanel.totalPanelSize||350}px`:`auto`}`,H(e)}setup(){if(!(`isSmall`in this.env)){let e=tK();(0,t.useSubEnv)({get isSmall(){return e.isSmall}})}let e=Ud();e.inject(Jd,this.model);let n=this.env;e.get(KV).setSmallThreshhold(()=>n.isSmall),this.notificationStore=B(LO),this.composerFocusStore=B(Qd),this.sidePanel=B(qV);let r=this.model.config.external.fileStore;(0,t.useSubEnv)({model:this.model,imageProvider:r?new zG(r):void 0,loadCurrencies:this.model.config.external.loadCurrencies,loadLocales:this.model.config.external.loadLocales,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.sidePanel.open.bind(this.sidePanel),replaceSidePanel:this.sidePanel.replace.bind(this.sidePanel),toggleSidePanel:this.sidePanel.toggle.bind(this.sidePanel),clipboard:this.env.clipboard||xK(),startCellEdition:e=>this.composerFocusStore.focusActiveComposer({content:e}),notifyUser:e=>this.notificationStore.notifyUser(e),askConfirmation:(e,t,n)=>this.notificationStore.askConfirmation(e,t,n),raiseError:(e,t)=>this.notificationStore.raiseError(e,t),isMobile:cw}),this.notificationStore.updateNotificationCallbacks({...this.props}),(0,t.useEffect)(()=>{!this.spreadsheetRef.el.contains(document.activeElement)&&document.activeElement?.contains(this.spreadsheetRef.el)&&this.focusGrid()}),(0,t.useExternalListener)(window,`resize`,()=>this.render(!0)),(0,t.useExternalListener)(document.body,`wheel`,()=>{}),this.bindModelEvents(),(0,t.onWillUpdateProps)(e=>{if(e.model!==this.props.model)throw Error(`Changing the props model is not supported at the moment.`);(e.notifyUser!==this.props.notifyUser||e.askConfirmation!==this.props.askConfirmation||e.raiseError!==this.props.raiseError)&&this.notificationStore.updateNotificationCallbacks({...e})});let i=Dt(this.render.bind(this,!0));(0,t.onMounted)(()=>{this.checkViewportSize(),e.on(`store-updated`,this,i),a.observe(this.spreadsheetRef.el)}),(0,t.onWillUnmount)(()=>{this.unbindModelEvents(),e.off(`store-updated`,this),a.disconnect(),ff()}),(0,t.onPatched)(()=>{this.checkViewportSize()});let a=new ResizeObserver(()=>{this.sidePanel.changeSpreadsheetWidth(this.spreadsheetRect.width)})}bindModelEvents(){this.model.on(`update`,this,()=>this.render(!0)),this.model.on(`notify-ui`,this,e=>this.notificationStore.notifyUser(e)),this.model.on(`raise-error-ui`,this,({text:e})=>this.notificationStore.raiseError(e))}unbindModelEvents(){this.model.off(`update`,this),this.model.off(`notify-ui`,this),this.model.off(`raise-error-ui`,this)}checkViewportSize(){let{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(!(!isFinite(e)||!isFinite(t)))if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.notificationStore.notifyUser({text:E(`The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns.`),type:`warning`,sticky:!1}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}focusGrid(){this._focusGrid&&this._focusGrid()}get gridHeight(){return this.env.model.getters.getSheetViewDimension().height}get gridContainerStyle(){let e=21*this.rowLayers.length,t=21*this.colLayers.length;return H({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`})}get rowLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`ROW`)}get colLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`COL`)}getGridSize(){let e=this.spreadsheetRef.el;if(!e)return{width:0,height:0};let t=t=>e.querySelector(t)?.getBoundingClientRect().height||0,n=t=>e.querySelector(t)?.getBoundingClientRect().width||0,r=e.getBoundingClientRect(),i=t(`.o-spreadsheet-topbar-wrapper`),a=t(`.o-spreadsheet-bottombar-wrapper`),o=t(`.o-column-groups`),s=n(`.o-grid`);return{width:Math.max(s-15,0),height:Math.max(r.height-i-a-o-15,0)}}};function wK(e){return hG.get(e.type)(e)}var TK=class e{buildTransformation;operations;constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){let t=this.operations.find(t=>t.id===e);if(!t)throw Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(let n of this.operations){if(n.id===e)return e;if(n.id===t)return t}throw Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find(t=>t.id===e)}prepend(e){let t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map(e=>e.transformed(t))]}insert(e,t){let n=this.buildTransformation.with(e.data),{before:r,operation:i,after:a}=this.locateOperation(t);this.operations=[...r,i,e,...a.map(e=>e.transformed(n))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(t){let{after:n}=this.locateOperation(t);return new e(this.buildTransformation,n)}transform(e){this.operations=this.operations.map(t=>t.transformed(e))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){let{before:t,operation:n}=this.locateOperation(e);this.operations=t.concat([n])}locateOperation(e){let t=this.operations.findIndex(t=>t.id===e);if(t===-1)throw Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}},EK=class{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new DK(this.id,kt(()=>e(this.data)))}},DK=class e{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(t){return new e(this.id,this.lazyData.map(t))}},OK=class e{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(t){function*n(e,t){for(let n of e)if(yield n,n.operation.id===t)return}return new e(n(this.operations,t))}stopBefore(t){function*n(e,t){for(let n of e){if(n.operation.id===t)return;yield n}}return new e(n(this.operations,t))}startAfter(t){function*n(e,t){let n=!0;for(let r of e)n||(yield r),r.operation.id===t&&(n=!1)}return new e(n(this.operations,t))}},kK=class{buildTransformation;branches;branchingOperationIds=new Map;constructor(e,t){this.buildTransformation=e,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new OK(pt(this._execution(e),this._execution(e)))}revertedExecution(e){return new OK(pt(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){let n=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),n&&this.insertPrevious(e,t,n)}insertOperationAfter(e,t,n){e.insert(t,n),this.updateNextWith(e,t,n),this.insertPrevious(e,t,n)}undo(e,t){let n=this.buildTransformation.without(t.data),r=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);let i=e.fork(t.id);r&&this.branchingOperationIds.set(i,r),this.insertBranchAfter(e,i),this.transform(i,n)}redo(e){let t=this.nextBranch(e);if(!t)return;let n=this.nextBranch(t);this.removeBranchFromTree(t);let r=this.branchingOperationIds.get(t);r?this.branchingOperationIds.set(e,r):this.branchingOperationIds.delete(e),n&&this.rebaseUp(n)}drop(e){for(let t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(let n of this.revertedExecution(e))if(n.operation.id===t)return n;throw Error(`Operation ${t} not found`)}rebaseUp(e){let{previousBranch:t,branchingOperation:n}=this.findPreviousBranchingOperation(e);if(!t||!n)return;let r=this.buildTransformation.without(n.data),i=t.fork(n.id);this.branchingOperationIds.set(i,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,i),i.transform(r);let a=this.nextBranch(i);a&&this.rebaseUp(a)}removeBranchFromTree(e){let t=this.branches.findIndex(t=>t===e);this.branches.splice(t,1)}insertBranchAfter(e,t){let n=this.branches.findIndex(t=>t===e);this.branches.splice(n+1,0,t)}updateNextWith(e,t,n){let r=this.branchingOperationIds.get(e),i=this.nextBranch(e);if(!(!r||!i))if(e.getFirstOperationAmong(n,r)===r){let a=this.addToNextBranch(e,i,r,t,n);this.updateNextWith(i,a,n)}else{let e=this.buildTransformation.with(t.data);this.transform(i,e)}}addToNextBranch(e,t,n,r,i){let a=r;return i===n?(a=this.getTransformedOperation(e,n,r),t.prepend(a)):t.contains(i)?(a=this.getTransformedOperation(e,n,r),t.insert(a,i)):t.append(r),a}getTransformedOperation(e,t,n){let r=e.getOperation(t),i=this.buildTransformation.without(r.data);return n.transformed(i)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);let n=this.nextBranch(e);n&&this.transform(n,t)}insertPrevious(e,t,n){let{previousBranch:r,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!r||!i)return;let a=this.buildTransformation.with(i.data),o=e.fork(n);o.transform(a),r.cutAfter(n),r.appendBranch(o);let s=t.transformed(a);this.insertPrevious(r,s,n)}findPreviousBranchingOperation(e){let t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};let n=this.branchingOperationIds.get(t);return n?{previousBranch:t,branchingOperation:t.getOperation(n)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){let t=this.branches.findIndex(t=>t===e);if(t!==-1)return this.branches[t+1]}previousBranch(e){let t=this.branches.findIndex(t=>t===e);if(t!==-1)return this.branches[t-1]}*_revertedExecution(e){let t=this.branchingOperationIds.get(e),n=!!t,r=e.getOperations();for(let i=r.length-1;i>=0;i--){let a=r[i];a.id===t&&(n=!1),n||(yield{operation:a,branch:e,isCancelled:!this.shouldExecute(e,a)})}let i=this.previousBranch(e);yield*i?this._revertedExecution(i):[]}*_execution(e){for(let t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){let t=this.nextBranch(e);yield*t?this._execution(t):[];return}if(!this.branchingOperationIds.get(e)){let t=this.nextBranch(e);yield*t?this._execution(t):[]}}},AK=class{HEAD_BRANCH;HEAD_OPERATION;tree;applyOperation;revertOperation;buildEmpty;buildTransformation;constructor(e){this.applyOperation=e.applyOperation,this.revertOperation=e.revertOperation,this.buildEmpty=e.buildEmpty,this.buildTransformation=e.buildTransformation,this.HEAD_BRANCH=new TK(this.buildTransformation),this.tree=new kK(this.buildTransformation,this.HEAD_BRANCH);let t=e.initialOperationId,n=new EK(t,this.buildEmpty(t));this.tree.insertOperationLast(this.HEAD_BRANCH,n),this.HEAD_OPERATION=n}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){let n=new EK(e,t),r=this.tree.getLastBranch();this.tree.insertOperationLast(r,n),this.HEAD_BRANCH=r,this.HEAD_OPERATION=n}insert(e,t,n){let r=new EK(e,t);this.revertTo(n),this.tree.insertOperationAfter(this.HEAD_BRANCH,r,n),this.fastForward()}undo(e,t,n){let{branch:r,operation:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(r,i),this.fastForward(),this.insert(t,this.buildEmpty(t),n)}redo(e,t,n){let{branch:r}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(r),this.fastForward(),this.insert(t,this.buildEmpty(t),n)}rebase(e){let t=this.get(e),n=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);let r=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,r);for(let{operation:e}of n)this.insert(e.id,e.data,this.HEAD_OPERATION.id)}revertBefore(e){let t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){let t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(let{next:t,operation:n,isCancelled:r}of e)r||this.revertOperation(n.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){let e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(let{operation:t,branch:n,isCancelled:r}of e)r||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=n}};function jK(e){return new AK({initialOperationId:e.initialRevisionId,applyOperation:t=>{let n=t.commands.slice(),{changes:r}=e.recordChanges(()=>{for(let t of n)e.dispatch(t)});t.setChanges(r)},revertOperation:e=>MK([e]),buildEmpty:e=>new iW(e,`empty`,[]),buildTransformation:{with:e=>t=>new iW(t.id,t.clientId,JU(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new iW(t.id,t.clientId,JU(t.commands,e.commands.map(wK).flat()),t.rootCommand,void 0,t.timestamp)}})}function MK(e){for(let t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){let n=t.changes[e];NK(n)}}function NK(e){let t=e.target,n=e.key,r=e.before;r===void 0?delete t[n]:t[n]=r}var PK=class{observers=new Map;defaultSubscription;mainSubscription;registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||=this.defaultSubscription}observe(e,t){this.observers.set(e,{owner:e,callbacks:t})}capture(e,t){if(this.observers.get(e))throw Error(`You are already subscribed forever`);this.mainSubscription?.owner&&this.mainSubscription.owner!==e&&this.mainSubscription.callbacks.release?.(),this.mainSubscription={owner:e,callbacks:t}}release(e){this.mainSubscription?.owner!==e||this.observers.get(e)||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){this.mainSubscription!==this.defaultSubscription&&(this.mainSubscription?.callbacks.release?.(),this.mainSubscription=this.defaultSubscription)}isListening(e){return this.mainSubscription?.owner===e}send(e){this.mainSubscription?.callbacks.handleEvent(e),this.observers.forEach(t=>t.callbacks.handleEvent(e))}},FK=class{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new PK,this.anchor={cell:{col:0,row:0},zone:z({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,n){this.stream.capture(e,n),this.anchor=t}registerAsDefault(e,t,n){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,n),this.defaultAnchor=t,this.capture(e,t,n)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}modifyAnchor(e,t,n){let r=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(r,e.zone)},this.processEvent({options:n,anchor:e,mode:t})}selectZone(e,t={scrollIntoView:!0}){return this.modifyAnchor(e,`overrideSelection`,t)}selectCell(e,t){let n=z({col:e,row:t});return this.selectZone({zone:n,cell:{col:e,row:t}},{scrollIntoView:!0})}moveAnchorCell(e,t=1){if(t!==`end`&&t<=0)return new xr(`InvalidSelectionStep`);let{col:n,row:r}=this.getNextAvailablePosition(e,t);return this.selectCell(n,r)}setAnchorCorner(e,t){let n=this.getters.getActiveSheetId(),{col:r,row:i}=this.anchor.cell,a={left:Math.min(r,e),top:Math.min(i,t),right:Math.max(r,e),bottom:Math.max(i,t)},o={zone:this.getters.expandZone(n,a),cell:{col:r,row:i}};return this.processEvent({mode:`updateAnchor`,anchor:o,options:{scrollIntoView:!1}})}addCellToSelection(e,t){let n=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:n,col:e,row:t}));let r=this.getters.expandZone(n,z({col:e,row:t}));return this.processEvent({options:{scrollIntoView:!0},anchor:{zone:r,cell:{col:e,row:t}},mode:`newAnchor`})}resizeAnchorZone(e,t=1){if(t!==`end`&&t<=0)return new xr(`InvalidSelectionStep`);let n=this.getters.getActiveSheetId(),r=this.anchor,{col:i,row:a}=r.cell,{left:o,right:s,top:c,bottom:l}=r.zone,u=this.getStartingPosition(e),[d,f]=this.deltaToTarget(u,e,t);if(d===0&&f===0)return xr.Success;let p=r.zone,m=e=>{e=Is(e);let{left:t,right:r,top:i,bottom:a}=this.getters.expandZone(n,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(n)-1,r),top:Math.max(0,i),bottom:Math.min(this.getters.getNumberRows(n)-1,a)}},{cell:h,zone:g}=this.getReferenceAnchor(),{col:_,row:v}=h,y=0;for(;p!==null;){if(y++,d<0){let e=this.getNextAvailableCol(d,s-(y-1),v);p=g.right<=s-y?m({top:c,left:o,bottom:l,right:e}):null}if(d>0){let e=this.getNextAvailableCol(d,o+(y-1),v);p=o+y<=g.left?m({top:c,left:e,bottom:l,right:s}):null}if(f<0){let e=this.getNextAvailableRow(f,_,l-(y-1));p=g.bottom<=l-y?m({top:c,left:o,bottom:e,right:s}):null}if(f>0){let e=this.getNextAvailableRow(f,_,c+(y-1));p=c+y<=g.top?m({top:e,left:o,bottom:l,right:s}):null}if(p&&=Is(p),p&&!Es(p,r.zone))return this.processEvent({options:{scrollIntoView:!0},mode:`updateAnchor`,anchor:{zone:p,cell:{col:i,row:a}}})}p=m(Cs({top:a,bottom:a,left:i,right:i},Is({top:this.getNextAvailableRow(f,_,c),left:this.getNextAvailableCol(d,o,v),bottom:this.getNextAvailableRow(f,_,l),right:this.getNextAvailableCol(d,s,v)})));let ee={zone:p,cell:{col:i,row:a}};return this.processEvent({anchor:ee,mode:`updateAnchor`,options:{scrollIntoView:!0}})}selectColumn(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getNumberRows(n)-1,i={left:e,right:e,top:0,bottom:r},a=this.getters.findFirstVisibleColRowIndex(n,`ROW`),o,s;switch(t){case`overrideSelection`:case`newAnchor`:o=e,s=a;break;case`updateAnchor`:({col:o,row:s}=this.anchor.cell),i=Cs(i,{left:o,right:o,top:a,bottom:r});break}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:o,row:s}},mode:t})}selectRow(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getNumberCols(n)-1,i={top:e,bottom:e,left:0,right:r},a=this.getters.findFirstVisibleColRowIndex(n,`COL`),o,s;switch(t){case`overrideSelection`:case`newAnchor`:o=a,s=e;break;case`updateAnchor`:({col:o,row:s}=this.anchor.cell),i=Cs(i,{left:a,right:r,top:s,bottom:s});break}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:o,row:s}},mode:t})}loopSelection(){let e=this.getters.getActiveSheetId(),t=this.anchor;if(Es(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:z(t.cell)},`updateAnchor`,{scrollIntoView:!1});let n=this.getters.getContiguousZone(e,t.zone);return w(n,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:n},`updateAnchor`,{scrollIntoView:!1})}selectTableAroundSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getContiguousZone(e,this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:t},`updateAnchor`,{scrollIntoView:!1})}selectAll(){let e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({mode:`overrideSelection`,anchor:{zone:t,cell:this.anchor.cell},options:{scrollIntoView:!1}})}isListening(e){return this.stream.isListening(e)}processEvent(e){let t={...e,previousAnchor:b(this.anchor)},n=this.checkEventAnchorZone(t);return n===`Success`?(this.anchor=t.anchor,this.stream.send(t),xr.Success):new xr(n)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){let{cell:t,zone:n}=e;if(!ks(t.col,t.row,n))return`InvalidAnchorZone`;let{left:r,right:i,top:a,bottom:o}=n,s=this.getters.getActiveSheetId(),c=this.getters.findVisibleHeader(s,`COL`,r,i);return this.getters.findVisibleHeader(s,`ROW`,a,o)===void 0||c===void 0?`SelectionOutOfBound`:`Success`}checkAnchorZoneOrThrow(e){if(this.checkAnchorZone(e)===`InvalidAnchorZone`)throw Error(`The provided anchor is invalid. The cell must be part of the zone.`)}getNextAvailablePosition(e,t=1){let{col:n,row:r}=this.anchor.cell,i=this.deltaToTarget({col:n,row:r},e,t);return{col:this.getNextAvailableCol(i[0],n,r),row:this.getNextAvailableRow(i[1],n,r)}}getNextAvailableCol(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`COL`,t,i,e=>this.getters.isInSameMerge(r,t,n,e,n))}getNextAvailableRow(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`ROW`,n,i,e=>this.getters.isInSameMerge(r,t,n,t,e))}getNextAvailableHeader(e,t,n,r,i){let a=this.getters.getActiveSheetId();if(e===0)return n;let o=Math.sign(e),s=n+e;for(;i(s);)s+=o;for(;this.getters.isHeaderHidden(a,t,s);)s+=o;return s<0||s>this.getters.getNumberHeaders(a,t)-1?this.getters.isHeaderHidden(a,t,n)?this.getNextAvailableHeader(-o,t,n,r,i):n:s}getReferenceAnchor(){let e=this.getters.getActiveSheetId(),t=this.anchor,{left:n,right:r,top:i,bottom:a}=t.zone,{col:o,row:s}=t.cell,c=this.getters.isColHidden(e,o)&&this.getters.findVisibleHeader(e,`COL`,n,r)||o,l=this.getters.isRowHidden(e,s)&&this.getters.findVisibleHeader(e,`ROW`,i,a)||s,u=this.getters.expandZone(e,{left:c,right:c,top:l,bottom:l});return{cell:{col:c,row:l},zone:u}}deltaToTarget(e,t,n){switch(t){case`up`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,-1)-e.row]:[0,-n];case`down`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,1)-e.row]:[0,n];case`left`:return n===`end`?[this.getEndOfCluster(e,`cols`,-1)-e.col,0]:[-n,0];case`right`:return n===`end`?[this.getEndOfCluster(e,`cols`,1)-e.col,0]:[n,0]}}getStartingPosition(e){let{col:t,row:n}=this.getPosition(),r=this.anchor.zone;switch(e){case`down`:case`up`:n=n===r.top?r.bottom:r.top;break;case`left`:case`right`:t=t===r.right?r.left:r.right;break}return{col:t,row:n}}getEndOfCluster(e,t,n){let r=this.getters.getActiveSheetId(),i=e,a=this.getNextCellPosition(e,t,n),o=!this.isCellSkippableInCluster({...i,sheetId:r})&&!this.isCellSkippableInCluster({...a,sheetId:r})?`endOfCluster`:`nextCluster`;for(;;){let e=this.getNextCellPosition(i,t,n);if(i.col===e.col&&i.row===e.row)break;let a=this.isCellSkippableInCluster({...e,sheetId:r});if(o===`endOfCluster`&&a)break;if(o===`nextCluster`&&!a){i=e;break}i=e}return t===`cols`?i.col:i.row}getNextCellPosition(e,t,n){let r=t===`cols`?`col`:`row`,i={...e};return i[r]=t===`cols`?this.getNextAvailableCol(n,i.col,i.row):this.getNextAvailableRow(n,i.col,i.row),{col:i.col,row:i.row}}getPosition(){return{...this.anchor.cell}}isCellSkippableInCluster(e){let t=this.getters.getMainCellPosition(e),n=this.getters.getEvaluatedCell(t);return n.type===`empty`||n.type===`text`&&n.value===``}};function IK(e){if(typeof e==`string`)return{};if(typeof e==`number`)return[];throw Error(`Cannot create new node`)}var LK=class{changes;commands=[];recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){let t=e.pop(),n=e[0],r=e.at(-1),i=e.length-2;for(let t=1;t<=i;t++){let r=e[t];if(n[r]===void 0){let i=e[t+1];n[r]=IK(i)}n=n[r]}n[r]!==t&&(this.changes?.push({key:r,target:n,before:n[r]}),t===void 0?delete n[r]:n[r]=t)}};let RK=17781237,zK=17781238,BK=88853993,VK=88853994;function HK(e,t,n){let r=[[`xmlns:r`,Tf],[`xmlns:a`,xf],[`xmlns:c`,Sf]],i=UK({backgroundColor:e.data.backgroundColor,line:{color:`000000`}}),a=J``;if(e.data.title?.text){let t=lw(ES(e.data.backgroundColor)),n=e.data.title.fontSize??16;a=J`
|
|
2656
2656
|
<c:title>
|
|
2657
2657
|
${KK(e.data.title.text,t,n,e.data.title)}
|
|
2658
2658
|
<c:overlay val="0" />
|
|
@@ -3409,4 +3409,4 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
3409
3409
|
<Relationships xmlns="${bf.Relationships}">
|
|
3410
3410
|
<Relationship ${K(e)} />
|
|
3411
3411
|
</Relationships>
|
|
3412
|
-
`),`_rels/.rels`)}function yJ(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=$t(e,n,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),n.push(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${ot(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function bJ(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>js(ps(e.range)).numberOfRows>1);return e}var xJ=class extends Rd{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},n={},r=[],i=new gl,a=!1){let o=performance.now();console.debug(`##### Model creation #####`),super(),ir(),r=_N(e,r);let s=lN(e,a);this.state=new LK,this.uuidGenerator=i,this.config=this.setupConfig(n),this.session=this.setupSession(s.revisionId),this.coreGetters={},this.range=new vH(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.selection=new FK(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of oG.getAll())this.setupCorePlugin(e,s);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(r);for(let e of lG.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of cG.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of sG.getAll()){let t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.dispatch(`START`),this.selection.observe(this,{handleEvent:()=>this.trigger(`update`)}),this.setupSessionEvents(),this.joinSession(),n.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly()){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),this.garbageCollectExternalResources(),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}(0,t.markRaw)(this),console.debug(`Model created in`,performance.now()-o,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:kt(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCoreViewPlugin(e){let t=new e(this.coreViewPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new oW(jK({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{if(!this.checkDispatchAllowed(e).isSuccessful){this.dispatchToHandlers(this.coreHandlers,{type:`UNDO`,commands:[e]});return}this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1}}),this.config.transportService,e)}setupSessionEvents(){this.session.on(`remote-revision-received`,this,this.onRemoteRevisionReceived),this.session.on(`revision-undone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`UNDO`,{commands:e}),this.finalize()}),this.session.on(`revision-redone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`REDO`,{commands:e}),this.finalize()}),this.session.on(`unexpected-revision-id`,this,()=>this.trigger(`unexpected-revision-id`)),this.session.on(`collaborative-event-received`,this,()=>{this.trigger(`update`)})}setupConfig(e){let t=e.client||{id:this.uuidGenerator.smallUuid(),name:E(`Anonymous`).toString()},n=e.transportService||new RG;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:n,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger(`notify-ui`,e),raiseBlockingErrorUI:e=>this.trigger(`raise-error-ui`,{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){let t=e.loadLocales||(()=>Promise.resolve(Er));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){let t=yr(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>e!==`Success`)?new xr(t.flat()):xr.Success}checkDispatchAllowedCoreCommand(e){let t=this.corePlugins.map(t=>t.allowDispatch(e));return t.push(this.range.allowDispatch(e)),t}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(let e of this.handlers)e.finalize();this.status=0,this.trigger(`command-finalized`)}canDispatch=(e,t)=>this.checkDispatchAllowed(SJ(e,t));dispatch=(e,t)=>{let n=SJ(e,t),r=this.status;if(this.getters.isReadonly()&&!br(n))return new xr(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new xr(`WaitingSessionConfirmation`);switch(r){case 0:let t=this.checkDispatchAllowed(n);if(!t.isSuccessful)return this.trigger(`update`),t;this.status=1;let{changes:r,commands:i}=this.state.recordChanges(()=>{let t=performance.now();yr(n)&&this.state.addCommand(n),this.dispatchToHandlers(this.handlers,n),this.finalize();let r=performance.now()-t;r>5&&console.debug(e,r,`ms`)});this.session.save(n,i,r),this.status=0,this.trigger(`update`);break;case 1:if(yr(n)){let e=this.checkDispatchAllowed(n);if(!e.isSuccessful)return e;this.state.addCommand(n)}this.dispatchToHandlers(this.handlers,n);break;case 3:throw Error(`Cannot dispatch commands in the finalize state`);case 2:if(yr(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return xr.Success};dispatchFromCorePlugin=(e,t)=>{let n=SJ(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,xr.Success};dispatchToHandlers(e,t){let n=yr(t);for(let r of e)!n&&r instanceof nH||r.beforeHandle(t);for(let r of e)!n&&r instanceof nH||r.handle(t);this.trigger(`command-dispatched`,t)}drawLayer(e,t){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore()}exportData(){let e=wN();for(let t of this.handlers)t instanceof nH&&t.export(e);return e.revisionId=this.session.getRevisionId()||`START_REVISION`,e=b(e),e}updateMode(e){this.config.mode=e,this.trigger(`update`)}exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=EN();for(let t of this.handlers)t instanceof tH&&t.exportForExcel(e);return e=b(e),uJ(e)}garbageCollectExternalResources(){for(let e of this.corePlugins)e.garbageCollectExternalResources()}};function SJ(e,t={}){let n=b(t);return n.type=e,n}let CJ={},wJ={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},TJ={autoCompleteProviders:PO,autofillModifiersRegistry:dU,autofillRulesRegistry:fU,cellMenuRegistry:KI,colMenuRegistry:uR,errorTypes:Ri,linkMenuRegistry:Fk,functionRegistry:Ix,featurePluginRegistry:sG,iconsOnCellRegistry:tU,statefulUIPluginRegistry:cG,coreViewsPluginRegistry:lG,corePluginRegistry:oG,rowMenuRegistry:_R,sidePanelRegistry:GV,figureRegistry:sO,chartSidePanelComponentRegistry:sB,chartComponentRegistry:pD,chartRegistry:fD,chartSubtypeRegistry:hD,topbarMenuRegistry:IG,topbarComponentRegistry:LG,clickableCellRegistry:mG,otRegistry:EU,inverseCommandRegistry:hG,urlRegistry:Ir,cellPopoverRegistry:uO,numberFormatMenuRegistry:jG,repeatLocalCommandTransformRegistry:VW,repeatCommandTransformRegistry:BW,clipboardHandlersRegistries:Fd,pivotRegistry:bV,pivotTimeAdapterRegistry:Uu,pivotSidePanelRegistry:EV,pivotNormalizationValueRegistry:bd,supportedPivotPositionalFormulaRegistry:QV,pivotToFunctionValueRegistry:xd,migrationStepRegistry:iN,chartJsExtensionRegistry:lf},EJ={arg:U,isEvaluationError:j,toBoolean:P,toJsDate:F,toNumber:M,toString:N,toNormalizedPivotValue:gd,toFunctionPivotValue:vd,toXC:T,toZone:ps,toUnboundedZone:fs,toCartesian:Zn,numberToLetters:Hn,lettersToNumber:Un,UuidGenerator:gl,formatValue:L,createCurrencyFormat:ko,ColorGenerator:In,computeTextWidth:$c,createEmptyWorkbookData:wN,createEmptySheet:CN,createEmptyExcelSheet:TN,rgbaToHex:mn,colorToRGBA:hn,positionToZone:z,isDefined:C,isMatrix:Or,lazy:kt,genericRepeat:HW,createAction:m,createActions:f,transformRangeData:Ld,deepEquals:w,overlap:Ds,union:Cs,isInside:ks,deepCopy:b,expandZoneOnInsertion:ys,reduceZoneOnDeletion:Ss,unquote:lt,getMaxObjectId:cd,getFunctionsFromTokens:sS,getFirstPivotFunction:QB,getNumberOfPivotFunctions:$B,parseDimension:dd,isDateOrDatetimeField:fd,makeFieldProposal:qB,insertTokenAfterArgSeparator:YB,insertTokenAfterLeftParenthesis:XB,mergeContiguousZones:Qs,getPivotHighlights:AB,pivotTimeAdapter:Wu,UNDO_REDO_PIVOT_COMMANDS:cU,createPivotFormula:hd,areDomainArgsFieldsValid:md,splitReference:vc,sanitizeSheetName:dt,getUniqueText:$t,isNumber:Pi,isDateTime:ni},DJ={isMarkdownLink:_t,parseMarkdownLink:bt,markdownLink:yt,openLink:Vr,urlRepresentation:Br},OJ={Checkbox:vk,Section:X,RoundColorPicker:rk,ChartDataSeries:gz,ChartErrorSection:_z,ChartLabelRange:vz,ChartTitle:Ez,ChartPanel:uB,ChartFigure:aO,ChartJsComponent:xC,Grid:ZV,GridOverlay:JR,ScorecardChart:RC,LineConfigPanel:Kz,BarConfigPanel:bz,PieChartDesignPanel:Yz,GenericChartConfigPanel:yz,ChartWithAxisDesignPanel:Pz,LineChartDesignPanel:qz,GaugeChartConfigPanel:zz,GaugeChartDesignPanel:Bz,ScorecardChartConfigPanel:Qz,ScorecardChartDesignPanel:$z,GeoChartDesignPanel:Wz,RadarChartDesignPanel:Xz,WaterfallChartDesignPanel:oB,ComboChartDesignPanel:Iz,FunnelChartDesignPanel:Rz,ChartTypePicker:cB,FigureComponent:cO,MenuPopover:rO,Popover:$D,SelectionInput:fk,ValidationMessages:zR,AddDimensionButton:FB,PivotDimensionGranularity:zB,PivotDimensionOrder:BB,PivotDimension:RB,PivotLayoutConfigurator:WB,PivotHTMLRenderer:eH,PivotDeferUpdate:MB,PivotTitleSection:GB,CogWheelMenu:LB,TextInput:IB,SidePanelCollapsible:mO,RadioSelection:Oz,GeoChartRegionSelectSection:Vz,ChartDashboardMenu:iO,FullScreenChart:$V},kJ={useDragAndDropListItems:ak,useHighlights:pB,useHighlightsOnHover:fB},AJ={useStoreProvider:Ud,DependencyContainer:zd,CellPopoverStore:Ck,ComposerFocusStore:Qd,CellComposerStore:ER,FindAndReplaceStore:wB,HighlightStore:IO,DelayedHoveredCellStore:lO,HoveredTableStore:GR,ModelStore:Jd,NotificationStore:LO,RendererStore:Yd,SelectionInputStore:dk,SpreadsheetStore:Xd,useStore:B,useLocalStore:Wd,SidePanelStore:qV,PivotSidePanelStore:wV,PivotMeasureDisplayPanelStore:OB,ClientFocusStore:yR,GridRenderer:nz};function jJ(e,t){return Ix.add(e,t),{addFunction:(e,t)=>jJ(e,t)}}let MJ={DEFAULT_LOCALE:D,HIGHLIGHT_COLOR:v,PIVOT_TABLE_CONFIG:tt,ChartTerms:jw},NJ={...SD,...CE};e.AbstractCellClipboardHandler=Dl,e.AbstractChart=SC,e.AbstractFigureClipboardHandler=Ed,e.CellErrorType=k,e.ClientDisconnectedError=aW,e.CommandResult=Cr,e.CorePlugin=nH,e.CoreViewPlugin=EH,e.DispatchResult=xr,e.EvaluationError=A,e.LocalTransportService=RG,e.Model=xJ,e.PivotRuntimeDefinition=eV,e.Registry=g,e.Revision=iW,e.SPREADSHEET_DIMENSIONS=wJ,e.Spreadsheet=CK,e.SpreadsheetPivotTable=iV,e.UIPlugin=SU,e.__info__=CJ,e.addFunction=jJ,e.addRenderingLayer=jr,e.astToFormula=gy,e.chartHelpers=NJ,e.compile=Qx,e.compileTokens=$x,e.components=OJ,e.constants=MJ,e.convertAstNodes=fy,e.coreTypes=vr,e.findCellInNewZone=Bs,e.functionCache=Zx,e.helpers=EJ,e.hooks=kJ,e.invalidateCFEvaluationCommands=hr,e.invalidateChartEvaluationCommands=pr,e.invalidateDependenciesCommands=mr,e.invalidateEvaluationCommands=fr,e.iterateAstNodes=py,e.links=DJ,e.load=lN,e.parse=uy,e.parseTokens=dy,e.readonlyAllowedCommands=_r,e.registries=TJ,e.setDefaultSheetViewSize=$e,e.setTranslationMethod=rr,e.stores=AJ,e.tokenColors=VO,e.tokenize=jl,CJ.version=`18.4.38`,CJ.date=`2026-05-11T13:46:00.483Z`,CJ.hash=`dafe57f`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|
|
3412
|
+
`),`_rels/.rels`)}function yJ(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=$t(e,n,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),n.push(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${ot(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function bJ(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>js(ps(e.range)).numberOfRows>1);return e}var xJ=class extends Rd{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},n={},r=[],i=new gl,a=!1){let o=performance.now();console.debug(`##### Model creation #####`),super(),ir(),r=_N(e,r);let s=lN(e,a);this.state=new LK,this.uuidGenerator=i,this.config=this.setupConfig(n),this.session=this.setupSession(s.revisionId),this.coreGetters={},this.range=new vH(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.selection=new FK(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of oG.getAll())this.setupCorePlugin(e,s);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(r);for(let e of lG.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of cG.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of sG.getAll()){let t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.dispatch(`START`),this.selection.observe(this,{handleEvent:()=>this.trigger(`update`)}),this.setupSessionEvents(),this.joinSession(),n.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly()){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),this.garbageCollectExternalResources(),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}(0,t.markRaw)(this),console.debug(`Model created in`,performance.now()-o,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:kt(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCoreViewPlugin(e){let t=new e(this.coreViewPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new oW(jK({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{if(!this.checkDispatchAllowed(e).isSuccessful){this.dispatchToHandlers(this.coreHandlers,{type:`UNDO`,commands:[e]});return}this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1}}),this.config.transportService,e)}setupSessionEvents(){this.session.on(`remote-revision-received`,this,this.onRemoteRevisionReceived),this.session.on(`revision-undone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`UNDO`,{commands:e}),this.finalize()}),this.session.on(`revision-redone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`REDO`,{commands:e}),this.finalize()}),this.session.on(`unexpected-revision-id`,this,()=>this.trigger(`unexpected-revision-id`)),this.session.on(`collaborative-event-received`,this,()=>{this.trigger(`update`)})}setupConfig(e){let t=e.client||{id:this.uuidGenerator.smallUuid(),name:E(`Anonymous`).toString()},n=e.transportService||new RG;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:n,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger(`notify-ui`,e),raiseBlockingErrorUI:e=>this.trigger(`raise-error-ui`,{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){let t=e.loadLocales||(()=>Promise.resolve(Er));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){let t=yr(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>e!==`Success`)?new xr(t.flat()):xr.Success}checkDispatchAllowedCoreCommand(e){let t=this.corePlugins.map(t=>t.allowDispatch(e));return t.push(this.range.allowDispatch(e)),t}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(let e of this.handlers)e.finalize();this.status=0,this.trigger(`command-finalized`)}canDispatch=(e,t)=>this.checkDispatchAllowed(SJ(e,t));dispatch=(e,t)=>{let n=SJ(e,t),r=this.status;if(this.getters.isReadonly()&&!br(n))return new xr(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new xr(`WaitingSessionConfirmation`);switch(r){case 0:let t=this.checkDispatchAllowed(n);if(!t.isSuccessful)return this.trigger(`update`),t;this.status=1;let{changes:r,commands:i}=this.state.recordChanges(()=>{let t=performance.now();yr(n)&&this.state.addCommand(n),this.dispatchToHandlers(this.handlers,n),this.finalize();let r=performance.now()-t;r>5&&console.debug(e,r,`ms`)});this.session.save(n,i,r),this.status=0,this.trigger(`update`);break;case 1:if(yr(n)){let e=this.checkDispatchAllowed(n);if(!e.isSuccessful)return e;this.state.addCommand(n)}this.dispatchToHandlers(this.handlers,n);break;case 3:throw Error(`Cannot dispatch commands in the finalize state`);case 2:if(yr(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return xr.Success};dispatchFromCorePlugin=(e,t)=>{let n=SJ(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,xr.Success};dispatchToHandlers(e,t){let n=yr(t);for(let r of e)!n&&r instanceof nH||r.beforeHandle(t);for(let r of e)!n&&r instanceof nH||r.handle(t);this.trigger(`command-dispatched`,t)}drawLayer(e,t){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore()}exportData(){let e=wN();for(let t of this.handlers)t instanceof nH&&t.export(e);return e.revisionId=this.session.getRevisionId()||`START_REVISION`,e=b(e),e}updateMode(e){this.config.mode=e,this.trigger(`update`)}exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=EN();for(let t of this.handlers)t instanceof tH&&t.exportForExcel(e);return e=b(e),uJ(e)}garbageCollectExternalResources(){for(let e of this.corePlugins)e.garbageCollectExternalResources()}};function SJ(e,t={}){let n=b(t);return n.type=e,n}let CJ={},wJ={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},TJ={autoCompleteProviders:PO,autofillModifiersRegistry:dU,autofillRulesRegistry:fU,cellMenuRegistry:KI,colMenuRegistry:uR,errorTypes:Ri,linkMenuRegistry:Fk,functionRegistry:Ix,featurePluginRegistry:sG,iconsOnCellRegistry:tU,statefulUIPluginRegistry:cG,coreViewsPluginRegistry:lG,corePluginRegistry:oG,rowMenuRegistry:_R,sidePanelRegistry:GV,figureRegistry:sO,chartSidePanelComponentRegistry:sB,chartComponentRegistry:pD,chartRegistry:fD,chartSubtypeRegistry:hD,topbarMenuRegistry:IG,topbarComponentRegistry:LG,clickableCellRegistry:mG,otRegistry:EU,inverseCommandRegistry:hG,urlRegistry:Ir,cellPopoverRegistry:uO,numberFormatMenuRegistry:jG,repeatLocalCommandTransformRegistry:VW,repeatCommandTransformRegistry:BW,clipboardHandlersRegistries:Fd,pivotRegistry:bV,pivotTimeAdapterRegistry:Uu,pivotSidePanelRegistry:EV,pivotNormalizationValueRegistry:bd,supportedPivotPositionalFormulaRegistry:QV,pivotToFunctionValueRegistry:xd,migrationStepRegistry:iN,chartJsExtensionRegistry:lf},EJ={arg:U,isEvaluationError:j,toBoolean:P,toJsDate:F,toNumber:M,toString:N,toNormalizedPivotValue:gd,toFunctionPivotValue:vd,toXC:T,toZone:ps,toUnboundedZone:fs,toCartesian:Zn,numberToLetters:Hn,lettersToNumber:Un,UuidGenerator:gl,formatValue:L,createCurrencyFormat:ko,ColorGenerator:In,computeTextWidth:$c,createEmptyWorkbookData:wN,createEmptySheet:CN,createEmptyExcelSheet:TN,rgbaToHex:mn,colorToRGBA:hn,positionToZone:z,isDefined:C,isMatrix:Or,lazy:kt,genericRepeat:HW,createAction:m,createActions:f,transformRangeData:Ld,deepEquals:w,overlap:Ds,union:Cs,isInside:ks,deepCopy:b,expandZoneOnInsertion:ys,reduceZoneOnDeletion:Ss,unquote:lt,getMaxObjectId:cd,getFunctionsFromTokens:sS,getFirstPivotFunction:QB,getNumberOfPivotFunctions:$B,parseDimension:dd,isDateOrDatetimeField:fd,makeFieldProposal:qB,insertTokenAfterArgSeparator:YB,insertTokenAfterLeftParenthesis:XB,mergeContiguousZones:Qs,getPivotHighlights:AB,pivotTimeAdapter:Wu,UNDO_REDO_PIVOT_COMMANDS:cU,createPivotFormula:hd,areDomainArgsFieldsValid:md,splitReference:vc,sanitizeSheetName:dt,getUniqueText:$t,isNumber:Pi,isDateTime:ni},DJ={isMarkdownLink:_t,parseMarkdownLink:bt,markdownLink:yt,openLink:Vr,urlRepresentation:Br},OJ={Checkbox:vk,Section:X,RoundColorPicker:rk,ChartDataSeries:gz,ChartErrorSection:_z,ChartLabelRange:vz,ChartTitle:Ez,ChartPanel:uB,ChartFigure:aO,ChartJsComponent:xC,Grid:ZV,GridOverlay:JR,ScorecardChart:RC,LineConfigPanel:Kz,BarConfigPanel:bz,PieChartDesignPanel:Yz,GenericChartConfigPanel:yz,ChartWithAxisDesignPanel:Pz,LineChartDesignPanel:qz,GaugeChartConfigPanel:zz,GaugeChartDesignPanel:Bz,ScorecardChartConfigPanel:Qz,ScorecardChartDesignPanel:$z,GeoChartDesignPanel:Wz,RadarChartDesignPanel:Xz,WaterfallChartDesignPanel:oB,ComboChartDesignPanel:Iz,FunnelChartDesignPanel:Rz,ChartTypePicker:cB,FigureComponent:cO,MenuPopover:rO,Popover:$D,SelectionInput:fk,ValidationMessages:zR,AddDimensionButton:FB,PivotDimensionGranularity:zB,PivotDimensionOrder:BB,PivotDimension:RB,PivotLayoutConfigurator:WB,PivotHTMLRenderer:eH,PivotDeferUpdate:MB,PivotTitleSection:GB,CogWheelMenu:LB,TextInput:IB,SidePanelCollapsible:mO,RadioSelection:Oz,GeoChartRegionSelectSection:Vz,ChartDashboardMenu:iO,FullScreenChart:$V},kJ={useDragAndDropListItems:ak,useHighlights:pB,useHighlightsOnHover:fB},AJ={useStoreProvider:Ud,DependencyContainer:zd,CellPopoverStore:Ck,ComposerFocusStore:Qd,CellComposerStore:ER,FindAndReplaceStore:wB,HighlightStore:IO,DelayedHoveredCellStore:lO,HoveredTableStore:GR,ModelStore:Jd,NotificationStore:LO,RendererStore:Yd,SelectionInputStore:dk,SpreadsheetStore:Xd,useStore:B,useLocalStore:Wd,SidePanelStore:qV,PivotSidePanelStore:wV,PivotMeasureDisplayPanelStore:OB,ClientFocusStore:yR,GridRenderer:nz};function jJ(e,t){return Ix.add(e,t),{addFunction:(e,t)=>jJ(e,t)}}let MJ={DEFAULT_LOCALE:D,HIGHLIGHT_COLOR:v,PIVOT_TABLE_CONFIG:tt,ChartTerms:jw},NJ={...SD,...CE};e.AbstractCellClipboardHandler=Dl,e.AbstractChart=SC,e.AbstractFigureClipboardHandler=Ed,e.CellErrorType=k,e.ClientDisconnectedError=aW,e.CommandResult=Cr,e.CorePlugin=nH,e.CoreViewPlugin=EH,e.DispatchResult=xr,e.EvaluationError=A,e.LocalTransportService=RG,e.Model=xJ,e.PivotRuntimeDefinition=eV,e.Registry=g,e.Revision=iW,e.SPREADSHEET_DIMENSIONS=wJ,e.Spreadsheet=CK,e.SpreadsheetPivotTable=iV,e.UIPlugin=SU,e.__info__=CJ,e.addFunction=jJ,e.addRenderingLayer=jr,e.astToFormula=gy,e.chartHelpers=NJ,e.compile=Qx,e.compileTokens=$x,e.components=OJ,e.constants=MJ,e.convertAstNodes=fy,e.coreTypes=vr,e.findCellInNewZone=Bs,e.functionCache=Zx,e.helpers=EJ,e.hooks=kJ,e.invalidateCFEvaluationCommands=hr,e.invalidateChartEvaluationCommands=pr,e.invalidateDependenciesCommands=mr,e.invalidateEvaluationCommands=fr,e.iterateAstNodes=py,e.links=DJ,e.load=lN,e.parse=uy,e.parseTokens=dy,e.readonlyAllowedCommands=_r,e.registries=TJ,e.setDefaultSheetViewSize=$e,e.setTranslationMethod=rr,e.stores=AJ,e.tokenColors=VO,e.tokenize=jl,CJ.version=`18.4.40`,CJ.date=`2026-05-15T07:04:46.418Z`,CJ.hash=`bb1e6d6`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|