@odoo/o-spreadsheet 19.1.0-alpha.4 → 19.1.0-alpha.6
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-engine.d.ts +6638 -0
- package/dist/{o-spreadsheet.cjs.js → o-spreadsheet-engine.esm.js} +35798 -71285
- package/dist/{o-spreadsheet.iife.js → o-spreadsheet-engine.iife.js} +35897 -71272
- package/dist/o-spreadsheet-engine.min.iife.js +817 -0
- package/dist/o-spreadsheet.d.ts +6112 -6064
- package/dist/{o-spreadsheet.esm.js → o_spreadsheet.esm.js} +76903 -75111
- package/dist/o_spreadsheet.iife.js +87589 -0
- package/dist/o_spreadsheet.min.iife.js +843 -0
- package/dist/o_spreadsheet.xml +31 -6
- package/package.json +37 -22
- package/dist/o-spreadsheet.iife.min.js +0 -843
|
@@ -0,0 +1,843 @@
|
|
|
1
|
+
!function(e,t){"use strict";const s=.5,o="#017E84",i="#F8F9FA",n="#E8EAED",r="#595959",a="#666666",l="#3266ca",c="#FFFFFF",h=11982760,d=o,u="#188038",g="#9B359B",p="#00000000",m="#4EA7F2",f="#EA6175",v="#AAAAAA",b="#111827",S="#D8DADD",C="#E7E9ED",y="#374151",I=y+"C2",w=o,E=20,R=16,x="#F28C28",T=["#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"],A=26,D=48,_=23,O=15,F=21,P={align:"left",verticalAlign:"bottom",wrapping:"overflow",bold:!1,italic:!1,strikethrough:!1,underline:!1,fontSize:10,fillColor:"",textColor:""},M=P.verticalAlign,N=P.wrapping,L=P.fontSize,k="'Roboto', arial",V="thin",U="#000000",H="START_REVISION",z="??",B="difference",G="#43C5B1",W="#EA6175",$=["'","*","?","/","\\","[","]"],q=/'|\*|\?|\/|\\|\[|\]/,Z="|";let j=0;function Y(){return j}const X="\n",K=[6,7,8,9,10,11,12,14,18,24,36],J={hasFilters:!1,totalRow:!1,firstColumn:!0,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,styleId:"TableStyleMedium5",automaticAutofill:!1},Q=1e5,ee={symbol:"$",position:"before",decimalPlaces:2,code:"",name:"Dollar"},te={fontSize:R,color:y},se="#000000",oe="#3da4ab",ie={OPERATOR:oe,NUMBER:"#02c39a",STRING:"#00a82d",FUNCTION:se,DEBUGGER:oe,LEFT_PAREN:se,RIGHT_PAREN:se,ARG_SEPARATOR:se,ORPHAN_RIGHT_PAREN:"#ff0000"},ne=new RegExp(q,"g");function re(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ae(e){switch(typeof e){case"object":{if(null===e)return e;if(function(e){return"clone"in e&&e.clone instanceof Function}(e))return e.clone();if(!(function(e){return"object"==typeof e&&null!==e&&(e?.constructor===Object||void 0===e?.constructor)}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");const t=Array.isArray(e)?new Array(e.length):{};if(Array.isArray(e))for(let s=0,o=e.length;s<o;s++)s in e&&(t[s]=ae(e[s]));else for(const s in e)t[s]=ae(e[s]);return t}case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function le(e){return ce(e,"'")}function ce(e,t='"'){return e.startsWith(t)&&(e=e.slice(1)),e.endsWith(t)&&(e=e.slice(0,-1)),e}function he(e){return e.match(/\w/g)?.length!==e.length&&(e=`'${e}'`),e}function de(e,t=" "){return e.replace(ne,t)}function ue(e,t,s){return e<t?t:e>s?s:e}function ge(e,t,s=1){if(t<=e&&s>0)return[];if(0===s)throw new Error("range() step must not be zero");const o=Math.ceil(Math.abs((t-e)/s)),i=Array(o);for(let t=0;t<o;t++)i[t]=e+t*s;return i}function pe(e){return e.reduce((e,t,s,o)=>{if(1===Math.abs(t-o[s-1])){e[e.length-1].push(t)}else e.push([t]);return e},[])}function*me(e,t){t.next();for(const s of e){const e=t.next();yield{...s,next:e.done?void 0:e.value}}}function fe(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}const ve=/^\[(.+)\]\((.+)\)$/,be=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function Se(e){return ve.test(e)}function Ce(e){return be.test(e)}function ye(e,t){return`[${e}](${t})`}function Ie(e){const t=e.match(ve)||[],s=t[1],o=t[2];if(!s||!o)throw new Error(`Could not parse markdown link ${e}.`);return{label:s,url:o}}const we="o-spreadsheet://";function Ee(e){return e.startsWith(we)}function Re(e){return`${we}${e}`}function xe(e){if(e.startsWith(we))return e.slice(16);throw new Error(`${e} is not a valid sheet link`)}function Te(e){return void 0!==e}function Ae(e){return void 0===e||Object.values(e).every(e=>"object"==typeof e?Ae(e):!e)}function De(e,t,s){let o;const i=function(){const i=this,n=Array.from(arguments);const r=s&&!o;clearTimeout(o),o=setTimeout(function(){o=void 0,s||e.apply(i,n)},t),r&&e.apply(i,n)};return i.isDebouncePending=()=>void 0!==o,i.stopDebounce=()=>{clearTimeout(o)},i}function _e(e){let t="";for(let s=0,o=e.length;s<o;s++)t+=e[s];return t}function Oe(e){let t,s=!1;const o=()=>(s||(t=e instanceof Function?e():e,s=!0),t);return o.map=e=>Oe(()=>e(o())),o}function Fe(e,t){let s=e.slice(t).find(e=>e);return s||(s=e.slice(0,t).reverse().find(e=>e)),s||""}function Pe(e,t){return"after"===e?t+1:t}function Me(...e){if(e.length<=1)return!0;for(let t=1;t<e.length;t++)if(!Ne(e[0],e[t]))return!1;return!0}function Ne(e,t){if(e===t)return!0;if(e&&!t||t&&!e)return!1;if(typeof e!=typeof t)return!1;if("object"!=typeof e)return!1;for(const s in t)if(!(s in e)&&void 0!==t[s])return!1;for(const s in e){if(typeof e[s]!=typeof t[s])return!1;if("object"==typeof e[s]){if(!Ne(e[s],t[s]))return!1}else if(e[s]!==t[s])return!1}return!0}function Le(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!Me(e[s],t[s]))return!1;return!0}function ke(e,t){if(e.length<t.length)return!1;const s=new Set(e);return t.every(e=>s.has(e))}function Ve(e){if(!e)return e;const t={...e};return Object.keys(t).forEach(e=>!t[e]&&delete t[e]),t}const Ue=["\t","\f","\v",String.fromCharCode(parseInt("00a0",16)),String.fromCharCode(parseInt("1680",16)),String.fromCharCode(parseInt("2000",16)),String.fromCharCode(parseInt("200a",16)),String.fromCharCode(parseInt("2028",16)),String.fromCharCode(parseInt("2029",16)),String.fromCharCode(parseInt("202f",16)),String.fromCharCode(parseInt("205f",16)),String.fromCharCode(parseInt("3000",16)),String.fromCharCode(parseInt("feff",16))],He=new RegExp(Ue.join("|"),"g"),ze=/(\r\n|\r)/g,Be=Ue.concat([" "]);function Ge(e){return e?e.replace(ze,X):""}function We(e){const 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 $e(e){const t=new Map,s=e.name?e.name+" (memoized)":"memoized";return{[s]:(...s)=>(t.has(s[0])||t.set(s[0],e(...s)),t.get(s[0]))}[s]}function qe(e,t){const s=new Set(t),o=[];for(let t=0;t<e.length;t++)s.has(t)||o.push(e[t]);return o}function Ze(e,t,s){return e.slice(0,s).concat(t).concat(e.slice(s))}function je(e,t,s){const o=[...e];return o[s]=t,o}function Ye(e,t,s){return t>s?Ye(e,s,t):e>=t&&e<=s}function Xe(e,t){let s=re(e);const o=t.matchCase?"":"i";return t.exactMatch&&(s=`^${s}$`),RegExp(s,o)}function Ke(e){let t=e.length;if(t<1e5)return Math.max(...e);let s=-1/0;for(;t--;)s=e[t]>s?e[t]:s;return s}function Je(e){let t=e.length;if(t<1e5)return Math.min(...e);let s=1/0;for(;t--;)s=e[t]<s?e[t]:s;return s}let Qe=class{text;currentIndex=0;current;constructor(e){this.text=e,this.current=e[0]}shift(){const 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 et(e,t=e=>e){const s=new Set;return e.filter(e=>{const o=t(e);return!s.has(o)&&(s.add(o),!0)})}function tt(e){const t={};for(const s in e)for(const o in e[s])t[o]||(t[o]={}),t[o][s]=e[s][o];return t}function st(e,t,s={}){const o=s.compute??((e,t)=>`${e} (${t})`),i=s.computeFirstOne??!1;let n=s.start??1,r=i?o(e,n):e;for(;t.includes(r);)r=o(e,n++);return r}function ot(e){return e.startsWith("=")||e.startsWith("+")}function it(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):it(Math.floor(e/26)-1)+it(e%26)}function nt(e){let t=0;const s=e.length;for(let o=0;o<s;o++){t=26*t+rt(e[o])}return t-1}function rt(e){const t=e.charCodeAt(0);return t>=65&&t<=90?t-64:t-96}function at(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function lt(e){return e>="0"&&e<="9"}const ct=nt("ZZZ"),ht=9999998;function dt(e){for(;" "===e.current;)e.advanceBy(1)}function ut(e){if("$"===e.current&&e.advanceBy(1),!e.current||!at(e.current))return-1;let t=0;for(;e.current&&at(e.current);)t=26*t+rt(e.shift());return t}function gt(e){if("$"===e.current&&e.advanceBy(1),!e.current||!lt(e.current))return-1;let t=0;for(;e.current&<(e.current);)t=10*t+Number(e.shift());return t}function pt(e){const t=new Qe(e);dt(t);const s=ut(t);if(-1===s||!t.current)throw new Error(`Invalid cell description: ${e}`);const o=gt(t);dt(t);const i=s-1,n=o-1;if(!t.isOver()||i>ct||n>ht)throw new Error(`Invalid cell description: ${e}`);return{col:i,row:n}}function mt(e,t,s={colFixed:!1,rowFixed:!1}){return(s.colFixed?"$":"")+it(e)+(s.rowFixed?"$":"")+String(t+1)}function ft(e,t=[]){if(e.length<=1&&0===t.length)return e;const s=[0],o=new Map([[0,[]]]);return vt(s,o,e,!1),vt(s,o,t,!0),function(e,t){const s=[];let o=[];for(let i=0;i<e.length;i++){const n=e[i],r=t.get(n);if(!r||0===r.length){s.push(...o),o=[];continue}let a=e[i+1];void 0!==a&&a--;const l=[];for(let e=0;e<r.length;e+=2){const t=r[e];let s=r[e+1];void 0!==s&&s--;const i={top:t,left:n,bottom:s,right:a,hasHeader:void 0===s&&0!==t||void 0===a&&0!==n};let c=!1;for(let e=o.length-1;e>=0;e--){const t=o[e];if(t.top===i.top&&t.bottom===i.bottom){t.right=i.right,o.splice(e,1),l.push(t),c=!0;break}}c||l.push(i)}s.push(...o),o=l}return s.push(...o),s}(s,o)}function vt(e,t,s,o=!1){for(const i of s){const s=i.left,n=void 0===i.right?void 0:i.right+1,r=bt(e,t,s,!0,0),a=bt(e,t,n,!1,r);for(let s=r;s<=a;s++){St(t.get(e[s]),i,o)}Ct(e,t,r,a)}}function bt(e,t,s,o,i){if(void 0===s)return e.length-1;const n=yt(e,s,i);return s!==e[n]?(e.splice(n+1,0,s),t.set(s,[...t.get(e[n])]),o?n+1:n):o?n:n-1}function St(e,t,s=!1){const o=t.top,i=void 0===t.bottom?void 0:t.bottom+1,n=[],r=yt(e,o,0,!1);if((r%2!=0&&!s||r%2==0&&s)&&n.push(o),void 0===i)return e.splice(r+1),void e.push(...n);const a=function(e,t,s=0,o=!0){let i=e.length-1,n=e.length;for(;s<=i;){const r=Math.floor((s+i)/2);if(e[r]===t&&o)return r;e[r]>t?(n=r,i=r-1):s=r+1}return n}(e,i,0,!1);(a%2==0&&!s||a%2!=0&&s)&&n.push(i),e.splice(r+1,a-r-1,...n)}function Ct(e,t,s,o){const i=s-1==-1?0:s-1;for(let s=o===e.length-1?o:o+1;s>i;s--)Le(t.get(e[s]),t.get(e[s-1]))&&(t.delete(e[s]),e.splice(s,1))}function yt(e,t,s=0,o=!0){let i=e.length-1,n=-1;for(;s<=i;){const r=Math.floor((s+i)/2);if(e[r]===t&&o)return r;e[r]<t?(n=r,s=r+1):i=r-1}return n}function It(e){const t=function(e){const t=new Qe(e);dt(t);const s=e.indexOf("!");-1!==s&&t.advanceBy(s+1);const o=ut(t),i=gt(t);let n,r,a,l,c=!1,h=!1,d=!1;if(-1===i?(a=l=o-1,n=r=0,c=!0):-1===o?(n=r=i-1,a=l=0,h=!0):(a=l=o-1,n=r=i-1,d=!0),dt(t),":"===t.current){t.advanceBy(1),dt(t);const e=ut(t),s=gt(t);-1===s?(l=e-1,c=!0):-1===e?(r=s-1,h=!0):(l=e-1,r=s-1,n=c?r:n,a=h?l:a,d=!0)}const u={top:n,left:a,bottom:c?void 0:r,right:h?void 0:l};return d=d&&(h||c),d&&(u.hasHeader=d),u}(e),s=Wt(t),o=s.bottom,i=s.right;if(void 0!==o&&o>ht||void 0!==i&&i>ct)throw new Error(`Range string out of bounds: ${e}`);if(void 0===o&&void 0===i)throw new Error("Wrong zone xc. The zone cannot be at the same time a full column and a full row");return s}function wt(e){const t=It(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function Et(e){try{return function(e){return Rt(It(e))}(e)}catch(e){return!1}}function Rt(e){const{bottom:t,top:s,left:o,right:i}=e;return!(void 0!==t&&isNaN(t)||isNaN(s)||isNaN(o)||void 0!==i&&isNaN(i))&&(xt(e)&&e.top>=0&&e.left>=0)}function xt(e){return(void 0===e.bottom||e.bottom>=e.top&&e.bottom>=0)&&(void 0===e.right||e.right>=e.left&&e.right>=0)}function Tt(e){const{top:t,bottom:s,left:o,right:i}=e,n="hasHeader"in e&&e.hasHeader,r=t===s&&o===i;if(void 0===s&&void 0!==i)return 0!==t||n?`${mt(o,t)}:${it(i)}`:`${it(o)}:${it(i)}`;if(void 0===i&&void 0!==s)return 0!==o||n?`${mt(o,t)}:${s+1}`:`${t+1}:${s+1}`;if(void 0!==s&&void 0!==i)return r?mt(o,t):`${mt(o,t)}:${mt(i,s)}`;throw new Error("Bad zone format")}function At(e,t,s,o,i){const n="left"===t?"columns":"rows",r="before"===o?s-1:s,a=e["left"===t?"right":"bottom"];return e[t]<=r&&a&&a>r?$t(e,n,"RESIZE",i):r<e[t]?$t(e,n,"MOVE",i):{...e}}function Dt(e,t,s,o,i){const n="left"===t?"columns":"rows",r="before"===o?s-1:s,a="left"===t?"right":"bottom";return e[t]<=r&&e[a]>r?$t(e,n,"RESIZE",i):r<e[t]?$t(e,n,"MOVE",i):{...e}}function _t(e,t,s){const o="left"===t?"right":"bottom";let i=e[t],n=e[o];for(const r of s.sort((e,t)=>t-e))e[t]>r&&(i--,n--),e[t]<r&&e[o]>=r&&n--;return{...e,[t]:i,[o]:n}}function Ot(e,t,s){const o="left"===t?"right":"bottom";let i=e[t],n=e[o];const r=e[o];for(const o of s.sort((e,t)=>t-e))e[t]>o&&(i--,void 0!==n&&n--),void 0!==r&&void 0!==n&&e[t]<=o&&r>=o&&n--;if(!(void 0!==n&&i>n))return{...e,[t]:i,[o]:n}}function Ft(...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 Pt(e,t){if(Lt(e,t))return{top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),bottom:void 0!==e.bottom?Math.min(e.bottom,t.bottom):e.bottom??t.bottom,right:void 0!==e.right?Math.min(e.right,t.right):e.right??t.right}}function Mt(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom&&e.hasHeader===t.hasHeader}function Nt(e,t){if(Pt(e,t))return;let s;return e.left===t.right+1&&(s={position:"left",start:Math.max(e.top,t.top),stop:void 0!==e.bottom?Math.min(e.bottom,t.bottom):t.bottom}),void 0!==e.right&&e.right+1===t.left&&(s={position:"right",start:Math.max(e.top,t.top),stop:void 0!==e.bottom?Math.min(e.bottom,t.bottom):t.bottom}),e.top===t.bottom+1&&(s={position:"top",start:Math.max(e.left,t.left),stop:void 0!==e.right?Math.min(e.right,t.right):t.right}),void 0!==e.bottom&&e.bottom+1===t.top&&(s={position:"bottom",start:Math.max(e.left,t.left),stop:void 0!==e.right?Math.min(e.right,t.right):t.right}),s&&s.start<=s.stop?s:void 0}function Lt(e,t){return!(void 0!==e.bottom&&e.bottom<t.top||void 0!==t.bottom&&t.bottom<e.top)&&!(void 0!==e.right&&e.right<t.left||void 0!==t.right&&t.right<e.left)}function kt(e,t,s){const{left:o,right:i,top:n,bottom:r}=s;return e>=o&&e<=i&&t>=n&&t<=r}function Vt(e,t){return Mt(Ft(t,e),t)}function Ut(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function Ht(e){const{numberOfCols:t,numberOfRows:s}=Ut(e);return 1===t||1===s}function zt(e){const t={};for(const s of e)t[s.sheetId]??=[],t[s.sheetId].push(Zt(s));for(const e in t)t[e]=ft(t[e]);return t}function Bt(e){const t=[],{left:s,right:o,top:i,bottom:n}=Wt(e);for(const e of ge(s,o+1))for(const s of ge(i,n+1))t.push({col:e,row:s});return t}function Gt(e,t){const s=[],{left:o,right:i,top:n,bottom:r}=Wt(t);for(const t of ge(o,i+1))for(const o of ge(n,r+1))s.push({sheetId:e,col:t,row:o});return s}function Wt(e){return void 0!==e.right&&e.left>e.right&&(e={...e,left:e.right,right:e.left}),void 0!==e.bottom&&e.top>e.bottom&&(e={...e,top:e.bottom,bottom:e.top}),e}function $t(e,t,s,o){const i="both"===t?o[0]:"columns"===t?o:0,n="both"===t?o[1]:"rows"===t?o:0,r="hasHeader"in e&&e.hasHeader;let a;a=Xt(e)&&!r?"rows"!==t:!(Yt(e)&&!r)||"columns"!==t;const l={...e};return a&&"MOVE"===s&&(l.left+=i,l.top+=n),void 0!==l.right&&(l.right+=i),void 0!==l.bottom&&(l.bottom+=n),l}function qt(e,t){let s,o;const{left:i,right:n,top:r,bottom:a}=e,{left:l,right:c,top:h,bottom:d}=t;return s=l!==i?l:c!==n?c:l,o=h!==r?h:d!==a?d:h,{col:s,row:o}}function Zt(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function jt(e){return{...e,right:e.left,bottom:e.top}}function Yt(e){return void 0===e.right}function Xt(e){return void 0===e.bottom}function Kt(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function Jt(e,t,s){return e.some(e=>function(e,t,s){return e.left<t&&t<=e.right||e.top<s&&s<=e.bottom}(e,t,s))}function Qt(e){return e.length<2||1===ft(e).length}function es(e){const t=[...e];let s=!0;for(;s;){s=!1;for(let e=0;e<t.length;e++){const o=t[e],i=t.findIndex((t,s)=>{return e!==s&&(n=o,((i=t).right+1===n.left||i.left===n.right+1?i.top<=n.bottom&&i.top>=n.top||n.top<=i.bottom&&n.top>=i.top:(i.bottom+1===n.top||i.top===n.bottom+1)&&(i.left<=n.right&&i.left>=n.left||n.left<=i.right&&n.left>=i.left))||Lt(t,o));var i,n});if(-1!==i){t[e]=Ft(t[i],o),t.splice(i,1),s=!0;break}}}return t}function ts(e,t){const s=Nt(e,t);if(!s)return[e];const o=[];switch(s.position){case"bottom":case"top":return o.push({top:e.top,bottom:e.bottom,left:s.start,right:s.stop}),s.start>e.left&&o.push({top:e.top,bottom:e.bottom,left:e.left,right:s.start-1}),(void 0===e.right||s.stop<e.right)&&o.push({top:e.top,bottom:e.bottom,left:s.stop+1,right:e.right}),o;case"left":case"right":return o.push({top:s.start,bottom:s.stop,left:e.left,right:e.right}),s.start>e.top&&o.push({top:e.top,bottom:s.start-1,left:e.left,right:e.right}),(void 0===e.bottom||s.stop<e.bottom)&&o.push({top:s.stop+1,bottom:e.bottom,left:e.left,right:e.right}),o}}function ss(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?Ot(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?At(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):e}function os(e,t){const s="DELETE_SHEET"===t.type&&t.sheetId;if("sheetId"in t&&e._sheetId!==t.sheetId)return e;{const o=ss(e._zone,t);if(o&&s!==e._sheetId)return{...e,_zone:o}}}let is=class{content={};add(e,t){if(e in this.content)throw new Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(e,t){return this.content[e]=t,this}get(e){const t=this.content[e];if(!t&&!(e in this.content))throw new 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]}};const ns=/(.*?)\((.*?)\)(.*)/,rs=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META","RANGE<META>"];function as(e,t="",s){return function(e,t,s){const o=e.match(ns),i=o[1].trim();if(!i)throw new Error(`Function argument definition is missing a name: '${e}'.`);const n=[];let r,a=!1,l=!1;for(const e of o[2].split(",")){const t=e.trim().toUpperCase(),s=rs.find(e=>t===e);s?n.push(s):"RANGE<ANY>"===t?n.push("RANGE"):"OPTIONAL"===t?a=!0:"REPEATING"===t?l=!0:t.startsWith("DEFAULT=")&&(r=e.trim().slice(8))}const c={name:i,description:t,type:n};(n.includes("ANY")||n.includes("RANGE"))&&(c.acceptErrors=!0);a&&(c.optional=!0);l&&(c.repeating=!0);void 0!==r&&(c.default=!0,c.defaultValue=r);n.some(e=>e.startsWith("RANGE"))&&(c.acceptMatrix=!0);n.every(e=>e.startsWith("RANGE"))&&(c.acceptMatrixOnly=!0);s&&s.length>0&&(c.proposalValues=s);return c}(e,t,s)}const ls={};function cs(e,t){const s=e.name,o=ls[s]?.[t];return o||(ls[s]||(ls[s]={}),ls[s][t]||(ls[s][t]=function(e,t){const s={},o=e.nbrArgRepeating?Math.floor((t-e.minArgRequired)/e.nbrArgRepeating):0,i=e.nbrArgRepeating*o,n=t-e.minArgRequired-i;let r=0,a=0;for(let t=0;t<e.args.length;t++){const i=e.args[t];if(i.optional||i.default)a<n&&(s[r]=t,r++),a++;else if(i.repeating){for(let i=0;i<o;i++)for(let o=0;o<e.nbrArgRepeating;o++)s[r]=t+o,r++;t+=e.nbrArgRepeating-1}else s[r]=t,r++}return e=>s[e]}(e,t)),ls[s][t])}const hs=["META","RANGE<META>"];const ds=e=>e,us=()=>!1;let gs=ds,ps=us;function ms(e,...t){if(1!==t.length||"object"!=typeof t[0]||t[0]instanceof String)t.length>0&&(e=e.replace(/\%s/g,()=>t.shift()));else{const s=t[0];e=e.replace(/\%\(([^\)]+)\)s/g,(e,t)=>s[t])}return e}const fs=function(e,...t){return ps()?ms(gs(e),...t):new vs(e,t)};let vs=class extends String{values;constructor(e,t){super(e),this.values=t}valueOf(){const e=super.valueOf();return ps()?ms(gs(e),...this.values):ms(e,...this.values)}toString(){return this.valueOf()}};const bs={NotAvailable:"#N/A",InvalidReference:"#REF",BadExpression:"#BAD_EXPR",CircularDependency:"#CYCLE",UnknownFunction:"#NAME?",DivisionByZero:"#DIV/0!",SpilledBlocked:"#SPILL!",GenericError:"#ERROR",NullError:"#NULL!"},Ss=new Set(Object.values(bs));class Cs{message;value;constructor(e=fs("Error"),t=bs.GenericError){this.message=e,this.value=t,this.message=e.toString()}}class ys extends Cs{constructor(e=fs("Invalid expression")){super(e,bs.BadExpression)}}class Is extends Cs{constructor(e=fs("Circular reference")){super(e,bs.CircularDependency)}}class ws extends Cs{constructor(e=fs("Invalid reference")){super(e,bs.InvalidReference)}}class Es extends Cs{constructor(e=fs("Data not available")){super(e,bs.NotAvailable)}}class Rs extends Cs{constructor(e=fs("Unknown function")){super(e,bs.UnknownFunction)}}class xs extends Cs{constructor(e=fs("Spill range is not empty")){super(e,bs.SpilledBlocked)}}class Ts extends Cs{constructor(e=fs("Division by zero")){super(e,bs.DivisionByZero)}}const As=["thin","medium","thick","dashed","dotted"];function Ds(e){return Array.isArray(e)&&Array.isArray(e[0])}var _s;!function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(_s||(_s={}));let Os=class e{jsDate;constructor(e,t,s,o=0,i=0,n=0){this.jsDate=new Date(Date.UTC(e,t,s,o,i,n,0))}static fromTimestamp(t){const s=new Date(t);return new e(s.getUTCFullYear(),s.getUTCMonth(),s.getUTCDate(),s.getUTCHours(),s.getUTCMinutes(),s.getUTCSeconds())}static now(){const 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(){const e=new Date(this.jsDate.getTime()),t=e.getUTCDay()||7;e.setUTCDate(e.getUTCDate()+4-t);const s=new Date(Date.UTC(e.getUTCFullYear(),0,1));return Math.ceil(((e.getTime()-s.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)}};const Fs=new Os(1899,11,30),Ps=864e5,Ms=2e3,Ns=Os.now().getFullYear(),Ls=Os.now().getMonth(),ks=Os.fromTimestamp(0).getTime()-Fs.getTime(),Vs=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,Us=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,Hs=Be.join(""),zs=new RegExp(`/|-|${Be.join("|")}`),Bs=new RegExp(`^(\\d{1,4})[/${Hs}-](\\d{1,4})([/${Hs}-](\\d{1,4}))?$`),Gs=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function Ws(e,t){switch(typeof e){case"number":return e;case"string":return $s(e,t)?Zs(e,t)?.value:!e||isNaN(Number(e))?void 0:Number(e);default:return}}function $s(e,t){return null!==Zs(e,t)}const qs=new Map;function Zs(e,t){return qs.has(t)||qs.set(t,new Map),qs.get(t).has(e)||qs.get(t).set(e,function(e,t){e=e.trim();let s=null;const o=e.match(Gs);if(o){if(s=function(e){if(e=e.trim(),Gs.test(e)){const t=/AM/i.test(e),s=/PM/i.test(e),o=(t||s?e.substring(0,e.length-2).trim():e).split(/:/),i=o.length>=2,n=3===o.length;let r=Number(o[0]),a=i?Number(o[1]):0,l=n?Number(o[2]):0,c=n?"hh:mm:ss":"hh:mm";if(t||s)c+=" a";else if(!i)return null;r>=12&&t?r-=12:r<12&&s&&(r+=12),a+=Math.floor(l/60),l%=60,r+=Math.floor(a/60),a%=60,r>=24&&(c="hhhh:mm:ss");return{value:r/24+a/1440+l/86400,format:c,jsDate:new Os(1899,11,30,r,a,l)}}return null}(o[0]),null===s)return null;e=e.replace(o[0],"").trim()}let i=null;const n=function(e,t){const s=e.match(Bs);if(!s)return null;const[,o,i,,n]=s;if(o.length>2&&n&&n.length>2)return null;if(o.length>2)return{year:o,month:i,day:n,dateString:e,type:"ymd"};const r=function(e){switch(e.dateFormat[0]){case"d":return"dmy";case"m":return"mdy";case"y":return"ymd"}throw new Error("Invalid date format in locale")}(t);if(!n)return i.length>2?{month:o,year:i,day:void 0,dateString:e,type:r}:"dmy"===r?{day:o,month:i,year:n,dateString:e,type:"dmy"}:{month:o,day:i,year:n,dateString:e,type:"mdy"};if(n.length>2)return"mdy"===r?{month:o,day:i,year:n,dateString:e,type:"mdy"}:{day:o,month:i,year:n,dateString:e,type:"dmy"};if("mdy"===r)return{month:o,day:i,year:n,dateString:e,type:"mdy"};if("ymd"===r)return{year:o,month:i,day:n,dateString:e,type:"ymd"};if("dmy"===r)return{day:o,month:i,year:n,dateString:e,type:"dmy"};return null}(e,t);if(n){const t=n.dateString.match(zs)[0];if(i=function(e,t){const{year:s,month:o,day:i}=e,n=function(e){if(!e)return Ls;const t=Number(e);if(t>=1&&t<=12)return t-1;return null}(o),r=function(e){if(!e)return 1;const t=Number(e);if(t>=0&&t<=31)return t;return null}(i),a=function(e){if(!e)return Ns;const t=Number(e);switch(e.length){case 1:return Ms+t;case 2:return Ms+(Ms+t>Ns+10?-100:0)+t;case 3:case 4:return t}return null}(s);if(null===a||null===n||null===r)return null;const l=2===o?.length&&n+1<10||2===i?.length&&r<10,c=2!==s?.length,h=new Os(a,n,r);if(h.getMonth()!==n||h.getDate()!==r)return null;const d=h.getTime()-Fs.getTime(),u=function(e,t,s,o){const i=e.year?o?"yyyy":"yy":void 0,n=e.month?s?"mm":"m":void 0,r=e.day?s?"dd":"d":void 0;switch(e.type){case"mdy":return[n,r,i].filter(Te).join(t);case"ymd":return[i,n,r].filter(Te).join(t);case"dmy":return[r,n,i].filter(Te).join(t)}}(e,t,l,c);return{value:Math.round(d/Ps),format:u,jsDate:h}}(n,t),null===i)return null;e=e.replace(n.dateString,"").trim()}if(""!==e||!i&&!s)return null;if(i&&i.jsDate&&s&&s.jsDate)return{value:i.value+s.value,format:i.format+" "+("hhhh:mm:ss"===s.format?"hh:mm:ss":s.format),jsDate:new Os(i.jsDate.getFullYear()+s.jsDate.getFullYear()-1899,i.jsDate.getMonth()+s.jsDate.getMonth()-11,i.jsDate.getDate()+s.jsDate.getDate()-30,i.jsDate.getHours()+s.jsDate.getHours(),i.jsDate.getMinutes()+s.jsDate.getMinutes(),i.jsDate.getSeconds()+s.jsDate.getSeconds())};return i||s}(e,t)),qs.get(t).get(e)}function js(e){const t=Math.trunc(e),s=Os.fromTimestamp(t*Ps-ks);let o=e-t;o=o<0?1+o:o;const i=Math.round(24*o),n=Math.round(24*(o-i/24)*60),r=Math.round(24*(o-i/24-n/24/60)*60*60);return s.setHours(i),s.setMinutes(n),s.setSeconds(r),s}function Ys(e){return Math.round(Xs(e))}function Xs(e){return(e.getTime()-Fs.getTime())/Ps}function Ks(e){return new Os(e.getFullYear(),e.getMonth()+1,0).getDate()}function Js(e){return Ks(e)===e.getDate()}function Qs(e,t,s){const o=e.getFullYear(),i=e.getMonth(),n=e.getDate(),r=new Os(o,i+t,1);return s&&n===Ks(e)||n>Ks(r)?r.setDate(Ks(r)):r.setDate(n),r}function eo(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function to(e,t,s){if(e===t)return 0;if(e>t){const s=t;t=e,e=s}const o=js(e),i=js(t);let n=o.getDate(),r=i.getDate();const a=o.getMonth(),l=i.getMonth(),c=o.getFullYear(),h=i.getFullYear();let d=0,u=0;switch(s){case 0:31===n&&(n=30),30===n&&31===r&&(r=30),1===a&&n===(eo(c)?29:28)&&(n=30,1===l&&r===(eo(h)?29:28)&&(r=30)),d=c+(30*a+n)/360,u=h+(30*l+r)/360;break;case 1:let s=365;const o=c===h;if(!o&&!(c+1===h)||!o&&a<l||!o&&a===l&&n<r){let e=0,t=0;for(let s=c;s<=h;s++)e++,t+=eo(s)?366:365;s=t/e}else o?eo(c)&&(s=366):(eo(c)&&a<2&&(s=366),eo(h)&&(l>1||1===l&&29===r)&&(s=366));d=e/s,u=t/s;break;case 2:d=e/360,u=t/360;break;case 3:d=e/365,u=t/365;break;case 4:31===n&&(n=30),31===r&&(r=30),d=c+(30*a+n)/360,u=h+(30*l+r)/360}return u-d}function so(e,t){const s=12*(t.getFullYear()-e.getFullYear())+t.getMonth()-e.getMonth();return e.getDate()>t.getDate()?s-1:s}function oo(e,t){const s=e.getTime(),o=t.getTime();return Math.floor((o-s)/Ps)}function io(e,t){const s=t.getFullYear()-e.getFullYear(),o=e.getMonth(),i=t.getMonth(),n=e.getDate(),r=t.getDate();return i>o||i===o&&r>=n?s:s-1}function no(e,t,s){return t>s?no(e,s,t):(e=Math.trunc(e),t=Math.trunc(t),s=Math.trunc(s),e>=t&&e<=s)}const ro=$e(function(e){return e=re(e),new RegExp(`(?:^-?\\d+(?:${e}?\\d*(?:e(\\+|-)?\\d+)?)?|^-?${e}\\d+)(?!\\w|!)`)}),ao=$e(function(e){const t=re(e.decimalSeparator),s="(?:\\s*"+`(?:\\d+(?:${re(e.thousandsSeparator||"")}\\d{3,})*(?:${t}\\d*)?)`+"|"+`(?:${t}\\d+)`+")(?:e(?:\\+|-)?\\d+)?(?:\\s*%)?",o="(?:\\s*-)?",i="(?:\\s*[\\$€])?",n="^(?:(?:"+[o+i+s,o+s+i,i+o+s].join(")|(?:")+"))$";return new RegExp(n,"i")});function lo(e,t){return!!e&&ao(t).test(e.trim())}const co=$e(function(e){return new RegExp(`[$€${re(e.thousandsSeparator||"")}]`,"g")});function ho(e,t){e=e.replace(co(t),""),"."!==t.decimalSeparator&&(e=e.replace(t.decimalSeparator,"."));let s=Number(e);return isNaN(s)&&e.includes("%")&&(s=Number(e.split("%")[0]),!isNaN(s))?s/100:s}function uo(e,t,s){const o=[...e].sort((e,t)=>e-t);let i=(o.length+(s?-1:1))*t;if(s||i--,Number.isInteger(i))return o[i];const n=Math.ceil(i),r=Math.floor(i);return o[n]*(i-r)+o[r]*(n-i)}const go=["number","string","boolean","undefined"];function po(e){if(void 0!==e)return Ds(e)?e[0][0]?.format:e.format}function mo(e){return"string"==typeof e&&Ss.has(e)}function fo(e){return{value:bs.NotAvailable,message:fs("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",Eo(e))}}const vo=e=>fs("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function bo(e,t){const s=Do(e);switch(typeof s){case"number":return s;case"boolean":return s?1:0;case"string":if(lo(s,t)||""===s)return ho(s,t);const e=Zs(s,t);if(e)return e.value;throw new Cs(vo(s));default:return 0}}function So(e,t){try{return bo(e,t)}catch(e){return}}function Co(e,t){return Xo(e).map(e=>e.map(e=>{if("number"!=typeof e.value){let s="";throw"object"==typeof e?s=fs("Function [[FUNCTION_NAME]] expects number values for %s, but got an empty value.",t):"string"==typeof e?s=fs("Function [[FUNCTION_NAME]] expects number values for %s, but got a string.",t):"boolean"==typeof e&&(s=fs("Function [[FUNCTION_NAME]] expects number values for %s, but got a boolean.",t)),new Cs(s)}return e.value}))}function yo(e,t){const s=Do(e);if(""===s)throw new Cs(vo(s));return bo(s,t)}function Io(e,t){return Math.trunc(bo(e,t))}function wo(e,t){return Math.trunc(yo(e,t))}function Eo(e){const t=Do(e);switch(typeof t){case"string":return t;case"number":return t.toString();case"boolean":return t?"TRUE":"FALSE";default:return""}}const Ro=$e(function(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"")}),xo=e=>fs("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a boolean.",e);function To(e){const t=Do(e);switch(typeof t){case"boolean":return t;case"string":if(t){const e=t.toUpperCase();if("TRUE"===e)return!0;if("FALSE"===e)return!1;throw new Cs(xo(t))}return!1;case"number":return!!t;default:return!1}}function Ao(e,t){return js(bo(Do(e),t))}function Do(e){if("object"==typeof e&&null!==e&&"value"in e){if(mo(e.value))throw e;return e.value}if(mo(e))throw new Cs("",e);return e}function _o(e,t,s){for(const o of e)if(Ds(o)){const e=o.length,s=o[0].length;for(let i=0;i<s;i++)for(let s=0;s<e;s++)t(o[s][i])}else s(o)}function Oo(e,t){_o(e,e=>{if(mo(e.value))throw e;t(e)},e=>{if(mo(e?.value))throw e;t(e)})}function Fo(e,t,s){_o(e,e=>{if("number"==typeof e?.value&&t(e),mo(e?.value))throw e},e=>{t({value:yo(e,s),format:e?.format})})}function Po(e,t,s,o,i="rowFirst"){let n=o;for(const o of e)if(Ds(o)){const e=o.length,s=o[0].length;if("rowFirst"===i)for(let i=0;i<s;i++)for(let s=0;s<e;s++)n=t(n,o[s][i]);else for(let i=0;i<e;i++)for(let e=0;e<s;e++)n=t(n,o[i][e])}else n=s(n,o);return n}function Mo(e,t,s,o="rowFirst"){return Po(e,t,t,s,o)}function No(e,t,s,o){return Po(e,(e,s)=>{const o=s?.value;if("number"==typeof o)return t(e,o);if(mo(o))throw s;return e},(e,s)=>t(e,yo(s,o)),s)}function Lo(e,t,s,o){return Po(e,(e,s)=>{const i=s?.value;if(null!=i){if("number"==typeof i)return t(e,i);if("boolean"==typeof i)return t(e,bo(i,o));if(mo(i))throw s;return t(e,0)}return e},(e,s)=>t(e,bo(s,o)),s)}function ko(e,t,s){const o=Array(e);for(let i=0;i<e;i++){o[i]=Array(t);for(let e=0;e<t;e++)o[i][e]=s(i,e)}return o}function Vo(e,t){return 0===e.length?[]:ko(e.length,e[0].length,(s,o)=>t(e[s][o]))}function Uo(e){return e.length?ko(e[0].length,e.length,(t,s)=>e[s][t]):[]}function Ho(e,t,s=void 0){let o,i=1,n=1,r=1/0,a=1/0;for(let e=0;e<t.length;e++){const l=t[e];if(Ds(l)&&(void 0===s||s[e])){const s=l.length,c=l[0].length;1!==s||1!==c?(o??=new Array(t.length),1!==s&&1!==c?(o[e]="matrix",i=Math.max(i,s),n=Math.max(n,c),r=Math.min(r,s),a=Math.min(a,c)):1!==s?(o[e]="horizontal",i=Math.max(i,s),r=Math.min(r,s)):1!==c&&(o[e]="vertical",n=Math.max(n,c),a=Math.min(a,c))):t[e]=l[0][0]}}if(1===i&&1===n)return e(...t);return ko(i,n,(s,i)=>{if(s>r-1||i>a-1)return new Es(fs("Array arguments to [[FUNCTION_NAME]] are of different size."));const n=e(...(l=s,c=i,t.map((e,t)=>{switch(o?.[t]){case"matrix":return e[l][c];case"horizontal":return e[l][0];case"vertical":return e[0][c];case void 0:return e}})));var l,c;return Ds(n)?n[0][0]:n})}function zo(e,t){return function(e,t,s){for(const o of e)if(Ds(o)){const e=o.length,s=o[0].length;for(let i=0;i<s;i++)for(let s=0;s<e;s++)if(!t(o[s][i]??void 0))return}else if(!s(o))return}(e,e=>{const s=e?.value;if("boolean"==typeof s)return t(s);if("number"==typeof s)return t(!!s);if(mo(s))throw e;return!0},e=>void 0===e||null===e.value||t(function(e){const t=Do(e);if(""===t)throw new Cs(xo(t));return To(t)}(e)))}function Bo(e,t){let s,o,i=e.substring(0,2);return"<="===i||">="===i||"<>"===i?(s=i,o=e.substring(2)):(i=e.substring(0,1),"<"===i||">"===i||"="===i?(s=i,o=e.substring(1)):(s="=",o=e)),lo(o,t)||$s(o,t)?o=bo(o,t):"TRUE"!==o&&"FALSE"!==o||(o=To(o)),{operator:s,operand:o}}const Go=$e(function(e){if("*"===e)return/.+/;let t="",s="";for(const o of e)"?"===o&&"~"!==s?t+=".":"*"===o&&"~"!==s?t+=".*":("*"!==o&&"?"!==o||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(o)&&(t+="\\"),t+=o),s=o;return new RegExp("^"+t+"$","i")});function Wo(e="",t,s){const{operator:o,operand:i}=t;if(void 0===i||null===e||null===i)return!1;if("number"==typeof i&&"="===o)return"string"==typeof e&&(lo(e,s)||$s(e,s))?bo(e,s)===i:e===i;if("<>"===o||"="===o){let t;return t=typeof e==typeof i&&("string"==typeof e&&"string"==typeof i?Go(i).test(e):e===i),"="===o?t:!t}if(typeof e==typeof i)switch(o){case"<":return e<i;case">":return e>i;case"<=":return e<=i;case">=":return e>=i}return!1}function $o(e,t,s,o=!1){const i=e.length;if(i%2==1)throw new Cs(fs("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const n=Xo(e[0]),r=n.length,a=n[0].length,l=[];for(let t=0;t<i-1;t+=2){const i=Xo(e[t]);if(i.length!==r||i[0].length!==a)throw new Cs(fs("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const n=Bo(Eo(e[t+1]),s);o&&"string"==typeof n.operand&&(n.operand+="*"),l.push(n)}for(let o=0;o<r;o++)for(let n=0;n<a;n++){let r=!0;for(let t=0;t<i-1;t+=2){if(r=Wo(Xo(e[t])[o][n].value??void 0,l[t/2],s),!r)break}r&&t(o,n)}}function qo(e,t,s,o,i,n){if(void 0===t||null===t.value)return-1;if(mo(t.value))throw t;const r=jo(t.value),a=typeof r;let l,c,h,d,u,g,p=0,m=i-1;const f="desc"===o?t=>jo(n(e,i-t-1)):t=>jo(n(e,t));for(;m-p>=0;){for(h=Math.floor((p+m)/2),d=h,u=f(d),g=typeof u;p<d&&a!==g;)d--,u=f(d),g=typeof u;g===a&&null!=u?("strict"===s&&u===r?(l=u,c=d):"nextSmaller"===s&&u<=r?(null==l||l<u||l===u&&c<d)&&(l=u,c=d):"nextGreater"===s&&u>=r&&(void 0===l||l>u||l===u&&c<d)&&(l=u,c=d),u>r||"strict"===s&&u===r?m=d-1:p=h+1):p=h+1}return void 0===c?-1:"desc"===o?i-c-1:c}function Zo(e,t,s,o,i,n,r=!1){if(void 0===t||null===t.value)return-1;if(mo(t.value))throw t;const a=jo(t.value),l=r?(e,t)=>jo(i(e,o-t-1)):(e,t)=>jo(i(e,t)),c="wildcard"!==s||"string"!=typeof a||!(a.includes("*")||a.includes("?"));if(n&&c){const t=r?"reverseSearch":"forwardSearch";let i=n[t].get(e);if(void 0===i){i=new Map;for(let t=0;t<o;t++){const s=l(e,t)??null;i.has(s)||i.set(s,t)}n[t].set(e,i)}if(i.has(a)){const e=i.get(a);return r?o-e-1:e}if("strict"===s)return-1}const h=function(e,t,s,o,i){let n=s=>i(e,s)===t;if("wildcard"===s&&"string"==typeof t&&(t.includes("*")||t.includes("?"))){const s=Go(t);n=t=>{const o=i(e,t);return"string"==typeof o&&s.test(o)}}let r,a=-1;"nextSmaller"===s&&(n=s=>{const o=i(e,s);return(!r&&Yo(t,o)>=0||Yo(t,o)>=0&&Yo(o,r)>0)&&(r=o,a=s),o===t});"nextGreater"===s&&(n=s=>{const o=i(e,s);return(!r&&Yo(t,o)<=0||Yo(t,o)<=0&&Yo(o,r)<0)&&(r=o,a=s),o===t});for(let e=0;e<o;e++)if(n(e))return e;return a}(e,a,s,o,l);return r&&-1!==h?o-h-1:h}function jo(e){return"string"==typeof e?Ro(e):e}function Yo(e,t){let s=go.indexOf(typeof e)-go.indexOf(typeof t);return 0===s&&("string"==typeof e&&"string"==typeof t?s=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?s=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(s=Number(e)-Number(t))),s}function Xo(e){return void 0===e?[[]]:Ds(e)?e:[[e]]}function Ko(e,t){return Mo(e,(e,s)=>(e.push(t(s)),e),[],"rowFirst")}function Jo(e){if(void 0===e)return!1;const{value:t}=e;return null!==t&&""!==t}const Qo=fs("[[FUNCTION_NAME]] has no valid input data.");function ei(e){return fs("[[FUNCTION_NAME]] expects the provided values of %(argName)s to be a non-empty matrix.",{argName:e})}function ti(e){function t(...t){for(let s=0;s<t.length;s++){const o=t[s],i=cs(e,t.length);if(!e.args[i(s)||s].acceptErrors&&!Ds(o)&&mo(o?.value))return o}try{return s.apply(this,t)}catch(t){return si(t,e.name)}}function s(...t){this.debug;const s=e.compute.apply(this,t);return Ds(s)?"object"==typeof s[0][0]&&null!==s[0][0]&&"value"in s[0][0]?(function(e,t){const s=e.length,o=e[0]?.length??0;for(let i=0;i<s;i++)for(let s=0;s<o;s++)t(e[i][s])}(s,t=>oi(t,e.name)),s):Vo(s,e=>({value:e})):"object"==typeof s&&null!==s&&"value"in s?(oi(s,e.name),s):{value:s}}return function(...s){const o=[],i=cs(e,s.length);for(let t=0;t<s.length;t++){const n=i(t)??-1,r=e.args[n];if(!Ds(s[t])&&r.acceptMatrixOnly)throw new ys(fs("Function %s expects the parameter '%s' to be reference to a cell or range.",e.name,(t+1).toString()));o.push(!r.acceptMatrix)}return Ho(t.bind(this),s,o)}}function si(e,t){return s=e,void 0!==s?.value&&"string"==typeof s.value&&mo(e.value)?(ni(e)&&oi(e,t),e):(console.error(e),new Cs(ii+(ni(e)?" "+e.message:"")));var s}function oi(e,t){e.message?.includes("[[FUNCTION_NAME]]")&&(e.message=e.message.replace("[[FUNCTION_NAME]]",t))}const ii=fs("An unexpected error occurred. Submit a support ticket at odoo.com/help.");function ni(e){return void 0!==e?.message&&"string"==typeof e.message}function ri(e,t){if(!e)throw new Cs(t)}function ai(e,t=fs("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")){if(0===e)throw new Ts(t)}function li(e){return 1===e.length||1===e[0].length}function ci(...e){if(e.every(Ds)){const t=e[0].length,s=e[0][0].length;for(const o of e)if(o.length!==t||o[0].length!==s)return!1;return!0}return!e.some(e=>Array.isArray(e)&&(1!==e.length||1!==e[0].length))}function hi(e){return e.length===e[0].length}const di=e=>fs("The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.",e);function ui(e){const t=Array(e);for(let s=0;s<e;s++)t[s]=Array(e).fill(0),t[s][s]=1;return t}function gi(e){if(e.length<1||e[0].length<1)throw new Error("invertMatrix: an empty matrix cannot be inverted.");if(e.length!==e[0].length)throw new Error("invertMatrix: only square matrices are invertible");let t=1;const s=e.length,o=ui(s),i=e.map(e=>e.slice());for(let e=0;e<s;e++){let n=i[e][e];if(0===n){for(let n=e+1;n<s;n++)if(0!==i[e][n]){pi(i,e,n),pi(o,e,n),t*=-1;break}if(n=i[e][e],0===n)return{determinant:0}}for(let t=0;t<s;t++)i[t][e]=i[t][e]/n,o[t][e]=o[t][e]/n;t*=n;for(let t=0;t<s;t++){if(t===e)continue;const n=i[e][t];for(let r=0;r<s;r++)i[r][t]-=n*i[r][e],o[r][t]-=n*o[r][e]}}return{inverted:o,determinant:t}}function pi(e,t,s){for(let o=0;o<e.length;o++){const i=e[o][t];e[o][t]=e[o][s],e[o][s]=i}}function mi(e,t){if(e.length<1||t.length<1)throw new Error("multiplyMatrices: empty matrices cannot be multiplied.");if(e.length!==t[0].length)throw new Error("multiplyMatrices: incompatible matrices size.");const s=e[0].length,o=t.length,i=e.length,n=Array(o);for(let r=0;r<o;r++){n[r]=Array(s);for(let o=0;o<s;o++){let s=0;for(let n=0;n<i;n++)s+=e[n][o]*t[r][n];n[r][o]=s}}return n}function fi(e){if(!Ds(e))return e;if(!vi(e))throw new Error("The value should be a scalar or a 1x1 matrix");return e[0][0]}function vi(e){return 1===e.length&&1===e[0].length}function bi(e){return Ds(e)&&!vi(e)}const Si={description:fs("Returns a result array constrained to a specific width and height."),args:[as("input_range (any, range<any>)",fs("The range to constrain.")),as("rows (number)",fs("The number of rows in the constrained array.")),as("columns (number)",fs("The number of columns in the constrained array."))],compute:function(e,t,s){const o=Xo(e),i=Io(t?.value,this.locale),n=Io(s?.value,this.locale);if(i<=0)return new Cs(fs("The rows argument (%s) must be strictly positive.",i.toString()));if(n<=0)return new Cs(fs("The columns argument (%s) must be strictly positive.",n.toString()));const r=Math.min(i,o[0].length);return ko(Math.min(n,o.length),r,(e,t)=>o[e][t])},isExported:!1},Ci={description:fs("Creates a new array from the selected columns in the existing range."),args:[as("array (any, range<any>)",fs("The array that contains the columns to be returned.")),as("col_num (number, range<number>)",fs("The first column index of the columns to be returned.")),as("col_num2 (number, range<number>, repeating)",fs("The columns indexes of the columns to be returned."))],compute:function(e,...t){const s=Xo(e),o=Ko(t,e=>Io(e?.value,this.locale)),i=o.filter(e=>0===e||s.length<Math.abs(e));if(0!==i.length)return new Cs(fs("The columns arguments must be between -%s and %s (got %s), excluding 0.",s.length.toString(),s.length.toString(),i.join(",")));const n=Array(o.length);for(let e=0;e<o.length;e++)o[e]>0?n[e]=s[o[e]-1]:n[e]=s[s.length+o[e]];return n},isExported:!0},yi={description:fs("Creates a new array from the selected rows in the existing range."),args:[as("array (any, range<any>)",fs("The array that contains the rows to be returned.")),as("row_num (number, range<number>)",fs("The first row index of the rows to be returned.")),as("row_num2 (number, range<number>, repeating)",fs("The rows indexes of the rows to be returned."))],compute:function(e,...t){const s=Xo(e),o=Ko(t,e=>Io(e?.value,this.locale)),i=s.length,n=o.filter(e=>0===e||s[0].length<Math.abs(e));return 0!==n.length?new Cs(fs("The rows arguments must be between -%s and %s (got %s), excluding 0.",s[0].length.toString(),s[0].length.toString(),n.join(","))):ko(i,o.length,(e,t)=>o[t]>0?s[e][o[t]-1]:s[e][s[e].length+o[t]])},isExported:!0},Ii={description:fs("Expands or pads an array to specified row and column dimensions."),args:[as("array (any, range<any>)",fs("The array to expand.")),as("rows (number)",fs("The number of rows in the expanded array. If missing, rows will not be expanded.")),as("columns (number, optional)",fs("The number of columns in the expanded array. If missing, columns will not be expanded.")),as("pad_with (any, default=0)",fs("The value with which to pad."))],compute:function(e,t,s,o={value:0}){const i=Xo(e),n=Io(t?.value,this.locale),r=void 0!==s?Io(s.value,this.locale):i.length;return n<i[0].length?new Cs(fs("The rows arguments (%s) must be greater or equal than the number of rows of the array.",n.toString())):r<i.length?new Cs(fs("The columns arguments (%s) must be greater or equal than the number of columns of the array.",r.toString())):ko(r,n,(e,t)=>e>=i.length||t>=i[e].length?o:i[e][t])},isExported:!0},wi={description:fs("Flattens all the values from one or more ranges into a single column."),args:[as("range (any, range<any>)",fs("The first range to flatten.")),as("range2 (any, range<any>, repeating)",fs("Additional ranges to flatten."))],compute:function(...e){return[Ko(e,e=>void 0===e?{value:""}:e)]},isExported:!1},Ei={description:fs("Calculates the frequency distribution of a range."),args:[as("data (range<number>)",fs("The array of ranges containing the values to be counted.")),as("classes (number, range<number>)",fs("The range containing the set of classes."))],compute:function(e,t){const s=Ko([e],e=>e.value).filter(e=>"number"==typeof e),o=Ko([t],e=>e.value).filter(e=>"number"==typeof e),i=o.map((e,t)=>({initialIndex:t,value:e,count:0})).sort((e,t)=>e.value-t.value);i.push({initialIndex:i.length,value:1/0,count:0});const n=s.sort((e,t)=>e-t);let r=0;for(const e of n){for(;e>i[r].value&&r<i.length-1;)r++;i[r].count++}return[i.sort((e,t)=>e.initialIndex-t.initialIndex).map(e=>e.count)]},isExported:!0},Ri={description:fs("Appends ranges horizontally and in sequence to return a larger array."),args:[as("range1 (any, range<any>)",fs("The first range to be appended.")),as("range2 (any, range<any>, repeating)",fs("Additional ranges to add to range1."))],compute:function(...e){const t=Math.max(...e.map(e=>e?.[0]?.length??0)),s=[];for(const o of e){const e=Xo(o);for(let o=0;o<e.length;o++){const i=Array(t).fill({value:null});for(let t=0;t<e[o].length;t++)i[t]=e[o][t];s.push(i)}}return s},isExported:!0},xi={description:fs("Returns the matrix determinant of a square matrix."),args:[as("square_matrix (number, range<number>)",fs("An range with an equal number of rows and columns representing a matrix whose determinant will be calculated."))],compute:function(e){const t=Co(e,"square_matrix");return hi(t)?gi(t).determinant:new Cs(fs("The argument square_matrix must have the same number of columns and rows."))},isExported:!0},Ti={description:fs("Returns the multiplicative inverse of a square matrix."),args:[as("square_matrix (number, range<number>)",fs("An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated."))],compute:function(e){const t=Co(e,"square_matrix");if(!hi(t))return new Cs(fs("The argument square_matrix must have the same number of columns and rows."));const{inverted:s}=gi(t);return s||new Cs(fs("The matrix is not invertible."))},isExported:!0},Ai={description:fs("Calculates the matrix product of two matrices."),args:[as("matrix1 (number, range<number>)",fs("The first matrix in the matrix multiplication operation.")),as("matrix2 (number, range<number>)",fs("The second matrix in the matrix multiplication operation."))],compute:function(e,t){const s=Co(e,"matrix1"),o=Co(t,"matrix2");return 0===s.length||0===o.length?new Cs(fs("The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.")):s.length!==o[0].length?new Cs(fs("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).",s.length.toString(),o[0].length.toString())):mi(s,o)},isExported:!0},Di={description:fs("Calculates the sum of the products of corresponding entries in equal-sized ranges."),args:[as("range1 (number, range<number>)",fs("The first range whose entries will be multiplied with corresponding entries in the other ranges.")),as("range2 (number, range<number>, repeating)",fs("The other range whose entries will be multiplied with corresponding entries in the other ranges."))],compute:function(...e){if(!ci(...e))return new Cs(fs("All the ranges must have the same dimensions."));const t=e.map(Xo);let s=0;for(let e=0;e<t[0].length;e++)for(let o=0;o<t[0][e].length;o++){if(!t.every(t=>"number"==typeof t[e][o].value))continue;let i=1;for(const s of t)i*=bo(s[e][o],this.locale);s+=i}return s},isExported:!0};function _i(e,t,s){if(!ci(e,t))return new Cs(fs("The arguments array_x and array_y must have the same dimensions."));const o=Xo(e),i=Xo(t);let n=!1,r=0;for(const e in o)for(const t in o[e]){const a=o[e][t].value,l=i[e][t].value;"number"==typeof a&&"number"==typeof l&&(n=!0,r+=s(a,l))}return n?r:new Cs(fs("The arguments array_x and array_y must contain at least one pair of numbers."))}const Oi={description:fs("Calculates the sum of the difference of the squares of the values in two array."),args:[as("array_x (number, range<number>)",fs("The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.")),as("array_y (number, range<number>)",fs("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 _i(e,t,(e,t)=>e**2-t**2)},isExported:!0},Fi={description:fs("Calculates the sum of the sum of the squares of the values in two array."),args:[as("array_x (number, range<number>)",fs("The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.")),as("array_y (number, range<number>)",fs("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 _i(e,t,(e,t)=>e**2+t**2)},isExported:!0},Pi={description:fs("Calculates the sum of squares of the differences of values in two array."),args:[as("array_x (number, range<number>)",fs("The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.")),as("array_y (number, range<number>)",fs("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 _i(e,t,(e,t)=>(e-t)**2)},isExported:!0},Mi=!1,Ni=[as("array (any, range<any>)",fs("The array which will be transformed.")),as("ignore (number, default=0)",fs("Whether to ignore certain types of values. By default, no values are ignored."),[{value:0,label:fs("Keep all values (default)")},{value:1,label:fs("Ignore blanks")},{value:2,label:fs("Ignore errors")},{value:3,label:fs("Ignore blanks and errors")}]),as("scan_by_column (number, default=false)",fs("Scan the array by column. By default, the array is scanned by row."),[{value:!1,label:fs("Scan by row (default)")},{value:!0,label:fs("Scan by column")}])];function Li(e){const t=Math.trunc(e);if(0===t)return()=>!0;if(1===t)return e=>null!==e.value;if(2===t)return e=>!mo(e.value);if(3===t)return e=>null!==e.value&&!mo(e.value);throw new Cs(fs("Argument ignore must be between 0 and 3"))}const ki={description:fs("Transforms a range of cells into a single column."),args:Ni,compute:function(e,t={value:0},s={value:Mi}){const o=Xo(e),i=bo(t.value,this.locale),n=(To(s.value)?o:Uo(o)).flat().filter(Li(i));return 0===n.length?new Es(fs("No results for the given arguments of TOCOL.")):[n]},isExported:!0},Vi={description:fs("Transforms a range of cells into a single row."),args:Ni,compute:function(e,t={value:0},s={value:Mi}){const o=Xo(e),i=bo(t.value,this.locale),n=(To(s.value)?o:Uo(o)).flat().filter(Li(i)).map(e=>[e]);return 0===n.length||0===n[0].length?new Es(fs("No results for the given arguments of TOROW.")):n},isExported:!0},Ui={description:fs("Transposes the rows and columns of a range."),args:[as("range (any, range<any>)",fs("The range to be transposed."))],compute:function(e){const t=Xo(e);return ko(t[0].length,t.length,(e,s)=>t[s][e])},isExported:!0},Hi={description:fs("Appends ranges vertically and in sequence to return a larger array."),args:[as("range1 (any, range<any>)",fs("The first range to be appended.")),as("range2 (any, range<any>, repeating)",fs("Additional ranges to add to range1."))],compute:function(...e){const t=Math.max(...e.map(e=>Xo(e).length)),s=e.reduce((e,t)=>e+Xo(t)[0].length,0),o=Array(t).fill([]).map(()=>Array(s).fill({value:0}));let i=0;for(const t of e){const e=Xo(t);for(let t=0;t<e.length;t++)for(let s=0;s<e[t].length;s++)o[t][i+s]=e[t][s];i+=e[0].length}return o},isExported:!0},zi={description:fs("Wraps the provided row or column of cells by columns after a specified number of elements to form a new array."),args:[as("range (any, range<any>)",fs("The range to wrap.")),as("wrap_count (number)",fs("The maximum number of cells for each column, rounded down to the nearest whole number.")),as("pad_with (any, default=0)",fs("The value with which to fill the extra cells in the range."))],compute:function(e,t,s={value:0}){const o=Xo(e),i=Io(t?.value,this.locale);if(!li(o))return new Cs(fs("Argument range must be a single row or column."));const n=o.flat();return ko(Math.ceil(n.length/i),i,(e,t)=>{const o=e*i+t;return o<n.length?n[o]:s})},isExported:!0},Bi={description:fs("Wraps the provided row or column of cells by rows after a specified number of elements to form a new array."),args:[as("range (any, range<any>)",fs("The range to wrap.")),as("wrap_count (number)",fs("The maximum number of cells for each row, rounded down to the nearest whole number.")),as("pad_with (any, default=0)",fs("The value with which to fill the extra cells in the range."))],compute:function(e,t,s={value:0}){const o=Xo(e),i=Io(t?.value,this.locale);if(!li(o))return new Cs(fs("Argument range must be a single row or column."));const n=o.flat(),r=Math.ceil(n.length/i);return ko(i,r,(e,t)=>{const o=t*i+e;return o<n.length?n[o]:s})},isExported:!0};var Gi=Object.freeze({__proto__:null,ARRAY_CONSTRAIN:Si,CHOOSECOLS:Ci,CHOOSEROWS:yi,EXPAND:Ii,FLATTEN:wi,FREQUENCY:Ei,HSTACK:Ri,MDETERM:xi,MINVERSE:Ti,MMULT:Ai,SUMPRODUCT:Di,SUMX2MY2:Oi,SUMX2PY2:Fi,SUMXMY2:Pi,TOCOL:ki,TOROW:Vi,TRANSPOSE:Ui,VSTACK:Hi,WRAPCOLS:zi,WRAPROWS:Bi});function Wi(e){let t;if('"'===e.current?(e.shift(),t='"'):e.currentStartsWith("[$")&&(e.advanceBy(2),t="]"),!t)return null;let s="";for(;e.current&&e.current!==t;)s+=e.shift();if(e.current!==t)throw new Error("Unterminated string in format");return e.shift(),{type:"STRING",value:s}}const $i=new Set("$+-/():!^&~{}<>= ");function qi(e){if("\\"===e.current){e.shift();const t=e.shift();if(!t)throw new Error("Unexpected end of format string");return{type:"CHAR",value:t}}return $i.has(e.current)?{type:"CHAR",value:e.shift()}:null}function Zi(e){return","===e.current?(e.shift(),{type:"THOUSANDS_SEPARATOR",value:","}):null}function ji(e){return"@"===e.current?(e.shift(),{type:"TEXT_PLACEHOLDER",value:"@"}):null}function Yi(e){return"."===e.current?(e.shift(),{type:"DECIMAL_POINT",value:"."}):null}function Xi(e){return"%"===e.current?(e.shift(),{type:"PERCENT",value:"%"}):null}function Ki(e){if("0"===e.current||"#"===e.current){const t=e.current;return e.shift(),{type:"DIGIT",value:t}}return null}const Ji=new Set("dmqyhsa");function Qi(e){if(!Ji.has(e.current))return null;const t=e.current;let s="";for(;e.current===t;)s+=e.shift();return{type:"DATE_PART",value:s}}function en(e){if("*"!==e.current)return null;e.shift();const t=e.shift();if(!t)throw new Error("Unexpected end of format string");return{type:"REPEATED_CHAR",value:t}}const tn={};function sn(e){let t=tn[e];return void 0===t&&(t=function(e){const t=function(e){const t=new Qe(e),s=[];let o=[];for(s.push(o);!t.isOver();){if(";"===t.current){o=[],s.push(o),t.shift();continue}const e=Ki(t)||Wi(t)||qi(t)||Zi(t)||Yi(t)||Xi(t)||Qi(t)||ji(t)||en(t);if(!e)throw new Error("Unknown token at "+t.remaining());o.push(e)}return s}(e);for(const e of t){const t=e.filter(e=>"REPEATED_CHAR"===e.type);for(const e of t.slice(1))e.type="CHAR"}const s=nn(t[0])||on(t[0])||rn(t[0]);if(!s)throw new Error("Invalid first format part of: "+e);if(t.length>1&&"text"===s.type)throw new Error("The first format in a multi-part format must be a number format: "+e);const o=nn(t[1])||on(t[1]);if(t[1]?.length&&!o)throw new Error("Invalid second format part of: "+e);const i=nn(t[2])||on(t[2]);if(t[2]?.length&&!i)throw new Error("Invalid third format part of: "+e);const n=rn(t[3]);if(t[3]?.length&&!n)throw new Error("Invalid fourth format part of: "+e);return{positive:s,negative:o,zero:i,text:n}}(e),tn[e]=t),t}function on(e){if(!e||!function(e){return e.every(e=>"DIGIT"===e.type||"DECIMAL_POINT"===e.type||"THOUSANDS_SEPARATOR"===e.type||"PERCENT"===e.type||"STRING"===e.type||"CHAR"===e.type||"REPEATED_CHAR"===e.type)}(e))return;const t=[];let s,o=t,i=0,n=0,r=e.findLastIndex(e=>"DIGIT"===e.type),a=!1,l=0;for(let c=0;c<e.length;c++){const h=e[c];switch(h.type){case"DIGIT":o===t?o.push(h):l<20&&(o.push(h),l++);break;case"DECIMAL_POINT":if(o!==t)throw new Error("Multiple decimal points in a number format");s=[],o=s;break;case"REPEATED_CHAR":case"CHAR":case"STRING":o.push(h);break;case"PERCENT":i++,o.push(h);break;case"THOUSANDS_SEPARATOR":c-1===r?(n+=1,r++,o.push(h)):"DIGIT"===e[c+1]?.type&&"DIGIT"===e[c-1]?.type?(o===t&&(a=!0),o.push(h)):o.push({type:"CHAR",value:","})}}return{type:"number",integerPart:t,decimalPart:s,percentSymbols:i,thousandsSeparator:a,magnitude:n}}function nn(e){const t=e&&function(e){return e.every(e=>"DATE_PART"===e.type||"DECIMAL_POINT"===e.type||"THOUSANDS_SEPARATOR"===e.type||"STRING"===e.type||"CHAR"===e.type||"REPEATED_CHAR"===e.type)}(e)?{type:"date",tokens:e}:void 0;if(!t)return;if(t.tokens.length&&t.tokens.every(e=>"DATE_PART"===e.type&&"a"===e.value))throw new Error("Invalid date format");const s=function(e){const t=e.filter(e=>"DATE_PART"===e.type);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}(t.tokens.map(e=>"THOUSANDS_SEPARATOR"===e.type||"DECIMAL_POINT"===e.type?{type:"CHAR",value:e.value}:e));return{type:"date",tokens:s}}function rn(e){return e&&function(e){return e.every(e=>"STRING"===e.type||"TEXT_PLACEHOLDER"===e.type||"CHAR"===e.type||"REPEATED_CHAR"===e.type)}(e)?{type:"text",tokens:e}:void 0}function an(e){return[ln(e.positive),ln(e.negative),ln(e.zero),ln(e.text)].filter(Te).join(";")}function ln(e){if(!e)return;let t="";const s="number"!==e.type?e.tokens:function(e){const t=[...e.integerPart];e.decimalPart&&(t.push({type:"DECIMAL_POINT",value:"."}),t.push(...e.decimalPart));return t}(e);for(const e of s)switch(e.type){case"STRING":t+=`[$${e.value}]`;break;case"CHAR":t+=cn(e.value)?`\\${e.value}`:e.value;break;case"REPEATED_CHAR":t+="*"+e.value;break;case"DATE_PART":t+="MM"===e.value?"mm":e.value;break;default:t+=e.value}return t}function cn(e){return!$i.has(e)}const hn="REPEATED_CHAR_PLACEHOLDER_",dn={0:fs("January"),1:fs("February"),2:fs("March"),3:fs("April"),4:fs("May"),5:fs("June"),6:fs("July"),7:fs("August"),8:fs("September"),9:fs("October"),10:fs("November"),11:fs("December")},un={0:fs("Sunday"),1:fs("Monday"),2:fs("Tuesday"),3:fs("Wednesday"),4:fs("Thursday"),5:fs("Friday"),6:fs("Saturday")};function gn(e,t,s,o=!1){return o?Mn({value:e,format:t},s):pn(e,{format:t,locale:s})}function pn(e,{format:t,locale:s,formatWidth:o}){switch("boolean"==typeof e&&(e=e?"TRUE":"FALSE"),typeof e){case"string":{if(e.includes('\\"')&&(e=e.replaceAll(/\\"/g,'"')),!t)return e;const s=mn(e,sn(t)).format;return s&&"text"===s.type?fn(e,s,o):e}case"number":t||(t=xn(e));const i=sn(t),{format:n,isNegativeFormat:r}=mn(e,i);if(!n)return e.toString();if("text"===n.type)return fn(e.toString(),n,o);if(r&&(e=Math.abs(e)),"date"===n.type)return vn(function(e,t){const s=js(e),o=t.tokens.some(e=>"DATE_PART"===e.type&&"a"===e.value);let i="";for(const e of t.tokens)switch(e.type){case"DATE_PART":i+=En(s,e.value,o);break;case"REPEATED_CHAR":i+=hn+e.value;break;default:i+=e.value}return i}(e,n),o);const a=e<0,l=vn(function(e,t,s){if(e===1/0)return"∞"+(t.percentSymbols?"%":"");const o=2*t.percentSymbols-3*t.magnitude;e*=10**o;let i=0;void 0!==t.decimalPart&&(i=t.decimalPart.filter(e=>"DIGIT"===e.type).length);const{integerDigits:n,decimalDigits:r}=Sn(Math.abs(e),i);let a=function(e,t,s){let o=t.integerPart;o.some(e=>"DIGIT"===e.type)||(o=[...o,{type:"DIGIT",value:"#"}]);"0"===e&&(e="");let i="";const n=o.findIndex(e=>"DIGIT"===e.type);let r=e.length-1;function a(t,o){if("0"===o&&(t=t||"0"),!t)return;const n=e.length-1-r;i=s&&n>0&&n%3==0?t+s+i:t+i}for(let t=o.length-1;t>=0;t--){const s=o[t];switch(s.type){case"DIGIT":if(a(e[r],s.value),r--,n===t)for(;r>=0;)a(e[r],"0"),r--;break;case"THOUSANDS_SEPARATOR":break;case"REPEATED_CHAR":i=hn+s.value+i;break;default:i=s.value+i}}return i}(n,t,t.thousandsSeparator?s.thousandsSeparator:void 0);void 0!==t.decimalPart&&(a+=s.decimalSeparator+function(e,t){if(!t.decimalPart)return"";let s="",o=0;for(const i of t.decimalPart)switch(i.type){case"DIGIT":s+="#"===i.value?e[o]||"":e[o]||"0",o++;break;case"THOUSANDS_SEPARATOR":break;case"REPEATED_CHAR":s+=hn+i.value;break;default:s+=i.value}return s}(r||"",t));return a}(Math.abs(e),n,s),o);return a?"-"+l:l;case"object":return""}}function mn(e,t){let s,o=!1;switch(typeof e){case"number":e<0&&t.negative?(s=t.negative,o=!0):s=0===e&&t.zero?t.zero:t.positive;break;case"string":const i=t.text||t.positive;"text"===i.type&&(s=i)}return{format:s,isNegativeFormat:o}}function fn(e,t,s){let o="";for(const s of t.tokens)switch(s.type){case"TEXT_PLACEHOLDER":o+=e;break;case"CHAR":case"STRING":o+=s.value;break;case"REPEATED_CHAR":o+=hn+s.value}return vn(o,s)}function vn(e,t){const s=e.indexOf(hn);if(-1===s)return e;const o=e.slice(0,s),i=e.slice(s+26+1),n=e[s+26];const{timesToRepeat:r,padding:a}=function(){if(!t)return{timesToRepeat:0,padding:""};const e=t.measureText(o+i),s=t.measureText(n),r=t.availableWidth-e;if(r<=0)return{timesToRepeat:0,padding:""};const a=Math.floor(r/s),l=r-a*s,c=t.measureText(" ");return{timesToRepeat:a,padding:" ".repeat(Math.floor(l/c))}}();return o+n.repeat(r)+a+i}const bn=[];function Sn(e,t=20){const s=e.toString();if(s.includes("e"))return function(e,t=20){let s=bn[t];s||(s=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),bn[t]=s);const[o,i]=s.format(e).split(".");return{integerDigits:o,decimalDigits:i}}(e,t);if(Number.isInteger(e))return{integerDigits:s,decimalDigits:void 0};const o=s.indexOf(".");let i=s.substring(0,o),n=s.substring(o+1);if(0===t)return Number(n[0])>=5&&(i=(Number(i)+1).toString()),{integerDigits:i,decimalDigits:void 0};if(n.length>t){const{integerDigits:e,decimalDigits:s}=function(e,t){let s="0",o=e;const i=e.slice(0,t),n=t;if(Number(e[n])<5)return{integerDigits:s,decimalDigits:i};const r=i.match(yn)?.[0]||"",a=(Number(i)+1).toString(),l=i.slice(r.length),c=a.length>l.length;c&&!r?(s="1",o=void 0):o=c?r.slice(0,-1)+a:r+a;return{integerDigits:s,decimalDigits:o}}(n,t);n=s,"0"!==e&&(i=(Number(i)+Number(e)).toString())}return{integerDigits:i,decimalDigits:Cn(n||"")}}function Cn(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const yn=/^0+/;function In(e,t){const{integerDigits:s,decimalDigits:o}=Sn(e,20);return o?s+t+o:s}const wn=$e(function(e){if(!e)return!1;try{return"date"===sn(e).positive.type}catch(e){return!1}});function En(e,t,s){switch(t){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return un[e.getDay()].slice(0,3);case"dddd":return un[e.getDay()].toString();case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return dn[e.getMonth()].slice(0,3);case"mmmm":return dn[e.getMonth()].toString();case"mmmmm":return dn[e.getMonth()].slice(0,1);case"qq":return fs("Q%(quarter)s",{quarter:e.getQuarter()}).toString();case"qqqq":return fs("Quarter %(quarter)s",{quarter:e.getQuarter()}).toString();case"yy":const o=String(e.getFullYear()).replace("-","").padStart(2,"0");return o.slice(o.length-2);case"yyyy":return e.getFullYear();case"hhhh":return Math.floor((e.getTime()-Fs.getTime())/36e5).toString();case"hh":let i=e.getHours();return s&&(i=0===i?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 new Error(`invalid date format token: ${t}`)}}const Rn=$e(function(e){return new RegExp(`[0-9]+${re(e.decimalSeparator)}[0-9]`)});function xn(e){let{integerDigits:t,decimalDigits:s}=Sn(e);if(!s)return"0";const o=t.replace("-","").length;if(o+2>11)return"0";const i=11-o-1;return({decimalDigits:s}=Sn(e,Math.min(i,s.length))),s?"0."+"0".repeat(s.length):"0"}function Tn(e,t){if(!$s(e,t))return;return Zs(e,t).format}function An(e){const t=e.includes(".")?"0.00":"0",s=e.match(/[\$€]/);if(s){const o=e.match(/[\d]/),i="[$"+s.values().next().value+"]";return o.index<s.index?"#,##"+t+i:i+"#,##"+t}if(e.includes("%"))return t+"%"}function Dn(e){const t=e.decimalPlaces??2,s=e.position??"before",o=e.code??"",i=e.symbol??"",n="#,##0"+(t?"."+"0".repeat(t):"");let r=`${o} ${i}`.trim();return"after"===s&&o&&(r=" "+r),function(e,t,s){const o=`[$${e}]`;return"before"===t?o+s:s+o}(r,s,n)}function _n(e){const t=e.decimalPlaces??2,s=e.position??"before",o=e.code??"",i=e.symbol??"",n="#,##0"+(t?"."+"0".repeat(t):"");let r=`${o} ${i}`.trim();"after"===s&&o&&(r=" "+r);return[On(r,s,` ${n} `),On(r,s,`(${n})`),On(r,s," - ")].join(";")}function On(e,t,s){const o=`[$${e}]`;return"before"===t?o+"* "+s:s+"* "+o}function Fn(e){const t=sn(e);return an({positive:Pn(t.positive),negative:t.negative?Pn(t.negative):void 0,zero:t.zero?Pn(t.zero):void 0,text:t.text})}function Pn(e){if("number"!==e.type||!e.decimalPart)return e;const t=e.decimalPart.filter(e=>"DIGIT"!==e.type);return{...e,decimalPart:void 0,integerPart:[...e.integerPart,...t]}}function Mn({value:e,format:t},s){return pn(e,{format:Nn({value:e,format:t},void 0,s),locale:s})}function Nn(e,t,s){let o=0;try{o=Math.abs(bo(e?.value,s))}catch(e){return""}const i=e?.format;if(void 0!==t){const e=t?.value;switch(e){case"k":return Ln(i,1,"k");case"m":return Ln(i,2,"m");case"b":return Ln(i,3,"b");default:throw new Cs(fs("The formatting unit should be 'k', 'm' or 'b'."))}}return o<1e5?Ln(i,0,""):o<1e8?Ln(i,1,"k"):o<1e11?Ln(i,2,"m"):Ln(i,3,"b")}function Ln(e,t,s,o){const i=sn(e||"#,##0");return an({positive:kn(i.positive,t,s),negative:i.negative?kn(i.negative,t,s):void 0,zero:i.zero?kn(i.zero,t,s):void 0,text:i.text})}function kn(e,t,s){if("number"!==e.type)return e;const o={type:"STRING",value:s};let i=[...e.integerPart];const n=i.findLastIndex(e=>"DIGIT"===e.type);if(-1===n)throw new Error("Cannot create a large number format from a format with no digit.");for(;"THOUSANDS_SEPARATOR"===i[n+1]?.type;)i=qe(i,[n+1]);const r=i[n+1];i="STRING"===r?.type&&["m","k","b"].includes(r.value)?je(i,o,n+1):Ze(i,[o],n+1),t>0&&(i=Ze(i,Array(t).fill({type:"THOUSANDS_SEPARATOR",value:","}),n+1));const a=e.percentSymbols-i.filter(e=>"PERCENT"===e.type).length;return i.push(...new Array(a).fill({type:"PERCENT",value:"%"})),{...e,integerPart:i,decimalPart:void 0,magnitude:t}}function Vn(e,t){const s=sn(e);return an(sn(an({positive:Un(s.positive,t),negative:s.negative?Un(s.negative,t):void 0,zero:s.zero?Un(s.zero,t):void 0,text:s.text})))}function Un(e,t){return"number"!==e.type?e:t>0?function(e,t){let s=e.integerPart,o=e.decimalPart;if(!o){const e=s.findLastIndex(e=>"DIGIT"===e.type);o=s.slice(e+1),s=s.slice(0,e+1)}const i=ge(0,t).map(()=>({type:"DIGIT",value:"0"})),n=o.findLastIndex(e=>"DIGIT"===e.type);o=-1===n?[...i,...o]:Ze(o,i,n+1);return{...e,decimalPart:o,integerPart:s}}(e,t):function(e,t){let s=e.decimalPart;if(!s)return e;const o=[];let i=0;for(let e=s.length-1;e>=0&&!(i>=Math.abs(t));e--)"DIGIT"===s[e].type&&(i++,o.push(e));if(s=qe(s,o),s.some(e=>"DIGIT"===e.type))return{...e,decimalPart:s};return{...e,decimalPart:void 0,integerPart:[...e.integerPart,...s]}}(e,Math.abs(t))}function Hn(e){const t=sn(e);for(const e of[t.positive,t.negative,t.zero])if(e&&"date"===e.type&&e.tokens.some(e=>"DATE_PART"===e.type&&e.value.includes("q")))return!1;return!0}function zn(e){if(!e)return!1;try{return"text"===sn(e).positive.type}catch{return!1}}const Bn={description:fs("Apply a large number format"),args:[as("value (number)",fs("The number.")),as("unit (string, optional)",fs("The formatting unit. Use 'k', 'm', or 'b' to force the unit"),[{value:"k",label:fs("Thousand")},{value:"m",label:fs("Million")},{value:"b",label:fs("Billion")}])],compute:function(e,t){return{value:bo(e,this.locale),format:Nn(e,t,this.locale)}}};var Gn=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:Bn});const Wn=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),$n=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),qn=new RegExp(/^\$?([A-Z]{1,3})+$/,"i"),Zn=new RegExp(/^\$?([0-9]{1,7})+$/,"i"),jn=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),Yn=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),Xn=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[Wn.source,/(\$?[A-Z]{1,3})?\$?[0-9]{1,7}\s*:\s*(\$?[A-Z]{1,3})?\$?[0-9]{1,7}\s*/i.source,/\$?[A-Z]{1,3}(\$?[0-9]{1,7})?\s*:\s*\$?[A-Z]{1,3}(\$?[0-9]{1,7})?\s*/i.source].join("|")+")"+/$/.source,"i");function Kn(e){return Yn.test(e)}function Jn(e){return qn.test(e)}function Qn(e){return Zn.test(e)}function er(e){return $n.test(e)}function tr(e){if(!e.includes("!"))return{xc:e};const t=e.split("!"),s=t.pop();return{sheetName:le(t.join("!"))||void 0,xc:s}}function sr(e,t){return void 0!==e?`${he(e)}!${t}`:t}function or(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:s}=tr(e.value),[o,i]=t.split(":"),n=ir(o),r=i?`:${ir(i)}`:"";return{...e,value:sr(s,n+r)}}function ir(e){switch(function(e){if(function(e){return e.startsWith("$")&&e.length>1&&e.slice(1).includes("$")}(e))return"colrow";if(function(e){return e.startsWith("$")}(e))return"col";if(function(e){return e.includes("$",1)}(e))return"row";return"none"}(e)){case"none":e=nr(e,"colrow");break;case"colrow":e=nr(e,"row");break;case"row":e=nr(e,"col");break;case"col":e=nr(e,"none")}return e}function nr(e,t){let s;({sheetName:s,xc:e}=tr(e)),s=s?s+"!":"";const o=(e=e.replace(/\$/g,"")).indexOf(":");return o>=0?`${s}${rr(e.slice(0,o),t)}:${rr(e.slice(o+1),t)}`:s+rr(e,t)}function rr(e,t){const s=e.search(/[0-9]/),o=0!==s,i=s>=0;switch(t){case"col":return o?"$"+e:e;case"row":return i?e.slice(0,s)+"$"+e.slice(s):e;case"colrow":return i&&o?"$"+e.slice(0,s)+"$"+e.slice(s):"$"+e;case"none":return e}}function ar(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class lr{getCrypto(){if("undefined"!=typeof globalThis&&globalThis.crypto)return globalThis.crypto;if("function"==typeof require)try{const e=require("crypto");if(e.webcrypto)return e.webcrypto}catch(e){}}smallUuid(){const e=this.getCrypto();return e?"10000000-1000".replace(/[01]/g,t=>{const s=Number(t);return(s^e.getRandomValues(new Uint8Array(1))[0]&15>>s/4).toString(16)}):"xxxxxxxx-xxxx".replace(/[xy]/g,function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}uuidv4(){const e=this.getCrypto();return e?"10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>{const s=Number(t);return(s^e.getRandomValues(new Uint8Array(1))[0]&15>>s/4).toString(16)}):"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}}const cr=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","DUPLICATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","UNDO","REDO","ADD_MERGE","REMOVE_MERGE","DUPLICATE_SHEET","UPDATE_LOCALE","ADD_PIVOT","UPDATE_PIVOT","INSERT_PIVOT","RENAME_PIVOT","REMOVE_PIVOT","DUPLICATE_PIVOT"]),hr=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"]),dr=new Set(["MOVE_RANGES"]),ur=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"]),pr=new Set(["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"]),mr=new Set(["START","ACTIVATE_SHEET","COPY","RESIZE_SHEETVIEW","SET_VIEWPORT_OFFSET","EVALUATE_CELLS","EVALUATE_CHARTS","SET_FORMULA_VISIBILITY","UPDATE_FILTER","UPDATE_CHART","UPDATE_CAROUSEL_ACTIVE_ITEM","UPDATE_PIVOT"]),fr=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","CREATE_CAROUSEL","UPDATE_CAROUSEL","SET_FORMATTING","CLEAR_FORMATTING","SET_BORDER","SET_ZONE_BORDERS","SET_BORDERS_ON_TARGET","CREATE_CHART","UPDATE_CHART","DELETE_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"]);function vr(e){return fr.has(e.type)}class br{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter(e=>"Success"!==e)}static get Success(){return Sr}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}const Sr=new br;var Cr;e.CommandResult=void 0,(Cr=e.CommandResult||(e.CommandResult={})).Success="Success",Cr.CancelledForUnknownReason="CancelledForUnknownReason",Cr.WillRemoveExistingMerge="WillRemoveExistingMerge",Cr.CannotMoveTableHeader="CannotMoveTableHeader",Cr.MergeIsDestructive="MergeIsDestructive",Cr.CellIsMerged="CellIsMerged",Cr.InvalidTarget="InvalidTarget",Cr.EmptyUndoStack="EmptyUndoStack",Cr.EmptyRedoStack="EmptyRedoStack",Cr.NotEnoughElements="NotEnoughElements",Cr.NotEnoughSheets="NotEnoughSheets",Cr.MissingSheetName="MissingSheetName",Cr.UnchangedSheetName="UnchangedSheetName",Cr.DuplicatedSheetName="DuplicatedSheetName",Cr.DuplicatedSheetId="DuplicatedSheetId",Cr.ForbiddenCharactersInSheetName="ForbiddenCharactersInSheetName",Cr.WrongSheetMove="WrongSheetMove",Cr.WrongSheetPosition="WrongSheetPosition",Cr.InvalidAnchorZone="InvalidAnchorZone",Cr.SelectionOutOfBound="SelectionOutOfBound",Cr.TargetOutOfSheet="TargetOutOfSheet",Cr.WrongCutSelection="WrongCutSelection",Cr.WrongPasteSelection="WrongPasteSelection",Cr.WrongPasteOption="WrongPasteOption",Cr.WrongFigurePasteOption="WrongFigurePasteOption",Cr.EmptyClipboard="EmptyClipboard",Cr.EmptyRange="EmptyRange",Cr.InvalidRange="InvalidRange",Cr.InvalidZones="InvalidZones",Cr.InvalidSheetId="InvalidSheetId",Cr.InvalidCellId="InvalidCellId",Cr.InvalidFigureId="InvalidFigureId",Cr.InputAlreadyFocused="InputAlreadyFocused",Cr.MaximumRangesReached="MaximumRangesReached",Cr.MinimumRangesReached="MinimumRangesReached",Cr.InvalidChartDefinition="InvalidChartDefinition",Cr.InvalidDataSet="InvalidDataSet",Cr.InvalidLabelRange="InvalidLabelRange",Cr.InvalidScorecardKeyValue="InvalidScorecardKeyValue",Cr.InvalidScorecardBaseline="InvalidScorecardBaseline",Cr.InvalidGaugeDataRange="InvalidGaugeDataRange",Cr.EmptyGaugeRangeMin="EmptyGaugeRangeMin",Cr.GaugeRangeMinNaN="GaugeRangeMinNaN",Cr.EmptyGaugeRangeMax="EmptyGaugeRangeMax",Cr.GaugeRangeMaxNaN="GaugeRangeMaxNaN",Cr.GaugeLowerInflectionPointNaN="GaugeLowerInflectionPointNaN",Cr.GaugeUpperInflectionPointNaN="GaugeUpperInflectionPointNaN",Cr.InvalidAutofillSelection="InvalidAutofillSelection",Cr.MinBiggerThanMax="MinBiggerThanMax",Cr.LowerBiggerThanUpper="LowerBiggerThanUpper",Cr.MidBiggerThanMax="MidBiggerThanMax",Cr.MinBiggerThanMid="MinBiggerThanMid",Cr.FirstArgMissing="FirstArgMissing",Cr.SecondArgMissing="SecondArgMissing",Cr.MinNaN="MinNaN",Cr.MidNaN="MidNaN",Cr.MaxNaN="MaxNaN",Cr.ValueUpperInflectionNaN="ValueUpperInflectionNaN",Cr.ValueLowerInflectionNaN="ValueLowerInflectionNaN",Cr.MinInvalidFormula="MinInvalidFormula",Cr.MidInvalidFormula="MidInvalidFormula",Cr.MaxInvalidFormula="MaxInvalidFormula",Cr.ValueUpperInvalidFormula="ValueUpperInvalidFormula",Cr.ValueLowerInvalidFormula="ValueLowerInvalidFormula",Cr.InvalidSortAnchor="InvalidSortAnchor",Cr.InvalidSortZone="InvalidSortZone",Cr.SortZoneWithArrayFormulas="SortZoneWithArrayFormulas",Cr.WaitingSessionConfirmation="WaitingSessionConfirmation",Cr.MergeOverlap="MergeOverlap",Cr.TooManyHiddenElements="TooManyHiddenElements",Cr.Readonly="Readonly",Cr.InvalidViewportSize="InvalidViewportSize",Cr.InvalidScrollingDirection="InvalidScrollingDirection",Cr.ViewportScrollLimitsReached="ViewportScrollLimitsReached",Cr.FigureDoesNotExist="FigureDoesNotExist",Cr.InvalidConditionalFormatId="InvalidConditionalFormatId",Cr.InvalidCellPopover="InvalidCellPopover",Cr.EmptyTarget="EmptyTarget",Cr.InvalidFreezeQuantity="InvalidFreezeQuantity",Cr.FrozenPaneOverlap="FrozenPaneOverlap",Cr.ValuesNotChanged="ValuesNotChanged",Cr.InvalidFilterZone="InvalidFilterZone",Cr.TableNotFound="TableNotFound",Cr.TableOverlap="TableOverlap",Cr.InvalidTableConfig="InvalidTableConfig",Cr.InvalidTableStyle="InvalidTableStyle",Cr.FilterNotFound="FilterNotFound",Cr.MergeInTable="MergeInTable",Cr.NonContinuousTargets="NonContinuousTargets",Cr.DuplicatedFigureId="DuplicatedFigureId",Cr.InvalidSelectionStep="InvalidSelectionStep",Cr.DuplicatedChartId="DuplicatedChartId",Cr.ChartDoesNotExist="ChartDoesNotExist",Cr.InvalidHeaderIndex="InvalidHeaderIndex",Cr.InvalidQuantity="InvalidQuantity",Cr.MoreThanOneColumnSelected="MoreThanOneColumnSelected",Cr.EmptySplitSeparator="EmptySplitSeparator",Cr.SplitWillOverwriteContent="SplitWillOverwriteContent",Cr.NoSplitSeparatorInSelection="NoSplitSeparatorInSelection",Cr.NoActiveSheet="NoActiveSheet",Cr.InvalidLocale="InvalidLocale",Cr.MoreThanOneRangeSelected="MoreThanOneRangeSelected",Cr.NoColumnsProvided="NoColumnsProvided",Cr.ColumnsNotIncludedInZone="ColumnsNotIncludedInZone",Cr.DuplicatesColumnsSelected="DuplicatesColumnsSelected",Cr.InvalidHeaderGroupStartEnd="InvalidHeaderGroupStartEnd",Cr.HeaderGroupAlreadyExists="HeaderGroupAlreadyExists",Cr.UnknownHeaderGroup="UnknownHeaderGroup",Cr.UnknownDataValidationRule="UnknownDataValidationRule",Cr.UnknownDataValidationCriterionType="UnknownDataValidationCriterionType",Cr.InvalidDataValidationCriterionValue="InvalidDataValidationCriterionValue",Cr.InvalidNumberOfCriterionValues="InvalidNumberOfCriterionValues",Cr.InvalidCopyPasteSelection="InvalidCopyPasteSelection",Cr.NoChanges="NoChanges",Cr.InvalidInputId="InvalidInputId",Cr.SheetIsHidden="SheetIsHidden",Cr.InvalidTableResize="InvalidTableResize",Cr.PivotIdNotFound="PivotIdNotFound",Cr.PivotInError="PivotInError",Cr.EmptyName="EmptyName",Cr.ValueCellIsInvalidFormula="ValueCellIsInvalidFormula",Cr.InvalidDefinition="InvalidDefinition",Cr.InvalidColor="InvalidColor",Cr.InvalidPivotDataSet="InvalidPivotDataSet",Cr.InvalidPivotCustomField="InvalidPivotCustomField",Cr.MissingFigureArguments="MissingFigureArguments",Cr.InvalidCarouselItem="InvalidCarouselItem";class yr{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(const s of e){let e=s.call(this,t);Array.isArray(e)||(e=[e]);const o=e.filter(e=>"Success"!==e);if(o.length)return o}return"Success"}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}class Ir extends yr{static layers=[];getters;ui;selection;dispatch;canDispatch;constructor({getters:e,stateObserver:t,dispatch:s,canDispatch:o,uiActions:i,selection:n}){super(t),this.getters=e,this.ui=i,this.selection=n,this.dispatch=s,this.canDispatch=o}drawLayer(e,t){}}function wr(e){return e.isFormula&&e.compiledFormula.tokens.some(e=>"SYMBOL"===e.type&&"SUBTOTAL"===e.value.toUpperCase())}function Er(e,t){return No(e,(e,t)=>e+t,0,t)}function Rr(e){return Mo(e,(e,t)=>Jo(t)?e.add(t?.value):e,new Set).size}const xr=/^-?[a-z0-9]+$/i,Tr={description:fs("Absolute value of a number."),args:[as("value (number)",fs("The number of which to return the absolute value."))],compute:function(e){return Math.abs(bo(e,this.locale))},isExported:!0},Ar={description:fs("Inverse cosine of a value, in radians."),args:[as("value (number)",fs("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive."))],compute:function(e){const t=bo(e,this.locale);return Math.abs(t)>1?new Cs(fs("The value (%s) must be between -1 and 1 inclusive.",t)):Math.acos(t)},isExported:!0},Dr={description:fs("Inverse hyperbolic cosine of a number."),args:[as("value (number)",fs("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1."))],compute:function(e){const t=bo(e,this.locale);return t<1?new Cs(fs("The value (%s) must be greater than or equal to 1.",t)):Math.acosh(t)},isExported:!0},_r={description:fs("Inverse cotangent of a value."),args:[as("value (number)",fs("The value for which to calculate the inverse cotangent."))],compute:function(e){const t=bo(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Or={description:fs("Inverse hyperbolic cotangent of a value."),args:[as("value (number)",fs("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive."))],compute:function(e){const t=bo(e,this.locale);return Math.abs(t)<=1?new Cs(fs("The value (%s) cannot be between -1 and 1 inclusive.",t)):Math.log((t+1)/(t-1))/2},isExported:!0},Fr={description:fs("Inverse sine of a value, in radians."),args:[as("value (number)",fs("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive."))],compute:function(e){const t=bo(e,this.locale);return Math.abs(t)>1?new Cs(fs("The value (%s) must be between -1 and 1 inclusive.",t)):Math.asin(t)},isExported:!0},Pr={description:fs("Inverse hyperbolic sine of a number."),args:[as("value (number)",fs("The value for which to calculate the inverse hyperbolic sine."))],compute:function(e){return Math.asinh(bo(e,this.locale))},isExported:!0},Mr={description:fs("Inverse tangent of a value, in radians."),args:[as("value (number)",fs("The value for which to calculate the inverse tangent."))],compute:function(e){return Math.atan(bo(e,this.locale))},isExported:!0},Nr={description:fs("Angle from the X axis to a point (x,y), in radians."),args:[as("x (number)",fs("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")),as("y (number)",fs("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis."))],compute:function(e,t){const s=bo(e,this.locale),o=bo(t,this.locale);return 0===s&&0===o?new Ts(fs("Function [[FUNCTION_NAME]] caused a divide by zero error.")):Math.atan2(o,s)},isExported:!0},Lr={description:fs("Inverse hyperbolic tangent of a number."),args:[as("value (number)",fs("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive."))],compute:function(e){const t=bo(e,this.locale);return Math.abs(t)>=1?new Cs(fs("The value (%s) must be between -1 and 1 exclusive.",t)):Math.atanh(t)},isExported:!0},kr={description:fs("Rounds number up to nearest multiple of factor."),args:[as("value (number)",fs("The value to round up to the nearest integer multiple of factor.")),as("factor (number, default=1)",fs("The number to whose multiples value will be rounded."))],compute:function(e,t={value:1}){const s=bo(e,this.locale),o=bo(t,this.locale);return o<0&&s>0?new Cs(fs("The factor (%s) must be positive when the value (%s) is positive.",o,s)):{value:o?Math.ceil(s/o)*o:0,format:e?.format}},isExported:!0};function Vr(e,t,s=0){return 0===t?0:(t=Math.abs(t),e>=0?Math.ceil(e/t)*t:0===s?-Math.floor(Math.abs(e)/t)*t:-Math.ceil(Math.abs(e)/t)*t)}const Ur={description:fs("Rounds number up to nearest multiple of factor."),args:[as("number (number)",fs("The value to round up to the nearest integer multiple of significance.")),as("significance (number, default=1)",fs("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),as("mode (number, default=0)",fs("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},s={value:0}){const o=bo(t,this.locale);return{value:Vr(bo(e,this.locale),o,bo(s,this.locale)),format:e?.format}},isExported:!0},Hr={description:fs("Rounds number up to nearest multiple of factor."),args:[as("number (number)",fs("The value to round up to the nearest integer multiple of significance.")),as("significance (number, default=1)",fs("The number to whose multiples number will be rounded."))],compute:function(e,t={value:1}){const s=bo(t,this.locale);return{value:Vr(bo(e,this.locale),s),format:e?.format}},isExported:!0},zr={description:fs("Cosine of an angle provided in radians."),args:[as("angle (number)",fs("The angle to find the cosine of, in radians."))],compute:function(e){return Math.cos(bo(e,this.locale))},isExported:!0},Br={description:fs("Hyperbolic cosine of any real number."),args:[as("value (number)",fs("Any real value to calculate the hyperbolic cosine of."))],compute:function(e){return Math.cosh(bo(e,this.locale))},isExported:!0},Gr={description:fs("Cotangent of an angle provided in radians."),args:[as("angle (number)",fs("The angle to find the cotangent of, in radians."))],compute:function(e){const t=bo(e,this.locale);return 0===t?new Ts(fs("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.tan(t)},isExported:!0},Wr={description:fs("Hyperbolic cotangent of any real number."),args:[as("value (number)",fs("Any real value to calculate the hyperbolic cotangent of."))],compute:function(e){const t=bo(e,this.locale);return 0===t?new Ts(fs("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.tanh(t)},isExported:!0},$r={description:fs("Number of empty values."),args:[as("value1 (any, range)",fs("The first value or range in which to count the number of blanks.")),as("value2 (any, range, repeating)",fs("Additional values or ranges in which to count the number of blanks."))],compute:function(...e){return Mo(e,(e,t)=>void 0===t||null===t.value||""===t.value?e+1:e,0)},isExported:!0},qr={description:fs("A conditional count across a range."),args:[as("range (range)",fs("The range that is tested against criterion.")),as("criterion (string)",fs("The pattern or test to apply to range."))],compute:function(...e){let t=0;return $o(e,(e,s)=>{t+=1},this.locale),t},isExported:!0},Zr={description:fs("Count values depending on multiple criteria."),args:[as("criteria_range1 (range)",fs("The range to check against criterion1.")),as("criterion1 (string)",fs("The pattern or test to apply to criteria_range1.")),as("criteria_range2 (any, range, repeating)",fs("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.")),as("criterion2 (string, repeating)",fs("Additional criteria to check."))],compute:function(...e){let t=0;return $o(e,(e,s)=>{t+=1},this.locale),t},isExported:!0},jr={description:fs("Counts number of unique values in a range."),args:[as("value1 (any, range)",fs("The first value or range to consider for uniqueness.")),as("value2 (any, range, repeating)",fs("Additional values or ranges to consider for uniqueness."))],compute:function(...e){return Rr(e)}},Yr={description:fs("Counts number of unique values in a range, filtered by a set of criteria."),args:[as("range (range)",fs("The range of cells from which the number of unique values will be counted.")),as("criteria_range1 (range)",fs("The range of cells over which to evaluate criterion1.")),as("criterion1 (string)",fs("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),as("criteria_range2 (any, range, repeating)",fs("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.")),as("criterion2 (string, repeating)",fs("The pattern or test to apply to criteria_range2."))],compute:function(e,...t){const s=new Set;return $o(t,(t,o)=>{const i=e[t]?.[o];Jo(i)&&s.add(i.value)},this.locale),s.size}},Xr={description:fs("Cosecant of an angle provided in radians."),args:[as("angle (number)",fs("The angle to find the cosecant of, in radians."))],compute:function(e){const t=bo(e,this.locale);return 0===t?new Ts(fs("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.sin(t)},isExported:!0},Kr={description:fs("Hyperbolic cosecant of any real number."),args:[as("value (number)",fs("Any real value to calculate the hyperbolic cosecant of."))],compute:function(e){const t=bo(e,this.locale);return 0===t?new Ts(fs("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.sinh(t)},isExported:!0},Jr={description:fs("Converts from another base to decimal."),args:[as("value (string)",fs("The number to convert.")),as("base (number)",fs("The base to convert the value from."))],compute:function(e,t){let s=bo(t,this.locale);if(s=Math.floor(s),2>s||s>36)return new Cs(fs("The base (%s) must be between 2 and 36 inclusive.",s));const o=Eo(e);if(""===o)return 0;if(!xr.test(o))return new Cs(fs("The value (%s) must be a valid base %s representation.",o,s));const i=parseInt(o,s);return isNaN(i)?new Cs(fs("The value (%s) must be a valid base %s representation.",o,s)):i},isExported:!0},Qr={description:fs("Converts an angle value in radians to degrees."),args:[as("angle (number)",fs("The angle to convert from radians to degrees."))],compute:function(e){return 180*bo(e,this.locale)/Math.PI},isExported:!0},ea={description:fs("Euler's number, e (~2.718) raised to a power."),args:[as("value (number)",fs("The exponent to raise e."))],compute:function(e){return Math.exp(bo(e,this.locale))},isExported:!0},ta={description:fs("Rounds number down to nearest multiple of factor."),args:[as("value (number)",fs("The value to round down to the nearest integer multiple of factor.")),as("factor (number, default=1)",fs("The number to whose multiples value will be rounded."))],compute:function(e,t={value:1}){const s=bo(e,this.locale),o=bo(t,this.locale);return o<0&&s>0?new Cs(fs("The factor (%s) must be positive when the value (%s) is positive.",o,s)):{value:o?Math.floor(s/o)*o:0,format:e?.format}},isExported:!0};function sa(e,t,s=0){return 0===t?0:(t=Math.abs(t),e>=0?Math.floor(e/t)*t:0===s?-Math.ceil(Math.abs(e)/t)*t:-Math.floor(Math.abs(e)/t)*t)}const oa={description:fs("Rounds number down to nearest multiple of factor."),args:[as("number (number)",fs("The value to round down to the nearest integer multiple of significance.")),as("significance (number, default=1)",fs("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),as("mode (number, default=0)",fs("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},s={value:0}){const o=bo(t,this.locale);return{value:sa(bo(e,this.locale),o,bo(s,this.locale)),format:e?.format}},isExported:!0},ia={description:fs("Rounds number down to nearest multiple of factor."),args:[as("number (number)",fs("The value to round down to the nearest integer multiple of significance.")),as("significance (number, default=1)",fs("The number to whose multiples number will be rounded."))],compute:function(e,t={value:1}){const s=bo(t,this.locale);return{value:sa(bo(e,this.locale),s),format:e?.format}},isExported:!0},na={description:fs("Whether the provided value is even."),args:[as("value (number)",fs("The value to be verified as even."))],compute:function(e){const t=yo(e,this.locale);return!(1&Math.floor(Math.abs(t)))},isExported:!0},ra={description:fs("Rounds number up to nearest multiple of factor."),args:[as("number (number)",fs("The value to round up to the nearest integer multiple of significance.")),as("significance (number, default=1)",fs("The number to whose multiples number will be rounded."))],compute:function(e,t={value:1}){return{value:Vr(bo(e,this.locale),bo(t,this.locale)),format:e?.format}},isExported:!0},aa={description:fs("Whether the provided value is even."),args:[as("value (number)",fs("The value to be verified as even."))],compute:function(e){const t=yo(e,this.locale);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},la={description:fs("The logarithm of a number, base e (euler's number)."),args:[as("value (number)",fs("The value for which to calculate the logarithm, base e."))],compute:function(e){const t=bo(e,this.locale);return t<=0?new Cs(fs("The value (%s) must be strictly positive.",t)):Math.log(t)},isExported:!0},ca={description:fs("The logarithm of a number, for a given base."),args:[as("value (number)",fs("The value for which to calculate the logarithm.")),as("base (number, default=10)",fs("The base of the logarithm."))],compute:function(e,t={value:10}){const s=bo(e,this.locale),o=bo(t,this.locale);return s<=0?new Cs(fs("The value (%s) must be strictly positive.",s)):o<=0?new Cs(fs("The base (%s) must be strictly positive.",o)):1===o?new Cs(fs("The base must be different from 1.")):Math.log10(s)/Math.log10(o)},isExported:!0};function ha(e,t){ai(t,fs("The divisor must be different from 0."));const s=e%t;return s>0&&t<0||s<0&&t>0?s+t:s}const da={description:fs("Modulo (remainder) operator."),args:[as("dividend (number)",fs("The number to be divided to find the remainder.")),as("divisor (number)",fs("The number to divide by."))],compute:function(e,t){const s=bo(t,this.locale);return{value:ha(bo(e,this.locale),s),format:e?.format}},isExported:!0},ua={description:fs("Returns a n x n unit matrix, where n is the input dimension."),args:[as("dimension (number)",fs("An integer specifying the dimension size of the unit matrix. It must be positive."))],compute:function(e){const t=Io(e,this.locale);return t<1?new Cs(fs("The argument dimension must be positive")):ui(t)},isExported:!0},ga={description:fs("Rounds a number up to the nearest odd integer."),args:[as("value (number)",fs("The value to round to the next greatest odd number."))],compute:function(e){const t=bo(e,this.locale);let s=Math.ceil(Math.abs(t));return s=1&s?s:s+1,{value:t<0?-s:s,format:e?.format}},isExported:!0},pa={description:fs("The number pi."),args:[],compute:function(){return Math.PI},isExported:!0},ma={description:fs("A number raised to a power."),args:[as("base (number)",fs("The number to raise to the exponent power.")),as("exponent (number)",fs("The exponent to raise base to."))],compute:function(e,t){const s=bo(e,this.locale),o=bo(t,this.locale);return s<0&&!Number.isInteger(o)?new Cs(fs("The exponent (%s) must be an integer when the base is negative.",o)):{value:Math.pow(s,o),format:e?.format}},isExported:!0},fa={description:fs("Result of multiplying a series of numbers together."),args:[as("factor1 (number, range<number>)",fs("The first number or range to calculate for the product.")),as("factor2 (number, range<number>, repeating)",fs("More numbers or ranges to calculate for the product."))],compute:function(...e){let t=0,s=1;for(const o of e)if(Ds(o))for(const e of o)for(const o of e){const e=o.value;if("number"==typeof e&&(s*=e,t+=1),mo(e))return o}else void 0!==o&&null!==o.value&&(s*=yo(o,this.locale),t+=1);return{value:0===t?0:s,format:po(e[0])}},isExported:!0},va={description:fs("A random number between 0 inclusive and 1 exclusive."),args:[],compute:function(){return Math.random()},isExported:!0},ba={description:fs("Returns a grid of random numbers between 0 inclusive and 1 exclusive."),args:[as("rows (number, default=1)",fs("The number of rows to be returned.")),as("columns (number, default=1)",fs("The number of columns to be returned.")),as("min (number, default=0)",fs("The minimum number you would like returned.")),as("max (number, default=1)",fs("The maximum number you would like returned.")),as("whole_number (boolean, default=FALSE)",fs("Return a whole number or a decimal value."),[{value:!1,label:fs("Decimal (default)")},{value:!0,label:fs("Integer")}])],compute:function(e={value:1},t={value:1},s={value:0},o={value:1},i={value:!1}){const n=Io(t,this.locale),r=Io(e,this.locale),a=bo(s,this.locale),l=bo(o,this.locale),c=To(i);if(n<1)return new Cs(fs("The number of columns (%s) must be positive.",n));if(r<1)return new Cs(fs("The number of rows (%s) must be positive.",r));if(a>l)return new Cs(fs("The maximum (%s) must be greater than or equal to the minimum (%s).",l,a));if(c&&(!Number.isInteger(a)||!Number.isInteger(l)))return new Cs(fs("The maximum (%s) and minimum (%s) must be integers when whole_number is TRUE.",l.toString(),a.toString()));const h=Array(n);for(let e=0;e<n;e++){h[e]=Array(r);for(let t=0;t<r;t++)h[e][t]=c?Math.floor(Math.random()*(l-a+1)+a):a+Math.random()*(l-a)}return h},isExported:!0},Sa={description:fs("Random integer between two values, inclusive."),args:[as("low (number)",fs("The low end of the random range.")),as("high (number)",fs("The high end of the random range."))],compute:function(e,t){let s=bo(e,this.locale);Number.isInteger(s)||(s=Math.ceil(s));let o=bo(t,this.locale);return Number.isInteger(o)||(o=Math.floor(o)),s>o?new Cs(fs("The high (%s) must be greater than or equal to the low (%s).",o,s)):{value:s+Math.ceil((o-s+1)*Math.random())-1,format:e?.format}},isExported:!0},Ca={description:fs("Rounds a number according to standard rules."),args:[as("value (number)",fs("The value to round to places number of places.")),as("places (number, default=0)",fs("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const s=bo(e,this.locale);let o=bo(t,this.locale);const i=Math.abs(s);let n;return 0===o?n=Math.round(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.round(i*Math.pow(10,o))/Math.pow(10,o)),{value:s>=0?n:-n,format:e?.format}},isExported:!0},ya={description:fs("Rounds down a number."),args:[as("value (number)",fs("The value to round to places number of places, always rounding down.")),as("places (number, default=0)",fs("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const s=bo(e,this.locale);let o=bo(t,this.locale);const i=Math.abs(s);let n;return 0===o?n=Math.floor(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.floor(i*Math.pow(10,o))/Math.pow(10,o)),{value:s>=0?n:-n,format:e?.format}},isExported:!0},Ia={description:fs("Rounds up a number."),args:[as("value (number)",fs("The value to round to places number of places, always rounding up.")),as("places (number, default=0)",fs("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const s=bo(e,this.locale);let o=bo(t,this.locale);const i=Math.abs(s);let n;return 0===o?n=Math.ceil(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.ceil(i*Math.pow(10,o))/Math.pow(10,o)),{value:s>=0?n:-n,format:e?.format}},isExported:!0},wa={description:fs("Secant of an angle provided in radians."),args:[as("angle (number)",fs("The angle to find the secant of, in radians."))],compute:function(e){return 1/Math.cos(bo(e,this.locale))},isExported:!0},Ea={description:fs("Hyperbolic secant of any real number."),args:[as("value (number)",fs("Any real value to calculate the hyperbolic secant of."))],compute:function(e){return 1/Math.cosh(bo(e,this.locale))},isExported:!0},Ra={description:fs("Returns a sequence of numbers."),args:[as("rows (number)",fs("The number of rows to return")),as("columns (number, optional, default=1)",fs("The number of columns to return")),as("start (number, optional, default=1)",fs("The first number in the sequence")),as("step (number, optional, default=1)",fs("The amount to increment each value in the sequence"))],compute:function(e,t={value:1},s={value:1},o={value:1}){const i=bo(s,this.locale),n=bo(o,this.locale),r=Io(e,this.locale),a=Io(t,this.locale);return a<1?new Cs(fs("The number of columns (%s) must be positive.",a)):r<1?new Cs(fs("The number of rows (%s) must be positive.",r)):ko(a,r,(e,t)=>({value:i+t*a*n+e*n}))},isExported:!0},xa={description:fs("Sine of an angle provided in radians."),args:[as("angle (number)",fs("The angle to find the sine of, in radians."))],compute:function(e){return Math.sin(bo(e,this.locale))},isExported:!0},Ta={description:fs("Hyperbolic sine of any real number."),args:[as("value (number)",fs("Any real value to calculate the hyperbolic sine of."))],compute:function(e){return Math.sinh(bo(e,this.locale))},isExported:!0},Aa={description:fs("Positive square root of a positive number."),args:[as("value (number)",fs("The number for which to calculate the positive square root."))],compute:function(e){const t=bo(e,this.locale);return t<0?new Cs(fs("The value (%s) must be positive or null.",t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},Da={1:"AVERAGE",2:"COUNT",3:"COUNTA",4:"MAX",5:"MIN",6:"PRODUCT",7:"STDEV",8:"STDEVP",9:"SUM",10:"VAR",11:"VARP"},_a=Object.entries(Da).map(([e,t])=>({value:parseInt(e),label:fs("%s (include manually-hidden rows)",t)})),Oa=Object.entries(Da).map(([e,t])=>({value:parseInt(e)+100,label:fs("%s (exclude manually-hidden rows)",t)})),Fa={description:fs("Returns a subtotal for a vertical range of cells using a specified aggregation function."),args:[as("function_code (number)",fs("The function to use in subtotal aggregation."),[..._a,...Oa]),as("ref1 (meta, range<meta>)",fs("The range or reference for which you want the subtotal.")),as("ref2 (meta, range<meta>, repeating)",fs("Additional ranges or references for which you want the subtotal."))],compute:function(e,...t){let s=Io(e,this.locale),o=!0;if(s>100&&(s-=100,o=!1),s<1||s>11)return new Cs(fs("The function code (%s) must be between 1 to 11 or 101 to 111.",s));const i=[];for(const e of t){const t=e[0][0],s=tr(t.value).sheetName,n=s?this.getters.getSheetIdByName(s):this.__originSheetId;if(!n)continue;const{top:r,left:a}=wt(t.value),l=a+e.length-1,c=r+e[0].length-1;for(let e=r;e<=c;e++)if(!this.getters.isRowFiltered(n,e)&&(o||!this.getters.isRowHiddenByUser(n,e)))for(let t=a;t<=l;t++){const s=this.getters.getCell({sheetId:n,col:t,row:e});s&&wr(s)||i.push(this.getters.getEvaluatedCell({sheetId:n,col:t,row:e}))}}return this[Da[s]].apply(this,[[i]])},isExported:!0},Pa={description:fs("Sum of a series of numbers and/or cells."),args:[as("value1 (number, range<number>)",fs("The first number or range to add together.")),as("value2 (number, range<number>, repeating)",fs("Additional numbers or ranges to add to value1."))],compute:function(...e){const t=e[0];return{value:Er(e,this.locale),format:po(t)}},isExported:!0},Ma={description:fs("A conditional sum across a range."),args:[as("criteria_range (range)",fs("The range which is tested against criterion.")),as("criterion (string)",fs("The pattern or test to apply to range.")),as("sum_range (range, default=criteria_range)",fs("The range to be summed, if different from range."))],compute:function(e,t,s){void 0===s&&(s=e);let o=0;return $o([e,t],(e,t)=>{const i=s[e]?.[t]?.value;"number"==typeof i&&(o+=i)},this.locale),o},isExported:!0},Na={description:fs("Sums a range depending on multiple criteria."),args:[as("sum_range (range)",fs("The range to sum.")),as("criteria_range1 (range)",fs("The range to check against criterion1.")),as("criterion1 (string)",fs("The pattern or test to apply to criteria_range1.")),as("criteria_range2 (any, range, repeating)",fs("Additional ranges to check.")),as("criterion2 (string, repeating)",fs("Additional criteria to check."))],compute:function(e,...t){let s=0;return $o(t,(t,o)=>{const i=e[t]?.[o]?.value;"number"==typeof i&&(s+=i)},this.locale),s},isExported:!0},La={description:fs("Tangent of an angle provided in radians."),args:[as("angle (number)",fs("The angle to find the tangent of, in radians."))],compute:function(e){return Math.tan(bo(e,this.locale))},isExported:!0},ka={description:fs("Hyperbolic tangent of any real number."),args:[as("value (number)",fs("Any real value to calculate the hyperbolic tangent of."))],compute:function(e){return Math.tanh(bo(e,this.locale))},isExported:!0};function Va(e,t){return 0===t?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*Math.pow(10,t))/Math.pow(10,t))}const Ua={description:fs("Truncates a number."),args:[as("value (number)",fs("The value to be truncated.")),as("places (number, default=0)",fs("The number of significant digits to the right of the decimal point to retain."))],compute:function(e,t={value:0}){return{value:Va(bo(e,this.locale),bo(t,this.locale)),format:e?.format}},isExported:!0},Ha={description:fs("Rounds a number down to the nearest integer that is less than or equal to it."),args:[as("value (number)",fs("The number to round down to the nearest integer."))],compute:function(e){return Math.floor(bo(e,this.locale))},isExported:!0};var za=Object.freeze({__proto__:null,ABS:Tr,ACOS:Ar,ACOSH:Dr,ACOT:_r,ACOTH:Or,ASIN:Fr,ASINH:Pr,ATAN:Mr,ATAN2:Nr,ATANH:Lr,CEILING:kr,CEILING_MATH:Ur,CEILING_PRECISE:Hr,COS:zr,COSH:Br,COT:Gr,COTH:Wr,COUNTBLANK:$r,COUNTIF:qr,COUNTIFS:Zr,COUNTUNIQUE:jr,COUNTUNIQUEIFS:Yr,CSC:Xr,CSCH:Kr,DECIMAL:Jr,DEGREES:Qr,EXP:ea,FLOOR:ta,FLOOR_MATH:oa,FLOOR_PRECISE:ia,INT:Ha,ISEVEN:na,ISODD:aa,ISO_CEILING:ra,LN:la,LOG:ca,MOD:da,MUNIT:ua,ODD:ga,PI:pa,POWER:ma,PRODUCT:fa,RAND:va,RANDARRAY:ba,RANDBETWEEN:Sa,ROUND:Ca,ROUNDDOWN:ya,ROUNDUP:Ia,SEC:wa,SECH:Ea,SEQUENCE:Ra,SIN:xa,SINH:Ta,SQRT:Aa,SUBTOTAL:Fa,SUM:Pa,SUMIF:Ma,SUMIFS:Na,TAN:La,TANH:ka,TRUNC:Ua});function Ba(...e){const t=e[0].length;e.forEach((e,s)=>ri(e.length===t,fs("[[FUNCTION_NAME]] has mismatched dimensions for argument %s (%s vs %s).",s.toString(),t.toString(),e.length.toString())))}function Ga(e,t){let s=0;const o=No(e,(e,t)=>(s+=1,e+t),0,t);return ai(s),o/s}function Wa(e,t){let s=0;for(const o of e)if(Ds(o))for(const e of o)for(const t of e)"number"==typeof t.value&&(s+=1);else{const e=o?.value;mo(e)||"string"==typeof e&&!lo(e,t)&&!Zs(e,t)||(s+=1)}return s}function $a(e){return Mo(e,(e,t)=>void 0!==t&&null!==t.value?e+1:e,0)}function qa(e,t){let s={value:-1/0};return Fo(e,e=>{e.value>=s.value&&(s=e)},t),s.value===-1/0?{value:0}:s}function Za(e,t){let s={value:1/0};return Fo(e,e=>{e.value<=s.value&&(s=e)},t),s.value===1/0?{value:0}:s}function ja(e,t,s){const o=e[0].length?e:[ge(1,t.flat().length+1)],i=o.length;let n=s[0].length?s:o;return n=n.length===i?Uo(n):n,{_X:o,_newX:n}}function Ya(e,t,s=!0,o=!1){const i=t.flat(),n=i.length;let{_X:r}=ja(e,t,[[]]);r=r.length===n?Uo(r):r.slice(),Ba(r[0],i);const a=r.length,l=n-a-(s?1:0),c=[i],h=Uo(r.reverse()),d=[];for(let e=0;e<a;e++)if(d.push(0),s){for(const t of r[e])d[e]+=t;d[e]/=n}let u=0;if(s){for(const e of i)u+=e;u/=n}const g=h.map(e=>e.map((e,t)=>e-d[t]));s&&h.forEach(e=>e.push(1));const p=Ka(h,c);if(s||p.push([0]),!o)return p;const m=mi(g,Uo(g)),{inverted:f}=gi(m);if(void 0===f)throw new Cs(fs("Matrix is not invertible"));let v=0,b=0;for(let e=0;e<n;e++){const t=i[e]-u;let s=0;for(let t=0;t<a;t++){s+=g[e][t]*p[t][0]}const o=t-s;v+=o*o,b+=s*s}const S=Math.sqrt(v/l),C=b/(b+v),y=b/a/(v/l),I=[];for(let e=0;e<a;e++)I.push(S*Math.sqrt(f[e][e]));if(s){const e=mi(f,[d]),t=mi(Uo([d]),e);I.push(S*Math.sqrt(t[0][0]+1/i.length))}const w=[[p[0][0],I[0],C,y,b],[p[1][0],I[1],S,l,v]];for(let e=2;e<a;e++)w.push([p[e][0],I[e],"","",""]);return s?w.push([p[a][0],I[a],"","",""]):w.push([0,"","","",""]),w}function Xa(e,t,s,o){Ba(t,e),ri(s>=1,fs("Function [[FUNCTION_NAME]] A regression of order less than 1 cannot be possible."));const i=[e],n=t.map(e=>ge(0,s).map(t=>Math.pow(e,s-t)));o&&n.forEach(e=>e.push(1));const r=Ka(n,i);return o||r.push([0]),r}function Ka(e,t){const s=mi(e,Uo(e)),{inverted:o}=gi(s);if(void 0===o)throw new Cs(fs("Matrix is not invertible"));const i=mi(e,t);return Uo(mi(o,i))}function Ja(e,t,s){return e.reduce((e,o,i)=>e+o*Math.pow(t,s-i),0)}function Qa(e){return e.map(e=>e.map(e=>Math.exp(e)))}function el(e){return e.map(e=>e.map(e=>Math.log(e)))}function tl(e,t,s,o){const{_X:i,_newX:n}=ja(t,e,s),r=Ya(i,e,o,!1),a=r.length-1,l=n.map(e=>{let t=0;for(let s=0;s<a;s++)t+=r[s][0]*e[a-s-1];return t+=r[a][0],[t]});return l.length===s.length?l:Uo(l)}const sl=[{value:!0,label:fs("b is calculated normally")},{value:!1,label:fs("b is forced to 1")}],ol=[{value:!1,label:fs("do not return additional regression statistics")},{value:!0,label:fs("return additional regression statistics")}],il=[{value:1,label:fs("order 1 (Linear)")},{value:2,label:fs("order 2 (Quadratic)")},{value:3,label:fs("order 3 (Cubic)")},{value:4,label:fs("order 4 (Quartic)")},{value:5,label:fs("order 5 (Quintic)")},{value:6,label:fs("order 6 (Sextic)")}],nl=[{value:!0,label:fs("Compute intercept")},{value:!1,label:fs("Force intercept to 0")}],rl=[{value:0,label:fs("Minimum value")},{value:1,label:fs("First quartile (25th percentile)")},{value:2,label:fs("Median value (50th percentile)")},{value:3,label:fs("Third quartile (75th percentile)")},{value:4,label:fs("Maximum value")}];function al(e,t){const s=[],o=[];let i=0,n=0;Oo([e],e=>{s.push(e),i+=1}),Oo([t],e=>{o.push(e),n+=1}),ri(i===n,fs("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",i,n));const r=[],a=[];for(let e=0;e<i;e++){const t=s[e]?.value,i=o[e]?.value;"number"==typeof t&&"number"==typeof i&&(a.push(t),r.push(i))}return{flatDataX:r,flatDataY:a}}function ll(e,t,s){const{flatDataX:o,flatDataY:i}=al(e,t),n=i.length;ai(n),s&&ai(n-1);let r=0,a=0;for(let e=0;e<n;e++)r+=i[e],a+=o[e];const l=r/n,c=a/n;let h=0;for(let e=0;e<n;e++)h+=(i[e]-l)*(o[e]-c);return h/(n-(s?1:0))}function cl(e,t,s,o){let i=0;const n=s?Lo:No,r=n(e,(e,t)=>(i+=1,e+t),0,o);ai(i),t&&ai(i-1);const a=r/i;return n(e,(e,t)=>e+Math.pow(t-a,2),0,o)/(i-(t?1:0))}function hl(e,t,s,o){const i=bo(t,o);ri(s?0<=i&&i<=1:0<i&&i<1,fs("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));const n=[];let r,a=0;return Oo(e,e=>{const t=e?.value;"number"==typeof t&&(r=qo(n,e,"nextSmaller","asc",n.length,(e,t)=>e[t]),n.splice(r+1,0,t),a++)}),ri(0!==a,Qo),s||ri(1/(a+1)<=i&&i<=a/(a+1),fs("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),uo(n,i,s)}const dl={description:fs("Average magnitude of deviations from mean."),args:[as("value1 (number, range<number>)",fs("The first value or range of the sample.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to include in the sample."))],compute:function(...e){let t=0;const s=No(e,(e,s)=>(t+=1,e+s),0,this.locale);if(0===t)return new Ts(fs("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const o=s/t;return No(e,(e,t)=>e+Math.abs(o-t),0,this.locale)/t},isExported:!0},ul={description:fs("Numerical average value in a dataset, ignoring text."),args:[as("value1 (number, range<number>)",fs("The first value or range to consider when calculating the average value.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to consider when calculating the average value."))],compute:function(...e){return{value:Ga(e,this.locale),format:po(e[0])}},isExported:!0},gl=fs("[[FUNCTION_NAME]] has mismatched range sizes."),pl=fs("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),ml={description:fs("Weighted average."),args:[as("values (number, range<number>)",fs("Values to average.")),as("weights (number, range<number>)",fs("Weights for each corresponding value.")),as("additional_values (number, range<number>, repeating)",fs("Additional values to average.")),as("additional_weights (number, range<number>, repeating)",fs("Additional weights."))],compute:function(...e){let t=0,s=0;for(let o=0;o<e.length-1;o+=2){const i=e[o],n=e[o+1];if(!ci(i,n))return new Cs(gl);if(Ds(i))for(let e=0;e<i.length;e++)for(let o=0;o<i[0].length;o++){const r=i[e][o].value,a=Ds(n)?n?.[e][o].value:bo(n,this.locale),l="number"==typeof r,c="number"==typeof a;if(l&&c){if(a<0)return new Cs(pl);t+=r*a,s+=a}else if(l!==c)return new Cs(fs("[[FUNCTION_NAME]] expects number values."))}else{const e=bo(i,this.locale),o=Ds(n)?n?.[0][0].value:bo(n,this.locale);if("number"==typeof o){if(o<0)return new Cs(pl);t+=e*o,s+=o}}}return 0===s?new Ts(fs("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):{value:t/s,format:po(e[0])}}},fl={description:fs("Numerical average value in a dataset."),args:[as("value1 (number, range<number>)",fs("The first value or range to consider when calculating the average value.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to consider when calculating the average value."))],compute:function(...e){let t=0;const s=Lo(e,(e,s)=>(t+=1,e+s),0,this.locale);return 0===t?new Ts(fs("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):{value:s/t,format:po(e[0])}},isExported:!0},vl={description:fs("Average of values depending on criteria."),args:[as("criteria_range (number, range<number>)",fs("The range to check against criterion.")),as("criterion (string)",fs("The pattern or test to apply to criteria_range.")),as("average_range (number, range<number>, default=criteria_range)",fs("The range to average. If not included, criteria_range is used for the average instead."))],compute:function(e,t,s){const o=Xo(void 0===s?e:s);let i=0,n=0;return $o([e,t],(e,t)=>{const s=o[e]?.[t]?.value;"number"==typeof s&&(i+=1,n+=s)},this.locale),0===i?new Ts(fs("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):n/i},isExported:!0},bl={description:fs("Average of values depending on multiple criteria."),args:[as("average_range (range)",fs("The range to average.")),as("criteria_range1 (range)",fs("The range to check against criterion1.")),as("criterion1 (string)",fs("The pattern or test to apply to criteria_range1.")),as("criteria_range2 (any, range, repeating)",fs("Additional criteria_range and criterion to check.")),as("criterion2 (string, repeating)",fs("The pattern or test to apply to criteria_range2."))],compute:function(e,...t){const s=Xo(e);let o=0,i=0;return $o(t,(e,t)=>{const n=s[e]?.[t]?.value;"number"==typeof n&&(o+=1,i+=n)},this.locale),0===o?new Ts(fs("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):i/o},isExported:!0},Sl={description:fs("The number of numeric values in dataset."),args:[as("value1 (number, any, range<number>)",fs("The first value or range to consider when counting.")),as("value2 (number, any, range<number>, repeating)",fs("Additional values or ranges to consider when counting."))],compute:function(...e){return Wa(e,this.locale)},isExported:!0},Cl={description:fs("The number of values in a dataset."),args:[as("value1 (any, range)",fs("The first value or range to consider when counting.")),as("value2 (any, range, repeating)",fs("Additional values or ranges to consider when counting."))],compute:function(...e){return $a(e)},isExported:!0},yl={description:fs("The covariance of a dataset."),args:[as("data_y (any, range)",fs("The range representing the array or matrix of dependent data.")),as("data_x (any, range)",fs("The range representing the array or matrix of independent data."))],compute:function(e,t){return ll(e,t,!1)},isExported:!0},Il={description:fs("The covariance of a dataset."),args:[as("data_y (any, range)",fs("The range representing the array or matrix of dependent data.")),as("data_x (any, range)",fs("The range representing the array or matrix of independent data."))],compute:function(e,t){return ll(e,t,!1)},isExported:!0},wl={description:fs("The sample covariance of a dataset."),args:[as("data_y (any, range)",fs("The range representing the array or matrix of dependent data.")),as("data_x (any, range)",fs("The range representing the array or matrix of independent data."))],compute:function(e,t){return ll(e,t,!0)},isExported:!0},El={description:fs("Calculates the expected y-value for a specified x based on a linear regression of a dataset."),args:[as("x (number, range<number>)",fs("The value(s) on the x-axis to forecast.")),as("data_y (range<number>)",fs("The range representing the array or matrix of dependent data.")),as("data_x (range<number>)",fs("The range representing the array or matrix of independent data."))],compute:function(e,t,s){const{flatDataX:o,flatDataY:i}=al(t,s);return 0===o.length||0===i.length?new Es(Qo):tl([i],[o],Vo(Xo(e),e=>bo(e,this.locale)),!0)},isExported:!0},Rl={description:fs("Fits points to exponential growth trend."),args:[as("known_data_y (range<number>)",fs("The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.")),as("known_data_x (range<number>, default={1;2;3;...})",fs("The values of the independent variable(s) corresponding with known_data_y.")),as("new_data_x (any, range, default=known_data_x)",fs("The data points to return the y values for on the ideal curve fit.")),as("b (boolean, default=TRUE)",fs("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."),sl)],compute:function(e,t=[[]],s=[[]],o={value:!0}){return 0===e.length||0===e[0].length?new Cs(ei("known_data_y")):Qa(tl(el(Co(e,"known_data_y")),Co(t,"known_data_x"),Co(s,"new_data_y"),To(o)))}},xl={description:fs("Compute the intercept of the linear regression."),args:[as("data_y (range<number>)",fs("The range representing the array or matrix of dependent data.")),as("data_x (range<number>)",fs("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:s,flatDataY:o}=al(e,t);if(0===s.length||0===o.length)return new Es(Qo);const[[],[i]]=Ya([s],[o]);return i},isExported:!0},Tl={description:fs("Nth largest element from a data set."),args:[as("data (any, range)",fs("Array or range containing the dataset to consider.")),as("n (number)",fs("The rank from largest to smallest of the element to return."))],compute:function(e,t){const s=Math.trunc(bo(t?.value,this.locale)),o=[];let i,n=0;Oo([e],e=>{"number"==typeof e?.value&&(i=qo(o,e,"nextSmaller","asc",o.length,(e,t)=>e[t].value),o.splice(i+1,0,e),n++,n>s&&(o.shift(),n--))});const r=o.shift();return void 0===r?new Cs(Qo):n<s?new Cs(fs("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s)):r},isExported:!0},Al={description:fs("Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method."),args:[as("data_y (range<number>)",fs("The range representing the array or matrix of dependent data.")),as("data_x (range<number>, default={1;2;3;...})",fs("The range representing the array or matrix of independent data.")),as("calculate_b (boolean, default=TRUE)",fs("A flag specifying whether to compute the slope or not"),sl),as("verbose (boolean, default=FALSE)",fs("A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept"),ol)],compute:function(e,t=[[]],s={value:!0},o={value:!1}){return 0===e.length||0===e[0].length?new Cs(ei("data_y")):Ya(Co(t,"data_x"),Co(e,"data_y"),To(s),To(o))},isExported:!0},Dl={description:fs("Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve."),args:[as("data_y (range<number>)",fs("The range representing the array or matrix of dependent data.")),as("data_x (range<number>, optional, default={1;2;3;...})",fs("The range representing the array or matrix of independent data.")),as("calculate_b (boolean, default=TRUE)",fs("A flag specifying whether to compute the slope or not"),sl),as("verbose (boolean, default=FALSE)",fs("A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept"),ol)],compute:function(e,t=[[]],s={value:!0},o={value:!1}){if(0===e.length||0===e[0].length)return new Cs(ei("data_y"));const i=Ya(Co(t,"data_x"),el(Co(e,"data_y")),To(s),To(o));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},_l={description:fs("Compute the Matthews correlation coefficient of a dataset."),args:[as("data_x (range)",fs("The range representing the array or matrix of observed data.")),as("data_y (range)",fs("The range representing the array or matrix of predicted data."))],compute:function(e,t){const s=e.flat(),o=t.flat();if(Ba(s,o),0===s.length||0===o.length)return new Es(Qo);const i=s.length;let n=0,r=0,a=0,l=0;for(let e=0;e<i;++e){const t=To(s[e]);t===To(o[e])?t?r++:n++:t?l++:a++}return(r*n-a*l)/Math.sqrt((r+a)*(r+l)*(n+a)*(n+l))},isExported:!1},Ol={description:fs("Maximum value in a numeric dataset."),args:[as("value1 (number, range<number>)",fs("The first value or range to consider when calculating the maximum value.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to consider when calculating the maximum value."))],compute:function(...e){return qa(e,this.locale)},isExported:!0},Fl={description:fs("Maximum numeric value in a dataset."),args:[as("value1 (any, range)",fs("The first value or range to consider when calculating the maximum value.")),as("value2 (any, range, repeating)",fs("Additional values or ranges to consider when calculating the maximum value."))],compute:function(...e){const t=Lo(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:po(e[0])}},isExported:!0},Pl={description:fs("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:[as("range (range)",fs("The range of cells from which the maximum will be determined.")),as("criteria_range1 (range)",fs("The range of cells over which to evaluate criterion1.")),as("criterion1 (string)",fs("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),as("criteria_range2 (any, range, repeating)",fs("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.")),as("criterion2 (string, repeating)",fs("The pattern or test to apply to criteria_range2."))],compute:function(e,...t){let s=-1/0;return $o(t,(t,o)=>{const i=e[t]?.[o]?.value;"number"==typeof i&&(s=s<i?i:s)},this.locale),s===-1/0?0:s},isExported:!0},Ml={description:fs("Median value in a numeric dataset."),args:[as("value1 (any, range)",fs("The first value or range to consider when calculating the median value.")),as("value2 (any, range, repeating)",fs("Additional values or ranges to consider when calculating the median value."))],compute:function(...e){const t=[];return Fo(e,e=>{t.push(e)},this.locale),{value:hl(t,{value:.5},!0,this.locale),format:po(t[0])}},isExported:!0},Nl={description:fs("Minimum value in a numeric dataset."),args:[as("value1 (number, range<number>)",fs("The first value or range to consider when calculating the minimum value.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to consider when calculating the minimum value."))],compute:function(...e){return Za(e,this.locale)},isExported:!0},Ll={description:fs("Minimum numeric value in a dataset."),args:[as("value1 (number, range<number>)",fs("The first value or range to consider when calculating the minimum value.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to consider when calculating the minimum value."))],compute:function(...e){const t=Lo(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:po(e[0])}},isExported:!0},kl={description:fs("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:[as("range (range)",fs("The range of cells from which the minimum will be determined.")),as("criteria_range1 (range)",fs("The range of cells over which to evaluate criterion1.")),as("criterion1 (string)",fs("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),as("criteria_range2 (any, range, repeating)",fs("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.")),as("criterion2 (string, repeating)",fs("The pattern or test to apply to criteria_range2."))],compute:function(e,...t){let s=1/0;return $o(t,(t,o)=>{const i=e[t]?.[o]?.value;"number"==typeof i&&(s=s>i?i:s)},this.locale),s===1/0?0:s},isExported:!0};function Vl(e,t){const{flatDataX:s,flatDataY:o}=al(e,t);if(0===s.length||0===o.length)return new Es(Qo);const i=s.length;let n=0,r=0,a=0,l=0,c=0;for(let e=0;e<i;e++){const t=s[e],i=o[e];n+=t,r+=i,a+=t*i,l+=t*t,c+=i*i}return(i*a-n*r)/Math.sqrt((i*l-n*n)*(i*c-r*r))}const Ul={description:fs("Compute the Pearson product-moment correlation coefficient of a dataset."),args:[as("data_y (range<number>)",fs("The range representing the array or matrix of dependent data.")),as("data_x (range<number>)",fs("The range representing the array or matrix of independent data."))],compute:function(e,t){return Vl(e,t)},isExported:!0},Hl=Ul,zl={description:fs("Value at a given percentile of a dataset."),args:[as("data (any, range)",fs("The array or range containing the dataset to consider.")),as("percentile (number)",fs("The percentile whose value within data will be calculated and returned."))],compute:function(e,t){return Gl.compute.bind(this)(e,t)},isExported:!0},Bl={description:fs("Value at a given percentile of a dataset exclusive of 0 and 1."),args:[as("data (any, range)",fs("The array or range containing the dataset to consider.")),as("percentile (number)",fs("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned."))],compute:function(e,t){return{value:hl([e],t,!1,this.locale),format:po(e)}},isExported:!0},Gl={description:fs("Value at a given percentile of a dataset."),args:[as("data (any, range)",fs("The array or range containing the dataset to consider.")),as("percentile (number)",fs("The percentile whose value within data will be calculated and returned."))],compute:function(e,t){return{value:hl([e],t,!0,this.locale),format:po(e)}},isExported:!0},Wl={description:fs("Compute the coefficients of polynomial regression of the dataset."),args:[as("data_y (range<number>)",fs("The range representing the array or matrix of dependent data.")),as("data_x (range<number>)",fs("The range representing the array or matrix of independent data.")),as("order (number)",fs("The order of the polynomial to fit the data, between 1 and 6."),il),as("intercept (boolean, default=TRUE)",fs("A flag specifying whether to compute the intercept or not."),nl)],compute:function(e,t,s,o={value:!0}){const{flatDataX:i,flatDataY:n}=al(e,t);return 0===i.length||0===n.length?new Es(Qo):Xa(n,i,bo(s,this.locale),To(o))},isExported:!1},$l={description:fs("Predict value by computing a polynomial regression of the dataset."),args:[as("x (number, range<number>)",fs("The value(s) on the x-axis to forecast.")),as("data_y (range<number>)",fs("The range representing the array or matrix of dependent data.")),as("data_x (range<number>)",fs("The range representing the array or matrix of independent data.")),as("order (number)",fs("The order of the polynomial to fit the data, between 1 and 6."),il),as("intercept (boolean, default=TRUE)",fs("A flag specifying whether to compute the intercept or not."),nl)],compute:function(e,t,s,o,i={value:!0}){const n=bo(o,this.locale),{flatDataX:r,flatDataY:a}=al(t,s);if(0===r.length||0===a.length)return new Es(Qo);const l=Xa(a,r,n,To(i)).flat();return Vo(Xo(e),e=>Ja(l,bo(e,this.locale),n))},isExported:!1},ql={description:fs("Value nearest to a specific quartile of a dataset."),args:[as("data (any, range)",fs("The array or range containing the dataset to consider.")),as("quartile_number (number)",fs("Which quartile value to return."),rl)],compute:function(e,t){return jl.compute.bind(this)(e,t)},isExported:!0},Zl={description:fs("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:[as("data (any, range)",fs("The array or range containing the dataset to consider.")),as("quartile_number (number)",fs("Which quartile value, exclusive of 0 and 4, to return."),[{value:1,label:fs("First quartile (25th percentile)")},{value:2,label:fs("Median value (50th percentile)")},{value:3,label:fs("Third quartile (75th percentile)")}])],compute:function(e,t){return{value:hl([e],{value:.25*Math.trunc(bo(t,this.locale))},!1,this.locale),format:po(e)}},isExported:!0},jl={description:fs("Value nearest to a specific quartile of a dataset."),args:[as("data (any, range)",fs("The array or range containing the dataset to consider.")),as("quartile_number (number)",fs("Which quartile value to return."),rl)],compute:function(e,t){return{value:hl([e],{value:.25*Math.trunc(bo(t,this.locale))},!0,this.locale),format:po(e)}},isExported:!0},Yl={description:fs("Returns the rank of a specified value in a dataset."),args:[as("value (number)",fs("The value whose rank will be determined.")),as("data (range)",fs("The range containing the dataset to consider.")),as("is_ascending (boolean, default=FALSE)",fs("Whether to consider the values in data in descending or ascending order."),[{value:!1,label:fs("Descending")},{value:!0,label:fs("Ascending")}])],compute:function(e,t,s={value:!1}){const o=To(s),i=bo(e,this.locale);let n=1,r=!1;for(const e of t)for(const t of e){if("number"!=typeof t.value)continue;const e=bo(t,this.locale);e===i?r=!0:e>i!==o&&n++}return r?n:new Es(fs("Value not found in the given data."))},isExported:!0},Xl={description:fs("Compute the square of r, the Pearson product-moment correlation coefficient of a dataset."),args:[as("data_y (range<number>)",fs("The range representing the array or matrix of dependent data.")),as("data_x (range<number>)",fs("The range representing the array or matrix of independent data."))],compute:function(e,t){const s=Vl(e,t);if(s instanceof Error)throw s;return Math.pow(s,2)},isExported:!0},Kl={description:fs("Compute the slope of the linear regression."),args:[as("data_y (range<number>)",fs("The range representing the array or matrix of dependent data.")),as("data_x (range<number>)",fs("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:s,flatDataY:o}=al(e,t);if(0===s.length||0===o.length)return new Es(Qo);const[[i]]=Ya([s],[o]);return i},isExported:!0},Jl={description:fs("Nth smallest element in a data set."),args:[as("data (any, range)",fs("The array or range containing the dataset to consider.")),as("n (number)",fs("The rank from smallest to largest of the element to return."))],compute:function(e,t){const s=Math.trunc(bo(t?.value,this.locale)),o=[];let i,n=0;Oo([e],e=>{"number"==typeof e?.value&&(i=qo(o,e,"nextSmaller","asc",o.length,(e,t)=>e[t].value),o.splice(i+1,0,e),n++,n>s&&(o.pop(),n--))});const r=o.pop();return void 0===r?new Cs(Qo):n<s?new Cs(fs("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s)):r},isExported:!0},Ql={description:fs("Compute the Spearman rank correlation coefficient of a dataset."),args:[as("data_y (range<number>)",fs("The range representing the array or matrix of dependent data.")),as("data_x (range<number>)",fs("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:s,flatDataY:o}=al(t,e);if(0===s.length||0===o.length)return new Es(Qo);const i=s.length,n=s.map((e,t)=>[e,o[t]]);n.sort((e,t)=>e[0]-t[0]);for(let e=0;e<i;++e)n[e][0]=e;n.sort((e,t)=>e[1]-t[1]);let r=0;for(let e=0;e<i;++e)r+=(n[e][0]-e)**2;return 1-6*r/(i**3-i)},isExported:!1},ec={description:fs("Standard deviation."),args:[as("value1 (number, range<number>)",fs("The first value or range of the sample.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to include in the sample."))],compute:function(...e){return Math.sqrt(lc.compute.bind(this)(...e))},isExported:!0},tc={description:fs("Standard deviation of entire population."),args:[as("value1 (number, range<number>)",fs("The first value or range of the population.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to include in the population."))],compute:function(...e){return Math.sqrt(cc.compute.bind(this)(...e))},isExported:!0},sc={description:fs("Standard deviation."),args:[as("value1 (number, range<number>)",fs("The first value or range of the sample.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to include in the sample."))],compute:function(...e){return Math.sqrt(hc.compute.bind(this)(...e))},isExported:!0},oc={description:fs("Standard deviation of sample (text as 0)."),args:[as("value1 (number, range<number>)",fs("The first value or range of the sample.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to include in the sample."))],compute:function(...e){return Math.sqrt(dc.compute.bind(this)(...e))},isExported:!0},ic={description:fs("Standard deviation of entire population."),args:[as("value1 (number, range<number>)",fs("The first value or range of the population.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to include in the population."))],compute:function(...e){return Math.sqrt(uc.compute.bind(this)(...e))},isExported:!0},nc={description:fs("Standard deviation of entire population (text as 0)."),args:[as("value1 (number, range<number>)",fs("The first value or range of the population.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to include in the population."))],compute:function(...e){return Math.sqrt(gc.compute.bind(this)(...e))},isExported:!0},rc={description:fs("Calculates the standard error of the predicted y-value for each x in the regression of a dataset."),args:[as("data_y (range<number>)",fs("The range representing the array or matrix of dependent data.")),as("data_x (range<number>)",fs("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:s,flatDataY:o}=al(e,t);if(0===s.length||0===o.length)return new Es(Qo);return Ya([s],[o],!0,!0)[1][2]},isExported:!0},ac={description:fs("Fits points to linear trend derived via least-squares."),args:[as("known_data_y (number, range<number>)",fs("The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.")),as("known_data_x (number, range<number>, optional, default={1;2;3;...})",fs("The values of the independent variable(s) corresponding with known_data_y.")),as("new_data_x (number, range<number>, optional, default=known_data_x)",fs("The data points to return the y values for on the ideal curve fit.")),as("b (boolean, optional, default=TRUE)",fs("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."),sl)],compute:function(e,t=[[]],s=[[]],o={value:!0}){return 0===e.length||0===e[0].length?new Cs(ei("known_data_y")):tl(Co(e,"known_data_y"),Co(t,"known_data_x"),Co(s,"new_data_y"),To(o))}},lc={description:fs("Variance."),args:[as("value1 (number, range<number>)",fs("The first value or range of the sample.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to include in the sample."))],compute:function(...e){return cl(e,!0,!1,this.locale)},isExported:!0},cc={description:fs("Variance of entire population."),args:[as("value1 (number, range<number>)",fs("The first value or range of the population.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to include in the population."))],compute:function(...e){return cl(e,!1,!1,this.locale)},isExported:!0},hc={description:fs("Variance."),args:[as("value1 (number, range<number>)",fs("The first value or range of the sample.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to include in the sample."))],compute:function(...e){return cl(e,!0,!1,this.locale)},isExported:!0},dc={description:fs("Variance of sample (text as 0)."),args:[as("value1 (number, range<number>)",fs("The first value or range of the sample.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to include in the sample."))],compute:function(...e){return cl(e,!0,!0,this.locale)},isExported:!0},uc={description:fs("Variance of entire population."),args:[as("value1 (number, range<number>)",fs("The first value or range of the population.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to include in the population."))],compute:function(...e){return cl(e,!1,!1,this.locale)},isExported:!0},gc={description:fs("Variance of entire population (text as 0)."),args:[as("value1 (number, range<number>)",fs("The first value or range of the population.")),as("value2 (number, range<number>, repeating)",fs("Additional values or ranges to include in the population."))],compute:function(...e){return cl(e,!1,!0,this.locale)},isExported:!0};var pc=Object.freeze({__proto__:null,AVEDEV:dl,AVERAGE:ul,AVERAGEA:fl,AVERAGEIF:vl,AVERAGEIFS:bl,AVERAGE_WEIGHTED:ml,CORREL:Hl,COUNT:Sl,COUNTA:Cl,COVAR:yl,COVARIANCE_P:Il,COVARIANCE_S:wl,FORECAST:El,GROWTH:Rl,INTERCEPT:xl,LARGE:Tl,LINEST:Al,LOGEST:Dl,MATTHEWS:_l,MAX:Ol,MAXA:Fl,MAXIFS:Pl,MEDIAN:Ml,MIN:Nl,MINA:Ll,MINIFS:kl,PEARSON:Ul,PERCENTILE:zl,PERCENTILE_EXC:Bl,PERCENTILE_INC:Gl,POLYFIT_COEFFS:Wl,POLYFIT_FORECAST:$l,QUARTILE:ql,QUARTILE_EXC:Zl,QUARTILE_INC:jl,RANK:Yl,RSQ:Xl,SLOPE:Kl,SMALL:Jl,SPEARMAN:Ql,STDEV:ec,STDEVA:oc,STDEVP:ic,STDEVPA:nc,STDEV_P:tc,STDEV_S:sc,STEYX:rc,TREND:ac,VAR:lc,VARA:dc,VARP:uc,VARPA:gc,VAR_P:cc,VAR_S:hc});function mc(e,t,s,o){const i=new Map,n=e.length;for(let t=n-1;t>=0;t--)i.set(Eo(e[t][0]).toUpperCase(),t);const r=t?.value;if("number"!=typeof r&&"string"!=typeof r)throw new Cs(fs("The field must be a number or a string"));let a;if("number"==typeof r){if(a=Math.trunc(r)-1,a<0||n-1<a)throw new Cs(fs("The field (%(fieldValue)s) must be one of %(dimRowDB)s or must be a number between 1 and %s inclusive.",{fieldValue:r.toString(),dimRowDB:n.toString()}))}else{const e=Eo(t).toUpperCase();if(a=i.get(e)??-1,-1===a)throw new Cs(fs("The field (%s) must be one of %s.",Eo(t),[...i.keys()].toString()))}const l=s[0].length;if(l<2)throw new Cs(fs("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const h=e[0].length;for(let t=1;t<l;t++){const n=[];let r=!0;for(let o=0;o<s.length;o++){const a=Eo(s[o][0]).toUpperCase(),l=i.get(a),c=s[o][t];if(null!==c.value){if(void 0===l){r=!1;break}n.push([e[l].slice(1,h)]),n.push(c)}}if(r){if(!(n.length>0)){c=new Set(Array(h-1).keys());break}$o(n,(e,t)=>{c.add(t)},o,!0)}}const d=e[a];return[...c].map(e=>d[e+1])}const fc=[as("database (range)",fs("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.")),as("field (number, string)",fs("Indicates which column in database contains the values to be extracted and operated on.")),as("criteria (range)",fs("An array or range containing zero or more criteria to filter the database values by before operating."))],vc={description:fs("Average of a set of values from a table-like range."),args:fc,compute:function(e,t,s){const o=mc(e,t,s,this.locale);return ul.compute.bind(this)([o])},isExported:!0},bc={description:fs("Counts values from a table-like range."),args:fc,compute:function(e,t,s){const o=mc(e,t,s,this.locale);return Sl.compute.bind(this)([o])},isExported:!0},Sc={description:fs("Counts values and text from a table-like range."),args:fc,compute:function(e,t,s){const o=mc(e,t,s,this.locale);return Cl.compute.bind(this)([o])},isExported:!0},Cc={description:fs("Single value from a table-like range."),args:fc,compute:function(e,t,s){const o=mc(e,t,s,this.locale);return 1!==o.length?new Cs(fs("More than one match found in DGET evaluation.")):o[0]},isExported:!0},yc={description:fs("Maximum of values from a table-like range."),args:fc,compute:function(e,t,s){const o=mc(e,t,s,this.locale);return Ol.compute.bind(this)([o])},isExported:!0},Ic={description:fs("Minimum of values from a table-like range."),args:fc,compute:function(e,t,s){const o=mc(e,t,s,this.locale);return Nl.compute.bind(this)([o])},isExported:!0},wc={description:fs("Product of values from a table-like range."),args:fc,compute:function(e,t,s){const o=mc(e,t,s,this.locale);return fa.compute.bind(this)([o])},isExported:!0},Ec={description:fs("Standard deviation of population sample from table."),args:fc,compute:function(e,t,s){const o=mc(e,t,s,this.locale);return ec.compute.bind(this)([o])},isExported:!0},Rc={description:fs("Standard deviation of entire population from table."),args:fc,compute:function(e,t,s){const o=mc(e,t,s,this.locale);return ic.compute.bind(this)([o])},isExported:!0},xc={description:fs("Sum of values from a table-like range."),args:fc,compute:function(e,t,s){const o=mc(e,t,s,this.locale);return Pa.compute.bind(this)([o])},isExported:!0},Tc={description:fs("Variance of population sample from table-like range."),args:fc,compute:function(e,t,s){const o=mc(e,t,s,this.locale);return lc.compute.bind(this)([o])},isExported:!0},Ac={description:fs("Variance of a population from a table-like range."),args:fc,compute:function(e,t,s){const o=mc(e,t,s,this.locale);return uc.compute.bind(this)([o])},isExported:!0};var Dc=Object.freeze({__proto__:null,DAVERAGE:vc,DCOUNT:bc,DCOUNTA:Sc,DGET:Cc,DMAX:yc,DMIN:Ic,DPRODUCT:wc,DSTDEV:Ec,DSTDEVP:Rc,DSUM:xc,DVAR:Tc,DVARP:Ac});const _c=[{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:";"}],Oc=_c[0],Fc=["%"],Pc="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(Fc);function Mc(e,t=Oc){e=Ge(e);const s=new Qe(e),o=[],i=He.test(e)?qc:Zc;for(;!s.isOver();){let e=jc(s)||i(s)||Vc(s,t)||kc(s)||Uc(s)||Bc(s)||Nc(s)||Yc(s)||zc(s,t)||$c(s);e||(e={type:"UNKNOWN",value:s.shift()}),o.push(e)}return o}function Nc(e){return"?"===e.current?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const Lc={"(":{type:"LEFT_PAREN",value:"("},")":{type:"RIGHT_PAREN",value:")"}};function kc(e){if("("===e.current||")"===e.current){const t=e.shift();return Lc[t]}return null}function Vc(e,t){if(e.current===t.formulaArgSeparator){return{type:"ARG_SEPARATOR",value:e.shift()}}return null}function Uc(e){for(const t of Pc)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:"OPERATOR",value:t};return null}const Hc=new Set("0123456789");function zc(e,t){if(!Hc.has(e.current)&&e.current!==t.decimalSeparator)return null;const s=e.remaining().match(ro(t.decimalSeparator));return s?(e.advanceBy(s[0].length),{type:"NUMBER",value:s[0]}):null}function Bc(e){if('"'===e.current){const t=e.shift();let s=t;for(;e.current&&(e.current!==t||"\\"===s[s.length-1]);)s+=e.shift();return'"'===e.current&&(s+=e.shift()),{type:"STRING",value:s}}return null}const Gc=/\p{L}|\p{N}|_|\.|!|\$/u,Wc=new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$");function $c(e){let t="";if("'"===e.current){let s=e.shift();for(t+=s;e.current;)if(s=e.shift(),t+=s,"'"===s){if(!e.current||"'"!==e.current)break;s=e.shift(),t+=s}if("'"!==s)return{type:"UNKNOWN",value:t}}for(;e.current&&(Wc.has(e.current)||e.current.match(Gc));)t+=e.shift();if(t.length){const e=t;return Xn.test(e)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}function qc(e){let t="";for(;" "===e.current||e.current&&e.current.match(He);)t+=e.shift();return t?{type:"SPACE",value:t}:null}function Zc(e){let t="";for(;" "===e.current;)t+=e.shift();return t?{type:"SPACE",value:t}:null}function jc(e){let t=0;for(;e.current===X;)t++,e.shift();return t?{type:"SPACE",value:X.repeat(t)}:null}function Yc(e){return e.currentStartsWith(bs.InvalidReference)?(e.advanceBy(bs.InvalidReference.length),{type:"INVALID_REFERENCE",value:bs.InvalidReference}):null}function Xc(e){if(!e||"object"!=typeof e||e.thousandsSeparator&&"string"!=typeof e.thousandsSeparator)return!1;for(const t of["code","name","decimalSeparator","dateFormat","timeFormat","formulaArgSeparator"])if(!e[t]||"string"!=typeof e[t])return!1;if(e.formulaArgSeparator===e.decimalSeparator)return!1;if(e.thousandsSeparator===e.decimalSeparator)return!1;try{pn(1,{locale:e,format:"#,##0.00"}),pn(1,{locale:e,format:e.dateFormat}),pn(1,{locale:e,format:e.timeFormat})}catch{return!1}return!0}function Kc(e,t){return ot(e)?th(e,t):ih(e,t)}function Jc(e,t){return ot(e)?th(e,t):function(e,t){if($s(e,t)){const s=bo(e,t);let o=Oc.dateFormat;return Number.isInteger(s)||(o+=" "+Oc.timeFormat),pn(s,{locale:Oc,format:o})}return ih(e,t)}(e,t)}function Qc(e,t){return e.startsWith("=")?sh(e,t):function(e,t){if($s(e,Oc)){const s=bo(e,Oc);let o=t.dateFormat;return Number.isInteger(s)||(o+=" "+t.timeFormat),pn(s,{locale:t,format:o})}return function(e,t){if("."===t.decimalSeparator||!lo(e,Oc))return e;const s=Rn(Oc);return e.replace(s,e=>e.replace(".",t.decimalSeparator))}(e,t)}(e,t)}function eh(e,t){return ot(e)?th(e,t):ih(e,t)}function th(e,t){return oh(e.startsWith("+")?"="+e.slice(1):e,t,Oc)}function sh(e,t){return oh(e,Oc,t)}function oh(e,t,s){if(t.formulaArgSeparator===s.formulaArgSeparator&&t.decimalSeparator===s.decimalSeparator)return e;const o=Mc(e,t);let i="";for(const e of o)"NUMBER"===e.type?i+=e.value.replace(t.decimalSeparator,s.decimalSeparator):"ARG_SEPARATOR"===e.type?i+=s.formulaArgSeparator:i+=e.value;return i}function ih(e,t){return"."!==t.decimalSeparator&&lo(e,t)?(t.thousandsSeparator&&(e=e.replaceAll(t.thousandsSeparator,"")),e.replace(t.decimalSeparator,".")):e}function nh(e,t){return lh(e,e=>Jc(e,t))}function rh(e,t){return lh(e,e=>Qc(e,t))}function ah(e,t){const s=ae(e);return s.criterion.values=s.criterion.values.map(e=>Qc(e,t)),s}function lh(e,t){switch((e=ae(e)).type){case"CellIsRule":switch(e.operator){case"isBetween":case"isNotBetween":case"isEqual":case"isNotEqual":case"isGreaterThan":case"isGreaterOrEqualTo":case"isLessThan":case"isLessOrEqualTo":case"customFormula":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=ch(e.minimum,t),e.maximum=ch(e.maximum,t),e.midpoint&&(e.midpoint=ch(e.midpoint,t)),e;case"IconSetRule":return e.lowerInflectionPoint.value=t(e.lowerInflectionPoint.value),e.upperInflectionPoint.value=t(e.upperInflectionPoint.value),e}}function ch(e,t){if(!e?.value)return e;const s=t("formula"===e.type?"="+e.value:e.value),o="formula"===e.type?s.slice(1):s;return{...e,value:o}}function hh(e){return e.dateFormat+" "+e.timeFormat}const dh=fs("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."),uh=fs("There must be both positive and negative values in cashflow_amounts."),gh=e=>fs("The cost (%s) must be positive or null.",e),ph=e=>fs("The frequency (%s) must be one of %s",e,[1,2,4].toString()),mh=e=>fs("The day_count_convention (%s) must be between 0 and 4 inclusive.",e),fh=e=>fs("The depreciation factor (%s) must be strictly positive.",e),vh=e=>fs("The discount (%s) must be strictly positive.",e),bh=e=>fs("The discount (%s) must be smaller than 1.",e),Sh=e=>fs("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e),Ch=(e,t)=>fs("The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).",{first:e,last:t}),yh=e=>fs("The first_period (%s) must be strictly positive.",e),Ih=e=>fs("The investment (%s) must be strictly positive.",e),wh=(e,t)=>fs("The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).",{last:e,nPeriods:t}),Eh=e=>fs("The last_period (%s) must be strictly positive.",e),Rh=e=>fs("The life (%s) must be strictly positive.",e),xh=(e,t)=>fs("The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).",{maturity:t,settlement:e}),Th=e=>fs("The number_of_periods (%s) must be strictly positive.",e),Ah=e=>fs("The periods_by_year (%s) must be strictly positive.",e),Dh=(e,t)=>fs("The period (%(period)s) must be less than or equal life (%(life)s).",{period:e,life:t}),_h=e=>fs("The period (%s) must be strictly positive.",e),Oh=e=>fs("The present_value (%s) must be strictly positive.",e),Fh=e=>fs("The price (%s) must be strictly positive.",e),Ph=e=>fs("The rate_guess (%s) must be strictly greater than -1.",e),Mh=e=>fs("The rate (%s) must be positive or null.",e),Nh=e=>fs("The rate (%s) must be strictly positive.",e),Lh=e=>fs("The redemption (%s) must be strictly positive.",e),kh=e=>fs("The salvage (%s) must be positive or null.",e),Vh=(e,t)=>fs("The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).",{settlement:e,maturity:t}),Uh=e=>fs("The unit (%s) must be strictly positive.",e),Hh=e=>fs("The yield (%s) must be positive or null.",e);function zh(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function Bh(e){return![0,1,2,3,4].includes(e)}function Gh(e){return![1,2,4].includes(e)}function Wh(e,t,s){const o=Ao(e,s),i=Ao(t,s),n=Ao(e,s);return n.setFullYear(o.getFullYear()+1),i.getTime()<=n.getTime()}const $h=[{value:0,label:fs("US (NASD) 30/360")},{value:1,label:fs("Actual/Actual")},{value:2,label:fs("Actual/360")},{value:3,label:fs("Actual/365")},{value:4,label:fs("European 30/360")}];var qh;!function(e){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"}(qh||(qh={}));const Zh={description:fs("Converts year/month/day into a date."),args:[as("year (number)",fs("The year component of the date.")),as("month (number)",fs("The month component of the date.")),as("day (number)",fs("The day component of the date."))],compute:function(e,t,s){let o=Math.trunc(bo(e,this.locale));const i=Math.trunc(bo(t,this.locale)),n=Math.trunc(bo(s,this.locale));if(o<0||o>9999)return new Cs(fs("The year (%s) must be between 0 and 9999 inclusive.",o.toString()));o<1900&&(o+=1900);const r=Ys(new Os(o,i-1,n));return r<0?new Cs(fs("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")):{value:r,format:this.locale.dateFormat}},isExported:!0},jh={description:fs("Calculates the number of days, months, or years between two dates."),args:[as("start_date (date)",fs("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.")),as("end_date (date)",fs("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.")),as("unit (string)",fs("A text abbreviation for unit of time."),[{value:"Y",label:fs("The number of whole years between start_date and end_date")},{value:"M",label:fs("The number of whole months between start_date and end_date")},{value:"D",label:fs("The number of days between start_date and end_date")},{value:"MD",label:fs("The number of days between start_date and end_date after subtracting whole months")},{value:"YM",label:fs("The number of whole months between start_date and end_date after subtracting whole years")},{value:"YD",label:fs("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,s){const o=Eo(s).toUpperCase();if(!Object.values(qh).includes(o))return new Cs(((e,t)=>{const s=e.map(e=>`'${e}'`).join(", ");return fs("The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.",t,s)})(Object.values(qh),Eo(s)));const i=Math.trunc(bo(e,this.locale)),n=Math.trunc(bo(t,this.locale)),r=js(i),a=js(n);if(n<i)return new Cs(fs("start_date (%s) should be on or before end_date (%s).",r.toLocaleDateString(),a.toLocaleDateString()));switch(o){case qh.WHOLE_YEARS:return io(r,a);case qh.WHOLE_MONTHS:return so(r,a);case qh.WHOLE_DAYS:return oo(r,a);case qh.MONTH_WITHOUT_WHOLE_YEARS:return so(r,a)-12*io(r,a);case qh.DAYS_WITHOUT_WHOLE_MONTHS:let e=a.getDate()-r.getDate();if(e<0){e=Ks(new Os(a.getFullYear(),a.getMonth()-1,1))-Math.abs(e)}return e;case qh.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR:{if(function(e,t){return to(e,t,1)<1}(i,n))return oo(r,a);const e=new Os(r.getFullYear(),a.getMonth(),a.getDate());let t=oo(r,e);return t<0&&(e.setFullYear(r.getFullYear()+1),t=oo(r,e)),t}}},isExported:!0},Yh={description:fs("Converts a date string to a date value."),args:[as("date_string (string)",fs("The string representing the date."))],compute:function(e){const t=Eo(e),s=Zs(t,this.locale);return null===s?new Cs(fs("The date_string (%s) cannot be parsed to date/time.",t.toString())):Math.trunc(s.value)},isExported:!0},Xh={description:fs("Day of the month that a specific date falls on."),args:[as("date (string)",fs("The date from which to extract the day."))],compute:function(e){return Ao(e,this.locale).getDate()},isExported:!0},Kh={description:fs("Number of days between two dates."),args:[as("end_date (date)",fs("The end of the date range.")),as("start_date (date)",fs("The start of the date range."))],compute:function(e,t){const s=Ao(e,this.locale),o=Ao(t,this.locale),i=s.getTime()-o.getTime();return Math.round(i/Ps)},isExported:!0},Jh=!1,Qh={description:fs("Number of days between two dates on a 360-day year (months of 30 days)."),args:[as("start_date (date)",fs("The start date to consider in the calculation.")),as("end_date (date)",fs("The end date to consider in the calculation.")),as("method (boolean, default=false)",fs("An indicator of what day count method to use."),[{value:!1,label:fs("U.S. NASD method (default)")},{value:!0,label:fs("European method")}])],compute:function(e,t,s={value:Jh}){const o=Math.trunc(bo(e,this.locale)),i=Math.trunc(bo(t,this.locale)),n=to(o,i,To(s)?4:0);return Math.sign(i-o)*Math.round(360*n)},isExported:!0},ed={description:fs("Date a number of months before/after another date."),args:[as("start_date (date)",fs("The date from which to calculate the result.")),as("months (number)",fs("The number of months before (negative) or after (positive) 'start_date' to calculate."))],compute:function(e,t){return{value:Ys(Qs(Ao(e,this.locale),Math.trunc(bo(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},td={description:fs("Last day of a month before or after a date."),args:[as("start_date (date)",fs("The date from which to calculate the result.")),as("months (number)",fs("The number of months before (negative) or after (positive) 'start_date' to consider."))],compute:function(e,t){const s=Ao(e,this.locale),o=Math.trunc(bo(t,this.locale)),i=s.getFullYear(),n=s.getMonth();return{value:Ys(new Os(i,n+o+1,0)),format:this.locale.dateFormat}},isExported:!0},sd={description:fs("Hour component of a specific time."),args:[as("time (date)",fs("The time from which to calculate the hour component."))],compute:function(e){return Ao(e,this.locale).getHours()},isExported:!0},od={description:fs("ISO week number of the year."),args:[as("date (date)",fs("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){const t=Ao(e,this.locale),s=t.getFullYear();let o=1;for(;4!==new Os(s,0,o).getDay();)o+=1;const i=new Os(s,0,o-3);let n=31;for(;4!==new Os(s,11,n).getDay();)n-=1;const r=new Os(s,11,n+3);let a,l;switch(a=i.getTime()<=t.getTime()?t.getTime()<=r.getTime()?0:1:-1,a){case 0:l=i;break;case 1:l=new Os(s,11,n+3+1);break;case-1:let e=1;for(;4!==new Os(s-1,0,e).getDay();)e+=1;l=new Os(s-1,0,e-3)}const c=(t.getTime()-l.getTime())/Ps;return Math.floor(c/7)+1},isExported:!0},id={description:fs("Minute component of a specific time."),args:[as("time (date)",fs("The time from which to calculate the minute component."))],compute:function(e){return Ao(e,this.locale).getMinutes()},isExported:!0},nd={description:fs("Month of the year a specific date falls in"),args:[as("date (date)",fs("The date from which to extract the month."))],compute:function(e){return Ao(e,this.locale).getMonth()+1},isExported:!0},rd={description:fs("Net working days between two provided days."),args:[as("start_date (date)",fs("The start date of the period from which to calculate the number of net working days.")),as("end_date (date)",fs("The end date of the period from which to calculate the number of net working days.")),as("holidays (date, range<date>, optional)",fs("A range or array constant containing the date serial numbers to consider holidays."))],compute:function(e,t,s){return cd.compute.bind(this)(e,t,{value:1},s)},isExported:!0};function ad(e){const t=e?.value;if("string"==typeof t){ri(7===t.length&&[...t].every(e=>"0"===e||"1"===e),fs('When weekend is a string (%s) it must be composed of "0" or "1".',t));const e=[];for(let s=0;s<7;s++)"1"===t[s]&&e.push((s+1)%7);return e}if("number"==typeof t)return ri(1<=t&&t<=7||11<=t&&t<=17,fs("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 Cs(fs("The weekend must be a number or a string."))}const ld=[{value:1,label:fs("Saturday/Sunday are weekends")},{value:2,label:fs("Sunday/Monday are weekends")},{value:3,label:fs("Monday/Tuesday are weekends")},{value:4,label:fs("Tuesday/Wednesday are weekends")},{value:5,label:fs("Wednesday/Thursday are weekends")},{value:6,label:fs("Thursday/Friday are weekends")},{value:7,label:fs("Friday/Saturday are weekends")},{value:11,label:fs("Sunday is the only weekend")},{value:12,label:fs("Monday is the only weekend")},{value:13,label:fs("Tuesday is the only weekend")},{value:14,label:fs("Wednesday is the only weekend")},{value:15,label:fs("Thursday is the only weekend")},{value:16,label:fs("Friday is the only weekend")},{value:17,label:fs("Saturday is the only weekend")}],cd={description:fs("Net working days between two dates (specifying weekends)."),args:[as("start_date (date)",fs("The start date of the period from which to calculate the number of net working days.")),as("end_date (date)",fs("The end date of the period from which to calculate the number of net working days.")),as("weekend (any, default=1)",fs("A number or string representing which days of the week are considered weekends."),ld),as("holidays (date, range<date>, optional)",fs("A range or array constant containing the dates to consider as holidays."))],compute:function(e,t,s={value:1},o){const i=Ao(e,this.locale),n=Ao(t,this.locale),r=ad(s),a=new Set;void 0!==o&&Oo([o],e=>{const t=Ao(e,this.locale);a.add(t.getTime())});const l=i.getTime()>n.getTime(),c=Os.fromTimestamp((l?i:n).getTime()),h=Os.fromTimestamp((l?n:i).getTime()),d=c.getTime();let u=h.getTime(),g=0;for(;u<=d;)r.includes(h.getDay())||a.has(u)||(g+=1),h.setDate(h.getDate()+1),u=h.getTime();return l?-g:g},isExported:!0},hd={description:fs("Current date and time as a date value."),args:[],compute:function(){const e=Os.now(),t=e.getTime()-Fs.getTime(),s=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/Ps)+s,format:hh(this.locale)}},isExported:!0},dd={description:fs("Minute component of a specific time."),args:[as("time (date)",fs("The time from which to calculate the second component."))],compute:function(e){return Ao(e,this.locale).getSeconds()},isExported:!0},ud={description:fs("Converts hour/minute/second into a time."),args:[as("hour (number)",fs("The hour component of the time.")),as("minute (number)",fs("The minute component of the time.")),as("second (number)",fs("The second component of the time."))],compute:function(e,t,s){let o=Math.trunc(bo(e,this.locale)),i=Math.trunc(bo(t,this.locale)),n=Math.trunc(bo(s,this.locale));return i+=Math.floor(n/60),n=n%60+(n<0?60:0),o+=Math.floor(i/60),i=i%60+(i<0?60:0),o%=24,o<0?new Cs(fs("The function [[FUNCTION_NAME]] result cannot be negative")):{value:o/24+i/1440+n/86400,format:this.locale.timeFormat}},isExported:!0},gd={description:fs("Converts a time string into its serial number representation."),args:[as("time_string (string)",fs("The string that holds the time representation."))],compute:function(e){const t=Eo(e),s=Zs(t,this.locale);if(null===s)return new Cs(fs("The time_string (%s) cannot be parsed to date/time.",t));const o=s.value-Math.trunc(s.value);return o<0?1+o:o},isExported:!0},pd={description:fs("Current date as a date value."),args:[],compute:function(){const e=Os.now();return{value:Ys(new Os(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},md={description:fs("Day of the week of the date provided (as number)."),args:[as("date (date)",fs("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.")),as("type (number, default=1)",fs("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1."),[{value:1,label:fs("Numbers 1 (Sunday) trough 7 (Saturday)")},{value:2,label:fs("Numbers 1 (Monday) trough 7 (Sunday)")},{value:3,label:fs("Numbers 0 (Monday) trough 6 (Sunday)")},{value:11,label:fs("Numbers 1 (Monday) trough 7 (Sunday)")},{value:12,label:fs("Numbers 1 (Tuesday) trough 7 (Monday)")},{value:13,label:fs("Numbers 1 (Wednesday) trough 7 (Tuesday)")},{value:14,label:fs("Numbers 1 (Thursday) trough 7 (Wednesday)")},{value:15,label:fs("Numbers 1 (Friday) trough 7 (Thursday)")},{value:16,label:fs("Numbers 1 (Saturday) trough 7 (Friday)")},{value:17,label:fs("Numbers 1 (Sunday) trough 7 (Saturday)")}])],compute:function(e,t={value:1}){const s=Ao(e,this.locale),o=Math.round(bo(t,this.locale)),i=s.getDay();if(!(1<=o&&o<=3||11<=o&&o<=17))return new Cs(fs("The type (%s) must be between 1 and 3 or between 11 and 17.",o));switch(o){case 1:return i+1;case 2:return 0===i?7:i;case 3:return 0===i?6:i-1}const n=(i+1-(o-10)+7)%7;return 0===n?7:n},isExported:!0},fd={description:fs("Week number of the year."),args:[as("date (date)",fs("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.")),as("type (number, default=1)",fs("A number representing the day that a week starts on. Sunday = 1."),[{value:1,label:fs("Sunday")},{value:2,label:fs("Monday")},{value:11,label:fs("Monday")},{value:12,label:fs("Tuesday")},{value:13,label:fs("Wednesday")},{value:14,label:fs("Thursday")},{value:15,label:fs("Friday")},{value:16,label:fs("Saturday")},{value:17,label:fs("Sunday")},{value:21,label:fs("ISO week number (Monday as first day of the week)")}])],compute:function(e,t={value:1}){const s=Ao(e,this.locale),o=Math.round(bo(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(o))return new Cs(fs("The type (%s) is out of range.",o.toString()));if(21===o)return od.compute.bind(this)(e);let i;i=1===o||2===o?o-1:o-10==7?0:o-10;const n=s.getFullYear();let r=1,a=new Os(n,0,r);for(;a.getDay()!==i;)r+=1,a=new Os(n,0,r);const l=(s.getTime()-a.getTime())/Ps;return l<0?1:Math.floor(l/7)+(1===r?1:2)},isExported:!0},vd={description:fs("Date after a number of workdays."),args:[as("start_date (date)",fs("The date from which to begin counting.")),as("num_days (number)",fs("The number of working days to advance from start_date. If negative, counts backwards.")),as("holidays (date, range<date>, optional)",fs("A range or array constant containing the dates to consider holidays."))],compute:function(e,t,s={value:null}){return bd.compute.bind(this)(e,t,{value:1},s)},isExported:!0},bd={description:fs("Date after a number of workdays (specifying weekends)."),args:[as("start_date (date)",fs("The date from which to begin counting.")),as("num_days (number)",fs("The number of working days to advance from start_date. If negative, counts backwards.")),as("weekend (any, default=1)",fs("A number or string representing which days of the week are considered weekends."),ld),as("holidays (date, range<date>, optional)",fs("A range or array constant containing the dates to consider holidays."))],compute:function(e,t,s={value:1},o){const i=Ao(e,this.locale),n=Math.trunc(bo(t,this.locale));if("1111111"===s.value)return new Cs(fs("The weekend must be different from '1111111'."));const r=ad(s),a=new Set;void 0!==o&&Oo([o],e=>{const t=Ao(e,this.locale);a.add(t.getTime())});const l=Os.fromTimestamp(i.getTime());let c=l.getTime();const h=Math.sign(n);let d=Math.abs(n);for(;d>0;)l.setDate(l.getDate()+h),c=l.getTime(),r.includes(l.getDay())||a.has(c)||(d-=1);const u=c-Fs.getTime();return{value:Math.round(u/Ps),format:this.locale.dateFormat}},isExported:!0},Sd={description:fs("Year specified by a given date."),args:[as("date (date)",fs("The date from which to extract the year."))],compute:function(e){return Ao(e,this.locale).getFullYear()},isExported:!0},Cd={description:fs("Exact number of years between two dates."),args:[as("start_date (date)",fs("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.")),as("end_date (date)",fs("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.")),as("day_count_convention (number, default=0)",fs("An indicator of what day count method to use."),$h)],compute:function(e,t,s={value:0}){const o=Math.trunc(bo(e,this.locale)),i=Math.trunc(bo(t,this.locale)),n=Math.trunc(bo(s,this.locale));return o<0?new Cs(fs("The start_date (%s) must be positive or null.",o)):i<0?new Cs(fs("The end_date (%s) must be positive or null.",i)):0>n||n>4?new Cs(fs("The day_count_convention (%s) must be between 0 and 4 inclusive.",n)):to(o,i,n)}},yd={description:fs("First day of the month preceding a date."),args:[as("date (date)",fs("The date from which to calculate the result."))],compute:function(e){const t=Ao(e,this.locale),s=t.getFullYear(),o=t.getMonth();return{value:Ys(new Os(s,o,1)),format:this.locale.dateFormat}}},Id={description:fs("Last day of the month following a date."),args:[as("date (date)",fs("The date from which to calculate the result."))],compute:function(e){return td.compute.bind(this)(e,{value:0})}},wd={description:fs("Quarter of the year a specific date falls in"),args:[as("date (date)",fs("The date from which to extract the quarter."))],compute:function(e){return Math.ceil((Ao(e,this.locale).getMonth()+1)/3)}},Ed={description:fs("First day of the quarter of the year a specific date falls in."),args:[as("date (date)",fs("The date from which to calculate the start of quarter."))],compute:function(e){const t=wd.compute.bind(this)(e),s=Sd.compute.bind(this)(e);return{value:Ys(new Os(s,3*(t-1),1)),format:this.locale.dateFormat}}},Rd={description:fs("Last day of the quarter of the year a specific date falls in."),args:[as("date (date)",fs("The date from which to calculate the end of quarter."))],compute:function(e){const t=wd.compute.bind(this)(e),s=Sd.compute.bind(this)(e);return{value:Ys(new Os(s,3*t,0)),format:this.locale.dateFormat}}},xd={description:fs("First day of the year a specific date falls in."),args:[as("date (date)",fs("The date from which to calculate the start of the year."))],compute:function(e){const t=Sd.compute.bind(this)(e);return{value:Ys(new Os(t,0,1)),format:this.locale.dateFormat}}},Td={description:fs("Last day of the year a specific date falls in."),args:[as("date (date)",fs("The date from which to calculate the end of the year."))],compute:function(e){const t=Sd.compute.bind(this)(e);return{value:Ys(new Os(t+1,0,0)),format:this.locale.dateFormat}}};var Ad=Object.freeze({__proto__:null,DATE:Zh,DATEDIF:jh,DATEVALUE:Yh,DAY:Xh,DAYS:Kh,DAYS360:Qh,EDATE:ed,EOMONTH:td,HOUR:sd,ISOWEEKNUM:od,MINUTE:id,MONTH:nd,MONTH_END:Id,MONTH_START:yd,NETWORKDAYS:rd,NETWORKDAYS_INTL:cd,NOW:hd,QUARTER:wd,QUARTER_END:Rd,QUARTER_START:Ed,SECOND:dd,TIME:ud,TIMEVALUE:gd,TODAY:pd,WEEKDAY:md,WEEKNUM:fd,WORKDAY:vd,WORKDAY_INTL:bd,YEAR:Sd,YEARFRAC:Cd,YEAR_END:Td,YEAR_START:xd});const Dd={description:fs("Compare two numeric values, returning 1 if they're equal."),args:[as("number1 (number)",fs("The first number to compare.")),as("number2 (number, default=0)",fs("The second number to compare."))],compute:function(e,t={value:0}){return bo(e,this.locale)===bo(t,this.locale)?1:0},isExported:!0};var _d,Od=Object.freeze({__proto__:null,DELTA:Dd});!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(_d||(_d={}));const Fd=[_d.number,_d.error,_d.text,_d.boolean];function Pd(e){const t="asc"===e?1:-1;return(e,s)=>{if(e.type===_d.empty)return s.type===_d.empty?0:1;if(s.type===_d.empty)return-1;let o=Fd.indexOf(e.type)-Fd.indexOf(s.type);return 0===o&&(o=e.type===_d.text||e.type===_d.error?e.value.localeCompare(s.value):e.value-s.value),t*o}}function Md(e,t,...s){for(let e=0;e<s.length;e++){const t=e%2==0?"sort_column":"is_ascending";ri(void 0!==s[e],fs("Value for parameter %s is missing in [[FUNCTION_NAME]].",t))}const o=[],i=[],n=e.length;for(let r=0;r<s.length;r+=2){o.push(To(fi(s[r+1])?.value)?"asc":"desc");const a=s[r];if(Ds(a)&&(a.length>1||a[0].length>1))ri(1===a.length&&a[0].length===n,fs("Wrong size for %s. Expected a range of size 1x%s. Got %sx%s.",`sort_column${r+1}`,n,a.length,a[0].length)),i.push(a.flat().map(e=>e.value));else{const s=bo(fi(a)?.value,t);if(s<1||s>e[0].length)return e;i.push(e.map(e=>e[s-1].value))}}if(0===i.length)for(let t=0;t<e[0].length;t++)i.push(e.map(e=>e[t].value)),o.push("asc");const r={desc:Pd("desc"),asc:Pd("asc")},a=ge(0,e.length);return a.sort((e,t)=>{for(const[s,n]of i.entries()){const i=n[e],a=n[t],l={value:i,type:null===i?_d.empty:"string"==typeof i?_d.text:typeof i},c={value:a,type:null===a?_d.empty:"string"==typeof a?_d.text:typeof a},h=r[o[s]](l,c);if(0!==h)return h}return 0}),a.map(t=>e[t])}const Nd={description:fs("Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions."),args:[as("range (any, range<any>)",fs("The data to be filtered.")),as("condition1 (boolean, range<boolean>)",fs("A column or row containing true or false values corresponding to the first column or row of range.")),as("condition2 (boolean, range<boolean>, repeating)",fs("Additional column or row containing true or false values."))],compute:function(e,...t){let s=Xo(e);const o=t.map(e=>Vo(Xo(e),e=>e.value));for(const e of o)if(!li(e))return new Cs(fs("The arguments condition must be a single column or row."));if(!ci(...t))return new Cs(fs("The arguments conditions must have the same dimensions."));const i=o.map(e=>e.flat()),n=1===o[0].length?"row":"col";if(s="row"===n?Uo(s):s,i.some(e=>e.length!==s.length))return new Cs(fs("FILTER has mismatched sizes on the range and conditions."));const r=[];for(let e=0;e<s.length;e++){const t=s[e];i.every(t=>("boolean"==typeof t[e]||"number"==typeof t[e])&&t[e])&&r.push(t)}return r.length?"row"===n?Uo(r):r:new Es(fs("No match found in FILTER evaluation"))},isExported:!1},Ld={description:fs("Sorts the rows of a given array or range by the values in one or more columns."),args:[as("range (range)",fs("The data to be sorted.")),as("sort_column (any, range<number>, repeating)",fs("The index of the column in range or a range outside of range containing the values by which to sort.")),as("is_ascending (boolean, repeating)",fs("TRUE or FALSE indicating whether to sort sort_column in ascending order."),[{value:!0,label:fs("Ascending")},{value:!1,label:fs("Descending")}])],compute:function(e,...t){const s=Uo(e);return Uo(Md(s,this.locale,...t))},isExported:!0},kd={description:fs("Returns the first n items in a data set after performing a sort."),args:[as("range (range)",fs("The data to be sorted.")),as("n (number)",fs("The number of items to return.")),as("display_ties_mode (number, default=0)",fs("A number representing the way to display ties.")),as("sort_column (number, range<number>, repeating)",fs("The index of the column in range or a range outside of range containing the values by which to sort.")),as("is_ascending (boolean, repeating)",fs("TRUE or FALSE indicating whether to sort sort_column in ascending order."),[{value:!0,label:fs("Ascending")},{value:!1,label:fs("Descending")}])],compute:function(e,t,...s){const o=bo(t?.value??1,this.locale),i=s.length%2==0?0:bo(s[0]?.value,this.locale),n=s.length%2==0?s:s.slice(1);if(o<0)return new Cs(fs("Wrong value of 'n'. Expected a positive number. Got %s.",o));if(i<0||i>3)return new Cs(fs("Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.",i));const r=Md(Uo(e),this.locale,...n),a=(e,t)=>JSON.stringify(r[e].map(e=>e.value))===JSON.stringify(r[t].map(e=>e.value));switch(i){case 0:return Uo(r.slice(0,o));case 1:for(let e=o;e<r.length;e++)if(!a(e,o-1))return Uo(r.slice(0,e));return Uo(r);case 2:{const e=[r[0]];for(let t=1;t<r.length;t++)for(let s=0;s<t&&!a(t,s);s++)s===t-1&&e.push(r[t]);return Uo(e.slice(0,o))}case 3:{const e=[r[0]];let t=1;for(let s=1;s<r.length&&(a(s,s-1)||t++,!(t>o));s++)e.push(r[s]);return Uo(e)}}},isExported:!1},Vd={description:fs("Unique rows in the provided source range."),args:[as("range (any, range<any>)",fs("The data to filter by unique entries.")),as("by_column (boolean, default=FALSE)",fs("Whether to filter the data by columns or by rows."),[{value:!0,label:fs("Return unique columns")},{value:!1,label:fs("Return unique rows")}]),as("exactly_once (boolean, default=FALSE)",fs("Whether to return only entries with no duplicates."),[{value:!0,label:fs("Return items that appear exactly once")},{value:!1,label:fs("Return every distinct item")}])],compute:function(e={value:""},t,s){if(!Ds(e))return[[e]];const o=To(t?.value)||!1,i=To(s?.value)||!1;o||(e=Uo(e));const n=new Map;for(const t of e){const e=JSON.stringify(t.map(e=>e.value)),s=n.get(e);s?s.count++:n.set(e,{data:t,count:1})}const r=[];for(const e of n.values())i&&e.count>1||r.push(e.data);return r.length?o?r:Uo(r):new Cs(fs("No unique values found"))},isExported:!0};var Ud=Object.freeze({__proto__:null,FILTER:Nd,SORT:Ld,SORTN:kd,UNIQUE:Vd});const Hd=[{value:1,label:fs("Annual")},{value:2,label:fs("Semi-annual")},{value:4,label:fs("Quarterly")}],zd=[{value:0,label:fs("End of period (default)")},{value:1,label:fs("Beginning of period")}],Bd=[as("settlement (date)",fs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),as("maturity (date)",fs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),as("frequency (number)",fs("The number of interest or coupon payments per year (1, 2, or 4)."),Hd),as("day_count_convention (number, default=0 )",fs("An indicator of what day count method to use."),$h)];function Gd(e,t,s,o,i=1e-10,n){let r,a,l,c,h=s,d=!1,u=0;do{l=e(h),isNaN(l)?(ri(u<o&&void 0!==n,fs("Function [[FUNCTION_NAME]] didn't find any result.")),u++,h=n(c),c=h):(r=h-l/t(h),a=Math.abs(r-h),h=r,d=a<i||Math.abs(l)<i,ri(u<o,fs("Function [[FUNCTION_NAME]] didn't find any result.")),u++)}while(!d);return h}const Wd={description:fs("Accrued interest of security paying at maturity."),args:[as("issue (date)",fs("The date the security was initially issued.")),as("maturity (date)",fs("The maturity date of the security.")),as("rate (number)",fs("The annualized rate of interest.")),as("redemption (number)",fs("The redemption amount per 100 face value, or par.")),as("day_count_convention (number, default=0 )",fs("An indicator of what day count method to use."),$h)],compute:function(e,t,s,o,i={value:0}){const n=Math.trunc(bo(e,this.locale)),r=Math.trunc(bo(t,this.locale)),a=bo(o,this.locale),l=bo(s,this.locale),c=Math.trunc(bo(i,this.locale));if(n<0)return new Cs((e=>fs("The issue (%s) must be positive or null.",e))(n));if(n>=r)return new Cs(xh(n,r));if(Bh(c))return new Cs(mh(c));if(a<=0)return new Cs(Lh(a));if(l<=0)return new Cs(Nh(l));return a*l*to(n,r,c)},isExported:!0},$d={description:fs("Depreciation for an accounting period."),args:[as("cost (number)",fs("The initial cost of the asset.")),as("purchase_date (date)",fs("The date the asset was purchased.")),as("first_period_end (date)",fs("The date the first period ended.")),as("salvage (number)",fs("The value of the asset at the end of depreciation.")),as("period (number)",fs("The single period within life for which to calculate depreciation.")),as("rate (number)",fs("The deprecation rate.")),as("day_count_convention (number, optional)",fs("An indicator of what day count method to use."),$h)],compute:function(e,t,s,o,i,n,r={value:0}){r=r||0;const a=bo(e,this.locale),l=Math.trunc(bo(t,this.locale)),c=Math.trunc(bo(s,this.locale)),h=bo(o,this.locale),d=bo(i,this.locale),u=bo(n,this.locale),g=Math.trunc(bo(r,this.locale));if(a<=0)return new Cs((e=>fs("The cost (%s) must be strictly positive.",e))(a));if(l<0)return new Cs((e=>fs("The purchase_date (%s) must be positive or null.",e))(l));if(h<0)return new Cs(kh(h));if(h>a)return new Cs(((e,t)=>fs("The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).",{salvage:e,cost:t}))(h,a));if(d<0)return new Cs((e=>fs("The period (%s) must be positive or null.",e))(d));if(u<=0)return new Cs(Nh(u));if(Bh(g))return new Cs(mh(g));if(l>c)return new Cs(((e,t)=>fs("The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).",{purchaseDate:e,firstPeriodEnd:t}))(l,c));const p=d<1&&d>0?1:Math.trunc(d),m=a*u,f=to(l,c,g),v=l===c?m:m*f,b=a-v-m*p;return b>=h?0===p?v:m:h-b<m?m-(h-b):0},isExported:!0},qd={description:fs("Days in coupon period containing settlement date."),args:Bd,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(bo(e,this.locale)),n=Math.trunc(bo(t,this.locale)),r=Math.trunc(bo(s,this.locale)),a=Math.trunc(bo(o,this.locale));if(i>=n)return new Cs(xh(i,n));if(Gh(r))return new Cs(ph(r));if(Bh(a))return new Cs(mh(a));if(1===a){const i=Kd.compute.bind(this)(e,t,s,o).value;return bo(Yd.compute.bind(this)(e,t,s,o).value,this.locale)-bo(i,this.locale)}return(3===a?365:360)/r},isExported:!0},Zd={description:fs("Days from settlement until next coupon."),args:Bd,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(bo(e,this.locale)),n=Math.trunc(bo(t,this.locale)),r=Math.trunc(bo(s,this.locale)),a=Math.trunc(bo(o,this.locale));if(i>=n)return new Cs(xh(i,n));if(Gh(r))return new Cs(ph(r));if(Bh(a))return new Cs(mh(a));const l=bo(Kd.compute.bind(this)(e,t,s,o).value,this.locale);if([1,2,3].includes(a))return i-l;if(4===a){const e=to(l,i,a);return Math.round(360*e)}const c=Ao(i,this.locale),h=Ao(l,this.locale),d=h.getFullYear(),u=c.getFullYear(),g=h.getMonth()+1,p=c.getMonth()+1;let m=h.getDate(),f=c.getDate();return 2===g&&2===p&&Js(h)&&Js(c)&&(f=30),31!==f||30!==m&&31!==m||(f=30),2===g&&Js(h)&&(m=30),31===m&&(m=30),360*(u-d)+30*(p-g)+(f-m)},isExported:!0},jd={description:fs("Days from settlement until next coupon."),args:Bd,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(bo(e,this.locale)),n=Math.trunc(bo(t,this.locale)),r=Math.trunc(bo(s,this.locale)),a=Math.trunc(bo(o,this.locale));if(i>=n)return new Cs(xh(i,n));if(Gh(r))return new Cs(ph(r));if(Bh(a))return new Cs(mh(a));const l=bo(Yd.compute.bind(this)(e,t,s,o).value,this.locale);if([1,2,3].includes(a))return l-i;if(4===a){const e=to(i,l,a);return Math.round(360*e)}const c=Zd.compute.bind(this)(e,t,s,o);return bo(qd.compute.bind(this)(e,t,s,o),this.locale)-bo(c,this.locale)},isExported:!0},Yd={description:fs("Next coupon date after the settlement date."),args:Bd,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(bo(e,this.locale)),n=Math.trunc(bo(t,this.locale)),r=Math.trunc(bo(s,this.locale)),a=Math.trunc(bo(o,this.locale));if(i>=n)return new Cs(xh(i,n));if(Gh(r))return new Cs(ph(r));if(Bh(a))return new Cs(mh(a));const l=12/r,c=Xd.compute.bind(this)(e,t,s,o);return{value:Ys(Qs(Ao(n,this.locale),-(bo(c,this.locale)-1)*l,!0)),format:this.locale.dateFormat}},isExported:!0},Xd={description:fs("Number of coupons between settlement and maturity."),args:Bd,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(bo(e,this.locale)),n=Math.trunc(bo(t,this.locale)),r=Math.trunc(bo(s,this.locale)),a=Math.trunc(bo(o,this.locale));if(i>=n)return new Cs(xh(i,n));if(Gh(r))return new Cs(ph(r));if(Bh(a))return new Cs(mh(a));let l=1,c=n;const h=12/r;for(;c>i;)c=Ys(Qs(Ao(c,this.locale),-h,!1)),l++;return l-1},isExported:!0},Kd={description:fs("Last coupon date prior to or on the settlement date."),args:Bd,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(bo(e,this.locale)),n=Math.trunc(bo(t,this.locale)),r=Math.trunc(bo(s,this.locale)),a=Math.trunc(bo(o,this.locale));if(i>=n)return new Cs(xh(i,n));if(Gh(r))return new Cs(ph(r));if(Bh(a))return new Cs(mh(a));const l=12/r,c=Xd.compute.bind(this)(e,t,s,o);return{value:Ys(Qs(Ao(n,this.locale),-c*l,!0)),format:this.locale.dateFormat}},isExported:!0},Jd={description:fs("Cumulative interest paid over a set of periods."),args:[as("rate (number)",fs("The interest rate.")),as("number_of_periods (number)",fs("The number of payments to be made.")),as("present_value (number)",fs("The current value of the annuity.")),as("first_period (number)",fs("The number of the payment period to begin the cumulative calculation.")),as("last_period (number)",fs("The number of the payment period to end the cumulative calculation.")),as("end_or_beginning (number, default=0)",fs("The timing of the payment payments are due for each period."),zd)],compute:function(e,t,s,o,i,n={value:0}){const r=bo(o,this.locale),a=bo(i,this.locale),l=bo(e,this.locale),c=bo(s,this.locale),h=bo(t,this.locale),d=To(n)?1:0;if(h<=0)return new Cs(Th(h));if(r<=0)return new Cs(yh(r));if(a<=0)return new Cs(Eh(a));if(r>a)return new Cs(Ch(r,a));if(a>h)return new Cs(wh(a,h));if(l<=0)return new Cs(Nh(l));if(c<=0)return new Cs(Oh(c));let u=0;for(let e=r;e<=a;e++)u+=uu(l,e,h,c,0,d);return u},isExported:!0},Qd={description:fs("Cumulative principal paid over a set of periods."),args:[as("rate (number)",fs("The interest rate.")),as("number_of_periods (number)",fs("The number of payments to be made.")),as("present_value (number)",fs("The current value of the annuity.")),as("first_period (number)",fs("The number of the payment period to begin the cumulative calculation.")),as("last_period (number)",fs("The number of the payment period to end the cumulative calculation.")),as("end_or_beginning (number, default=0)",fs("The timing of the payment payments are due for each period."),zd)],compute:function(e,t,s,o,i,n={value:0}){const r=bo(o,this.locale),a=bo(i,this.locale),l=bo(e,this.locale),c=bo(s,this.locale),h=bo(t,this.locale),d=To(n)?1:0;if(h<=0)return new Cs(Th(h));if(r<=0)return new Cs(yh(r));if(a<=0)return new Cs(Eh(a));if(r>a)return new Cs(Ch(r,a));if(a>h)return new Cs(wh(a,h));if(l<=0)return new Cs(Nh(l));if(c<=0)return new Cs(Oh(c));let u=0;for(let e=r;e<=a;e++)u+=Ru(l,e,h,c,0,d);return u},isExported:!0},eu={description:fs("Depreciation via declining balance method."),args:[as("cost (number)",fs("The initial cost of the asset.")),as("salvage (number)",fs("The value of the asset at the end of depreciation.")),as("life (number)",fs("The number of periods over which the asset is depreciated.")),as("period (number)",fs("The single period within life for which to calculate depreciation.")),as("month (number, optional)",fs("The number of months in the first year of depreciation."))],compute:function(e,t,s,o,...i){const n=bo(e,this.locale),r=bo(t,this.locale),a=bo(s,this.locale),l=Math.trunc(bo(o,this.locale)),c=i.length?Math.trunc(bo(i[0],this.locale)):12,h=a+(12===c?0:1);if(n<0)return new Cs(gh(n));if(r<0)return new Cs(kh(r));if(l<=0)return new Cs(_h(l));if(a<=0)return new Cs(Rh(a));if(1>c||c>12)return new Cs(fs("The month (%s) must be between 1 and 12 inclusive.",c));if(l>h)return new Cs(((e,t)=>fs("The period (%(period)s) must be less than or equal to %(lifeLimit)s.",{period:e,lifeLimit:t}))(l,h));const d=c/12;let u=1-Math.pow(r/n,1/a);u=Math.round(1e3*u)/1e3;let g=n,p=n*(1-u*d);for(let e=1;e<l;e++)g=p,p=g*(1-u),e===a&&(p=g*(1-u*(1-d)));return{value:g-p,format:"#,##0.00"}},isExported:!0},tu="#,##0.00",su={description:fs("Depreciation via double-declining balance method."),args:[as("cost (number)",fs("The initial cost of the asset.")),as("salvage (number)",fs("The value of the asset at the end of depreciation.")),as("life (number)",fs("The number of periods over which the asset is depreciated.")),as("period (number)",fs("The single period within life for which to calculate depreciation.")),as("factor (number, default=2)",fs("The factor by which depreciation decreases."))],compute:function(e,t,s,o,i={value:2}){const n=bo(e,this.locale),r=bo(t,this.locale),a=bo(s,this.locale),l=bo(o,this.locale),c=bo(i,this.locale);if(n<0)return new Cs(gh(n));if(r<0)return new Cs(kh(r));if(l<=0)return new Cs(_h(l));if(a<=0)return new Cs(Rh(a));if(l>a)return new Cs(Dh(l,a));if(c<=0)return new Cs(fh(c));if(0===n||r>=n)return{value:0,format:tu};const h=c/a;if(h>1)return{value:1===l?n-r:0,format:tu};if(l<=1)return{value:n*h,format:tu};const d=n*Math.pow(1-h,l-1),u=n*Math.pow(1-h,l),g=u<r?d-r:d-u;return{value:Math.max(g,0),format:tu}},isExported:!0},ou={description:fs("Discount rate of a security based on price."),args:[as("settlement (date)",fs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),as("maturity (date)",fs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),as("price (number)",fs("The price at which the security is bought per 100 face value.")),as("redemption (number)",fs("The redemption amount per 100 face value, or par.")),as("day_count_convention (number, default=0 )",fs("An indicator of what day count method to use."),$h)],compute:function(e,t,s,o,i={value:0}){i=i||0;const n=Math.trunc(bo(e,this.locale)),r=Math.trunc(bo(t,this.locale)),a=bo(s,this.locale),l=bo(o,this.locale),c=Math.trunc(bo(i,this.locale));if(n>=r)return new Cs(xh(n,r));if(Bh(c))return new Cs(mh(c));if(a<=0)return new Cs(Fh(a));if(l<=0)return new Cs(Lh(l));return(l-a)/l/to(n,r,c)},isExported:!0},iu={description:fs("Convert a decimal fraction to decimal value."),args:[as("fractional_price (number)",fs("The price quotation given using fractional decimal conventions.")),as("unit (number)",fs("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],compute:function(e,t){const s=bo(e,this.locale),o=Math.trunc(bo(t,this.locale));if(o<=0)return new Cs(Uh(o));const i=Math.trunc(s);return i+(s-i)*(10**Math.ceil(Math.log10(o))/o)},isExported:!0},nu={description:fs("Convert a decimal value to decimal fraction."),args:[as("decimal_price (number)",fs("The price quotation given as a decimal value.")),as("unit (number)",fs("The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],compute:function(e,t){const s=bo(e,this.locale),o=Math.trunc(bo(t,this.locale));if(o<=0)return new Cs(Uh(o));const i=Math.trunc(s);return i+(s-i)*(o/10**Math.ceil(Math.log10(o)))},isExported:!0},ru={description:fs("Number of periods for an investment to reach a value."),args:[as("settlement (date)",fs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),as("maturity (date)",fs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),as("rate (number)",fs("The annualized rate of interest.")),as("yield (number)",fs("The expected annual yield of the security.")),as("frequency (number)",fs("The number of interest or coupon payments per year (1, 2, or 4)."),Hd),as("day_count_convention (number, default=0 )",fs("An indicator of what day count method to use."),$h)],compute:function(e,t,s,o,i,n={value:0}){const r=Math.trunc(bo(e,this.locale)),a=Math.trunc(bo(t,this.locale)),l=bo(s,this.locale),c=bo(o,this.locale),h=Math.trunc(bo(i,this.locale)),d=Math.trunc(bo(n,this.locale));if(r>=a)return new Cs(xh(r,a));if(Gh(h))return new Cs(ph(h));if(Bh(d))return new Cs(mh(d));if(l<0)return new Cs(Mh(l));if(c<0)return new Cs(Hh(c));const u=to(r,a,d),g=u-Math.trunc(u)||1/h,p=Math.ceil(u*h),m=l/h,f=c/h;let v=0,b=0;for(let e=1;e<=p;e++){const t=(m+(e===p?1:0))/(1+f)**e;b+=(g+(e-1)/h)*t,v+=t}return 0===v?0:b/v},isExported:!0},au={description:fs("Annual effective interest rate."),args:[as("nominal_rate (number)",fs("The nominal interest rate per year.")),as("periods_per_year (number)",fs("The number of compounding periods per year."))],compute:function(e,t){const s=bo(e,this.locale),o=Math.trunc(bo(t,this.locale));return s<=0?new Cs(fs("The nominal_rate (%s) must be strictly positive.",s)):o<=0?new Cs(Ah(o)):Math.pow(1+s/o,o)-1},isExported:!0};function lu(e,t,s,o,i){return 0===e?-(o+s*t):-o*(1+e)**t-s*(1+e*i)*((1+e)**t-1)/e}const cu={description:fs("Future value of an annuity investment."),args:[as("rate (number)",fs("The interest rate.")),as("number_of_periods (number)",fs("The number of payments to be made.")),as("payment_amount (number)",fs("The amount per period to be paid.")),as("present_value (number, default=0)",fs("The current value of the annuity.")),as("end_or_beginning (number, default=0)",fs("The timing of the payment payments are due for each period."),zd)],compute:function(e,t,s,o={value:0},i={value:0}){o=o||0,i=i||0;return{value:lu(bo(e,this.locale),bo(t,this.locale),bo(s,this.locale),bo(o,this.locale),To(i)?1:0),format:"#,##0.00"}},isExported:!0},hu={description:fs("Future value of principal from series of rates."),args:[as("principal (number)",fs("The amount of initial capital or value to compound against.")),as("rate_schedule (number, range<number>)",fs("A series of interest rates to compound against the principal."))],compute:function(e,t){return Mo([t],(e,t)=>e*(1+bo(t,this.locale)),bo(e,this.locale))},isExported:!0},du={description:fs("Calculates effective interest rate."),args:[as("settlement (date)",fs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),as("maturity (date)",fs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),as("investment (number)",fs("The amount invested in the security.")),as("redemption (number)",fs("The amount to be received at maturity.")),as("day_count_convention (number, default=0 )",fs("An indicator of what day count method to use."),$h)],compute:function(e,t,s,o,i={value:0}){const n=Math.trunc(bo(e,this.locale)),r=Math.trunc(bo(t,this.locale)),a=bo(o,this.locale),l=bo(s,this.locale),c=Math.trunc(bo(i,this.locale));if(n>=r)return new Cs(xh(n,r));if(l<=0)return new Cs(Ih(l));if(a<=0)return new Cs(Lh(a));if(Bh(c))return new Cs(mh(c));return(a-l)/l/to(n,r,c)},isExported:!0};function uu(e,t,s,o,i,n){return wu(e,s,o,i,n)-Ru(e,t,s,o,i,n)}const gu={description:fs("Payment on the principal of an investment."),args:[as("rate (number)",fs("The annualized rate of interest.")),as("period (number)",fs("The amortization period, in terms of number of periods.")),as("number_of_periods (number)",fs("The number of payments to be made.")),as("present_value (number)",fs("The current value of the annuity.")),as("future_value (number, default=0)",fs("The future value remaining after the final payment has been made.")),as("end_or_beginning (number, default=0)",fs("The timing of the payment payments are due for each period."),zd)],compute:function(e,t,s,o,i={value:0},n={value:0}){return{value:uu(bo(e,this.locale),bo(t,this.locale),bo(s,this.locale),bo(o,this.locale),bo(i,this.locale),To(n)?1:0),format:"#,##0.00"}},isExported:!0},pu={description:fs("Internal rate of return given periodic cashflows."),args:[as("cashflow_amounts (number, range<number>)",fs("An array or range containing the income or payments associated with the investment.")),as("rate_guess (number, default=0.1)",fs("An estimate for what the internal rate of return will be."))],compute:function(e,t={value:.1}){const s=bo(t,this.locale);if(s<=-1)return new Cs(Ph(s));let o=!1,i=!1;const n=[];if(Fo([e],({value:e})=>{e>0&&(o=!0),e<0&&(i=!0),n.push(e)},this.locale),!o||!i)return new Cs(uh);const r=n.shift();return{value:Gd(function(e){return function(e,t,s){const o=s.length;let i=0;return s.reduce((t,s)=>(i++,t+s*e**(o-i)),t*e**o)}(e,r,n)},function(e){return function(e,t,s){const o=s.length;let i=0;return s.reduce((t,s)=>(i++,t+s*(o-i)*e**(o-i-1)),t*o*e**(o-1))}(e,r,n)},s+1,20,1e-5)-1,format:"0%"}},isExported:!0},mu={description:fs("Returns the interest paid at a particular period of an investment."),args:[as("rate (number)",fs("The interest rate.")),as("period (number)",fs("The period for which you want to view the interest payment.")),as("number_of_periods (number)",fs("The number of payments to be made.")),as("present_value (number)",fs("The current value of the annuity."))],compute:function(e,t,s,o){const i=bo(e,this.locale),n=bo(t,this.locale),r=bo(s,this.locale),a=bo(o,this.locale);if(0===r)return new Cs(fs("The number_of_periods (%s) must be different from zero.",r));return-1*(a-a*(n/r))*i},isExported:!0},fu={description:fs("Modified Macaulay duration."),args:[as("settlement (date)",fs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),as("maturity (date)",fs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),as("rate (number)",fs("The annualized rate of interest.")),as("yield (number)",fs("The expected annual yield of the security.")),as("frequency (number)",fs("The number of interest or coupon payments per year (1, 2, or 4)."),Hd),as("day_count_convention (number, default=0 )",fs("An indicator of what day count method to use."))],compute:function(e,t,s,o,i,n={value:0}){const r=ru.compute.bind(this)(e,t,s,o,i,n),a=bo(o,this.locale),l=Math.trunc(bo(i,this.locale));return bo(r,this.locale)/(1+a/l)},isExported:!0},vu={description:fs("Modified internal rate of return."),args:[as("cashflow_amounts (range<number>)",fs("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")),as("financing_rate (number)",fs("The interest rate paid on funds invested.")),as("reinvestment_return_rate (number)",fs("The return (as a percentage) earned on reinvestment of income received from the investment."))],compute:function(e,t,s){const o=bo(t,this.locale),i=bo(s,this.locale),n=Uo(e).flat().filter(e=>null!==e.value).map(e=>bo(e,this.locale)),r=n.length;let a=0,l=0;for(const e of ge(0,r)){const t=n[e];t>=0?a+=t*(i+1)**(r-e-1):l+=t/(o+1)**e}if(0===l||0===a)return new Cs(uh);return(-a/l)**(1/(r-1))-1},isExported:!0},bu={description:fs("Annual nominal interest rate."),args:[as("effective_rate (number)",fs("The effective interest rate per year.")),as("periods_per_year (number)",fs("The number of compounding periods per year."))],compute:function(e,t){const s=bo(e,this.locale),o=Math.trunc(bo(t,this.locale));return s<=0?new Cs(fs("The effective_rate (%s) must be strictly positive.",s)):o<=0?new Cs(Ah(o)):(Math.pow(s+1,1/o)-1)*o},isExported:!0},Su={description:fs("Number of payment periods for an investment."),args:[as("rate (number)",fs("The interest rate.")),as("payment_amount (number)",fs("The amount of each payment made.")),as("present_value (number)",fs("The current value of the annuity.")),as("future_value (number, default=0)",fs("The future value remaining after the final payment has been made.")),as("end_or_beginning (number, default=0)",fs("The timing of the payment payments are due for each period."),zd)],compute:function(e,t,s,o={value:0},i={value:0}){o=o||0,i=i||0;const n=bo(e,this.locale),r=bo(t,this.locale),a=bo(s,this.locale),l=bo(o,this.locale),c=To(i)?1:0;if(0===n)return-(l+a)/r;const h=r*(1+n*c)/n;return Math.log((h-l)/(a+h))/Math.log(1+n)},isExported:!0};function Cu(e,t,s,o){let i=0;return No(s,(t,s)=>(i++,t+s/(1+e)**i),t,o)}const yu={description:fs("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:[as("discount (number)",fs("The discount rate of the investment over one period.")),as("cashflow1 (number, range<number>)",fs("The first future cash flow.")),as("cashflow2 (number, range<number>, repeating)",fs("Additional future cash flows."))],compute:function(e,...t){const s=bo(e,this.locale);return-1===s?new Cs((e=>fs("The discount (%s) must be different from -1.",e))(s)):{value:Cu(s,0,t,this.locale),format:"#,##0.00"}},isExported:!0},Iu={description:fs("Computes the number of periods needed for an investment to reach a value."),args:[as("rate (number)",fs("The rate at which the investment grows each period.")),as("present_value (number)",fs("The investment's current value.")),as("future_value (number)",fs("The investment's desired future value."))],compute:function(e,t,s){const o=bo(e,this.locale),i=bo(t,this.locale),n=bo(s,this.locale);return o<=0?new Cs(Nh(o)):i<=0?new Cs(Oh(i)):n<=0?new Cs(fs("The future_value (%s) must be strictly positive.",n)):(Math.log(n)-Math.log(i))/Math.log(1+o)},isExported:!0};function wu(e,t,s,o,i){if(t<=0)throw new Cs(Th(t));if(0===e)return-(o+s)/t;let n=-(s*(1+e)**t+o);return n=n*e/((1+e*i)*((1+e)**t-1)),n}const Eu={description:fs("Periodic payment for an annuity investment."),args:[as("rate (number)",fs("The annualized rate of interest.")),as("number_of_periods (number)",fs("The number of payments to be made.")),as("present_value (number)",fs("The current value of the annuity.")),as("future_value (number, default=0)",fs("The future value remaining after the final payment has been made.")),as("end_or_beginning (number, default=0)",fs("The timing of the payment payments are due for each period."),zd)],compute:function(e,t,s,o={value:0},i={value:0}){const n=bo(t,this.locale),r=bo(e,this.locale),a=To(i)?1:0,l=bo(o,this.locale);return{value:wu(r,n,bo(s,this.locale),l,a),format:"#,##0.00"}},isExported:!0};function Ru(e,t,s,o,i,n){if(s<=0)throw new Cs(Th(s));if(t<=0||t>s)throw new Cs(fs("The period must be between 1 and number_of_periods (%s)",s));const r=wu(e,s,o,i,n);if(1===n&&1===t)return r;return r+-lu(e,0===n?t-1:t-2,r,o+r*n,0)*e}const xu={description:fs("Payment on the principal of an investment."),args:[as("rate (number)",fs("The annualized rate of interest.")),as("period (number)",fs("The amortization period, in terms of number of periods.")),as("number_of_periods (number)",fs("The number of payments to be made.")),as("present_value (number)",fs("The current value of the annuity.")),as("future_value (number, default=0)",fs("The future value remaining after the final payment has been made.")),as("end_or_beginning (number, default=0)",fs("The timing of the payment payments are due for each period."),zd)],compute:function(e,t,s,o,i={value:0},n={value:0}){const r=bo(s,this.locale),a=bo(e,this.locale),l=bo(t,this.locale),c=To(n)?1:0,h=bo(i,this.locale);return{value:Ru(a,l,r,bo(o,this.locale),h,c),format:"#,##0.00"}},isExported:!0},Tu={description:fs("Present value of an annuity investment."),args:[as("rate (number)",fs("The interest rate.")),as("number_of_periods (number)",fs("The number of payments to be made.")),as("payment_amount (number)",fs("The amount per period to be paid.")),as("future_value (number, default=0)",fs("The future value remaining after the final payment has been made.")),as("end_or_beginning (number, default=0)",fs("The timing of the payment payments are due for each period."),zd)],compute:function(e,t,s,o={value:0},i={value:0}){o=o||0,i=i||0;const n=bo(e,this.locale),r=bo(t,this.locale),a=bo(s,this.locale),l=bo(o,this.locale),c=To(i)?1:0;return{value:n?-(a*(1+n*c)*((1+n)**r-1)/n+l)/(1+n)**r:-(l+a*r),format:"#,##0.00"}},isExported:!0},Au={description:fs("Price of a security paying periodic interest."),args:[as("settlement (date)",fs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),as("maturity (date)",fs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),as("rate (number)",fs("The annualized rate of interest.")),as("yield (number)",fs("The expected annual yield of the security.")),as("redemption (number)",fs("The redemption amount per 100 face value, or par.")),as("frequency (number)",fs("The number of interest or coupon payments per year (1, 2, or 4)."),Hd),as("day_count_convention (number, default=0 )",fs("An indicator of what day count method to use."),$h)],compute:function(e,t,s,o,i,n,r={value:0}){r=r||0;const a=Math.trunc(bo(e,this.locale)),l=Math.trunc(bo(t,this.locale)),c=bo(s,this.locale),h=bo(o,this.locale),d=bo(i,this.locale),u=Math.trunc(bo(n,this.locale)),g=Math.trunc(bo(r,this.locale));if(a>=l)return new Cs(xh(a,l));if(Gh(u))return new Cs(ph(u));if(Bh(g))return new Cs(mh(g));if(c<0)return new Cs(Mh(c));if(h<0)return new Cs(Hh(h));if(d<=0)return new Cs(Lh(d));const p=to(a,l,g)*u,m=Math.ceil(p),f=p-Math.floor(p)||1,v=1+h/u,b=100*c/u;if(1===m)return(b+d)/(f*h/u+1)-b*(1-f);let S=0;for(let e=1;e<=m;e++)S+=b/v**(e-1+f);return d/v**(m-1+f)+S-b*(1-f)},isExported:!0},Du={description:fs("Price of a discount security."),args:[as("settlement (date)",fs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),as("maturity (date)",fs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),as("discount (number)",fs("The discount rate of the security at time of purchase.")),as("redemption (number)",fs("The redemption amount per 100 face value, or par.")),as("day_count_convention (number, default=0 )",fs("An indicator of what day count method to use."),$h)],compute:function(e,t,s,o,i={value:0}){i=i||0;const n=Math.trunc(bo(e,this.locale)),r=Math.trunc(bo(t,this.locale)),a=bo(s,this.locale),l=bo(o,this.locale),c=Math.trunc(bo(i,this.locale));if(n>=r)return new Cs(xh(n,r));if(Bh(c))return new Cs(mh(c));if(a<=0)return new Cs(vh(a));if(l<=0)return new Cs(Lh(l));return l-a*l*to(n,r,c)},isExported:!0},_u={description:fs("Calculates the price of a security paying interest at maturity, based on expected yield."),args:[as("settlement (date)",fs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),as("maturity (date)",fs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),as("issue (date)",fs("The date the security was initially issued.")),as("rate (number)",fs("The annualized rate of interest.")),as("yield (number)",fs("The expected annual yield of the security.")),as("day_count_convention (number, default=0 )",fs("An indicator of what day count method to use."),$h)],compute:function(e,t,s,o,i,n={value:0}){n=n||0;const r=Math.trunc(bo(e,this.locale)),a=Math.trunc(bo(t,this.locale)),l=Math.trunc(bo(s,this.locale)),c=bo(o,this.locale),h=bo(i,this.locale),d=Math.trunc(bo(n,this.locale));if(r<=l)return new Cs(((e,t)=>fs("The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).",{settlement:e,issue:t}))(r,l));if(r>=a)return new Cs(xh(r,a));if(Bh(d))return new Cs(mh(d));if(c<0)return new Cs(Mh(c));if(h<0)return new Cs(Hh(h));const u=to(r,a,d),g=to(r,l,d);return(100+to(l,a,d)*c*100)/(1+u*h)-g*c*100},isExported:!0},Ou=.1,Fu={description:fs("Interest rate of an annuity investment."),args:[as("number_of_periods (number)",fs("The number of payments to be made.")),as("payment_per_period (number)",fs("The amount per period to be paid.")),as("present_value (number)",fs("The current value of the annuity.")),as("future_value (number, default=0)",fs("The future value remaining after the final payment has been made.")),as("end_or_beginning (number, default=0)",fs("The timing of the payment payments are due for each period."),zd),as("rate_guess (number, default=0.1)",fs("An estimate for what the interest rate will be."))],compute:function(e,t,s,o={value:0},i={value:0},n={value:Ou}){const r=bo(e,this.locale),a=bo(t,this.locale),l=To(i)?1:0,c=bo(n,this.locale)||Ou;let h=bo(o,this.locale),d=bo(s,this.locale);if(r<=0)return new Cs(Th(r));if(!zh([a,d,h]))return new Cs(fs("There must be both positive and negative values in [payment_amount, present_value, future_value]."));if(c<=-1)return new Cs(Ph(c));h-=a*l,d+=a*l;return{value:Gd(e=>{const t=Math.pow(1+e,r);return h+d*t+a*((t-1)/e)},e=>{const t=Math.pow(1+e,r-1),s=Math.pow(1+e,r);return d*r*t+a*(r*t/e-(s-1)/e/e)},c,40,1e-5),format:"0%"}},isExported:!0},Pu={description:fs("Amount received at maturity for a security."),args:[as("settlement (date)",fs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),as("maturity (date)",fs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),as("investment (number)",fs("The amount invested (irrespective of face value of each security).")),as("discount (number)",fs("The discount rate of the security invested in.")),as("day_count_convention (number, default=0 )",fs("An indicator of what day count method to use."),$h)],compute:function(e,t,s,o,i={value:0}){i=i||0;const n=Math.trunc(bo(e,this.locale)),r=Math.trunc(bo(t,this.locale)),a=bo(s,this.locale),l=bo(o,this.locale),c=Math.trunc(bo(i,this.locale));if(n>=r)return new Cs(xh(n,r));if(Bh(c))return new Cs(mh(c));if(a<=0)return new Cs(Ih(a));if(l<=0)return new Cs(vh(l));return a/(1-l*to(n,r,c))},isExported:!0},Mu={description:fs("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:[as("number_of_periods (number)",fs("The number of periods.")),as("present_value (number)",fs("The present value of the investment.")),as("future_value (number)",fs("The future value of the investment."))],compute:function(e,t,s){const o=bo(e,this.locale),i=bo(t,this.locale),n=bo(s,this.locale);return o<=0?new Cs(Th(o)):(n/i)**(1/o)-1},isExported:!0},Nu={description:fs("Depreciation of an asset using the straight-line method."),args:[as("cost (number)",fs("The initial cost of the asset.")),as("salvage (number)",fs("The value of the asset at the end of depreciation.")),as("life (number)",fs("The number of periods over which the asset is depreciated."))],compute:function(e,t,s){return{value:(bo(e,this.locale)-bo(t,this.locale))/bo(s,this.locale),format:"#,##0.00"}},isExported:!0},Lu={description:fs("Depreciation via sum of years digit method."),args:[as("cost (number)",fs("The initial cost of the asset.")),as("salvage (number)",fs("The value of the asset at the end of depreciation.")),as("life (number)",fs("The number of periods over which the asset is depreciated.")),as("period (number)",fs("The single period within life for which to calculate depreciation."))],compute:function(e,t,s,o){const i=bo(e,this.locale),n=bo(t,this.locale),r=bo(s,this.locale),a=bo(o,this.locale);if(a<=0)return new Cs(_h(a));if(r<=0)return new Cs(Rh(r));if(a>r)return new Cs(Dh(a,r));return{value:(r-a+1)/(r*(r+1)/2)*(i-n),format:"#,##0.00"}},isExported:!0};function ku(e,t,s){return 100*(1-s*to(e,t,2))}const Vu={description:fs("Price of a US Treasury bill."),args:[as("settlement (date)",fs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),as("maturity (date)",fs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),as("discount (number)",fs("The discount rate of the bill at time of purchase."))],compute:function(e,t,s){const o=Math.trunc(bo(e,this.locale)),i=Math.trunc(bo(t,this.locale)),n=bo(s,this.locale);return o>=i?new Cs(xh(o,i)):Wh(o,i,this.locale)?n<=0?new Cs(vh(n)):n>=1?new Cs(bh(n)):ku(o,i,n):new Cs(Vh(o,i))},isExported:!0},Uu={description:fs("Equivalent rate of return for a US Treasury bill."),args:[as("settlement (date)",fs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),as("maturity (date)",fs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),as("discount (number)",fs("The discount rate of the bill at time of purchase."))],compute:function(e,t,s){const o=Math.trunc(bo(e,this.locale)),i=Math.trunc(bo(t,this.locale)),n=bo(s,this.locale);if(o>=i)return new Cs(xh(o,i));if(!Wh(o,i,this.locale))return new Cs(Vh(o,i));if(n<=0)return new Cs(vh(n));if(n>=1)return new Cs(bh(n));const r=Kh.compute.bind(this)({value:i},{value:o});if(r<=182)return 365*n/(360-n*r);const a=ku(o,i,n)/100,l=r/(366===r?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},Hu={description:fs("The yield of a US Treasury bill based on price."),args:[as("settlement (date)",fs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),as("maturity (date)",fs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),as("price (number)",fs("The price at which the security is bought per 100 face value."))],compute:function(e,t,s){const o=Math.trunc(bo(e,this.locale)),i=Math.trunc(bo(t,this.locale)),n=bo(s,this.locale);if(o>=i)return new Cs(xh(o,i));if(!Wh(o,i,this.locale))return new Cs(Vh(o,i));if(n<=0)return new Cs(Fh(n));return(100-n)/n*(1/to(o,i,2))},isExported:!0},zu=!1,Bu={description:fs("Variable declining balance. WARNING : does not handle decimal periods."),args:[as("cost (number)",fs("The initial cost of the asset.")),as("salvage (number)",fs("The value of the asset at the end of depreciation.")),as("life (number)",fs("The number of periods over which the asset is depreciated.")),as("start (number)",fs("Starting period to calculate depreciation.")),as("end (number)",fs("Ending period to calculate depreciation.")),as("factor (number, default=2)",fs("The number of months in the first year of depreciation.")),as("no_switch (number, default=false)",fs("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation."),[{value:!1,label:fs("Switch to straight-line depreciation")},{value:!0,label:fs("Do not switch to straight-line depreciation")}])],compute:function(e,t,s,o,i,n={value:2},r={value:zu}){n=n||0;const a=bo(e,this.locale),l=bo(t,this.locale),c=bo(s,this.locale),h=Math.trunc(bo(o,this.locale)),d=Math.trunc(bo(i,this.locale)),u=bo(n,this.locale),g=To(r);if(a<0)return new Cs(gh(a));if(l<0)return new Cs(kh(l));if(c<=0)return new Cs(Rh(c));if(h<0)return new Cs((e=>fs("The start_period (%s) must be positive or null.",e))(h));if(d<0)return new Cs((e=>fs("The end_period (%s) must be positive or null.",e))(d));if(h>d)return new Cs(fs("The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).",{start:h,end:d}));if(d>c)return new Cs(((e,t)=>fs("The end_period (%(end)s) must be smaller or equal to the life (%(life)s).",{end:e,life:t}))(d,c));if(u<=0)return new Cs(fh(u));if(0===a)return 0;if(l>=a)return h<1?a-l:0;const p=u/c;if(p>=1)return h<1?a-l:0;let m=a,f=0,v=0,b=!1;for(let e=0;e<d;e++){if(!b||g){const t=m*p,s=(m-l)/(c-e);!g&&s>t?(b=!0,f=s):f=t}const t=Math.max(m-f,l);e>=h&&(v+=m-t),m=t}return v},isExported:!0},Gu={description:fs("Internal rate of return given non-periodic cash flows."),args:[as("cashflow_amounts (range<number>)",fs("An range containing the income or payments associated with the investment.")),as("cashflow_dates (range<number>)",fs("An range with dates corresponding to the cash flows in cashflow_amounts.")),as("rate_guess (number, default=0.1)",fs("An estimate for what the internal rate of return will be."))],compute:function(e,t,s={value:Ou}){const o=bo(s,this.locale);if(!ci(e,t))return new Cs(dh);const i=e.flat().map(e=>bo(e,this.locale)),n=t.flat().map(e=>bo(e,this.locale));if(!zh(i))return new Cs(uh);if(n.some(e=>e<n[0]))return new Cs(Sh(n[0]));if(o<=-1)return new Cs(Ph(o));const r=new Map;for(const e of ge(0,n.length)){const t=n[e];r.has(t)?r.set(t,r.get(t)+i[e]):r.set(t,i[e])}const a=Array.from(r.keys()),l=a.map(e=>r.get(e));return Gd(e=>{let t=l[0];for(const s of ge(1,l.length)){const o=(a[0]-a[s])/365;t+=l[s]*(1+e)**o}return t},e=>{let t=0;for(const s of ge(1,l.length)){const o=(a[0]-a[s])/365;t+=o*l[s]*(1+e)**(o-1)}return t},o,40,1e-5,e=>e?e/10-.9:-.9)},isExported:!0},Wu={description:fs("Net present value given to non-periodic cash flows.."),args:[as("discount (number)",fs("The discount rate of the investment over one period.")),as("cashflow_amounts (number, range<number>)",fs("An range containing the income or payments associated with the investment.")),as("cashflow_dates (number, range<number>)",fs("An range with dates corresponding to the cash flows in cashflow_amounts."))],compute:function(e,t,s){const o=bo(e,this.locale);if(!ci(t,s))return new Cs(dh);const i=Xo(t).flat().map(e=>yo(e,this.locale)),n=Xo(s).flat().map(e=>yo(e,this.locale));if(n.some(e=>e<n[0]))return new Cs(Sh(n[0]));if(o<=0)return new Cs(Nh(o));if(1===i.length)return i[0];const r=new Map;for(const e of ge(0,n.length)){const t=n[e];r.has(t)?r.set(t,r.get(t)+i[e]):r.set(t,i[e])}const a=Array.from(r.keys()),l=a.map(e=>r.get(e));let c=l[0];for(const e of ge(1,l.length)){const t=(a[0]-a[e])/365;c+=l[e]*(1+o)**t}return c},isExported:!0},$u={description:fs("Annual yield of a security paying periodic interest."),args:[as("settlement (date)",fs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),as("maturity (date)",fs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),as("rate (number)",fs("The annualized rate of interest.")),as("price (number)",fs("The price at which the security is bought per 100 face value.")),as("redemption (number)",fs("The redemption amount per 100 face value, or par.")),as("frequency (number)",fs("The number of interest or coupon payments per year (1, 2, or 4)."),Hd),as("day_count_convention (number, default=0 )",fs("An indicator of what day count method to use."),$h)],compute:function(e,t,s,o,i,n,r={value:0}){r=r||0;const a=Math.trunc(bo(e,this.locale)),l=Math.trunc(bo(t,this.locale)),c=bo(s,this.locale),h=bo(o,this.locale),d=bo(i,this.locale),u=Math.trunc(bo(n,this.locale)),g=Math.trunc(bo(r,this.locale));if(a>=l)return new Cs(xh(a,l));if(Gh(u))return new Cs(ph(u));if(Bh(g))return new Cs(mh(g));if(c<0)return new Cs(Mh(c));if(h<=0)return new Cs(Fh(h));if(d<=0)return new Cs(Lh(d));const p=to(a,l,g)*u,m=Math.ceil(p),f=p-Math.floor(p)||1,v=100*c/u;if(1===m){const e=h+v*(1-f);return(d+v-e)*u*(1/f)/e}const b=Gd(function(e){return function(e,t,s,o,i,n){let r=n-(e+i*(1-t))*o**(s-1+t);for(let e=1;e<=s;e++)r+=i*o**(e-1);return r}(h,f,m,e,v,d)},function(e){return function(e,t,s,o,i){let n=-(e+i*(1-t))*(s-1+t)*o**(s-2+t);for(let e=1;e<=s;e++)n+=i*(e-1)*o**(e-2);return n}(h,f,m,e,v)},1+(c+1)/u,100,1e-5);return(b-1)*u},isExported:!0},qu={description:fs("Annual yield of a discount security."),args:[as("settlement (date)",fs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),as("maturity (date)",fs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),as("price (number)",fs("The price at which the security is bought per 100 face value.")),as("redemption (number)",fs("The redemption amount per 100 face value, or par.")),as("day_count_convention (number, default=0 )",fs("An indicator of what day count method to use."),$h)],compute:function(e,t,s,o,i={value:0}){i=i||0;const n=Math.trunc(bo(e,this.locale)),r=Math.trunc(bo(t,this.locale)),a=bo(s,this.locale),l=bo(o,this.locale),c=Math.trunc(bo(i,this.locale));if(n>=r)return new Cs(xh(n,r));if(Bh(c))return new Cs(mh(c));if(a<=0)return new Cs(Fh(a));if(l<=0)return new Cs(Lh(l));return(l/a-1)/to(n,r,c)},isExported:!0},Zu={description:fs("Annual yield of a security paying interest at maturity."),args:[as("settlement (date)",fs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),as("maturity (date)",fs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),as("issue (date)",fs("The date the security was initially issued.")),as("rate (number)",fs("The annualized rate of interest.")),as("price (number)",fs("The price at which the security is bought.")),as("day_count_convention (number, default=0 )",fs("An indicator of what day count method to use."),$h)],compute:function(e,t,s,o,i,n={value:0}){n=n||0;const r=Math.trunc(bo(e,this.locale)),a=Math.trunc(bo(t,this.locale)),l=Math.trunc(bo(s,this.locale)),c=bo(o,this.locale),h=bo(i,this.locale),d=Math.trunc(bo(n,this.locale));if(r>=a)return new Cs(xh(r,a));if(Bh(d))return new Cs(mh(d));if(r<l)return new Cs(((e,t)=>fs("The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).",{settlement:e,issue:t}))(r,l));if(c<0)return new Cs(Mh(c));if(h<=0)return new Cs(Fh(h));return(100*(1+c*to(l,a,d))/(h+100*c*to(l,r,d))-1)/to(r,a,d)},isExported:!0};var ju=Object.freeze({__proto__:null,ACCRINTM:Wd,AMORLINC:$d,COUPDAYBS:Zd,COUPDAYS:qd,COUPDAYSNC:jd,COUPNCD:Yd,COUPNUM:Xd,COUPPCD:Kd,CUMIPMT:Jd,CUMPRINC:Qd,DB:eu,DDB:su,DISC:ou,DOLLARDE:iu,DOLLARFR:nu,DURATION:ru,EFFECT:au,FV:cu,FVSCHEDULE:hu,INTRATE:du,IPMT:gu,IRR:pu,ISPMT:mu,MDURATION:fu,MIRR:vu,NOMINAL:bu,NPER:Su,NPV:yu,PDURATION:Iu,PMT:Eu,PPMT:xu,PRICE:Au,PRICEDISC:Du,PRICEMAT:_u,PV:Tu,RATE:Fu,RECEIVED:Pu,RRI:Mu,SLN:Nu,SYD:Lu,TBILLEQ:Uu,TBILLPRICE:Vu,TBILLYIELD:Hu,VDB:Bu,XIRR:Gu,XNPV:Wu,YIELD:$u,YIELDDISC:qu,YIELDMAT:Zu});const Yu=[{value:"address",label:fs("Returns an absolute reference as plain text of the top left cell in reference.")},{value:"col",label:fs("Returns the column number of the cell in reference.")},{value:"contents",label:fs("Returns the value contained in the top left cell in reference.")},{value:"format",label:fs("Returns the format of the top left cell in reference.")},{value:"row",label:fs("Returns the row number of the top left cell in reference.")},{value:"type",label:fs('Returns the type of data in the cell in reference. The following values are returned: "b" for a blank cell, "l" (for label) if the cell contains plain text, and "v" (for value) if the cell contains any other type of data.')}],Xu={description:fs("Gets information about a cell."),args:[as("info_type (string)",fs("The type of information requested."),Yu),as("reference (meta, range<meta>)",fs("The reference to the cell."))],compute:function(e,t){const s=Eo(e).toLowerCase();if(!Yu.map(e=>e.value).includes(s))return new Cs(fs("The info_type should be one of %s.",Yu.join(", ")));const o=this.__originSheetId,i=t[0][0].value;let{sheetName:n,xc:r}=tr(i);n=n===this.getters.getSheetName(o)?void 0:n;const a=sr(n,nr(r,"colrow")),l=this.getters.getRangeFromSheetXC(o,a);switch(s){case"address":return this.getters.getRangeString(l,o);case"col":return l.zone.left+1;case"contents":{const e={sheetId:l.sheetId,col:l.zone.left,row:l.zone.top};return this.getters.getEvaluatedCell(e).value}case"format":{const e={sheetId:l.sheetId,col:l.zone.left,row:l.zone.top};return this.getters.getEvaluatedCell(e).format||""}case"row":return l.zone.top+1;case"type":{const e={sheetId:l.sheetId,col:l.zone.left,row:l.zone.top},t=this.getters.getEvaluatedCell(e).type;return t===_d.empty?"b":t===_d.text?"l":"v"}}return""},isExported:!0},Ku={description:fs("Whether a value is an error other than #N/A."),args:[as("value (any)",fs("The value to be verified as an error type."))],compute:function(e){const t=e?.value;return mo(t)&&t!==bs.NotAvailable},isExported:!0},Ju={description:fs("Whether a value is an error."),args:[as("value (any)",fs("The value to be verified as an error type."))],compute:function(e){const t=e?.value;return mo(t)},isExported:!0},Qu={description:fs("Whether a value is `true` or `false`."),args:[as("value (any)",fs("The value to be verified as a logical TRUE or FALSE."))],compute:function(e){return"boolean"==typeof e?.value},isExported:!0},eg={description:fs("Whether a value is the error #N/A."),args:[as("value (any)",fs("The value to be verified as an error type."))],compute:function(e){return e?.value===bs.NotAvailable},isExported:!0},tg={description:fs("Whether a value is non-textual."),args:[as("value (any)",fs("The value to be checked."))],compute:function(e){return!og.compute.bind(this)(e)},isExported:!0},sg={description:fs("Whether a value is a number."),args:[as("value (any)",fs("The value to be verified as a number."))],compute:function(e){return"number"==typeof e?.value},isExported:!0},og={description:fs("Whether a value is text."),args:[as("value (any)",fs("The value to be verified as text."))],compute:function(e){return"string"==typeof e?.value&&!1===mo(e?.value)},isExported:!0},ig={description:fs("Whether the referenced cell is empty"),args:[as("value (any)",fs("Reference to the cell that will be checked for emptiness."))],compute:function(e){return null===e?.value},isExported:!0},ng={description:fs("Returns the error value #N/A."),args:[],compute:function(){return{value:bs.NotAvailable}},isExported:!0};var rg=Object.freeze({__proto__:null,CELL:Xu,ISBLANK:ig,ISERR:Ku,ISERROR:Ju,ISLOGICAL:Qu,ISNA:eg,ISNONTEXT:tg,ISNUMBER:sg,ISTEXT:og,NA:ng});function ag(e){let t=!1,s=!0;return zo(e,e=>(t=!0,s=s&&e,s)),{foundBoolean:t,result:s}}function lg(e){let t=!1,s=!1;return zo(e,e=>(t=!0,s=s||e,!s)),{foundBoolean:t,result:s}}const cg={description:fs("Logical `and` operator."),args:[as("logical_expression1 (boolean, range<boolean>)",fs("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.")),as("logical_expression2 (boolean, range<boolean>, repeating)",fs("More expressions that represent logical values."))],compute:function(...e){const{result:t,foundBoolean:s}=ag(e);return s?t:new Cs(Qo)},isExported:!0},hg={description:fs("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},dg={description:fs("Returns value depending on logical expression."),args:[as("logical_expression (boolean, range<boolean>)",fs("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")),as("value_if_true (any, range)",fs("The value the function returns if logical_expression is TRUE.")),as("value_if_false (any, range, default=FALSE)",fs("The value the function returns if logical_expression is FALSE."))],compute:function(e,t,s){if(bi(e))return Ho(dg.compute,[e,t,s]);return(To(fi(e))?t:s)??{value:0}},isExported:!0},ug={description:fs("Value if it is not an error, otherwise 2nd argument."),args:[as("value (any, range)",fs("The value to return if value itself is not an error.")),as('value_if_error (any, range, default="empty")',fs("The value the function returns if value is an error."))],compute:function(e,t){if(bi(e))return Ho(ug.compute,[e,t]);return(mo(fi(e)?.value)?t:e)??{value:0}},isExported:!0},gg={description:fs("Value if it is not an #N/A error, otherwise 2nd argument."),args:[as("value (any, range)",fs("The value to return if value itself is not #N/A an error.")),as('value_if_error (any, range, default="empty")',fs("The value the function returns if value is an #N/A error."))],compute:function(e,t){if(bi(e))return Ho(gg.compute,[e,t]);return(fi(e)?.value===bs.NotAvailable?t:e)??{value:0}},isExported:!0},pg={description:fs("Returns a value depending on multiple logical expressions."),args:[as("condition1 (boolean, range<boolean>)",fs("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")),as("value1 (any, range)",fs("The returned value if condition1 is TRUE.")),as("condition2 (boolean, any, range, repeating)",fs("Additional conditions to be evaluated if the previous ones are FALSE.")),as("value2 (any, range, repeating)",fs("Additional values to be returned if their corresponding conditions are TRUE."))],compute:function(...e){if(e.length%2!=0)return new Cs(fs("Wrong number of arguments. Expected an even number of arguments."));for(;e.length>0;){if(bi(e[0]))return Ho(pg.compute,e);const t=To(fi(e.shift())),s=e.shift();if(t)return s??{value:0}}return new Cs(fs("No match."))},isExported:!0},mg={description:fs("Returns opposite of provided logical value."),args:[as("logical_expression (boolean)",fs("An expression or reference to a cell holding an expression that represents some logical value."))],compute:function(e){return!To(e)},isExported:!0},fg={description:fs("Logical `or` operator."),args:[as("logical_expression1 (boolean, range<boolean>)",fs("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.")),as("logical_expression2 (boolean, range<boolean>, repeating)",fs("More expressions that evaluate to logical values."))],compute:function(...e){const{result:t,foundBoolean:s}=lg(e);return s?t:new Cs(Qo)},isExported:!0},vg={description:fs("Returns a value by comparing cases to an expression."),args:[as("expression (number, boolean, string)",fs("The value to be checked.")),as("case1 (number, boolean, string)",fs("The first case to be checked against expression.")),as("value1 (any)",fs("The corresponding value to be returned if case1 matches expression.")),as("case2 (any, repeating)",fs("Additional cases to try if the previous ones don't match expression.")),as("value2 (any, repeating)",fs("Additional values to be returned if their corresponding cases match expression.")),as('default (any, default="empty")',fs("An optional default value to be returned if none of the cases match expression."))],compute:function(e,...t){const s=t.length%2==0?fo(e):t.pop();for(let s=0;s<t.length;s+=2){const o=t[s];if(o&&mo(o.value))return o;if(e?.value===o?.value)return t[s+1]||{value:0}}return s||{value:0}},isExported:!0},bg={description:fs("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},Sg={description:fs("Logical `xor` operator."),args:[as("logical_expression1 (boolean, range<boolean>)",fs("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.")),as("logical_expression2 (boolean, range<boolean>, repeating)",fs("More expressions that evaluate to logical values."))],compute:function(...e){let t=!1,s=!1;return zo(e,e=>(t=!0,s=s?!e:e,!0)),t?s:new Cs(Qo)},isExported:!0};var Cg=Object.freeze({__proto__:null,AND:cg,FALSE:hg,IF:dg,IFERROR:ug,IFNA:gg,IFS:pg,NOT:mg,OR:fg,SWITCH:vg,TRUE:bg,XOR:Sg});const yg={Errors:{InvalidRange:fs("The range is invalid"),FirstArgMissing:fs("The argument is missing. Please provide a value"),SecondArgMissing:fs("The second argument is missing. Please provide a value"),MinNaN:fs("The minpoint must be a number"),MidNaN:fs("The midpoint must be a number"),MaxNaN:fs("The maxpoint must be a number"),ValueUpperInflectionNaN:fs("The first value must be a number"),ValueLowerInflectionNaN:fs("The second value must be a number"),MinBiggerThanMax:fs("Minimum must be smaller then Maximum"),MinBiggerThanMid:fs("Minimum must be smaller then Midpoint"),MidBiggerThanMax:fs("Midpoint must be smaller then Maximum"),LowerBiggerThanUpper:fs("Lower inflection point must be smaller than upper inflection point"),MinInvalidFormula:fs("Invalid Minpoint formula"),MaxInvalidFormula:fs("Invalid Maxpoint formula"),MidInvalidFormula:fs("Invalid Midpoint formula"),ValueUpperInvalidFormula:fs("Invalid upper inflection point formula"),ValueLowerInvalidFormula:fs("Invalid lower inflection point formula"),EmptyRange:fs("A range needs to be defined"),ValueCellIsInvalidFormula:fs("At least one of the provided values is an invalid formula"),Unexpected:fs("The rule is invalid for an unknown reason")},ColorScale:fs("Color scale"),IconSet:fs("Icon set"),DataBar:fs("Data bar")},Ig={Series:fs("Series"),BackgroundColor:fs("Background color"),StackedBarChart:fs("Stacked bar chart"),StackedLineChart:fs("Stacked line chart"),StackedAreaChart:fs("Stacked area chart"),StackedColumnChart:fs("Stacked column chart"),CumulativeData:fs("Cumulative data"),TreatLabelsAsText:fs("Treat labels as text"),AggregatedChart:fs("Aggregate"),Errors:{Unexpected:fs("The chart definition is invalid for an unknown reason"),InvalidDataSet:fs("The dataset is invalid"),InvalidLabelRange:fs("Labels are invalid"),InvalidScorecardKeyValue:fs("The key value is invalid"),InvalidScorecardBaseline:fs("The baseline value is invalid"),InvalidGaugeDataRange:fs("The data range is invalid"),EmptyGaugeRangeMin:fs("A minimum range limit value is needed"),GaugeRangeMinNaN:fs("The minimum range limit value must be a number"),EmptyGaugeRangeMax:fs("A maximum range limit value is needed"),GaugeRangeMaxNaN:fs("The maximum range limit value must be a number"),GaugeLowerInflectionPointNaN:fs("The lower inflection point value must be a number"),GaugeUpperInflectionPointNaN:fs("The upper inflection point value must be a number")},GeoChart:{ColorScales:{blues:fs("Blues"),cividis:fs("Cividis"),greens:fs("Greens"),greys:fs("Greys"),oranges:fs("Oranges"),purples:fs("Purples"),rainbow:fs("Rainbow"),reds:fs("Reds"),viridis:fs("Viridis")}}},wg={Custom:fs("Custom")},Eg=fs("Merged cells are preventing this operation. Unmerge those cells and try again."),Rg=fs("The header row of a table can't be moved."),xg={Errors:{Unexpected:fs("Cannot split the selection for an unknown reason"),NoSplitSeparatorInSelection:fs("There is no match for the selected separator in the selection"),MoreThanOneColumnSelected:fs("Only a selection from a single column can be split"),SplitWillOverwriteContent:fs("Splitting will overwrite existing content")}},Tg={Errors:{Unexpected:fs("Cannot remove duplicates for an unknown reason"),MoreThanOneRangeSelected:fs("Please select only one range of cells"),EmptyTarget:fs("Please select a range of cells containing values."),NoColumnsProvided:fs("Please select at latest one column to analyze."),WillRemoveExistingMerge:fs("This operation is not possible due to a merge. Please remove the merges first than try again.")}},Ag={DateIs:{today:fs("today"),yesterday:fs("yesterday"),tomorrow:fs("tomorrow"),lastWeek:fs("in the past week"),lastMonth:fs("in the past month"),lastYear:fs("in the past year")},DateIsBefore:{today:fs("today"),yesterday:fs("yesterday"),tomorrow:fs("tomorrow"),lastWeek:fs("one week ago"),lastMonth:fs("one month ago"),lastYear:fs("one year ago")},CriterionError:{notEmptyValue:fs("The value must not be empty"),numberValue:fs("The value must be a number"),dateValue:fs("The value must be a date"),validRange:fs("The value must be a valid range"),validFormula:fs("The formula must be valid")},Errors:{InvalidRange:fs("The range is invalid."),InvalidDataValidationCriterionValue:fs("One or more of the provided criteria values are invalid. Please review and correct them."),InvalidNumberOfCriterionValues:fs("One or more of the provided criteria values are missing."),Unexpected:fs("The rule is invalid for an unknown reason.")}},Dg={Errors:{Unexpected:fs("The table zone is invalid for an unknown reason"),TableOverlap:fs("You cannot create overlapping tables."),NonContinuousTargets:fs("A table can only be created on a continuous selection."),InvalidRange:fs("The range is invalid"),TargetOutOfSheet:fs("The range is out of the sheet")},Checkboxes:{hasFilters:fs("Filter button"),headerRow:fs("Header row(s)"),bandedRows:fs("Banded rows"),firstColumn:fs("First column"),lastColumn:fs("Last column"),bandedColumns:fs("Banded columns"),automaticAutofill:fs("Automatically autofill formulas"),totalRow:fs("Total row"),isDynamic:fs("Auto-adjust to formula result")},Tooltips:{filterWithoutHeader:fs("Cannot have filters without a header row"),isDynamic:fs("For tables based on array formulas only")}},_g={labels:{no_calculations:fs("No calculations"),"%_of_grand_total":fs("% of grand total"),"%_of_col_total":fs("% of column total"),"%_of_row_total":fs("% of row total"),"%_of":fs("% of"),"%_of_parent_row_total":fs("% of parent row total"),"%_of_parent_col_total":fs("% of parent column total"),"%_of_parent_total":fs("% of parent total"),difference_from:fs("Difference from"),"%_difference_from":fs("% difference from"),running_total:fs("Running total"),"%_running_total":fs("% Running total"),rank_asc:fs("Rank smallest to largest"),rank_desc:fs("Rank largest to smallest"),index:fs("Index")},descriptions:{"%_of_grand_total":()=>fs("Displayed as % of grand total"),"%_of_col_total":()=>fs("Displayed as % of column total"),"%_of_row_total":()=>fs("Displayed as % of row total"),"%_of":e=>fs('Displayed as % of "%s"',e),"%_of_parent_row_total":e=>fs('Displayed as % of parent row total of "%s"',e),"%_of_parent_col_total":()=>fs("Displayed as % of parent column total"),"%_of_parent_total":e=>fs('Displayed as % of parent "%s" total',e),difference_from:e=>fs('Displayed as difference from "%s"',e),"%_difference_from":e=>fs('Displayed as % difference from "%s"',e),running_total:e=>fs('Displayed as running total based on "%s"',e),"%_running_total":e=>fs('Displayed as % running total based on "%s"',e),rank_asc:e=>fs('Displayed as rank from smallest to largest based on "%s"',e),rank_desc:e=>fs('Displayed as rank largest to smallest based on "%s"',e),index:()=>fs("Displayed as index")},documentation:{no_calculations:fs("Displays the value that is entered in the field."),"%_of_grand_total":fs("Displays values as a percentage of the grand total of all the values or data points in the report."),"%_of_col_total":fs("Displays all the values in each column or series as a percentage of the total for the column or series."),"%_of_row_total":fs("Displays the value in each row or category as a percentage of the total for the row or category."),"%_of":fs("Displays values as a percentage of the value of the Base item in the Base field."),"%_of_parent_row_total":fs("Calculates values as follows:\n(value for the item) / (value for the parent item on rows)"),"%_of_parent_col_total":fs("Calculates values as follows:\n(value for the item) / (value for the parent item on columns)"),"%_of_parent_total":fs("Calculates values as follows:\n(value for the item) / (value for the parent item of the selected Base field)"),difference_from:fs("Displays values as the difference from the value of the Base item in the Base field."),"%_difference_from":fs("Displays values as the percentage difference from the value of the Base item in the Base field."),running_total:fs("Displays the value for successive items in the Base field as a running total."),"%_running_total":fs("Calculates the value as a percentage for successive items in the Base field that are displayed as a running total."),rank_asc:fs("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:fs("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:fs("Calculates values as follows:\n((value in cell) x (Grand Total of Grand Totals)) / ((Grand Row Total) x (Grand Column Total))")}};class Og{content={};add(e,t){if(e in this.content)throw new Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(e,t){return this.content[e]=t,this}get(e){const t=this.content[e];if(!t&&!(e in this.content))throw new 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]}}const Fg=new Og;function Pg(e){return Fg.get(e)}const Mg={normalizeFunctionValue:e=>bo(e,Oc),toValueAndFormat:(e,t)=>({value:bo(e,Oc),format:"dd mmm yyyy"}),toFunctionValue(e){const t=Ao(e,Oc);return`DATE(${t.getFullYear()},${t.getMonth()+1},${t.getDate()})`}},Ng={normalizeFunctionValue(e){const t=bo(e,Oc);if(t<1||t>31)throw new Cs(fs("%s is not a valid day of month (it should be a number between 1 and 31)",t));return t},toValueAndFormat:e=>({value:bo(e,Oc),format:"0"}),toFunctionValue:e=>`${e}`},Lg={normalizeFunctionValue(e){const t=bo(e,Oc);if(t<1||t>7)throw new Cs(fs("%s is not a valid day of week (it should be a number between 1 and 7)",t));return t},toValueAndFormat(e,t){const s=(e-1+(t||Oc).weekStart)%7;return{value:un[s].toString(),format:"@"}},toFunctionValue:e=>`${e}`},kg={normalizeFunctionValue(e){const t=bo(e,Oc);if(t<0||t>53)throw new Cs(fs("%s is not a valid week (it should be a number between 0 and 53)",t));return t},toValueAndFormat:e=>({value:bo(e,Oc),format:"0"}),toFunctionValue:e=>`${e}`},Vg={normalizeFunctionValue(e){const t=bo(e,Oc);if(t<1||t>12)throw new Cs(fs("%s is not a valid month (it should be a number between 1 and 12)",t));return t},toValueAndFormat:e=>({value:dn[bo(e,Oc)-1].toString(),format:"@"}),toFunctionValue:e=>`${e}`},Ug={normalizeFunctionValue:e=>pn(bo(e,Oc),{locale:Oc,format:"mm/yyyy"}),toValueAndFormat:e=>({value:bo(e,Oc),format:"mmmm yyyy"}),toFunctionValue(e){const t=Ao(e,Oc);return`DATE(${t.getFullYear()},${t.getMonth()+1},1)`}},Hg={normalizeFunctionValue(e){const t=bo(e,Oc);if(t<1||t>4)throw new Cs(fs("%s is not a valid quarter (it should be a number between 1 and 4)",t));return t},toValueAndFormat:e=>({value:fs("Q%(quarter_number)s",{quarter_number:e}),format:"@"}),toFunctionValue:e=>`${e}`},zg={normalizeFunctionValue(e){const t=bo(e,Oc);return t>3e3?Ao(t,Oc).getFullYear():t},toValueAndFormat:e=>({value:bo(e,Oc),format:"0"}),toFunctionValue:e=>`${e}`},Bg={normalizeFunctionValue(e){const t=bo(e,Oc);if(t<0||t>23)throw new Cs(fs("%s is not a valid hour (it should be a number between 0 and 23)",t));return t},toValueAndFormat:e=>({value:fs("%(hour_number)sh",{hour_number:e}),format:"@"}),toFunctionValue:e=>`${e}`},Gg={normalizeFunctionValue(e){const t=bo(e,Oc);if(t<0||t>59)throw new Cs(fs("%s is not a valid minute (it should be a number between 0 and 59)",t));return t},toValueAndFormat:e=>({value:fs("%(minute_number)s'",{minute_number:e}),format:"@"}),toFunctionValue:e=>`${e}`},Wg={normalizeFunctionValue(e){const t=bo(e,Oc);if(t<0||t>59)throw new Cs(fs("%s is not a valid second (it should be a number between 0 and 59)",t));return t},toValueAndFormat:e=>({value:fs("%(second_number)s''",{second_number:e}),format:"@"}),toFunctionValue:e=>`${e}`};function $g(e){return{normalizeFunctionValue:t=>null===t?null:e.normalizeFunctionValue(t),toValueAndFormat:(t,s)=>null===t?{value:fs("(Undefined)")}:e.toValueAndFormat(t,s),toFunctionValue:t=>null===t?"false":e.toFunctionValue(t)}}Fg.add("day",$g(Mg)).add("year",$g(zg)).add("day_of_month",$g(Ng)).add("iso_week_number",$g(kg)).add("month_number",$g(Vg)).add("month",$g(Ug)).add("quarter_number",$g(Hg)).add("day_of_week",$g(Lg)).add("hour_number",$g(Bg)).add("minute_number",$g(Gg)).add("second_number",$g(Wg));const qg={count:fs("Count"),count_distinct:fs("Count Distinct"),bool_and:fs("Boolean And"),bool_or:fs("Boolean Or"),max:fs("Maximum"),min:fs("Minimum"),avg:fs("Average"),sum:fs("Sum")},Zg=["max","min","avg","sum","count_distinct","count"],jg={integer:Zg,char:Zg,datetime:Zg,boolean:["count_distinct","count","bool_and","bool_or"]},Yg={};for(const e in jg){Yg[e]={};for(const t of jg[e])Yg[e][t]=qg[t]}const Xg={count:e=>({value:$a([e]),format:"0"}),count_distinct:e=>({value:Rr([e]),format:"0"}),bool_and:e=>({value:ag([e]).result}),bool_or:e=>({value:lg([e]).result}),max:(e,t)=>qa([e],t),min:(e,t)=>Za([e],t),avg:(e,t)=>({value:Ga([e],t),format:po(e)}),sum:(e,t)=>({value:Er([e],t),format:po(e)})};function Kg(e){const t=Object.keys(e);if(!t.length)return 0;const s=t.map(e=>parseInt(e,10));return Math.max(...s)}const Jg={year:fs("Year"),quarter:fs("Quarter & Year"),month:fs("Month & Year"),week:fs("Week & Year"),day:fs("Day"),quarter_number:fs("Quarter"),month_number:fs("Month"),iso_week_number:fs("Week"),day_of_month:fs("Day of Month"),day_of_week:fs("Day of Week"),hour_number:fs("Hour"),minute_number:fs("Minute"),second_number:fs("Second")},Qg=["date","datetime"];function ep(e){const[t,s]=e.split(":");return s?{fieldName:t,granularity:s}:{fieldName:t}}function tp(e){return Qg.includes(e.type)}function sp(e,t,s){const o=[e];s&&o.push(`"${s}"`);for(const{field:e,value:s,type:i}of t){if("measure"===e){o.push('"measure"',`"${s}"`);continue}const{granularity:t}=ep(e),n=ap(s,{type:i,granularity:t});o.push(`"${e}"`,n)}return o}function op(e,t){let s=0,o=0;const i=t.columns.map(e=>e.nameWithGranularity),n=t.rows.map(e=>e.nameWithGranularity);for(;void 0!==e[s]&&e[s]===n[o];)s++,o++;for(o=0;void 0!==e[s]&&e[s]===i[o];)s++,o++;return e.length===s}function ip(e,t){switch(t.type){case"HEADER":return`=PIVOT.HEADER(${sp(e,t.domain).join(",")})`;case"VALUE":return`=PIVOT.VALUE(${sp(e,t.domain,t.measure).join(",")})`;case"MEASURE_HEADER":return`=PIVOT.HEADER(${sp(e,[...t.domain,{field:"measure",value:t.measure,type:"char"}]).join(",")})`}return""}function np(e,t){if(null===t||"null"===t)return null;const s="object"==typeof t?t.value:t;if(mo(s))return s;if("custom"===e.type)return Do(t)??null;const o="boolean"==typeof t?Eo(t).toLocaleLowerCase():Eo(t);if("null"===o)return null;if(!cp.contains(e.type))throw new Cs(fs("Field %(field)s is not supported because of its type (%(type)s)",{field:e.displayName,type:e.type}));if("false"===o.toLowerCase())return!1;return cp.get(e.type)(o,e.granularity)}function rp(e,t){return Pg(t??"month").normalizeFunctionValue(e)}function ap(e,t){return null===e?'"null"':hp.contains(t.type)?hp.get(t.type)(e,t.granularity):`"${e}"`}function lp(e,t){return Pg(t??"month").toFunctionValue(e)}const cp=new Og;cp.add("date",rp).add("datetime",rp).add("integer",e=>bo(e,Oc)).add("boolean",e=>To(e)).add("char",e=>Eo(e)).add("custom",e=>e);const hp=new Og;function dp(e){return e.displayName+(e.granularity?` (${Jg[e.granularity]})`:"")}function up(e,t){return 0===e.length?t:{...t,format:(t.format||"@")+"* "}}function gp(e,t){try{if(!t.getMeasure(e.measure))return!1;const s=t.definition.columns;for(let o=0;o<e.domain.length;o++){if(s[o].nameWithGranularity!==e.domain[o].field)return!1;const i=t.getPossibleFieldValues(s[o]).map(e=>e.value);if(!(i.includes(e.domain[o].value)||null===e.domain[o].value&&i.includes("")))return!1}return!0}catch(e){return!1}}function pp(e,t){return st(e,t.groups.map(e=>e.name),{compute:(e,t)=>`${e}${t}`,start:2})}function mp(e,t){return st(e,Object.values(t).map(e=>[e?.name,e?.string]).flat().filter(Te),{compute:(e,t)=>`${e}${t}`,start:2})}function fp(e,t){const s={};for(const o of Object.values(e.customFields||{})){t[o.parentField]&&(s[o.name]={type:"custom",isCustomField:!0,name:o.name,string:o.name,customGroups:o.groups,parentField:o.parentField})}return s}function vp(e,t){t.groups=t.groups.filter(t=>!t.values.some(t=>e.includes(t)))}function bp(e,t,s){const o=e.rows.some(e=>e.fieldName===t)?e.rows:e.columns,i=o.findIndex(e=>e.fieldName===t);return-1===i||o.some(e=>e.fieldName===s)||o.splice(i,0,{fieldName:s}),e}function Sp(e,t,s){return Object.values(e.customFields||{}).find(e=>e.parentField===t.name)||{parentField:t.name,name:mp(t.string,s),groups:[]}}function Cp(e,t){const s=t.model.getters.getPivotCellFromPosition(e),o=t.model.getters.getPivotIdFromPosition(e);if(!o||"HEADER"!==s.type)return;const i=t.model.getters.getPivotCoreDefinition(o),n=i.collapsedDomains?.[s.dimension]?[...i.collapsedDomains[s.dimension]]:[],r=n.findIndex(e=>Me(e,s.domain));-1!==r?n.splice(r,1):n.push(s.domain);const a=i.collapsedDomains?{...i.collapsedDomains}:{COL:[],ROW:[]};a[s.dimension]=n,t.model.dispatch("UPDATE_PIVOT",{pivotId:o,pivot:{...i,collapsedDomains:a}})}function yp(e,t){const s=t.getPivotId(e);if(!s)throw new Cs(fs('There is no pivot with id "%s"',e));return s}function Ip(e){if(e.length%2!=0)throw new Cs(fs("Function PIVOT takes an even number of arguments."))}function wp(e,t,s){const o=[];if("SPREADSHEET"===t.type&&t.dataSet){const{sheetId:s,zone:i}=t.dataSet,n=Tt(i),r=e.getters.getRangeFromSheetXC(s,n);if(void 0===r||r.invalidXc||r.invalidSheetName)throw new ws;if(e.__originCellPosition&&r.sheetId===e.__originSheetId&&Vt(Zt(e.__originCellPosition),i))throw new Is;o.push(r)}for(const t of s)if(t.computedBy){const s=e.getters.getMeasureCompiledFormula(t);o.push(...s.dependencies.filter(e=>!e.invalidXc))}const i=e.__originCellPosition;i&&o.length&&(e.updateDependencies?.(i),e.addDependencies?.(i,o))}hp.add("date",lp).add("datetime",lp).add("integer",e=>`${bo(e,Oc)}`).add("boolean",e=>To(e)?"TRUE":"FALSE").add("char",e=>`"${Eo(e).replace(/"/g,'\\"')}"`).add("custom",e=>"string"==typeof e?`"${e}"`:String(e));const Ep=!0,Rp=[{value:!0,label:fs("A1 style (default)")},{value:!1,label:fs("R1C1 style")}],xp=[{value:!0,label:fs("Approximate match (default)")},{value:!1,label:fs("Exact match")}],Tp={description:fs("Returns a cell reference as a string. "),args:[as("row (number)",fs("The row number of the cell reference. ")),as("column (number)",fs("The column number (not name) of the cell reference. A is column number 1. ")),as("absolute_relative_mode (number, default=1)",fs("An indicator of whether the reference is row/column absolute."),[{value:1,label:fs("Absolute row and column (e.g. $A$1)")},{value:2,label:fs("Absolute row, relative column (e.g. A$1)")},{value:3,label:fs("Relative row, absolute column (e.g. $A1)")},{value:4,label:fs("Relative row and column (e.g. A1)")}]),as("use_a1_notation (boolean, default=TRUE)",fs("A boolean indicating whether to use A1 style notation or R1C1 style notation."),Rp),as("sheet (string, optional)",fs("A string indicating the name of the sheet into which the address points."))],compute:function(e,t,s={value:1},o={value:!0},i){const n=wo(e,this.locale),r=wo(t,this.locale);if(n<1)return new Cs(di(n));if(r<1)return new Cs(di(r));const a=wo(s,this.locale);if(![1,2,3,4].includes(a))return new Cs((l=4,c=a,fs("The function [[FUNCTION_NAME]] expects a number value between %s and %s inclusive, but receives %s.",1..toString(),l.toString(),c.toString())));var l,c;let h;if(To(o)){h=mt(r-1,n-1,{rowFixed:[1,2].includes(a),colFixed:[1,3].includes(a)})}else{h=([1,2].includes(a)?`R${n}`:`R[${n}]`)+([1,3].includes(a)?`C${r}`:`C[${r}]`)}return void 0!==i?sr(Eo(i),h):h},isExported:!0},Ap={description:fs("Column number of a specified cell."),args:[as("cell_reference (meta, range<meta>, default='this cell')",fs("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(void 0===e)return void 0===this.__originCellPosition?.col?new Cs(fs("In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.")):this.__originCellPosition.col+1;if(void 0===e[0][0])return new Cs(fs("The range is out of bounds."));if(e[0][0].value===bs.InvalidReference)return e[0][0];const t=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),e[0][0].value).zone.left;return 1===e.length?t+1:ko(e.length,1,(e,s)=>({value:t+e+1}))},isExported:!0},Dp={description:fs("Number of columns in a specified array or range."),args:[as("range (any, range<any>)",fs("The range whose column count will be returned."))],compute:function(e){const t=Xo(e);return void 0===t[0][0]?new Cs(fs("The range is out of bounds.")):t[0][0].value===bs.InvalidReference?t[0][0]:t.length},isExported:!0},_p={description:fs("Horizontal lookup"),args:[as("search_key (string, number, boolean)",fs("The value to search for. For example, 42, 'Cats', or I24.")),as("range (any, range)",fs("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")),as("index (number)",fs("The row index of the value to be returned, where the first row in range is numbered 1.")),as("is_sorted (boolean, default=true)",fs("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."),xp)],compute:function(e,t,s,o={value:Ep}){const i=Math.trunc(bo(s?.value,this.locale)),n=Xo(t);if(1>i||i>n[0].length)return new Cs(fs("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const r=(e,t)=>e[t][0].value,a=n[To(o.value)?qo(n,e,"nextSmaller","asc",n.length,r):Zo(n,e,"wildcard",n.length,r,this.lookupCaches)];return void 0===a?fo(e):a[i-1]},isExported:!0},Op={description:fs("Returns the content of a cell, specified by row and column offset."),args:[as("reference (any, range)",fs("The range of cells from which the values are returned.")),as("row (number, default=0)",fs("The index of the row to be returned from within the reference range of cells.")),as("column (number, default=0)",fs("The index of the column to be returned from within the reference range of cells."))],compute:function(e,t={value:0},s={value:0}){const o=Xo(e),i=bo(t.value,this.locale),n=bo(s.value,this.locale);return n<0||n-1>=o.length||i<0||i-1>=o[0].length?new Cs(fs("Index out of range.")):0===i&&0===n?o:0===i?[o[n-1]]:0===n?o.map(e=>[e[i-1]]):o[n-1][i-1]},isExported:!0},Fp={description:fs("Returns the content of a cell, specified by a string."),args:[as("reference (string)",fs("The range of cells from which the values are returned.")),as("use_a1_notation (boolean, default=TRUE)",fs("A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE)."),Rp)],compute:function(e,t={value:!0}){const s=e?.value?.toString();if(!s)return new ws(fs("Reference should be defined."));if(!To(t))return new Cs(fs("R1C1 notation is not supported."));const o=this.__originSheetId,i=this.__originCellPosition;i&&this.updateDependencies?.(i);const n=this.getters.getRangeFromSheetXC(o,s);if(void 0===n||n.invalidXc||n.invalidSheetName)return new ws;i&&this.addDependencies?.(i,[n]);const r=[];for(let e=n.zone.left;e<=n.zone.right;e++){const t=[];for(let s=n.zone.top;s<=n.zone.bottom;s++){const o={sheetId:n.sheetId,col:e,row:s};t.push(this.getters.getEvaluatedCell(o))}r.push(t)}return 1===r.length&&1===r[0].length?r[0][0]:r},isExported:!0},Pp={description:fs("Look up a value."),args:[as("search_key (string, number, boolean)",fs("The value to search for. For example, 42, 'Cats', or I24.")),as("search_array (any, range)",fs("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.")),as("result_range (any, range, optional)",fs("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,s){const o=Xo(t),i=Xo(s);let n=o.length,r=o[0].length;const a=r>=n,l=a?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,c=qo(o,e,"nextSmaller","asc",a?r:n,l);return-1===c||a&&void 0===o[0][c]||!a&&void 0===o[c][r-1]?fo(e):0===i[0].length?a?o[n-1][c]:o[c][r-1]:(n=i.length,r=i[0].length,1!==n&&1!==r?new Cs(fs("The result_range must be a single row or a single column.")):n>1?c>n-1?new Cs(fs("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",c+1)):i[c][0]:c>r-1?new Cs(fs("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",c+1)):i[0][c])},isExported:!0},Mp={description:fs("Position of item in range that matches value."),args:[as("search_key (string, number, boolean)",fs("The value to search for. For example, 42, 'Cats', or I24.")),as("range (any, range)",fs("The one-dimensional array to be searched.")),as("search_type (number, default=1)",fs("The search method is a number 1, 0 or -1 indicating which value to return. 1 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."),[{value:1,label:fs("Ascending order (default)")},{value:0,label:fs("Exact match")},{value:-1,label:fs("Descending order")}])],compute:function(e,t,s={value:1}){let o=bo(s,this.locale);const i=Xo(t),n=i.length,r=i[0].length;if(1!==n&&1!==r)return new Cs(fs("The range must be a single row or a single column."));let a=-1;const l=1===n?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,c=1===n?i[0].length:i.length;switch(o=Math.sign(o),o){case 1:a=qo(i,e,"nextSmaller","asc",c,l);break;case 0:a=Zo(i,e,"wildcard",c,l,this.lookupCaches);break;case-1:a=qo(i,e,"nextGreater","desc",c,l)}return 1===n&&void 0===i[0][a]||1!==n&&void 0===i[a]?fo(e):a+1},isExported:!0},Np={description:fs("Row number of a specified cell."),args:[as("cell_reference (meta, range<meta>, default='this cell')",fs("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(void 0===e)return void 0===this.__originCellPosition?.row?new Cs(fs("In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.")):this.__originCellPosition.row+1;if(void 0===e[0][0])return new Cs(fs("The range is out of bounds."));if(e[0][0].value===bs.InvalidReference)return e[0][0];const t=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),e[0][0].value).zone.top;return 1===e[0].length?t+1:ko(1,e[0].length,(e,s)=>({value:t+s+1}))},isExported:!0},Lp={description:fs("Number of rows in a specified array or range."),args:[as("range (any, range<any>)",fs("The range whose row count will be returned."))],compute:function(e){const t=Xo(e);return void 0===t[0][0]?new Cs(fs("The range is out of bounds.")):t[0][0].value===bs.InvalidReference?t[0][0]:t[0].length},isExported:!0},kp={description:fs("Vertical lookup."),args:[as("search_key (string, number, boolean)",fs("The value to search for. For example, 42, 'Cats', or I24.")),as("range (any, range)",fs("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")),as("index (number)",fs("The column index of the value to be returned, where the first column in range is numbered 1.")),as("is_sorted (boolean, default=true)",fs("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."),xp)],compute:function(e,t,s,o={value:Ep}){const i=Math.trunc(bo(s?.value,this.locale)),n=Xo(t);if(1>i||i>n.length)return new Cs(fs("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const r=(e,t)=>e[0][t].value,a=To(o.value)?qo(n,e,"nextSmaller","asc",n[0].length,r):Zo(n,e,"wildcard",n[0].length,r,this.lookupCaches),l=n[i-1][a];return void 0===l?fo(e):l},isExported:!0},Vp={0:"strict",1:"nextGreater","-1":"nextSmaller",2:"wildcard"},Up={description:fs("Search a range for a match and return the corresponding item from a second range."),args:[as("search_key (string,number,boolean)",fs("The value to search for.")),as("lookup_range (any, range)",fs("The range to consider for the search. Should be a single column or a single row.")),as("return_range (any, range)",fs("The range containing the return value. Should have the same dimensions as lookup_range.")),as("if_not_found (any, optional)",fs("If a valid match is not found, return this value.")),as("match_mode (any, default=0)",fs("Specifies how to match search_key with the items in lookup_range. "),[{value:0,label:fs("Exact match (default)")},{value:-1,label:fs("Exact match or next smaller item")},{value:1,label:fs("Exact match or next larger item")},{value:2,label:fs("Wildcard character match")}]),as("search_mode (any, default=1)",fs("Specifies the search mode to use. By default, a first to last search will be used."),[{value:1,label:fs("Search first to last (default)")},{value:-1,label:fs("Search last to first")},{value:2,label:fs("Binary search (sorted ascending order)")},{value:-2,label:fs("Binary search (sorted descending order)")}])],compute:function(e,t,s,o,i={value:0},n={value:1}){const r=Math.trunc(bo(i.value,this.locale)),a=Math.trunc(bo(n.value,this.locale)),l=Xo(t),c=Xo(s);if(1!==l.length&&1!==l[0].length)return new Cs(fs("lookup_range should be either a single row or single column."));if(![1,-1,2,-2].includes(a))return new Cs(fs("search_mode should be a value in [-1, 1, -2, 2]."));if(![-1,0,1,2].includes(r))return new Cs(fs("match_mode should be a value in [-1, 0, 1, 2]."));const h=1===l.length?"col":"row";if(2===r&&[-2,2].includes(a))return new Cs(fs("The search and match mode combination is not supported for XLOOKUP evaluation."));if("col"===h?c[0].length!==l[0].length:c.length!==l.length)return new Cs(fs("return_range should have the same dimensions as lookup_range."));const d="col"===h?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,u="col"===h?l[0].length:l.length,g=Vp[r],p=-1===a,m=2===a||-2===a?qo(l,e,g,2===a?"asc":"desc",u,d):Zo(l,e,g,u,d,this.lookupCaches,p);return-1!==m?"col"===h?c.map(e=>[e[m]]):[c[m]]:void 0===o?fo(e):[[o]]},isExported:!0},Hp={description:fs("Get the value from a pivot."),args:[as("pivot_id (number,string)",fs("ID of the pivot.")),as("measure_name (string)",fs("Name of the measure.")),as("domain_field_name (string,repeating)",fs("Field name.")),as("domain_value (number,string,boolean,repeating)",fs("Value."))],compute:function(e,t,...s){const o=Eo(e),i=Eo(t),n=yp(o,this.getters);!function(e,t,s){const{measures:o}=s.getPivotCoreDefinition(e);if(!o.find(e=>e.id===t)){const e=`(${o.map(e=>e.id).join(", ")})`;throw new Cs(fs("The argument %s is not a valid measure. Here are the measures: %s",t,e))}}(n,i,this.getters),Ip(s);const r=this.getters.getPivot(n),a=this.getters.getPivotCoreDefinition(n);wp(this,a,a.measures.filter(e=>e.id===i)),r.init({reload:r.needsReevaluation});const l=r.assertIsValid({throwOnError:!1});if(l)return l;if(!r.areDomainArgsFieldsValid(s)){const e=fs("Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.",`=PIVOT(${o})`);return{value:bs.GenericError,message:fs("Dimensions don't match the pivot definition")+". "+e}}const c=r.parseArgsToPivotDomain(s);return this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(n)?.trackValue(i,c),r.getPivotCellValueAndFormat(i,c)}},zp={description:fs("Get the header of a pivot."),args:[as("pivot_id (number,string)",fs("ID of the pivot.")),as("domain_field_name (string,repeating)",fs("Field name.")),as("domain_value (number,string,value,repeating)",fs("Value."))],compute:function(e,...t){const s=Eo(e),o=yp(s,this.getters);Ip(t);const i=this.getters.getPivot(o);wp(this,this.getters.getPivotCoreDefinition(o),[]),i.init({reload:i.needsReevaluation});const n=i.assertIsValid({throwOnError:!1});if(n)return n;if(!i.areDomainArgsFieldsValid(t)){const e=fs("Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.",`=PIVOT(${s})`);return{value:bs.GenericError,message:fs("Dimensions don't match the pivot definition")+". "+e}}const r=i.parseArgsToPivotDomain(t);this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(o)?.trackHeader(r);const a=r.at(-1);if("measure"===a?.field)return i.getPivotMeasureValue(Eo(a.value),r);const{value:l,format:c}=i.getPivotHeaderValueAndFormat(r);return{value:l,format:a&&"measure"!==a.field&&"false"!==a.value?c:void 0}}},Bp={description:fs("Get a pivot table."),args:[as("pivot_id (string)",fs("ID of the pivot.")),as("row_count (number, optional)",fs("number of rows")),as("include_total (boolean, default=TRUE)",fs("Whether to include total/sub-totals or not.")),as("include_column_titles (boolean, default=TRUE)",fs("Whether to include the column titles or not.")),as("column_count (number, optional)",fs("number of columns")),as("include_measure_titles (boolean, default=TRUE)",fs("Whether to include the measure titles row or not."))],compute:function(e,t={value:1e4},s={value:!0},o={value:!0},i={value:Number.MAX_VALUE},n={value:!0}){const r=Eo(e),a=bo(t,this.locale);if(a<0)return new Cs(fs("The number of rows must be positive."));const l=bo(i,this.locale);if(l<0)return new Cs(fs("The number of columns must be positive."));const c={displayColumnHeaders:To(o),displayTotals:To(s),displayMeasuresRow:To(n)},h=yp(r,this.getters),d=this.getters.getPivot(h),u=this.getters.getPivotCoreDefinition(h);wp(this,u,u.measures),d.init({reload:d.needsReevaluation});const g=d.assertIsValid({throwOnError:!1});if(g)return g;const p=d.getCollapsedTableStructure();if(p.numberOfCells>Q)return new Cs(function(e,t){const s=pn(e,{format:"0,00",locale:t});return fs("Oops—this pivot table is quite large (%s cells). Try simplifying it using the side panel.",s)}(p.numberOfCells,this.locale));const m=p.getPivotCells(c);let f=0;c.displayColumnHeaders&&(f=p.columns.length-1),c.displayMeasuresRow&&f++;const v=this.getters.getPivotName(h),b=Math.min(f+a,m[0].length);if(0===b)return[[{value:v}]];const S=Math.min(1+l,m.length),C=[];for(const e of ge(0,S)){C[e]=[];for(const t of ge(0,b)){const s=m[e][t];switch(s.type){case"EMPTY":C[e].push({value:""});break;case"HEADER":const t=d.getPivotHeaderValueAndFormat(s.domain);C[e].push(up(s.domain,t));break;case"MEASURE_HEADER":C[e].push(d.getPivotMeasureValue(s.measure,s.domain));break;case"VALUE":C[e].push(d.getPivotCellValueAndFormat(s.measure,s.domain))}}}return(c.displayColumnHeaders||c.displayMeasuresRow)&&(C[0][0]={value:v}),C}},Gp={description:fs("Returns a range reference shifted by a specified number of rows and columns from a starting cell reference."),args:[as("cell_reference (meta, range<meta>)",fs("The starting point from which to count the offset rows and columns.")),as("offset_rows (number)",fs("The number of rows to offset by.")),as("offset_columns (number)",fs("The number of columns to offset by.")),as("height (number, default='height of cell_reference')",fs("The number of rows of the range to return starting at the offset target.")),as("width (number, default='width of cell_reference')",fs("The number of columns of the range to return starting at the offset target."))],compute:function(e,t,s,o,i){if(mo(e[0][0].value))return e[0][0];const n=e[0][0].value;if(!n)return new Cs("In this context, the function OFFSET needs to have a cell or range in parameter.");const r=wt(n);let a=e[0].length,l=e.length;if(o){const e=bo(o,this.locale);if(e<1)return new Cs(fs("Height value is %(_height)s. It should be greater than or equal to 1.",{_height:e}));a=e}if(i){const e=bo(i,this.locale);if(e<1)return new Cs(fs("Width value is %(_width)s. It should be greater than or equal to 1.",{_width:e}));l=e}const{sheetName:c}=tr(n),h=c&&this.getters.getSheetIdByName(c)||this.getters.getActiveSheetId(),d=bo(t,this.locale),u=bo(s,this.locale),g=this.__originCellPosition;g&&this.updateDependencies?.(g);const p=r.left+u,m=r.top+d;if(p<0||m<0)return new ws(fs("OFFSET evaluates to an out of bounds range."));const f={left:p,top:m,right:p+l-1,bottom:m+a-1},v=this.getters.getRangeFromZone(h,f);return v.invalidXc||v.invalidSheetName?new ws:(g&&this.addDependencies?.(g,[v]),ko(l,a,(e,t)=>this.getters.getEvaluatedCell({sheetId:h,col:p+e,row:m+t})))}};var Wp=Object.freeze({__proto__:null,ADDRESS:Tp,COLUMN:Ap,COLUMNS:Dp,HLOOKUP:_p,INDEX:Op,INDIRECT:Fp,LOOKUP:Pp,MATCH:Mp,OFFSET:Gp,PIVOT:Bp,PIVOT_HEADER:zp,PIVOT_VALUE:Hp,ROW:Np,ROWS:Lp,VLOOKUP:kp,XLOOKUP:Up});const $p={description:fs("Sum of two numbers."),args:[as("value1 (number)",fs("The first addend.")),as("value2 (number)",fs("The second addend."))],compute:function(e,t){return{value:bo(e,this.locale)+bo(t,this.locale),format:e?.format||t?.format}}},qp={description:fs("Concatenation of two values."),args:[as("value1 (string)",fs("The value to which value2 will be appended.")),as("value2 (string)",fs("The value to append to value1."))],compute:function(e,t){return Eo(e)+Eo(t)},isExported:!0},Zp={description:fs("One number divided by another."),args:[as("dividend (number)",fs("The number to be divided.")),as("divisor (number)",fs("The number to divide by."))],compute:function(e,t){const s=bo(t,this.locale);return 0===s?new Ts(fs("The divisor must be different from zero.")):{value:bo(e,this.locale)/s,format:e?.format||t?.format}}};function jp(e){return void 0===e||null===e.value}const Yp={number:0,string:"",boolean:!1};function Xp(e,t,s=2e-16){return Math.abs(e-t)<s}const Kp={description:fs("Equal."),args:[as("value1 (string, number, boolean)",fs("The first value.")),as("value2 (string, number, boolean)",fs("The value to test against value1 for equality."))],compute:function(e,t){if(mo(e?.value))return e;if(mo(t?.value))return t;let s=jp(e)?Yp[typeof t?.value]:e?.value,o=jp(t)?Yp[typeof e?.value]:t?.value;return"string"==typeof s&&(s=s.toUpperCase()),"string"==typeof o&&(o=o.toUpperCase()),"number"==typeof s&&"number"==typeof o?{value:Xp(s,o)}:{value:s===o}}};function Jp(e,t,s){if(mo(e?.value))return e;if(mo(t?.value))return t;let o=jp(e)?Yp[typeof t?.value]:e?.value,i=jp(t)?Yp[typeof e?.value]:t?.value;"number"!=typeof o&&(o=Eo(o).toUpperCase()),"number"!=typeof i&&(i=Eo(i).toUpperCase());const n=typeof o,r=typeof i;return"string"===n&&"number"===r?{value:!0}:"string"===r&&"number"===n?{value:!1}:{value:s(o,i)}}const Qp={description:fs("Strictly greater than."),args:[as("value1 (number, string, boolean)",fs("The value to test as being greater than value2.")),as("value2 (number, string, boolean)",fs("The second value."))],compute:function(e,t){return Jp(e,t,(e,t)=>"number"==typeof e&&"number"==typeof t?!Xp(e,t)&&e>t:e>t)}},em={description:fs("Greater than or equal to."),args:[as("value1 (number, string, boolean)",fs("The value to test as being greater than or equal to value2.")),as("value2 (number, string, boolean)",fs("The second value."))],compute:function(e,t){return Jp(e,t,(e,t)=>"number"==typeof e&&"number"==typeof t?Xp(e,t)||e>t:e>=t)}},tm={description:fs("Less than."),args:[as("value1 (number, string, boolean)",fs("The value to test as being less than value2.")),as("value2 (number, string, boolean)",fs("The second value."))],compute:function(e,t){const s=em.compute.bind(this)(e,t);return mo(s.value)?s:{value:!s.value}}},sm={description:fs("Less than or equal to."),args:[as("value1 (number, string, boolean)",fs("The value to test as being less than or equal to value2.")),as("value2 (number, string, boolean)",fs("The second value."))],compute:function(e,t){const s=Qp.compute.bind(this)(e,t);return mo(s.value)?s:{value:!s.value}}},om={description:fs("Difference of two numbers."),args:[as("value1 (number)",fs("The minuend, or number to be subtracted from.")),as("value2 (number)",fs("The subtrahend, or number to subtract from value1."))],compute:function(e,t){return{value:bo(e,this.locale)-bo(t,this.locale),format:e?.format||t?.format}}},im={description:fs("Product of two numbers"),args:[as("factor1 (number)",fs("The first multiplicand.")),as("factor2 (number)",fs("The second multiplicand."))],compute:function(e,t){return{value:bo(e,this.locale)*bo(t,this.locale),format:e?.format||t?.format}}},nm={description:fs("Not equal."),args:[as("value1 (string, number, boolean)",fs("The first value.")),as("value2 (string, number, boolean)",fs("The value to test against value1 for inequality."))],compute:function(e,t){const s=Kp.compute.bind(this)(e,t);return mo(s.value)?s:{value:!s.value}}},rm={description:fs("A number raised to a power."),args:[as("base (number)",fs("The number to raise to the exponent power.")),as("exponent (number)",fs("The exponent to raise base to."))],compute:function(e,t){return ma.compute.bind(this)(e,t)}},am={description:fs("A number with the sign reversed."),args:[as("value (number)",fs("The number to have its sign reversed. Equivalently, the number to multiply by -1."))],compute:function(e){return{value:-bo(e,this.locale),format:e?.format}}},lm={description:fs("Value interpreted as a percentage."),args:[as("percentage (number)",fs("The value to interpret as a percentage."))],compute:function(e){return bo(e,this.locale)/100}},cm={description:fs("A specified number, unchanged."),args:[as("value (any)",fs("The number to return."))],compute:function(e={value:null}){return e}};var hm=Object.freeze({__proto__:null,ADD:$p,CONCAT:qp,DIVIDE:Zp,EQ:Kp,GT:Qp,GTE:em,LT:tm,LTE:sm,MINUS:om,MULTIPLY:im,NE:nm,POW:rm,UMINUS:am,UNARY_PERCENT:lm,UPLUS:cm});const dm=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),um={transform:e=>e,inverseTransform:e=>e},gm=1e-10,pm=.0254,mm=pm/72,fm=.3048,vm=.9144,bm=1609.34,Sm=1852,Cm=946073047258e4,ym={g:{...um,category:"weight"},u:{...dm(166053e-29),category:"weight"},grain:{...dm(.0647989),category:"weight"},ozm:{...dm(28.3495),category:"weight"},lbm:{...dm(453.592),category:"weight"},stone:{...dm(6350.29),category:"weight"},sg:{...dm(14593.90294),category:"weight"},cwt:{...dm(45359.237),category:"weight"},uk_cwt:{...dm(50802.3),category:"weight"},ton:{...dm(907184.74),category:"weight"},uk_ton:{...dm(1016046.9),category:"weight"},m:{...um,category:"distance"},km:{...dm(1e3),category:"distance"},ang:{...dm(gm),category:"distance"},Picapt:{...dm(mm),category:"distance"},pica:{...dm(pm/6),category:"distance"},in:{...dm(pm),category:"distance"},ft:{...dm(fm),category:"distance"},yd:{...dm(vm),category:"distance"},ell:{...dm(1.143),category:"distance"},mi:{...dm(bm),category:"distance"},survey_mi:{...dm(1609.34),category:"distance"},Nmi:{...dm(Sm),category:"distance"},ly:{...dm(Cm),category:"distance"},parsec:{...dm(0x6da012f95c9fd0),category:"distance"},sec:{...um,category:"time"},min:{...dm(60),category:"time"},hr:{...dm(3600),category:"time"},day:{...dm(86400),category:"time"},yr:{...dm(31556952),category:"time"},Pa:{...um,category:"pressure"},bar:{...dm(1e5),category:"pressure"},mmHg:{...dm(133.322),category:"pressure"},Torr:{...dm(133.322),category:"pressure"},psi:{...dm(6894.76),category:"pressure"},atm:{...dm(101325),category:"pressure"},N:{...um,category:"force"},dyn:{...dm(1e-5),category:"force"},pond:{...dm(.00980665),category:"force"},lbf:{...dm(4.44822),category:"force"},J:{...um,category:"energy"},eV:{...dm(160218e-24),category:"energy"},e:{...dm(1e-7),category:"energy"},flb:{...dm(1.3558179483),category:"energy"},c:{...dm(4.184),category:"energy"},cal:{...dm(4.1868),category:"energy"},BTU:{...dm(1055.06),category:"energy"},Wh:{...dm(3600),category:"energy"},HPh:{...dm(2684520),category:"energy"},W:{...um,category:"power"},PS:{...dm(735.499),category:"power"},HP:{...dm(745.7),category:"power"},T:{...um,category:"magnetism"},ga:{...dm(1e-4),category:"magnetism"},K:{...um,category:"temperature"},C:{transform:e=>e+273.15,inverseTransform:e=>e-273.15,category:"temperature"},F:{transform:e=>5*(e-32)/9+273.15,inverseTransform:e=>9*(e-273.15)/5+32,category:"temperature"},Rank:{...dm(5/9),category:"temperature"},Reau:{transform:e=>1.25*e+273.15,inverseTransform:e=>(e-273.15)/1.25,category:"temperature"},"m^3":{...um,category:"volume",order:3},"ang^3":{...dm(Math.pow(gm,3)),category:"volume",order:3},"Picapt^3":{...dm(Math.pow(mm,3)),category:"volume",order:3},tsp:{...dm(492892e-11),category:"volume"},tspm:{...dm(5e-6),category:"volume"},tbs:{...dm(14786764825785619e-21),category:"volume"},"in^3":{...dm(Math.pow(pm,3)),category:"volume",order:3},oz:{...dm(295735295625e-16),category:"volume"},cup:{...dm(237e-6),category:"volume"},pt:{...dm(.0004731765),category:"volume"},uk_pt:{...dm(568261e-9),category:"volume"},qt:{...dm(.0009463529),category:"volume"},l:{...dm(.001),category:"volume"},uk_qt:{...dm(.0011365225),category:"volume"},gal:{...dm(.0037854118),category:"volume"},uk_gal:{...dm(.00454609),category:"volume"},"ft^3":{...dm(Math.pow(fm,3)),category:"volume",order:3},bushel:{...dm(.0352390704),category:"volume"},barrel:{...dm(.158987295),category:"volume"},"yd^3":{...dm(Math.pow(vm,3)),category:"volume",order:3},MTON:{...dm(1.13267386368),category:"volume"},GRT:{...dm(2.83168),category:"volume"},"mi^3":{...dm(Math.pow(bm,3)),category:"volume",order:3},"Nmi^3":{...dm(Math.pow(Sm,3)),category:"volume",order:3},"ly^3":{...dm(Math.pow(Cm,3)),category:"volume",order:3},"m^2":{...um,category:"area",order:2},"ang^2":{...dm(Math.pow(gm,2)),category:"area",order:2},"Picapt^2":{...dm(Math.pow(mm,2)),category:"area",order:2},"in^2":{...dm(Math.pow(pm,2)),category:"area",order:2},"ft^2":{...dm(Math.pow(fm,2)),category:"area",order:2},"yd^2":{...dm(Math.pow(vm,2)),category:"area",order:2},ar:{...dm(100),category:"area"},Morgen:{...dm(2500),category:"area"},uk_acre:{...dm(4046.8564224),category:"area"},us_acre:{...dm(4046.8726098743),category:"area"},ha:{...dm(1e4),category:"area"},"mi^2":{...dm(Math.pow(bm,2)),category:"area",order:2},"Nmi^2":{...dm(Math.pow(Sm,2)),category:"area",order:2},"ly^2":{...dm(Math.pow(Cm,2)),category:"area",order:2},bit:{...um,category:"information"},byte:{...dm(8),category:"information"},"m/s":{...um,category:"speed"},"m/hr":{...dm(1/3600),category:"speed"},"km/hr":{...dm(1/3.6),category:"speed"},mph:{...dm(.44704),category:"speed"},kn:{...dm(.5144444444),category:"speed"},admkn:{...dm(.5147733333),category:"speed"}},Im={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"},wm={"":1,Y:1e24,Z:1e21,E:1e18,P:1e15,T:1e12,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:Math.pow(2,80),Zi:Math.pow(2,70),Ei:Math.pow(2,60),Pi:Math.pow(2,50),Ti:Math.pow(2,40),Gi:Math.pow(2,30),Mi:Math.pow(2,20),ki:Math.pow(2,10)},Em={weight:fs("Weight"),distance:fs("Distance"),time:fs("Time"),pressure:fs("Pressure"),force:fs("Force"),energy:fs("Energy"),power:fs("Power"),magnetism:fs("Magnetism"),temperature:fs("Temperature"),volume:fs("Volume"),area:fs("Area"),information:fs("Information"),speed:fs("Speed")},Rm=Object.entries(ym).map(([e,t])=>({value:e,label:xm(t.category)}));function xm(e){return Em[e]??""}function Tm(e){for(const[t,s]of Object.entries(wm)){if(t&&!e.startsWith(t))continue;const o=e.slice(t.length);let i=ym[o];if(!i&&Im[o]&&(i=ym[Im[o]]),i)return{...i,factor:i.order?Math.pow(s,i.order):s}}}const Am={description:fs("Converts a numeric value to a different unit of measure."),args:[as("value (number)",fs("the numeric value in start_unit to convert to end_unit")),as("start_unit (string)",fs("The starting unit, the unit currently assigned to value"),Rm),as("end_unit (string)",fs("The unit of measure into which to convert value"),Rm)],compute:function(e,t,s){const o=bo(e,this.locale),i=Eo(t),n=Eo(s),r=Tm(i),a=Tm(n);return r?a?r.category!==a.category?{value:bs.GenericError,message:fs("Incompatible units of measure ('%s' vs '%s')",xm(r.category),xm(a.category))}:{value:a.inverseTransform(r.factor*r.transform(o))/a.factor,format:e?.format}:{value:bs.GenericError,message:fs("Invalid units of measure ('%s')",n)}:{value:bs.GenericError,message:fs("Invalid units of measure ('%s')",i)}},isExported:!0};var Dm=Object.freeze({__proto__:null,CONVERT:Am});const _m=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,Om=[{value:0,label:fs("Case-sensitive (default)")},{value:1,label:fs("Case-insensitive")}],Fm=[{value:0,label:fs("Don't match to end (default)")},{value:1,label:fs("Match to end")}],Pm={description:fs("Gets character associated with number."),args:[as("table_number (number)",fs("The number of the character to look up from the current Unicode table in decimal format."))],compute:function(e){const t=Math.trunc(bo(e,this.locale));return t<1?new Cs(fs("The table_number (%s) is out of range.",t)):String.fromCharCode(t)},isExported:!0},Mm={description:fs("Remove non-printable characters from a piece of text."),args:[as("text (string)",fs("The text whose non-printable characters are to be removed."))],compute:function(e){const t=Eo(e);let s="";for(const e of t)e&&e.charCodeAt(0)>31&&(s+=e);return s},isExported:!0},Nm={description:fs("Appends strings to one another."),args:[as("string1 (string, range<string>)",fs("The initial string.")),as("string2 (string, range<string>, repeating)",fs("More strings to append in sequence."))],compute:function(...e){return Mo(e,(e,t)=>e+Eo(t),"")},isExported:!0},Lm={description:fs("Tests whether two strings are identical."),args:[as("string1 (string)",fs("The first string to compare.")),as("string2 (string)",fs("The second string to compare."))],compute:function(e,t){return Eo(e)===Eo(t)},isExported:!0},km={description:fs("First position of string found in text, case-sensitive."),args:[as("search_for (string)",fs("The string to look for within text_to_search.")),as("text_to_search (string)",fs("The text to search for the first occurrence of search_for.")),as("starting_at (number, default=1)",fs("The character within text_to_search at which to start the search."))],compute:function(e,t,s={value:1}){const o=Eo(e),i=Eo(t),n=bo(s,this.locale);if(""===i)return new Cs(fs("The text_to_search must be non-empty."));if(n<1)return new Cs(fs("The starting_at (%s) must be greater than or equal to 1.",n));const r=i.indexOf(o,n-1);return-1===r?new Cs(fs("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o,i)):r+1},isExported:!0},Vm={description:fs("Concatenates elements of arrays with delimiter."),args:[as("delimiter (string)",fs("The character or string to place between each concatenated value.")),as("value_or_array1 (string, range<string>)",fs("The value or values to be appended using delimiter.")),as("value_or_array2 (string, range<string>, repeating)",fs("More values to be appended using delimiter."))],compute:function(e,...t){const s=Eo(e);return Mo(t,(e,t)=>(e?e+s:"")+Eo(t),"")}},Um={description:fs("Substring from beginning of specified string."),args:[as("text (string)",fs("The string from which the left portion will be returned.")),as("number_of_characters (number, optional)",fs("The number of characters to return from the left side of string."))],compute:function(e,...t){const s=t.length?bo(t[0],this.locale):1;return s<0?new Cs(fs("The number_of_characters (%s) must be positive or null.",s)):Eo(e).substring(0,s)},isExported:!0},Hm={description:fs("Length of a string."),args:[as("text (string)",fs("The string whose length will be returned."))],compute:function(e){return Eo(e).length},isExported:!0},zm={description:fs("Converts a specified string to lowercase."),args:[as("text (string)",fs("The string to convert to lowercase."))],compute:function(e){return Eo(e).toLowerCase()},isExported:!0},Bm={description:fs("A segment of a string."),args:[as("text (string)",fs("The string to extract a segment from.")),as("starting_at (number)",fs("The index from the left of string from which to begin extracting. The first character in string has the index 1.")),as("extract_length (number)",fs("The length of the segment to extract."))],compute:function(e,t,s){const o=Eo(e),i=bo(t,this.locale),n=bo(s,this.locale);return i<1?new Cs(fs("The starting_at argument (%s) must be positive greater than one.",i.toString())):n<0?new Cs(fs("The extract_length argument (%s) must be positive or null.",n)):o.slice(i-1,i+n-1)},isExported:!0},Gm={description:fs("Capitalizes each word in a specified string."),args:[as("text_to_capitalize (string)",fs("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 Eo(e).replace(_m,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},Wm={description:fs("Extract text from a string based on the supplied regular expression."),args:[as("text (string)",fs("The string on which you want to extract text.")),as("pattern (string)",fs("The regular expression pattern to match against the text.")),as("return_mode (number, default=0)",fs("0 = first match, 1 = all matches as an array, 2 = capturing groups from the first match as an array."),[{value:0,label:fs("First match")},{value:1,label:fs("All matches")},{value:2,label:fs("Capture groups of first match")}]),as("case_sensitivity (number, default=0)",fs("Whether the match is case-sensitive."),[{value:0,label:fs("Case-sensitive")},{value:1,label:fs("Case-insensitive")}])],compute:function(e,t,s={value:0},o={value:0}){const i=Eo(e),n=Eo(t),r=bo(s,this.locale),a=bo(o,this.locale);if(""===i||""===n)return{value:""};if(r<0||r>2)return new Cs(fs("The return_mode (%s) must be 0, 1 or 2.",r));if(0!==a&&1!==a)return new Cs(fs("The case_sensitivity (%s) must be 0 or 1.",a));const l=new RegExp(n,1===a?"gi":"g"),c=[...i.matchAll(l)];return 0===c.length?{value:bs.NotAvailable,message:fs("No matches found.")}:0===r?c[0][0]:1===r?c.map(e=>[e[0]]):c[0].length<2?new Cs(fs("No capturing groups found.")):c[0].slice(1).map(e=>[e])},isExported:!0},$m={description:fs("Replaces part of a text string with different text."),args:[as("text (string)",fs("The text, a part of which will be replaced.")),as("position (number)",fs("The position where the replacement will begin (starting from 1).")),as("length (number)",fs("The number of characters in the text to be replaced.")),as("new_text (string)",fs("The text which will be inserted into the original text."))],compute:function(e,t,s,o){const i=bo(t,this.locale);if(i<1)return new Cs(fs("The position (%s) must be greater than or equal to 1.",i));const n=Eo(e),r=bo(s,this.locale),a=Eo(o);return n.substring(0,i-1)+a+n.substring(i-1+r)},isExported:!0},qm={description:fs("A substring from the end of a specified string."),args:[as("text (string)",fs("The string from which the right portion will be returned.")),as("number_of_characters (number, optional)",fs("The number of characters to return from the right side of string."))],compute:function(e,...t){const s=t.length?bo(t[0],this.locale):1;if(s<0)return new Cs(fs("The number_of_characters (%s) must be positive or null.",s));const o=Eo(e),i=o.length;return o.substring(i-s,i)},isExported:!0},Zm={description:fs("First position of string found in text, ignoring case."),args:[as("search_for (string)",fs("The string to look for within text_to_search.")),as("text_to_search (string)",fs("The text to search for the first occurrence of search_for.")),as("starting_at (number, default=1)",fs("The character within text_to_search at which to start the search."))],compute:function(e,t,s={value:1}){const o=Eo(e).toLowerCase(),i=Eo(t).toLowerCase(),n=bo(s,this.locale);if(""===i)return{value:bs.GenericError,message:fs("The text_to_search must be non-empty.")};if(n<1)return{value:bs.GenericError,message:fs("The starting_at (%s) must be greater than or equal to 1.",n)};const r=i.indexOf(o,n-1);return-1===r?{value:bs.GenericError,message:fs("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o,i)}:{value:r+1}},isExported:!0},jm=!0,Ym=!0,Xm={description:fs("Split text by specific character delimiter(s)."),args:[as("text (string)",fs("The text to divide.")),as("delimiter (string)",fs("The character or characters to use to split text.")),as("split_by_each (boolean, default=true})",fs("Whether or not to divide text around each character contained in delimiter.")),as("remove_empty_text (boolean, default=true)",fs("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,s={value:jm},o={value:Ym}){const i=Eo(e),n=re(Eo(t)),r=To(s),a=To(o);if(n.length<=0)return new Cs(fs("The delimiter (%s) must be not be empty.",n));const l=r?new RegExp(`[${n}]`,"g"):new RegExp(n,"g");let c=i.split(l);return a&&(c=c.filter(e=>""!==e)),Uo([c])},isExported:!1},Km={description:fs("Replaces existing text with new text in a string."),args:[as("text_to_search (string)",fs("The text within which to search and replace.")),as("search_for (string)",fs("The string to search for within text_to_search.")),as("replace_with (string)",fs("The string that will replace search_for.")),as("occurrence_number (number, optional)",fs("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,s,o){const i=bo(o,this.locale);if(i<0)return new Cs(fs("The occurrenceNumber (%s) must be positive or null.",i));const n=Eo(e),r=Eo(t);if(""===r)return n;const a=Eo(s),l=new RegExp(re(r),"g");if(0===i)return n.replace(l,a);let c=0;return n.replace(l,e=>++c===i?a:e)},isExported:!0},Jm={description:fs("Combines text from multiple strings and/or arrays."),args:[as("delimiter (string)",fs(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")),as("ignore_empty (boolean)",fs("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result."),[{value:!0,label:fs("Ignore empty cells")},{value:!1,label:fs("Include empty cells (default)")}]),as("text1 (string, range<string>)",fs("Any text item. This could be a string, or an array of strings in a range.")),as("text2 (string, range<string>, repeating)",fs("Additional text item(s)."))],compute:function(e,t={value:true},...s){const o=Eo(e),i=To(t);let n=0;return Mo(s,(e,t)=>i&&""===Eo(t)?e:(n++?e+o:"")+Eo(t),"")},isExported:!0},Qm=!1,ef={description:fs("Splits text into rows or columns using specified column and row delimiters."),args:[as("text (string)",fs("The text to split.")),as("col_delimiter (string, range<string>)",fs("Character or string to split columns by.")),as("row_delimiter (string, range<string>, optional)",fs("Character or string to split rows by.")),as("ignore_empty (boolean, default=false)",fs("Whether to ignore empty cells."),[{value:!1,label:fs("Include empty cells (default)")},{value:!0,label:fs("Ignore empty cells")}]),as("match_mode (number, default=0)",fs("Searches the text for a delimiter match. By default, a case-sensitive match is done."),Om),as(`pad_with (string, default="${bs.NotAvailable}")`,fs("The value to use for padding empty cells."))],compute:function(e,t,s,o={value:Qm},i={value:0},n=new Es){const r=Eo(e);if(r.length<=0)return new Cs(fs("No text to split."));if(void 0===t&&void 0===s)return new Cs(fs("At least one delimiter must be provided."));const a=Xo(t).flat().map(e=>re(Eo(e))),l=Xo(s).flat().map(e=>re(Eo(e)));if(a.some(e=>""===e)||l.some(e=>""===e))return new Cs(fs("The delimiters cannot be empty values."));const c=To(o),h=bo(i,this.locale);if(![0,1].includes(h))return new Cs(fs("match_mode should be a value of 0 or 1."));const d=[],u=1===h?"gi":"g",g=l.filter(e=>!a.includes(e));let p=g.length?r.split(new RegExp(g.join("|"),u)):[r];c&&(p=p.filter(e=>""!==e));const m=new RegExp(a.join("|"),u);for(const e of p){let t=a.length?e.split(m):[e];c&&(t=t.filter(e=>""!==e)),d.push(t.map(e=>({value:e})))}const f=Math.max(...d.map(e=>e.length));for(const e of d)for(;e.length<f;)e.push(n);return Uo(d)},isExported:!0},tf={description:fs("Removes space characters."),args:[as("text (string)",fs("The text or reference to a cell containing text to be trimmed."))],compute:function(e){return Eo(e).split("\n").map(e=>e.replace(/\s+/g," ").trim()).join("\n")},isExported:!0},sf={description:fs("Converts a specified string to uppercase."),args:[as("text (string)",fs("The string to convert to uppercase."))],compute:function(e){return Eo(e).toUpperCase()},isExported:!0},of={description:fs("Converts a number to text according to a specified format."),args:[as("number (number)",fs("The number, date or time to format.")),as("format (string)",fs('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 pn(bo(e,this.locale),{format:Eo(t),locale:this.locale})},isExported:!0},nf={description:fs("Converts a string to a numeric value."),args:[as("value (number)",fs("the string to be converted"))],compute:function(e){return bo(e,this.locale)},isExported:!0},rf={description:fs("Returns text that occurs after a given substring or delimiter."),args:[as("text (string)",fs("The source text.")),as("delimiter (string)",fs("The substring after which text will be returned.")),as("instance_num (number, default=1)",fs("The desired instance of the delimiter after which we extract the text. A negative number searches from the end.")),as("match_mode (number, default=0)",fs("Searches the text for a delimiter match. By default, a case-sensitive match is done."),Om),as("match_end (number, default=0))",fs("Whether to treat the end of text as a delimiter."),Fm),as(`if_not_found (string, default="${bs.NotAvailable}")`,fs("Value to return if the delimiter is not found."))],compute:function(e,t,s={value:1},o={value:0},i={value:0},n=new Es){const r=Eo(e),a=bo(s,this.locale),l=bo(o,this.locale),c=bo(i,this.locale);if(0===a)return new Cs(fs("The instance_num (%s) must not be zero.",a));if(0!==l&&1!==l)return new Cs(fs("match_mode should have a value of 0 or 1."));if(0!==c&&1!==c)return new Cs(fs("match_end should have a value of 0 or 1."));const h=Eo(t);if(""===h)return Math.sign(a)>0?{value:r}:{value:""};const d=1===l?"gi":"g",u=re(h),g=new RegExp(u,d);let p=[...r.matchAll(g)].map(e=>e.index+u.length);if(a<0&&(p=p.reverse()),c&&Math.abs(a)===p.length+1)return Math.sign(a)>0?{value:""}:{value:r};const m=p[Math.abs(a)-1];return void 0===m?n:{value:r.substring(m)}},isExported:!0},af={description:fs("Returns text that occurs before a given substring or delimiter."),args:[as("text (string)",fs("The source text.")),as("delimiter (string)",fs("The substring after which text will be returned.")),as("instance_num (number, default=1)",fs("The desired instance of the delimiter before which we extract the text. A negative number searches from the end.")),as("match_mode (number, default=0)",fs("Searches the text for a delimiter match. By default, a case-sensitive match is done."),Om),as("match_end (number, default=0))",fs("Whether to match a delimiter against the end of the text."),Fm),as(`if_not_found (string, default="${bs.NotAvailable}")`,fs("Value to return if the delimiter is not found."))],compute:function(e,t,s={value:1},o={value:0},i={value:0},n=new Es){const r=Eo(e),a=bo(s,this.locale),l=bo(o,this.locale),c=bo(i,this.locale);if(0===a)return new Cs(fs("The instance_num (%s) must not be zero.",a));if(0!==l&&1!==l)return new Cs(fs("match_mode should have a value of 0 or 1."));if(0!==c&&1!==c)return new Cs(fs("match_end should have a value of 0 or 1."));const h=Eo(t);if(""===h)return Math.sign(a)>0?{value:""}:{value:r};const d=1===l?"gi":"g",u=re(h),g=new RegExp(u,d);let p=[...r.matchAll(g)].map(e=>e.index+u.length);if(a<0&&(p=p.reverse()),c&&Math.abs(a)===p.length+1)return Math.sign(a)>0?{value:r}:{value:""};const m=p[Math.abs(a)-1];return void 0===m?n:{value:r.substring(0,m-h.length)}},isExported:!0};var lf=Object.freeze({__proto__:null,CHAR:Pm,CLEAN:Mm,CONCATENATE:Nm,EXACT:Lm,FIND:km,JOIN:Vm,LEFT:Um,LEN:Hm,LOWER:zm,MID:Bm,PROPER:Gm,REGEXEXTRACT:Wm,REPLACE:$m,RIGHT:qm,SEARCH:Zm,SPLIT:Xm,SUBSTITUTE:Km,TEXT:of,TEXTAFTER:rf,TEXTBEFORE:af,TEXTJOIN:Jm,TEXTSPLIT:ef,TRIM:tf,UPPER:sf,VALUE:nf});const cf={description:fs("Creates a hyperlink in a cell."),args:[as("url (string)",fs("The full URL of the link enclosed in quotation marks.")),as("link_label (string, optional)",fs("The text to display in the cell, enclosed in quotation marks."))],compute:function(e,t){const s=Eo(e).trim(),o=Eo(t)||s;return""===s?o:ye(o,s)},isExported:!0};var hf=Object.freeze({__proto__:null,HYPERLINK:cf});const df=/^[A-Z0-9\_\.]+$/;const uf=new class extends is{mapping={};add(e,t){if((e=e.toUpperCase())in this.content)throw new Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(e,t){if(e=e.toUpperCase(),!df.test(e))throw new Error(fs("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const s=function(e,t){let s=0,o=0,i=0,n=0;for(const e of t.args)s++,e.optional||e.repeating||e.default||o++,e.repeating&&i++,(e.optional||e.default)&&n++;const r=t;return r.minArgRequired=o,r.maxArgPossible=i?1/0:s,r.nbrArgRepeating=i,r.nbrArgOptional=n,r.hidden=t.hidden||!1,r.name=e,r}(e,t);return function(e){if(e.nbrArgRepeating&&e.nbrArgOptional>=e.nbrArgRepeating)throw new Error(`Function ${e.name} has more optional arguments than repeatable ones.`);let t=!1,s=!1;for(const o of e.args){if(o.type.some(e=>hs.includes(e))&&o.type.some(e=>!hs.includes(e)))throw new Error(`Function ${e.name} has a mix of META and non-META types in the same argument: ${o.type}.`);if(o.repeating){if(!s&&t)throw new Error(`Function ${e.name} has non-consecutive repeating arguments. All repeating arguments must be declared consecutively.`);t=!0,s=!0}else s=!1}}(s),this.mapping[e]=ti(s),super.replace(e,s),this}},gf=[{name:fs("Array"),functions:Gi},{name:fs("Database"),functions:Dc},{name:fs("Date"),functions:Ad},{name:fs("Filter"),functions:Ud},{name:fs("Financial"),functions:ju},{name:fs("Info"),functions:rg},{name:fs("Lookup"),functions:Wp},{name:fs("Logical"),functions:Cg},{name:fs("Math"),functions:za},{name:fs("Misc"),functions:Gn},{name:fs("Operator"),functions:hm},{name:fs("Statistical"),functions:pc},{name:fs("Text"),functions:lf},{name:fs("Engineering"),functions:Od},{name:fs("Web"),functions:hf},{name:fs("Parser"),functions:Dm}];for(const e of gf){const t=e.functions;for(let s in t){const o=t[s];o.category=o.category||e.name,s=s.replace(/_/g,"."),uf.add(s,{isExported:!1,...o})}}var pf;!function(e){e[e.LeftRef=0]="LeftRef",e[e.RightRef=1]="RightRef",e[e.Separator=2]="Separator",e[e.FullColumnSeparator=3]="FullColumnSeparator",e[e.FullRowSeparator=4]="FullRowSeparator",e[e.RightColumnRef=5]="RightColumnRef",e[e.RightRowRef=6]="RightRowRef",e[e.Found=7]="Found"}(pf||(pf={}));const mf=(e,t=()=>!0)=>[{goTo:e,guard:t}],ff=(e,t=()=>!0)=>({goTo:e,guard:t}),vf={[pf.LeftRef]:{REFERENCE:mf(pf.Separator),NUMBER:mf(pf.FullRowSeparator),SYMBOL:[ff(pf.FullColumnSeparator,e=>{return t=e.value,jn.test(t);var t}),ff(pf.FullRowSeparator,e=>Kn(e.value))]},[pf.FullColumnSeparator]:{SPACE:mf(pf.FullColumnSeparator),OPERATOR:mf(pf.RightColumnRef,e=>":"===e.value)},[pf.FullRowSeparator]:{SPACE:mf(pf.FullRowSeparator),OPERATOR:mf(pf.RightRowRef,e=>":"===e.value)},[pf.Separator]:{SPACE:mf(pf.Separator),OPERATOR:mf(pf.RightRef,e=>":"===e.value)},[pf.RightRef]:{SPACE:mf(pf.RightRef),NUMBER:mf(pf.Found),REFERENCE:mf(pf.Found,e=>er(e.value)),SYMBOL:mf(pf.Found,e=>Jn(e.value)||Qn(e.value))},[pf.RightColumnRef]:{SPACE:mf(pf.RightColumnRef),SYMBOL:mf(pf.Found,e=>Jn(e.value)),REFERENCE:mf(pf.Found,e=>er(e.value))},[pf.RightRowRef]:{SPACE:mf(pf.RightRowRef),NUMBER:mf(pf.Found),REFERENCE:mf(pf.Found,e=>er(e.value)),SYMBOL:mf(pf.Found,e=>Qn(e.value))},[pf.Found]:{}};function bf(e){let t=0,s=vf[pf.LeftRef],o="";for(;void 0!==s;){const i=e[t++];if(!i)return null;const n=s[i.type]?.find(e=>e.guard(i)),r=n?n.goTo:void 0;switch(r){case void 0:return null;case pf.Found:return o+=i.value,e.splice(0,t),{type:"REFERENCE",value:o};default:s=vf[r],o+=i.value}}return null}function Sf(e,t=Oc){const s=Mc(e,t),o=[];for(;s.length;)o.push(bf(s)||s.shift());return o}const Cf=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,yf=["-","+"],If=["%"];class wf{tokens;currentIndex=0;current;length;constructor(e){this.tokens=e,this.current=e[0],this.length=e.length}shift(){const e=this.tokens[this.currentIndex];return this.current=this.tokens[++this.currentIndex],e}get next(){return this.tokens[this.currentIndex+1]}}const Ef={"%":40,"^":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function Rf(e){const t=e.shift();if(!t)throw new ys;switch(t.type){case"DEBUGGER":const s=Af(e,1e3);return s.debug=!0,s;case"NUMBER":return{type:"NUMBER",value:ho(t.value,Oc),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"STRING":return{type:"STRING",value:ce(t.value),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"INVALID_REFERENCE":return{type:"REFERENCE",value:bs.InvalidReference,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"REFERENCE":if(":"===e.current?.value&&"REFERENCE"===e.next?.type){e.shift();const s=e.shift();return{type:"REFERENCE",value:`${t.value}:${s?.value}`,tokenStartIndex:t.tokenIndex,tokenEndIndex:s.tokenIndex}}return{type:"REFERENCE",value:t.value,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"SYMBOL":const o=t.value,i=e.current;if("LEFT_PAREN"===i?.type&&Cf.test(t.value)&&o===ce(o,"'")){const{args:s,rightParen:i}=function(e){Tf(e,"LEFT_PAREN",fs("Missing opening parenthesis"));const t=e.current;if("RIGHT_PAREN"===t?.type){return{args:[],rightParen:Tf(e,"RIGHT_PAREN")}}const s=[];s.push(xf(e));for(;"RIGHT_PAREN"!==e.current?.type;)Tf(e,"ARG_SEPARATOR",fs("Wrong function call")),s.push(xf(e));const o=Tf(e,"RIGHT_PAREN");return{args:s,rightParen:o}}(e);return{type:"FUNCALL",value:o,args:s,tokenStartIndex:t.tokenIndex,tokenEndIndex:i.tokenIndex}}const n=o.toUpperCase();return"TRUE"===n||"FALSE"===n?{type:"BOOLEAN",value:"TRUE"===n,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:{type:"SYMBOL",value:ce(t.value,"'"),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"LEFT_PAREN":const r=Af(e),a=Tf(e,"RIGHT_PAREN",fs("Missing closing parenthesis"));return{...r,tokenStartIndex:t.tokenIndex,tokenEndIndex:a.tokenIndex};case"OPERATOR":const l=t.value;if(yf.includes(l)){const s=Af(e,Ef[l]);return{type:"UNARY_OPERATION",value:l,operand:s,tokenStartIndex:t.tokenIndex,tokenEndIndex:s.tokenEndIndex}}throw new ys(fs("Unexpected token: %s",t.value));default:throw new ys(fs("Unexpected token: %s",t.value))}}function xf(e){const t=e.current;return"ARG_SEPARATOR"===t?.type||"RIGHT_PAREN"===t?.type?{type:"EMPTY",value:"",tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:Af(e)}function Tf(e,t,s){const o=e.shift();if(!o||o.type!==t)throw new ys(s);return o}function Af(e,t=0){if(0===e.length)throw new ys;let s=Rf(e);for(;"OPERATOR"===e.current?.type&&Ef[e.current.value]>t;){const t=e.shift(),o=t.value;if(If.includes(o))s={type:"UNARY_OPERATION",value:o,operand:s,postfix:!0,tokenStartIndex:s.tokenStartIndex,tokenEndIndex:t.tokenIndex};else{const t=Af(e,Ef[o]);s={type:"BIN_OPERATION",value:o,left:s,right:t,tokenStartIndex:s.tokenStartIndex,tokenEndIndex:t.tokenEndIndex}}}return s}function Df(e){return _f(Sf(e))}function _f(e){const t=e.map((e,t)=>({type:e.type,value:e.value,tokenIndex:t})).filter(e=>"SPACE"!==e.type),s=new wf(t);"="===s.current?.value&&s.shift();const o=Af(s);if(s.current)throw new ys;return o}function Of(e,t,s){return Mf(e,e=>e.type===t?s(e):e)}function Ff(e){return Array.from(Pf(e))}function*Pf(e){switch(yield e,e.type){case"FUNCALL":for(const t of e.args)yield*Pf(t);break;case"UNARY_OPERATION":yield*Pf(e.operand);break;case"BIN_OPERATION":yield*Pf(e.left),yield*Pf(e.right)}}function Mf(e,t){switch((e=t(e)).type){case"FUNCALL":return{...e,args:e.args.map(e=>Mf(e,t))};case"UNARY_OPERATION":return{...e,operand:Mf(e.operand,t)};case"BIN_OPERATION":return{...e,right:Mf(e.right,t),left:Mf(e.left,t)};default:return e}}const Nf=uf.content;function Lf(e){try{return 0===Ff(_f(e)).filter(e=>"FUNCALL"===e.type&&!Nf[e.value.toUpperCase()]?.isExported).length}catch(e){return!1}}function kf(e,t){if(!e.some(e=>"SYMBOL"===e.type&&t.includes(e.value.toUpperCase())))return[];let s;try{s=_f(e)}catch{return[]}return function(e,t){return Ff(e).filter(e=>"FUNCALL"===e.type&&t.includes(e.value.toUpperCase())).map(e=>({functionName:e.value.toUpperCase(),args:e.args}))}(s,t)}function Vf(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const Uf=new Og;function Hf(e,t){return{url:e=Vf(e),label:t||e,isExternal:!0,isUrlEditable:!0}}Uf.add("sheet_URL",{match:e=>Ee(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){const s=xe(e);return t.tryGetSheetName(s)||fs("Invalid sheet")},open(e,t){const s=xe(e);t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:s}).isCancelledBecause("SheetIsHidden")&&t.notifyUser({type:"warning",sticky:!1,text:fs("Cannot open the link because the linked sheet is hidden.")})},sequence:0});const zf={createLink:Hf,match:e=>Ce(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function Bf(e){return Uf.getAll().sort((e,t)=>e.sequence-t.sequence).find(t=>t.match(e))||zf}function Gf(e,t){return Bf(e.url).urlRepresentation(e.url,t)}function Wf(e,t,s){Bf(e.url).open(e.url,t,s)}function $f(e){if("string"==typeof e){if(Se(e)){const{label:t,url:s}=Ie(e);return Bf(s).createLink(s,t)}return Ce(e)?Hf(e):void 0}}function qf(e){return e.map(jf).sort((e,t)=>e.sequence-t.sequence)}let Zf=1;function jf(e){const t=e.name,s=e.children,o=e.description,i=e.icon,n=e.secondaryIcon,r=e.id||Zf++,a=e.isEnabled?e.isEnabled:()=>!0;return{id:r.toString(),name:"function"==typeof t?t:()=>t,isVisible:e.isVisible?e.isVisible:()=>!0,isEnabled:a,isActive:e.isActive,execute:e.execute?(t,s)=>{if(a(t))return e.execute(t,s)}:void 0,children:s?e=>s.map(t=>"function"==typeof t?t(e):t).flat().map(jf):()=>[],isReadonlyAllowed:e.isReadonlyAllowed||!1,separator:e.separator||!1,icon:"function"==typeof i?i:()=>i||"",iconColor:e.iconColor,secondaryIcon:"function"==typeof n?n:()=>n||"",description:"function"==typeof o?o:()=>o||"",textColor:e.textColor,sequence:e.sequence||0,onStartHover:e.onStartHover,onStopHover:e.onStopHover}}class Yf{subscriptions={};on(e,t,s){if(!s)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:s})}trigger(e,t){const s=this.subscriptions[e]||[];for(let e=0,o=s.length;e<o;e++){const o=s[e];o.callback.call(o.owner,t)}}off(e,t){const s=this.subscriptions[e];s&&(this.subscriptions[e]=s.filter(e=>e.owner!==t))}clear(){this.subscriptions={}}}class Xf extends Yf{dependencies=new Map;factory=new Kf(this.get.bind(this));inject(e,t){if(this.dependencies.has(e)&&this.dependencies.get(e)!==t)throw new 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(const e of this.dependencies.values())"dispose"in e&&"function"==typeof e.dispose&&e.dispose()}}class Kf{get;pendingBuilds=new Set;constructor(e){this.get=e}build(e,...t){if(this.pendingBuilds.has(e))throw new Error(`Circular dependency detected: ${[...this.pendingBuilds,e].map(e=>e.name).join(" -> ")}`);this.pendingBuilds.add(e);const s=new e(this.get,...t);return this.pendingBuilds.delete(e),s}}class Jf{get;disposeCallbacks=[];constructor(e){this.get=e}onDispose(e){this.disposeCallbacks.push(e)}dispose(){this.disposeCallbacks.forEach(e=>e())}}function Qf(){const e=t.useEnv();if(e.__spreadsheet_stores__ instanceof Xf)return e.__spreadsheet_stores__;const s=new Xf;return t.useSubEnv({__spreadsheet_stores__:s,getStore:e=>ov(s.get(e),()=>s.trigger("store-updated"))}),t.onWillUnmount(()=>s.dispose()),s}function ev(e){const s=iv(t.useEnv()),o=s.get(e);return sv(s,o)}function tv(e,...s){const o=iv(t.useEnv()),i=o.instantiate(e,...s);return t.onWillUnmount(()=>i.dispose()),sv(o,i)}function sv(e,s){const o=t.useComponent();return ov(s,()=>{"mounted"===t.status(o)&&e.trigger("store-updated")})}function ov(e,t){return new Proxy(e,{get(s,o,i){const n=s,r=Reflect.get(s,o,n);if(e.mutators?.includes(o)){const e=new Proxy(r,{apply(e,s,o){"noStateChange"!==Reflect.apply(e,n,o)&&t()}});return e}return r}})}function iv(e){const t=e.__spreadsheet_stores__;if(!(t instanceof Xf))throw new Error("No store provider found. Did you forget to call useStoreProvider()?");return t}const nv=(rv="Model",class{constructor(e){throw new Error(`This is a abstract store for ${rv}, it cannot be instantiated.\nDid you forget to inject your store instance?\n\nconst stores = useStoreProvider();\nstores.inject(MyMetaStore, storeInstance);\n`)}});var rv;const av={Background:0,Highlights:1,Clipboard:2,Chart:4,Autofill:5,Selection:6,Headers:100},lv=$e(()=>Object.keys(av).sort((e,t)=>av[e]-av[t]));class cv{mutators=["register","unRegister","draw","startAnimation","stopAnimation"];renderers={};model;context=void 0;animationFrameId=null;registeredAnimations=new Set;constructor(e){this.model=e(nv)}register(e){if(e.renderingLayers.length)for(const t of e.renderingLayers)this.renderers[t]||(this.renderers[t]=[]),this.renderers[t].push(e)}unRegister(e){for(const t of Object.keys(this.renderers))this.renderers[t]=this.renderers[t].filter(t=>t!==e)}drawLayer(e,t,s){const o=this.renderers[t];if(o)for(const i of o)e.ctx.save(),i.drawLayer(e,t,s),e.ctx.restore();return"noStateChange"}draw(e,t){if(!(e=e||this.context))throw new Error("Rendering context is not defined");this.context=e;for(const s of lv())this.model.drawLayer(e,s),this.drawLayer(e,s,t);return"noStateChange"}startAnimation(e){if(this.registeredAnimations.add(e),!this.animationFrameId){const e=t=>{this.animationFrameId=requestAnimationFrame(e),this.draw(void 0,t)};this.animationFrameId=requestAnimationFrame(e)}return"noStateChange"}stopAnimation(e){return this.registeredAnimations.delete(e),0===this.registeredAnimations.size&&null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),"noStateChange"}dispose(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}}class hv extends Jf{model=this.get(nv);getters=this.model.getters;renderer=this.get(cv);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,s){}}const dv={id:"void-composer",get editionMode(){return"inactive"},startEdition:()=>{throw new Error("No composer is registered")},stopEdition:()=>{throw new Error("No composer is registered")},setCurrentContent:()=>{throw new Error("No composer is registered")}};class uv extends hv{mutators=["focusComposer","focusActiveComposer"];activeComposer=dv;_focusMode="inactive";get focusMode(){return"inactive"===this.activeComposer.editionMode?"inactive":this._focusMode}focusComposer(e,t){if(this.activeComposer=e,this.getters.isReadonly())return"noStateChange";this._focusMode=t.focusMode||"contentFocus","inactive"!==this._focusMode&&this.setComposerContent(t)}focusActiveComposer(e){if(this.getters.isReadonly())return"noStateChange";if(!this.activeComposer)throw new Error("No composer is registered");this._focusMode=e.focusMode||"contentFocus","inactive"!==this._focusMode&&this.setComposerContent(e)}setComposerContent({content:e,selection:t}){"inactive"===this.activeComposer.editionMode?this.activeComposer.startEdition(e,t):e&&this.activeComposer.setCurrentContent(e,t)}}const gv=/rgba?\(|\s+|\)/gi,pv=/^#([A-F\d]{2}){3,4}$/,mv=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function fv(e,t=1){const s=1!==t?Math.round(255*t).toString(16).padStart(2,"0"):"";return bv(e.toString(16).padStart(6,"0"))+s}function vv(e){return"number"==typeof e?e:Number.parseInt(bv(e).slice(1,7),16)}function bv(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(gv,"").split(",");let s=255;if(3!==t.length&&4!==t.length)throw new Error("invalid color");if(4===t.length){const e=parseFloat(t.pop()||"1");if(isNaN(e))throw new Error("invalid alpha value");s=Math.round(255*e)}const o=t.map(e=>parseInt(e,10));255!==s&&o.push(s);return"#"+_e(o.map(e=>e.toString(16).padStart(2,"0"))).toUpperCase()}(e):(t=e.replace("#","").toUpperCase(),3!==t.length&&4!==t.length||(t=t.split("").reduce((e,t)=>e+t+t,"")),t=`#${t}`),!pv.test(t))throw new Error(`invalid color input: ${e}`);return t}function Sv(e){try{return bv(e),!0}catch(e){return!1}}const Cv=e=>e>=0&&e<=255;function yv(e,t,s,o=1){if(!Cv(e)||!Cv(t)||!Cv(s)||o<0||o>1)throw new Error(`Invalid RGBA values ${[e,t,s,o]}`);return{a:o,b:s,g:t,r:e}}function Iv(e){let{r:t,g:s,b:o}=Ev(e);t/=255,s/=255,o/=255;const i=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return.2126*i(t)+.7152*i(s)+.0722*i(o)}function wv(e){let t=e.r.toString(16),s=e.g.toString(16),o=e.b.toString(16),i=Math.round(255*e.a).toString(16);return 1===t.length&&(t="0"+t),1===s.length&&(s="0"+s),1===o.length&&(o="0"+o),1===i.length&&(i="0"+i),"ff"===i&&(i=""),("#"+t+s+o+i).toUpperCase()}function Ev(e){let t,s,o,i;if(7===(e=bv(e)).length)t=parseInt(e[1]+e[2],16),s=parseInt(e[3]+e[4],16),o=parseInt(e[5]+e[6],16),i=255;else{if(9!==e.length)throw new Error("Invalid color");t=parseInt(e[1]+e[2],16),s=parseInt(e[3]+e[4],16),o=parseInt(e[5]+e[6],16),i=parseInt(e[7]+e[8],16)}return i=+(i/255).toFixed(3),{a:i,r:t,g:s,b:o}}function Rv(e){(e={...e}).s/=100,e.l/=100;const t=(1-Math.abs(2*e.l-1))*e.s,s=t*(1-Math.abs(e.h/60%2-1)),o=e.l-t/2;let i=0,n=0,r=0;return 0<=e.h&&e.h<60?(i=t,n=s,r=0):60<=e.h&&e.h<120?(i=s,n=t,r=0):120<=e.h&&e.h<180?(i=0,n=t,r=s):180<=e.h&&e.h<240?(i=0,n=s,r=t):240<=e.h&&e.h<300?(i=s,n=0,r=t):300<=e.h&&e.h<360&&(i=t,n=0,r=s),i=Math.round(255*(i+o)),n=Math.round(255*(n+o)),r=Math.round(255*(r+o)),{a:e.a,r:i,g:n,b:r}}function xv(e){const t=e.r/255,s=e.g/255,o=e.b/255,i=Math.min(t,s,o),n=Math.max(t,s,o),r=n-i;let a=0,l=0,c=0;return a=0===r?0:n===t?(s-o)/r%6:n===s?(o-t)/r+2:(t-s)/r+4,a=Math.round(60*a),a<0&&(a+=360),c=(n+i)/2,l=0===r?0:r/(1-Math.abs(2*c-1)),l=+(100*l).toFixed(1),c=+(100*c).toFixed(1),{a:e.a,h:a,s:l,l:c}}function Tv(e){return wv(Rv(e))}function Av(e){return xv(Ev(e))}function Dv(e){return Ev("number"==typeof e?fv(e):e)}function _v(e,t){return 1===t?bv(e).slice(0,7):wv({...Ev(e),a:t})}function Ov(e,t){const s=Av(e);return 1===t?"#fff":(s.l=t*(100-s.l)+s.l,Tv(s))}function Fv(e,t){const s=Av(e);return 1===t?"#000":(s.s=Math.min(100,t*s.s+s.s),s.l=s.l-t*s.l,Tv(s))}function Pv(e){return Iv(e)<.6?Ov(e,.9):Fv(e,.75)}const Mv=["#4EA7F2","#EA6175","#43C5B1","#F4A261","#8481DD","#FFD86D"],Nv=["#4EA7F2","#3188E6","#43C5B1","#00A78D","#EA6175","#CE4257","#F4A261","#F48935","#8481DD","#5752D1","#FFD86D","#FFBC2C"],Lv=["#4EA7F2","#3188E6","#056BD9","#A76DBC","#7F4295","#6D2387","#EA6175","#CE4257","#982738","#43C5B1","#00A78D","#0E8270","#F4A261","#F48935","#BE5D10","#8481DD","#5752D1","#3A3580","#A4A8B6","#7E8290","#545B70","#FFD86D","#FFBC2C","#C08A16"],kv=["#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"],Vv=["#4EA7F2","#43C5B1","#EA6175","#F4A261","#8481DD","#FFD86D","#3188E6","#00A78D","#CE4257","#F48935","#5752D1","#FFBC2C"],Uv=["#4EA7F2","#A76DBC","#EA6175","#43C5B1","#F4A261","#8481DD","#A4A8B6","#FFD86D","#3188E6","#7F4295","#CE4257","#00A78D","#F48935","#5752D1","#7E8290","#FFBC2C","#056BD9","#6D2387","#982738","#0E8270","#BE5D10","#3A3580","#545B70","#C08A16"],Hv=["#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"];function zv(e,t){return t[e%t.length]}function Bv(e){return e<=6?Mv:e<=12?Nv:e<=24?Lv:kv}class Gv{preferredColors;currentColorIndex=0;palette;constructor(e,t=[]){this.preferredColors=t,this.palette=Bv(e).filter(e=>!t.includes(e))}next(){return this.preferredColors?.[this.currentColorIndex]?this.preferredColors[this.currentColorIndex++]:zv(this.currentColorIndex++,this.palette)}}class Wv extends Gv{constructor(e,t=[]){var s;super(e,t),this.palette=(s=e,s<=6?Mv:s<=12?Vv:s<=24?Uv:Hv).filter(e=>!t.includes(e))}}class $v{availableColors;colors={};constructor(e=12){this.availableColors=new Wv(e)}get(e){return this.colors[e]||(this.colors[e]=this.availableColors.next()),this.colors[e]}}function qv(e){if(e.length<2)throw new Error("Color scale must have at least 2 points");const t=[...e.sort((e,t)=>e.value-t.value)],s=[];for(let e=1;e<t.length;e++){const o=Dv(t[e-1].color).a,i=Dv(t[e].color).a,n=vv(t[e-1].color),r=vv(t[e].color);s.push({min:t[e-1].value,max:t[e].value,minColor:n,maxColor:r,minColorAlpha:o,maxColorAlpha:i,colorDiff:Zv(t[e-1].value,t[e].value,n,r)})}return e=>{if(e<s[0].min)return fv(s[0].minColor,s[0].minColorAlpha);for(const t of s)if(e>=t.min&&e<=t.max)return fv(jv(e,t.min,t.minColor,t.colorDiff),t.maxColorAlpha);return fv(s[s.length-1].maxColor,s[s.length-1].maxColorAlpha)}}function Zv(e,t,s,o){const i=t-e;return[((s>>16)%256-(o>>16)%256)/i,((s>>8)%256-(o>>8)%256)/i,(s%256-o%256)/i]}function jv(e,t,s,o){const[i,n,r]=o;return Math.round((s>>16)%256-i*(e-t))<<16|Math.round((s>>8)%256-n*(e-t))<<8|Math.round(s%256-r*(e-t))}function Yv(e,t,s){return Kv({value:zn(t.format)&&null!==e.parsedValue?e.content:e.parsedValue,format:t.format,origin:s},t.locale)}function Xv(e,t){if(e.startsWith("="))throw new Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);if(e.startsWith("'"))return e.slice(1);if(""===e)return null;if(e.includes("\n"))return e;if(lo(e,Oc))return ho(e,Oc);const s=Zs(e,t);return s?s.value:fe(e)?"TRUE"===e.toUpperCase():e}function Kv(e,t=Oc,s,o){const i=$f(e.value);if(!i){return tb(Jv(e,t,s),e.origin??o)}const n=Xv(i.label,t);return tb({...Jv({value:n,format:e.format||("number"==typeof n?Tn(i.label,t)||An(i.label):void 0)},t,s),link:i},e.origin??o)}function Jv(e,t,s){let{value:o,format:i,message:n}=e;i=s?.format||i;const r=pn(o,{format:i,locale:t});return mo(o)?function(e,t){return{value:e,formattedValue:e,message:t,type:_d.error,isAutoSummable:!1,defaultAlign:"center"}}(o,n):null===o?eb(i):zn(i)?Qv(Eo(o),i,r):"number"==typeof o?wn(i||"")?function(e,t,s){return{value:e,format:t,formattedValue:s,type:_d.number,isAutoSummable:!1,defaultAlign:"right"}}(o,i,r):function(e,t,s){return{value:e||0,format:t,formattedValue:s,type:_d.number,isAutoSummable:!0,defaultAlign:"right"}}(o,i,r):"boolean"==typeof o?function(e,t,s){return{value:e,format:t,formattedValue:s,type:_d.boolean,isAutoSummable:!1,defaultAlign:"center"}}(o,i,r):Qv(o,i,r)}function Qv(e,t,s){return{value:e,format:t,formattedValue:s,type:_d.text,isAutoSummable:!0,defaultAlign:"left"}}const eb=$e(function(e){return{value:null,format:e,formattedValue:"",type:_d.empty,isAutoSummable:!0,defaultAlign:"left"}});function tb(e,t){return null===e.value||"origin"in e||(e.origin=t),e}function sb(e){const t=Os.now();switch(e){case"today":return Xs(t);case"yesterday":return Xs(Os.fromTimestamp(t.setDate(t.getDate()-1)));case"tomorrow":return Xs(Os.fromTimestamp(t.setDate(t.getDate()+1)));case"lastWeek":return Xs(Os.fromTimestamp(t.setDate(t.getDate()-7)));case"lastMonth":return Xs(Os.fromTimestamp(t.setMonth(t.getMonth()-1)));case"lastYear":return Xs(Os.fromTimestamp(t.setFullYear(t.getFullYear()-1)))}}function ob(e,t){return"dateValue"in e&&"exactDate"!==e.dateValue?[sb(e.dateValue)]:e.values.map(e=>Ws(e,t))}function ib(e,t){return e.map(e=>{if(e.startsWith("="))return e;const s=Xv(e,t);return"number"==typeof s?pn(s,{format:t.dateFormat,locale:t}):""})}const nb=new WeakMap,rb=new WeakMap;function ab(e,t){nb.has(t)||(nb.set(t,new Map),rb.set(t,0));const s=nb.get(t),o=hb(e);if(s.has(o)){const i=s.get(o);return t[i]=e,i}const i=rb.get(t)+1;return s.set(o,i),rb.set(t,i),t[i]=e,i}function lb(e){const t={};for(const s in e){const o=ft(e[s].map(Zt));for(const e of o)t[Tt(e)]=Number(s)}return t}function*cb(e,t){for(const s in t){const o=wt(s),i=t[s];for(let t=o.top;t<=o.bottom;t++)for(let s=o.left;s<=o.right;s++){const o={sheetId:e,col:s,row:t};yield[o,i]}}}function hb(e){if(null===e)return"null";if(void 0===e)return"undefined";if("object"!=typeof e)return String(e);if(Array.isArray(e)){const t=e.length;let s="[";for(let o=0;o<t;o++)o>0&&(s+=","),s+=hb(e[o]);return s+"]"}const t=Object.keys(e).sort();let s="{";for(const o of t)void 0!==e[o]&&(s+=`"${o}":${hb(e[o])},`);return s+="}",s}function db(e){return 20+120*Math.exp(-.035*(e-1))}function ub(e){const t=[];for(let s=0;s<e;s++){const e={cells:{}};t.push(e)}return t}function gb(e,t,s){return s.map(s=>s>=e?s+t:s)}function pb(e,t){return e=[...e].sort((e,t)=>t-e),t.map(t=>{for(const s of e)if(t>s)t--;else if(t===s)return;return t}).filter(Te)}function mb(e,t="Sheet"){let s=1,o=`${t}${s}`;for(;e.includes(o);)o=`${t}${s}`,s++;return o}function fb(e,t){let s=1;const o=fs("Copy of %s",e);let i=o.toString();for(;t.includes(i);)i=`${o} (${s})`,s++;return i}function vb(e,t){return void 0!==e&&void 0!==t&&le(e.trim().toUpperCase())===le(t.trim().toUpperCase())}function bb(e,t){const s=e.zone,o=function(e,t){const{left:s,top:o,bottom:i,right:n}=e;if(void 0!==n&&void 0!==i)return e;if(void 0===i&&void 0!==n)return{right:n,top:o,left:s,bottom:t.numberOfRows-1};if(void 0===n&&void 0!==i)return{bottom:i,left:s,top:o,right:t.numberOfCols-1};throw new Error("Bad zone format")}(s,t(e.sheetId));let i=e.parts;return 1===e.parts.length&&Kt(o)>1?i=[e.parts[0],e.parts[0]]:2===e.parts.length&&1===Kt(o)&&(i=[e.parts[0]]),{unboundedZone:s,zone:o,parts:i,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function Sb(e,t){const s=e.xc,{xc:o,sheetName:i}=tr(s),n=It(o),r=function(e,t){const s=e.split(":").map(e=>{const t=Kn(e);return{colFixed:!t&&e.startsWith("$"),rowFixed:t?e.startsWith("$"):e.includes("$",1)}}),o=void 0===t.bottom,i=void 0===t.right;o&&(s[0].rowFixed=s[0].rowFixed||s[1].rowFixed,s[1].rowFixed=s[0].rowFixed||s[1].rowFixed);i&&(s[0].colFixed=s[0].colFixed||s[1].colFixed,s[1].colFixed=s[0].colFixed||s[1].colFixed);return s}(o,n);return bb({zone:n,parts:r,sheetId:e.sheetId,prefixSheet:Boolean(i),invalidSheetName:e.invalidSheetName},t)}function Cb(e){const t={left:-1,top:-1,right:-1,bottom:-1};return{sheetId:"",zone:t,unboundedZone:t,parts:[],invalidXc:e,prefixSheet:!1}}function yb(e){return Xt(e.unboundedZone)}function Ib(e){return Yt(e.unboundedZone)}function wb(e,t,s,o={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)return bs.InvalidReference;if(e.zone.left<0||e.zone.top<0)return bs.InvalidReference;const i=e.sheetId!==t||e.invalidSheetName||e.prefixSheet;let n="";if(i&&(n=e.invalidSheetName?e.invalidSheetName:he(s(e.sheetId))),i&&!n)return bs.InvalidReference;let r=Nb(e,0,o);return e.parts&&2===e.parts.length&&(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)&&(r+=":",r+=Nb(e,1,o)),`${i?n+"!":""}${r}`}function Eb(e,t,s){const o=s.sheetId===e?t:s.sheetId;return{...s,sheetId:o}}function Rb(e,t,s){if(!s)return;const o=e.getRangeFromSheetXC(t,s);return o.invalidSheetName||o.invalidXc?void 0:o}function xb(e){const t=[];for(const s of e)for(const e of Bt(s.zone))t.push({...e,sheetId:s.sheetId});return t}function Tb(e){return Ab.get(e.type)?.(e)}const Ab=new class extends Og{add(e,t){return super.add(e,t),this}get(e){return this.content[e]}};function Db(e){const t="COL"===e.dimension?"left":"top",s="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows",i=[...e.elements];i.sort((e,t)=>t-e);const n=pe(i);return i=>{if(!vb(i.sheetId,e.sheetId))return{changeType:"NONE"};let r=i,a="NONE";for(const e of n){const n=Je(e),l=Ke(e);if(i.zone[t]<=n&&n<=i.zone[s]){const e=Math.min(i.zone[s],l)-n+1;a="RESIZE",r=Mb(r,o,a,-e)}else if(i.zone[t]>=n&&i.zone[s]<=l)a="REMOVE",r=Cb(bs.InvalidReference);else if(i.zone[t]<=l&&i.zone[s]>=l){const e=l-i.zone[t]+1;a="RESIZE",r=Mb(r,o,a,-e),r=Mb(r,o,"MOVE",-(i.zone[t]-n))}else n<i.zone[t]&&(a="MOVE",r=Mb(r,o,a,-(l-n+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}}function _b(e){const t="COL"===e.dimension?"left":"top",s="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";return i=>{if(i.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(i.zone[t]<=e.base&&e.base<i.zone[s])return{changeType:"RESIZE",range:Mb(i,o,"RESIZE",e.quantity)};if(e.base<i.zone[t])return{changeType:"MOVE",range:Mb(i,o,"MOVE",e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[s])return{changeType:"RESIZE",range:Mb(i,o,"RESIZE",e.quantity)};if(e.base<=i.zone[t])return{changeType:"MOVE",range:Mb(i,o,"MOVE",e.quantity)}}return{changeType:"NONE"}}}function Ob(e){return t=>{if(t.sheetId!==e.sheetId&&t.invalidSheetName!==e.sheetName)return{changeType:"NONE"};const s=e.sheetName;return{changeType:"REMOVE",range:t={...Cb(bs.InvalidReference),invalidSheetName:s}}}}function Fb(e){return t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.newName&&t.invalidSheetName===e.newName){const s=void 0,o=e.sheetId;return{changeType:"CHANGE",range:{...t,sheetId:o,invalidSheetName:s}}}if(e.oldName&&t.invalidSheetName===e.oldName){const s=void 0,o=e.sheetId;return{changeType:"CHANGE",range:{...t,sheetId:o,invalidSheetName:s}}}return{changeType:"NONE"}}}function Pb(e){const t=e.target[0];return s=>{if(s.sheetId!==e.sheetId||!Vt(s.zone,t))return{changeType:"NONE"};const o=e.targetSheetId,i=Mb(s,"both","MOVE",[e.col-t.left,e.row-t.top]),n=e.sheetId!==o||i.prefixSheet;return{changeType:"MOVE",range:{...i,sheetId:o,prefixSheet:n}}}}function Mb(e,t,s,o){return{...e,unboundedZone:$t(e.unboundedZone,t,s,o),zone:$t(e.zone,t,s,o)}}function Nb(e,t,s={useBoundedReference:!1,useFixedReference:!1}){const o=e.parts[t]?.colFixed||s.useFixedReference?"$":"",i=it(0===t?e.zone.left:e.zone.right),n=e.parts[t]?.rowFixed||s.useFixedReference?"$":"",r=String(0===t?e.zone.top+1:e.zone.bottom+1);let a="";return a=Xt(e.unboundedZone)&&!s.useBoundedReference?0===t&&e.unboundedZone.hasHeader?o+i+n+r:o+i:Yt(e.unboundedZone)&&!s.useBoundedReference?0===t&&e.unboundedZone.hasHeader?o+i+n+r:n+r:o+i+n+r,a}function Lb(e,t=1){return t*(e+4)-4}function kb(e=100,t=100){return new OffscreenCanvas(e,t).getContext("2d")}function Vb(e,t,s,o){const i=Yb(e,t,s,"wrap"===s?.wrapping?o-8:void 0).length;return Lb(Zb(s),i)+6}function Ub(e,t=!1,s=!1){return`${s?"italic":""} ${t?"bold":""} ${e}px ${k}`}Ab.add("REMOVE_COLUMNS_ROWS",e=>({applyChange:Db(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("ADD_COLUMNS_ROWS",e=>({applyChange:_b(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("DELETE_SHEET",e=>({applyChange:Ob(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("RENAME_SHEET",e=>({applyChange:Fb(e),sheetId:e.sheetId,sheetName:{old:e.oldName,current:e.newName}})).add("MOVE_RANGES",e=>({applyChange:Pb(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}}));const Hb={};function zb(e,t,s,o="pt"){return Bb(e,t,qb(s,o))}function Bb(e,t,s){if(Hb[s]||(Hb[s]={}),void 0===Hb[s][t]){const o=e.font;e.font=s,Hb[s][t]=e.measureText(t).width,e.font=o}return Hb[s][t]}const Gb={};function Wb(e,t,s,o="pt"){const i=qb(s,o);e.save(),e.font=i;const n=function(e,t){const s=e.font;Gb[s]||(Gb[s]={});if(void 0===Gb[s][t]){const o=e.measureText(t),i=o.width,n=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent;Gb[s][t]={width:i,height:n}}return Gb[s][t]}(e,t);return e.restore(),n}function $b(e){return Math.round(96*e/72)}function qb(e,t="pt"){return`${e.italic?"italic ":""}${e.bold?"bold":"400"} ${("pt"===t?Zb(e):e.fontSize)??L}px ${k}`}function Zb(e){return $b(e?.fontSize||L)}function jb(e,t,s,o){if(zb(e,t,o)<=s)return[t];const i=[];let n="";for(const r of t){zb(e,n+r,o)>s?(i.push(n),n=r):n+=r}return i.push(n),i}function Yb(e,t,s,o){s||(s={}),Se(t)&&(t=Ie(t).label);const i=[],n=t.includes(X)?t.split(X):[t];for(const t of n){const n=t.includes(" ")?t.split(" "):[t];if(!o){i.push(t);continue}let r="",a=o;for(const t of n){const n=jb(e,t,o,s),l=n.pop(),c=zb(e,l,s);if(n.length)""!==r&&(i.push(r),r="",a=o),n.forEach(e=>{i.push(e)}),r=l,a=o-c;else{const t=""===r?l:" "+l,n=zb(e,t,s);n<=a?(r+=t,a-=n):(i.push(r),r=l,a=o-c)}}""!==r&&i.push(r)}return i}function Xb(e){return e?e.toLowerCase():""}const Kb=/([0-9\.]*)px/;function Jb(e,t,s){let o=Bb(e,t,e.font);if(o<=s)return t;const i=Bb(e,"…",e.font);if(o<=i)return t;let n=t.length;for(;o>=s-i&&n-- >0;)o=Bb(e,t=t.substring(0,n),e.font);return t+"…"}function Qb(e,t,s,o=!1,i=!1,n=function(e){return Number(e.match(Kb)?.[1])}(e.font)/10){if(e.fillText(t,s.x,s.y),!o&&!i)return;const r=e.measureText(t),a=r.width,l=r.actualBoundingBoxAscent+r.actualBoundingBoxDescent,c=r.fontBoundingBoxAscent+r.fontBoundingBoxDescent;let{x:h,y:d}=s,u=d,g=d;switch(e.textAlign){case"center":h-=a/2;break;case"right":h-=a}switch(e.textBaseline){case"top":g+=c-2*n,u+=c/2-n;break;case"middle":g+=c/2-n;break;case"alphabetic":g+=2*n,u-=3*n;break;case"bottom":g=d,u-=l/2-n/2}o&&(e.lineWidth=n,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(h,g),e.lineTo(h+a,g),e.stroke()),i&&(e.lineWidth=n,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(h,u),e.lineTo(h+a,u),e.stroke())}function eS(e,t,s,o,i="pt"){if(zb(e,s,o,i)<=t)return s;const n=zb(e,"...",o,i);if(n>=t)return"";let r,a=1,l=s.length;for(;a<=l;){const c=Math.floor((a+l)/2);r=zb(e,s.slice(0,c),o,i),r+n>t?l=c-1:a=c+1}const c=s.slice(0,Math.max(0,a-1));return c?c+"...":""}function tS(e,t,s){const o=[];return t.forEach(t=>{const i=function(e,t){e=e.toLocaleLowerCase();let s=0,o=0;const i=(t=t.toLocaleLowerCase()).length;let n=0;for(let r=0;r<i;r++)t[r]===e[n]?(n++,o+=100+o-r/200):o=0,s+=o;return n===e.length?s:0}(e,s(t));i>0&&o.push({score:i,elem:t})}),o.sort((e,t)=>t.score-e.score),o.map(e=>e.elem)}const sS=new Og;function oS(){if(window.Chart&&!window.Chart.registry.plugins.get("chartShowValuesPlugin"))for(const e of sS.getAll())e.register(window.Chart)}class iS extends hv{mutators=["disableAnimationForChart","enableAnimationForChart"];animationPlayed={};disableAnimationForChart(e,t){return this.animationPlayed[e]=t,"noStateChange"}enableAnimationForChart(e){return this.animationPlayed[e]=void 0,"noStateChange"}}function nS(){return class extends window.Chart.BarController{static id="funnel";static defaults={...window.Chart?.BarController.defaults,dataElementType:"funnel",animation:{duration:e=>{if("data"!==e.type)return 1e3;return e.raw[1]/Math.max(...e.dataset.data.map(e=>e[1]))*1e3}}};updateElements(e,t,s,o){super.updateElements(e,t,s,o);for(let i=t;i<t+s;i++){const t=e[i];this.updateElement(t,i,{nextElement:e[i+1]},o)}}}}function rS(){return class extends window.Chart.BarElement{static id="funnel";draw(e){e.save();const{x:t,y:s,height:o,nextElement:i,base:n,options:r}=this.getProps(["x","y","width","height","nextElement","base","options"]),a=aS(this),l=(a-(i?aS(i):0))/2,c=Math.min(t,n),h=s-o/2;e.fillStyle=r.backgroundColor,e.beginPath(),e.moveTo(c,h),e.lineTo(c+a,h),e.lineTo(c+a-l,h+o),e.lineTo(c+l,h+o),e.closePath(),e.fill(),r.borderWidth&&(e.strokeStyle=r.borderColor,e.lineWidth=r.borderWidth,e.stroke()),e.restore()}inRange(e,t){const{x:s,y:o,height:i,nextElement:n,base:r}=this.getProps(["x","y","width","height","nextElement","base","options"]),a=aS(this),l=n?aS(n):0,c=Math.min(s,r),h=o-i/2;if(t<h||t>h+i)return!1;const d=(a-l)/2;return!(e<c+d*(t-h)/i||e>c+a-d*(t-h)/i)}}}function aS(e){const{x:t,base:s}=e.getProps(["x","base"]),o=Math.min(t,s);return Math.max(t,s)-o}const lS=function(e){if(!e.length)return{x:0,y:0};const t=e[0].element,{x:s,y:o,base:i,width:n,height:r}=t.getProps(["x","y","width","height","base"]);return{x:Math.min(s,i)+2*n/3,y:o-r/2+r/2}},cS="000000",hS={arrows:"3Arrows",smiley:"3Symbols",dots:"3TrafficLights1"},dS="http://schemas.openxmlformats.org/spreadsheetml/2006/main",uS="http://schemas.openxmlformats.org/spreadsheetml/2006/main",gS="http://schemas.openxmlformats.org/package/2006/relationships",pS="http://schemas.openxmlformats.org/package/2006/content-types",mS="http://schemas.openxmlformats.org/spreadsheetml/2006/main",fS="http://schemas.openxmlformats.org/spreadsheetml/2006/main",vS="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing",bS="http://schemas.openxmlformats.org/spreadsheetml/2006/main",SS="http://schemas.microsoft.com/office/spreadsheetml/2014/revision",CS="http://schemas.microsoft.com/office/spreadsheetml/2016/revision3",yS="http://schemas.openxmlformats.org/markup-compatibility/2006",IS="http://schemas.openxmlformats.org/drawingml/2006/main",wS="http://schemas.openxmlformats.org/drawingml/2006/chart",ES={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"},RS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",xS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",TS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata",AS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",DS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",_S="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing",OS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart",FS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/table",PS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",MS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",NS="bdbb8cdc-fa1e-496e-a857-3c3f30c029c3",LS="http://schemas.openxmlformats.org/officeDocument/2006/relationships",kS=.75,VS=.143,US=8.43,HS=12.75,zS={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}]},BS=["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"],GS="[Content_Types].xml";function WS(e,t,s){if(!t.startsWith("="))return t;const o=Sf(t);for(let t=1;t<o.length;t++){if("REFERENCE"!==o[t].type)continue;const i=o[t].value,n=$S(e,i,s);i!==n&&(o[t]={value:n,type:"REFERENCE"})}return _e(o.map(e=>e.value))}function $S(e,t,s){const o=tr(t).sheetName;if(o?!vb(o,s.sheetName.old):e!==s.sheetId)return t;const i=function(e,t){if(!Xn.test(e))return Cb(e);return Sb({xc:e,sheetId:t},qS)}(t,o?s.sheetId:e);if(i.invalidXc)return t;const n=s.applyChange(i);return"NONE"===n.changeType||"REMOVE"===n.changeType?t:wb(n.range,e,function(e){return t=>t===e.sheetId?e.sheetName.current:""}(s))}function qS(e){return{numberOfRows:Number.MAX_SAFE_INTEGER,numberOfCols:Number.MAX_SAFE_INTEGER}}const ZS="x1",jS="xMovingAverage",YS={exponential:"exp",logarithmic:"log",polynomial:"poly",trailingMovingAverage:"movingAvg"};function XS(e,t,s,o){let i=!1;const n=[];for(const o in s){let r=s[o];if(r.labelCell){const e=QS(r.labelCell,t);r.labelCell!==e&&(i=!0,r={...r,labelCell:e})}const a=QS(r.dataRange,t);void 0===a||e.getRangeString(a,a.sheetId)===bs.InvalidReference?(i=!0,r=void 0):a!==r.dataRange&&(i=!0,r={...r,dataRange:a}),n[o]=r}let r=o;const a=QS(r,t);a!==r&&(i=!0,r=a);return{isStale:i,dataSets:n.filter(Te),labelRange:r}}function KS(e,t,s){return s.map(s=>({dataRange:Eb(e,t,s.dataRange),labelCell:s.labelCell?Eb(e,t,s.labelCell):void 0}))}function JS(e,t,s){return s?Eb(e,t,s):void 0}function QS(e,t){if(!e)return;const s=t(e);switch(s.changeType){case"NONE":return e;case"REMOVE":return;default:return s.range}}function eC(e,t,s,o){const i=[];for(const n of t){const t=e.getRangeFromSheetXC(s,n.dataRange),{unboundedZone:r,sheetId:a,invalidSheetName:l,invalidXc:c}=t;if(!l&&!c)if(r.left!==r.right&&r.top!==r.bottom){if(void 0===r.right)continue;for(let t=r.left;t<=r.right;t++){const s={...r,left:t,right:t};i.push({...tC(e,a,s,o?{top:s.top,bottom:s.top,left:s.left,right:s.left}:void 0),backgroundColor:n.backgroundColor,rightYAxis:"y1"===n.yAxisId,customLabel:n.label,trend:n.trend})}}else i.push({...tC(e,a,r,o?{top:r.top,bottom:r.top,left:r.left,right:r.left}:void 0),backgroundColor:n.backgroundColor,rightYAxis:"y1"===n.yAxisId,customLabel:n.label,trend:n.trend})}return i}function tC(e,t,s,o){if(s.left!==s.right&&s.top!==s.bottom)throw new Error(`Zone should be a single column or row: ${Tt(s)}`);if(o){const i=Tt(s),n=Tt(o);return{labelCell:e.getRangeFromSheetXC(t,n),dataRange:e.getRangeFromSheetXC(t,i)}}return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,Tt(s))}}function sC(e,t){const s=t.labelCell?.zone;let o=t.dataRange.zone;if(s){const{numberOfRows:e,numberOfCols:t}=Ut(o);1===e?o={...o,left:o.left+1}:1===t&&(o={...o,top:o.top+1})}const i=bb({...t.dataRange,zone:o},e.getSheetSize);let n,r={};return t.customLabel?r={text:t.customLabel}:t.labelCell&&(r={reference:e.getRangeString(t.labelCell,"forceSheetReference",{useBoundedReference:!0})}),t.trend?.type&&(n={type:"polynomial"===t.trend.type&&1===t.trend.order?"linear":YS[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:r,range:e.getRangeString(i,"forceSheetReference",{useBoundedReference:!0}),backgroundColor:t.backgroundColor,rightYAxis:t.rightYAxis,trend:n}}function oC(e,t,s){if(!t)return;const o={...t.zone};s&&t.zone.bottom>t.zone.top&&(o.top=o.top+1);const i=bb({...t,zone:o},e.getSheetSize);return e.getRangeString(i,"forceSheetReference",{useBoundedReference:!0})}function iC(e,t,s){let o;if(t.labelRange){const i=$S(e,t.labelRange,s);i!==bs.InvalidReference&&(o=i)}const i=[];for(const o of t.dataSets){const t={...o},n=$S(e,o.dataRange,s);n!==bs.InvalidReference&&(t.dataRange=n,i.push(t))}return{...t,dataSets:i,labelRange:o}}function nC(e){return e&&Iv(e)<.3?"#FFFFFF":"#000000"}function rC(e){return e&&Iv(e)<.3?"#C8C8C8":"#666666"}function aC(e){if(e.dataSets){const t=void 0!==e.dataSets.find(e=>!Xn.test(e.dataRange));if(t)return"InvalidDataSet";if(e.dataSets.map(e=>It(e.dataRange)).some(e=>e.top!==e.bottom&&Yt(e)))return"InvalidDataSet"}return"Success"}function lC(e){if(e.labelRange){if(!Xn.test(e.labelRange||""))return"InvalidLabelRange"}return"Success"}function cC(e,t,s){if(!s)return!1;if(!e)return!1;if(!t)return!0;const o=Kt(t.dataRange.zone);return!(Kt(e.zone)<o)}function hC(e){let t=!1,s=!1;if("horizontal"in e&&e.horizontal)return{useLeftAxis:!0,useRightAxis:!1};for(const o of e.dataSets||[])"y1"===o.yAxisId?s=!0:t=!0;return t||=!s,{useLeftAxis:t,useRightAxis:s}}function dC(e,t,s=!1){return(o,i)=>{const n=e?.[i];return uC({format:n,locale:t},s)(o)}}function uC(e,t=!1){return s=>{if(s=Number(s),isNaN(s))return s;const{locale:o,format:i}=e;return mC(t?Mn({value:s,format:i},o):pn(s,{locale:o,format:!i&&Math.abs(s)>=1e3?"#,##":i}))}}const gC=[{value:"left",label:fs("Left")},{value:"right",label:fs("Right")}];function pC(e,t){const s=[],o=Ke(t.map(e=>e.data.length));for(let t=0;t<=o;t++)s.push(e.next());return s}function mC(e,t=20){return e?e.length>t?e.substring(0,t)+"…":e:""}function fC(e){return e===ZS||e===jS}const vC={id:"chartShowValuesPlugin",afterDatasetsDraw(e,t,s){if(!s.showValues)return;const o=e._metasets?.[0]?.data;if(!o)return;const i=e.ctx;i.save();const{left:n,top:r,height:a,width:l}=e.chartArea;switch(i.beginPath(),i.rect(n,r,l,a),i.clip(),i.textAlign="center",i.textBaseline="middle",i.miterLimit=1,e.config.type){case"pie":case"doughnut":!function(e,t,s){for(const o of e._metasets)for(let e=0;e<o._parsed.length;e++){const i=Number(o._parsed[e]);if(isNaN(i)||0===i)continue;const n=o.data[e],{startAngle:r,endAngle:a,innerRadius:l,outerRadius:c}=n,h=(r+a)/2,d=(l+c)/2,u=n.x+d*Math.cos(h),g=n.y+d*Math.sin(h),p=t.callback(i,o,e),m=12,f=zb(s,p,{fontSize:m},"px"),v=c-l;if(f>=v||v<m)continue;const b=a-r,S=2*d*Math.tan(b/2);b<Math.PI/2&&(f>=S||S<m)||(s.fillStyle=nC(t.background),s.strokeStyle=t.background||"#ffffff",bC(p,u,g,s))}}(e,s,i);break;case"bar":case"line":case"radar":s.horizontal?SC(e,s,i):function(e,t,s){const o=e.chartArea.bottom,i=e.chartArea.top,n={};for(const r of e._metasets){if(fC(r.xAxisID)||r.hidden)continue;const a=e.scales[r.yAxisID];for(let l=0;l<r._parsed.length;l++){const c=r._parsed[l],h=Number("radar"===e.config.type?c.r:c.y);if(isNaN(h))continue;const d=r.data[l],u=d.x;let g=0;if("line"===e.config.type||"radar"===e.config.type)g=h<0?d.y+10:d.y-10;else{const e=a.getPixelForValue(0),t=12;g=Math.abs(e-d.y)<t?h<0?e+t/2:e-t/2:h<0?d.y-d.height/2:d.y+d.height/2}g=Math.min(g,o),g=Math.max(g,i),n[u]||(n[u]=[]);for(const e of n[u]||[])Math.abs(e-g)<13&&(g=h<0?e+13:e-13);n[u].push(g),s.fillStyle=d.options.backgroundColor,s.strokeStyle=t.background||"#ffffff";bC(t.callback(Number(h),r,l),u,g,s)}}}(e,s,i);break;case"funnel":SC(e,s,i)}i.restore()}};function bC(e,t,s,o){o.lineWidth=3,o.strokeText(e,t,s),o.lineWidth=1,o.fillText(e,t,s)}function SC(e,t,s){const o=e.chartArea.right,i=e.chartArea.left,n={};for(const r of e._metasets){if(fC(r.xAxisID))return;const a=e.scales[r.xAxisID].getPixelForValue(0);for(let e=0;e<r._parsed.length;e++){const l=Number(r._parsed[e].x);if(isNaN(l))continue;const c=t.callback(l,r,e),h=r.data[e],d=h.y,u=zb(s,c,{fontSize:12},"px"),g=3;let p;Math.abs(h.x-a)<u?p=l<0?a-u/2-g:a+u/2+g:(p=l<0?h.x+h.width/2:h.x-h.width/2,p=Math.min(p,o),p=Math.max(p,i)),n[d]||(n[d]=[]);for(const e of n[d])Math.abs(e-p)<u&&(p=l<0?e-u-g:e+u+g);n[d].push(p),s.fillStyle=h.options.backgroundColor,s.strokeStyle=t.background||"#ffffff",bC(c,p,d,s)}}}const CC={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}};function yC(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function IC(e){switch(typeof e){case"object":{if(null===e)return e;if(function(e){return"clone"in e&&e.clone instanceof Function}(e))return e.clone();if(!(function(e){return"object"==typeof e&&null!==e&&(e?.constructor===Object||void 0===e?.constructor)}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");const t=Array.isArray(e)?new Array(e.length):{};if(Array.isArray(e))for(let s=0,o=e.length;s<o;s++)s in e&&(t[s]=IC(e[s]));else for(const s in e)t[s]=IC(e[s]);return t}case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function wC(e,t,s=1){if(t<=e&&s>0)return[];if(0===s)throw new Error("range() step must not be zero");const o=Math.ceil(Math.abs((t-e)/s)),i=Array(o);for(let t=0;t<o;t++)i[t]=e+t*s;return i}function EC(e){return e.reduce((e,t,s,o)=>{if(1===Math.abs(t-o[s-1])){e[e.length-1].push(t)}else e.push([t]);return e},[])}function RC(e){return void 0!==e}function xC(...e){if(e.length<=1)return!0;for(let t=1;t<e.length;t++)if(!TC(e[0],e[t]))return!1;return!0}function TC(e,t){if(e===t)return!0;if(e&&!t||t&&!e)return!1;if(typeof e!=typeof t)return!1;if("object"!=typeof e)return!1;for(const s in t)if(!(s in e)&&void 0!==t[s])return!1;for(const s in e){if(typeof e[s]!=typeof t[s])return!1;if("object"==typeof e[s]){if(!TC(e[s],t[s]))return!1}else if(e[s]!==t[s])return!1}return!0}function AC(e){if(!e)return e;const t={...e};return Object.keys(t).forEach(e=>!t[e]&&delete t[e]),t}function DC(e){const t=new Map,s=e.name?e.name+" (memoized)":"memoized";return{[s]:(...s)=>(t.has(s[0])||t.set(s[0],e(...s)),t.get(s[0]))}[s]}function _C(e){return e.split("\n").map(e=>e.replace(/\s+/g," ").trim()).join("\n")}class OC{text;currentIndex=0;current;constructor(e){this.text=e,this.current=e[0]}shift(){const 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}}const FC="nullValue";function PC(e,t){const{dataSetsValues:s}=t,o=[],i=KC(e,s.length),n=[];for(const r in s){let{label:a,data:l,hidden:h}=s[r];a=e.dataSets?.[r].label||a;const d=i.next(),u={label:a,data:l,hidden:h,borderColor:e.background||c,borderWidth:e.stacked?1:0,backgroundColor:d,yAxisID:e.horizontal?"y":e.dataSets?.[r].yAxisId||"y",xAxisID:"x"};o.push(u);const g=e.dataSets?.[r].trend,p=t.trendDataSetsValues?.[r];g?.display&&!e.horizontal&&p&&n.push(YC(u,g,p))}return o.push(...n),o}function MC(e,t){const{dataSetsValues:s,labels:o}=t,i=e.negativeValuesColor||f,n=e.positiveValuesColor||m,r=e.subTotalValuesColor||v,a=[],l=[],c={label:"",data:l,backgroundColor:a},h=[];let d=0;for(const t of s)if(!t.hidden){for(let c=0;c<t.data.length;c++){const u=t.data[c];if(h.push(o[c]),isNaN(Number(u))){l.push([d,d]),a.push("");continue}l.push([d,u+d]);let g=u>=0?n:i;0===c&&t===s[0]&&e.firstValueAsSubtotal&&(g=r),a.push(g),d+=u}e.showSubTotals&&(h.push(fs("Subtotal")),l.push([0,d]),a.push(r))}return{datasets:[c],labels:h}}function NC(e,t){const{dataSetsValues:s,axisType:o,labels:i}=t,n=[],r=!!e.fillArea,a=!!e.stacked,l=[],c=KC(e,s.length);for(let h=0;h<s.length;h++){let{label:d,data:u,hidden:g}=s[h];d=e.dataSets?.[h].label||d;const p=c.next();o&&["linear","time"].includes(o)&&(u=u.map((e,t)=>({x:i[t]||void 0,y:e})));const m={label:d,data:u,hidden:g,tension:0,borderColor:p,backgroundColor:r?_v(p,.4):p,pointBackgroundColor:p,fill:!!r&&XC(h,a),pointRadius:e.hideDataMarkers?0:3,yAxisID:e.dataSets?.[h].yAxisId||"y"};n.push(m);const f=e.dataSets?.[h].trend,v=t.trendDataSetsValues?.[h];f?.display&&v&&l.push(YC(m,f,v))}return n.push(...l),n}function LC(e,t){const s=NC(e,t);for(const e of s)fC(e.xAxisID)||(e.showLine=!1);return s}function kC(e,t){const{dataSetsValues:s}=t,o=[],i=Math.max(0,...s.map(e=>e?.data?.length??0)),n=pC(new Gv(i),s);for(const{label:t,data:i,hidden:r}of s){if(r)continue;const s={label:t,data:i,borderColor:e.background||"#FFFFFF",backgroundColor:n,hoverOffset:10};o.push(s)}return o}function VC(e,t){const{dataSetsValues:s}=t,o=[],i=KC(e,s.length),n=[];for(let r=0;r<s.length;r++){let{label:a,data:l,hidden:c}=s[r];a=e.dataSets?.[r].label||a;const h=e.dataSets?.[r],d=i.next(),u=h?.type??"line",g={label:a,data:l,hidden:c,borderColor:d,backgroundColor:d,yAxisID:e.dataSets?.[r].yAxisId||"y",xAxisID:"x",type:u,order:"bar"===u?s.length+r:r,pointRadius:e.hideDataMarkers?0:3};o.push(g);const p=e.dataSets?.[r].trend,m=t.trendDataSetsValues?.[r];p?.display&&m&&n.push(YC(g,p,m))}return o.push(...n),o}function UC(e,t){const{dataSetsValues:s}=t,o=[],i=e.fillArea??!1,n=KC(e,s.length);for(let t=0;t<s.length;t++){let{label:r,data:a,hidden:l}=s[t];e.dataSets?.[t]?.label&&(r=e.dataSets[t].label);const c=n.next(),h={label:r,data:a,hidden:l,borderColor:c,backgroundColor:c,pointRadius:e.hideDataMarkers?0:3};i&&(h.backgroundColor=_v(c,.4),h.fill="start"),o.push(h)}return o}function HC(e,t){const{availableRegions:s,dataSetsValues:o,labels:i}=t,n=e.region||s[0]?.id,r=n?t.getGeoJsonFeatures(n):void 0,a={outline:r,showOutline:!!r,data:[]};if(r&&n){const e={};if(o[0])for(let s=0;s<o[0].data.length;s++){if(!i[s]||void 0===o[0].data[s])continue;const r=t.geoFeatureNameToId(n,i[s]);r&&(e[r]={value:o[0].data[s],label:i[s]})}for(const t of r)t.id&&a.data.push({feature:{...t,properties:{name:e[t.id]?.label}},value:e[t.id]?.value})}return[a]}function zC(e,t){const s=t.dataSetsValues[0],o=t.labels;if(!s)return[];let{label:i,data:n}=s;i=e.dataSets?.[0].label||i;return[{label:i,data:n.map(e=>e<=0?[0,0]:[-e,e]),backgroundColor:BC(o,e.funnelColors),yAxisID:"y",xAxisID:"x",barPercentage:1,categoryPercentage:1,borderColor:e.background||c,borderWidth:3}]}function BC(e,t){const s=new Gv(e.length,t);return e.map(()=>s.next())}function GC(e,t){const{dataSetsValues:s,labels:o}=t,i=qC(WC(s,o)),n=i[0]||[],r=new Gv(n.length,e.groupColors||[]),a=n.map(e=>({label:e.label,color:r.next()})),l=[];for(let t=i.length-1;t>=0;t--){const s={groupColors:a,parsing:{key:"value"},data:i[t],borderColor:t=>{const s="data"===t.type?t.raw:void 0;return s&&s.label!==FC?e.background||c:p},backgroundColor:e=>{const t="data"===e.type?e.raw:void 0;if(!t||t.label===FC)return p;const s=t.groups[0];return a.find(e=>e.label===s)?.color},hoverOffset:10};l.push(s)}return l}function WC(e,t){const s=function(e,t){const s=[],o=Math.max(...e.map(e=>e.data.length));for(let i=0;i<o;i++){s[i]={};for(let t=0;t<e.length;t++){const o=null===e[t].data[i]?FC:String(e[t].data[i]);s[i][t]=o}s[i].value=Number(t[i])}return s}(e,t);return $C(s,0,e.length,[])}function $C(e,t,s,o){if(t>=s)return[];const i=Object.groupBy(e,e=>e[t]);return Object.keys(i).map(e=>{const n=i[e]?.reduce((e,t)=>e+Number(t.value),0)||0,r=[...o,e];return{label:e,value:n,children:$C(i[e]||[],t+1,s,[...o,e]),groups:r,depth:t}}).sort((e,t)=>t.value-e.value)}function qC(e){const t=[],s=[...e];for(;s.length>0;){const e=s.shift();e&&(t[e.depth]||(t[e.depth]=[]),t[e.depth].push(e),e.children&&s.push(...e.children))}return t}function ZC(e,t){const{dataSetsValues:s,labels:o,locale:i,axisFormats:n}=t,r={locale:i,format:n?.y};if(0===s.length)return[];const a=WC(s,o).sort((e,t)=>t.value-e.value),l=function(e,t){const s="categoryColor"===e.coloringOptions?.type?e.coloringOptions.colors:[],o=new Gv(t.length,s);return t.map(e=>({label:e.label,color:o.next()}))}(e,a),c=[],h=Math.max(...s.map(e=>e.data.length));for(let e=0;e<h;e++){c[e]={};for(let t=0;t<s.length;t++)c[e][t]=s[t].data[e]?String(s[t].data[e]):void 0;c[e].value=Number(o[e])}const d=e.showLabels??CC.showLabels,u=e.showValues??CC.showValues,g=e.coloringOptions||CC.coloringOptions;let p;"colorScale"===g?.type&&(p=function(e,t){const s=qC(e),o=s[s.length-1],i=Math.min(...o.map(e=>e.value)),n=Math.max(...o.map(e=>e.value));if(Number.isFinite(i)&&Number.isFinite(n)){const e=[{value:i,color:t.minColor}];if(t.midColor){const s=(i+n)/2;e.push({value:s,color:t.midColor})}return e.push({value:n,color:t.maxColor}),qv(e)}return}(a,g));const m=[{data:[],tree:c,labels:{display:d||u,overflow:"hidden",...jC(e.valuesDesign,CC.valuesDesign),formatter:e=>[d?e.raw.g:void 0,u?pn(e.raw.v,r):void 0].filter(RC)},captions:{display:e.showHeaders??CC.showHeaders,padding:6,...jC(e.headerDesign,CC.headerDesign)},key:"value",groups:wC(0,s.length).map(e=>String(e)),borderWidth:0,spacing:1,displayMode:"headerBoxes",groupColors:l,backgroundColor:t=>{if("data"!==t.type)return"transparent";if(!t.raw.isLeaf)return e.headerDesign?.fillColor||CC.headerDesign?.fillColor;if("colorScale"===g.type)return p?.(t.raw.v)||"#FF0000";if("categoryColor"===g.type)return function(e,t,s,o){const i=e.raw._data.children[0][0],n=o.find(e=>e.label===i)?.color;if(!n||!s.useValueBasedGradient)return n||"#FF0000";const r=t.find(e=>e.label===i);if(!r||!r.children.length)return n;const a=qC(r.children),l=a[a.length-1],c=Math.max(...l.map(e=>e.value)),h=Math.min(...l.map(e=>e.value));if(h===c||!isFinite(h)||!isFinite(c))return n;const d=Number(e.raw.v)||0,u=(d-c)/(h-c)*.5;return Ov(n,u)}(t,a,g,l);throw new Error("Unsupported coloring option type}")}}];return m}function jC(e,t){const s=e=>Iv(e.element.options.backgroundColor)>.7?"#666666":"#FFFFFF";return{align:e?.align??t?.align,position:e?.verticalAlign??t?.verticalAlign,color:e?.color||s,hoverColor:e?.color||s,font:{weight:e?.bold??t?.bold?"bold":"normal",style:e?.italic??t?.italic?"italic":"normal",size:e?.fontSize??t?.fontSize}}}function YC(e,t,s){const o=Ev(e.backgroundColor);o.a=1;const i=t.color||Ov(wv(o),.5);return{type:"line",xAxisID:"trailingMovingAverage"===t.type?jS:ZS,yAxisID:e.yAxisID,label:e.label?fs("Trend line for %s",e.label):"",data:s,order:-1,showLine:!0,pointRadius:0,backgroundColor:i,borderColor:i,borderDash:[5,5],borderWidth:void 0,fill:!1,pointBackgroundColor:i}}function XC(e,t){return t?0===e?"origin":"-1":"origin"}function KC(e,t){return new Gv(t,e.dataSets?.map(e=>e.backgroundColor)||[])}const JC={id:"sunburstHoverPlugin",afterEvent(e,t,s){if(!s.enabled)return;const o=e.getActiveElements();let i=o.map(e=>({datasetIndex:e.datasetIndex,index:e.index}));for(const t of o){const s=e.data.datasets[t.datasetIndex].data[t.index];for(let t=0;t<e.data.datasets.length;t++){const o=e.data.datasets[t];for(let e=0;e<o.data.length;e++){const n=o.data[e];QC(s.groups,n.groups)&&i.push({datasetIndex:t,index:e})}}}i=i.filter(t=>{const{datasetIndex:s,index:o}=t;return e.data.datasets[s].data[o].label!==FC}),e.setActiveElements(i);for(const t of e.getSortedVisibleDatasetMetas())for(const e of t.data){const t=e.$context,{datasetIndex:s,index:o,dataset:n,raw:r}=t;if(r.label===FC)continue;const a="function"==typeof n.backgroundColor?n.backgroundColor(t):n.backgroundColor;i.length&&!i.some(e=>e.datasetIndex===s&&e.index===o)?e.options.backgroundColor=Ov(a,.5):e.options.backgroundColor=a}}};function QC(e,t){return t.length>e.length&&e.every((e,s)=>e===t[s])}const ey={id:"sunburstLabelsPlugin",afterDatasetsDraw(e,t,s){if(!s.showValues&&!s.showLabels||"doughnut"!==e.config.type)return;!function(e,t,s){const o=t.style,i=o.fontSize||13,n=i+3;for(const r of e._metasets)for(let a=0;a<r._dataset.data.length;a++){const l=r._dataset.data[a];if(l.label===FC)continue;const c=[t.showLabels?l.label:void 0,t.showValues?t.callback(l.value,"y"):void 0].filter(Te),h=r.data[a];let{startAngle:d,endAngle:u,innerRadius:g,outerRadius:p,circumference:m}=h;const f=h.options.offset/4,v=f*(1-Math.sin(Math.min(Math.PI,m||0)));g+=v,p+=v;const b=(d+u)/2,S=(g+p)/2,C=.9*(p-g),y=u-d;if((y>=Math.PI?p:Math.sin(y/2)*g*2)<c.length*n)continue;s.save();const I={x:Math.cos(b)*f,y:Math.sin(b)*f},w=e.chartArea.left+e.chartArea.width/2+I.x,E=e.chartArea.top+e.chartArea.height/2+I.y;let R;s.translate(w,E),b>Math.PI/2?(s.rotate(b-Math.PI),R=-S):(R=S,s.rotate(b));const x=Iv(h.options.backgroundColor)>.7?"#666666":"#FFFFFF";s.fillStyle=o.textColor||x,s.textAlign="center",s.textBaseline="middle",s.font=Ub(i,o.bold,o.italic);const T=-(c.length-1)*n/2;for(let e=0;e<c.length;e++){const t=eS(s,C,c[e],o,"px");s.fillText(t,R,T+e*n)}s.restore()}}(e,s,e.ctx)}};const ty={id:"waterfallLinesPlugin",beforeDraw(e,t,s){if(!s.showConnectorLines)return;const o=e._metasets?.[0]?.data;if(!o)return;const i=e.ctx;i.save(),i.setLineDash([3,2]);for(let e=0;e<o.length;e++){const t=o[e];if(0===t.height)continue;const s=oy(o,e);if(!s)break;const n=sy(t),r=sy(s),a=t.$context.raw,l=a[1]-a[0],c=Math.round(l<0?n.bottom-1:n.top),h=Math.round(n.right),d=Math.round(r.left);i.strokeStyle="#999",i.beginPath(),i.moveTo(h+1,c+.5),i.lineTo(d,c+.5),i.stroke()}i.restore()}};function sy(e){const 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 oy(e,t){return e.find((e,s)=>s>t&&0!==e.height)}sS.add("chartShowValuesPlugin",{register:e=>e.register(vC),unregister:e=>e.unregister(vC)}),sS.add("waterfallLinesPlugin",{register:e=>e.register(ty),unregister:e=>e.unregister(ty)}),sS.add("funnelController",{register:e=>e.register(nS()),unregister:e=>e.unregister(nS())}),sS.add("funnelElement",{register:e=>e.register(rS()),unregister:e=>e.unregister(rS())}),sS.add("funnelTooltipPositioner",{register:e=>e.Tooltip.positioners.funnelTooltipPositioner=lS,unregister:e=>e.Tooltip.positioners.funnelTooltipPositioner=void 0}),sS.add("sunburstLabelsPlugin",{register:e=>e.register(ey),unregister:e=>e.unregister(ey)}),sS.add("sunburstHoverPlugin",{register:e=>e.register(JC),unregister:e=>e.unregister(JC)});class iy extends t.Component{static template="o-spreadsheet-ChartJsComponent";static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=t.useRef("graphContainer");chart;currentRuntime;animationStore;currentDevicePixelRatio=window.devicePixelRatio;get background(){return this.chartRuntime.background}get canvasStyle(){return`background-color: ${this.background}`}get chartRuntime(){const e=this.env.model.getters.getChartRuntime(this.props.chartId);if(!("chartJsConfig"in e))throw new Error("Unsupported chart runtime");return e}setup(){this.shouldAnimate&&(this.animationStore=ev(iS)),t.onMounted(()=>{oS();const e=this.chartRuntime;this.currentRuntime=e,this.createChart(ae(e))}),t.onWillUnmount(this.unmount.bind(this)),t.useEffect(()=>{const e=this.chartRuntime;e!==this.currentRuntime?(e.chartJsConfig.type!==this.currentRuntime.chartJsConfig.type?(this.chart?.destroy(),this.createChart(ae(e))):this.updateChartJs(ae(e)),this.currentRuntime=e):this.currentDevicePixelRatio!==window.devicePixelRatio&&(this.currentDevicePixelRatio=window.devicePixelRatio,this.updateChartJs(ae(this.currentRuntime)))})}unmount(){this.chart?.destroy()}get shouldAnimate(){return this.env.model.getters.isDashboard()}createChart(e){let t=e.chartJsConfig;if(this.shouldAnimate&&this.animationStore){const e=this.env.model.getters.getChart(this.props.chartId)?.type;e&&this.animationStore.animationPlayed[this.animationChartId]!==e&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}const s=this.canvas.el.getContext("2d");this.chart=new window.Chart(s,t)}updateChartJs(e){let t=e.chartJsConfig;if(this.shouldAnimate){const e=this.env.model.getters.getChart(this.props.chartId)?.type;e&&this.hasChartDataChanged()&&this.animationStore&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}t.data&&t.data.datasets?(this.chart.data=t.data,t.options?.plugins?.title&&(this.chart.config.options.plugins.title=t.options.plugins.title)):this.chart.data.datasets=[],this.chart.config.options=t.options,this.chart.update()}hasChartDataChanged(){return!Me(this.getChartDataInRuntime(this.currentRuntime),this.getChartDataInRuntime(this.chartRuntime))}enableAnimationInChartData(e){return{...e,options:{...e.options,animation:{animateRotate:!0}}}}getChartDataInRuntime(e){const t=e.chartJsConfig.data;return{labels:t.labels,dataset:t.datasets.map(e=>({data:e.data,label:e.label,tree:e.tree}))}}get animationChartId(){return this.props.isFullScreen?this.props.chartId+"-fullscreen":this.props.chartId}}class ny{sheetId;title;getters;humanize;constructor(e,t,s){this.title=e.title,this.sheetId=t,this.getters=s,this.humanize=e.humanize??!0}static validateChartDefinition(e,t){throw new Error("This method should be implemented by sub class")}static transformDefinition(e,t,s){throw new Error("This method should be implemented by sub class")}static getDefinitionFromContextCreation(e){throw new Error("This method should be implemented by sub class")}getCommonDataSetAttributesForExcel(e,t,s){return{dataSets:t.map(e=>sC(this.getters,e)).filter(e=>""!==e.range&&e.range!==bs.InvalidReference),labelRange:oC(this.getters,e,s)}}}function ry(e,t,s,o,i){if("text"===t||"progress"===t||e?.type!==_d.number||s?.type!==_d.number)return;const n=s.value-e.value;return n>0?o:n<0?i:void 0}function ay(e,t,s){if("text"===s||e?.type!==_d.number||t?.type!==_d.number)return"neutral";const o=t.value-e.value;return o>0?"up":o<0?"down":"neutral"}function ly(e){return e.keyValue&&!Xn.test(e.keyValue)?"InvalidScorecardKeyValue":"Success"}function cy(e){return e.baseline&&!Xn.test(e.baseline)?"InvalidScorecardBaseline":"Success"}const hy=globalThis.Path2D,dy=hy&&new hy("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"),uy=hy&&new hy("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");let gy=class e extends ny{keyValue;keyDescr;baseline;baselineMode;baselineDescr;progressBar=!1;background;baselineColorUp;baselineColorDown;fontColor;humanize;type="scorecard";constructor(e,t,s){super(e,t,s),this.keyValue=Rb(s,t,e.keyValue),this.keyDescr=e.keyDescr,this.baseline=Rb(s,t,e.baseline),this.baselineMode=e.baselineMode,this.baselineDescr=e.baselineDescr,this.background=e.background,this.baselineColorUp=e.baselineColorUp??G,this.baselineColorDown=e.baselineColorDown??W,this.humanize=e.humanize??!0}static validateChartDefinition(e,t){return e.checkValidations(t,ly,cy)}static getDefinitionFromContextCreation(e){return{background:e.background,type:"scorecard",keyValue:e.range?e.range[0].dataRange:void 0,title:e.title||{text:""},baselineMode:B,baselineColorUp:G,baselineColorDown:W,baseline:e.auxiliaryRange||"",humanize:e.humanize}}static transformDefinition(e,t,s){let o,i;if(t.baseline){const i=$S(e,t.baseline,s);i!==bs.InvalidReference&&(o=i)}if(t.keyValue){const o=$S(e,t.keyValue,s);o!==bs.InvalidReference&&(i=o)}return{...t,baseline:o,keyValue:i}}duplicateInDuplicatedSheet(t){const s=JS(this.sheetId,t,this.baseline),o=JS(this.sheetId,t,this.keyValue),i=this.getDefinitionWithSpecificRanges(s,o,t);return new e(i,t,this.getters)}copyInSheetId(t){const s=this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,t);return new e(s,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,s){return{baselineColorDown:this.baselineColorDown,baselineColorUp:this.baselineColorUp,baselineMode:this.baselineMode,title:this.title,type:"scorecard",background:this.background,baseline:e?this.getters.getRangeString(e,s||this.sheetId):void 0,baselineDescr:this.baselineDescr,keyValue:t?this.getters.getRangeString(t,s||this.sheetId):void 0,keyDescr:this.keyDescr,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(t){const s=QS(this.baseline,t),o=QS(this.keyValue,t);if(this.baseline===s&&this.keyValue===o)return this;const i=this.getDefinitionWithSpecificRanges(s,o);return new e(i,this.sheetId,this.getters)}};function py(e,t){const s=t.getContext("2d");if(!s)throw new Error("Unable to retrieve 2D context from canvas");const o="number"==typeof globalThis.devicePixelRatio?globalThis.devicePixelRatio:1;t.width=o*e.canvas.width,t.height=o*e.canvas.height,s.scale(o,o);const i=e.canvas.width-E;if(s.fillStyle=e.canvas.backgroundColor,s.fillRect(0,0,e.canvas.width,e.canvas.height),e.title){s.font=e.title.style.font,s.fillStyle=e.title.style.color;const t=s.textBaseline;s.textBaseline="middle",s.fillText(Jb(s,e.title.text,i-e.title.position.x),e.title.position.x,e.title.position.y),s.textBaseline=t}if(e.baseline&&(s.font=e.baseline.style.font,s.fillStyle=e.baseline.style.color,Qb(s,e.baseline.text,e.baseline.position,e.baseline.style.underline,e.baseline.style.strikethrough)),e.baselineArrow&&e.baselineArrow.style.size>0&&hy){s.save(),s.fillStyle=e.baselineArrow.style.color,s.translate(e.baselineArrow.position.x,e.baselineArrow.position.y);const t=e.baselineArrow.style.size/10;switch(s.scale(t,t),e.baselineArrow.direction){case"down":s.fill(dy);break;case"up":s.fill(uy)}s.restore()}if(e.baselineDescr){const t=e.baselineDescr;s.font=t.style.font,s.fillStyle=t.style.color,s.fillText(Jb(s,t.text,i-t.position.x),t.position.x,t.position.y)}if(e.key&&(s.font=e.key.style.font,s.fillStyle=e.key.style.color,Qb(s,Jb(s,e.key.text,i-e.key.position.x),e.key.position,e.key.style.underline,e.key.style.strikethrough)),e.keyDescr){const t=e.keyDescr;s.font=e.keyDescr?.style.font??t.style.font,s.fillStyle=t.style.color,s.fillText(Jb(s,t.text,i-t.position.x),t.position.x,t.position.y)}if(e.progressBar){if(s.fillStyle=e.progressBar.style.backgroundColor,s.beginPath(),s.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width,e.progressBar.dimension.height,e.progressBar.dimension.height/2),s.fill(),s.fillStyle=e.progressBar.style.color,s.beginPath(),e.progressBar.value>0)s.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{const t=e.progressBar.dimension.width*Math.max(0,Math.min(1,-e.progressBar.value));s.roundRect(e.progressBar.position.x+e.progressBar.dimension.width-t,e.progressBar.position.y,t,e.progressBar.dimension.height,e.progressBar.dimension.height/2)}s.fill()}}function my(e,t){let s,o="";const i=t.getLocale();if(e.keyValue){const n={sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top};s=t.getEvaluatedCell(n),o=function(e,t,s){return e?t?Mn(e,s):e.formattedValue??String(e.value??""):""}(s,e.humanize??!0,i)}let n;const r=e.baseline;if(r){const e={sheetId:r.sheetId,col:r.zone.left,row:r.zone.top};n=t.getEvaluatedCell(e)}const{background:a,fontColor:l}=t.getStyleOfSingleCellChart(e.background,e.keyValue),c=function(e,t,s,o,i){if(!e)return"";if("text"===s||t?.type!==_d.number||e.type!==_d.number)return o?Mn(e,i):e.formattedValue;let{value:n,format:r}=e;return"progress"===s?(n=t.value/n,r="0.0%"):(n=Math.abs(t.value-n),"percentage"===s&&0!==n&&(n/=e.value),"percentage"===s&&(r="0.0%"),r||(n=Math.round(100*n)/100)),o?Mn({value:n,format:r},i):pn(n,{format:r,locale:i})}(n,s,e.baselineMode,e.humanize??!0,i),h="progress"===e.baselineMode&&lo(c,i)?bo(c,i):0;return{title:{...e.title,text:e.title.text?t.dynamicTranslate(e.title.text):""},keyValue:o,keyDescr:e.keyDescr?.text?t.dynamicTranslate(e.keyDescr.text):"",baselineDisplay:c,baselineArrow:ay(n,s,e.baselineMode),baselineColor:ry(n,e.baselineMode,s,e.baselineColorUp,e.baselineColorDown),baselineDescr:"progress"!==e.baselineMode&&e.baselineDescr?.text?t.dynamicTranslate(e.baselineDescr.text):"",fontColor:l,background:a,baselineStyle:{..."percentage"!==e.baselineMode&&"progress"!==e.baselineMode&&r?t.getCellComputedStyle({sheetId:r.sheetId,col:r.zone.left,row:r.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:"progress"===e.baselineMode?{value:h,color:h>0?e.baselineColorUp:e.baselineColorDown}:void 0}}const fy=.05;function vy(e,t){const s=e||"";return t&&s?" "+s:s}function by({width:e,height:t},s){return new Sy({width:e,height:t},s).computeDesign()}class Sy{runtime;context;width;height;constructor({width:e,height:t},s){if(this.runtime=s,this.width=e,this.height=t,"undefined"==typeof OffscreenCanvas)throw new Error("OffscreenCanvas is not supported in this environment");const o=new globalThis.OffscreenCanvas(e,t).getContext("2d");if(!o)throw new Error("Unable to create scorecard measurement context");this.context=o}computeDesign(){const e={canvas:{width:this.width,height:this.height,backgroundColor:this.backgroundColor}},t=this.getTextStyles();let s=0;if(this.title){let o,i;switch(({height:s,width:i}=this.getFullTextDimensions(this.title,t.title.font)),this.runtime.title.align){case"center":o=(this.width-i)/2;break;case"right":o=this.width-i-E;break;default:o=E}e.title={text:this.title,style:t.title,position:{x:o,y:10+s/2}}}const o=t.baselineArrow?.size??0;let{height:i,width:n}=this.getTextDimensions(this.baseline,t.baselineValue.font);this.baseline||(i=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).height);const r=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).width;let a;switch(this.runtime.baselineStyle?.align){case"right":a=this.width-E-r-n;break;case"left":a=E+o;break;default:a=(this.width-n-r+o)/2}if(this.baseline&&(e.baseline={text:this.baseline,style:t.baselineValue,position:{x:a,y:this.keyValue?this.height*(1-fy*(this.runtime.progressBar?1:2)):this.height-(this.height-s-i)/2-10}},t.baselineArrow&&!this.runtime.progressBar&&(e.baselineArrow={direction:this.baselineArrow,style:t.baselineArrow,position:{x:e.baseline.position.x-o,y:e.baseline.position.y-(i+o)/2}})),e.baseline&&this.baselineDescr){const s={x:e.baseline.position.x+n,y:e.baseline.position.y};e.baselineDescr={text:this.baselineDescr,style:t.baselineDescr,position:s}}let l=0;this.runtime.progressBar&&(l=.05*this.height,e.progressBar={position:{x:40,y:.9*this.height-i-l},dimension:{height:l,width:this.width-80},value:this.runtime.progressBar.value,style:{color:this.runtime.progressBar.color,backgroundColor:this.secondaryFontColor}});const{width:c,height:h}=this.getFullTextDimensions(this.keyValue,t.keyValue.font),d=this.getTextDimensions(this.keyDescr,t.keyDescr.font).width;let u;switch(this.runtime.keyValueStyle?.align){case"right":u=this.width-E-d-c;break;case"left":u=E;break;default:u=(this.width-c-d)/2}if(this.keyValue&&(e.key={text:this.keyValue,style:t.keyValue,position:{x:Math.max(E,u),y:.4*this.height+5+(s+h/2)/2}}),e.key&&this.keyDescr){const s={x:e.key.position.x+c,y:e.key.position.y};e.keyDescr={text:this.keyDescr,style:t.keyDescr,position:s}}return e}get title(){return this.runtime.title.text??""}get keyValue(){return this.runtime.keyValue}get keyDescr(){return vy(this.runtime.keyDescr,this.keyValue)}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){return vy(this.runtime.baselineDescr,this.baseline)}get baselineArrow(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get secondaryFontColor(){return rC(this.backgroundColor)}getTextDimensions(e,t){this.context.font=t;const s=this.context.measureText(e);return{width:s.width,height:s.actualBoundingBoxAscent+s.actualBoundingBoxDescent}}getFullTextDimensions(e,t){this.context.font=t;const s=this.context.measureText(e);return{width:s.width,height:s.fontBoundingBoxAscent+s.fontBoundingBoxDescent}}getTextStyles(){const e=this.runtime.keyValueStyle?.fontSize??32,t=Math.floor(.9*e);let s=this.runtime.baselineStyle?.fontSize??16;const o=Math.floor(.9*s);return this.runtime.progressBar&&(s/=1.5),{title:{font:Ub(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:Ub(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:Ub(t,this.runtime.keyValueDescrStyle?.bold,this.runtime.keyValueDescrStyle?.italic),strikethrough:this.runtime.keyValueDescrStyle?.strikethrough,underline:this.runtime.keyValueDescrStyle?.underline},baselineValue:{font:Ub(s,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:Ub(o,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:"neutral"===this.baselineArrow||this.runtime.progressBar?void 0:{size:this.keyValue?.8*s:0,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor}}}}class Cy extends t.Component{static template="o-spreadsheet-ScorecardChart";static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=t.useRef("chartContainer");get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}get title(){const e=this.env.model.getters.getChartDefinition(this.props.chartId).title.text;return e?this.env.model.getters.dynamicTranslate(e):""}setup(){t.useEffect(this.createChart.bind(this),()=>{const e=this.canvas.el.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}createChart(){const e=this.canvas.el;py(by(e.getBoundingClientRect(),this.runtime),e)}}function yy({strikethrough:e,underline:t}){return e||t?`${e?"line-through":""} ${t?"underline":""}`:"none"}function Iy(e){const t=wy(e);return e?(e.fillColor&&(t.background=e.fillColor),t):t}function wy(e){const t={};if(!e)return t;if(e.bold&&(t["font-weight"]="bold"),e.italic&&(t["font-style"]="italic"),e.fontSize&&(t["font-size"]=`${e.fontSize}px`),e.strikethrough||e.underline){let s=e.strikethrough?"line-through":"";s=e.underline?s+" underline":s,t["text-decoration"]=s}return e.textColor&&(t.color=e.textColor),t}function Ey(e){let t="";for(const s in e)e[s]&&(t+=`${s}:${e[s]}; `);return t}function Ry(e,t){const{scrollX:s,scrollY:o}=e.getActiveSheetScrollInfo(),i=e.getSheetViewDimension(),n=s+Math.max(0,(i.width-t.width)/2),r=o+Math.max(0,(i.height-t.height)/2);return e.getPositionAnchorOffset({x:n,y:r})}function xy(e,t){const s=ae(t),o=e.getSheetViewDimension(),i=o.width,n=o.height;if(s.width>i){const e=i/s.width;s.width=i,s.height=s.height*e}if(s.height>n){const e=n/s.height;s.height=n,s.width=s.width*e}return s}const Ty=/Mac/i,Ay=["Shift","Control","Alt","Meta"];function Dy(e,t){return!!e&&(!!t.target&&e.contains(t.target))}function _y(){const e=document.querySelector(".o-grid-overlay");if(e){const{top:t,left:s}=e.getBoundingClientRect();return{top:t,left:s}}throw new Error("Can't find spreadsheet position")}function Oy(e){return e.el?Fy(e.el):{x:0,y:0,width:0,height:0}}function Fy(e){const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function*Py(e){if(yield e,e.hasChildNodes())for(const t of e.childNodes)yield*Py(t)}function My(e){const{startElement:t,endElement:s,startSelectionOffset:o,endSelectionOffset:i}=function(e){const t=document.getSelection();return{startElement:t.anchorNode||e,startSelectionOffset:t.anchorOffset,endElement:t.focusNode||e,endSelectionOffset:t.focusOffset}}(e);return{start:Ny(e,t,o),end:Ny(e,s,i)}}function Ny(e,t,s){let o=0;const i=Py(e);let n=i.next(),r=!0;for(;!n.done&&n.value!==t;)n.value.hasChildNodes()||n.value.textContent&&(o+=n.value.textContent.length),("P"===n.value.nodeName||"DIV"===n.value.nodeName&&n.value!==e)&&(r?r=!1:o++),n=i.next();if(n.value!==t)return 0;if(n.value.hasChildNodes()){const e=[...n.value.childNodes].slice(0,s);o+=e.reduce((t,s,o)=>{if(null!==s.textContent){let i=s.textContent.length;return"P"===s.nodeName&&o!==e.length-1&&i++,t+i}return t},0)}else o+=s;return"P"!==t.nodeName||r||""!==t.textContent||o++,o}const Ly=/^[a-zA-Z]$/;function ky(e,t="key"){let s="";Ay.includes(e.key)||(Uy(e)&&(s+="Ctrl+"),e.altKey&&(s+="Alt+"),e.shiftKey&&(s+="Shift+"));const o="key"===t?e.key:e.code;return s+=Ly.test(o)?o.toUpperCase():o,s}function Vy(){return Boolean(Ty.test(navigator.userAgent))}function Uy(e){return Vy()||Gy()?e.metaKey:e.ctrlKey}function Hy(e){return 1===e.button||Uy(e)&&0===e.button}function zy(e,t){const s=document.createElement("a");s.href=e,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s)}function By(){return/Firefox/i.test(navigator.userAgent)}function Gy(){return/(iPad|iPhone|iPod)/i.test(navigator.userAgent)||"MacIntel"===navigator.platform&&(navigator.maxTouchPoints||1)>1}function Wy(){return/Android/i.test(navigator.userAgent)||Gy()||/(webOS|BlackBerry|Windows Phone)/i.test(navigator.userAgent)}const $y=new Og;function qy(e){const t=$y.getAll().sort((e,t)=>e.sequence-t.sequence);return function(s,o,i){const n=t.find(e=>e.match(o.type));if(!n)throw new Error(`No builder for this chart: ${o.type}`);return n.createChart(o,i,e)}}function Zy(e){const t=$y.getAll().sort((e,t)=>e.sequence-t.sequence);return function(s){const o=t.find(e=>e.match(s.type));if(!o)throw new Error("No runtime builder for this chart.");const i=o.getChartRuntime(s,e),n=s.getDefinition();if("chartJsConfig"in i&&/line|combo|bar|scatter|waterfall/.test(n.type)){const e=i.chartJsConfig;i.masterChartConfig=function(e){return{...e,data:{...e.data,datasets:e.data.datasets.filter(e=>!fC(e.xAxisID)).map(e=>({...e,pointRadius:0,showLine:!0}))},options:{...e.options,hover:{mode:null},plugins:{...e.options.plugins,title:{display:!1},legend:{display:!1},tooltip:{enabled:!1},chartShowValuesPlugin:void 0},layout:{padding:{...e.options.layout?.padding,top:5,bottom:10}},scales:{y:{...e.options.scales?.y,display:!1},y1:{...e.options.scales?.y1,display:!1},x:{...e.options.scales?.x,title:void 0,ticks:{...e.options.scales?.x?.ticks,callback:function(t){return mC(e.options.scales?.x?.ticks?.callback?.call(this,t),5)},padding:0,font:{size:9}}}}}}}(e)}return i}}function jy(e,t){const s=$y.getAll().find(e=>e.match(t.type));if(!s)throw new Error("Unknown chart type.");return s.validateChartDefinition(e,t)}function Yy(e,t,s){const o=$y.getAll().find(e=>e.match(t.type));if(!o)throw new Error("Unknown chart type.");return o.transformDefinition(e,t,s)}const Xy=12,Ky="#F3F2F1";function Jy(e,t,s){const o=s??function(e){if(e instanceof HTMLCanvasElement){const t=e.getBoundingClientRect();return{width:t.width,height:t.height}}return{width:e.width,height:e.height}}(e),i="number"==typeof globalThis.devicePixelRatio?globalThis.devicePixelRatio:1;e.width=o.width*i,e.height=o.height*i;const n=e.getContext("2d");if(!n)throw new Error("Unable to retrieve 2D context from canvas");n.scale(i,i);const r=function(e,t,s){const o=t.maxValue,i=t.minValue,n=iI(t,"animated"),r=function(e,t){const s=t?25:0,o=e.height-20-s-10,i=e.width-60;let n,r;i>2*o?(n=2*o,r=o):(n=i,r=i/2);const a=s+10+(o-r)/2;return{x:30+(i-n)/2,y:a,width:n,height:r}}(e,t.title.text),a=r.width/6,l=n?(n-i.value)/(o.value-i.value):0,c={x:e.width/2,y:r.y+r.height-r.height/12};let h=80;r.height<300&&(h*=r.height/300);const d=r.width/2,u=t.gaugeValue?.label||"-";zb(s,u,{fontSize:h},"px")>d&&(h=function(e,t,s,o=.25){let i=1;if(s(i)>e)return i;if(s(t)<e)return t;let n=(i+t)/2,r=s(n),a=0;for(;Math.abs(r-e)>o&&a<20;)r>=e?t=(i+t)/2:i=(i+t)/2,n=(i+t)/2,r=s(n),a++;return n}(d,h,e=>zb(s,u,{fontSize:e},"px")));const g={x:r.x+a/2,y:r.y+r.height+Xy},p={x:r.x+r.width-a/2,y:r.y+r.height+Xy},m=rC(t.background),f=function(e,t,s,o){const i=e.maxValue,n=e.minValue,r={x:t.x+t.width/2,y:t.y+t.height},a={fontSize:Xy},l=[],c=[];for(const h of e.inflectionValues){const e=(h.value-n.value)/(i.value-n.value),d=zb(o,h.label,a,"px"),u=Math.PI-Math.PI*e,g=oI(u,t.height+6,r.x,r.y,d+2,Xy),p=c.some(e=>sI(e,g))?Xy:0;c.push(g),l.push({rotation:u,label:h.label,fontSize:Xy,color:s,offset:p})}return l}(t,r,m,s);let v=0,b=0,S=0;t.title.text&&({width:b,height:S}=Wb(s,t.title.text,{fontSize:R,...t.title},"px"));switch(t.title.align){case"right":v=e.width-b-E;break;case"center":v=(e.width-b)/2;break;default:v=E}return{width:e.width,height:e.height,title:{label:t.title.text??"",fontSize:t.title.fontSize??R,textPosition:{x:v,y:15+S/2},color:t.title.color??m,bold:t.title.bold,italic:t.title.italic},backgroundColor:t.background,gauge:{rect:r,arcWidth:a,percentage:ue(l,0,1),color:Qy(t)},inflectionValues:f,gaugeValue:{label:u,textPosition:c,fontSize:h,color:m},minLabel:{label:t.minValue.label,textPosition:g,fontSize:Xy,color:m},maxLabel:{label:t.maxValue.label,textPosition:p,fontSize:Xy,color:m}}}({...o,x:0,y:0},t,n);!function(e,t){e.save(),e.fillStyle=t.backgroundColor,e.fillRect(0,0,t.width,t.height),e.restore()}(n,r),function(e,t){e.save();const s=t.gauge,o=s.rect.x+s.rect.width/2,i=s.rect.y+s.rect.height,n=s.rect.height-s.arcWidth/2;if(n<0)return;const r=1===s.percentage?0:Math.PI*(1+s.percentage);e.strokeStyle=Ky,e.beginPath(),e.lineWidth=s.arcWidth,e.arc(o,i,n,r,0),e.stroke(),e.strokeStyle=s.color,e.beginPath(),e.arc(o,i,n,Math.PI,r),e.stroke(),e.restore()}(n,r),function(e,t){const{x:s,y:o,width:i,height:n}=t.gauge.rect;for(const r of t.inflectionValues){e.save(),e.translate(s+i/2-.5,o+n-.5),e.rotate(Math.PI/2-r.rotation),e.lineWidth=2,e.strokeStyle=rC(t.backgroundColor)+"aa",e.beginPath(),e.moveTo(0,-(n-t.gauge.arcWidth)),e.lineTo(0,-n-3),e.stroke(),e.textAlign="center",e.font=`${r.fontSize}px ${k}`,e.fillStyle=r.color;const a=-n-6-r.offset;e.fillText(r.label,0,a),e.restore()}}(n,r),function(e,t){for(const s of[t.minLabel,t.maxLabel,t.gaugeValue])e.save(),e.textAlign="center",e.fillStyle=s.color,e.font=`${s.fontSize}px ${k}`,e.fillText(s.label,s.textPosition.x,s.textPosition.y),e.restore()}(n,r),function(e,t){e.save();const s=t.title;e.font=Ub(s.fontSize,s.bold,s.italic),e.textBaseline="middle",e.fillStyle=s.color,e.fillText(s.label,s.textPosition.x,s.textPosition.y),e.restore()}(n,r)}function Qy(e){const t=iI(e,"final");if(void 0===t)return Ky;for(let s=0;s<e.inflectionValues.length;s++){const o=e.inflectionValues[s];if("<"===o.operator&&t<o.value)return e.colors[s];if("<="===o.operator&&t<=o.value)return e.colors[s]}return e.colors.at(-1)}function eI(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 tI(e,t){const s=e.start,o=e.end,i=t.start,n=t.end;function r(e,t,s){return(s.y-e.y)*(t.x-e.x)>(t.y-e.y)*(s.x-e.x)}return r(s,i,n)!==r(o,i,n)&&r(s,o,i)!==r(s,o,n)}function sI(e,t){const s=eI(e),o=eI(t);for(const e of s)for(const t of o)if(tI(e,t))return!0;return!1}function oI(e,t,s,o,i,n){const r=Math.cos(e),a=Math.sin(e),l=r*t,c=a*t,h=a*(i/2),d=r*(i/2),u=r*(t+n),g=a*(t+n);return{bottomLeft:{x:l-h+s,y:o-(c+d)},bottomRight:{x:l+h+s,y:o-(c-d)},topRight:{x:u+h+s,y:o-(g-d)},topLeft:{x:u-h+s,y:o-(g+d)}}}function iI(e,t){return"animated"===t&&void 0!==e.animationValue?e.animationValue:e.gaugeValue?.value}const nI={responsive:!0,maintainAspectRatio:!1,elements:{line:{fill:!1},point:{hitRadius:15}},animation:!1,events:["mousemove","mouseout","click","touchstart","touchmove","mouseup"]};async function rI(e,t,s){const o=cI(t.width,t.height);let i;if("chartJsConfig"in e){const t=ae(e.chartJsConfig);t.plugins=[lI];const s=new globalThis.Chart(o,t);try{i=await dI(o)}finally{s.destroy()}}else{if(!globalThis.OffscreenCanvas)throw new Error(`converting a ${s} chart to an image using OffscreenCanvas is not supported in this environment`);if("scorecard"===s){py(by(t,e),o),i=await dI(o)}else"gauge"===s&&(Jy(o,e,t),i=await dI(o))}return i}async function aI(e,t,s){const o=cI(t.width,t.height);let i=null;if("chartJsConfig"in e){const t=ae(e.chartJsConfig);t.plugins=[lI];const s=new globalThis.Chart(o,t);try{i=await hI(o)}finally{s.destroy()}}else{if(!globalThis.OffscreenCanvas)throw new Error(`converting a ${s} chart to an image using OffscreenCanvas is not supported in this environment`);if("scorecard"===s){py(by(t,e),o),i=await hI(o)}else"gauge"===s&&(Jy(o,e,t),i=await hI(o))}return i}const lI={id:"customCanvasBackgroundColor",beforeDraw:e=>{const{ctx:t}=e;t.save(),t.globalCompositeOperation="destination-over",t.fillStyle="#ffffff",t.fillRect(0,0,e.width,e.height),t.restore()}};function cI(e,t){return new OffscreenCanvas(e,t)}async function hI(e){return"convertToBlob"in e?e.convertToBlob({type:"image/png"}):new Promise(t=>e.toBlob(t,"image/png"))}async function dI(e){const t=await hI(e);if(t){if(!URL.createObjectURL)throw new Error("URL.createObjectURL is not supported in this environment");return URL.createObjectURL(t)}}function uI(e){return 8===(e=bv(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}var gI;!function(e){e.PlainText="text/plain",e.Html="text/html",e.Image="image"}(gI||(gI={}));const pI=new Set(["containsText","notContainsText","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","beginsWithText","endsWithText","isNotEmpty","isEmpty","isNotEqual","isEqual","customFormula"]),mI=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"]),fI="(previous)",vI="(next)";new Set(["containsText","notContainsText","isEqualText","dateIs","dateIsBefore","dateIsOnOrBefore","dateIsAfter","dateIsOnOrAfter","dateIsBetween","dateIsNotBetween","isEqual","isNotEqual","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","customFormula","beginsWithText","endsWithText","isNotEmpty","isEmpty"]);const bI=["containsText","notContainsText","isEqualText","isEmpty","isNotEmpty","beginsWithText","endsWithText"],SI=["isEqual","isNotEqual","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","isEmpty","isNotEmpty"],CI=["dateIs","dateIsBefore","dateIsOnOrBefore","dateIsAfter","dateIsOnOrAfter","dateIsBetween","dateIsNotBetween","isEmpty","isNotEmpty"],yI={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},II=function(e){return Math.floor(e/yI.second)},wI=function(e){return Math.floor(e/yI.minute)},EI=function(e){return Math.floor(e/yI.hour)},RI=function(e){return Math.floor(e/yI.day)},xI=function(e){return Math.floor(e/yI.month)},TI=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function AI(e,t,s){const o=function(e){const t=e.indexOf("h");e=t>=0?e.slice(0,t).replace(/m/g,"M")+e.slice(t):e.replace(/m/g,"M");e.includes("a")||(e=e.replace(/h/g,"H"));return e}(t),i=function(e,t,s){const o=e.map(e=>Zs(e,s)?.jsDate);if(o.some(e=>void 0===e)||e.length<2)return;const i=o.map(e=>e.getTime()),n=Ke(i)-Je(i),r=function(e){if(e.includes("s"))return"second";if(e.includes("m"))return"minute";if(e.includes("h")||e.includes("H"))return"hour";if(e.includes("d"))return"day";if(e.includes("M"))return"month";return"year"}(t);if(yI.second>=yI[r]&&II(n)<180)return"second";if(yI.minute>=yI[r]&&wI(n)<180)return"minute";if(yI.hour>=yI[r]&&EI(n)<96)return"hour";if(yI.day>=yI[r]&&RI(n)<90)return"day";if(yI.month>=yI[r]&&xI(n)<36)return"month";return"year"}(e,o,s),n={};return i&&(n[i]=o),{parser:o,displayFormats:n,unit:i??!1,tooltipFormat:o}}function DI(e,t,s,o){let i=jI(o,t,s).formattedValues,n=XI(o,t);cC(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=$I(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=qI(i,n));const r=YI(o,t,"left"),a=YI(o,t,"right"),l=e.horizontal?{x:r||a}:{y:r,y1:a},c=[];for(const t in n){const{data:s}=n[t],o=e.dataSets?.[t].trend;if(!o?.display||e.horizontal){c.push(void 0);continue}const i=kI(o,s);c.push(i)}return{dataSetsValues:n,trendDataSetsValues:c,axisFormats:l,labels:i,locale:o.getLocale(),topPadding:JI(e,o)}}function _I(e,t,s,o){const i=DI(e,t.slice(0,2),s,o),n=i.dataSetsValues.filter(e=>!e.hidden),r=[];if(n[0]){const e=n[0].data.map(e=>e>0?e:0);r.push({...n[0],data:e})}if(n[1]){const e=n[1].data.map(e=>e>0?-e:0);r.push({...n[1],data:e})}return{...i,dataSetsValues:r}}function OI(e,t,s,o){const i=function(e,t,s,o){if(function(e,t,s,o){return!e.labelsAsText&&zI(e,t,s,o)}(e,t,s,o)&&function(){if(!window.Chart)return!1;const e="luxon"===new window.Chart._adapters._date({})._id;e||GI||(GI=!0,console.warn("'chartjs-adapter-luxon' time adapter is not installed. Time scale axes are disabled."));return e}())return"time";if(function(e,t,s,o){return!e.labelsAsText&&BI(e,t,s,o)}(e,t,s,o))return"linear";return"category"}(e,t,s,o),n=jI(o,t,s);let r="linear"===i?n.values:n.formattedValues,a=XI(o,t);const l=cC(s,t[0],e.dataSetsHaveTitle||!1);l&&r.shift(),({labels:r,dataSetsValues:a}=$I(r,a)),"time"===i&&({labels:r,dataSetsValues:a}=function(e,t){if(0===e.length||e.every(e=>!e))return{labels:e,dataSetsValues:t};const s=[...e],o=ae(t);for(let e=0;e<s.length;e++)if(!s[e]){s[e]=Fe(s,e);for(const t of o)t.data[e]=void 0}return{labels:s,dataSetsValues:o}}(r,a)),e.aggregated&&({labels:r,dataSetsValues:a}=qI(r,a)),e.cumulative&&(a=KI(a,"asc"));const c={y:YI(o,t,"left"),y1:YI(o,t,"right"),x:ZI(o,s,l)},h=[];for(const t in a){const s=e.dataSets?.[t].trend;if(!s?.display){h.push(void 0);continue}const{data:n}=a[t];h.push(VI(s,n,r,i,o.getLocale()))}return{dataSetsValues:a,axisFormats:c,labels:r,locale:o.getLocale(),trendDataSetsValues:h,axisType:i,topPadding:JI(e,o)}}function FI(e,t,s,o){let i=jI(o,t,s).formattedValues,n=XI(o,t);cC(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=$I(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=qI(i,n)),({dataSetsValues:n,labels:i}=function(e,t){const s=Math.max(e.length,...t.map(e=>e.data?.length||0)),o=ge(0,s).filter(e=>t.some(t=>"number"==typeof t.data[e]&&t.data[e]>0));return{labels:o.map(t=>e[t]||""),dataSetsValues:t.map(e=>({...e,data:o.map(t=>"number"==typeof e.data[t]&&e.data[t]>0?e.data[t]:null)}))}}(i,n));return{dataSetsValues:n,axisFormats:{y:YI(o,t,"left")},labels:i,locale:o.getLocale(),topPadding:JI(e,o)}}function PI(e,t,s,o){let i=jI(o,t,s).formattedValues,n=XI(o,t);cC(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=$I(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=qI(i,n));return{dataSetsValues:n,axisFormats:{r:YI(o,t,"left")||YI(o,t,"right")},labels:i,locale:o.getLocale()}}function MI(e,t,s,o){const i=t.slice(0,1);let n=jI(o,i,s).formattedValues;cC(s,i[0],e.dataSetsHaveTitle||!1)&&n.shift();let r=XI(o,i);({labels:n,dataSetsValues:r}=qI(n,r));return{dataSetsValues:r,axisFormats:{y:YI(o,i,"left")||YI(o,i,"right")},labels:n,locale:o.getLocale(),availableRegions:o.getGeoChartAvailableRegions(),geoFeatureNameToId:o.geoFeatureNameToId,getGeoJsonFeatures:o.getGeoJsonFeatures}}function NI(e,t,s,o){let i=jI(o,t,s).formattedValues,n=XI(o,t);cC(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=$I(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=qI(i,n)),e.cumulative&&(n=KI(n,"desc"));return{dataSetsValues:n,axisFormats:{x:YI(o,t,"left")||YI(o,t,"right")},labels:i,locale:o.getLocale()}}function LI(e,t,s,o){let i=jI(o,t,s).values,n=function(e,t){t=t.filter(t=>!e.isColHidden(t.dataRange.sheetId,t.dataRange.zone.left));const s=t.map(()=>({data:[],label:""})),o=t.map(t=>WI(e,t));if(!o.length)return s;const i=Math.min(...o.map(e=>e.length));let n=[];const r=t.length-1;for(let e=0;e<i;e++)for(let t=0;t<o.length;t++){let i=o[t][e];null==i&&t!==r&&(i=n[t]),i!==n[t]&&(n=n.slice(0,t),n[t]=i),s[t].data.push(i??null)}return s.filter(e=>e.data.some(e=>null!==e))}(o,t);const r=cC(s,t[0],e.dataSetsHaveTitle||!1);return r&&i.shift(),({labels:i,dataSetsValues:n}=function(e,t){const s=[],o=[];for(let t=0;t<e.length;t++)Number(e[t])<=0?o.push(t):Number(e[t])>0&&s.push(t);const i=s.length?s:o;return{labels:i.map(t=>e[t]),dataSetsValues:t.map(e=>({...e,data:i.map(t=>e.data[t])}))}}(i,n)),({labels:i,dataSetsValues:n}=function(e,t){const s=Math.max(e.length,...t.map(e=>e.data?.length||0)),o=e=>null==e||""===e,i=ge(0,s).filter(s=>{const i=t.map(e=>e.data?.[s]);if(o(i[0]))return!1;let n=!1;for(const e of i)if(n||=o(e),n&&!o(e))return!1;return e[s]&&!isNaN(Number(e[s]))});return{labels:i.map(t=>e[t]),dataSetsValues:t.map(e=>({...e,data:i.map(t=>e.data[t])}))}}(i,n)),{dataSetsValues:n,axisFormats:{y:ZI(o,s,r)},labels:i,locale:o.getLocale()}}function kI(e,t){const s=[],o=[],i=[];for(let e=0;e<t.length;e++)"number"==typeof t[e]&&(s.push(t[e]),o.push(e+1)),i.push(e+1);const n=UI(e,s,o,ge(.5,i.length+.55,.2));return n.length?n:void 0}function VI(e,t,s,o,i){const n=[],r=[],a=[],l=t.length;if(l<2)return;switch(o){case"category":for(let e=0;e<l;e++)"number"==typeof t[e]&&(n.push(t[e]),r.push(e+1)),a.push(e+1);break;case"linear":for(let e=0;e<t.length;e++){const o=Number(s[e]);isNaN(o)||("number"==typeof t[e]&&(n.push(t[e]),r.push(o)),a.push(o))}break;case"time":for(let e=0;e<t.length;e++){const o=bo({value:s[e]},i);null!==t[e]&&(n.push(t[e]),r.push(o)),a.push(o)}}const c=Math.min(...a),h=Math.max(...a);if(h===c)return;const d=(h-c)/(5*a.length),u=UI(e,n,r,ge(c,h+d/2,d));return u.length?u:void 0}function UI(e,t,s,o){if(t.length<2||s.length<2||0===o.length)return[];const{normalizedLabels:i,normalizedNewLabels:n}=function(e,t,s){let o=[],i=[];if("logarithmic"===s.type){const s=Math.max(...e.map(Math.abs));o=e.map(e=>e/s),i=t.map(e=>e/s)}else{const s=Math.max(...e),n=Math.min(...e),r=s-n;o=e.map(e=>(e-s)/r),i=t.map(e=>(e-s)/r)}return{normalizedLabels:o,normalizedNewLabels:i}}(s,o,e);try{switch(e.type){case"polynomial":{const s=e.order;if(!s)return o.map(e=>({x:e,y:NaN}));if(1===s)return tl([t],[i],[n],!0)[0].map((e,t)=>({x:o[t],y:e}));const r=Xa(t,i,s,!0).flat();return n.map((e,t)=>({x:o[t],y:Ja(r,e,s)}))}case"exponential":{const e=[],s=[];for(let o=0;o<t.length;o++)t[o]>0&&(e.push(Math.log(t[o])),s.push(i[o]));return s.length?Qa(tl([e],[s],[n],!0))[0].map((e,t)=>({x:o[t],y:e})):o.map(e=>({x:e,y:NaN}))}case"logarithmic":return tl([t],el([i]),el([n]),!0)[0].map((e,t)=>({x:o[t],y:e}));case"trailingMovingAverage":return function(e,t,s=2){const o=[];for(let e=0;e<s-1;e++)o.push({x:t[e],y:NaN});for(let i=0;i<=e.length-s;i++){let n=0;for(let t=i;t<i+s;t++)n+=e[t];o.push({x:t[i+s-1],y:n/s})}return o}(t,s,e.window);default:return o.map(e=>({x:e,y:NaN}))}}catch(e){return o.map(e=>({x:e,y:NaN}))}}function HI(e,t,s,o){return zI(e,t,s,o)||BI(e,t,s,o)}function zI(e,t,s,o){if(!s||!BI(e,t,s,o))return!1;const i=ZI(o,s,cC(s,t[0],e.dataSetsHaveTitle||!1));return Boolean(i&&TI.test(i))}function BI(e,t,s,o){if(!s)return!1;const i=o.getRangeValues(s);return cC(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),!i.some(e=>isNaN(Number(e))&&e)&&!i.every(e=>!e)}let GI=!1;function WI(e,t){if(t.dataRange){const s=t.labelCell?[t.labelCell.zone]:[],o=ft([t.dataRange.zone],s)[0];if(void 0===o)return[];const i=e.getRangeFromZone(t.dataRange.sheetId,o);return e.getRangeValues(i).map(e=>""===e?void 0:e)}return[]}function $I(e,t){const s=ge(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(s=>{const o=e[s],i=t.map(e=>e.data?.[s]);return o||i.some(e=>"number"==typeof e)});return{labels:s.map(t=>e[t]||""),dataSetsValues:t.map(e=>({...e,data:s.map(t=>"number"==typeof e.data[t]?e.data[t]:null)}))}}function qI(e,t){const s=e=>"number"==typeof e?e:0,o=new Set(e),i={};o.forEach(e=>{i[e]=new Array(t.length).fill(0)});for(const o of ge(0,e.length)){const n=e[o];for(const e of ge(0,t.length))i[n][e]+=s(t[e].data[o])}return{labels:Array.from(o),dataSetsValues:t.map((e,t)=>({...e,data:Array.from(o).map(e=>i[e][t])}))}}function ZI(e,t,s){if(!t)return;const{sheetId:o,zone:i}=t,n=Bt(i).map(t=>e.getEvaluatedCell({sheetId:o,...t}).format);return s&&n.shift(),n.find(e=>void 0!==e)}function jI(e,t,s){let o={values:[],formattedValues:[]};if(s){const{left:i}=s.zone;if(s.invalidXc||s.invalidSheetName||e.isColHidden(s.sheetId,i)){if(t[0]){o={formattedValues:ge(0,WI(e,t[0]).length).map(e=>e.toString()),values:o.formattedValues}}}else o={formattedValues:e.getRangeFormattedValues(s),values:e.getRangeValues(s).map(e=>String(e??""))}}else if(1===t.length){const s=WI(e,t[0]).length;for(let e=0;e<s;e++)o.formattedValues.push(""),o.values.push("")}else if(t[0]){o={formattedValues:ge(0,WI(e,t[0]).length).map(e=>e.toString()),values:o.formattedValues}}return o}function YI(e,t,s){const o=t.filter(e=>"right"===s==!!e.rightYAxis);for(const t of o){const s=e.getRangeFormats(t.dataRange).find(e=>void 0!==e&&!wn(e));if(s)return s}}function XI(e,t){const s=[];for(const[o,i]of Object.entries(t)){let t=`${Ig.Series} ${parseInt(o)+1}`,n=e.isColHidden(i.dataRange.sheetId,i.dataRange.zone.left);if(i.labelCell){const{sheetId:s,zone:o}=i.labelCell,n=e.getEvaluatedCell({sheetId:s,col:o.left,row:o.top});n&&(t=n.formattedValue)}let r=i.dataRange?WI(e,i):[];r.every(e=>!e||"string"==typeof e&&!mo(e))&&r.filter(e=>"string"==typeof e).length>1?r=r.map(e=>e&&!mo(e)?1:null):r.every(e=>null==e||!lo(e.toString(),Oc))&&(n=!0),s.push({data:r,label:t,hidden:n})}return s}function KI(e,t){return e.map(e=>{const s=[];let o=0;const i="asc"===t?Object.keys(e.data):Object.keys(e.data).reverse();for(const t of i)isNaN(parseFloat(e.data[t]))?s[t]=e.data[t]:(o+=parseFloat(e.data[t]),s[t]=o);return{...e,data:s}})}function JI(e,t){const{title:s,legendPosition:o}=e,i=s&&s.text||"top"===o;return t.isDashboard()&&!i?30:0}function QI(e,t){return{padding:{left:E,right:E,top:Math.max(15,t.topPadding||0),bottom:10}}}function ew(e,t){return{display:"none"!==e.legendPosition,position:"none"!==e.legendPosition?e.legendPosition:void 0}}function tw(e,t){return{...cw,...ew(e),...hw(nC(e.background),{pointStyle:"rect",lineWidth:3})}}function sw(e,t){const s=e.fillArea,o=s?"rect":"line",i=s?2:3;return{...cw,...ew(e),...hw(nC(e.background),{pointStyle:o,lineWidth:i})}}function ow(e,t){const{dataSetsValues:s}=t,o=Math.max(0,...s.map(e=>e?.data?.length??0)),i=pC(new Gv(o),s),n=nC(e.background);return{...ew(e),labels:{usePointStyle:!0,generateLabels:e=>(e.data.labels?.map((e,t)=>({text:mC(String(e)),strokeStyle:i[t],fillStyle:i[t],pointStyle:"rect",lineWidth:2,fontColor:n}))||[]).filter(e=>e.text),filter:(e,t)=>!("datasetIndex"in e)||!t.datasets[e.datasetIndex].hidden}}}function iw(e,t){return{...cw,...ew(e),...hw(nC(e.background),{pointStyle:"circle",strokeStyle:e.background||"#ffffff",lineWidth:8})}}function nw(e,t){return{...cw,...ew(e),...hw(nC(e.background),{lineWidth:3})}}function rw(e,t){const s=nC(e.background),o=e.negativeValuesColor||f,i=e.positiveValuesColor||m,n=e.subTotalValuesColor||v;return{...ew(e),labels:{usePointStyle:!0,generateLabels:()=>{const t=[{text:fs("Positive values"),fontColor:s,fillStyle:i,strokeStyle:i,pointStyle:"rect"},{text:fs("Negative values"),fontColor:s,fillStyle:o,strokeStyle:o,pointStyle:"rect"}];return(e.showSubTotals||e.firstValueAsSubtotal)&&t.push({text:fs("Subtotals"),fontColor:s,fillStyle:n,strokeStyle:n,pointStyle:"rect"}),t},filter:(e,t)=>!("datasetIndex"in e)||!t.datasets[e.datasetIndex].hidden},onClick:()=>{}}}function aw(e,t){const s=e.fillArea??!1,o=s?"rect":"line",i=s?2:3;return{...cw,...ew(e),...hw(nC(e.background),{pointStyle:o,lineWidth:i})}}function lw(e,t){const s=nC(e.background);return{...ew(e),labels:{usePointStyle:!0,generateLabels:e=>{const t=e.data.datasets.at(-1);if(!t)return[];return t.groupColors.map(({color:e,label:t})=>({text:mC(t),fontColor:s,fillStyle:e,strokeStyle:e,pointStyle:"rect"}))}}}}const cw={onHover:e=>{const t=e.native?.target;t&&(t.style.cursor="pointer")},onLeave:e=>{const t=e.native?.target;t&&(t.style.cursor="default")},onClick:(e,t,s)=>{if("click"!==e.type)return;const o=t.datasetIndex;s.legendItems&&void 0!==o&&(s.chart.isDatasetVisible(o)?s.chart.hide(o):s.chart.show(o),e.native.preventDefault(),e.native.stopPropagation())}};function hw(e,t){return{labels:{color:e,usePointStyle:!0,generateLabels:s=>s.data.datasets.map((o,i)=>fC(o.xAxisID)?{text:mC(o.label),fontColor:e,strokeStyle:o.borderColor,hidden:!s.isDatasetVisible(i),pointStyle:"line",datasetIndex:i,lineWidth:3}:{text:mC(o.label),fontColor:e,strokeStyle:o.borderColor,fillStyle:o.backgroundColor,hidden:!s.isDatasetVisible(i),pointStyle:"line"===o.type?"line":"rect",datasetIndex:i,...t}).filter(e=>e.text),filter:(e,t)=>!("datasetIndex"in e)||!t.datasets[e.datasetIndex].hidden}}}function dw(e,t){let s={};const{trendDataSetsValues:o,locale:i,axisFormats:n}=t,r={stacked:e.stacked,locale:i};if(e.horizontal)s.x=yw(e,"bottom","values",{...r,format:n?.x}),s.y=yw(e,"left","labels",r);else{s.x=yw(e,"bottom","labels",r);const t={...r,format:n?.y};s.y=yw(e,"left","values",t);const o={...r,format:n?.y1};s.y1=yw(e,"right","values",o)}if(s=AC(s),o&&o.length&&o.some(RC)){const e=Math.max(...o.map(e=>e?.length||0));s[ZS]={...s.x,labels:Array(e).fill(""),offset:!1,display:!1},s[jS]={...s.x,offset:!0,display:!1}}return s}function uw(e,t){const{locale:s,axisType:o,trendDataSetsValues:i,labels:n,axisFormats:r}=t,a=r?.x,l=e.stacked;let c={x:yw(e,"bottom","labels",{locale:s}),y:yw(e,"left","values",{locale:s,stacked:l,format:r?.y}),y1:yw(e,"right","values",{locale:s,stacked:l,format:r?.y1})};if(c=AC(c),"time"===o&&n&&a){const e={type:"time",time:AI(n,a,s)};Object.assign(c.x,e),c.x.ticks.maxTicksLimit=15,delete c?.x?.ticks?.callback}else"linear"===o&&(c.x.type="linear",c.x.ticks.callback=e.humanize?e=>Mn({value:e,format:a},s):e=>pn(e,{format:a,locale:s}));if(i&&i.length&&i.some(RC)&&(c[ZS]={...c.x,display:!1},c[jS]={...c.x,display:!1},"category"===o||"time"===o)){const e=Math.max(...i.map(e=>e?.length||0));c[ZS].type="category",c[ZS].labels=wC(0,e).map(e=>e.toString()),c[ZS].offset=!1,c[jS].type="category",c[jS].offset=!1}return c}function gw(e,t){const s=uw(e,t);return{...s,x:{...s.x,grid:{display:!0}}}}function pw(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;e.dataSets;const n={x:{...yw(e,"bottom","labels",{locale:s}),grid:{display:!1}},y:{position:e.verticalAxisPosition,ticks:{color:nC(e.background),callback:uC({locale:s,format:i},e.humanize)},grid:{lineWidth:e=>0===e.tick.value?2:1},title:Cw(e.axesDesign?.y)}},r=n?.y||n?.y1;return r&&(r.grid={lineWidth:e=>0===e.tick.value?2:1}),n}function mw(e,t){const{dataSetsValues:s}=t,o=dw(e,t),i=o.x.ticks.callback;o.x.ticks.callback=e=>i(Math.abs(e));const n=Math.max(...s.map(e=>Math.max(...e.data.map(Math.abs))));return o.x.suggestedMin=-n,o.x.suggestedMax=n,o}function fw(e,t){const{locale:s,axisFormats:o,dataSetsValues:i}=t,n=Math.min(...i.map(e=>Math.min(...e.data.filter(e=>!isNaN(e)))));return{r:{beginAtZero:!0,ticks:{callback:uC({format:o?.r,locale:s},e.humanize),backdropColor:e.background||"#FFFFFF"},pointLabels:{color:nC(e.background),callback:e=>mC(e)},suggestedMin:n<0?n-1:0}}}function vw(e,t){const{locale:s,axisFormats:o,availableRegions:i}=t,n=function(e){switch(e){case"top":return"top-left";case"right":return"top-right";case"bottom":return"bottom-right";case"left":case"none":return"bottom-left"}}(e.legendPosition),r=e.region?i.find(t=>t.id===e.region):i[0],a=o?.y||o?.y1;return{projection:{projection:Sw(r?.defaultProjection||"mercator"),axis:"x"},color:{axis:"x",display:"none"!==e.legendPosition,border:{color:S},grid:{color:S},ticks:{color:nC(e.background),callback:uC({locale:s,format:a},e.humanize)},legend:{position:n,align:n.includes("right")?"left":"right",margin:ww(e)},interpolate:Iw(e),missing:e.missingValueColor||"#ffffff"}}}function bw(e,t){const s=t.dataSetsValues[0];return{x:{display:!1},y:{grid:{offset:!1},ticks:{callback:function(e){return mC(this.getLabelForValue(e))}},border:{display:!1}},percentages:{position:"right",border:{display:!1},ticks:{callback:function(e,o,i){const n=s.data?.[o],r=s.data?.[0];return r&&void 0!==n?pn(n/r,{format:"0%",locale:t.locale}):""}},grid:{display:!1}}}}function Sw(e){return"conicConformal"===e?window.ChartGeo.geoConicConformal().rotate([100,0]):e}function Cw(e){if(e?.title?.text){const{text:t,color:s,align:o,italic:i,bold:n}=e.title;return{display:!0,text:t,color:s,font:{style:i?"italic":"normal",weight:n?"bold":"normal",size:e.title.fontSize??12},align:"left"===o?"start":"right"===o?"end":"center"}}}function yw(e,t,s,o){const{useLeftAxis:i,useRightAxis:n}=hC(e);if("left"===t&&!i||"right"===t&&!n)return;const r=nC(e.background);let a;if(a="bottom"===t?e.axesDesign?.x:"left"===t?e.axesDesign?.y:e.axesDesign?.y1,"values"===s){const s=!("right"===t&&i);return{position:t,title:Cw(a),grid:{display:s},beginAtZero:!0,stacked:o?.stacked,ticks:{color:r,callback:uC(o,e.humanize)}}}return{ticks:{padding:5,color:r,callback:function(e,t,s){return mC(this.getLabelForValue(e))}},grid:{display:!1},stacked:o?.stacked,title:Cw(a)}}function Iw(e){if(!e.colorScale||"string"==typeof e.colorScale)return e.colorScale||"oranges";const t=[{value:0,color:e.colorScale.minColor}];return e.colorScale.midColor&&t.push({value:.5,color:e.colorScale.midColor}),t.push({value:1,color:e.colorScale.maxColor}),qv(t)}function ww(e){switch(e.legendPosition){case"top":case"right":return{top:!!e.title.text?45:15,left:E,right:E};case"bottom":case"left":case"none":return{left:E,right:E,bottom:10}}}const Ew={showValues:!1,showLabels:!0,valuesDesign:{align:"center",fontSize:13}};function Rw(e,t){const{axisFormats:s,locale:o}=t;return{horizontal:"horizontal"in e&&e.horizontal,showValues:"showValues"in e&&!!e.showValues,background:e.background,callback:(t,i)=>{const n=function(e,t){if(t.rAxisID)return t.rAxisID;const s="horizontal"in e&&e.horizontal?t.xAxisID:t.yAxisID;return s||"y"}(e,i);return dC(s,o,e.humanize)(t,n)}}}function xw(e,t){const{axisFormats:s,locale:o}=t;return{callback:dC(s,o,e.humanize),showLabels:e.showLabels??Ew.showLabels,showValues:e.showValues??Ew.showValues,style:{fontSize:e.valuesDesign?.fontSize??Ew.valuesDesign.fontSize,align:e.valuesDesign?.align??Ew.valuesDesign.align,bold:e.valuesDesign?.bold??Ew.valuesDesign.bold,italic:e.valuesDesign?.italic??Ew.valuesDesign.italic,textColor:e.valuesDesign?.color??Ew.valuesDesign.color}}}function Tw(e,t){const{axisFormats:s,locale:o}=t;return{horizontal:!0,showValues:"showValues"in e&&!!e.showValues,background:e.background,callback:(e,t)=>0===(e=Math.abs(Number(e)))?"":dC(s,o)(e,t.xAxisID||"x")}}function Aw(e,t){const{axisFormats:s,locale:o,dataSetsValues:i}=t,n=i.reduce((e,t)=>(e.push((e.at(-1)||-1)+t.data.length+1),e),[]);return{showValues:"showValues"in e&&!!e.showValues,background:e.background,callback:(t,i,r)=>{const a=i._dataset.data[r],l=a[1]-a[0];let c=l>=0?"+":"";return e.showSubTotals&&n.includes(r)&&"+"===c&&(c=""),`${c}${dC(s,o,e.humanize)(l,i.yAxisID)}`}}}function Dw(e,t){const s=e.title,o=rC(e.background);return{display:!!s.text,text:s.text?t.dynamicTranslate(s.text):"",color:s?.color??o,align:"center"===s.align?"center":"right"===s.align?"end":"start",font:{size:e.title.fontSize??R,weight:s.bold?"bold":"normal",style:s.italic?"italic":"normal"},padding:{bottom:"top"===e.legendPosition?0:E}}}const _w='\n<templates>\n <t t-name="o-spreadsheet-CustomTooltip">\n <div\n class="o-chart-custom-tooltip border rounded px-2 py-1 pe-none mw-100 position-absolute text-nowrap shadow opacity-100">\n <table class="overflow-hidden m-0">\n <thead t-if="title">\n <tr>\n <th class="o-tooltip-title align-baseline border-0 text-truncate" t-esc="title" t-attf-style="max-width: {{ labelsMaxWidth }}"/>\n </tr>\n </thead>\n <tbody>\n <tr t-foreach="tooltipItems" t-as="tooltipItem" t-key="tooltipItem_index">\n <td>\n <span\n class="badge ps-2 py-2 rounded-0 align-middle"\n t-attf-style="background-color: {{ tooltipItem.boxColor }}"\n > </span>\n <small\n t-if="tooltipItem.label"\n class="o-tooltip-label d-inline-block text-truncate align-middle smaller ms-2"\n t-esc="tooltipItem.label"\n t-attf-style="max-width: {{ labelsMaxWidth }}"\n />\n </td>\n <td class="o-tooltip-value ps-2 fw-bolder text-end">\n <small class="smaller d-inline-block text-truncate align-middle" t-attf-style="max-width: {{ valuesMaxWidth }}">\n <t t-esc="tooltipItem.value"/>\n <t t-if="tooltipItem.percentage">\n (\n <t t-esc="tooltipItem.percentage"/>\n %)\n </t>\n </small>\n </td>\n </tr>\n </tbody>\n </table>\n </div>\n </t>\n</templates>\n';let Ow;function Fw(e,s={}){return function(e,s={}){Ow||(Ow=new t.App(t.Component,{templates:_w,translateFn:fs}));const o=Ow.getTemplate(e),i=o(s,{}),n=document.createElement("div");return t.blockDom.mount(i,n),n}(e,s).innerHTML}function Pw(e,t){return{enabled:!1,external:Gw,callbacks:{title:function(e){return e.some(e=>!fC(e.dataset.xAxisID))?void 0:""},beforeLabel:e=>e.dataset?.label||e.label,label:function(s){const o=e.horizontal;let i=o?s.parsed.x:s.parsed.y;null==i&&(i=s.parsed);const n=o?s.dataset.xAxisID:s.dataset.yAxisID;return dC(t.axisFormats,t.locale,e.humanize)(i,n)}}}}function Mw(e,t){const{axisType:s,locale:o,axisFormats:i}=t,n=i?.x,r={enabled:!1,external:Gw,callbacks:{}};return r.callbacks.label="linear"===s?t=>{const s=t.parsed.y;let r=fC(t.dataset.xAxisID)?"":t.parsed.x;"string"==typeof r&&lo(r,o)&&(r=bo(r,o));const a=gn(r,n,o,e.humanize),l=t.dataset.yAxisID||"y",c=gn(s,i?.[l],o,e.humanize);return a?`(${a}, ${c})`:`${c}`}:function(t){const s=t.parsed.y,n=t.dataset.yAxisID;return dC(i,o,e.humanize)(s,n)},r.callbacks.beforeLabel=e=>e.dataset?.label||e.label,r.callbacks.title=function(e){return"linear"!==s&&e.some(e=>!fC(e.dataset.xAxisID))?void 0:""},r}function Nw(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;return{enabled:!1,external:Gw,callbacks:{title:function(e){return e[0].dataset.label},beforeLabel:e=>e.label||e.dataset.label,label:function(t){const o=function(e,t){const s=e.filter(e=>"number"==typeof e).reduce((e,t)=>e+t,0);if(!s)return"";const o=e[t]/s*100;return o.toFixed(2)}(t.dataset.data,t.dataIndex),n=t.parsed.y??t.parsed;return`${gn(n,!i&&n>=1e3?"#,##":i,s,e.humanize)} (${o}%)`}}}}function Lw(e,t){const{dataSetsValues:s,locale:o,axisFormats:i,labels:n}=t,r=i?.y||i?.y1,a=s.map(e=>e.label);return{enabled:!1,external:Gw,callbacks:{beforeLabel:function(e){const t=n.length?Math.floor(e.dataIndex/n.length):0;return a[t]},label:function(t){const[s,i]=t.raw,n=i-s;return gn(n,!r&&Math.abs(n)>1e3?"#,##":r,o,e.humanize)}}}}function kw(e,t){const s=Pw(e,t);return{...s,callbacks:{...s.callbacks,label:e=>{const t={...e,parsed:{y:e.parsed.y,x:Math.abs(e.parsed.x)}};return(s?.callbacks?.label)(t)}}}}function Vw(e,t){const{locale:s,axisFormats:o}=t;return{enabled:!1,external:Gw,callbacks:{beforeLabel:e=>e.dataset?.label||e.label,label:function(t){return gn(t.parsed.r,o?.r,s,e.humanize)}}}}function Uw(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;return{enabled:!1,external:Gw,filter:function(e){return void 0!==e.raw.value},callbacks:{beforeLabel:e=>e.raw.feature.properties.name,label:function(t){const o=t.raw.value;return gn(o,!i&&Math.abs(o)>=1e3?"#,##":i,s,e.humanize)}}}}function Hw(e,t){return{enabled:!1,external:Gw,position:"funnelTooltipPositioner",callbacks:{title:()=>"",beforeLabel:e=>e.label,label:function(s){const o=s.parsed.x,i=s.dataset.xAxisID;return dC(t.axisFormats,t.locale,e.humanize)(o,i)}}}}function zw(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;return{enabled:!1,external:Gw,filter:function(e){const t=e.raw;return t?.label!==FC},callbacks:{title:()=>"",beforeLabel:e=>e.raw.groups.join(" / "),label:function(t){const o=t.raw.value;return gn(o,!i&&o>=1e3?"#,##":i,s,e.humanize)}}}}function Bw(e,t){const{locale:s,axisFormats:o}=t,i=o?.y;return{enabled:!1,external:Gw,filter:(e,t,s)=>t===s.length-1,callbacks:{title:()=>"",beforeLabel:e=>{const t=e.raw._data.children[0];if(!t)return"";const s=[];for(let o=0;o<=e.raw.l;o++)s.push(t[o]);return s.join(" / ")},label:t=>{const o=t.raw.v;return gn(o,!i&&o>=1e3?"#,##":i,s,e.humanize)}}}}function Gw({chart:e,tooltip:t}){if(e.canvas.parentNode.querySelector("div.o-chart-custom-tooltip")?.remove(),0===t.opacity||0===t.dataPoints.length)return;const s=t.body.map((e,s)=>{let o=e.before[0],i=e.lines[0];i||(i=o,o="");const n=t.labelColors[s].backgroundColor;return{label:o,value:i,boxColor:"string"==typeof n?_v(n,1):n}}),o=Fw("o-spreadsheet-CustomTooltip",{labelsMaxWidth:Math.floor(.5*e.canvas.clientWidth)+"px",valuesMaxWidth:Math.floor(.25*e.canvas.clientWidth)+"px",title:t.title[0],tooltipItems:s}),i=Object.assign(document.createElement("template"),{innerHTML:o}).content.firstChild;e.canvas.parentNode?.appendChild(i),Object.assign(i.style,{left:Ww(e,t,i.clientWidth)+"px",top:Math.floor(t.caretY-i.clientHeight/2)+"px"})}function Ww(e,t,s){const o=t.caretX;return o+s>e.chartArea.right?Math.max(0,o-s):o}var $w=Object.freeze({__proto__:null,GHOST_SUNBURST_VALUE:FC,INTERACTIVE_LEGEND_CONFIG:cw,canChartParseLabels:HI,getBarChartData:DI,getBarChartDatasets:PC,getBarChartLegend:tw,getBarChartScales:dw,getBarChartTooltip:Pw,getChartColorsGenerator:KC,getChartLabelFormat:ZI,getChartLayout:QI,getChartShowValues:Rw,getChartTitle:Dw,getComboChartDatasets:VC,getComboChartLegend:nw,getData:WI,getFunnelChartData:NI,getFunnelChartDatasets:zC,getFunnelChartScales:bw,getFunnelChartTooltip:Hw,getFunnelLabelColors:BC,getGeoChartData:MI,getGeoChartDatasets:HC,getGeoChartScales:vw,getGeoChartTooltip:Uw,getHierarchalChartData:LI,getLineChartData:OI,getLineChartDatasets:NC,getLineChartLegend:sw,getLineChartScales:uw,getLineChartTooltip:Mw,getPieChartData:FI,getPieChartDatasets:kC,getPieChartLegend:ow,getPieChartTooltip:Nw,getPyramidChartData:_I,getPyramidChartScales:mw,getPyramidChartShowValues:Tw,getPyramidChartTooltip:kw,getRadarChartData:PI,getRadarChartDatasets:UC,getRadarChartLegend:aw,getRadarChartScales:fw,getRadarChartTooltip:Vw,getScatterChartDatasets:LC,getScatterChartLegend:iw,getScatterChartScales:gw,getSunburstChartDatasets:GC,getSunburstChartLegend:lw,getSunburstChartTooltip:zw,getSunburstShowValues:xw,getTopPaddingForDashboard:JI,getTreeMapChartDatasets:ZC,getTreeMapChartTooltip:Bw,getTrendDatasetForBarChart:kI,getTrendDatasetForLineChart:VI,getWaterfallChartLegend:rw,getWaterfallChartScales:pw,getWaterfallChartShowValues:Aw,getWaterfallChartTooltip:Lw,getWaterfallDatasetAndLabels:MC,makeDatasetsCumulative:KI});class qw extends ny{dataSets;labelRange;background;legendPosition;stacked;aggregated;type="bar";dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal;showValues;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,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.axesDesign=e.axesDesign,this.horizontal=e.horizontal,this.showValues=e.showValues,this.zoomable=e.zoomable}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}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:"bar",labelRange:e.auxiliaryRange||void 0,axesDesign:e.axesDesign,showValues:e.showValues,horizontal:e.horizontal,zoomable:e.zoomable,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new qw(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new qw(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"bar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated,axesDesign:this.axesDesign,horizontal:this.horizontal,showValues:this.showValues,zoomable:this.horizontal?void 0:this.zoomable,humanize:this.humanize}}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,cC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:uI(this.background||c),fontColor:uI(nC(this.background)),dataSets:e,labelRange:t,verticalAxis:hC(s)}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new qw(i,this.sheetId,this.getters)}}function Zw(e,t){const s=e.getDefinition(),o=DI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:PC(s,o)},options:{...nI,indexAxis:e.horizontal?"y":"x",layout:QI(0,o),scales:dw(s,o),plugins:{title:Dw(s,t),legend:tw(s),tooltip:Pw(s,o),chartShowValuesPlugin:Rw(s,o)}}},background:e.background||c}}class jw{scope;code="";constructor(e=new Xw){this.scope=e}append(...e){this.code+=e.map(e=>e.toString()).join("\n")+"\n"}return(e){return new Yw(this.scope,this.code,e)}toString(){return Kw(this.code)}}class Yw{scope;returnExpression;code;constructor(e,t,s){this.scope=e,this.returnExpression=s,this.code=Kw(t)}toString(){return this.code}assignResultToVariable(){if(this.scope.isAlreadyDeclared(this.returnExpression))return this;const e=this.scope.nextVariableName(),t=new jw(this.scope);return t.append(this.code),t.append(`const ${e} = ${this.returnExpression};`),t.return(e)}}class Xw{nextId=1;declaredVariables=new Set;nextVariableName(){const e="_"+this.nextId++;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}}function Kw(e){let t="",s=0;const o=e.split("\n").map(e=>e.trim()).filter(e=>""!==e);for(const e of o)e.startsWith("}")&&s--,t+="\t".repeat(s)+e+"\n",e.endsWith("{")&&s++;return t.trim()}const Jw=uf.content,Qw={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},eE={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"},tE={};function sE(e){return oE(Sf(e))}function oE(e){try{return function(e){const{dependencies:t,literalValues:s,symbols:o}=function(e){const t={numbers:[],strings:[]},s=[],o=[];for(const i of e)switch(i.type){case"INVALID_REFERENCE":case"REFERENCE":s.push(i.value);break;case"STRING":const e=ce(i.value);t.strings.push({value:e});break;case"NUMBER":{const e=ho(i.value,Oc);t.numbers.push({value:e});break}case"SYMBOL":o.push(ce(i.value,"'"))}return{dependencies:s,literalValues:t,symbols:o}}(e),i=function(e){let t="";for(const s of e)switch(s.type){case"STRING":t+="|S|";break;case"NUMBER":t+="|N|";break;case"REFERENCE":case"INVALID_REFERENCE":s.value.includes(":")?t+="|R|":t+="|C|";break;case"SPACE":break;default:t+=s.value}return t}(e);if(!tE[i]){const r=_f([...e]),a=new Xw;let l=0,c=0,h=0;if("BIN_OPERATION"===r.type&&":"===r.value)throw new ys(fs("Invalid formula"));if("EMPTY"===r.type)throw new ys(fs("Invalid formula"));const d=m(r),u=new jw;u.append(`// ${i}`),u.append(d),u.append(`return ${d.returnExpression};`);const g=new Function("deps","ref","range","getSymbolValue","ctx",u.toString());function p(e){const{args:t}=e,s=e.value.toUpperCase(),o=Jw[s];if(!o)throw new Rs(fs('Unknown function: "%s"',e.value));!function(e){const t=e.args.length,s=e.value.toUpperCase(),o=Jw[s],{nbrArgRepeating:i,minArgRequired:n}=o;if(t<n)throw new ys(fs("Invalid number of arguments for the %(functionName)s function. Expected %(minArgRequired)s minimum, but got %(nbrArgSupplied)s instead.",{functionName:s,minArgRequired:n,nbrArgSupplied:t}));if(t>o.maxArgPossible)throw new ys(fs("Invalid number of arguments for the %(functionName)s function. Expected %(maxArgPossible)s maximum, but got %(nbrArgSupplied)s instead.",{functionName:s,maxArgPossible:o.maxArgPossible,nbrArgSupplied:t}));if(i>1){const e=t-n-i*Math.floor((t-n)/i)-o.nbrArgOptional;if(e>0)throw new ys(fs("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:s,nbrArgRepeating:i,nbrArgOptional:o.nbrArgOptional,nbrValueRemaining:e}))}}(e);const i=[],n=cs(o,t.length);for(let e=0;e<t.length;e++){const s=o.args[n(e)??-1],r=t[e],a=s.type||[],l=a.includes("META")||a.includes("RANGE<META>"),c=a.some(e=>iE(e));i.push(m(r,l,c))}return i}function m(e,t=!1,s=!1){const i=new jw(a);if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&t)throw new ys(fs("Argument must be a reference to a cell or range."));switch(e.debug&&(i.append("debugger;"),i.append('ctx["debug"] = true;')),e.type){case"BOOLEAN":return i.return(`{ value: ${e.value} }`);case"NUMBER":return i.return(`this.literalValues.numbers[${c++}]`);case"STRING":return i.return(`this.literalValues.strings[${l++}]`);case"REFERENCE":return i.return(`${e.value.includes(":")||s?"range":"ref"}(deps[${h++}], ${t?"true":"false"})`);case"FUNCALL":const n=p(e).map(e=>e.assignResultToVariable());i.append(...n);const r=e.value.toUpperCase();return i.return(`ctx['${r}'](${n.map(e=>e.returnExpression)})`);case"UNARY_OPERATION":{const t=eE[e.value],s=m(e.operand,!1,!1).assignResultToVariable();return i.append(s),i.return(`ctx['${t}'](${s.returnExpression})`)}case"BIN_OPERATION":{const t=Qw[e.value],s=m(e.left,!1,!1).assignResultToVariable(),o=m(e.right,!1,!1).assignResultToVariable();return i.append(s),i.append(o),i.return(`ctx['${t}'](${s.returnExpression}, ${o.returnExpression})`)}case"SYMBOL":const a=o.indexOf(e.value);return i.return(`getSymbolValue(this.symbols[${a}])`);case"EMPTY":return i.return("undefined")}}tE[i]=g}const n={execute:tE[i],dependencies:t,literalValues:s,symbols:o,tokens:e,isBadExpression:!1,normalizedFormula:i};return n}(e)}catch(t){return{tokens:e,dependencies:[],execute:function(){return t},isBadExpression:!0,normalizedFormula:e.map(e=>e.value).join("")}}}function iE(e){return e.startsWith("RANGE")}class nE{listeners=[];async sendMessage(e){for(const{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)}}class rE{transportService;constructor(e){this.transportService=e}async sendMessage(e){"CLIENT_JOINED"!==e.type&&"CLIENT_LEFT"!==e.type&&"CLIENT_MOVED"!==e.type||this.transportService.sendMessage(e)}onNewMessage(e,t){this.transportService.onNewMessage(e,t)}leave(e){this.transportService.leave(e)}}const aE=new class extends Og{addTransformation(e,t,s){this.content[e]||(this.content[e]=new Map);for(const o of t)this.content[e].set(o,s);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}};const lE=new class extends Og{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}},cE={light:fs("Light"),medium:fs("Medium"),dark:fs("Dark"),custom:fs("Custom")},hE={hasFilters:!1,totalRow:!1,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,automaticAutofill:!0,styleId:"TableStyleMedium2"};function dE(e,t){return{coloredText:Fv(t,.3),light:Ov(t,.8),medium:Ov(t,.6),dark:Fv(t,.3),mediumBorder:Ov(t,.45),highlight:t,name:e}}const uE={black:{name:fs("Black"),coloredText:"#000000",light:"#D9D9D9",medium:"#A6A6A6",dark:"#404040",mediumBorder:"#000000",highlight:"#000000"},lightBlue:dE(fs("Light blue"),"#346B90"),red:dE(fs("Red"),"#C53628"),lightGreen:dE(fs("Light green"),"#748747"),purple:dE(fs("Purple"),"#6C4E65"),gray:{name:fs("Gray"),coloredText:"#666666",light:"#EEEEEE",medium:"#DDDDDD",dark:"#767676",mediumBorder:"#D0D0D0",highlight:"#A9A9A9"},orange:dE(fs("Orange"),"#C37034")},gE={black:uE.black,orangeBlue:{...uE.lightBlue,highlight:uE.orange.highlight},purpleGreen:{...uE.lightGreen,highlight:uE.purple.highlight},redBlue:{...uE.lightBlue,highlight:uE.red.highlight}},pE=e=>({category:"light",templateName:"lightColoredText",primaryColor:e.highlight,wholeTable:{style:{textColor:e.coloredText},border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"}}},headerRow:{border:{bottom:{color:e.highlight,style:"thin"}}},totalRow:{border:{top:{color:e.highlight,style:"thin"}}},firstRowStripe:{style:{fillColor:e.light}}}),mE=e=>({category:"light",templateName:"lightWithHeader",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"},left:{color:e.highlight,style:"thin"},right:{color:e.highlight,style:"thin"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"},border:{bottom:{color:e.highlight,style:"thin"}}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{border:{bottom:{color:e.highlight,style:"thin"}}},secondRowStripe:{border:{bottom:{color:e.highlight,style:"thin"}}}}),fE=e=>({category:"light",templateName:"lightAllBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"},left:{color:e.highlight,style:"thin"},right:{color:e.highlight,style:"thin"},horizontal:{color:e.highlight,style:"thin"},vertical:{color:e.highlight,style:"thin"}}},headerRow:{border:{bottom:{color:e.highlight,style:"medium"}}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{style:{fillColor:e.light}},firstColumnStripe:{style:{fillColor:e.light}}}),vE=e=>({category:"medium",templateName:"mediumBandedBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.mediumBorder,style:"thin"},bottom:{color:e.mediumBorder,style:"thin"},left:{color:e.mediumBorder,style:"thin"},right:{color:e.mediumBorder,style:"thin"},horizontal:{color:e.mediumBorder,style:"thin"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{style:{fillColor:e.light}},firstColumnStripe:{style:{fillColor:e.light}}}),bE=e=>({category:"medium",templateName:"mediumWhiteBorders",primaryColor:e.highlight,wholeTable:{border:{horizontal:{color:"#FFFFFF",style:"thin"},vertical:{color:"#FFFFFF",style:"thin"}},style:{fillColor:e.light}},headerRow:{border:{bottom:{color:"#FFFFFF",style:"thick"}},style:{fillColor:e.highlight,textColor:"#FFFFFF"}},totalRow:{border:{top:{color:"#FFFFFF",style:"thick"}},style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},lastColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),SE=e=>({category:"medium",templateName:"mediumMinimalBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:"#000000",style:"medium"},bottom:{color:"#000000",style:"medium"}}},totalRow:{border:{top:{color:"#000000",style:"medium"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"},border:{bottom:{color:"#000000",style:"medium"}}},firstColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},lastColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstRowStripe:{style:{fillColor:uE.black.light}},firstColumnStripe:{style:{fillColor:uE.black.light}}}),CE=e=>({category:"medium",templateName:"mediumAllBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.mediumBorder,style:"thin"},bottom:{color:e.mediumBorder,style:"thin"},left:{color:e.mediumBorder,style:"thin"},right:{color:e.mediumBorder,style:"thin"},horizontal:{color:e.mediumBorder,style:"thin"},vertical:{color:e.mediumBorder,style:"thin"}},style:{fillColor:e.light}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),yE=e=>({category:"dark",templateName:"dark",primaryColor:e.highlight,wholeTable:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},totalRow:{style:{fillColor:e.dark,textColor:"#FFFFFF"},border:{top:{color:"#FFFFFF",style:"thick"}}},headerRow:{style:{fillColor:"#000000"},border:{bottom:{color:"#FFFFFF",style:"thick"}}},firstColumn:{style:{fillColor:e.dark},border:{right:{color:"#FFFFFF",style:"thick"}}},lastColumn:{style:{fillColor:e.dark},border:{left:{color:"#FFFFFF",style:"thick"}}},firstRowStripe:{style:{fillColor:e.dark}},firstColumnStripe:{style:{fillColor:e.dark}}}),IE=e=>({category:"dark",templateName:"darkNoBorders",primaryColor:e.highlight,wholeTable:{style:{fillColor:e.light}},totalRow:{border:{top:{color:"#000000",style:"medium"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),wE=yE(uE.black);wE.wholeTable.style.fillColor="#737373";const EE=SE(uE.black);function RE(e,t,s){return{...t(s),displayName:`${s.name}, ${e}`}}EE.wholeTable.border={...EE.wholeTable.border,left:{color:"#000000",style:"thin"},right:{color:"#000000",style:"thin"},horizontal:{color:"#000000",style:"thin"},vertical:{color:"#000000",style:"thin"}};const xE={None:{category:"light",templateName:"none",primaryColor:"",displayName:"none"},TableStyleLight1:RE("TableStyleLight1",pE,uE.black),TableStyleLight2:RE("TableStyleLight2",pE,uE.lightBlue),TableStyleLight3:RE("TableStyleLight3",pE,uE.red),TableStyleLight4:RE("TableStyleLight4",pE,uE.lightGreen),TableStyleLight5:RE("TableStyleLight5",pE,uE.purple),TableStyleLight6:RE("TableStyleLight6",pE,uE.gray),TableStyleLight7:RE("TableStyleLight7",pE,uE.orange),TableStyleLight8:RE("TableStyleLight8",mE,uE.black),TableStyleLight9:RE("TableStyleLight9",mE,uE.lightBlue),TableStyleLight10:RE("TableStyleLight10",mE,uE.red),TableStyleLight11:RE("TableStyleLight11",mE,uE.lightGreen),TableStyleLight12:RE("TableStyleLight12",mE,uE.purple),TableStyleLight13:RE("TableStyleLight13",mE,uE.gray),TableStyleLight14:RE("TableStyleLight14",mE,uE.orange),TableStyleLight15:RE("TableStyleLight15",fE,uE.black),TableStyleLight16:RE("TableStyleLight16",fE,uE.lightBlue),TableStyleLight17:RE("TableStyleLight17",fE,uE.red),TableStyleLight18:RE("TableStyleLight18",fE,uE.lightGreen),TableStyleLight19:RE("TableStyleLight19",fE,uE.purple),TableStyleLight20:RE("TableStyleLight20",fE,uE.gray),TableStyleLight21:RE("TableStyleLight21",fE,uE.orange),TableStyleMedium1:RE("TableStyleMedium1",vE,uE.black),TableStyleMedium2:RE("TableStyleMedium2",vE,uE.lightBlue),TableStyleMedium3:RE("TableStyleMedium3",vE,uE.red),TableStyleMedium4:RE("TableStyleMedium4",vE,uE.lightGreen),TableStyleMedium5:RE("TableStyleMedium5",vE,uE.purple),TableStyleMedium6:RE("TableStyleMedium6",vE,uE.gray),TableStyleMedium7:RE("TableStyleMedium7",vE,uE.orange),TableStyleMedium8:RE("TableStyleMedium8",bE,uE.black),TableStyleMedium9:RE("TableStyleMedium9",bE,uE.lightBlue),TableStyleMedium10:RE("TableStyleMedium10",bE,uE.red),TableStyleMedium11:RE("TableStyleMedium11",bE,uE.lightGreen),TableStyleMedium12:RE("TableStyleMedium12",bE,uE.purple),TableStyleMedium13:RE("TableStyleMedium13",bE,uE.gray),TableStyleMedium14:RE("TableStyleMedium14",bE,uE.orange),TableStyleMedium15:{...EE,displayName:"Black, TableStyleMedium15"},TableStyleMedium16:RE("TableStyleMedium16",SE,uE.lightBlue),TableStyleMedium17:RE("TableStyleMedium17",SE,uE.red),TableStyleMedium18:RE("TableStyleMedium18",SE,uE.lightGreen),TableStyleMedium19:RE("TableStyleMedium19",SE,uE.purple),TableStyleMedium20:RE("TableStyleMedium20",SE,uE.gray),TableStyleMedium21:RE("TableStyleMedium21",SE,uE.orange),TableStyleMedium22:RE("TableStyleMedium22",CE,uE.black),TableStyleMedium23:RE("TableStyleMedium23",CE,uE.lightBlue),TableStyleMedium24:RE("TableStyleMedium24",CE,uE.red),TableStyleMedium25:RE("TableStyleMedium25",CE,uE.lightGreen),TableStyleMedium26:RE("TableStyleMedium26",CE,uE.purple),TableStyleMedium27:RE("TableStyleMedium27",CE,uE.gray),TableStyleMedium28:RE("TableStyleMedium28",CE,uE.orange),TableStyleDark1:{...wE,displayName:"Black, TableStyleDark1"},TableStyleDark2:RE("TableStyleDark2",yE,uE.lightBlue),TableStyleDark3:RE("TableStyleDark3",yE,uE.red),TableStyleDark4:RE("TableStyleDark4",yE,uE.lightGreen),TableStyleDark5:RE("TableStyleDark5",yE,uE.purple),TableStyleDark6:RE("TableStyleDark6",yE,uE.gray),TableStyleDark7:RE("TableStyleDark7",yE,uE.orange),TableStyleDark8:RE("TableStyleDark8",IE,gE.black),TableStyleDark9:RE("TableStyleDark9",IE,gE.redBlue),TableStyleDark10:RE("TableStyleDark10",IE,gE.purpleGreen),TableStyleDark11:RE("TableStyleDark11",IE,gE.orangeBlue)},TE={none:()=>({category:"none",templateName:"none",primaryColor:"",name:"none"}),lightColoredText:pE,lightAllBorders:fE,mediumAllBorders:CE,lightWithHeader:mE,mediumBandedBorders:vE,mediumMinimalBorders:SE,darkNoBorders:IE,mediumWhiteBorders:bE,dark:yE};function AE(e,t,s){const o=dE("",s);return{...TE[t](o),category:"custom",displayName:e}}function DE(e,t){if("SPREADSHEET"!==e.pivot.type)return e;if(e.pivot.dataSet?.sheetId!==t.sheetId)return e;const s=ss(e.pivot.dataSet.zone,t),o=s?{...e.pivot.dataSet,zone:s}:void 0;return{...e,pivot:{...e.pivot,dataSet:o}}}function _E(e,t){if(e.sheetId!==t.sheetId)return e;if(("FREEZE_COLUMNS"===e.type?"COL":"ROW")!==t.dimension)return e;let s=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort((e,t)=>t-e);for(const t of e)s>t&&s--}if("ADD_COLUMNS_ROWS"===t.type){s=s>("before"===t.position?t.base-1:t.base)?s+t.quantity:s}return s>0?{...e,quantity:s}:void 0}function OE(e,t){if(e.sheetId!==t.sheetId)return e;const s=ss(e.zone,t);if(!s)return;const o=e.newTableRange?os(e.newTableRange,t):void 0;return{...e,newTableRange:o,zone:s}}function FE(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let s;if("REMOVE_COLUMNS_ROWS"===t.type)s=pb(t.elements,[e.base])[0];else if("ADD_COLUMNS_ROWS"===t.type){s=gb(Pe(t.position,t.base),t.quantity,[e.base])[0]}return void 0!==s?{...e,base:s}:void 0}function PE(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;const s=ge(e.start,e.end+1);let o=[];if("REMOVE_COLUMNS_ROWS"===t.type)o=pb(t.elements,s);else if("ADD_COLUMNS_ROWS"===t.type){o=gb(Pe(t.position,t.base),t.quantity,s)}return 0!==o.length?{...e,start:Math.min(...o),end:Math.max(...o)}:void 0}function ME(e,t){return(e=ae(e)).pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=WS(e.computedBy.sheetId,e.computedBy.formula,t))}),e}function NE(e,t){return{...e,definition:Yy(e.sheetId,e.definition,t)}}aE.addTransformation("ADD_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],FE),aE.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],FE),aE.addTransformation("DELETE_SHEET",["MOVE_RANGES"],function(e,t){const s=t.sheetId;if(e.targetSheetId===s||e.sheetId===s)return;return e}),aE.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART","UPDATE_CAROUSEL"],function(e,t){if(e.figureId===t.figureId)return;return e}),aE.addTransformation("DELETE_CHART",["UPDATE_CHART"],function(e,t){if(e.chartId===t.chartId)return;return e}),aE.addTransformation("DELETE_CHART",["UPDATE_CAROUSEL"],function(e,t){return{...e,definition:{...e.definition,items:e.definition.items.filter(e=>!("chart"===e.type&&e.chartId===t.chartId))}}}),aE.addTransformation("CREATE_SHEET",["CREATE_SHEET"],function(e,t){e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`});if(e.name===t.name)return{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,e=>(parseInt(e)+1).toString()):`${e.name}~`,position:e.position+1};return e}),aE.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE"],function(e,t){if(e.sheetId!==t.sheetId)return e;const s=[];for(const o of e.target)t.target.every(e=>!Lt(o,e))&&s.push(o);if(s.length)return{...e,target:s};return}),aE.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],_E),aE.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],_E),aE.addTransformation("ADD_COLUMNS_ROWS",["UPDATE_TABLE"],OE),aE.addTransformation("REMOVE_COLUMNS_ROWS",["UPDATE_TABLE"],OE),aE.addTransformation("REMOVE_TABLE_STYLE",["CREATE_TABLE","UPDATE_TABLE"],function(e,t){if(e.config?.styleId!==t.tableStyleId)return e;return{...e,config:{...e.config,styleId:hE.styleId}}}),aE.addTransformation("ADD_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],PE),aE.addTransformation("REMOVE_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],PE),aE.addTransformation("REMOVE_PIVOT",["RENAME_PIVOT","DUPLICATE_PIVOT","INSERT_PIVOT","UPDATE_PIVOT"],function(e,t){if(e.pivotId===t.pivotId)return;return e}),aE.addTransformation("DELETE_SHEET",["ADD_PIVOT","UPDATE_PIVOT"],function(e,t){if("SPREADSHEET"!==e.pivot.type)return e;if(e.pivot.dataSet?.sheetId===t.sheetId)return{...e,pivot:{...e.pivot,dataSet:void 0}};return e}),aE.addTransformation("ADD_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],DE),aE.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],DE),lE.add("UPDATE_CELL",function(e,t){const s=e.content&&WS(e.sheetId,e.content,t);return{...e,content:s}}),lE.add("ADD_CONDITIONAL_FORMAT",function(e,t){const s=e.cf.rule;if(e={...e,cf:{...e.cf}},"CellIsRule"===s.type)e.cf.rule={...s,values:s.values.map(s=>WS(e.sheetId,s,t))};else if("ColorScaleRule"===s.type){const{minimum:o,maximum:i,midpoint:n}=s;e.cf.rule={...s,minimum:{...o,value:o.value&&WS(e.sheetId,o.value,t)},maximum:{...i,value:i.value&&WS(e.sheetId,i.value,t)},midpoint:n?{...n,value:WS(e.sheetId,n.value,t)}:void 0}}else if("IconSetRule"===s.type){const{upperInflectionPoint:o,lowerInflectionPoint:i}=s;e.cf.rule={...s,upperInflectionPoint:{...o,value:WS(e.sheetId,o.value,t)},lowerInflectionPoint:{...i,value:WS(e.sheetId,i.value,t)}}}else"DataBarRule"===s.type&&(e.cf.rule={...s,rangeValues:s.rangeValues?$S(e.sheetId,s.rangeValues,t):void 0});return e}),lE.add("ADD_DATA_VALIDATION_RULE",function(e,t){return(e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}}).rule.criterion.values=e.rule.criterion.values.map(s=>WS(e.sheetId,s,t)),e}),lE.add("ADD_PIVOT",ME),lE.add("UPDATE_PIVOT",ME),lE.add("CREATE_CHART",NE),lE.add("UPDATE_CHART",NE);const LE=[{match:function(e){return"sheetId"in e},fn:UE},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const s=UE(e,t);if("SKIP_TRANSFORMATION"!==s)return"IGNORE_COMMAND"===s?"IGNORE_COMMAND":e;const o=[];for(const s of e.target){const e=ss(s,t);e&&o.push(e)}if(!o.length)return"IGNORE_COMMAND";return{...e,target:o}}},{match:function(e){return"sheetId"in e&&"zone"in e},fn:function(e,t){const s=UE(e,t);if("SKIP_TRANSFORMATION"!==s)return"IGNORE_COMMAND"===s?"IGNORE_COMMAND":e;const o=ss(e.zone,t);if(o)return{...e,zone:o};return"IGNORE_COMMAND"}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const s=UE(e,t);if("SKIP_TRANSFORMATION"!==s)return"IGNORE_COMMAND"===s?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const s="COL"===t.dimension?"col":"row";let o=e[s];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort((e,t)=>t-e);if(e.includes(o))return"IGNORE_COMMAND";for(const t of e)o>=t&&o--}"ADD_COLUMNS_ROWS"===t.type&&(o>t.base||o===t.base&&"before"===t.position)&&(o+=t.quantity);return{...e,[s]:o}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const s of t.target){if(!(e.col===s.left&&e.row===s.top)&&kt(e.col,e.row,s))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e&&"sheetId"in e&&"elements"in e},fn:function(e,t){const s=UE(e,t);if("SKIP_TRANSFORMATION"!==s)return"IGNORE_COMMAND"===s?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"!==t.type&&"REMOVE_COLUMNS_ROWS"!==t.type)return"SKIP_TRANSFORMATION";if(t.dimension!==e.dimension)return e;let o=[];if("REMOVE_COLUMNS_ROWS"===t.type)o=pb(t.elements,e.elements);else if("ADD_COLUMNS_ROWS"===t.type){o=gb(Pe(t.position,t.base),t.quantity,e.elements)}if(0===o.length)return"IGNORE_COMMAND";return{...e,elements:o}}},{match:function(e){return"ranges"in e},fn:function(e,t){if(!("sheetId"in t))return e;const s=e.ranges.map(e=>os(e,t)).filter(Te);if(!s.length)return"IGNORE_COMMAND";return{...e,ranges:s}}}];function kE(e,t){const s=aE.getTransformation(e.type,t.type),o=s?s(e,t):function(e,t){for(const{match:s,fn:o}of LE)if(s(e)){const s=o(e,t);if("SKIP_TRANSFORMATION"===s)continue;if("IGNORE_COMMAND"===s)return;e=s}return e}(e,t);return o?function(e,t){const s=lE.get(e.type);if(!s)return e;const o=Tb(t);if(o)return s(e,o);return e}(o,t):o}function VE(e,t){let s=[...e];const o=new Set(aE.getKeys());for(const e of t)(o.has(e.type)||Ab.contains(e.type))&&(s=s.reduce((t,s)=>{const o=kE(s,e);return o&&t.push(o),t},[]));return s}function UE(e,t){if(!("sheetId"in t))return e;const s="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===s?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class HE{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,s,o,i,n){this.rootCommand=o,this.timestamp=n,this.id=e,this.clientId=t,this._commands=[...s],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class zE extends Error{}class BE extends Yf{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new lr;lastLocalOperation;constructor(e,t,s=H){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=s,this.debouncedMove=De(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,s){if(!t.length||!s.length||!this.canApplyOptimisticUpdate())return;const o=new HE(this.uuidGenerator.uuidv4(),this.clientId,t,e,s,Date.now());this.revisions.append(o.id,o),"REQUEST_REDO"!==e.type&&(this.lastLocalOperation=o),this.trigger("new-local-state-update",{id:o.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:o.id,clientId:o.clientId,commands:o.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),this.awaitingClientPosition=void 0)}loadInitialMessages(e){const t=performance.now(),s=e.reduce((e,t)=>e+("REMOTE_REVISION"===t.type?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug("Replayed",s,"commands in",performance.now()-t,"ms")}async leave(e){e&&1===Object.keys(this.clients).length&&this.lastRevisionMessage&&"SNAPSHOT_CREATED"!==this.lastRevisionMessage?.type&&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(0!==this.pendingMessages.length)return;const 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){const t=this.clients[e];if(!t)throw new zE("The client left the session");return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(Te))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId])return void(this.awaitingClientPosition=e);const t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;const s=t?"CLIENT_MOVED":"CLIENT_JOINED",o=this.getCurrentClient();this.clients[this.clientId]={...o,position:e},this.transportService.sendMessage({type:s,version:1,client:{...o,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{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":const{clientId:t,commands:s,timestamp:o}=e,i=new HE(e.nextRevisionId,t,s,void 0,void 0,o);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);const t=this.pendingMessages.filter(e=>"REMOTE_REVISION"===e.type).map(e=>e.commands).flat();this.trigger("remote-revision-received",{commands:VE(s,t)})}break;case"SNAPSHOT_CREATED":{const t=new HE(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;const t=this.clients[this.clientId];if(t){const{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("REMOTE_REVISION"===e.type){let t=this.revisions.get(e.nextRevisionId);0===t.commands.length&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw new Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.\n ${JSON.stringify(e)}`);this.waitingAck=!0,this.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch("REVISION_UNDONE"!==e.type&&"REVISION_REDONE"!==e.type||(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);const t=this.pendingMessages.findIndex(e=>"REMOTE_REVISION"===e.type);-1!==t&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}isAlreadyProcessed(e){if("CLIENT_MOVED"===e.type&&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})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e)}}const GE=(new Og).add("ADD_COLUMNS_ROWS",function(e){const t=[];let s=e.base;"after"===e.position&&s++;for(let o=0;o<e.quantity;o++)t.push(o+s);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId,sheetName:e.sheetName}]}).add("REMOVE_COLUMNS_ROWS",function(e){const t=[],s=[...e.elements].sort((e,t)=>e-t);for(const o of pe(s)){const s=0===o[0]?0:o[0]-1,i=0===o[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:o.length,base:s,sheetId:e.sheetId,sheetName:e.sheetName,position:i})}return t}).add("ADD_MERGE",function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]}).add("REMOVE_MERGE",function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]}).add("CREATE_SHEET",function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId,sheetName:e.name}]}).add("DELETE_SHEET",function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1,name:e.sheetName}]}).add("DUPLICATE_SHEET",function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo,sheetName:""}]}).add("CREATE_FIGURE",function(e){return[{type:"DELETE_FIGURE",figureId:e.figureId,sheetId:e.sheetId}]}).add("CREATE_CHART",function(e){return[{type:"DELETE_FIGURE",figureId:e.figureId,sheetId:e.sheetId}]}).add("HIDE_COLUMNS_ROWS",function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}).add("UNHIDE_COLUMNS_ROWS",function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}).add("CREATE_TABLE_STYLE",function(e){return[{type:"REMOVE_TABLE_STYLE",tableStyleId:e.tableStyleId}]}).add("ADD_PIVOT",function(e){return[{type:"REMOVE_PIVOT",pivotId:e.pivotId}]}).add("RENAME_SHEET",function(e){return[{type:"RENAME_SHEET",sheetId:e.sheetId,oldName:e.newName,newName:e.oldName}]});for(const e of fr.values())GE.contains(e)||GE.add(e,WE);function WE(e){return[e]}function $E(e){return GE.get(e.type)(e)}class qE{buildTransformation;operations;constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find(t=>t.id===e);if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(const s of this.operations){if(s.id===e)return e;if(s.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find(t=>t.id===e)}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map(e=>e.transformed(t))]}insert(e,t){const s=this.buildTransformation.with(e.data),{before:o,operation:i,after:n}=this.locateOperation(t);this.operations=[...o,i,e,...n.map(e=>e.transformed(s))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new qE(this.buildTransformation,t)}transform(e){this.operations=this.operations.map(t=>t.transformed(e))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:s}=this.locateOperation(e);this.operations=t.concat([s])}locateOperation(e){const t=this.operations.findIndex(t=>t.id===e);if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class ZE{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new jE(this.id,Oe(()=>e(this.data)))}}class jE{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new jE(this.id,this.lazyData.map(e))}}class YE{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new YE(function*(e,t){for(const s of e)if(yield s,s.operation.id===t)return}(this.operations,e))}stopBefore(e){return new YE(function*(e,t){for(const s of e){if(s.operation.id===t)return;yield s}}(this.operations,e))}startAfter(e){return new YE(function*(e,t){let s=!0;for(const o of e)s||(yield o),o.operation.id===t&&(s=!1)}(this.operations,e))}}class XE{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 YE(me(this._execution(e),this._execution(e)))}revertedExecution(e){return new YE(me(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){const s=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),s&&this.insertPrevious(e,t,s)}insertOperationAfter(e,t,s){e.insert(t,s),this.updateNextWith(e,t,s),this.insertPrevious(e,t,s)}undo(e,t){const s=this.buildTransformation.without(t.data),o=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const i=e.fork(t.id);o&&this.branchingOperationIds.set(i,o),this.insertBranchAfter(e,i),this.transform(i,s)}redo(e){const t=this.nextBranch(e);if(!t)return;const s=this.nextBranch(t);this.removeBranchFromTree(t);const o=this.branchingOperationIds.get(t);o?this.branchingOperationIds.set(e,o):this.branchingOperationIds.delete(e),s&&this.rebaseUp(s)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const s of this.revertedExecution(e))if(s.operation.id===t)return s;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:s}=this.findPreviousBranchingOperation(e);if(!t||!s)return;const o=this.buildTransformation.without(s.data),i=t.fork(s.id);this.branchingOperationIds.set(i,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,i),i.transform(o);const n=this.nextBranch(i);n&&this.rebaseUp(n)}removeBranchFromTree(e){const t=this.branches.findIndex(t=>t===e);this.branches.splice(t,1)}insertBranchAfter(e,t){const s=this.branches.findIndex(t=>t===e);this.branches.splice(s+1,0,t)}updateNextWith(e,t,s){const o=this.branchingOperationIds.get(e),i=this.nextBranch(e);if(o&&i)if(e.getFirstOperationAmong(s,o)===o){const n=this.addToNextBranch(e,i,o,t,s);this.updateNextWith(i,n,s)}else{const e=this.buildTransformation.with(t.data);this.transform(i,e)}}addToNextBranch(e,t,s,o,i){let n=o;return i===s?(n=this.getTransformedOperation(e,s,o),t.prepend(n)):t.contains(i)?(n=this.getTransformedOperation(e,s,o),t.insert(n,i)):t.append(o),n}getTransformedOperation(e,t,s){const o=e.getOperation(t),i=this.buildTransformation.without(o.data);return s.transformed(i)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const s=this.nextBranch(e);s&&this.transform(s,t)}insertPrevious(e,t,s){const{previousBranch:o,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!o||!i)return;const n=this.buildTransformation.with(i.data),r=e.fork(s);r.transform(n),o.cutAfter(s),o.appendBranch(r);const a=t.transformed(n);this.insertPrevious(o,a,s)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const s=this.branchingOperationIds.get(t);return s?{previousBranch:t,branchingOperation:t.getOperation(s)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex(t=>t===e);if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex(t=>t===e);if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let s=!!t;const o=e.getOperations();for(let i=o.length-1;i>=0;i--){const n=o[i];n.id===t&&(s=!1),s||(yield{operation:n,branch:e,isCancelled:!this.shouldExecute(e,n)})}const i=this.previousBranch(e);yield*i?this._revertedExecution(i):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class KE{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 qE(this.buildTransformation),this.tree=new XE(this.buildTransformation,this.HEAD_BRANCH);const t=e.initialOperationId,s=new ZE(t,this.buildEmpty(t));this.tree.insertOperationLast(this.HEAD_BRANCH,s),this.HEAD_OPERATION=s}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const s=new ZE(e,t),o=this.tree.getLastBranch();this.tree.insertOperationLast(o,s),this.HEAD_BRANCH=o,this.HEAD_OPERATION=s}insert(e,t,s){const o=new ZE(e,t);this.revertTo(s),this.tree.insertOperationAfter(this.HEAD_BRANCH,o,s),this.fastForward()}undo(e,t,s){const{branch:o,operation:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(o,i),this.fastForward(),this.insert(t,this.buildEmpty(t),s)}redo(e,t,s){const{branch:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(o),this.fastForward(),this.insert(t,this.buildEmpty(t),s)}rebase(e){const t=this.get(e),s=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);const o=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,o);for(const{operation:e}of s)this.insert(e.id,e.data,this.HEAD_OPERATION.id)}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:s,isCancelled:o}of e)o||this.revertOperation(s.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:s,isCancelled:o}of e)o||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=s}}function JE(e){return new KE({initialOperationId:e.initialRevisionId,applyOperation:t=>{const s=t.commands.slice(),{changes:o}=e.recordChanges(()=>{for(const t of s)e.dispatch(t)});t.setChanges(o)},revertOperation:e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){QE(t.changes[e])}}([e]),buildEmpty:e=>new HE(e,"empty",[]),buildTransformation:{with:e=>t=>new HE(t.id,t.clientId,VE(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new HE(t.id,t.clientId,VE(t.commands,e.commands.map($E).flat()),t.rootCommand,void 0,t.timestamp)}})}function QE(e){const t=e.target,s=e.key,o=e.before;void 0===o?delete t[s]:t[s]=o}class eR{xmlString;constructor(e){this.xmlString=e}toString(){return this.xmlString}}const tR=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart","comboChart","radarChart"],sR="M256 9 a247 247 0 1 0.1 0 0";function oR(e){return{name:"CARET_DOWN",width:512,height:512,paths:[{fillColor:e.textColor||I,path:"M120 195 h270 l-135 130"}]}}function iR(e){return{name:"CARET_UP",width:512,height:512,paths:[{fillColor:e.textColor||I,path:"M120 325 h270 l-135 -130"}]}}const nR="M40 185 h270 l-135 128";function rR(e){return{name:"CHIP",width:512,height:512,paths:[{fillColor:e.textColor||I,path:nR}]}}function aR(e){return{name:"CHIP",width:512,height:512,paths:[{fillColor:e.textColor||I,path:"M0,225 A175,175 0 1,0 350,225 A175,175 0 1,0 0,225"},{fillColor:e.fillColor||I,path:nR}]}}const lR={name:"CHECKBOX_UNCHECKED",width:512,height:512,paths:[{fillColor:S,path:"M45,45 h422 v422 h-422 v-422 m30,30 v362 h362 v-362"}]},cR={name:"CHECKBOX_UNCHECKED",width:512,height:512,paths:[{fillColor:w,path:"M45,45 h422 v422 h-422 v-422 m30,30 v362 h362 v-362"}]},hR={name:"CHECKBOX_CHECKED",width:512,height:512,paths:[{fillColor:w,path:"M45,45 h422 v422 h-422 v-422"},{fillColor:"#FFF",path:"M165,240 l45,45 l135,-135 h60 l-195,195 l-105,-105"}]};function dR(e,t){return{name:"PIVOT_ICON",width:512,height:512,paths:[{path:"M21,21 h469 v469 h-469",fillColor:t?b:"#777"},{path:"M64,64 v384 h384 v-384",fillColor:t?C:"#eee"},{path:e?"M149,235 h213 v43 h-213 M235,149 h43 v213 h-43":"M149,235 h213 v43 h-213",fillColor:t?b:"#777"}]}}function uR(e,t,s){const o=e?"M18.6 3.5H4.29c-.7 0-1.06.85-.56 1.35l6.1 6.1v6.8c0 .26.13.5.34.65l2.64 1.85a.79.79 0 0 0 1.25-.65v-8.64l6.1-6.1a.79.79 0 0 0-.56-1.35":"M 339.667 681 L 510.333 681 L 510.333 595.667 L 339.667 595.667 L 339.667 681 Z M 41 169 L 41 254.333 L 809 254.333 L 809 169 L 41 169 Z M 169 467.667 L 681 467.667 L 681 382.333 L 169 382.333 L 169 467.667 Z",i=e?"M0,0 h24 v24 h-24":"M0,0 h850 v850 h-850",n={iconColor:u,hoverBackgroundColor:u};return s&&!t?n.iconColor="#fff":!s&&t?n.iconColor="#defade":s&&t&&(n.iconColor=u,n.hoverBackgroundColor="#fff"),{name:"DATA_FILTER_ICON",width:e?24:850,height:e?24:850,paths:[s?{path:i,fillColor:n.hoverBackgroundColor}:void 0,{path:o,fillColor:n.iconColor}].filter(Te)}}const gR={arrowGood:{template:"ARROW_UP",svg:{name:"ARROW_UP",width:448,height:512,paths:[{fillColor:"#6AA84F",path:"M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9L413 289.4c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z"}]}},arrowNeutral:{template:"ARROW_RIGHT",svg:{name:"ARROW_RIGHT",width:448,height:512,paths:[{fillColor:"#F0AD4E",path:"M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"}]}},arrowBad:{template:"ARROW_DOWN",svg:{name:"ARROW_DOWN",width:448,height:512,paths:[{fillColor:"#E06666",path:"M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z"}]}},smileyGood:{template:"SMILE",svg:{name:"SMILE",width:496,height:512,paths:[{fillColor:"#6AA84F",path:"M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160 0c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm4 72.6c-20.8 25-51.5 39.4-84 39.4s-63.2-14.3-84-39.4c-8.5-10.2-23.7-11.5-33.8-3.1-10.2 8.5-11.5 23.6-3.1 33.8 30 36 74.1 56.6 120.9 56.6s90.9-20.6 120.9-56.6c8.5-10.2 7.1-25.3-3.1-33.8-10.1-8.4-25.3-7.1-33.8 3.1z"}]}},smileyNeutral:{template:"MEH",svg:{name:"MEH",width:496,height:512,paths:[{fillColor:"#F0AD4E",path:"M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm8 144H160c-13.2 0-24 10.8-24 24s10.8 24 24 24h176c13.2 0 24-10.8 24-24s-10.8-24-24-24z"}]}},smileyBad:{template:"FROWN",svg:{name:"FROWN",width:496,height:512,paths:[{fillColor:"#E06666",path:"M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm-80 128c-40.2 0-78 17.7-103.8 48.6-8.5 10.2-7.1 25.3 3.1 33.8 10.2 8.4 25.3 7.1 33.8-3.1 16.6-19.9 41-31.4 66.9-31.4s50.3 11.4 66.9 31.4c8.1 9.7 23.1 11.9 33.8 3.1 10.2-8.5 11.5-23.6 3.1-33.8C326 321.7 288.2 304 248 304z"}]}},dotGood:{template:"GREEN_DOT",svg:{name:"GREEN_DOT",width:512,height:512,paths:[{fillColor:"#6AA84F",path:sR}]}},dotNeutral:{template:"YELLOW_DOT",svg:{name:"YELLOW_DOT",width:512,height:512,paths:[{fillColor:"#F0AD4E",path:sR}]}},dotBad:{template:"RED_DOT",svg:{name:"RED_DOT",width:512,height:512,paths:[{fillColor:"#E06666",path:sR}]}}},pR={arrows:{good:"arrowGood",neutral:"arrowNeutral",bad:"arrowBad"},smiley:{good:"smileyGood",neutral:"smileyNeutral",bad:"smileyBad"},dots:{good:"dotGood",neutral:"dotNeutral",bad:"dotBad"}},mR={};function fR(e){if(mR[e])return mR[e];const t=new Path2D(e);return mR[e]=t,t}function vR(e,t){const s=e.split("/"),o=t.split("/");let i="",n=0;for(let e=0;e<s.length-1;e++)s[e]===o[e]?n++:i+="../";return i+=o.slice(n).join("/"),i}function bR(e,t=0){const s={};for(let o=0;o<e.length;o++)e[o]&&(s[o+t]=e[o]);return s}function SR(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,(e,t)=>String.fromCharCode(parseInt(t,16)))}function CR(e,t,s){return"COL"===t?(e.cols[s]||(e.cols[s]={}),e.cols[s]):(e.rows[s]||(e.rows[s]={}),e.rows[s])}function yR(e){if("="===e[0])return e;const t=Mc(e);return 1===t.length&&"REFERENCE"!==t[0].type?e:"="+e}var IR;!function(e){e.DiagonalBorderNotSupported="Diagonal Borders",e.BorderStyleNotSupported="Border style",e.FillStyleNotSupported="Fill Style",e.FontNotSupported="Font",e.HorizontalAlignmentNotSupported="Horizontal Alignment",e.VerticalAlignmentNotSupported="Vertical Alignments",e.MultipleRulesCfNotSupported="Multiple rules conditional formats",e.CfTypeNotSupported="Conditional format type",e.CfFormatBorderNotSupported="Borders in conditional formats",e.CfFormatAlignmentNotSupported="Alignment in conditional formats",e.CfFormatNumFmtNotSupported="Num formats in conditional formats",e.CfIconSetEmptyIconNotSupported="IconSets with empty icons",e.BadlyFormattedHyperlink="Badly formatted hyperlink",e.NumFmtIdNotSupported="Number format",e.TimeDataValidationNotSupported="Time data validation rules",e.TextLengthDataValidationNotSupported="Text length data validation rules",e.WholeNumberDataValidationNotSupported="Whole number data validation rules",e.NotEqualDateDataValidationNotSupported="Not equal date data validation rules"}(IR||(IR={}));class wR{_parsingWarnings=new Set;_conversionWarnings=new Set;addParsingWarning(e){this._parsingWarnings.add(e)}addConversionWarning(e){this._conversionWarnings.add(e)}get warnings(){return[...this._parsingWarnings,...this._conversionWarnings]}generateNotSupportedWarning(e,t,s){let o=`${e} ${t?'"'+t+'" is':"are"} not yet supported. `;s&&(o+=`Only ${s.join(", ")} are currently supported.`),this._conversionWarnings.has(o)||this._conversionWarnings.add(o)}}const ER=["thin","medium","thick","dashed","dotted"],RR=["general","left","center","right"],xR=["top","center","bottom"],TR=["Arial"],AR=["solid","none"],DR=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWithText","containsBlanks","notContainsBlanks"],_R={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},OR={dashDot:"thin",dashDotDot:"thin",dashed:"dashed",dotted:"dotted",double:"thin",hair:"thin",medium:"medium",mediumDashDot:"thin",mediumDashDotDot:"thin",mediumDashed:"thin",none:void 0,slantDashDot:"thin",thick:"thick",thin:"thin"},FR={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"},PR={top:"top",center:"middle",bottom:"bottom",justify:"middle",distributed:"middle"},MR={top:"top",middle:"center",bottom:"bottom"},NR={beginsWith:"beginsWithText",endsWith:"endsWithText",containsText:"containsText",notContains:"notContainsText",between:"isBetween",notBetween:"isNotBetween",equal:"isEqual",notEqual:"isNotEqual",greaterThan:"isGreaterThan",greaterThanOrEqual:"isGreaterOrEqualTo",lessThan:"isLessThan",lessThanOrEqual:"isLessOrEqualTo"},LR={aboveAverage:void 0,expression:"customFormula",cellIs:void 0,colorScale:void 0,dataBar:void 0,iconSet:void 0,top10:void 0,uniqueValues:void 0,duplicateValues:void 0,containsText:"containsText",notContainsText:"notContainsText",beginsWith:"beginsWithText",endsWith:"endsWithText",containsBlanks:"isEmpty",notContainsBlanks:"isNotEmpty",containsErrors:void 0,notContainsErrors:void 0,timePeriod:void 0},kR={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},VR={NoIcons:void 0,"3Arrows":"arrows","3ArrowsGray":"arrows","3Symbols":"smiley","3Symbols2":"smiley","3Signs":"dots","3Flags":"dots","3TrafficLights1":"dots","3TrafficLights2":"dots","4Arrows":"arrows","4ArrowsGray":"arrows","4RedToBlack":"dots","4Rating":"smiley","4TrafficLights":"dots","5Arrows":"arrows","5ArrowsGray":"arrows","5Rating":"smiley","5Quarters":"dots","3Stars":"smiley","3Triangles":"arrows","5Boxes":"dots"},UR={none:"none",b:"bottom",t:"top",l:"left",r:"right",tr:"right"},HR={areaChart:void 0,area3DChart:void 0,lineChart:"line",line3DChart:void 0,stockChart:void 0,radarChart:"radar",scatterChart:"scatter",pieChart:"pie",pie3DChart:void 0,doughnutChart:"pie",barChart:"bar",bar3DChart:void 0,ofPieChart:void 0,surfaceChart:void 0,surface3DChart:void 0,bubbleChart:void 0,comboChart:"combo"},zR={exp:"exponential",log:"logarithmic",poly:"polynomial",movingAvg:"trailingMovingAverage"},BR={1:"AVERAGE",2:"COUNT",3:"COUNTA",4:"MAX",5:"MIN",6:"PRODUCT",7:"STDEV",8:"STDEVP",9:"SUM",10:"VAR",11:"VARP",101:"AVERAGE",102:"COUNT",103:"COUNTA",104:"MAX",105:"MIN",106:"PRODUCT",107:"STDEV",108:"STDEVP",109:"SUM",110:"VAR",111:"VARP"},GR={0:"General",1:"0",2:"0.00",3:"#,#00",4:"#,##0.00",9:"0%",10:"0.00%",11:void 0,12:void 0,13:void 0,14:"m/d/yyyy",15:"m/d/yyyy",16:"m/d/yyyy",17:"m/d/yyyy",18:"hh:mm:ss a",19:"hh:mm:ss a",20:"hhhh:mm:ss",21:"hhhh:mm:ss",22:"m/d/yy h:mm",37:void 0,38:void 0,39:void 0,40:void 0,45:"hhhh:mm:ss",46:"hhhh:mm:ss",47:"hhhh:mm:ss",48:void 0,49:"@"},WR={0:1,"0.00":2,"#,#00":3,"#,##0.00":4,"0%":9,"0.00%":10,"0.00E+00":11,"# ?/?":12,"# ??/??":13,"mm-dd-yy":14,"d-mm-yy":15,"mm-yy":16,"mmm-yy":17,"h:mm AM/PM":18,"h:mm:ss AM/PM":19,"h:mm":20,"h:mm:ss":21,"m/d/yy h:mm":22,"#,##0 ;(#,##0)":37,"#,##0 ;[Red](#,##0)":38,"#,##0.00;(#,##0.00)":39,"#,##0.00;[Red](#,##0.00)":40,"mm:ss":45,"[h]:mm:ss":46,"mmss.0":47,"##0.0E+0":48,"@":49,"hh:mm:ss a":19},$R={0:"000000",1:"FFFFFF",2:"FF0000",3:"00FF00",4:"0000FF",5:"FFFF00",6:"FF00FF",7:"00FFFF",8:"000000",9:"FFFFFF",10:"FF0000",11:"00FF00",12:"0000FF",13:"FFFF00",14:"FF00FF",15:"00FFFF",16:"800000",17:"008000",18:"000080",19:"808000",20:"800080",21:"008080",22:"C0C0C0",23:"808080",24:"9999FF",25:"993366",26:"FFFFCC",27:"CCFFFF",28:"660066",29:"FF8080",30:"0066CC",31:"CCCCFF",32:"000080",33:"FF00FF",34:"FFFF00",35:"00FFFF",36:"800080",37:"800000",38:"008080",39:"0000FF",40:"00CCFF",41:"CCFFFF",42:"CCFFCC",43:"FFFF99",44:"99CCFF",45:"FF99CC",46:"CC99FF",47:"FFCC99",48:"3366FF",49:"33CCCC",50:"99CC00",51:"FFCC00",52:"FF9900",53:"FF6600",54:"666699",55:"969696",56:"003366",57:"339966",58:"003300",59:"333300",60:"993300",61:"993366",62:"333399",63:"333333",64:"000000",65:"FFFFFF"},qR={"image/avif":"avif","image/bmp":"bmp","image/gif":"gif","image/vnd.microsoft.icon":"ico","image/jpeg":"jpeg","image/png":"png","image/tiff":"tiff","image/webp":"webp"},ZR={avif:"image/avif",bmp:"image/bmp",gif:"image/gif",ico:"image/vnd.microsoft.icon",jpeg:"image/jpeg",png:"image/png",tiff:"image/tiff",webp:"image/webp",jpg:"image/jpeg"},jR={between:"isBetween",notBetween:"isNotBetween",equal:"isEqual",notEqual:"isNotEqual",greaterThan:"isGreaterThan",greaterThanOrEqual:"isGreaterOrEqualTo",lessThan:"isLessThan",lessThanOrEqual:"isLessOrEqualTo"},YR={between:"dateIsBetween",notBetween:"dateIsNotBetween",equal:"dateIs",greaterThan:"dateIsAfter",greaterThanOrEqual:"dateIsOnOrAfter",lessThan:"dateIsBefore",lessThanOrEqual:"dateIsOnOrBefore"};function XR(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=cS;else{if(!e.indexed)return;t=$R[e.indexed]}var s;return t=6===(s=t).length?"#"+s+"FF":"#"+s.slice(2)+s.slice(0,2),e.tint&&(t=function(e,t){const s=Ev(e),o=xv(s);t<0&&(o.l=o.l*(1+t));t>0&&(o.l=o.l*(1-t)+(100-100*(1-t)));return wv(Rv(o))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function KR(e){return 9===e.length&&(e=e.slice(0,7)),parseInt(e.replace("#",""),16)}const JR=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function QR(e,t,s){const o=GR[e]||t.find(t=>t.id===e)?.format;if("General"!==o){if(o)try{let e=o.replace(/\[(.*)-[A-Z0-9]{3}\]/g,"[$1]");if(e=e.replace(/\[\$\]/g,""),e=e.replace(/_.{1}/g,""),e=e.replace(/\*.{1}/g,""),function(e){return JR.test(e)}(e)&&(e=function(e){return e=e.toLowerCase(),e=e.replace(/mmmmm/g,"mmm"),e=e.replace(/am\/pm|a\/m/g,"a"),e=e.replace(/hhhh/g,"hh"),e=e.replace(/\bh\b/g,"hh"),e}(e)),function(e){try{return pn(0,{format:e,locale:Oc}),!0}catch(e){return!1}}(e))return e}catch(e){}s.generateNotSupportedWarning(IR.NumFmtIdNotSupported,o||`nmFmtId ${e}`)}}function ex(e,t){const s=e.borders.map(e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(IR.DiagonalBorderNotSupported)}(e,t);const s={top:tx(e.top,t),bottom:tx(e.bottom,t),left:tx(e.left,t),right:tx(e.right,t)};return Object.keys(s).forEach(e=>void 0===s[e]&&delete s[e]),s});return bR(s,1)}function tx(e,t){if(!e)return;!function(e,t){ER.includes(e.style)||t.generateNotSupportedWarning(IR.BorderStyleNotSupported,e.style,ER)}(e,t);const s=OR[e.style];return s?{style:s,color:XR(e.color)}:void 0}function sx(e,t){return bR(e.styles.map(s=>ox({fontStyle:e.fonts[s.fontId],fillStyle:e.fills[s.fillId],alignment:s.alignment},t)),1)}function ox(e,t){return function(e,t,s){e&&e.name&&!TR.includes(e.name)&&s.generateNotSupportedWarning(IR.FontNotSupported,e.name,TR);t&&t.patternType&&!AR.includes(t.patternType)&&s.generateNotSupportedWarning(IR.FillStyleNotSupported,t.patternType,AR)}(e?.fontStyle,e?.fillStyle,t),function(e,t){e&&!RR.includes(e)&&t.generateNotSupportedWarning(IR.HorizontalAlignmentNotSupported,e,RR)}(e?.alignment?.horizontal,t),function(e,t){e&&!xR.includes(e)&&t.generateNotSupportedWarning(IR.VerticalAlignmentNotSupported,e,xR)}(e?.alignment?.vertical,t),{bold:e.fontStyle?.bold,italic:e.fontStyle?.italic,strikethrough:e.fontStyle?.strike,underline:e.fontStyle?.underline,verticalAlign:e.alignment?.vertical?PR[e.alignment.vertical]:void 0,align:e.alignment?.horizontal?FR[e.alignment.horizontal]:void 0,fillColor:"solid"===e.fillStyle?.patternType?XR(e.fillStyle?.fgColor):XR(e.fillStyle?.bgColor),textColor:XR(e.fontStyle?.color),fontSize:e.fontStyle?.size,wrapping:e.alignment?.wrapText?"wrap":"overflow"}}function ix(e,t){const s=[];for(const o of e.styles){const i=QR(o.numFmtId,e.numFmts,t);i&&(s[o.numFmtId]=i)}return bR(s,1)}function nx(e,t,s){const o=[];let i=1;for(const n of e){if(0===n.cfRules.length)continue;hx(n,t,s);const e=n.cfRules[0];let r;const a=[];if(void 0!==e.dxfId||"colorScale"===e.type||"iconSet"===e.type||"dataBar"===e.type){switch(e.type){case"aboveAverage":case"containsErrors":case"notContainsErrors":case"duplicateValues":case"top10":case"uniqueValues":case"timePeriod":continue;case"dataBar":const t=rx(i++,n);t&&o.push(t);continue;case"colorScale":const l=ax(i++,n);l&&o.push(l);continue;case"iconSet":const c=lx(i++,n,s);c&&o.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;r=LR[e.type],a.push(e.text);break;case"expression":if(!e.formula?.length)continue;r=LR[e.type],a.push(`=${e.formula[0]}`);break;case"containsBlanks":case"notContainsBlanks":r=LR[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;r=NR[e.operator],a.push(yR(e.formula[0])),2===e.formula.length&&a.push(yR(e.formula[1]))}r&&void 0!==e.dxfId&&o.push({id:(i++).toString(),ranges:n.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:r,values:a,style:ox({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},s)}})}}return o}function rx(e,t){const s=t.cfRules[0].dataBar;if(!s)return;const o=KR(XR(s.color)||"#FFFFFF");return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"DataBarRule",color:o}}}function ax(e,t){const s=t.cfRules[0].colorScale;if(!s||s.cfvos.length!==s.colors.length||s.cfvos.length<2||s.cfvos.length>3)return;const o=[];for(let e=0;e<s.cfvos.length;e++)o.push({color:KR(XR(s.colors[e])||"#FFFFFF"),type:kR[s.cfvos[e].type],value:s.cfvos[e].value});const i=o[0],n=2===o.length?o[1]:o[2],r=3===o.length?o[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"ColorScaleRule",minimum:i,midpoint:r,maximum:n}}}function lx(e,t,s){const o=t.cfRules[0].iconSet;if(!o)return;let i=o.cfvos,n=o.cfIcons;if(i.length<3||n&&n.length<3)return;i.length>3&&(i=[i[0],i[Math.floor(i.length/2)],i[i.length-1]]),n&&n.length>3&&(n=[n[0],n[Math.floor(n.length/2)],n[n.length-1]]);const r=[];for(let e=1;e<=2;e++){const t=kR[i[e].type];if("value"===t)return;r.push({value:i[e].value||"",operator:i[e].gte?"ge":"gt",type:t})}let a={lower:n?cx(n[0].iconSet,n[0].iconId):cx(o.iconSet,0),middle:n?cx(n[1].iconSet,n[1].iconId):cx(o.iconSet,1),upper:n?cx(n[2].iconSet,n[2].iconId):cx(o.iconSet,2)};o.reverse&&(a={upper:a.lower,middle:a.middle,lower:a.upper});for(const e of Object.keys(a))if(!a[e])switch(s.generateNotSupportedWarning(IR.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=pR.dots.good;break;case"middle":a[e]=pR.dots.neutral;break;case"lower":a[e]=pR.dots.bad}return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"IconSetRule",icons:a,upperInflectionPoint:r[1],lowerInflectionPoint:r[0]}}}function cx(e,t){const s=VR[e];return s?0===t?pR[s].bad:1===t?pR[s].neutral:pR[s].good:""}function hx(e,t,s){if(e.cfRules.length>1&&s.generateNotSupportedWarning(IR.MultipleRulesCfNotSupported),DR.includes(e.cfRules[0].type)||s.generateNotSupportedWarning(IR.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const o=t[e.cfRules[0].dxfId];o.border&&s.generateNotSupportedWarning(IR.CfFormatBorderNotSupported),o.alignment&&s.generateNotSupportedWarning(IR.CfFormatAlignmentNotSupported),o.numFmt&&s.generateNotSupportedWarning(IR.CfFormatNumFmtNotSupported)}}function dx(e){switch(e){case"isNotEmpty":case"notContainsText":return"notContainsBlanks";case"isEmpty":return"containsBlanks";case"containsText":return"containsText";case"beginsWithText":return"beginsWith";case"endsWithText":return"endsWith";case"isGreaterThan":return"greaterThan";case"isGreaterOrEqualTo":return"greaterThanOrEqual";case"isLessThan":return"lessThan";case"isLessOrEqualTo":return"lessThanOrEqual";case"isBetween":return"between";case"isNotBetween":return"notBetween";case"isEqual":return"equal";case"isNotEqual":return"notEqual";case"customFormula":return""}}function ux(e){return Math.round(kS*e*100)/100}function gx(e){return Math.round(VS*e*100)/100}function px(e){return e?Math.round(e/kS*100)/100:e}function mx(e){return e?Math.round(e/VS*100)/100:e}function fx(e,t,s,o,i){const n=s?e.styles[s]:{},r=o?e.formats[o]:void 0,a={font:{size:n?.fontSize||L,color:{rgb:n?.textColor?n.textColor:"000000"},family:2,name:"Arial"},fill:n?.fillColor?{fgColor:{rgb:n.fillColor}}:{reservedAttribute:"none"},numFmt:r?{format:r,id:0}:void 0,border:i||0,alignment:{horizontal:n.align,vertical:n.verticalAlign?MR[n.verticalAlign]:void 0,wrapText:!("wrap"!==n.wrapping&&!t?.includes(X))||void 0}};return a.font.strike=!!n?.strikethrough||void 0,a.font.underline=!!n?.underline||void 0,a.font.bold=!!n?.bold||void 0,a.font.italic=!!n?.italic||void 0,a}function vx(e,t){const s=function(e,t){if(!e)return 0;let s=WR[e.format];s||(s=Cx(e,t)+164);return s}(t.numFmt,e.numFmts),o={fontId:Cx(t.font,e.fonts),fillId:Cx(t.fill,e.fills),borderId:t.border,numFmtId:s,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal,wrapText:t.alignment.wrapText}};return Cx(o,e.styles)}function bx(e,t,s){const o=e.find(e=>e.path===t);let i;return o?(i=`rId${(o.rels.length+1).toString()}`,o.rels.push({...s,id:i})):(i="rId1",e.push({path:t,rels:[{...s,id:i}]})),i}const Sx=new WeakMap;function Cx(e,t){let s=Sx.get(t);if(!s){s=new Map;for(let e=0;e<t.length;e++){const o=hb(t[e]);s.set(o,e)}Sx.set(t,s)}const o=hb(e);if(s.has(o))return s.get(o);const i=t.length;return t.push(e),s.set(o,i),i}function yx(e,t){const s=t.chartIds.findIndex(t=>t===e);return-1===s?(t.chartIds.push(e),t.chartIds.length):s+1}const Ix=[];function wx(e){const t=Ix.findIndex(t=>t===e);return-1===t?(Ix.push(e),Ix.length):t+1}function Ex(e){return Math.round(914400*e/96)}function Rx(e,t,s){let o,i,n=e;if(({xc:n,sheetName:o}=tr(e)),o){const e=s.sheets.findIndex(e=>vb(e.name,o));if(e<0)throw new Error("Unable to find a sheet with the name "+o);i=e}else i=Number(t);const r=It(n);return void 0===r.right&&(r.right=s.sheets[i].colNumber),void 0===r.bottom&&(r.bottom=s.sheets[i].rowNumber),(r.right-r.left+1)*(r.bottom-r.top+1)}function xx(e){return Math.round(96*e/914400)}function Tx(e,t){let s=0;for(let o=0;o<e;o++){const e=t.cols.find(e=>o>=e.min&&o<=e.max);e?.width?s+=e.width:t.sheetFormat?.defaultColWidth?s+=t.sheetFormat.defaultColWidth:s+=US}return s/VS}function Ax(e,t){let s=0;for(let o=0;o<e;o++){const e=t.rows.find(e=>e.index-1===o);e?.height?s+=e.height:t.sheetFormat?.defaultRowHeight?s+=t.sheetFormat.defaultRowHeight:s+=HS}return s/kS}function Dx(e){let t=1;return e.figures.map(s=>function(e,t,s){let o,i,n,r,a;if(1===e.anchors.length)({col:o,row:i,offset:n}=Px(e.anchors[0])),a=xx(e.figureSize.cx),r=xx(e.figureSize.cy);else{({col:o,row:i,offset:n}=Px(e.anchors[0]));const{x:t,y:l}=Mx(e.anchors[0],s),{x:c,y:h}=Mx(e.anchors[1],s);a=c-t,r=h-l}const l={id:t,col:o,row:i,offset:n};if("dataSets"in(c=e.data)&&c.dataSets.length>0)return{...l,width:a,height:r,tag:"chart",data:_x(e.data)};if(function(e){return"imageSrc"in e}(e.data))return{...l,width:xx(e.data.size.cx),height:xx(e.data.size.cy),tag:"image",data:{path:e.data.imageSrc,mimetype:e.data.mimetype}};var c;return}(s,(t++).toString(),e)).filter(Te)}function _x(e){const t=e.dataSets.some(e=>"reference"in(e.label??{})),s=e.labelRange?Ox(e.labelRange,t):void 0,o=e.dataSets.map(e=>{let s;return e.label&&"text"in e.label&&(s=e.label.text),{dataRange:Ox(e.range,t),label:s,backgroundColor:e.backgroundColor,trend:Fx(e.trend)}});"pie"===e.type&&o.reverse();const i={range:o,dataSetsHaveTitle:t,auxiliaryRange:s,title:e.title??{text:""},background:XR({rgb:e.backgroundColor})||"#FFFFFF",legendPosition:e.legendPosition,stacked:e.stacked||!1,aggregated:!1,cumulative:e.cumulative||!1,labelsAsText:!1,horizontal:e.horizontal,isDoughnut:e.isDoughnut,pieHolePercentage:e.pieHolePercentage};try{return $y.get(e.type).getChartDefinitionFromContextCreation(i)}catch(e){return}}function Ox(e,t){const{sheetName:s,xc:o}=tr(e);let i=It(o);if(t&&void 0!==i.bottom&&void 0!==i.right){const e=i.bottom-i.top+1,t=i.right-i.left+1;1===e?i={...i,left:i.left-1}:1===t&&(i={...i,top:i.top-1})}return sr(s,Tt(i))}function Fx(e){if(e&&e.type)return{type:"linear"===e.type?"polynomial":zR[e.type],order:"linear"===e.type?1:e.order,color:e.color,window:e.window||2,display:!0}}function Px(e){const t={x:xx(e.colOffset)-1,y:xx(e.rowOffset)-1};return{col:e.col,row:e.row,offset:t}}function Mx(e,t){return{x:Tx(e.col,t)+xx(e.colOffset),y:Ax(e.row,t)+xx(e.rowOffset)}}function Nx(e,t){const s=[];let o=1;for(const i of e)if(i)switch(i.type){case"time":t.generateNotSupportedWarning(IR.TimeDataValidationNotSupported);break;case"textLength":t.generateNotSupportedWarning(IR.TextLengthDataValidationNotSupported);break;case"whole":t.generateNotSupportedWarning(IR.WholeNumberDataValidationNotSupported);break;case"decimal":const e=Lx(o++,i);s.push(e);break;case"list":const n=kx(o++,i);s.push(n);break;case"date":if("notEqual"===i.operator){t.generateNotSupportedWarning(IR.NotEqualDateDataValidationNotSupported);break}const r=Vx(o++,i);s.push(r);break;case"custom":const a=Ux(o++,i);s.push(a)}return s}function Lx(e,t){const s=[yR(t.formula1.toString())];return t.formula2&&s.push(yR(t.formula2.toString())),{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:jR[t.operator],values:s}}}function kx(e,t){const s=t.formula1.toString(),o=Xn.test(s);return{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:o?"isValueInRange":"isValueInList",values:o?[s]:s.replaceAll('"',"").split(","),displayStyle:"arrow"}}}function Vx(e,t){let s;const o=[yR(t.formula1.toString())];return t.formula2?(o.push(yR(t.formula2.toString())),s={type:YR[t.operator],values:ib(o,Oc)}):s={type:YR[t.operator],values:ib(o,Oc),dateValue:"exactDate"},{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:s}}function Ux(e,t){return{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:"customFormula",values:[yR(t.formula1.toString())]}}}const Hx=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),zx=new RegExp(/SUBTOTAL\(([0-9]*),/g),Bx=new RegExp(Wn.source,"ig");function Gx(e,t){const s=function(e){const t={};for(const s of e.rows)for(const e of s.cells)e.formula&&void 0!==e.formula.sharedIndex&&e.formula.content&&(t[e.formula.sharedIndex]={refCellXc:e.xc,formula:e.formula.content});return t}(e);for(const o of e.rows.map(e=>e.cells).flat())o?.formula&&(o.formula.content=void 0===o.formula.sharedIndex||o.formula.content?"="+o.formula.content:"="+$x(o.xc,s[o.formula.sharedIndex]),o.formula.content=Wx(o.formula.content,t))}function Wx(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(zx,(e,t)=>{const s=BR[t];return s?s+"(":e})).replace(Hx,(e,s,o,i)=>{s=Number(s)-1,i=i.replace(/\$/g,"");const n=t.externalBooks[s].sheetNames.findIndex(e=>vb(e,o));if(-1===n)return e;const r=t.externalBooks[s].datasets.find(e=>e.sheetId===n)?.data;if(!r)return e;const a=r&&r[i];return(Number(a)?a:`"${a}"`)||e})}function $x(e,t){const s=pt(t.refCellXc);let o,i=t.formula.slice();do{if(o=Bx.exec(i),o){const t=pt(o[0].replace("$","")),n=pt(e),r={colFixed:o[0].startsWith("$"),rowFixed:o[0].includes("$",1)},a={col:n.col-s.col,row:n.row-s.row},l={col:r.colFixed?t.col:t.col+a.col,row:r.rowFixed?t.row:t.row+a.row};i=i.slice(0,o.index)+mt(l.col,l.row,r)+i.slice(o.index+o[0].length)}}while(o);return i}function qx(e,t){return e.sheets.map(s=>{Gx(s,e);const o=function(e){const t=[0,0];for(const s of e.rows)t[0]=Math.max(t[0],Ke(s.cells.map(e=>pt(e.xc).col))),t[1]=Math.max(t[1],s.index);for(const s of e.figures)t[0]=Math.max(t[0],s.anchors[s.anchors.length-1]?.col??0),t[1]=Math.max(t[1],s.anchors[s.anchors.length-1]?.row??0);return t[0]=Math.max(t[0]+5,30),t[1]=Math.max(t[1]+5,100),t}(s),i=s.sheetViews[0],n=Kx(s,"ROW",o[1]),r=Kx(s,"COL",o[0]);return{id:s.sheetName,areGridLinesVisible:!i||i.showGridLines,name:s.sheetName,colNumber:o[0],rowNumber:o[1],...Yx(s,e,o,t),merges:s.merges,cols:Zx(s,o[0],r),rows:jx(s,o[1],n),conditionalFormats:nx(s.cfs,e.dxfs,t),dataValidationRules:Nx(s.dataValidations,t),figures:Dx(s),isVisible:s.isVisible,panes:i?{xSplit:i.pane.xSplit,ySplit:i.pane.ySplit}:{xSplit:0,ySplit:0},tables:[],headerGroups:{COL:r,ROW:n},color:XR(s.sheetProperties?.tabColor)}})}function Zx(e,t,s){const o={};for(let i=1;i<t+1;i++){const t=e.cols.find(e=>e.min<=i&&i<=e.max);let n;n=t&&t.width?t.width:e.sheetFormat?.defaultColWidth?e.sheetFormat.defaultColWidth:US;const r=i-1,a=s.some(e=>e.isFolded&&e.start<=r&&r<=e.end);o[r]={size:mx(n),isHidden:!a&&t?.hidden}}return o}function jx(e,t,s){const o={};for(let i=1;i<t+1;i++){const t=e.rows.find(e=>e.index===i);let n;n=t&&t.height?t.height:e.sheetFormat?.defaultRowHeight?e.sheetFormat.defaultRowHeight:HS;const r=i-1,a=s.some(e=>e.isFolded&&e.start<=r&&r<=e.end);o[r]={size:px(n),isHidden:!a&&t?.hidden}}return o}function Yx(e,t,s,o){const i={},n={},r={},a={},l=t.sharedStrings.map(Ge);const c=e.hyperlinks.reduce((e,t)=>(e[t.xc]=t,e),{});for(const s of e.rows)for(const e of s.cells)i[e.xc]=Xx(e,c,l,o),e.styleIndex&&(n[e.xc]=e.styleIndex+1,r[e.xc]=t.styles[e.styleIndex].numFmtId+1,a[e.xc]=t.styles[e.styleIndex].borderId+1);for(const o of e.rows.filter(e=>e.styleIndex))for(let e=1;e<=s[0];e++){const s=mt(e-1,o.index-1);n[s]??=o.styleIndex+1,a[s]??=t.styles[o.styleIndex].borderId+1,r[s]??=t.styles[o.styleIndex].numFmtId+1}for(const o of e.cols.filter(e=>e.styleIndex))for(let e=o.min;e<=Math.min(o.max,s[0]);e++)for(let i=1;i<=s[1];i++){const s=mt(e-1,i-1);n[s]??=o.styleIndex+1,a[s]??=t.styles[o.styleIndex].borderId+1,r[s]??=t.styles[o.styleIndex].numFmtId+1}return{cells:i,styles:n,formats:r,borders:a}}function Xx(e,t,s,o){let i;switch(e.type){case"sharedString":i=s[parseInt(e.value,10)];break;case"boolean":i=Number(e.value)?"TRUE":"FALSE";break;case"date":case"error":case"inlineStr":case"number":case"str":i=e.value}return i&&t[e.xc]&&(i=function(e,t,s){const o=e.display||t;e.relTarget||e.location||s.generateNotSupportedWarning(IR.BadlyFormattedHyperlink);const i=e.relTarget?e.relTarget:Re(tr(e.location).sheetName);return ye(o,i)}(t[e.xc],i,o)),e.formula&&(i=e.formula.content),i}function Kx(e,t,s){const o=e?.sheetProperties?.outlinePr,i=[];let n=0;for(let r=0;r<s;r++){const s=Qx(e,t,r),a=s?.outlineLevel||0;if(a>n){const s=Jx(e,t,r,("ROW"===t?o?.summaryBelow:o?.summaryRight)??!0);s&&i.push(s)}n=a}return i}function Jx(e,t,s,o){const i=Qx(e,t,s),n=i?.outlineLevel;if(!n||!n)return;let r=n,a=s,l=i;for(;l&&r>=n;)a++,l=Qx(e,t,a),r=l?.outlineLevel||0;const c=s,h=a-1,d=Qx(e,t,o?h+1:c-1);return{start:c-1,end:h-1,isFolded:d?.collapsed||!1}}function Qx(e,t,s){return"COL"===t?e.cols.find(e=>e.min<=s&&s<=e.max):e.rows.find(e=>e.index===s)}function eT(e,t){for(const s of t.sheets){const t=e.sheets.find(e=>e.name===s.sheetName);if(t){t.tables||(t.tables=[]);for(const e of s.tables)t.tables.push({range:e.ref,config:tT(e)});for(const e of s.pivotTables)t.tables.push({range:e.location.ref,config:sT(e)})}}!function(e,t){let s=null;for(const o of e){const i=t.find(e=>vb(e.sheetName,o.name)).tables;if(i&&0!==i.length){s||(s=oT(e));for(const t of i)for(const i in s){const n=e.find(e=>e.id===i);for(const e in s[i]){for(let r=s[i][e].length-3;r>=0;r-=2){const a=s[i][e][r];if(!a.endsWith(t.name))continue;const l=s[i][e][r+1],c=iT(o.id===n.id?"":o.name+"!",l,t,e);s[i][e][r+2]=a.slice(0,a.indexOf(t.name))+c+s[i][e][r+2],s[i][e].splice(r,2)}}}}}if(!s)return;for(const t in s){const o=e.find(e=>e.id===t);for(const e in s[t]){const i=s[t][e];if(1===i.length){o.cells[e]=i[0];continue}let n="";for(let e=0;e<i.length;e+=2)n+=i[e]+"["+i[e+1]+"]";n+=i[i.length-1],o.cells[e]=n}}}(e.sheets,t.sheets)}function tT(e){const t=e.style?.name||"";return{hasFilters:void 0!==e.autoFilter,numberOfHeaders:e.headerRowCount,totalRow:e.totalsRowCount>0,firstColumn:e.style?.showFirstColumn||!1,lastColumn:e.style?.showLastColumn||!1,bandedRows:e.style?.showRowStripes||!1,bandedColumns:e.style?.showColumnStripes||!1,styleId:xE[t]?t:hE.styleId}}function sT(e){return{hasFilters:!1,numberOfHeaders:e.location.firstDataRow,totalRow:e.rowGrandTotals,firstColumn:!0,lastColumn:e.style?.showLastColumn||!1,bandedRows:e.style?.showRowStripes||!1,bandedColumns:e.style?.showColStripes||!1,styleId:hE.styleId}}function oT(e){const t={};for(const s of e)for(const e in s.cells){const o=s.cells[e];if(!o||!o.startsWith("="))continue;const i=o.indexOf("[");if(-1===i)continue;const n=[];let r=o.slice(0,i),a="",l=1,c=0,h=i;for(let e=i+1;e<o.length;e++)"["!==o[e]?"]"===o[e]&&(l--,0===l&&(a=o.slice(h+1,e),n.push(r),n.push(a),c=e+1)):(0===l&&(r=o.slice(c,e),h=e),l++);n.length&&(t[s.id]||(t[s.id]={}),n.push(o.slice(c)),t[s.id][e]=[...n])}return t}function iT(e,t,s,o){const i=t.split(",").map(e=>e.trim()),n=wt(s.ref),r=[],a=[],l=[];for(const e of i)if(nT(e).startsWith("#")){const t=nT(e);switch(l.push(t),t){case"#All":a.push(n.top,n.bottom);break;case"#Data":const e=s.headerRowCount?n.top+s.headerRowCount:n.top,t=s.totalsRowCount?n.bottom-s.totalsRowCount:n.bottom;a.push(e,t);break;case"#This Row":a.push(pt(o).row);break;case"#Headers":if(!s.headerRowCount)return bs.InvalidReference;a.push(n.top);break;case"#Totals":if(!s.totalsRowCount)return bs.InvalidReference;a.push(n.bottom)}}else{const t=e.split(":").map(e=>e.trim()).map(nT);if(r.length)return bs.InvalidReference;const o=s.cols.findIndex(e=>e.name===t[0]);if(-1===o)return bs.InvalidReference;if(r.push(o+n.left),t[1]){const e=s.cols.findIndex(e=>e.name===t[1]);if(-1===e)return bs.InvalidReference;r.push(e+n.left)}}if(!function(e){if(e.length<2)return!0;if(e.length>2)return!1;if(e.includes("#Data")&&e.includes("#Totals"))return!0;if(e.includes("#Headers")&&e.includes("#Data"))return!0;return!1}(l))return bs.InvalidReference;if(0===a.length){const e=s.headerRowCount?n.top+s.headerRowCount:n.top,t=s.totalsRowCount?n.bottom-s.totalsRowCount:n.bottom;a.push(e,t)}0===r.length&&r.push(n.left,n.right);return e+Tt({top:Math.min(...a),left:Math.min(...r),bottom:Math.max(...a),right:Math.max(...r)})}function nT(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,e.length-1):e}function rT(e,t,s){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:s}}function aT(e){return String(e).replace(/\&/g,"&").replace(/\</g,"<").replace(/\>/g,">").replace(/\"/g,""").replace(/\'/g,"'").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"")}function lT(e){return new eR(e.map(([e,t])=>`${e}="${aT(t)}"`).join(" "))}function cT(e,t="text/xml"){const s=(new DOMParser).parseFromString(e.toString(),t),o=s.querySelector("parsererror");if(o){const t=o.innerHTML,s=parseInt(t.split(":")[0],10),i=e.toString().trim().split("\n"),n=i.slice(Math.max(s-3,0),Math.min(s+2,i.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${n}`)}return s}function hT(e){if(e)return{style:e.style,color:{rgb:e.color}}}function dT(e,t){return gT`
|
|
2
|
+
<Override ContentType="${t}" PartName="${e}" />
|
|
3
|
+
`}function uT(e){return new eR(e.join("\n"))}function gT(e,...t){const s=[e[0]];for(let o=0;o<t.length;o++){const i=t[o]instanceof eR?t[o]:aT(t[o]);s.push(i+e[o+1])}return new eR(_e(s))}function pT(e){return e.replace(/NAMESPACE.*NAMESPACE(.*)/,"$1")}function mT(e){return e.replaceAll(/(<\/?)([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,"$1NAMESPACE$2NAMESPACE$3")}function fT(e){return e.replaceAll(/([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,"NAMESPACE$1NAMESPACE$2")}class vT{value;constructor(e){this.value=e}asString(){return SR(String(this.value))}asBool(){return"true"===this.value||"false"!==this.value&&Boolean(Number(this.value))}asNum(){return Number(this.value)}}class bT{rootFile;xlsxFileStructure;warningManager;relationships;currentFile=void 0;constructor(e,t,s){this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=s,this.relationships={},e.rels&&this.extractRelationships(e.rels).map(e=>{this.relationships[e.id]=e})}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:"Relationship"},e=>({id:this.extractAttr(e,"Id",{required:!0}).asString(),target:this.extractAttr(e,"Target",{required:!0}).asString(),type:this.extractAttr(e,"Type",{required:!0}).asString()}))}getListOfXMLFiles(){return Object.entries(this.xlsxFileStructure).filter(([e])=>"images"!==e).map(([e,t])=>t).flat().filter(Te)}mapOnElements(e,t){const s=[],o=this.currentFile;let i;if(e.children){const t=this.querySelector(e.parent,e.query)?.children;i=t||[]}else i=this.querySelectorAll(e.parent,e.query);if(i)for(const e of i)try{s.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=o,s}catchErrorOnElement(e,t){const s=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([s,e.message].join("\n"))}extractAttr(e,t,s){const o=e.attributes[t];o||this.handleMissingValue(e,`attribute "${t}"`,s);const i=o?.value?o.value:s?.default;return void 0===i?void 0:new vT(i)}extractTextContent(e,t){if(void 0!==t?.default&&"string"!=typeof t.default)throw new Error("extractTextContent default value should be a string");const s="preserve"===e?.attributes["xml:space"]?.value;let o=e?.textContent;return e&&null!==o||this.handleMissingValue(e,"text content",t),o&&(o=s?o:o.trim()),o?SR(o):t?.default}extractChildAttr(e,t,s,o){let i;i="number"==typeof t?e.children[t]:this.querySelector(e,t),i||this.handleMissingValue(e,"number"==typeof t?`child at index ${t}`:`child <${t}>`,o);const n=i?this.extractAttr(i,s,o)?.asString():o?.default;return void 0!==n?new vT(n):void 0}extractChildTextContent(e,t,s){if(void 0!==s?.default&&"string"!=typeof s.default)throw new Error("extractTextContent default value should be a string");const o=this.querySelector(e,t);return o||this.handleMissingValue(e,`child <${t}>`,s),o?this.extractTextContent(o,s):s?.default}handleMissingValue(e,t,s){if(s?.required){if(void 0===s?.default)throw new Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`);this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${s.default}`)}}extractColor(e,t,s){if(!e)return s?{rgb:s}:void 0;const o=this.extractAttr(e,"theme")?.asString();let i;if(void 0!==o){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");i=this.getThemeColor(o,t.clrScheme)}else i=this.extractAttr(e,"rgb")?.asString(),i="FF000000"===i?void 0:i;return{rgb:i||s,auto:this.extractAttr(e,"auto")?.asBool(),indexed:this.extractAttr(e,"indexed")?.asNum(),tint:this.extractAttr(e,"tint")?.asNum()}}getTargetXmlFile(e){if(!e)throw new Error("Undefined target file");const t=this.processRelationshipTargetName(e.target),s=this.getListOfXMLFiles().find(e=>e.file.fileName.endsWith(t));if(!s||!s.file)throw new Error("Cannot find target file");return s}getTargetImageFile(e){if(!e)throw new Error("Undefined target file");const t=this.processRelationshipTargetName(e.target),s=this.xlsxFileStructure.images.find(e=>e.fileName.endsWith(t));if(!s)throw new Error("Cannot find target file");return s}querySelector(e,t){const s=fT(t);return e.querySelector(s)}querySelectorAll(e,t){const s=fT(t);return e.querySelectorAll(s)}getThemeColor(e,t){switch(e){case"0":return"FFFFFF";case"1":return"000000";case"2":return t[3].value;case"3":return t[2].value;default:return t[e].value}}processRelationshipTargetName(e){return e.replace(/\.+\//,"")}}class ST extends bT{getTheme(){return{clrScheme:this.mapOnElements({query:"a:clrScheme",parent:this.rootFile.file.xml,children:!0},e=>({name:e.tagName,value:this.extractChildAttr(e,0,"val",{required:!0,default:cS}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:cS}).asString()}))}}getSharedStrings(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"si"},e=>this.mapOnElements({parent:e,query:"t"},e=>this.extractTextContent(e)||"").join(""))}}class CT extends bT{theme;constructor(e,t,s,o){super(e,t,s),this.theme=o}extractConditionalFormattings(){const e=this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > conditionalFormatting"},e=>({sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),pivot:this.extractAttr(e,"pivot")?.asBool(),cfRules:this.extractCFRules(e,this.theme)}));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:"extLst x14:conditionalFormatting"},e=>({sqref:this.extractChildTextContent(e,"xm:sqref",{required:!0}).split(" "),pivot:this.extractAttr(e,"xm:pivot")?.asBool(),cfRules:this.extractCFRules(e,this.theme)}))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:"cfRule, x14:cfRule"},e=>({type:this.extractAttr(e,"type",{required:!0}).asString(),priority:this.extractAttr(e,"priority",{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:this.extractAttr(e,"dxfId")?.asNum(),stopIfTrue:this.extractAttr(e,"stopIfTrue")?.asBool(),aboveAverage:this.extractAttr(e,"aboveAverage")?.asBool(),percent:this.extractAttr(e,"percent")?.asBool(),bottom:this.extractAttr(e,"bottom")?.asBool(),operator:this.extractAttr(e,"operator")?.asString(),text:this.extractAttr(e,"text")?.asString(),timePeriod:this.extractAttr(e,"timePeriod")?.asString(),rank:this.extractAttr(e,"rank")?.asNum(),stdDev:this.extractAttr(e,"stdDev")?.asNum(),equalAverage:this.extractAttr(e,"equalAverage")?.asBool(),dataBar:this.extractCfDataBar(e,t)}))}extractCfFormula(e){return this.mapOnElements({parent:e,query:"formula"},e=>this.extractTextContent(e,{required:!0}))}extractCfColorScale(e,t){const s=this.querySelector(e,"colorScale");if(s)return{colors:this.mapOnElements({parent:s,query:"color"},e=>this.extractColor(e,t,"ffffff")),cfvos:this.extractCFVos(s)}}extractCfDataBar(e,t){const s=this.querySelector(e,"dataBar");if(s)return{color:this.extractColor(s.querySelector("color"),t,"EFF7FF"),cfvos:this.extractCFVos(s)}}extractCfIconSet(e){const t=this.querySelector(e,"iconSet, x14:iconSet");if(t)return{iconSet:this.extractAttr(t,"iconSet",{default:"3TrafficLights1"}).asString(),showValue:this.extractAttr(t,"showValue",{default:!0}).asBool(),percent:this.extractAttr(t,"percent",{default:!0}).asBool(),reverse:this.extractAttr(t,"reverse")?.asBool(),custom:this.extractAttr(t,"custom")?.asBool(),cfvos:this.extractCFVos(t),cfIcons:this.extractCfIcons(t)}}extractCfIcons(e){const t=this.mapOnElements({parent:e,query:"cfIcon, x14:cfIcon"},e=>({iconSet:this.extractAttr(e,"iconSet",{required:!0}).asString(),iconId:this.extractAttr(e,"iconId",{required:!0}).asNum()}));return 0===t.length?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:"cfvo, x14:cfvo"},e=>({type:this.extractAttr(e,"type",{required:!0}).asString(),gte:this.extractAttr(e,"gte",{default:!0})?.asBool(),value:e.attributes.val?this.extractAttr(e,"val")?.asString():this.extractChildTextContent(e,"f, xm:f")}))}}class yT extends bT{theme;constructor(e,t,s,o){super(e,t,s),this.theme=o}extractDataValidations(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > dataValidations > dataValidation"},e=>({type:this.extractAttr(e,"type",{required:!0}).asString(),operator:this.extractAttr(e,"operator",{default:"between"})?.asString(),sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),errorStyle:this.extractAttr(e,"errorStyle")?.asString(),formula1:this.extractDataValidationFormula(e,1)[0],formula2:this.extractDataValidationFormula(e,2)[0],showErrorMessage:this.extractAttr(e,"showErrorMessage")?.asBool(),errorTitle:this.extractAttr(e,"errorTitle")?.asString(),error:this.extractAttr(e,"error")?.asString(),showInputMessage:this.extractAttr(e,"showInputMessage")?.asBool(),promptTitle:this.extractAttr(e,"promptTitle")?.asString(),prompt:this.extractAttr(e,"prompt")?.asString(),allowBlank:this.extractAttr(e,"allowBlank")?.asBool()}))}extractDataValidationFormula(e,t){return this.mapOnElements({parent:e,query:`formula${t}`},e=>this.extractTextContent(e,{required:!0}))}}class IT extends bT{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},e=>{const t=this.getChartType(e);if(!HR[t])throw new Error(`Unsupported chart type ${t}`);if("combo"===HR[t])return this.extractComboChart(e);const s=this.mapOnElements({parent:e,query:"c:chart > c:title a:t"},e=>e.textContent||"").join(""),o=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString(),i=this.extractChildAttr(e,"c:barDir","val",{default:"col"}).asString(),n=this.extractChildAttr(e,"c:holeSize","val",{default:"0"}).asNum();return{title:{text:s},type:HR[t],dataSets:this.extractChartDatasets(this.querySelectorAll(e,`c:${t}`),t),labelRange:this.extractLabelRange(t,e),backgroundColor:this.extractChildAttr(e,"c:chartSpace > c:spPr a:srgbClr","val",{default:"ffffff"}).asString(),legendPosition:UR[this.extractChildAttr(e,"c:legendPos","val",{default:"none"}).asString()],stacked:"stacked"===o,fontColor:"000000",horizontal:"bar"===i,isDoughnut:n>0,pieHolePercentage:n}})[0]}extractLabelRange(e,t){return"scatterChart"===e?this.extractChildTextContent(t,"c:ser c:strRef c:f")||this.extractChildTextContent(t,"c:ser c:numRef c:f"):this.extractChildTextContent(t,"c:ser c:cat c:f")}extractComboChart(e){const t=this.mapOnElements({parent:e,query:"c:title a:t"},e=>e.textContent||"").join(""),s=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString();return{title:{text:t},type:"combo",dataSets:[...this.extractChartDatasets(this.querySelectorAll(e,"c:barChart"),"comboChart"),...this.extractChartDatasets(this.querySelectorAll(e,"c:lineChart"),"comboChart")],labelRange:this.extractChildTextContent(e,"c:ser c:cat c:f"),backgroundColor:this.extractChildAttr(e,"c:chartSpace > c:spPr a:srgbClr","val",{default:"ffffff"}).asString(),legendPosition:UR[this.extractChildAttr(e,"c:legendPos","val",{default:"none"}).asString()],stacked:"stacked"===s,fontColor:"000000"}}extractChartDatasets(e,t){return Array.from(e).map(e=>"scatterChart"===t?this.extractScatterChartDatasets(e):this.mapOnElements({parent:e,query:"c:ser"},e=>{let t={};const s=this.extractChildTextContent(e,"c:tx c:f");if(s)t={reference:s};else{const s=this.extractChildTextContent(e,"c:tx c:v");s&&(t={text:s})}const o=this.querySelectorAll(e,"c:spPr a:solidFill"),i=o.length?this.querySelector(o[0],"a:srgbClr"):void 0,n=i?i.getAttribute("val"):void 0;return{label:t,range:this.extractChildTextContent(e,"c:val c:f",{required:!0}),backgroundColor:n&&Sv(n)?`${bv(n)}`:void 0,trend:this.extractChartTrendline(e)}})).flat()}extractChartTrendline(e){const t=this.querySelector(e,"c:trendline");if(!t)return;const s=this.extractChildAttr(t,"c:trendlineType","val"),o=this.extractChildAttr(t,"a:solidFill a:srgbClr","val");return{type:s?s.asString():void 0,order:this.extractChildAttr(t,"c:order","val")?.asNum(),window:this.extractChildAttr(t,"c:period","val")?.asNum(),color:o&&Sv(o.asString())?`${bv(o.asString())}`:void 0}}extractScatterChartDatasets(e){return this.mapOnElements({parent:e,query:"c:ser"},e=>{let t={};const s=this.querySelectorAll(e,"c:spPr a:solidFill a:srgbClr"),o=s.length?s[0].getAttribute("val"):void 0,i=this.extractChildTextContent(e,"c:tx c:f");if(i)t={reference:i};else{const s=this.extractChildTextContent(e,"c:tx c:v");s&&(t={text:s})}return{label:t,range:this.extractChildTextContent(e,"c:yVal c:f",{required:!0}),trend:this.extractChartTrendline(e),backgroundColor:o&&Sv(o)?`${bv(o)}`:void 0}})}getChartType(e){const t=this.querySelector(e,"c:plotArea");if(!t)throw new Error("Missing plot area in the chart definition.");let s;for(const e of t.children){const t=pT(e.tagName);tR.some(e=>e===t)&&(s?s!==t&&(s="comboChart"):s=t)}if(s)return s;throw new Error("Unknown chart type")}}const wT="oneCellAnchor",ET="twoCellAnchor";class RT extends bT{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},e=>{const t=pT(e.tagName),s=this.extractFigureAnchorsByType(e,t),o=this.querySelector(e,"c:chart"),i=this.querySelector(e,"a:blip");if(!o&&!i)throw new Error("Only chart and image figures are currently supported.");return{anchors:s,data:o?this.extractChart(o):this.extractImage(e),figureSize:t===wT?this.extractFigureSizeFromSizeTag(e,"xdr:ext"):void 0}})}extractFigureAnchorsByType(e,t){switch(t){case wT:return[this.extractFigureAnchor("xdr:from",e)];case ET:return[this.extractFigureAnchor("xdr:from",e),this.extractFigureAnchor("xdr:to",e)];default:throw new Error(`${t} is not supported for xlsx drawings. `)}}extractFigureSizeFromSizeTag(e,t){const s=this.querySelector(e,t);if(!s)throw new Error(`Missing size element '${t}'`);return{cx:this.extractAttr(s,"cx",{required:!0}).asNum(),cy:this.extractAttr(s,"cy",{required:!0}).asNum()}}extractFigureAnchor(e,t){const s=this.querySelector(t,e);if(!s)throw new Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(s,"xdr:col",{required:!0})),colOffset:Number(this.extractChildTextContent(s,"xdr:colOff",{required:!0})),row:Number(this.extractChildTextContent(s,"xdr:row",{required:!0})),rowOffset:Number(this.extractChildTextContent(s,"xdr:rowOff",{required:!0}))}}extractChart(e){const t=this.extractAttr(e,"r:id",{required:!0}).asString(),s=this.getTargetXmlFile(this.relationships[t]),o=new IT(s,this.xlsxFileStructure,this.warningManager).extractChart();if(!o)throw new Error("Unable to extract chart definition");return o}extractImage(e){const t=this.querySelector(e,"a:blip"),s=this.extractAttr(t,"r:embed",{required:!0}).asString(),o=this.getTargetImageFile(this.relationships[s]);if(!o)throw new Error("Unable to extract image");const i=o.fileName.split(".").at(-1),n=pT(e.tagName),r=n===ET?this.querySelector(e,"a:xfrm"):e,a=n===ET?"a:ext":"xdr:ext",l=this.extractFigureSizeFromSizeTag(r,a);return{imageSrc:o.imageSrc,mimetype:i?ZR[i]:void 0,size:l}}}class xT extends bT{getPivotTable(){return this.mapOnElements({query:":root",parent:this.rootFile.file.xml},e=>({name:this.extractAttr(e,"name",{required:!0}).asString(),rowGrandTotals:this.extractAttr(e,"rowGrandTotals",{default:!0}).asBool(),location:this.extractPivotLocation(e),style:this.extractPivotStyleInfo(e)}))[0]}extractPivotLocation(e){return this.mapOnElements({query:"location",parent:e},e=>({ref:this.extractAttr(e,"ref",{required:!0}).asString(),firstHeaderRow:this.extractAttr(e,"firstHeaderRow",{required:!0}).asNum(),firstDataRow:this.extractAttr(e,"firstDataRow",{required:!0}).asNum(),firstDataCol:this.extractAttr(e,"firstDataCol",{required:!0}).asNum()}))[0]}extractPivotStyleInfo(e){return this.mapOnElements({query:"pivotTableStyleInfo",parent:e},e=>({name:this.extractAttr(e,"name",{required:!0}).asString(),showRowHeaders:this.extractAttr(e,"showRowHeaders",{required:!0}).asBool(),showColHeaders:this.extractAttr(e,"showColHeaders",{required:!0}).asBool(),showRowStripes:this.extractAttr(e,"showRowStripes",{required:!0}).asBool(),showColStripes:this.extractAttr(e,"showColStripes",{required:!0}).asBool(),showLastColumn:this.extractAttr(e,"showLastColumn")?.asBool()}))[0]}}class TT extends bT{getTable(){return this.mapOnElements({query:"table",parent:this.rootFile.file.xml},e=>({displayName:this.extractAttr(e,"displayName",{required:!0}).asString(),name:this.extractAttr(e,"name")?.asString(),id:this.extractAttr(e,"id",{required:!0}).asString(),ref:this.extractAttr(e,"ref",{required:!0}).asString(),headerRowCount:this.extractAttr(e,"headerRowCount",{default:1}).asNum(),totalsRowCount:this.extractAttr(e,"totalsRowCount",{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)}))[0]}extractTableCols(e){return this.mapOnElements({query:"tableColumn",parent:e},e=>({id:this.extractAttr(e,"id",{required:!0}).asString(),name:this.extractAttr(e,"name",{required:!0}).asString(),colFormula:this.extractChildTextContent(e,"calculatedColumnFormula")}))}extractTableStyleInfo(e){return this.mapOnElements({query:"tableStyleInfo",parent:e},e=>({name:this.extractAttr(e,"name")?.asString(),showFirstColumn:this.extractAttr(e,"showFirstColumn")?.asBool(),showLastColumn:this.extractAttr(e,"showLastColumn")?.asBool(),showRowStripes:this.extractAttr(e,"showRowStripes")?.asBool(),showColumnStripes:this.extractAttr(e,"showColumnStripes")?.asBool()}))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:"autoFilter",parent:e},e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,"ref",{required:!0}).asString()}))[0]}extractFilterColumns(e){return this.mapOnElements({query:"tableColumn",parent:e},t=>({colId:this.extractAttr(e,"colId",{required:!0}).asNum(),hiddenButton:this.extractAttr(e,"hiddenButton",{default:!1}).asBool(),filters:this.extractSimpleFilter(t)}))}extractSimpleFilter(e){return this.mapOnElements({query:"filter",parent:e},e=>({val:this.extractAttr(e,"val",{required:!0}).asString()}))}}class AT extends bT{theme;constructor(e,t,s,o){super(e,t,s),this.theme=o}getSheet(){return this.mapOnElements({query:"worksheet",parent:this.rootFile.file.xml},e=>{const t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),sheetProperties:this.extractSheetProperties(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),dataValidations:this.extractDataValidations(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:this.extractTables(e),pivotTables:this.extractPivotTables(),isVisible:"visible"===t.state}})[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:"sheetView"},e=>{const t=this.querySelector(e,"pane");return{tabSelected:this.extractAttr(e,"tabSelected",{default:!1}).asBool(),showFormulas:this.extractAttr(e,"showFormulas",{default:!1}).asBool(),showGridLines:this.extractAttr(e,"showGridLines",{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,"showRowColHeaders",{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,"xSplit",{default:0}).asNum():0,ySplit:t?this.extractAttr(t,"ySplit",{default:0}).asNum():0}}})}extractSheetName(){const e=vR(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find(t=>t.target===e).id;for(const e of this.querySelectorAll(this.xlsxFileStructure.workbook.file.xml,"sheet"))if(e.attributes["r:id"].value===t)return e.attributes.name.value;throw new Error("Missing sheet name")}getSheetWorkbookInfo(){const e=vR(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find(t=>t.target===e).id,s=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:"sheet"},e=>({relationshipId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetId:this.extractAttr(e,"sheetId",{required:!0}).asString(),sheetName:this.extractAttr(e,"name",{required:!0}).asString(),state:this.extractAttr(e,"state",{default:"visible"}).asString()})).find(e=>e.relationshipId===t);if(!s)throw new Error("Cannot find corresponding workbook sheet");return s}extractConditionalFormats(){return new CT(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractDataValidations(){return new yT(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractDataValidations()}extractFigures(e){return this.mapOnElements({parent:e,query:"drawing"},e=>{const t=this.extractAttr(e,"r:id",{required:!0})?.asString(),s=this.getTargetXmlFile(this.relationships[t]);return new RT(s,this.xlsxFileStructure,this.warningManager).extractFigures()})[0]||[]}extractTables(e){return this.mapOnElements({query:"tablePart",parent:e},e=>{const t=this.extractAttr(e,"r:id",{required:!0})?.asString(),s=this.getTargetXmlFile(this.relationships[t]);return new TT(s,this.xlsxFileStructure,this.warningManager).getTable()})}extractPivotTables(){try{return Object.values(this.relationships).filter(e=>e.type.endsWith("pivotTable")).map(e=>{const t=this.getTargetXmlFile(e);return new xT(t,this.xlsxFileStructure,this.warningManager).getPivotTable()})}catch(e){return this.catchErrorOnElement(e),[]}}extractMerges(e){return this.mapOnElements({parent:e,query:"mergeCell"},e=>this.extractAttr(e,"ref",{required:!0}).asString())}extractSheetFormat(e){const t=this.querySelector(e,"sheetFormatPr");if(t)return{defaultColWidth:this.extractAttr(t,"defaultColWidth",{default:US.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:HS.toString()}).asNum()}}extractSheetProperties(e){const t=this.querySelector(e,"sheetPr");if(t)return{outlinePr:this.extractSheetOutlineProperties(t),tabColor:this.extractColor(this.querySelector(t,"tabColor"),this.theme)}}extractSheetOutlineProperties(e){const t=this.querySelector(e,"outlinePr");if(t)return{summaryBelow:this.extractAttr(t,"summaryBelow",{default:!0}).asBool(),summaryRight:this.extractAttr(t,"summaryRight",{default:!0}).asBool()}}extractCols(e){return this.mapOnElements({parent:e,query:"cols col"},e=>({width:this.extractAttr(e,"width")?.asNum(),customWidth:this.extractAttr(e,"customWidth")?.asBool(),bestFit:this.extractAttr(e,"bestFit")?.asBool(),hidden:this.extractAttr(e,"hidden")?.asBool(),min:this.extractAttr(e,"min",{required:!0})?.asNum(),max:this.extractAttr(e,"max",{required:!0})?.asNum(),styleIndex:this.extractAttr(e,"style")?.asNum(),outlineLevel:this.extractAttr(e,"outlineLevel")?.asNum(),collapsed:this.extractAttr(e,"collapsed")?.asBool()}))}extractRows(e){const t=new Set;return this.mapOnElements({parent:e,query:"sheetData row"},e=>({index:this.extractAttr(e,"r",{required:!0})?.asNum(),cells:this.extractCells(e,t),height:this.extractAttr(e,"ht")?.asNum(),customHeight:this.extractAttr(e,"customHeight")?.asBool(),hidden:this.extractAttr(e,"hidden")?.asBool(),styleIndex:this.extractAttr(e,"s")?.asNum(),outlineLevel:this.extractAttr(e,"outlineLevel")?.asNum(),collapsed:this.extractAttr(e,"collapsed")?.asBool()}))}extractCells(e,t){return this.mapOnElements({parent:e,query:"c"},e=>{const s=this.extractAttr(e,"r",{required:!0})?.asString(),o=this.extractCellFormula(e);if(o?.ref&&void 0===o.sharedIndex){const e=wt(o.ref);for(const{col:o,row:i}of Bt(e)){const e=mt(o,i);e!==s&&t.add(e)}}const i=t.has(s);return{xc:s,styleIndex:this.extractAttr(e,"s")?.asNum(),type:_R[this.extractAttr(e,"t",{default:"n"})?.asString()],value:i?void 0:this.extractChildTextContent(e,"v")??void 0,formula:i?void 0:o}})}extractCellFormula(e){const t=this.querySelector(e,"f");if(!t)return;const s=this.extractTextContent(t),o=this.extractAttr(t,"si")?.asNum(),i=this.extractAttr(t,"ref")?.asString();return void 0!==s&&""!==s.trim()||void 0!==o?{content:s,sharedIndex:o,ref:i}:void 0}extractHyperLinks(e){return this.mapOnElements({parent:e,query:"hyperlink"},e=>{const t=this.extractAttr(e,"r:id")?.asString();return{xc:this.extractAttr(e,"ref",{required:!0})?.asString(),location:this.extractAttr(e,"location")?.asString(),display:this.extractAttr(e,"display")?.asString(),relTarget:t?this.relationships[t].target:void 0}})}extractSharedFormulas(e){const t=this.querySelectorAll(e,"f[si][ref]"),s={};for(const e of t){const t=this.extractAttr(e,"si",{required:!0}).asNum(),o=this.extractTextContent(e,{required:!0});s[t]=o}const o=[];for(let e=0;e<Object.keys(s).length;e++)s[e]?o.push(s[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),o.push(""));return o}}class DT extends bT{theme;constructor(e,t,s){super(e.styles,e,t),this.theme=s}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"numFmt"},e=>this.extractNumFormats(e))}extractNumFormats(e){return{id:this.extractAttr(e,"numFmtId",{required:!0}).asNum(),format:this.extractAttr(e,"formatCode",{required:!0,default:""}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"font"},e=>this.extractFont(e))}extractFont(e){const t=this.extractChildAttr(e,"name","val",{default:"Arial"}).asString(),s=this.extractChildAttr(e,"sz","val",{default:L.toString()}).asNum(),o=this.extractColor(this.querySelector(e,"color"),this.theme),i=this.querySelector(e,"i")||void 0,n=i&&"0"!==i.attributes.val?.value,r=this.querySelector(e,"b")||void 0,a=r&&"0"!==r.attributes.val?.value,l=this.querySelector(e,"strike")||void 0,c=l&&"0"!==l.attributes.val?.value,h=this.querySelector(e,"u")||void 0;return{name:t,size:s,color:o,italic:n,bold:a,underline:h&&"none"!==h.attributes.val?.value,strike:c}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"fill"},e=>this.extractFill(e))}extractFill(e){const t=e.children[0];return"patternFill"===t.tagName?{patternType:t.attributes.patternType?.value,bgColor:this.extractColor(this.querySelector(t,"bgColor"),this.theme),fgColor:this.extractColor(this.querySelector(t,"fgColor"),this.theme)}:{patternType:"solid",fgColor:this.extractColor(this.querySelectorAll(t,"color")[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"border"},e=>this.extractBorder(e))}extractBorder(e){const t={left:this.extractSingleBorder(e,"left",this.theme),right:this.extractSingleBorder(e,"right",this.theme),top:this.extractSingleBorder(e,"top",this.theme),bottom:this.extractSingleBorder(e,"bottom",this.theme),diagonal:this.extractSingleBorder(e,"diagonal",this.theme)};return t.diagonal&&(t.diagonalUp=this.extractAttr(e,"diagonalUp")?.asBool(),t.diagonalDown=this.extractAttr(e,"diagonalDown")?.asBool()),t}extractSingleBorder(e,t,s){const o=this.querySelector(e,t);if(o&&o.attributes.style)return{style:this.extractAttr(o,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(o.children[0],s,"000000")}}extractAlignment(e){return{horizontal:this.extractAttr(e,"horizontal",{default:"general"}).asString(),vertical:this.extractAttr(e,"vertical",{default:"bottom"}).asString(),textRotation:this.extractAttr(e,"textRotation")?.asNum(),wrapText:this.extractAttr(e,"wrapText")?.asBool(),indent:this.extractAttr(e,"indent")?.asNum(),relativeIndent:this.extractAttr(e,"relativeIndent")?.asNum(),justifyLastLine:this.extractAttr(e,"justifyLastLine")?.asBool(),shrinkToFit:this.extractAttr(e,"shrinkToFit")?.asBool(),readingOrder:this.extractAttr(e,"readingOrder")?.asNum()}}getDxfs(){return this.mapOnElements({query:"dxf",parent:this.rootFile.file.xml},e=>{const t=this.querySelector(e,"font"),s=this.querySelector(e,"fill"),o=this.querySelector(e,"border"),i=this.querySelector(e,"numFmt"),n=this.querySelector(e,"alignment");return{font:t?this.extractFont(t):void 0,fill:s?this.extractFill(s):void 0,numFmt:i?this.extractNumFormats(i):void 0,alignment:n?this.extractAlignment(n):void 0,border:o?this.extractBorder(o):void 0}})}getStyles(){return this.mapOnElements({query:"cellXfs xf",parent:this.rootFile.file.xml},e=>{const t=this.querySelector(e,"alignment");return{fontId:this.extractAttr(e,"fontId",{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,"fillId",{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,"borderId",{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,"numFmtId",{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}})}}class _T extends bT{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"externalBook"},e=>({rId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:"sheetName"},e=>this.extractAttr(e,"val",{required:!0}).asString()),datasets:this.extractExternalSheetData(e)}))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:"sheetData"},e=>{const t=this.mapOnElements({parent:e,query:"cell"},e=>({xc:this.extractAttr(e,"r",{required:!0}).asString(),value:this.extractChildTextContent(e,"v",{required:!0})})),s={};for(const e of t)s[e.xc]=e.value;return{sheetId:this.extractAttr(e,"sheetId",{required:!0}).asNum(),data:s}})}}function OT(e,t){const s=function(e,t){const s=t[GS],o=s.querySelectorAll(`Override[ContentType="${e}"]`),i=[];for(const e of o){const t=e?.attributes.PartName.value;i.push(t.substring(1))}return i}(e,t);return function(e,t){const s=[];for(const o of e){const e=FT(o,t);s.push({file:{fileName:o,xml:t[o]},rels:e?{fileName:e,xml:t[e]}:void 0})}return s}(s,t)}function FT(e,t){if(e===GS)return"_rels/.rels";let s="";const o=e.split("/");for(let e=0;e<o.length-1;e++)s+=o[e]+"/";return s+="_rels/",s+=o[o.length-1]+".rels",t[s]||(s=void 0),s}class PT{warningManager;xmls;images;constructor(e){this.warningManager=new wR,this.xmls={},this.images=[];for(const t of Object.keys(e))if(t.endsWith(".xml")||t.endsWith(".rels")){const s=mT(e[t]);this.xmls[t]=cT(new eR(s))}else t.includes("media/image")&&this.images.push({fileName:t,imageSrc:e[t].imageSrc})}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new ST(e.theme,e,this.warningManager).getTheme():void 0,s=e.sharedStrings?new ST(e.sharedStrings,e,this.warningManager).getSharedStrings():[],o=e.sheets.sort((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0})).map(s=>new AT(s,e,this.warningManager,t).getSheet()),i=e.externalLinks.map(t=>new _T(t,e,this.warningManager).getExternalBook()),n=new DT(e,this.warningManager,t);return{fonts:n.getFonts(),fills:n.getFills(),borders:n.getBorders(),dxfs:n.getDxfs(),numFmts:n.getNumFormats(),styles:n.getStyles(),sheets:o,sharedStrings:s,externalBooks:i,chartIds:[],imageIds:[]}}buildXlsxFileStructure(){const e={sheets:OT(ES.sheet,this.xmls),workbook:OT(ES.workbook,this.xmls)[0]||OT(ES.macroEnabledWorkbook,this.xmls)[0]||OT(ES.templateWorkbook,this.xmls)[0]||OT(ES.macroEnabledTemplateWorkbook,this.xmls)[0]||OT(ES.excelAddInWorkbook,this.xmls)[0],styles:OT(ES.styles,this.xmls)[0],sharedStrings:OT(ES.sharedStrings,this.xmls)[0],theme:OT(ES.themes,this.xmls)[0],charts:OT(ES.chart,this.xmls),figures:OT(ES.drawing,this.xmls),tables:OT(ES.table,this.xmls),pivots:OT(ES.pivot,this.xmls),externalLinks:OT(ES.externalLink,this.xmls),images:this.images};if(!e.workbook.rels)throw Error(fs("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:"18.4.2",sheets:qx(e,this.warningManager),styles:sx(e,this.warningManager),formats:ix(e,this.warningManager),borders:ex(e,this.warningManager),revisionId:H};return eT(t,e),Object.keys(e.styles).map(t=>{e.styles[t]=Ve(e.styles[t])}),t}}function MT(e){const t=Sf(e),s=[];return{text:"".concat(...t.map(e=>{if("REFERENCE"===e.type&&Wn.test(e.value)){const t=e.value.trim();return s.includes(t)||s.push(t),`${Z}${s.indexOf(t)}${Z}`}return e.value})),dependencies:s}}const NT={am_ET:7,ar_001:6,ar_SY:6,az_AZ:1,eu_ES:1,be_BY:1,bn_IN:1,bs_BA:1,bg_BG:1,ca_ES:1,zh_CN:7,zh_HK:7,zh_TW:7,hr_HR:1,cs_CZ:1,da_DK:1,nl_BE:1,nl_NL:1,en_AU:7,en_CA:7,en_GB:1,en_IN:7,en_NZ:7,et_EE:1,fi_FI:1,fr_BE:1,fr_CA:7,fr_CH:1,fr_FR:1,gl_ES:1,ka_GE:1,de_DE:1,de_CH:1,el_GR:1,gu_IN:7,he_IL:7,hi_IN:7,hu_HU:1,id_ID:7,it_IT:1,ja_JP:7,kab_DZ:6,km_KH:7,ko_KP:1,ko_KR:7,lo_LA:7,lv_LV:1,lt_LT:1,lb_LU:1,mk_MK:1,ml_IN:1,mn_MN:7,ms_MY:1,nb_NO:1,fa_IR:6,pl_PL:1,pt_AO:1,pt_BR:7,pt_PT:1,ro_RO:1,ru_RU:1,sr_RS:7,"sr@latin":7,sk_SK:1,sl_SI:1,es_AR:7,es_BO:1,es_CL:1,es_CO:7,es_CR:1,es_DO:1,es_EC:1,es_GT:7,es_MX:7,es_PA:7,es_PE:7,es_PY:7,es_UY:1,es_VE:7,sw:1,sv_SE:1,th_TH:7,tl_PH:1,tr_TR:1,uk_UA:1,vi_VN:1,sq_AL:1,te_IN:7,en_US:7,my_MM:7,es_ES:1,es_419:1},LT=new is;function kT(e){for(const t of e.sheets||[]){const e=[];for(const s of t.filterTables||[]){const t=wt(s.range),o=e.findIndex(e=>Lt(e,t));-1!==o?e[o]=t:e.push(t)}t.filterTables=e.map(e=>({range:Tt(e)}))}return e}function VT(){return UT().at(-1)}function UT(){return LT.getKeys().sort(GT)}LT.add("0.1",{migrate:e=>(e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e)}).add("0.2",{migrate(e){if(e.sheets&&e.sheets.length)for(const t of e.sheets)t.id=t.id||t.name;return e}}).add("0.3",{migrate(e){if(e.sheets&&e.activeSheet){const t=e.sheets.find(t=>t.name===e.activeSheet);e.activeSheet=t.id}return e}}).add("0.4",{migrate(e){for(const t of e.sheets||[])t.figures=t.figures||[];return e}}).add("0.5",{migrate(e){for(const t of e.sheets||[])for(const e in t.cells||[]){const s=t.cells[e];s.content&&s.content.startsWith("=")&&(s.formula=MT(s.content))}return e}}).add("0.6",{migrate(e){for(const t of e.sheets||[])for(const e in t.figures||[]){const{dataSets:s,...o}=t.figures[e].data,i=[];for(const e of s)if(e.labelCell){const t=wt(e.dataRange),s=e.labelCell+":"+mt(t.right,t.bottom);i.push(s)}else i.push(e.dataRange);o.dataSetsHaveTitle=Boolean(s[0].labelCell),o.dataSets=i,t.figures[e].data=o}return e}}).add("0.7",{migrate(e){const t=[];for(const s of e.sheets||[]){if(!s.name)continue;const e=s.name,o=st(de(e,"_"),t,{compute:(e,t)=>`${e}${t}`});s.name=o,t.push(o);const i=t=>{if(void 0===t)return t;let s=t.replace(e,o),i=t;for(;i!==s;)i=s,s=i.replace(e,o);return i};for(const e in s.cells){const t=s.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(i))}for(const e of s.figures||[])if("chart"===e.tag){const t=e.data.dataSets.map(i),s=i(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:s}}for(const e of s.conditionalFormats||[]){e.ranges=e.ranges.map(i);for(const t of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===e.rule[t]?.type&&(e.rule[t].value=i(e.rule[t].value))}}return e}}).add("0.8",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[])e.data.background=c,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stacked=!1;return e}}).add("0.9",{migrate(e){for(const t of e.sheets||[])for(const e in t.cells||[]){const s=t.cells[e];if(s.formula){let{text:e,dependencies:t}=s.formula;for(const[s,o]of Object.entries(t)){const t=`\\${Z}${s}\\${Z}`;e=e.replace(new RegExp(t,"g"),o)}s.content=e,delete s.formula}}return e}}).add("0.10",{migrate(e){const t={};for(const s of e.sheets||[])for(const e in s.cells||[]){const o=s.cells[e];o.format&&(o.format=ab(o.format,t))}return e.formats=t,e}}).add("15.4",{migrate(e){for(const t of e.sheets||[])t.isVisible=!0;return e}}).add("15.4.1",{migrate:e=>kT(e)}).add("16.3",{migrate(e){for(const t in e.borders){const s=e.borders[t];for(const e in s)Array.isArray(s[e])&&(s[e]={style:s[e][0],color:s[e][1]})}return e}}).add("16.4",{migrate:e=>(e.settings||(e.settings={}),e.settings.locale||(e.settings.locale=Oc),e)}).add("16.4.1",{migrate:e=>kT(e)}).add("17.2",{migrate(e){for(const t of e.sheets||[])t.tables=t.tables||t.filterTables||[],delete t.filterTables;return e}}).add("17.3",{migrate:e=>(e.pivots||(e.pivots={}),e.pivotNextId||(e.pivotNextId=Kg(e.pivots)+1),e)}).add("17.4",{migrate(e){for(const t of e.sheets||[])for(const e in t.figures||[]){const s=t.figures[e];"title"in s.data&&"string"==typeof s.data.title&&(s.data.title={text:s.data.title});const o=s.data.type;if(!["line","bar","pie","scatter","waterfall","combo"].includes(o))continue;const{dataSets:i,...n}=t.figures[e].data,r=i.map(e=>({dataRange:e}));n.dataSets=r,t.figures[e].data=n}return e}}).add("18.0",{migrate:e=>e}).add("18.0.1",{migrate(e){for(const t of Object.values(e.pivots||{}))t.measures=t.measures.map(e=>({id:e.name,fieldName:e.name,aggregator:e.aggregator})),t.columns=t.columns.map(e=>({fieldName:e.name,order:e.order,granularity:e.granularity})),t.rows=t.rows.map(e=>({fieldName:e.name,order:e.order,granularity:e.granularity}));return e}}).add("18.0.2",{migrate(e){const t=e.settings?.locale;if(t){const e=t.code;t.weekStart=NT[e]||1}return e}}).add("18.0.3",{migrate(e){for(const t of e.sheets||[]){t.styles={},t.formats={},t.borders={};for(const e in t.cells)t.styles[e]=t.cells[e].style,t.formats[e]=t.cells[e].format,t.borders[e]=t.cells[e].border,delete t.cells[e].style,delete t.cells[e].format,delete t.cells[e].border}return e}}).add("18.0.4",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[]){if("chart"!==e.tag||"gauge"!==e.data.type)continue;const t=e.data;t?.sectionRule?.lowerInflectionPoint&&(t.sectionRule.lowerInflectionPoint.operator="<="),t?.sectionRule?.upperInflectionPoint&&(t.sectionRule.upperInflectionPoint.operator="<=")}return e}}).add("18.1",{migrate(e){for(const t of e.sheets||[])for(const e of t.tables||[])e.config||(e.config={...hE,hasFilters:!0});return e}}).add("18.1.1",{migrate(e){for(const t of e.sheets||[])for(const e in t.cells){const s=t.cells[e];s&&(t.cells[e]=s.content)}return e}}).add("18.2",{migrate:e=>e}).add("18.3",{migrate(e){if(!e.pivots)return e;for(const t of Object.values(e.pivots)){if(!t.sortedColumn)continue;t.measures.map(e=>e.id).includes(t.sortedColumn.measure)||delete t.sortedColumn}return e}}).add("18.3.1",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[]){const t=e;e.offset={x:t.x||0,y:t.y||0},e.col=0,e.row=0,delete e.x,delete e.y}return e}}).add("18.4.1",{migrate(e){const t={textContains:"containsText",textNotContains:"notContainsText",textIs:"isEqualText",textIsEmail:"isEmail",textIsLink:"isLink"},s={BeginsWith:"beginsWithText",Between:"isBetween",ContainsText:"containsText",EndsWith:"endsWithText",Equal:"isEqual",GreaterThan:"isGreaterThan",GreaterThanOrEqual:"isGreaterOrEqualTo",IsEmpty:"isEmpty",IsNotEmpty:"isNotEmpty",LessThan:"isLessThan",LessThanOrEqual:"isLessOrEqualTo",NotBetween:"isNotBetween",NotContains:"notContainsText",NotEqual:"isNotEqual"};for(const t of e.sheets||[])for(const e of t.conditionalFormats||[])"CellIsRule"===e.rule.type&&(e.rule.operator=s[e.rule.operator]);for(const s of e.sheets||[])for(const e of s.dataValidationRules||[])e.criterion.type in t&&(e.criterion.type=t[e.criterion.type]);return e}}).add("18.4.2",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[]){if("chart"!==e.tag||"scorecard"!==e.data.type)continue;const t=e.data;t.baselineDescr&&(t.baselineDescr={text:t.baselineDescr})}return e}}).add("18.4.3",{migrate(e){if(!e.pivots)return e;for(const t in e.pivots){const s=e.pivots[t];if(s.sortedColumn){const e=s.measures.find(e=>e.fieldName===s.sortedColumn?.measure);e&&(s.sortedColumn.measure=e.id)}}return e}}).add("18.5.1",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[])"chart"===e.tag&&(e.data.chartId=e.id);return e}});const HT="Sheet1";function zT(e,t){if(!e)return ZT();console.debug("### Loading data ###");const s=performance.now();if(e["[Content_Types].xml"]){const s=new PT(e);if(e=s.convertXlsx(),t)for(const e of s.warningManager.warnings.sort())console.warn(e)}return"version"in e&&(function(e){return"number"==typeof e.version}(e)&&(e.version=BT[e.version]),e.version!==VT()&&(console.debug("Migrating data from version",e.version),e=function(e){const t=performance.now(),s=UT();for(let t=s.findIndex(t=>t===e.version)+1;t<s.length;t++){const o=s[t];e=LT.get(o).migrate(e)}return console.debug("Data migrated in",performance.now()-t,"ms"),e}(e))),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,s=new lr;for(const o of e.sheets||[])for(const e of o.figures||[])t.has(e.id)&&(e.id+=s.smallUuid()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){const t=Object.assign(ZT(),e,{version:VT()});t.sheets=t.sheets?t.sheets.map((e,t)=>Object.assign(qT(`Sheet${t+1}`,`Sheet${t+1}`),e)):[],0===t.sheets.length&&t.sheets.push(qT(HT,"Sheet1"));Xc(t.settings.locale)||(t.settings.locale=Oc);return t}(e),e}(e),console.debug("Data loaded in",performance.now()-s,"ms"),console.debug("###"),e}const BT={25:"18.2",24:"18.1.1",23:"18.1",22:"18.0.4",21:"18.0.3",20:"18.0.2",19:"18.0.1",18:"18.0",17:"17.4",16:"17.3",15:"17.2",14:"16.4",13:"16.3",12:"15.4",11:"0.10",10:"0.9",9:"0.8",8:"0.7",7:"0.6",6:"0.5",5:"0.4",4:"0.3",3:"0.2",2:"0.1",1:"0"};function GT(e,t){const s=e.split(".").map(Number),o=t.split(".").map(Number);for(let e=0;e<Math.max(s.length,o.length);e++){const t=s[e]||0,i=o[e]||0;if(t>i)return 1;if(t<i)return-1}return 0}function WT(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const s=[],o=[],i=e=>{if("CREATE_SHEET"===e.type)s.push(e.sheetId);else if("sheetId"in e&&!s.includes(e.sheetId))return{...e,sheetId:HT};return e};for(const e of t)"REMOTE_REVISION"===e.type?o.push({...e,commands:e.commands.map(i)}):o.push(e);return o}(e,t),t=$T(t,"SORT_CELLS"),t=function(e,t){const s=[],o={};for(const t of e.sheets||[])t.figures?.forEach(t=>{"chart"===t.tag&&(e.version&>(String(e.version),"18.5.1")<=0?o[t.data.chartId]=t.data:o[t.id]=t.data)});for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const s of e.commands){let e=s;switch(s.type){case"CREATE_CHART":o[s.chartId]=s.definition;break;case"UPDATE_CHART":if(!o[s.chartId]){console.log(`Fix chart definition: chart with id ${s.chartId} not found.`);continue}const t={...o[s.chartId],...s.definition};e={...s,definition:t},o[s.chartId]=t}t.push(e)}s.push({...e,commands:t})}else s.push(e);return s}(e,t=$T(t,"SET_DECIMAL")),t=function(e,t){const s={};for(const t of e.sheets||[])t.figures?.forEach(e=>{s[e.id]=e.offset});for(const e of t)if("REMOTE_REVISION"===e.type)for(const t of e.commands)switch(t.type){case"UPDATE_FIGURE":t.offset&&(void 0===t.offset.x&&(t.offset.x=s[t.figureId]||0),void 0===t.offset.y&&(t.offset.y=s[t.figureId]||0),s[t.figureId]=s);break;case"CREATE_IMAGE":case"CREATE_CHART":case"CREATE_FIGURE":s[t.figureId]=t.offset}return t}(e,t),t=function(e,t){const s={};for(const t of e.sheets||[])s[t.id]=t.name;const o=[];for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const o of e.commands){switch(o.type){case"DUPLICATE_SHEET":o.sheetNameTo=o.sheetNameTo??fb(s[o.sheetId],Object.values(s));break;case"CREATE_SHEET":s[o.sheetId]=o.name||mb(Object.values(s));break;case"RENAME_SHEET":s[o.sheetId]=o.newName||mb(Object.values(s))}t.push(o)}o.push({...e,commands:t})}else o.push(e);return t}(e,t),t}function $T(e,t){const s=[];for(const o of e)"REMOTE_REVISION"===o.type?s.push({...o,commands:o.commands.filter(e=>e.type!==t)}):s.push(o);return s}function qT(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},styles:{},formats:{},borders:{},cols:{},rows:{},merges:[],conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],isVisible:!0}}function ZT(e="Sheet1"){return{version:VT(),sheets:[qT(HT,e)],styles:{},formats:{},borders:{},revisionId:H,uniqueFigureIds:!0,settings:{locale:Oc},pivots:{},pivotNextId:1,customTableStyles:{}}}function jT(e,t){return{...qT(e,t),charts:[],images:[],cellValues:{}}}class YT{map={};constructor(e=[]){for(const[t,s]of e)this.set(t,s)}set({sheetId:e,col:t,row:s},o){const i=this.map;i[e]||(i[e]={}),i[e][t]||(i[e][t]={}),i[e][t][s]=o}setMany(e){for(const[t,s]of e)this.set(t,s)}get({sheetId:e,col:t,row:s}){return this.map[e]?.[t]?.[s]}getSheet(e){return this.map[e]}clearSheet(e){delete this.map[e]}has({sheetId:e,col:t,row:s}){return void 0!==this.map[e]?.[t]?.[s]}delete({sheetId:e,col:t,row:s}){delete this.map[e]?.[t]?.[s]}keys(){const e=this.map,t=[];for(const s in e)for(const o in e[s])for(const i in e[s][o])t.push({sheetId:s,col:parseInt(o),row:parseInt(i)});return t}keysForSheet(e){const t=this.map[e];if(!t)return[];const s=[];for(const o in t)for(const i in t[o])s.push({sheetId:e,col:parseInt(o),row:parseInt(i)});return s}*entries(){const e=this.map;for(const t of this.keys()){const{sheetId:s,col:o,row:i}=t;yield[t,e[s][o][i]]}}}class XT extends yr{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:s,dispatch:o,canDispatch:i}){super(t),s.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=o,this.canDispatch=i}import(e){}export(e){}adaptRanges(e,t,s){}garbageCollectExternalResources(){}}class KT{id;format;style;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,s,o,i,n,r){this.id=e,this.format=s,this.style=o,this.sheetId=n,this.getRangeString=r;let a=0;const l=t.tokens.map(e=>{if("REFERENCE"===e.type){const e=a++;return new JT(i,e,this.sheetId,this.getRangeString)}return e});this.compiledFormula={...t,dependencies:i,tokens:l}}get content(){return _e(this.compiledFormula.tokens.map(e=>e.value))}get contentWithFixedReferences(){let e=0;return _e(this.compiledFormula.tokens.map(t=>{if("REFERENCE"===t.type){const t=e++;return this.getRangeString(this.compiledFormula.dependencies[t],this.sheetId,{useBoundedReference:!0})}return t.value}))}}class JT{ranges;rangeIndex;sheetId;getRangeString;type="REFERENCE";constructor(e,t,s,o){this.ranges=e,this.rangeIndex=t,this.sheetId=s,this.getRangeString=o}get value(){const e=this.ranges[this.rangeIndex];return this.getRangeString(e,this.sheetId)}}const QT=new Og;QT.add("containsText",{type:"containsText",isValueValid:(e,t)=>String(e).toLowerCase().includes(String(t.values[0]).toLowerCase()),getErrorString:e=>fs('The value must be a text that contains "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Ag.CriterionError.notEmptyValue,numberOfValues:()=>1,name:fs("Text contains"),getPreview:e=>fs('Text contains "%s"',e.values[0])}),QT.add("notContainsText",{type:"notContainsText",isValueValid:(e,t)=>!String(e).toLowerCase().includes(String(t.values[0]).toLowerCase()),getErrorString:e=>fs('The value must be a text that does not contain "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Ag.CriterionError.notEmptyValue,numberOfValues:()=>1,name:fs("Text does not contain"),getPreview:e=>fs('Text does not contain "%s"',e.values[0])}),QT.add("isEqualText",{type:"isEqualText",isValueValid:(e,t)=>String(e).toLowerCase()===String(t.values[0]).toLowerCase(),getErrorString:e=>fs('The value must be exactly "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Ag.CriterionError.notEmptyValue,numberOfValues:()=>1,name:fs("Text is exactly"),getPreview:e=>fs('Text is exactly "%s"',e.values[0])});const eA=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/;function tA(e,t){return e.values.map(e=>void 0!==e?Qc(String(e),t):bs.InvalidReference)}function sA(e,t){return ob(e,Oc).map(e=>void 0!==e?pn(e,{locale:t,format:t.dateFormat}):bs.InvalidReference)}function oA(e){return void 0!==Ws(e,Oc)}function iA(e){return void 0!==So(e,Oc)}function nA(e){return""===e?NaN:Number(e)}QT.add("isEmail",{type:"isEmail",isValueValid:(e,t)=>"string"==typeof e&&eA.test(e),getErrorString:()=>fs("The value must be a valid email address"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:fs("Text is valid email"),getPreview:()=>fs("Text is valid email")}),QT.add("isLink",{type:"isLink",isValueValid:(e,t)=>void 0!==$f(e),getErrorString:()=>fs("The value must be a valid link"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:fs("Text is valid link"),getPreview:()=>fs("Text is valid link")}),QT.add("dateIs",{type:"dateIs",isValueValid:(e,t)=>{const s=ob(t,Oc)[0],o=Ws(e,Oc);if(void 0===o||void 0===s)return!1;if(["lastWeek","lastMonth","lastYear"].includes(t.dateValue)){return no(o,Ys(Os.now()),s)}return i=o,n=s,Math.trunc(i)===Math.trunc(n);var i,n},getErrorString:(e,t)=>{const s=t.getLocale();return"exactDate"===e.dateValue?fs("The value must be the date %s",sA(e,s)[0]):fs("The value must be %s",Ag.DateIs[e.dateValue])},isCriterionValueValid:e=>oA(e),criterionValueErrorString:Ag.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:fs("Date is"),getPreview:(e,t)=>"exactDate"===e.dateValue?fs("Date is %s",ib(e.values,t.getLocale())[0]):fs("Date is %s",Ag.DateIs[e.dateValue])}),QT.add("dateIsBefore",{type:"dateIsBefore",isValueValid:(e,t)=>{const s=ob(t,Oc)[0],o=Ws(e,Oc);return void 0!==o&&void 0!==s&&function(e,t){return Math.trunc(e)<Math.trunc(t)}(o,s)},getErrorString:(e,t)=>{const s=t.getLocale();return"exactDate"===e.dateValue?fs("The value must be a date before %s",sA(e,s)[0]):fs("The value must be a date before %s",Ag.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>oA(e),criterionValueErrorString:Ag.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:fs("Date is before"),getPreview:(e,t)=>"exactDate"===e.dateValue?fs("Date is before %s",ib(e.values,t.getLocale())[0]):fs("Date is before %s",Ag.DateIsBefore[e.dateValue])}),QT.add("dateIsOnOrBefore",{type:"dateIsOnOrBefore",isValueValid:(e,t)=>{const s=ob(t,Oc)[0],o=Ws(e,Oc);return void 0!==o&&void 0!==s&&function(e,t){return Math.trunc(e)<=Math.trunc(t)}(o,s)},getErrorString:(e,t)=>{const s=t.getLocale();return"exactDate"===e.dateValue?fs("The value must be a date on or before %s",sA(e,s)[0]):fs("The value must be a date on or before %s",Ag.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>oA(e),criterionValueErrorString:Ag.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:fs("Date is on or before"),getPreview:(e,t)=>"exactDate"===e.dateValue?fs("Date is on or before %s",ib(e.values,t.getLocale())[0]):fs("Date is on or before %s",Ag.DateIsBefore[e.dateValue])}),QT.add("dateIsAfter",{type:"dateIsAfter",isValueValid:(e,t)=>{const s=ob(t,Oc)[0],o=Ws(e,Oc);return void 0!==o&&void 0!==s&&function(e,t){return Math.trunc(e)>Math.trunc(t)}(o,s)},getErrorString:(e,t)=>{const s=t.getLocale();return"exactDate"===e.dateValue?fs("The value must be a date after %s",sA(e,s)[0]):fs("The value must be a date after %s",Ag.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>oA(e),criterionValueErrorString:Ag.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:fs("Date is after"),getPreview:(e,t)=>"exactDate"===e.dateValue?fs("Date is after %s",ib(e.values,t.getLocale())[0]):fs("Date is after %s",Ag.DateIsBefore[e.dateValue])}),QT.add("dateIsOnOrAfter",{type:"dateIsOnOrAfter",isValueValid:(e,t)=>{const s=ob(t,Oc)[0],o=Ws(e,Oc);return void 0!==o&&void 0!==s&&function(e,t){return Math.trunc(e)>=Math.trunc(t)}(o,s)},getErrorString:(e,t)=>{const s=t.getLocale();return"exactDate"===e.dateValue?fs("The value must be a date on or after %s",sA(e,s)[0]):fs("The value must be a date on or after %s",Ag.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>oA(e),criterionValueErrorString:Ag.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:fs("Date is on or after"),getPreview:(e,t)=>"exactDate"===e.dateValue?fs("Date is on or after %s",ib(e.values,t.getLocale())[0]):fs("Date is on or after %s",Ag.DateIsBefore[e.dateValue])}),QT.add("dateIsBetween",{type:"dateIsBetween",isValueValid:(e,t)=>{const s=ob(t,Oc),o=Ws(e,Oc);return void 0!==o&&void 0!==s[0]&&void 0!==s[1]&&no(o,s[0],s[1])},getErrorString:(e,t)=>{const s=sA(e,t.getLocale());return fs("The value must be a date between %s and %s",s[0],s[1])},isCriterionValueValid:e=>oA(e),criterionValueErrorString:Ag.CriterionError.dateValue,numberOfValues:()=>2,name:fs("Date is between"),getPreview:(e,t)=>{const s=ib(e.values,t.getLocale());return fs("Date is between %s and %s",s[0],s[1])}}),QT.add("dateIsNotBetween",{type:"dateIsNotBetween",isValueValid:(e,t)=>{const s=ob(t,Oc),o=Ws(e,Oc);return void 0!==o&&void 0!==s[0]&&void 0!==s[1]&&!no(o,s[0],s[1])},getErrorString:(e,t)=>{const s=sA(e,t.getLocale());return fs("The value must be a date not between %s and %s",s[0],s[1])},isCriterionValueValid:e=>oA(e),criterionValueErrorString:Ag.CriterionError.dateValue,numberOfValues:()=>2,name:fs("Date is not between"),getPreview:(e,t)=>{const s=ib(e.values,t.getLocale());return fs("Date is not between %s and %s",s[0],s[1])}}),QT.add("dateIsValid",{type:"dateIsValid",isValueValid:(e,t)=>void 0!==Ws(e,Oc),getErrorString:()=>fs("The value must be a valid date"),isCriterionValueValid:e=>oA(e),criterionValueErrorString:"",numberOfValues:()=>0,name:fs("Is valid date"),getPreview:()=>fs("Date is valid")}),QT.add("isEqual",{type:"isEqual",isValueValid:(e,t)=>e===t.values[0],getErrorString:(e,t)=>{const s=tA(e,t.getLocale());return fs("The value must be equal to %s",s[0])},isCriterionValueValid:e=>iA(e),criterionValueErrorString:Ag.CriterionError.numberValue,numberOfValues:()=>1,name:fs("Is equal to"),getPreview:e=>fs("Value is equal to %s",e.values[0])}),QT.add("isNotEqual",{type:"isNotEqual",isValueValid:(e,t)=>e!==t.values[0],getErrorString:(e,t)=>{const s=tA(e,t.getLocale());return fs("The value must not be equal to %s",s[0])},isCriterionValueValid:e=>iA(e),criterionValueErrorString:Ag.CriterionError.numberValue,numberOfValues:()=>1,name:fs("Is not equal to"),getPreview:e=>fs("Value is not equal to %s",e.values[0])}),QT.add("isGreaterThan",{type:"isGreaterThan",isValueValid:(e,t)=>{if("number"!=typeof e)return!1;const s=t.values[0];return"number"==typeof s&&e>s},getErrorString:(e,t)=>{const s=tA(e,t.getLocale());return fs("The value must be greater than %s",s[0])},isCriterionValueValid:e=>iA(e),criterionValueErrorString:Ag.CriterionError.numberValue,numberOfValues:()=>1,name:fs("Is greater than"),getPreview:e=>fs("Value is greater than %s",e.values[0])}),QT.add("isGreaterOrEqualTo",{type:"isGreaterOrEqualTo",isValueValid:(e,t)=>{if("number"!=typeof e)return!1;const s=t.values[0];return"number"==typeof s&&e>=s},getErrorString:(e,t)=>{const s=tA(e,t.getLocale());return fs("The value must be greater or equal to %s",s[0])},isCriterionValueValid:e=>iA(e),criterionValueErrorString:Ag.CriterionError.numberValue,numberOfValues:()=>1,name:fs("Is greater or equal to"),getPreview:e=>fs("Value is greater or equal to %s",e.values[0])}),QT.add("isLessThan",{type:"isLessThan",isValueValid:(e,t)=>{if("number"!=typeof e)return!1;const s=t.values[0];return"number"==typeof s&&e<s},getErrorString:(e,t)=>{const s=tA(e,t.getLocale());return fs("The value must be less than %s",s[0])},isCriterionValueValid:e=>iA(e),criterionValueErrorString:Ag.CriterionError.numberValue,numberOfValues:()=>1,name:fs("Is less than"),getPreview:e=>fs("Value is less than %s",e.values[0])}),QT.add("isLessOrEqualTo",{type:"isLessOrEqualTo",isValueValid:(e,t)=>{if("number"!=typeof e)return!1;const s=t.values[0];return"number"==typeof s&&e<=s},getErrorString:(e,t)=>{const s=tA(e,t.getLocale());return fs("The value must be less or equal to %s",s[0])},isCriterionValueValid:e=>iA(e),criterionValueErrorString:Ag.CriterionError.numberValue,numberOfValues:()=>1,name:fs("Is less or equal to"),getPreview:e=>fs("Value is less or equal to %s",e.values[0])}),QT.add("isBetween",{type:"isBetween",isValueValid:(e,t)=>"number"==typeof e&&("number"==typeof t.values[0]&&"number"==typeof t.values[1]&&Ye(e,t.values[0],t.values[1])),getErrorString:(e,t)=>{const s=tA(e,t.getLocale());return fs("The value must be between %s and %s",s[0],s[1])},isCriterionValueValid:e=>iA(e),criterionValueErrorString:Ag.CriterionError.numberValue,numberOfValues:()=>2,name:fs("Is between"),getPreview:e=>fs("Value is between %s and %s",e.values[0],e.values[1])}),QT.add("isNotBetween",{type:"isNotBetween",isValueValid:(e,t)=>"number"==typeof e&&("number"==typeof t.values[0]&&"number"==typeof t.values[1]&&!Ye(e,t.values[0],t.values[1])),getErrorString:(e,t)=>{const s=tA(e,t.getLocale());return fs("The value must not be between %s and %s",s[0],s[1])},isCriterionValueValid:e=>iA(e),criterionValueErrorString:Ag.CriterionError.numberValue,numberOfValues:()=>2,name:fs("Is not between"),getPreview:e=>fs("Value is not between %s and %s",e.values[0],e.values[1])}),QT.add("isBoolean",{type:"isBoolean",isValueValid:(e,t)=>""===e||"boolean"==typeof e,getErrorString:()=>fs("The value must be a boolean"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:fs("Checkbox"),getPreview:()=>fs("Checkbox")}),QT.add("isValueInList",{type:"isValueInList",isValueValid:(e,t)=>null!==e&&t.values.map(e=>String(e).toLowerCase()).includes(e.toString().toLowerCase()),getErrorString:e=>fs("The value must be one of: %s",e.values.join(", ")),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>{},allowedValues:"onlyLiterals",name:fs("Value in list"),getPreview:e=>fs("Value one of: %s",e.values.join(", "))}),QT.add("isValueInRange",{type:"isValueInList",isValueValid:(e,t,s,o)=>{if(!e)return!1;return s.getDataValidationRangeValues(o,t).map(e=>e.value.toLowerCase()).includes(e.toString().toLowerCase())},getErrorString:e=>fs("The value must be a value in the range %s",String(e.values[0])),isCriterionValueValid:e=>Xn.test(e),criterionValueErrorString:Ag.CriterionError.validRange,numberOfValues:()=>1,allowedValues:"onlyLiterals",name:fs("Value in range"),getPreview:e=>fs("Value in range %s",e.values[0])}),QT.add("customFormula",{type:"customFormula",isValueValid:(e,t)=>{const s=t.values[0];return("number"==typeof s||"boolean"==typeof s)&&!!s},getErrorString:()=>fs("The value does not match the custom formula data validation rule"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>1,allowedValues:"onlyFormulas",name:fs("Custom formula"),getPreview:e=>fs("Custom formula %s",e.values[0])}),QT.add("beginsWithText",{type:"beginsWithText",isValueValid:(e,t)=>String(e).toLowerCase().startsWith(String(t.values[0]).toLowerCase()),getErrorString:e=>fs('The value must be a text that begins with "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Ag.CriterionError.notEmptyValue,numberOfValues:()=>1,name:fs("Text begins with"),getPreview:e=>fs('Text begins with "%s"',e.values[0])}),QT.add("endsWithText",{type:"endsWithText",isValueValid:(e,t)=>String(e).toLowerCase().endsWith(String(t.values[0]).toLowerCase()),getErrorString:e=>fs('The value must be a text that ends with "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Ag.CriterionError.notEmptyValue,numberOfValues:()=>1,name:fs("Text ends with"),getPreview:e=>fs('Text ends with "%s"',e.values[0])}),QT.add("isEmpty",{type:"isEmpty",isValueValid:(e,t)=>""===(e??"").toString().trim(),getErrorString:()=>fs("The value must be empty"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:fs("Is empty"),getPreview:()=>fs("Is empty")}),QT.add("isNotEmpty",{type:"isNotEmpty",isValueValid:(e,t)=>""!==(e??"").toString().trim(),getErrorString:()=>fs("The value must not be empty"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:fs("Is not empty"),getPreview:()=>fs("Is not empty")});function rA(e){return Object.entries(e).map(([e,t])=>t?aA(parseInt(e,10),t):void 0).filter(Te).map(e=>mt(e.left,e.top)+":"+mt(e.right,e.bottom))}function aA(e,t){return{...t.zone,id:e}}function lA(e,t){const s=e.definition.rows.map(e=>e.nameWithGranularity),o=t.filter(e=>s.includes(e.field)),i=e.definition.columns.map(e=>e.nameWithGranularity);return{colDomain:t.filter(e=>i.includes(e.field)),rowDomain:o}}function cA(e,t,s){return"column"===t?lA(e,s).colDomain:lA(e,s).rowDomain}function hA(e,t){return void 0!==dA(e,t)}function dA(e,t,s){let o=t;for(const t of e){const e=o.find(e=>e.value===t.value);if(!e)return;if(e.field===s)return o;o=e.children}return o}function uA(e,t,s){const o=(e=ae(e)).find(e=>e.field===t);return o?(o.value=s,e):e}function gA(e,t){return t.some(t=>t.field===e)}function pA(e,t){if(e.definition.rows.map(e=>e.nameWithGranularity).includes(t))return"row";if(e.definition.columns.map(e=>e.nameWithGranularity).includes(t))return"column";throw new Error(`Field ${t} not found in pivot`)}function mA(e){return e?e.map(fA).join(", "):""}function fA(e){return e?`${e.field}=${e.value}`:""}function vA(e,t){const s=e.findIndex(e=>e.field===t);if(-1===s)return"";const o=e.slice(0,s),i=e.at(-1);return mA(i.field===t?o:[...o,i])}function bA(e,t){const s=e.findIndex(e=>e.field===t);return-1===s?"":mA([...e.slice(0,s),...e.slice(s+1)])}function SA(e,t,s){const o=[...e],i=[...t];o.sort((e,t)=>s([...i,e],[...i,t]));for(const t of e){const e=SA(t.children,[...i,t],s);t.children=e}return o}function CA(e,t){return e.length>t.length&&t.every((t,s)=>Me(t,e[s]))}class yA{columns;rows;measures;fieldsType;maxIndent;pivotCells={};rowTree;colTree;isSorted=!1;constructor(e,t,s,o,i={COL:[],ROW:[]}){this.measures=s,this.fieldsType=o,i.COL.length&&(e=this.removeCollapsedColumns(e,s,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=Oe(()=>this.buildRowsTree()),this.colTree=Oe(()=>this.buildColumnsTree())}removeCollapsedColumns(e,t,s){const o=(s,o)=>{const i=this.getDomain(s),n=e[o],r=n.findIndex(e=>CA(this.getDomain(e),i)),a=n.findLastIndex(e=>CA(this.getDomain(e),i)),l=o===e.length-1,c=t.map(e=>({fields:l?[...s.fields,"measure"]:[],values:l?[...s.values,e]:[],width:1,offset:0,collapsedHeader:!l}));n.splice(r,a-r+1,...c)};return e.map((i,n)=>{for(const r of i){if(n>=e.length-2)return i;const a=this.getDomain(r);if(s.some(e=>Me(a,e))){r.width=t.length;for(let t=n+1;t<e.length;t++)o(r,t)}}return i})}isParentCollapsed(e,t){const s=this.getDomain(t);return e.some(e=>CA(s,e))}getNumberOfDataColumns(){return this.columns.at(-1)?.length||0}getSkippedRows(e){const 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}){const t=JSON.stringify(e);if(!this.pivotCells[t]){const{displayTotals:s}=e,o=this.rows.length,i=this.getNumberOfDataColumns();let n=this.columns.length+o,r=1+i;s||1===o||(n-=1),s||i===this.measures.length||(r-=this.measures.length);const a=[],l=this.getSkippedRows(e);for(let e=0;e<r;e++){a.push([]);for(let t=0;t<n;t++)l.has(t)||a[e].push(this.getPivotCell(e,t,s))}this.pivotCells[t]=a}return this.pivotCells[t]}getRowTree(){return this.rowTree()}getColTree(){return this.colTree()}isTotalRow(e){return this.rows[e].indent!==this.maxIndent}getPivotCell(e,t,s=!0){const o=this.columns.length;if(e>0&&t===o-1){const s=this.getColHeaderDomain(e,t);if(!s)return IA;const o=s.at(-1)?.value?.toString()||"";return{type:"MEASURE_HEADER",domain:s.slice(0,-1),measure:o}}if(t<=o-1){const s=this.getColHeaderDomain(e,t);return s?{type:"HEADER",domain:s,dimension:"COL"}:IA}if(0===e){const e=t-o;return{type:"HEADER",domain:this.getDomain(this.rows[e]),dimension:"ROW"}}{const i=t-o;if(!s&&this.isTotalRow(i))return IA;return{type:"VALUE",domain:[...this.getDomain(this.rows[i]),...this.getColDomain(e)],measure:this.getColMeasure(e)}}}getColHeaderDomain(e,t){if(0===e)return;const s=this.columns[t].find(t=>t.offset===e);return s&&!s.collapsedHeader?this.getDomain(s):void 0}getDomain(e){return e.fields.map((t,s)=>{if("measure"===t)return{type:"char",field:t,value:np({displayName:"measure",type:"char"},e.values[s])};{const{fieldName:o,granularity:i}=ep(t),n=this.fieldsType[o]||"char";return{type:n,field:t,value:np({displayName:o,type:n,granularity:i},e.values[s])}}})}getColDomain(e){const t=this.getColHeaderDomain(e,this.columns.length-1);return t?t.slice(0,-1):[]}getColMeasure(e){const t=this.getColHeaderDomain(e,this.columns.length-1),s=t?.at(-1)?.value;if(null==s)throw new Error("Measure is missing");return s.toString()}buildRowsTree(){const e=[];let t=0;const s={};s[0]=e;for(const o of this.rows){if(0===o.fields.length||0===o.values.length)return e;const i=o.fields.length-1,n=o.fields[i],{fieldName:r,granularity:a}=ep(n),l=np({displayName:r,type:this.fieldsType[r]??"char",granularity:a},o.values[i]);if(i>t){t=i,s[t]=[];const e=s[t-1].at(-1);e&&(e.children=s[t])}t=i;const c={value:l,field:o.fields[i],children:[],type:this.fieldsType[r]||"char",width:0};s[t].push(c)}return e}buildColumnsTree(){const e=[],t=this.columns.at(-2)||[],s={};s[0]=e;for(const e of t)for(let t=0;t<e.fields.length;t++){const o=e.fields[t],{fieldName:i,granularity:n}=ep(o),r=np({displayName:i,type:this.fieldsType[i]??"char",granularity:n},e.values[t]),a={value:r,field:e.fields[t],children:[],width:e.width,type:this.fieldsType[i]||"char"};s[t]?.at(-1)?.value!==r&&(s[t+1]=[],a.children=s[t+1],s[t].push(a))}return e}export(){return{cols:this.columns,rows:this.rows,measures:this.measures,fieldsType:this.fieldsType}}sort(e,t,s){if(this.isSorted)return;const o=(e,t)=>{const o=s(e,t).value;return"number"==typeof o?o:-1/0},i=t.domain,n=SA(this.rowTree(),[],(s,n)=>{const r=o(e,[...s,...i]),a=o(e,[...n,...i]);return"asc"===t.order?r-a:a-r});this.rowTree=Oe(n),this.rows=[...this.rowTreeToRows(n),this.rows[this.rows.length-1]],this.isSorted=!0}rowTreeToRows(e,t){return e.flatMap(e=>{const s={indent:t?t.indent+1:1,fields:[...t?.fields||[],e.field],values:[...t?.values||[],e.value]};return[s,...this.rowTreeToRows(e.children,s)]})}get numberOfCells(){return this.rows.length*this.getNumberOfDataColumns()}getColumnDomainsAtDepth(e){return e<0||e>=this.columns.length-1?[]:this.columns[e].map(e=>this.getDomain(e)).filter(e=>e.length)}getRowDomainsAtDepth(e){return e<0||e>this.maxIndent?[]:this.rows.filter(t=>t.indent===e+1).map(e=>this.getDomain(e))}}const IA={type:"EMPTY"};function wA(e,t){if(!e)return;const s=t(e);switch(s.changeType){case"NONE":return e;case"REMOVE":return;default:return s.range}}const EA=["wholeTable","firstColumnStripe","secondColumnStripe","firstRowStripe","secondRowStripe","firstColumn","lastColumn","headerRow","totalRow"];function RA(e){const t=e.range;return{row:t.zone.top,col:t.zone.left,sheetId:t.sheetId}}function xA(e,t,s,o){const i=t.zone;if(i.left!==i.right)throw new Error("Can only define a filter on a single column");const n={...i,top:i.top+s.numberOfHeaders},r=o(t.sheetId,n);return{id:e,rangeWithHeaders:t,col:i.left,filteredRange:n.top>n.bottom?void 0:r}}function TA(e){return"static"===e.type||"forceStatic"===e.type}function AA(e,t,s,o){return{borders:DA(e,t,s,o),styles:OA(e,t,s,o)}}function DA(e,t,s,o){const i=ko(s,o,()=>({}));for(const n of EA){const r=t[n]?.border;if(!r)continue;const a=PA(n,e,s,o);for(const t of a)for(let a=t.left;a<=t.right;a++)for(let l=t.top;l<=t.bottom;l++){const c="wholeTable"===n&&l<=e.numberOfHeaders-1;l===t.top&&r?.top?_A(i,"top",r.top,a,l,s,o):l!==t.top&&!c&&r?.horizontal&&_A(i,"top",r.horizontal,a,l,s,o),l===t.bottom&&r?.bottom&&_A(i,"bottom",r.bottom,a,l,s,o),a===t.left&&r?.left&&_A(i,"left",r.left,a,l,s,o),a===t.right&&r?.right?_A(i,"right",r.right,a,l,s,o):a!==t.right&&!c&&r?.vertical&&_A(i,"right",r.vertical,a,l,s,o)}}return i}function _A(e,t,s,o,i,n,r){switch(t){case"top":return e[o][i].top=s,void(0!==i&&(e[o][i-1].bottom=s));case"bottom":return e[o][i].bottom=s,void(i!==r-1&&(e[o][i+1].top=s));case"left":return e[o][i].left=s,void(0!==o&&(e[o-1][i].right=s));case"right":return e[o][i].right=s,void(o!==n-1&&(e[o+1][i].left=s))}}function OA(e,t,s,o){const i=ko(s,o,()=>({}));for(const n of EA){const r=t[n],a=FA(n);if(!r&&!a)continue;const l=PA(n,e,s,o);for(const e of l)for(let t=e.left;t<=e.right;t++)for(let s=e.top;s<=e.bottom;s++)i[t][s]||(i[t][s]={}),i[t][s]={...i[t][s],...r?.style},a&&(i[t][s].bold=!0)}return i}function FA(e){return"firstColumn"===e||"lastColumn"===e||"headerRow"===e||"totalRow"===e}function PA(e,t,s,o){const i=[],n=Math.min(t.numberOfHeaders,o),r=t.totalRow?1:0,a=s-1,l=o-1;switch(e){case"wholeTable":i.push({top:0,left:0,bottom:l,right:a});break;case"firstColumn":if(!t.firstColumn)break;i.push({top:0,left:0,bottom:l,right:0});break;case"lastColumn":if(!t.lastColumn)break;i.push({top:0,left:a,bottom:l,right:a});break;case"headerRow":if(!t.numberOfHeaders)break;i.push({top:0,left:0,bottom:n-1,right:a});break;case"totalRow":if(!t.totalRow)break;i.push({top:l,left:0,bottom:l,right:a});break;case"firstRowStripe":if(!t.bandedRows)break;for(let e=n;e<o-r;e+=2)i.push({top:e,left:0,bottom:e,right:a});break;case"secondRowStripe":if(!t.bandedRows)break;for(let e=n+1;e<o-r;e+=2)i.push({top:e,left:0,bottom:e,right:a});break;case"firstColumnStripe":if(!t.bandedColumns)break;for(let e=0;e<s;e+=2)i.push({top:n,left:e,bottom:l-r,right:e});break;case"secondColumnStripe":if(!t.bandedColumns)break;for(let e=1;e<s;e+=2)i.push({top:n,left:e,bottom:l-r,right:e})}return i}class MA extends yr{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}}const NA=uf.mapping;function LA(e,t,s){return new kA(e,t,s).getParameters()}class kA{getters;computeCell;evalContext;rangeCache={};constructor(e,t,s){this.getters=t,this.computeCell=s,this.evalContext=Object.assign(Object.create(NA),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){const s=this.getRangeError(e);if(s)return s;const o={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};if(t){this.computeCell(o);return{value:sr(this.getters.getSheetName(e.sheetId),Tt(e.zone))}}return this.computeCell(o)}range(e,t){const s=this.getRangeError(e);if(s)return[[s]];const o=e.sheetId,i=e.zone,n=Pt(i,this.getters.getSheetZone(o));if(!n)return[[]];const{top:r,left:a,bottom:l,right:c}=i,h=`${o}-${r}-${a}-${l}-${c}-${t}`;if(h in this.rangeCache)return this.rangeCache[h];const d=n.bottom-n.top+1,u=n.right-n.left+1,g=new Array(u),p=this.getters.getSheetName(e.sheetId);for(let e=n.left;e<=n.right;e++){const s=e-n.left;g[s]=new Array(d);for(let i=n.top;i<=n.bottom;i++){const r=i-n.top,a=this.computeCell({sheetId:o,col:e,row:i});g[s][r]=t?{value:sr(p,mt(e,i))}:a}}return this.rangeCache[h]=g,g}getRangeError(e){return Rt(e.zone)?e.invalidSheetName?new ws(fs("Invalid sheet name: %s",e.invalidSheetName)):void 0:new ws}}function VA(e,t,s,o,i){UA(e,t,s||0,o||e.length-1,i||zA)}function UA(e,t,s,o,i){for(;o>s;){if(o-s>600){var n=o-s+1,r=t-s+1,a=Math.log(n),l=.5*Math.exp(2*a/3),c=.5*Math.sqrt(a*l*(n-l)/n)*(r-n/2<0?-1:1);UA(e,t,Math.max(s,Math.floor(t-r*l/n+c)),Math.min(o,Math.floor(t+(n-r)*l/n+c)),i)}var h=e[t],d=s,u=o;for(HA(e,s,t),i(e[o],h)>0&&HA(e,s,o);d<u;){for(HA(e,d,u),d++,u--;i(e[d],h)<0;)d++;for(;i(e[u],h)>0;)u--}0===i(e[s],h)?HA(e,s,u):HA(e,++u,o),u<=t&&(s=u+1),t<=u&&(o=u-1)}}function HA(e,t,s){var o=e[t];e[t]=e[s],e[s]=o}function zA(e,t){return e<t?-1:e>t?1:0}class BA{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data;const s=[];if(!eD(e,t))return s;const o=this.toBBox,i=[];for(;t;){for(let n=0;n<t.children.length;n++){const r=t.children[n],a=t.leaf?o(r):r;eD(e,a)&&(t.leaf?s.push(r):QA(e,a)?this._all(r,s):i.push(r))}t=i.pop()}return s}collides(e){let t=this.data;if(!eD(e,t))return!1;const s=[];for(;t;){for(let o=0;o<t.children.length;o++){const i=t.children[o],n=t.leaf?this.toBBox(i):i;if(eD(e,n)){if(t.leaf||QA(e,n))return!0;s.push(i)}}t=s.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let t=0;t<e.length;t++)this.insert(e[t]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){const e=this.data;this.data=t,t=e}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=tD([]),this}remove(e,t){if(!e)return this;let s=this.data;const o=this.toBBox(e),i=[],n=[];let r,a,l;for(;s||i.length;){if(s||(s=i.pop(),a=i[i.length-1],r=n.pop(),l=!0),s.leaf){const o=GA(e,s.children,t);if(-1!==o)return s.children.splice(o,1),i.push(s),this._condense(i),this}l||s.leaf||!QA(s,o)?a?(r++,s=a.children[r],l=!1):s=null:(i.push(s),n.push(r),r=0,a=s,s=s.children[0])}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){const s=[];for(;e;)e.leaf?t.push(...e.children):s.push(...e.children),e=s.pop();return t}_build(e,t,s,o){const i=s-t+1;let n,r=this._maxEntries;if(i<=r)return n=tD(e.slice(t,s+1)),WA(n,this.toBBox),n;o||(o=Math.ceil(Math.log(i)/Math.log(r)),r=Math.ceil(i/Math.pow(r,o-1))),n=tD([]),n.leaf=!1,n.height=o;const a=Math.ceil(i/r),l=a*Math.ceil(Math.sqrt(r));sD(e,t,s,l,this.compareMinX);for(let i=t;i<=s;i+=l){const t=Math.min(i+l-1,s);sD(e,i,t,a,this.compareMinY);for(let s=i;s<=t;s+=a){const i=Math.min(s+a-1,t);n.children.push(this._build(e,s,i,o-1))}}return WA(n,this.toBBox),n}_chooseSubtree(e,t,s,o){for(;o.push(t),!t.leaf&&o.length-1!==s;){let s,o=1/0,i=1/0;for(let n=0;n<t.children.length;n++){const r=t.children[n],a=YA(r),l=KA(e,r)-a;l<i?(i=l,o=a<o?a:o,s=r):l===i&&a<o&&(o=a,s=r)}t=s||t.children[0]}return t}_insert(e,t,s){const o=s?e:this.toBBox(e),i=[],n=this._chooseSubtree(o,this.data,t,i);for(n.children.push(e),qA(n,o);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(o,i,t)}_split(e,t){const s=e[t],o=s.children.length,i=this._minEntries;this._chooseSplitAxis(s,i,o);const n=this._chooseSplitIndex(s,i,o),r=tD(s.children.splice(n,s.children.length-n));r.height=s.height,r.leaf=s.leaf,WA(s,this.toBBox),WA(r,this.toBBox),t?e[t-1].children.push(r):this._splitRoot(s,r)}_splitRoot(e,t){this.data=tD([e,t]),this.data.height=e.height+1,this.data.leaf=!1,WA(this.data,this.toBBox)}_chooseSplitIndex(e,t,s){let o,i=1/0,n=1/0;for(let r=t;r<=s-t;r++){const t=$A(e,0,r,this.toBBox),a=$A(e,r,s,this.toBBox),l=JA(t,a),c=YA(t)+YA(a);l<i?(i=l,o=r,n=c<n?c:n):l===i&&c<n&&(n=c,o=r)}return o||s-t}_chooseSplitAxis(e,t,s){const o=e.leaf?this.compareMinX:ZA,i=e.leaf?this.compareMinY:jA;this._allDistMargin(e,t,s,o)<this._allDistMargin(e,t,s,i)&&e.children.sort(o)}_allDistMargin(e,t,s,o){e.children.sort(o);const i=this.toBBox,n=$A(e,0,t,i),r=$A(e,s-t,s,i);let a=XA(n)+XA(r);for(let o=t;o<s-t;o++){const t=e.children[o];qA(n,e.leaf?i(t):t),a+=XA(n)}for(let o=s-t-1;o>=t;o--){const t=e.children[o];qA(r,e.leaf?i(t):t),a+=XA(r)}return a}_adjustParentBBoxes(e,t,s){for(let o=s;o>=0;o--)qA(t[o],e)}_condense(e){for(let t,s=e.length-1;s>=0;s--)0===e[s].children.length?s>0?(t=e[s-1].children,t.splice(t.indexOf(e[s]),1)):this.clear():WA(e[s],this.toBBox)}}function GA(e,t,s){if(!s)return t.indexOf(e);for(let o=0;o<t.length;o++)if(s(e,t[o]))return o;return-1}function WA(e,t){$A(e,0,e.children.length,t,e)}function $A(e,t,s,o,i){i||(i=tD(null)),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(let n=t;n<s;n++){const t=e.children[n];qA(i,e.leaf?o(t):t)}return i}function qA(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 ZA(e,t){return e.minX-t.minX}function jA(e,t){return e.minY-t.minY}function YA(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function XA(e){return e.maxX-e.minX+(e.maxY-e.minY)}function KA(e,t){return(Math.max(t.maxX,e.maxX)-Math.min(t.minX,e.minX))*(Math.max(t.maxY,e.maxY)-Math.min(t.minY,e.minY))}function JA(e,t){const s=Math.max(e.minX,t.minX),o=Math.max(e.minY,t.minY),i=Math.min(e.maxX,t.maxX),n=Math.min(e.maxY,t.maxY);return Math.max(0,i-s)*Math.max(0,n-o)}function QA(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function eD(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function tD(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function sD(e,t,s,o,i){const n=[t,s];for(;n.length;){if((s=n.pop())-(t=n.pop())<=o)continue;const r=t+Math.ceil((s-t)/o/2)*o;VA(e,r,t,s,i),n.push(t,r,r,s)}}class oD{rTrees={};constructor(e=[]){const t={};for(const s of e){const e=s.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(s)}for(const e in t)this.rTrees[e]=new iD,this.rTrees[e].load(t[e])}insert(e){const t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new iD),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){const 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&&Me(e.data,t.data)}}class iD extends BA{toBBox({boundingBox:e}){const 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}}class nD{createEmptyPositionSet;dependencies=new YT;rTree;constructor(e,t=[]){this.createEmptyPositionSet=e,this.rTree=new oD(t)}removeAllDependencies(e){const t=this.dependencies.get(e);if(t){for(const e of t)this.rTree.remove(e);this.dependencies.delete(e)}}addDependencies(e,t){const s=t.map(({sheetId:t,zone:s})=>({data:e,boundingBox:{zone:s,sheetId:t}}));for(const e of s)this.rTree.insert(e);const o=this.dependencies.get(e);o?o.push(...s):this.dependencies.set(e,s)}getCellsDependingOn(e,t){const s=this.createEmptyPositionSet(),o=Array.from(e).reverse();for(;o.length>0;){const e=o.pop(),i=e.zone,n=e.sheetId;for(let e=i.left;e<=i.right;e++)for(let t=i.top;t<=i.bottom;t++)s.add({sheetId:n,col:e,row:t});const r=this.rTree.search(e).map(e=>e.data),a={};for(const e of r)s.has(e)||t.has(e)||(a[e.sheetId]||(a[e.sheetId]=[]),a[e.sheetId].push(Zt(e)));for(const e in a){const t=ft(a[e],[]);o.push(...t.map(t=>({sheetId:e,zone:t})))}}for(const t of e){const e=t.zone,o=t.sheetId;for(let t=e.left;t<=e.right;t++)for(let i=e.top;i<=e.bottom;i++)s.delete({sheetId:o,col:t,row:i})}return s}}class rD extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){const s=function(e){if(0===e)return-1/0;if(e<0)return NaN;return 32-Math.clz32(--e)}(t),o=new this((e<<s>>5)+1);return o.columnOffset=s,o.cols=t,o.rows=e,o}getValue(e){const[t,s]=this.getCoordinates(e);return this[t]>>s&1}setValue(e,t){const[s,o]=this.getCoordinates(e),i=0===(this[s]>>o&1)&&1===t;return this[s]=this[s]&~(1<<o)|t<<o,i}isEmpty(){return!this.some(e=>0!==e)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){const{row:t,col:s}=e,o=(t<<this.columnOffset)+s,i=o>>5;return[i,o-(i<<5)]}}class aD{sheets={};insertions=[];maxSize=0;constructor(e){for(const t in e){const s=e[t].cols,o=e[t].rows;this.maxSize+=s*o,this.sheets[t]=rD.create(o,s)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(const t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(const t of e)this.delete(t)}has(e){return 1===this.sheets[e.sheetId].getValue(e)}clear(){const e=[...this];this.insertions=[];for(const e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(0===this.insertions.length)return!0;for(const e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=new Array(this.maxSize);let e=0;for(const t in this.sheets){const s=this.sheets[t];s.fillAllPositions();for(let o=0;o<s.rows;o++)for(let i=0;i<s.cols;i++)this.insertions[e++]={sheetId:t,row:o,col:i}}}*[Symbol.iterator](){for(const e of this.insertions)1===this.sheets[e.sheetId].getValue(e)&&(yield e)}}class lD{resultsToArrayFormulas=new oD;arrayFormulasToResults=new YT;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||cD}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:Zt(e)},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)}}const cD=[],hD=new Og;hD.add("pivots",e=>{for(const t of e.getPivotIds()){const s=e.getPivot(t);s.markAsDirtyForEvaluation?.()}});const dD=Object.freeze(Kv({...new Is,origin:void 0})),uD=Object.freeze(Kv({value:null}));class gD{context;getters;compilationParams;evaluatedCells=new YT;formulaDependencies=Oe(new nD(this.createEmptyPositionSet.bind(this)));blockedArrayFormulas=new aD({});spreadingRelations=new lD;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=LA(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||uD}getSpreadZone(e,t={ignoreSpillError:!1}){const s=this.spreadingRelations.getArrayResultZone(e);if(!s)return;const o=this.evaluatedCells.get(e);return o?.type!==_d.error||t.ignoreSpillError&&o?.value===bs.SpilledBlocked?Ft(Zt(e),s):Zt(e)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type===_d.empty)return;const t=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,Zt(e));return Array.from(t).find(e=>!this.blockedArrayFormulas.has(e))}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);const t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t);for(const e of t){const t=e.sheetId,{left:s,bottom:o,right:i,top:n}=e.zone;for(let e=s;e<=i;e++)for(let s=n;s<=o;s++)this.computeAndSave({sheetId:t,col:e,row:s})}}updateCompilationParameters(){this.compilationParams=LA(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(){const e={};for(const t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new aD(e)}evaluateCells(e){const t=performance.now(),s=this.createEmptyPositionSet();s.addMany(e);const o=this.getArrayFormulasImpactedByChangesOf(e);s.addMany(this.getCellsDependingOn(e)),s.addMany(o),s.addMany(this.getCellsDependingOn(o)),this.evaluate(s),console.debug("evaluate Cells",performance.now()-t,"ms")}getArrayFormulasImpactedByChangesOf(e){const t=this.createEmptyPositionSet();for(const s of e){const e=this.getters.getCell(s)?.content,o=this.getArrayFormulaSpreadingOn(s);void 0!==o&&t.add(o),e||t.add(s)}const s=zt(t);for(const e in s)for(const o of s[e])t.addMany(this.getArrayFormulasBlockedBy(e,o));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new lD,this.formulaDependencies=Oe(()=>{const 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 nD(this.createEmptyPositionSet.bind(this),e)})}evaluateAllCells(){const e=performance.now();this.evaluatedCells=new YT,this.evaluate(this.getAllCells()),console.debug("evaluate all cells",performance.now()-e,"ms")}evaluateFormulaResult(e,t){const s=sE(t),o=s.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return this.updateCompilationParameters(),this.evaluateCompiledFormula(e,{...s,dependencies:o})}evaluateCompiledFormula(e,t,s){try{const o=fD(t,this.compilationParams,e,this.buildSafeGetSymbolValue(s),this.compilationParams.evalContext.__originCellPosition);return Ds(o)?Vo(o,mD):mD(o)}catch(e){return si(e,"")}}getAllCells(){const e=this.createEmptyPositionSet();return e.fillAllPositions(),e}getArrayFormulasBlockedBy(e,t){const s=this.createEmptyPositionSet(),o=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);s.addMany(o);const i=[...o].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&s.deleteMany(i),s.addMany(this.getCellsDependingOn(s)),s}nextPositionsToUpdate=new aD({});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();const 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){const s=e[t];if(this.nextPositionsToUpdate.has(s))continue;const o=this.computeCell(s);o!==uD&&this.evaluatedCells.set(s,o)}hD.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn("Maximum iteration reached while evaluating cells")}computeCell(e){const t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);const s=this.getters.getCell(e);if(void 0===s)return uD;const o=s.id,i={format:s.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(o)?dD:(this.cellsBeingComputed.add(o),s.isFormula?this.computeFormulaCell(e,s):Yv(s,i,e))}catch(t){return t.value=t?.value||bs.GenericError,t.message=t?.message||ii,t.origin=e,Kv(t)}finally{this.cellsBeingComputed.delete(o)}}computeAndSave(e){const t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){const s=fD(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!Ds(s)){const o=Kv(mD(s),this.getters.getLocale(),t,e);return o.type===_d.error&&(o.errorOriginPosition=s.errorOriginPosition??e),o}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,s);const o=s.length,i=s[0].length,n={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+o-1};return this.spreadingRelations.addRelation({resultZone:n,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,s),pD(o,i,this.checkCollision(e)),pD(o,i,this.spreadValues(e,s)),this.invalidatePositionsDependingOnSpread(e.sheetId,n),Kv(mD(s[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){const s=this.formulaDependencies().getCellsDependingOn(function(e){const{top:t,left:s,bottom:o,right:i}=e;if(1===Kt(e))return[];const n={top:t+1,bottom:o,left:s,right:s};if(i===s)return[n];const r={top:t,bottom:o,left:s+1,right:i};return t===o?[r]:[n,r]}(t).map(t=>({sheetId:e,zone:t})),this.nextPositionsToUpdate);s.delete({sheetId:e,col:t.left,row:t.top}),this.nextPositionsToUpdate.addMany(s)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:s},o){const i=this.getters.getNumberCols(e),n=this.getters.getNumberRows(e),r=t+o.length<=i,a=s+o[0].length<=n;if(!r||!a){if(r)throw new xs(fs("Result couldn't be automatically expanded. Please insert more rows."));if(a)throw new xs(fs("Result couldn't be automatically expanded. Please insert more columns."));throw new xs(fs("Result couldn't be automatically expanded. Please insert more columns and rows."))}}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:s},o){if(0!==this.getters.getMergesInZone(e,{top:s,bottom:s+o[0].length-1,left:t,right:t+o.length-1}).length)throw new xs(fs("Merged cells found in the spill zone. Please unmerge cells before using array formulas."))}checkCollision(e){const{sheetId:t,col:s,row:o}=e;return(i,n)=>{const r={sheetId:t,col:i+s,row:n+o},a=this.getters.getCell(r);if(a?.content||this.getters.getEvaluatedCell(r).type!==_d.empty)throw this.blockedArrayFormulas.add(e),new xs(fs("Array result was not expanded because it would overwrite data in %s.",mt(r.col,r.row)));this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:s},o){return(i,n)=>{const r={sheetId:e,col:i+t,row:n+s},a=this.getters.getCell(r),l=Kv(mD(o[i][n]),this.getters.getLocale(),a,r);l.type===_d.error&&(l.errorOriginPosition=o[i][n].errorOriginPosition??r),this.evaluatedCells.set(r,l)}}invalidateSpreading(e){const t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let s=t.left;s<=t.right;s++)for(let o=t.top;o<=t.bottom;o++){const t={sheetId:e.sheetId,col:s,row:o},i=this.getters.getCell(t)?.content;i||this.evaluatedCells.delete(t)}const s=e.sheetId;this.invalidatePositionsDependingOnSpread(s,t),this.nextPositionsToUpdate.addMany(this.getArrayFormulasBlockedBy(s,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return dD;this.symbolsBeingComputed.add(t);try{const s=e?.(t);return s||new ys(fs("Invalid formula"))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){const t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.dependencies:[]}getCellsDependingOn(e){const t=[],s=zt(e);for(const e in s)t.push(...s[e].map(t=>({sheetId:e,zone:t})));return this.formulaDependencies().getCellsDependingOn(t,this.nextPositionsToUpdate)}}function pD(e,t,s){for(let o=0;o<e;++o)for(let e=0;e<t;++e)0===o&&0===e||s(o,e)}function mD(e){return null===e.value||void 0===e.value?{...e,value:0}:e}function fD(e,t,s,o,i){return t.evalContext.__originCellPosition=i,t.evalContext.__originSheetId=s,e.execute(e.dependencies,t.referenceDenormalizer,t.ensureRange,o,t.evalContext)}const vD=new Og;vD.add("data_validation_checkbox",(e,t)=>{if(e.isCellValidCheckbox(t)){const s=!!e.getEvaluatedCell(t).value;return{svg:s?hR:lR,hoverSvg:s?hR:cR,priority:2,horizontalAlign:"center",size:17,margin:2,position:t,type:"data_validation_checkbox",onClick:(e,t)=>{const o=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||!!o?.isFormula)return;const i=s?"FALSE":"TRUE";t.model.dispatch("UPDATE_CELL",{...e,content:i})}}}}),vD.add("data_validation_chip_icon",(e,t)=>{const s=e.getDataValidationChipStyle(t);if(s){const o=e.getCellComputedStyle(t);return{svg:rR(s),hoverSvg:aR(s),priority:10,horizontalAlign:"right",size:Zb(o),margin:4,position:t,onClick:(e,t)=>{const{col:s,row:o}=e;t.model.selection.selectCell(s,o),t.startCellEdition()},type:"data_validation_chip_icon"}}}),vD.add("data_validation_list_icon",(e,t)=>{if(!e.isReadonly()&&e.cellHasListDataValidationIcon(t)){const o=e.getCellComputedStyle(t);return{svg:oR(o),hoverSvg:(s=o,{name:"CARET_DOWN",width:512,height:512,paths:[{fillColor:s.textColor||I,path:"M15 15 h482 v482 h-482"},{fillColor:s.fillColor||"#fff",path:"M120 195 h270 l-135 130"}]}),priority:2,horizontalAlign:"right",size:17,margin:2,position:t,onClick:(e,t)=>{const{col:s,row:o}=e;t.model.selection.selectCell(s,o),t.startCellEdition()},type:"data_validation_list_icon"}}var s}),vD.add("conditional_formatting",(e,t)=>{const s=e.getConditionalIcon(t);if(s){const o=e.getCellStyle(t);return{type:"conditional_formatting",svg:gR[s].svg,priority:1,horizontalAlign:"left",size:Zb(o),margin:4,position:t}}}),vD.add("pivot_collapse",(e,t)=>{if(!e.isSpillPivotFormula(t))return;const s=e.getPivotCellFromPosition(t),o=e.getPivotIdFromPosition(t);if("HEADER"===s.type&&o&&s.domain.length){const i=e.getPivotCoreDefinition(o),n=e.isDashboard(),r="COL"===s.dimension?i.columns:i.rows,a=!n&&s.domain.length!==r.length,l=(i.collapsedDomains?.[s.dimension]??[]).some(e=>Me(e,s.domain)),c="ROW"===s.dimension?15*(s.domain.length-1):0;return{type:"pivot_collapse",priority:4,horizontalAlign:"left",size:a||!n&&"ROW"===s.dimension&&i.rows.length>1?12:0,margin:a?4+c:c,svg:a?dR(l,!1):void 0,hoverSvg:a?dR(l,!0):void 0,position:t,onClick:Cp}}}),vD.add("pivot_dashboard_sorting",(e,t)=>{if(!e.isDashboard())return;if("MEASURE_HEADER"!==e.getPivotCellFromPosition(t).type)return;const s=e.getPivotCellSortDirection(t);if("asc"!==s&&"desc"!==s)return;const o=e.getCellComputedStyle(t);return{type:`pivot_dashboard_sorting_${s}`,priority:5,horizontalAlign:"right",size:17,margin:2,svg:"asc"===s?iR(o):oR(o),position:t,onClick:void 0}});const bD=/"(#[0-9a-fA-F]{6})"/g;const SD={isValid:!0};const CD=["*","+","&"];function yD(e,t=60){return"="+function(e,t){return function(e){let t="";for(;e;)t+=e.subString,e=e.next;return t}(function(e,t){const s={indentLevel:0,doc:t,next:null};return TD(e,0,s)}(t,e))}(AD(e),t-1)}function ID(e,t){return{type:"nest",indentLevel:e,doc:t}}function wD(e){return{type:"concat",docs:e}}function ED(e){return{type:"chooseBetween",doc1:RD(e),doc2:e}}function RD(e){return"string"==typeof e?e:"chooseBetween"===e.type?RD(e.doc1):"concat"===e.type?wD(e.docs.map(RD)):"nest"===e.type?{type:"nest",indentLevel:e.indentLevel,doc:RD(e.doc)}:"insertLine"===e.type?"":e}const xD=$e(function(e){return"\n"+"\t".repeat(e)});function TD(e,t,s){if(null===s)return null;const{indentLevel:o,doc:i,next:n}=s;if("string"==typeof i)return{subString:i,next:TD(e,t+i.length,n)};if("concat"===i.type){let s=n;for(let e=i.docs.length-1;e>=0;e--)s={indentLevel:o,doc:i.docs[e],next:s};return TD(e,t,s)}if("nest"===i.type)return TD(e,t,{indentLevel:o+i.indentLevel,doc:i.doc,next:n});if("insertLine"===i.type)return{subString:xD(o),next:TD(e,o,n)};if("chooseBetween"===i.type){const s=TD(e,t,{indentLevel:o,doc:i.doc1,next:n});if(function(e,t){for(;t;){if("\n"===t.subString[0])return!0;if((e-=t.subString.length)<0)return!1;t=t.next}return!0}(e-t,s))return s;return TD(e,t,{indentLevel:o,doc:i.doc2,next:n})}return null}function AD(e){switch(e.type){case"NUMBER":return String(e.value);case"STRING":return`"${e.value}"`;case"BOOLEAN":return e.value?"TRUE":"FALSE";case"REFERENCE":case"SYMBOL":return e.value;case"FUNCALL":return DD(wD(e.args.map(AD).map((e,t)=>t<1?e:wD([", ",{type:"insertLine"},e]))),e.value);case"UNARY_OPERATION":const t=AD(e.operand),s=(e.postfix?OD(e):FD(e))?DD(t):t;return e.postfix?wD([s,e.value]):wD([e.value,s]);case"BIN_OPERATION":{const t=AD(e.left),s=OD(e)?DD(t):t,o=AD(e.right),i=FD(e)?DD(o):o;return ED(wD([s,`${e.value}`,ID(1,wD([{type:"insertLine"},i]))]))}case"EMPTY":return""}}function DD(e,t=void 0){const s=["(",ID(1,wD([{type:"insertLine"},e])),{type:"insertLine"},")"];return t&&s.unshift(t),ED(wD(s))}function _D(e){switch(e.type){case"FUNCALL":const t=e.args.map(e=>_D(e));return`${e.value}(${t.join(",")})`;case"NUMBER":return e.value.toString();case"REFERENCE":default:return e.value;case"STRING":return`"${e.value}"`;case"BOOLEAN":return e.value?"TRUE":"FALSE";case"UNARY_OPERATION":if(e.postfix){return(OD(e)?`(${_D(e.operand)})`:_D(e.operand))+e.value}const s=FD(e)?`(${_D(e.operand)})`:_D(e.operand);return e.value+s;case"BIN_OPERATION":const o=OD(e)?`(${_D(e.left)})`:_D(e.left),i=FD(e)?`(${_D(e.right)})`:_D(e.right);return o+e.value+i}}function OD(e){const t=e.value,s="left"in e?e.left:e.operand,o=s.value;return"BIN_OPERATION"===s.type&&Ef[o]<Ef[t]}function FD(e){const t=e.value,s="right"in e?e.right:e.operand,o=Ef[s.value],i=Ef[t];return"BIN_OPERATION"===s.type&&(o<i||o===i&&!CD.includes(t))}const PD=["PIVOT.VALUE","PIVOT.HEADER","PIVOT"];function MD(e){return kf(e,PD)[0]}function ND(e){return kf(e,PD).length}const LD="0.00%";function kD(e){return class extends e{getters;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t){super(e,t),this.getters=t.getters}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){const s=`${e}-${t.map(e=>e.field+"="+e.value).join(",")}`;if(this.cache[s])return this.cache[s];const o=this.getMeasure(e),i=o.computedBy?this.computeMeasure(o,t):super.getPivotCellValueAndFormat(e,t);return o.format?this.cache[s]={...i,format:o.format}:this.cache[s]=i,this.cache[s]}computeMeasure(e,t){if(!e.computedBy)return{value:0};const{columns:s,rows:o}=super.definition;if(e.aggregator&&s.length+o.length!==t.length){const s=this.getValuesToAggregate(e,t),o=Xg[e.aggregator];if(!o)return{value:0};try{return o([s],this.getters.getLocale())}catch(t){return si(t,e.aggregator.toUpperCase())}}const i=this.getters.getMeasureCompiledFormula(e),n=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,e=>{const{columns:s,rows:o}=this.definition;if(s.find(t=>t.nameWithGranularity===e)){const{colDomain:s}=lA(this,t),o=s.findIndex(t=>t.field===e);return-1===o?new Es:this.getPivotHeaderValueAndFormat(s.slice(0,o+1))}if(o.find(t=>t.nameWithGranularity===e)){const{rowDomain:s}=lA(this,t),o=s.findIndex(t=>t.field===e);return-1===o?new Es:this.getPivotHeaderValueAndFormat(s.slice(0,o+1))}return this.getPivotCellValueAndFormat(e,t)});return Ds(n)?n[0][0]:n}getValuesToAggregate(e,t){const{rowDomain:s,colDomain:o}=lA(this,t),i=super.getExpandedTableStructure(),n=[];if(0===o.length&&s.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){const t=this.treeToLeafDomains(i.getColTree()),o=this.getSubTreeMatchingDomain(i.getRowTree(),s),r=this.treeToLeafDomains(o);for(const o of t)for(const t of r)n.push(this._getPivotCellValueAndFormat(e.id,s.concat(t).concat(o)));return n}if(s.length===this.definition.rows.length&&0===o.length){const t=i.getColTree(),r=this.getSubTreeMatchingDomain(t,o),a=this.treeToLeafDomains(r,o);for(const t of a)n.push(this._getPivotCellValueAndFormat(e.id,s.concat(t)));return n}if(s.length===this.definition.rows.length&&o.length&&o.length<this.definition.columns.length){const t=this.getSubTreeMatchingDomain(i.getColTree(),o),r=this.treeToLeafDomains(t,o);for(const t of r)n.push(this._getPivotCellValueAndFormat(e.id,s.concat(t)));return n}{const t=i.getRowTree(),r=this.getSubTreeMatchingDomain(t,s),a=this.treeToLeafDomains(r,s);for(const t of a)n.push(this._getPivotCellValueAndFormat(e.id,t.concat(o)));return n}}getSubTreeMatchingDomain(e,t,s=0){if(s>t.length)return[];if(t.length===s)return e;for(const o of e){const e=np(this.definition.getDimension(o.field),t[s]?.value);if(o.field===t[s]?.field&&o.value===e)return this.getSubTreeMatchingDomain(o.children,t,s+1)}return[]}treeToLeafDomains(e,t=[]){const s=[];for(const o of e){const e=this.definition.getDimension(o.field),i=[...t,{field:o.field,value:o.value,type:e.type}];0===o.children.length?s.push(i):s.push(...this.treeToLeafDomains(o.children,i))}return s}getMeasureDisplayValue(e,t){const s=this.getMeasure(e),o=this._getPivotCellValueAndFormat(e,t);if(!s.display||"no_calculations"===s.display.type||o.message)return o;const i=s.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:bs.NotAvailable,message:fs('Field "%s" not found in pivot for measure display calculation',i)};try{const e=s.display;switch(e.type){case"%_of_grand_total":return this.asPercentOfGrandTotal(o,s);case"%_of_col_total":return this.asPercentOfColumnTotal(o,s,t);case"%_of_row_total":return this.asPercentOfRowTotal(o,s,t);case"%_of_parent_row_total":return this.asPercentOfParentRowTotal(o,s,t);case"%_of_parent_col_total":return this.asPercentOfParentColumnTotal(o,s,t);case"index":return this.asIndex(o,s,t);case"%_of_parent_total":return this.asPercentOfParentTotal(o,s,t,e);case"running_total":return this.asRunningTotal(o,s,t,e,"running_total");case"%_running_total":return this.asRunningTotal(o,s,t,e,"%_running_total");case"rank_asc":return this.asRank(o,s,t,e,"asc");case"rank_desc":return this.asRank(o,s,t,e,"desc");case"%_of":return this.asPercentOf(o,s,t,e);case"difference_from":return this.asDifferenceFrom(o,s,t,e);case"%_difference_from":return this.asDifferenceFromInPercent(o,s,t,e)}return o}catch(e){return si(e,"COMPUTE_MEASURE_DISPLAY_VALUE")}}asPercentOfGrandTotal(e,t){const s=this.getGrandTotal(t.id);return 0===s?{value:bs.DivisionByZero}:{value:this.measureValueToNumber(e)/s,format:LD}}asPercentOfRowTotal(e,t,s){const o=this.getRowTotal(t.id,s);return 0===o?{value:bs.DivisionByZero}:{value:this.measureValueToNumber(e)/o,format:LD}}asPercentOfColumnTotal(e,t,s){const o=this.getColumnTotal(t.id,s);return 0===o?{value:bs.DivisionByZero}:{value:this.measureValueToNumber(e)/o,format:LD}}asPercentOfParentRowTotal(e,t,s){const o=function(e,t){const{colDomain:s,rowDomain:o}=lA(e,t);return[...s,...o.slice(0,o.length-1)]}(this,s),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,o));return 0===i?{value:""}:{value:this.measureValueToNumber(e)/i,format:LD}}asPercentOfParentColumnTotal(e,t,s){const o=function(e,t){const{colDomain:s,rowDomain:o}=lA(e,t);return[...s.slice(0,s.length-1),...o]}(this,s),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,o));return 0===i?{value:""}:{value:this.measureValueToNumber(e)/i,format:LD}}asPercentOfParentTotal(e,t,s,o){const{fieldNameWithGranularity:i}=o;if(!i)return e;if(!gA(i,s))return{value:""};const n=function(e,t,s){let{rowDomain:o,colDomain:i}=lA(e,s);if("row"===pA(e,t)){const e=o.findIndex(e=>e.field===t);if(-1===e)return s;o=o.slice(0,e+1)}else{const e=i.findIndex(e=>e.field===t);if(-1===e)return s;i=i.slice(0,e+1)}return[...o,...i]}(this,i,s),r=this._getPivotCellValueAndFormat(t.id,n),a=this.measureValueToNumber(r);return 0===a?{value:""}:{value:this.measureValueToNumber(e)/a,format:LD}}asIndex(e,t,s){const o=this.measureValueToNumber(e),i=this.getRowTotal(t.id,s),n=this.getColumnTotal(t.id,s),r=this.getGrandTotal(t.id);return 0===i||0===n?{value:bs.DivisionByZero}:{value:o*r/(n*i),format:void 0}}asRunningTotal(e,t,s,o,i){const{fieldNameWithGranularity:n}=o;if(!n)return e;const r="running_total"===i?this.runningTotal:this.runningTotalInPercent;let a=r[t.id]?.[n];a||(a=this.computeRunningTotal(t,n,i),r[t.id]||(r[t.id]={}),r[t.id][n]=a);const{rowDomain:l,colDomain:c}=lA(this,s),h=mA(c),d=mA(l),u=a[h]?.[d];return{value:u??"",format:"running_total"===i?e.format:LD}}asPercentOf(e,t,s,o){const{fieldNameWithGranularity:i,value:n}=o;if(void 0===n||!i)return e;if(!gA(i,s))return{value:""};const r=this.getComparisonValue(t,s,i,n),a=this.strictMeasureValueToNumber(e);return 0===r||"sameValue"===r&&0===a?{value:bs.DivisionByZero}:!r||"sameValue"===r&&!a?{value:""}:"sameValue"===r?{value:1,format:LD}:void 0===a?{value:bs.NullError}:{value:a/r,format:LD}}asDifferenceFrom(e,t,s,o){const{fieldNameWithGranularity:i,value:n}=o;if(void 0===n||!i)return e;if(!gA(i,s))return{value:""};const r=this.getComparisonValue(t,s,i,n)||0;return"sameValue"===r?{value:""}:{value:this.measureValueToNumber(e)-r,format:e.format}}asDifferenceFromInPercent(e,t,s,o){const{fieldNameWithGranularity:i,value:n}=o;if(void 0===n||!i)return e;if(!gA(i,s))return{value:""};const r=this.getComparisonValue(t,s,i,n),a=this.strictMeasureValueToNumber(e);return 0===r?{value:bs.DivisionByZero}:r&&"sameValue"!==r?void 0===a?{value:bs.NullError}:{value:(a-r)/r,format:LD}:{value:""}}asRank(e,t,s,o,i){const{fieldNameWithGranularity:n}=o;if(!n)return e;if(!gA(n,s))return{value:""};const r="asc"===i?this.rankAsc:this.rankDesc;let a=r[t.id]?.[n];a||(a=this.computeRank(t,n,i),r[t.id]||(r[t.id]={}),r[t.id][n]=a);const{rowDomain:l,colDomain:c}=lA(this,s),h=mA(c),d=mA(l),u=a[h]?.[d];return{value:u??""}}computeRank(e,t,s){const o={},i=pA(this,t),n="row"===i?"column":"row";let r=this.getPivotValueCells(e.id);"column"===i&&(r=Uo(r));for(const a of r){const r=mA(cA(this,n,a[0].domain)),l=a.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:cA(this,i,t.domain)})).filter(e=>gA(t,e.rowDomain)),c=Object.groupBy(l,e=>vA(e.rowDomain,t));for(const e in c)c[e]=et(c[e]||[],e=>e.value).filter(e=>void 0!==e.value).sort((e,t)=>"asc"===s?e.value-t.value:t.value-e.value);o[r]={};for(const e of l){const s=mA(cA(this,i,e.domain)),n=c[vA(e.rowDomain,t)];if(!n)continue;const a=n.findIndex(t=>t.value===e.value);-1!==a&&(o[r][s]=a+1)}}return"row"===i?o:tt(o)}computeRunningTotal(e,t,s){const o={},i=pA(this,t),n="row"===i?"column":"row";let r=this.getPivotValueCells(e.id);"column"===i&&(r=Uo(r));for(const a of r){const r=mA(cA(this,n,a[0].domain));o[r]={};const l={},c=a.map(t=>({...t,rowDomain:cA(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>gA(t,e.rowDomain));for(const e of c){const s=mA(e.rowDomain),i=bA(e.rowDomain,t),n=(l[i]||0)+e.value;l[i]=n,o[r][s]=n}if("%_running_total"===s)for(const e of c){const s=e.rowDomain,i=mA(s),n=bA(s,t),a=o[r][i]||0,c=l[n];o[r][i]=c?a/c:void 0}}return"row"===i?o:tt(o)}getGrandTotal(e){const t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){const s=lA(this,t).rowDomain,o=this._getPivotCellValueAndFormat(e,s);return this.measureValueToNumber(o)}getColumnTotal(e,t){const s=lA(this,t).colDomain,o=this._getPivotCellValueAndFormat(e,s);return this.measureValueToNumber(o)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,s,o){const i=o===fI||o===vI?function(e,t,s,o){const i=pA(e,s),n="row"===i?e.getExpandedTableStructure().getRowTree():e.getExpandedTableStructure().getColTree(),r=dA(cA(e,i,t),n,s),a=r?.map(e=>e.value)??[],l=function(e,t){const s=t.find(t=>t.field===e);return s?.value}(s,t);if(void 0===l)return;const c=a.indexOf(l);if(void 0===l||-1===c)return;return uA(t,s,a[ue(c+(o===fI?-1:1),0,a.length-1)])}(this,t,s,o):uA(t,s,o);if(Me(i,t))return"sameValue";if(!i||!function(e,t){for(const s of t)if(void 0===e.definition.rows.find(e=>e.nameWithGranularity===s.field)&&void 0===e.definition.columns.find(e=>e.nameWithGranularity===s.field))return!1;const{rowDomain:s,colDomain:o}=lA(e,t);return hA(s,e.getExpandedTableStructure().getRowTree())&&hA(o,e.getExpandedTableStructure().getColTree())}(this,i))throw new Es;const n=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(n)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map(t=>t.filter(t=>"VALUE"===t.type&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if("number"==typeof e.value)return e.value;if(!e.value)return 0;throw new Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if("number"==typeof e.value)return e.value;if(e.value)throw new Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){const e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){const e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;const t=this.definition.sortedColumn.measure;gp(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}}class VD{measures;columns;rows;sortedColumn;collapsedDomains;customFields;constructor(e,t){this.columns=e.columns.map(e=>this.createPivotDimension(t,e)),this.rows=e.rows.map(e=>this.createPivotDimension(t,e)),this.measures=e.measures.map(e=>this.createMeasure(t,e)),this.sortedColumn=e.sortedColumn,this.collapsedDomains=e.collapsedDomains,this.customFields=e.customFields}getDimension(e){const t=this.columns.find(t=>t.nameWithGranularity===e)||this.rows.find(t=>t.nameWithGranularity===e);if(!t)throw new Cs(fs("Dimension %s does not exist",e));return t}getMeasure(e){const t=this.measures.find(t=>t.id===e);if(!t)throw new Cs(fs("Field %s is not a measure",e));return t}get invalidAggregatorsForCustomField(){return[]}createMeasure(e,t){const s=t.fieldName,o="__count"===s?{name:"__count",string:fs("Count"),type:"integer",aggregator:"sum"}:e[s],i=t.aggregator;let n=!(!o&&!t.computedBy);for(const t of[...this.rows,...this.columns]){const s=e[t.fieldName];if(s?.isCustomField&&this.invalidAggregatorsForCustomField.includes(i)){n=!1;break}}return{id:t.id,get displayName(){return t.userDefinedName??o?.string??t.fieldName},userDefinedName:t.userDefinedName,fieldName:s,aggregator:i,type:"__count"===s?"integer":o?.type??"integer",isValid:n,isHidden:t.isHidden,format:t.format,computedBy:t.computedBy,display:t.display}}createPivotDimension(e,t){const s=e[t.fieldName],o=s?.type??"integer",i=s&&tp(s)?t.granularity:void 0;return{displayName:s?.string??t.fieldName,nameWithGranularity:t.fieldName+(i?`:${i}`:""),fieldName:t.fieldName,granularity:i,type:s?.isCustomField?"custom":o,order:t.order,isValid:!!s,isCustomField:!!s?.isCustomField,customGroups:s?.customGroups,parentField:s?.parentField}}}class UD extends VD{range;constructor(e,t,s){if(super(e,t),e.dataSet){const{sheetId:t,zone:o}=e.dataSet;this.range=s.getRangeFromZone(t,o)}}}function HD(e,t,s){const o=t.measures.filter(e=>!e.isHidden).map(e=>e.id),i=BD(e,t.columns,0);GD(i,o.length);const n=function(e,t){const s=t.columns.map(e=>e.nameWithGranularity),o=s.length,i=t.measures.filter(e=>!e.isHidden),n=i.length,r=new Array(o).fill(0).map(()=>[]);function a(e,t,i){const n=r[t];for(const r of e){const e=i.concat([r.value]),l={fields:s.slice(0,t+1),values:e,width:r.width,offset:0};n.push(l),t<=o-1&&a(r.children,t+1,e)}}a(e,0,[]);const l=s.length>0,c=[];l&&r[r.length-1].forEach(e=>{i.forEach(t=>{const s={fields:[...e.fields,"measure"],values:[...e.values,t.id],width:1,offset:0};c.push(s)})});i.forEach(e=>{const t={fields:["measure"],values:[e.id],width:1,offset:0};c.push(t)}),r.push(c),1===r.length&&r.unshift([]);return r[r.length-2].push({fields:[],values:[],width:n,offset:0}),r}(i,t),r=zD(e,0,t.rows,[],[]);r.push({fields:[],values:[],indent:0});const a={};for(const e of t.columns)a[e.fieldName]=e.type;for(const e of t.rows)a[e.fieldName]=e.type;const l="collapsed"===s?t.collapsedDomains:void 0;return new yA(n,r,o,a,l)}function zD(e,t,s,o,i){if(t>=s.length)return[];const n=s[t],r=n.nameWithGranularity,a=WD(e,n),l=$D(a,n),c=[],h=o.concat(r);for(const e of l){const o=i.concat(e);c.push({fields:h,values:o,indent:t+1});const n=a[e];n&&c.push(...zD(n,t+1,s,h,o))}return c}function BD(e,t,s){if(s>=t.length)return[];const o=t[s],i=t[s].nameWithGranularity,n=WD(e,o);return $D(n,t[s]).map(e=>({value:n[e]?.[0]?.[o.nameWithGranularity]?.value??null,field:i,children:BD(n[e]||[],t,s+1),type:o.type,width:0}))}function GD(e,t){for(const s in e){const o=e[s];0===o.children.length?o.width=t:(GD(o.children,t),o.width=o.children.reduce((e,t)=>e+t.width,0))}}function WD(e,t){return Object.groupBy(e,function(e){const t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}(t))}function $D(e,t){const s=t.order,o=t.customGroups?.find(e=>e.isOtherGroup);return s||o?Object.keys(e).sort((e,i)=>o&&e===o.name?1:o&&i===o.name?-1:s?function(e,t,s){if("null"===t)return"asc"===e.order?1:-1;if("null"===s)return"asc"===e.order?-1:1;if("integer"===e.type||"datetime"===e.type)return"asc"===e.order?bo(t,Oc)-bo(s,Oc):bo(s,Oc)-bo(t,Oc);return"asc"===e.order?t.localeCompare(s):s.localeCompare(t)}(t,e,i):0):Object.keys(e)}const qD=Symbol("NULL");function ZD(e,t,s){const o=e.granularity||"month";if(!(o in jD))throw new Error(`Unknown date granularity: ${o}`);const i="number"==typeof t||"string"==typeof t?t:qD;if(!jD[o].set.has(t)){jD[o].set.add(t);let n=null;if("number"==typeof t||"string"==typeof t){const e=Ao(t,s);switch(o){case"year":n=e.getFullYear();break;case"quarter_number":n=Math.floor(e.getMonth()/3)+1;break;case"month_number":n=e.getMonth()+1;break;case"month":case"day":n=Math.floor(bo(t,s));break;case"iso_week_number":n=e.getIsoWeek();break;case"day_of_month":n=e.getDate();break;case"day_of_week":n=(e.getDay()+7-s.weekStart)%7+1;break;case"hour_number":n=e.getHours();break;case"minute_number":n=e.getMinutes();break;case"second_number":n=e.getSeconds()}}jD[o].values[i]=np(e,n)}return jD[o].values[i]}const jD={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:{}}};var YD;!function(e){e[e.NONE=0]="NONE",e[e.TABLE=1]="TABLE",e[e.DATA=2]="DATA",e[e.DEFINITION=3]="DEFINITION",e[e.ALL=4]="ALL"}(YD||(YD={}));const XD=new is,KD=["year","quarter_number","month_number","month","iso_week_number","day_of_month","day","day_of_week"];XD.add("SPREADSHEET",{ui: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(YD.ALL),this.needsReevaluation=!1)}reload(e){e===YD.ALL&&(this.metaData=this.loadMetaData()),e>=YD.DEFINITION&&(this._definition=this.loadRuntimeDefinition()),e>=YD.DATA&&(this.dataEntries=this.loadData()),e>=YD.TABLE&&(this.collapsedTable=void 0,this.expandedTable=void 0)}onDefinitionChange(e){const t=this.coreDefinition;if(this.coreDefinition=e,this._definition){const s=Math.max(this.computeShouldReload(t,e),YD.NONE);this.reload(s)}}computeShouldReload(e,t){return Me(e.dataSet,t.dataSet)?YD.DEFINITION:YD.ALL}get isInvalidRange(){return!!this.invalidRangeError}get invalidRangeMessage(){return this.invalidRangeError?.message}get definition(){if(this._definition||this.init(),!this._definition)throw new Error("Pivot definition should be defined at this point.");return this._definition}isValid(){if(this.invalidRangeError||!this.definition)return!1;for(const e of this.definition.measures)if(!e.isValid)return!1;for(const e of this.definition.columns)if(!e.isValid)return!1;for(const 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 Cs(fs("At least one measure and/or dimension is not correct."));return{value:bs.GenericError,message:this.invalidRangeError?.message??fs("At least one measure and/or dimension is not correct.")}}}areDomainArgsFieldsValid(e){let t=e.filter((e,t)=>t%2==0).map(Eo);return t.length&&"measure"===t.at(-1)&&(t=t.slice(0,-1)),op(t,this.definition)}parseArgsToPivotDomain(e){const t=[];for(let s=0;s<e.length-1;s+=2){const o=Eo(e[s]),i=this.getTypeOfDimension(o),n="measure"===o?Eo(e[s+1]):np(this.getDimension(o),e[s+1]);t.push({field:o,value:n,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){const t=e.at(-1);if(!t)return{value:fs("Total")};const s=this.getDimension(t.field),o=this.filterDataEntriesFromDomain(this.dataEntries,e),i=o[0]?.[s.nameWithGranularity];if("datetime"===s.type){return Pg(s.granularity||"month").toValueAndFormat(t.value,this.getters.getLocale())}return i?null===i.value?{value:fs("(Undefined)")}:i:{value:""}}getPivotCellValueAndFormat(e,t){const s=this.filterDataEntriesFromDomain(this.dataEntries,t);if(0===s.length)return{value:""};const o=this.getMeasure(e),i=s.map(e=>e[o.fieldName]).filter(Te),n=i.filter(e=>e.type!==_d.empty),r=o.aggregator,a=Xg[r];if(!a)throw new Error(`Aggregator ${r} does not exist`);try{const e=a([i],this.getters.getLocale());return 0===n.length?{...e,value:""}:e}catch(e){return si(e,r.toUpperCase())}}getPossibleFieldValues(e){const t=[],s=WD(this.dataEntries,e),o=$D(s,e);for(const i of o)t.push({value:s[i]?.[0]?.[e.nameWithGranularity]?.value??"",label:s[i]?.[0]?.[e.nameWithGranularity]?.formattedValue||""});return t}getCollapsedTableStructure(){if(!this.isValid())throw new Error("Pivot is not valid !");return this.collapsedTable||(this.collapsedTable=HD(this.dataEntries,this.definition,"collapsed")),this.collapsedTable}getExpandedTableStructure(){if(!this.isValid())throw new Error("Pivot is not valid !");return this.expandedTable||(this.expandedTable=HD(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)return this.invalidRangeError=new Cs(fs("The pivot cannot be created because the dataset is missing.")),{fields:{},fieldKeys:[]};{const{zone:e,sheetId:t}=this.coreDefinition.dataSet,s=this.getters.getRangeFromZone(t,e);try{const e=this.extractFieldsFromRange(s),t=fp(this.coreDefinition,e.fields);return{...e,fields:{...e.fields,...t}}}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}}loadRuntimeDefinition(){return new UD(this.coreDefinition,this.fields,this.getters)}loadData(){const e=this._definition?.range;return this.isValid()&&e?this.extractDataEntriesFromRange(e):[]}getTypeOfDimension(e){if("measure"===e)return"char";const{fieldName:t}=ep(e),s=this.fields[t]?.type;if(!s)throw new Error(`Field ${t} does not exist`);return s}filterDataEntriesFromDomain(e,t){return t.reduce((e,t)=>this.filterDataEntriesFromDomainNode(e,t),e)}filterDataEntriesFromDomainNode(e,t){const{field:s,value:o,type:i}=t,{nameWithGranularity:n}=this.getDimension(s);return e.filter(e=>{const t=e[n]?.value;return"char"===i?String(t)===String(o):t===o})}getDimension(e){return this.definition.getDimension(e)}getTypeFromZone(e,t){const s=this.getters.getEvaluatedCellsInZone(e,t).filter(e=>!(e.type===_d.empty||""===e.value));return 0===s.length?"integer":s.every(e=>e.type===_d.number&&e.format&&wn(e.format))?"datetime":s.every(e=>e.type===_d.boolean)?"boolean":s.some(e=>e.type===_d.text)?"char":"integer"}assertCellIsValidField(e,t,s){if(s.type===_d.error)throw new Cs(fs("The pivot cannot be created because cell %s contains an error",mt(e,t)));if(s.type===_d.empty||""===s.value)throw new Cs(fs("The pivot cannot be created because cell %s is empty",mt(e,t)));if("__count"===s.value)throw new Cs(fs("The pivot cannot be created because cell %s contains a reserved value",mt(e,t)))}extractFieldsFromRange(e){const t={},s=[],o=e.sheetId,i=e.zone.top;for(let n=e.zone.left;n<=e.zone.right;n++){const r=this.getters.getEvaluatedCell({sheetId:o,col:n,row:i});this.assertCellIsValidField(n,i,r);const a=r.value?.toString();if(a){const i=this.getTypeFromZone(o,{top:e.zone.top+1,left:n,bottom:e.zone.bottom,right:n}),r=mp(a,t);t[r]={name:r,type:i,string:r,aggregator:"integer"===i?"sum":"count"},s.push(r)}}return{fields:t,fieldKeys:s}}extractDataEntriesFromRange(e){const t=[];for(let s=e.zone.top+1;s<=e.zone.bottom;s++){const o={top:s,bottom:s,left:e.zone.left,right:e.zone.right},i=this.getters.getEvaluatedCellsInZone(e.sheetId,o),n={};for(const e in i){const t=i[e],s=this.fields[this.metaData.fieldKeys[e]];if(!s)throw new Error(`Field ${this.metaData.fieldKeys[e]} does not exist`);""===t.value?n[s.name]={value:null,type:_d.empty,formattedValue:""}:n[s.name]=t}for(const e in this.definition.customFields||{}){const t=this.definition.customFields?.[e];if(!t)continue;const s=n[t.parentField],o=this.fields[t.parentField];if(!s||!o){n[e]={value:null,type:_d.empty,formattedValue:""};continue}const i=t.groups.find(e=>e.values.some(e=>e===s?.value))||t.groups.find(e=>e.isOtherGroup);n[e]={...s,value:i?i.name:s.value}}n.__count={value:1,type:_d.number,formattedValue:"1"},t.push(n)}const s=this.definition.columns.concat(this.definition.rows).filter(e=>"datetime"===e.type);if(s.length){const e=this.getters.getLocale();for(const o of t)for(const t of s){const s=ZD(t,o[t.fieldName]?.value||null,this.getters.getLocale()),i=Pg(t.granularity||"month"),{format:n,value:r}=i.toValueAndFormat(s,e);o[t.nameWithGranularity]={value:s,type:o[t.fieldName]?.type||_d.empty,format:o[t.fieldName]?.format,formattedValue:pn(r,{locale:e,format:n})}}}return t}},definition:UD,externalData:!1,dateGranularities:[...KD],datetimeGranularities:[...KD,"hour_number","minute_number","second_number"],isMeasureCandidate:e=>"boolean"!==e.type,isGroupable:()=>!0,canHaveCustomGroup:e=>"char"===e.type&&!e.isCustomField});const JD=["ADD_PIVOT","UPDATE_PIVOT","REMOVE_PIVOT"];function QD(e){return JD.includes(e.type)}const e_=new Og;e_.add("ALPHANUMERIC_INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;let s=Math.abs(e.current).toString();s="0".repeat(Math.max(e.numberPostfixLength-s.length,0))+s;const o=`${e.prefix}${s}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:{props:{content:o}}}}}).add("INCREMENT_MODIFIER",{apply:(e,t,s)=>{e.current+=e.increment;const o=e.current.toString(),i=s.getLocale(),n=pn(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:o},tooltip:o?{props:{content:n}}:void 0}}}).add("DATE_INCREMENT_MODIFIER",{apply:(e,t,s)=>{const o=Ao(e.current,s.getLocale());o.setFullYear(o.getFullYear()+e.increment.years||0),o.setMonth(o.getMonth()+e.increment.months||0),o.setDate(o.getDate()+e.increment.days||0);const i=Xs(o);e.current=i;const n=s.getLocale(),r=pn(i,{format:t.cell?.format,locale:n});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:r}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,s)=>{const o=t.cell?.content||"",i={locale:s.getLocale(),format:t.cell?.format};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:t.cell?Yv(t.cell,i).formattedValue:""}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,s,o)=>{e.current+=e.increment;let i=0,n=0;switch(o){case"up":i=0,n=-e.current;break;case"down":i=0,n=e.current;break;case"left":i=-e.current,n=0;break;case"right":i=e.current,n=0}const r=t.cell;if(!r||!r.isFormula)return{cellData:{}};const a=t.sheetId,l=s.getTranslatedCellFormula(a,i,n,r.compiledFormula.tokens);return{cellData:{border:t.border,style:r.style,format:r.format,content:l},tooltip:l?{props:{content:l}}:void 0}}});const t_=new Og,s_=/(\d+)$/,o_=/^(.*\D+)/,i_=/^(.*\D+)(\d+)$/,n_=/^0*/;function r_(e,t,s){let o=[],i=!1;for(const n of t){n===e&&(i=!0);const t=void 0===n||n.isFormula?void 0:Yv(n,{locale:Oc,format:n.format});if(t&&s(t))o.push(t);else{if(i)return o;o=[]}}return o}function a_(e){let t=1;return e.length>=2&&(t=function(e){const t=[];let s=e[0];for(let o=1;o<e.length;o++){const i=e[o];t.push(i-s),s=i}return t.reduce((e,t)=>e+t,0)/t.length}(e)*e.length),t}function l_(e){if(e.length<2)return 1;const t=e.map(e=>Ao(e,Oc)),s=function(e){if(e.length<2)return[{years:0,months:0,days:0}];const t=e.map((t,s)=>{if(0===s)return{years:0,months:0,days:0};const o=Os.fromTimestamp(e[s-1].getTime()),i=io(o,t),n=so(o,t)%12;o.setFullYear(o.getFullYear()+i),o.setMonth(o.getMonth()+n);return{years:i,months:n,days:oo(o,t)}});return t.slice(1)}(t),o=(i=s).length<2?i[0]||{years:0,months:0,days:0}:i.every(e=>e.years===i[0].years&&e.months===i[0].months&&e.days===i[0].days)?i[0]:void 0;var i;if(void 0===o)return;const n=1===Object.values(o).filter(e=>0!==e).length,r=Object.values(o).every(e=>0===e);if(!n||r){const s=t.map((e,s)=>{if(0===s)return 0;const o=t[s-1];return Math.floor(e.getTime())-Math.floor(o.getTime())}).slice(1);if(s.every(e=>e===s[0]))return e.length*(e[1]-e[0])}return{years:o.years*e.length,months:o.months*e.length,days:o.days*e.length}}t_.add("simple_value_copy",{condition:(e,t)=>!(1!==t.length||e.isFormula||e.format&&wn(e.format)),generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&Yv(e,{locale:Oc}).type===_d.text&&i_.test(e.content),generateRule:(e,t,s)=>{const o=parseInt(e.content.match(s_)[0]),i=e.content.match(o_)[0],n=r_(e,t,e=>e.type===_d.text&&i_.test(e.value)).filter(e=>i===(e.value??"").toString().match(o_)[0]).map(e=>(e.value??"").toString().match(s_)[0]),r=n.reduce((e,t)=>{const s=t.match(n_)[0].length;return s>e[1]?[t,s]:e},[n[0],0]),a=r[1]?r[0].length:0;let l=a_(n.map(e=>parseInt(e)));return["up","left"].includes(s)&&1===n.length&&(l=-l),{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:i,current:o,increment:l,numberPostfixLength:a}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&Yv(e,{locale:Oc}).type===_d.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&&Yv(e,{locale:Oc}).type===_d.number&&!!e.format&&wn(e.format),generateRule:(e,t)=>{const s=l_(r_(e,t,e=>e.type===_d.number&&!!e.format&&wn(e.format)).map(e=>Number(e.value)));if(void 0===s)return{type:"COPY_MODIFIER"};const o=Yv(e,{locale:Oc});return"object"==typeof s?{type:"DATE_INCREMENT_MODIFIER",increment:s,current:o.type===_d.number?o.value:0}:{type:"INCREMENT_MODIFIER",increment:s,current:o.type===_d.number?o.value:0}},sequence:25}).add("increment_number",{condition:e=>!e.isFormula&&Yv(e,{locale:Oc}).type===_d.number,generateRule:(e,t,s)=>{const o=r_(e,t,e=>e.type===_d.number&&!wn(e.format||"")).map(e=>Number(e.value));let i=a_(o);["up","left"].includes(s)&&1===o.length&&(i=-i);const n=Yv(e,{locale:Oc});return{type:"INCREMENT_MODIFIER",increment:i,current:n.type===_d.number?n.value:0}},sequence:40});class c_{cells;getters;index=0;direction;constructor(e,t,s){this.cells=e,this.getters=t,this.direction=s}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:s,tooltip:o}=e_.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:s,tooltip:o,origin:{col:e.data.col,row:e.data.row}}}}const h_=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 d_(e){return h_.has(e.type)}const u_=new Og,g_=new Og;function p_(e,t){if(e.rootCommand&&"object"==typeof e.rootCommand)return vr(e.rootCommand)?function(e,t){if(!t)return;if(!u_.contains(t.type))return;return u_.get(t.type)(e,t)}(t,e.rootCommand):function(e,t,s){if(!g_.contains(t.type))return;return g_.get(t.type)(e,t,s)}(t,e.rootCommand,e.commands)}class m_{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,Eo(e.value)])}isValuePresent(e,t){const s=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(s)}isHeaderPresent(e){const t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){const s=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(s)}trackHeader(e){const t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}}const f_=new Og,v_={type:"bar",title:{},stacked:!1,dataSetsHaveTitle:!1,dataSets:[],legendPosition:"top",humanize:!0};function b_(e,t){if(t.title)return t.title;if("carouselDataView"===t.type)return fs("Data");const s=e.getChartDefinition(t.chartId);return(f_.getAll().find(e=>e.matcher?.(s))||f_.get(s.type)).displayName}const S_=["image/avif","image/bmp","image/gif","image/vnd.microsoft.icon","image/jpeg","image/png","image/tiff","image/webp"];function C_(e,t){const s=new Set(t.map(e=>e.left)),o=new Set(t.map(e=>e.right)),i=new Set(t.map(e=>e.top)),n=new Set(t.map(e=>e.bottom)),r=1===i.size&&1===n.size||1===s.size&&1===o.size?function(e){return e.reduce((e,t)=>{const s=e.length;for(let o=0;o<s;o++)if(Lt(e[o],t))return e[o]=Ft(e[o],t),e;return e[s]=t,e},[])}(t):[t[t.length-1]],a=r.map(e=>Bt(e)).flat();return{sheetId:e,zones:t,clippedZones:r,columnsIndexes:[...new Set(a.map(e=>e.col))].sort((e,t)=>e-t),rowsIndexes:[...new Set(a.map(e=>e.row))].sort((e,t)=>e-t)}}function y_(e,t,s){const o=Math.max(e.right-t+1,e.left),i=Math.max(e.bottom-s+1,e.top),n=[];for(let r=e.left;r<=o;r+=t)for(let o=e.top;o<=i;o+=s)n.push({left:r,top:o,bottom:o+s-1,right:r+t-1});return n}function I_(e,t){if(!t.length||!t[0].length)return e;const s=t[0].length,o=t.length;return e.map(e=>y_(e,s,o)).flat()}function w_(e){let t;if(e[gI.Html]){t=function(e){const t=[...e.documentElement.attributes];if(t.some(e=>e.value.includes("microsoft")))return;const s=e.querySelector("div")?.getAttribute("data-osheet-clipboard");return s&&JSON.parse(s)}((new DOMParser).parseFromString(e[gI.Html],"text/html"))}const s=e[gI.PlainText]||"";let o;if(!s.trim())for(const t of S_)if(e[t]){o=e[t];break}return{text:s,data:t,imageBlob:o}}const E_=(e,t,s,o)=>{e.forEach(({handlerName:e,handler:i})=>{const n=t[e];n&&i.paste(s,n,o)})};function R_(e,t,s,o,i){let n;const r=[],a={sheetId:e,zones:t};for(const{handlerName:l,handler:c}of o){const o=s[l];if(!o)continue;const h=c.getPasteTarget(e,t,o,i);h.figureId&&(a.figureId=h.figureId);for(const e of h.zones)r.push(e),n=void 0!==n?Ft(n,e):e}return{target:a,zone:n,selectedZones:r}}const x_=(e,t,s)=>{const o={col:t[0].left,row:t[0].top};e.getBackToDefault(),e.selectZone({cell:o,zone:Ft(...s)},{scrollIntoView:!1})},T_={figureHandlers:new Og,cellHandlers:new Og},A_=5242880;const D_={filterType:"criterion",type:"none",values:[]};class __{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,s,o,i,n){if(this.getters=e,this.sheetId=t,this.boundaries=s,o.width<0||o.height<0)throw new Error("Viewport size cannot be negative");this.viewportWidth=o.height&&o.width,this.viewportHeight=o.width&&o.height,this.top=s.top,this.bottom=s.bottom,this.left=s.left,this.right=s.right,this.offsetX=n.x,this.offsetY=n.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(){const 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:s}=this.getters.getColDimensions(this.sheetId,e),{end:o}=this.getters.getRowDimensions(this.sheetId,t);let i=s-this.offsetCorrectionX;this.canScrollHorizontally&&(i=Math.max(i,this.viewportWidth));let n=o-this.offsetCorrectionY;return this.canScrollVertically&&(n=Math.max(n,this.viewportHeight),o+46>n&&!this.getters.isReadonly()&&(n+=46)),{width:i,height:n}}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){const t=this.sheetId,s=this.getters.getMainCellPosition({sheetId:t,...e}),{col:o,row:i}=this.getters.getNextVisibleCellPosition(s);kt(o,this.boundaries.top,this.boundaries)&&this.adjustPositionX(o),kt(this.boundaries.left,i,this.boundaries)&&this.adjustPositionY(i)}adjustPositionX(e){const t=this.sheetId,{start:s,end:o}=this.getters.getColDimensions(t,e);this.offsetX+this.viewportWidth+this.offsetCorrectionX<o?this.offsetX=o-this.viewportWidth:this.offsetX+this.offsetCorrectionX>s&&(this.offsetX=s-this.offsetCorrectionX),this.adjustViewportZoneX()}adjustPositionY(e){const t=this.sheetId,{start:s,end:o}=this.getters.getRowDimensions(t,e);this.offsetY+this.viewportHeight+this.offsetCorrectionY<o?this.offsetY=o-this.viewportHeight:this.offsetY+this.offsetCorrectionY>s&&(this.offsetY=s-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){const t=Pt(e,this),s=this.snapCorrection.x,o=this.snapCorrection.y;if(t){return{x:this.getters.getColRowOffset("COL",this.left,t.left)+this.offsetCorrectionX-(this.left!==t.left?s:0),y:this.getters.getColRowOffset("ROW",this.top,t.top)+this.offsetCorrectionY-(this.top!==t.top?o:0),width:Math.min(this.getters.getColRowOffset("COL",t.left,t.right+1)-(this.left===t.left?s:0),this.viewportWidth),height:Math.min(this.getters.getColRowOffset("ROW",t.top,t.bottom+1)-(this.top===t.top?o:0),this.viewportHeight)}}}getFullRect(e){const t=Pt(e,this.boundaries),s=this.snapCorrection.x,o=this.snapCorrection.y;if(t){return{x:this.getters.getColRowOffset("COL",this.left,e.left)+this.offsetCorrectionX-s,y:this.getters.getColRowOffset("ROW",this.top,e.top)+this.offsetCorrectionY-o,width:this.getters.getColRowOffset("COL",e.left,e.right+1),height:this.getters.getColRowOffset("ROW",e.top,e.bottom+1)}}}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,s=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;const o=this.sheetId,i=this.getters.getNumberHeaders(o,e);let n=s,r=i;for(;n<=r&&n!==i&&-1!==r;){const i=Math.floor((n+r)/2),a=this.getters.getColRowOffset(e,s,i),l=this.getters.getHeaderSize(o,e,i);if(t>=a&&t<a+l)return i;t>=a+l?n=i+1:r=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){const{width:e}=this.getMaxSize();this.viewportWidth+this.offsetX>e&&(this.offsetX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){const{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&&(-1===this.left&&(this.left=this.boundaries.left),-1===this.right&&(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&&(-1===this.top&&(this.top=this.boundaries.top),-1===this.bottom&&(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)))}}}const O_=(new is).add("settings",class extends XT{static getters=["getLocale"];locale=Oc;allowDispatch(e){return"UPDATE_LOCALE"===e.type?Xc(e.locale)?"Success":"InvalidLocale":"Success"}handle(e){if("UPDATE_LOCALE"===e.type){const t=this.locale,s=e.locale;this.history.update("locale",s),this.changeCellsDateFormatWithLocale(t,s)}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(const s of this.getters.getSheetIds())for(const[o,i]of Object.entries(this.getters.getCells(s))){let s;if(i.format===e.dateFormat&&(s=t.dateFormat),i.format===e.timeFormat&&(s=t.timeFormat),i.format===hh(e)&&(s=hh(t)),s){const{col:e,row:t,sheetId:i}=this.getters.getCellPosition(o);this.dispatch("UPDATE_CELL",{col:e,row:t,sheetId:i,format:s})}}}import(e){this.locale=e.settings?.locale??Oc}export(e){e.settings={locale:this.locale}}}).add("sheet",class extends XT{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"];sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if("Success"!==t)return t;switch(e.type){case"HIDE_SHEET":return 1===this.getVisibleSheetIds().length?"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{const t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),"Success"}catch(e){return"WrongSheetMove"}case"RENAME_SHEET":return this.isRenameAllowed(e);case"COLOR_SHEET":return!e.color||Sv(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":{const t=Je(e.elements),s=Ke(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,s)?"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":const 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":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?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(const t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(const t of e.sheets){const e=t.name||"Sheet"+(Object.keys(this.sheets).length+1),{colNumber:s,rowNumber:o}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:s,rows:ub(o),areGridLinesVisible:void 0===t.areGridLinesVisible||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(Te).map(e=>{const t=this.sheets[e],s={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:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(s.panes=t.panes),s})}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){const t=this.sheets[e];if(!t)throw new 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){const t=le(e);for(const e in this.sheetIdsMapName)if(vb(e,t))return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,s){return"COL"===t?s>=0&&s<this.getNumberCols(e):s>=0&&s<this.getNumberRows(e)}doesHeadersExist(e,t,s){return s.every(s=>this.doesHeaderExist(e,t,s))}getCell({sheetId:e,col:t,row:s}){const o=this.tryGetSheet(e),i=o?.rows[s]?.cells[t];if(void 0!==i)return this.getters.getCellById(i)}getColsZone(e,t,s){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:s}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(Te)}getRowsZone(e,t,s){return{top:t,bottom:s,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new 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"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){return mb(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(void 0===t.bottom||void 0===t.right)return t;const s=0===t.left&&t.right===this.getNumberCols(e)-1,o=0===t.top&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:o?void 0:t.bottom,right:s&&!o?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,s){const o={...this.getPaneDivisions(e)};"COL"===s?o.xSplit=t:"ROW"===s&&(o.ySplit=t),this.history.update("sheets",e,"panes",o)}checkElementsIncludeAllNonFrozenHeaders(e,t,s){const o=this.getters.getPaneDivisions(e),i="ROW"===t?o.ySplit:o.xSplit,n=this.getters.getNumberHeaders(e,t);if(!i)return!1;return ke(s,ge(i,n))}getCommandZones(e){const 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&&void 0!==e.col&&"row"in e&&void 0!==e.row&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(Rt))return"InvalidRange";if(t.length){const s=this.getSheetZone(e);return t.every(e=>Vt(e,s))?"Success":"TargetOutOfSheet"}return"Success"}updateCellPosition(e){const{sheetId:t,cellId:s,col:o,row:i}=e;s?this.setNewPosition(s,t,o,i):this.clearPosition(t,o,i)}setNewPosition(e,t,s,o){const i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update("cellPosition",e,{row:o,col:s,sheetId:t}),this.history.update("sheets",t,"rows",o,"cells",s,e)}clearPosition(e,t,s){const o=this.sheets[e]?.rows[s].cells[t];o&&(this.history.update("cellPosition",o,void 0),this.history.update("sheets",e,"rows",s,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}createSheet(e,t,s,o,i){const n={id:e,name:t,numberOfCols:s,rows:ub(o),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},r=this.orderedSheetIds.slice();r.splice(i,0,n.id);const a=this.sheets;return this.history.update("orderedSheetIds",r),this.history.update("sheets",Object.assign({},a,{[n.id]:n})),n}moveSheet(e,t){const s=this.orderedSheetIds.slice(),o=s.findIndex(t=>t===e),i=s.splice(o,1),n=this.findIndexOfTargetSheet(o,t);s.splice(n,0,i[0]),this.history.update("orderedSheetIds",s)}findIndexOfTargetSheet(e,t){for(;0!==t&&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(0===t)return e;throw new Error("There is not enough visible sheets")}checkSheetName(e){const t=this.getters.tryGetSheetName(e.sheetId),s="RENAME_SHEET"===e.type?e.newName:e.name;if(void 0!==t&&s===t)return"UnchangedSheetName";const{orderedSheetIds:o,sheets:i}=this,n=s&&s.trim().toLowerCase();return o.find(t=>vb(i[t]?.name,n)&&t!==e.sheetId)?"DuplicatedSheetName":q.test(n)?"ForbiddenCharactersInSheetName":"Success"}checkSheetPosition(e){const{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){const t=this.getters.getMerges(e.sheetId);for(const s of t)if(s.top<e.quantity&&e.quantity<=s.bottom)return"MergeOverlap";return"Success"}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(const s of t)if(s.left<e.quantity&&e.quantity<=s.right)return"MergeOverlap";return"Success"}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):"MissingSheetName"}renameSheet(e,t){const s=e.name;this.history.update("sheets",e.id,"name",t.trim());const o=Object.assign({},this.sheetIdsMapName);delete o[s],o[t]=e.id,this.history.update("sheetIdsMapName",o)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t,s){const o=ae(this.getSheet(e));o.id=t,o.name=s;for(let e=0;e<=o.numberOfCols;e++)for(let t=0;t<=o.rows.length;t++)o.rows[t]&&(o.rows[t].cells[e]=void 0);const i=this.orderedSheetIds.slice(),n=i.indexOf(e);i.splice(n+1,0,o.id),this.history.update("orderedSheetIds",i),this.history.update("sheets",Object.assign({},this.sheets,{[o.id]:o}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:s}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:o.id,col:e,row:s,content:t.content,format:t.format,style:t.style})}const r=Object.assign({},this.sheetIdsMapName);r[o.name]=o.id,this.history.update("sheetIdsMapName",r)}getDuplicateSheetName(e){return fb(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){const t=e.name,s=Object.assign({},this.sheets);delete s[e.id],this.history.update("sheets",s);const o=this.orderedSheetIds.slice(),i=o.indexOf(e.id);o.splice(i,1),this.history.update("orderedSheetIds",o);const n=Object.assign({},this.sheetIdsMapName);delete n[t],this.history.update("sheetIdsMapName",n)}removeColumns(e,t){t.sort((e,t)=>t-e);for(const s of t)this.moveCellOnColumnsDeletion(e,s);const s=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",s-t.length);const o=t.filter(t=>t<e.panes.xSplit).length;o&&this.setPaneDivisions(e.id,e.panes.xSplit-o,"COL")}removeRows(e,t){t.sort((e,t)=>t-e);for(const s of pe(t)){const t=s[s.length-1],o=s[0];this.moveCellOnRowsDeletion(e,t,o),this.updateRowsStructureOnDeletion(e,t,o)}const s=t.filter(t=>t<e.panes.ySplit).length;s&&this.setPaneDivisions(e.id,e.panes.ySplit-s,"ROW")}addColumns(e,t,s,o){const i="before"===s?t:t+1;this.moveCellsOnAddition(e,i,o,"columns");const n=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",n+o),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+o,"COL")}addRows(e,t,s,o){const i="before"===s?t:t+1;this.addEmptyRows(e,o),this.moveCellsOnAddition(e,i,o,"rows"),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+o,"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 s=0;s<e.rows.length;s++){const o=e.rows[s];for(const i in o.cells){const n=Number(i),r=o.cells[i];r&&n>t&&this.setNewPosition(r,e.id,n-1,s)}}}moveCellsOnAddition(e,t,s,o){const i=[];for(let n=0;n<e.rows.length;n++){const r=e.rows[n];if("rows"!==o||n>=t)for(const a in r.cells){const l=Number(a),c=r.cells[a];c&&("rows"===o||l>=t)&&i.push({sheetId:e.id,cellId:c,col:l+("columns"===o?s:0),row:n+("rows"===o?s:0),type:"UPDATE_CELL_POSITION"})}}for(const e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,s){this.dispatch("CLEAR_CELLS",{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:s}]});const o=s-t+1;for(let t=0;t<e.rows.length;t++){const i=e.rows[t];if(t>s)for(const s in i.cells){const n=Number(s),r=i.cells[s];r&&this.setNewPosition(r,e.id,n,t-o)}}}updateRowsStructureOnDeletion(e,t,s){const o=[],i=e.rows.map(e=>e.cells).reverse();for(const n in e.rows){const e=Number(n);e>=t&&e<=s||o.push({cells:i.pop()})}this.history.update("sheets",e.id,"rows",o)}addEmptyRows(e,t){const s=e.rows.slice();for(let e=0;e<t;e++)s.push({cells:{}});this.history.update("sheets",e.id,"rows",s)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(pt);let s=e.rowNumber,o=e.colNumber;for(const{col:e,row:i}of t)s=Math.max(s,i+1),o=Math.max(o,e+1);return{rowNumber:s,colNumber:o}}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?"InvalidSheetId":"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?"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"}}).add("header grouping",class extends XT{static getters=["getHeaderGroups","getGroupsLayers","getVisibleGroupLayers","getHeaderGroup","getHeaderGroupsInZone","isGroupFolded","isRowFolded","isColFolded"];groups={};allowDispatch(e){switch(e.type){case"GROUP_HEADERS":{const{start:t,end:s,sheetId:o}=e;if(!this.getters.tryGetSheet(o))return"InvalidSheetId";if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,s]))return"InvalidHeaderGroupStartEnd";if(t>s)return"InvalidHeaderGroupStartEnd";if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,s))return"HeaderGroupAlreadyExists";break}case"UNGROUP_HEADERS":{const{start:t,end:s,sheetId:o}=e;if(!this.getters.tryGetSheet(o))return"InvalidSheetId";if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,s]))return"InvalidHeaderGroupStartEnd";if(t>s)return"InvalidHeaderGroupStartEnd";break}case"UNFOLD_HEADER_GROUP":case"FOLD_HEADER_GROUP":if(!this.getters.tryGetSheet(e.sheetId))return"InvalidSheetId";const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return"UnknownHeaderGroup";if(ge(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(s=>s>=t.start&&s<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,s)))return"NotEnoughElements"}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":{const t=ae(this.groups[e.sheetId]);this.history.update("groups",e.sheetIdTo,t);break}case"DELETE_SHEET":{const t={...this.groups};delete t[e.sheetId],this.history.update("groups",t);break}case"ADD_COLUMNS_ROWS":const t=Pe(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":{const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case"FOLD_HEADER_GROUP":{const 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":{const t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(const s of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,s);break}case"FOLD_ALL_HEADER_GROUPS":{const t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(const s of t)this.foldHeaderGroup(e.sheetId,e.dimension,s);break}case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":{const t="UNFOLD_HEADER_GROUPS_IN_ZONE"===e.type?"unfold":"fold",s=this.getGroupsLayers(e.sheetId,e.dimension);"fold"===t&&s.reverse();const o=s.flat(),i="ROW"===e.dimension?e.zone.top:e.zone.left,n="ROW"===e.dimension?e.zone.bottom:e.zone.right,r=new Set;for(let e=i;e<=n;e++){const s=o.filter(t=>t.start-1<=e&&e<=t.end);for(const e of s)if(!("fold"===t&&e.isFolded||"unfold"===t&&!e.isFolded)){r.add(e);break}}for(const s of r)"unfold"===t?this.unfoldHeaderGroup(e.sheetId,e.dimension,s):this.foldHeaderGroup(e.sheetId,e.dimension,s);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,s,o){return this.getHeaderGroups(e,t).find(e=>e.start===s&&e.end===o)}getHeaderGroupsInZone(e,t,s){return this.getHeaderGroups(e,t).filter(e=>{const o="ROW"===t?s.top:s.left,i="ROW"===t?s.bottom:s.right;return this.doGroupOverlap(e,o,i)})}getGroupsLayers(e,t){const s=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(s,0,0)}getVisibleGroupLayers(e,t){const s=this.getGroupsLayers(e,t);for(const o of s)for(let s=o.length-1;s>=0;s--){const i=o[s];if(0===i.start)continue;ge(i.start-1,i.end+1).every(s=>this.getters.isHeaderHiddenByUser(e,t,s))&&o.splice(s,1)}return s.filter(e=>e.length>0)}isGroupFolded(e,t,s,o){return this.getHeaderGroup(e,t,s,o)?.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,s,o=0){const i={};for(const t of e)i[this.getGroupId(t)]=t.isFolded;const n={};for(const t of e)for(let e=t.start;e<=t.end;e++)n[e]=n[e]?n[e]+1:1;for(let e=t;e<=s;e++)n[e]=n[e]?n[e]+o:o;const r=Math.max(...Object.values(n),0),a=Array.from({length:r},()=>[]),l=Math.max(s,...e.map(e=>e.end)),c=Math.min(t,...e.map(e=>e.start));for(let e=c;e<=l;e++){const t=n[e]||0;for(let s=0;s<t;s++){const t=a[s].at(-1);if(t&&We([t.end,e]))t.end++;else{const t={start:e,end:e};a[s].push(t)}}}for(const e of a)for(const t of e)t.isFolded=i[this.getGroupId(t)];return a}groupHeaders(e,t,s,o){const i=this.getHeaderGroups(e,t),n=this.bricksFallingAlgorithm(i,s,o,1).flat();this.history.update("groups",e,t,this.removeDuplicateGroups(n))}unGroupHeaders(e,t,s,o){const i=this.getHeaderGroups(e,t),n=this.bricksFallingAlgorithm(i,s,o,-1).flat();this.history.update("groups",e,t,this.removeDuplicateGroups(n))}moveGroupsOnHeaderInsertion(e,t,s,o){const i=this.groups[e][t];for(let n=0;n<i.length;n++){const r=i[n],[a,l]=gb(s,o,[r.start,r.end]);a===r.start&&l===r.end||this.history.update("groups",e,t,n,{...r,start:a,end:l})}}moveGroupsOnHeaderDeletion(e,t,s){const o=this.getHeaderGroups(e,t),i=[];for(const e of o){const t=pb(s,ge(e.start,e.end+1));0!==t.length&&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,s){return e.start<=s&&e.end>=t}removeDuplicateGroups(e){const t={};for(const s of e)t[this.getGroupId(s)]=s;return Object.values(t)}findGroupWithStartEnd(e,t,s,o){return this.getHeaderGroups(e,t).find(e=>e.start===s&&e.end===o)}foldHeaderGroup(e,t,s){const o=this.getGroupIndex(e,t,s.start,s.end);if(void 0===o)return;this.history.update("groups",e,t,o,"isFolded",!0);const i=this.getters.getHeaderGroups(e,t);for(let o=0;o<i.length;o++){const n=i[o];n.start===s.start&&n.end<=s.end&&this.history.update("groups",e,t,o,"isFolded",!0)}}unfoldHeaderGroup(e,t,s){const o=this.getGroupIndex(e,t,s.start,s.end);if(void 0===o)return;this.history.update("groups",e,t,o,"isFolded",!1);const i=this.getters.getHeaderGroups(e,t);for(let o=0;o<i.length;o++){const n=i[o];n.start===s.start&&n.end>=s.end&&this.history.update("groups",e,t,o,"isFolded",!1)}}getGroupIndex(e,t,s,o){const i=this.groups[e][t].findIndex(e=>e.start===s&&e.end===o);return-1===i?void 0:i}import(e){for(const t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(const e of["ROW","COL"])for(const s of t.headerGroups[e]||[])this.groups[t.id][e].push({...s})}export(e){for(const t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(const t of e.sheets)for(const e of["ROW","COL"]){const s=this.getGroupsLayers(t.id,e);for(let o=0;o<s.length;o++){const i=s[o];for(const s of i){for(let i=s.start;i<=s.end;i++){const n=CR(t,e,i);n.outlineLevel=o+1,s.isFolded&&(n.isHidden=!0)}if(s.isFolded){CR(t,e,s.end+1).collapsed=!0}}}}}}).add("header visibility",class extends XT{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";const t="COL"===e.dimension?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),s="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=s?"TooManyHiddenElements":Je(e.elements)<0||Ke(e.elements)>s?"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":const 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,ae(this.hiddenHeaders[e.sheetId]));break;case"DELETE_SHEET":this.history.update("hiddenHeaders",e.sheetId,void 0);break;case"REMOVE_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(const s of[...e.elements].sort((e,t)=>t-e))t.splice(s,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=Pe(e.position,e.base),s=Ze([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update("hiddenHeaders",e.sheetId,e.dimension,s);break}case"HIDE_COLUMNS_ROWS":for(const t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!0);break;case"UNHIDE_COLUMNS_ROWS":for(const t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!1)}}checkElementsIncludeAllVisibleHeaders(e,t,s){return ke(s,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,s){return"COL"===t?this.isColHiddenByUser(e,s):this.isRowHiddenByUser(e,s)}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){const t=[[]],s=this.hiddenHeaders[e].COL;for(let e=0;e<s.length;e++){s[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getHiddenRowsGroups(e){const t=[[]],s=this.hiddenHeaders[e].ROW;for(let e=0;e<s.length;e++){s[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getAllVisibleHeaders(e,t){const s=ge(0,this.getters.getNumberHeaders(e,t)),o=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&o.push(...ge(e.start,e.end+1))}),s.filter(s=>!this.hiddenHeaders[e][t][s]&&!o.includes(s))}import(e){for(const t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=Boolean(t.rows[e]?.isHidden);for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=Boolean(t.cols[e]?.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(const s of e.sheets){void 0===s.rows&&(s.rows={});for(let e=0;e<this.getters.getNumberRows(s.id);e++)(t||this.hiddenHeaders[s.id].ROW[e])&&(void 0===s.rows[e]&&(s.rows[e]={}),s.rows[e].isHidden||=this.hiddenHeaders[s.id].ROW[e]);void 0===s.cols&&(s.cols={});for(let e=0;e<this.getters.getNumberCols(s.id);e++)(t||this.hiddenHeaders[s.id].COL[e])&&(void 0===s.cols[e]&&(s.cols[e]={}),s.cols[e].isHidden||=this.hiddenHeaders[s.id].COL[e])}}}).add("tables",class extends XT{static getters=["getCoreTable","getCoreTables","getCoreTableMatchingTopLeft"];tables={};nextTableId=1;adaptRanges(e,t){for(const s of this.getCoreTables(t))this.applyRangeChangeOnTable(t,s,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";const t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return Qt(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(const t of this.getCoreTables(e.sheetId)){const s=t.range.zone;for(const t of e.target)if(Lt(s,t))return"MergeInTable"}}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":{const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break}case"DUPLICATE_SHEET":{const t={};for(const s of this.getCoreTables(e.sheetId))t[s.id]="dynamic"===s.type?this.copyDynamicTableForSheet(e.sheetIdTo,s):this.copyStaticTableForSheet(e.sheetIdTo,s);this.history.update("tables",e.sheetIdTo,t);break}case"CREATE_TABLE":{const t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),s=this.getters.getRangesUnion(t),o=this.getters.getMergesInZone(e.sheetId,s.zone);o.length&&this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:o});const i=this.consumeNextId(),n=e.config||hE,r="dynamic"===e.tableType?this.createDynamicTable(i,s,n):this.createStaticTable(i,e.tableType,s,n);this.history.update("tables",e.sheetId,r.id,r);break}case"REMOVE_TABLE":{const t={};for(const s of this.getCoreTables(e.sheetId))e.target.every(e=>!Pt(s.range.zone,e))&&(t[s.id]=s);this.history.update("tables",e.sheetId,t);break}case"UPDATE_TABLE":this.updateTable(e);break;case"UPDATE_CELL":{const t=e.sheetId;for(const s of this.getCoreTables(t)){if("dynamic"===s.type)continue;const o=this.canUpdateCellCmdExtendTable(e,s);"down"===o?this.extendTableDown(t,s):"right"===o&&this.extendTableRight(t,s)}break}case"DELETE_CONTENT":{const t={...this.tables[e.sheetId]};for(const s in t){const o=t[s];o&&e.target.some(e=>Vt(o.range.zone,e))&&this.dispatch("REMOVE_TABLE",{sheetId:e.sheetId,target:[o.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(Te):[]}getCoreTable({sheetId:e,col:t,row:s}){return this.getCoreTables(e).find(e=>kt(t,s,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>Lt(e.range.zone,t)))}extendTableDown(e,t){const s=this.getters.extendRange(t.range,"ROW",1);this.history.update("tables",e,t.id,this.updateStaticTable(t,s))}extendTableRight(e,t){const s=this.getters.extendRange(t.range,"COL",1);this.history.update("tables",e,t.id,this.updateStaticTable(t,s))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:s,row:o},i){if(!e)return"none";const n=i.range.zone;let r="none";if(n.bottom+1===o&&s>=n.left&&s<=n.right?r="down":n.right+1===s&&o>=n.top&&o<=n.bottom&&(r="right"),"none"===r)return"none";const a="down"===r?{...n,bottom:n.bottom+1,top:n.bottom+1}:{...n,right:n.right+1,left:n.right+1};for(let e=a.top;e<=a.bottom;e++)for(let s=a.left;s<=a.right;s++){const o={sheetId:t,col:s,row:e},i=this.getters.getCell(o)?.content;if(i||this.getters.isInMerge(o)||this.getTablesOverlappingZones(t,[Zt(o)]).length)return"none"}return r}getCoreTableMatchingTopLeft(e,t){for(const s of this.getCoreTables(e)){const e=s.range.zone;if(e.left===t.left&&e.top===t.top)return s}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return"Success";const t=this.getters.getRangeFromRangeData(e.newTableRange).zone,s=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if("Success"!==s)return s;const o=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!o)return"TableNotFound";return this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==o.id).length?"TableOverlap":"Success"}checkTableConfigUpdateIsValid(e){return e&&(void 0!==e.numberOfHeaders&&e.numberOfHeaders<0||e.hasFilters&&0===e.numberOfHeaders)?"InvalidTableConfig":"Success"}createStaticTable(e,t,s,o,i){const n=s.zone;if(!i){i=[];for(const e of ge(n.left,n.right+1)){const t={...n,left:e,right:e},r=this.consumeNextId();i.push(this.createFilterFromZone(r,s.sheetId,t,o))}}return{id:e,range:s,filters:i,config:o,type:t}}createDynamicTable(e,t,s){const o=jt(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,o),config:s,type:"dynamic"}}updateTable(e){const t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;const s=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(s){const t=this.getters.getMergesInZone(e.sheetId,s.zone);this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:t})}const o=s||t.range,i=this.updateTableConfig(e.config,t.config),n=e.tableType??t.type;if("dynamic"===n&&"dynamic"!==t.type||"dynamic"!==n&&"dynamic"===t.type){const s="dynamic"===n?this.createDynamicTable(t.id,o,i):this.createStaticTable(t.id,n,o,i);this.history.update("tables",e.sheetId,t.id,s)}else{const s="dynamic"===t.type?this.updateDynamicTable(t,o,i):this.updateStaticTable(t,o,i,n);this.history.update("tables",e.sheetId,t.id,s)}}updateStaticTable(e,t,s,o=e.type){if("dynamic"===o)throw new Error("Cannot use updateStaticTable to update a dynamic table");const i=t||e.range,n=i.zone,r=this.updateTableConfig(s,e.config),a=r||e.config,l=[];if(t||r&&"numberOfHeaders"in r)for(const t of ge(n.left,n.right+1)){const s=n.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,o={...n,left:t,right:t},r=s?.id||this.consumeNextId();l.push(this.createFilterFromZone(r,i.sheetId,o,a))}return{...e,range:i,config:a,filters:l.length?l:e.filters,type:o}}updateDynamicTable(e,t,s){const o=t?this.getters.getRangeFromZone(t.sheetId,jt(t.zone)):e.range,i=s||e.config;return{...e,range:o,config:i}}updateTableConfig(e,t){if(!e)return t;const s={...t,...e};return 0===e.numberOfHeaders?s.hasFilters=!1:!0===e.hasFilters&&(s.numberOfHeaders||=1),s}createFilterFromZone(e,t,s,o){return xA(e,this.getters.getRangeFromZone(t,s),o,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){const s=this.getters.getRangeFromZone(e,t.range.zone),o=t.filters.map(s=>{const o=this.getters.getRangeFromZone(e,s.rangeWithHeaders.zone);return xA(s.id,o,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:s,filters:o,config:ae(t.config),type:t.type}}copyDynamicTableForSheet(e,t){const s=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:s,config:ae(t.config),type:"dynamic"}}applyRangeChangeOnTable(e,t,s){const o=s(t.range);let i;switch(o.changeType){case"REMOVE":return void this.history.update("tables",e,t.id,void 0);case"NONE":return;default:i=o.range}if("dynamic"===t.type){const s=this.updateDynamicTable(t,i);return void this.history.update("tables",e,t.id,s)}const n=[];for(const e of t.filters){const o=s(e.rangeWithHeaders);switch(o.changeType){case"REMOVE":continue;case"NONE":n.push(e);break;default:const s=o.range,i=xA(e.id,s,t.config,this.getters.getRangeFromZone);n.push(i)}}const r=i.zone;if(n.length<Ut(r).numberOfCols){for(let s=r.left;s<=r.right;s++)if(!n.find(e=>e.col===s)){const o=this.consumeNextId(),i={...r,left:s,right:s};n.push(this.createFilterFromZone(o,e,i,t.config))}n.sort((e,t)=>e.col-t.col)}const a=this.createStaticTable(t.id,t.type,i,t.config,n);this.history.update("tables",e,t.id,a)}consumeNextId(){const e=`${this.nextTableId}`;return this.history.update("nextTableId",this.nextTableId+1),e}import(e){for(const t of e.sheets)for(const e of t.tables||[]){const s=this.consumeNextId(),o=e.config||hE,i=this.getters.getRangeFromSheetXC(t.id,e.range),n=e.type||"static",r="dynamic"===n?this.createDynamicTable(s,i,o):this.createStaticTable(s,n,i,o);this.history.update("tables",t.id,r.id,r)}}export(e){for(const t of e.sheets)for(const e of this.getCoreTables(t.id)){const s={range:Tt(e.range.zone),type:e.type};Me(e.config,hE)||(s.config=e.config),t.tables.push(s)}}exportForExcel(e){for(const t of e.sheets)for(const e of this.getCoreTables(t.id)){const s=Tt(e.range.zone);t.tables.push({range:s,filters:[],config:e.config})}}}).add("dataValidation",class extends XT{static getters=["cellHasListDataValidationIcon","getDataValidationRule","getDataValidationRules","getValidationRuleForCell"];rules={};adaptRanges(e,t){this.adaptDVRanges(t,e),this.adaptDVFormulas(e)}adaptDVFormulas(e){for(const t in this.rules){for(let s=this.rules[t].length-1;s>=0;s--){const o=this.rules[t][s];for(let i=0;i<o.criterion.values.length;i++){const n=this.getters.adaptFormulaStringDependencies(t,o.criterion.values[i],e);this.history.update("rules",t,s,"criterion","values",i,n)}}}}adaptDVRanges(e,t){for(let s=this.rules[e].length-1;s>=0;s--){const o=this.rules[e][s];for(let i=o.ranges.length-1;i>=0;i--){const n=t(o.ranges[i]);switch(n.changeType){case"REMOVE":if(1===o.ranges.length)this.removeDataValidationRule(e,o.id);else{const t=o.ranges.slice();t.splice(i,1),this.history.update("rules",e,s,"ranges",t)}break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("rules",e,s,"ranges",i,n.range)}}}}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)):"InvalidSheetId";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"}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("rules",e.sheetId,[]);break;case"DUPLICATE_SHEET":{const t=ae(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>Eb(e.sheetId,e.sheetIdTo,t))}));this.history.update("rules",e.sheetIdTo,t);break}case"DELETE_SHEET":{const 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":{const t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case"DELETE_CONTENT":{const t=ft(e.target),s=e.sheetId;for(const e of t)for(let t=e.top;t<=e.bottom;t++)for(let o=e.left;o<=e.right;o++){const e=this.getValidationRuleForCell({sheetId:s,col:o,row:t});if(e&&("isBoolean"===e.criterion.type||"isValueInList"===e.criterion.type&&!this.getters.getCell({sheetId:s,col:o,row:t})?.content)){const e=this.rules[s],i=[this.getters.getRangeFromSheetXC(s,mt(o,t))],n=this.removeRangesFromRules(s,i,e);this.history.update("rules",s,n)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:s}){if(this.rules[e])for(const o of this.rules[e])for(const e of o.ranges)if(kt(t,s,e.zone))return o}cellHasListDataValidationIcon(e){const t=this.getValidationRuleForCell(e);return!!t&&!("isValueInList"!==t.criterion.type&&"isValueInRange"!==t.criterion.type||"arrow"!==t.criterion.displayStyle&&"chip"!==t.criterion.displayStyle)}addDataValidationRule(e,t){const s=this.rules[e];"isBoolean"===t.criterion.type?this.setCenterStyleToBooleanCells(t):"isValueInList"===t.criterion.type&&(t.criterion.values=Array.from(new Set(t.criterion.values)));const o=this.removeRangesFromRules(e,t.ranges,s,t.id),i=o.findIndex(e=>e.id===t.id);-1!==i?(o[i]=t,this.history.update("rules",e,o)):this.history.update("rules",e,[...o,t])}removeRangesFromRules(e,t,s,o){s=ae(s);for(const e of s)e.id!==o&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return s.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){const s=this.rules[e].filter(e=>e.id!==t);this.history.update("rules",e,s)}setCenterStyleToBooleanCells(e){for(const t of xb(e.ranges)){const e=this.getters.getCell(t),s={...e?.style,align:e?.style?.align??"center",verticalAlign:e?.style?.verticalAlign??"middle"};this.dispatch("UPDATE_CELL",{...t,style:s})}}checkEmptyRange(e){return e.ranges.length?"Success":"EmptyRange"}import(e){for(const t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(const 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(const t of e.sheets){t.dataValidationRules=[];for(const 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(const t of e.sheets){t.dataValidationRules=[];for(const e of this.rules[t.id]){const s={...ae(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};"isValueInRange"===e.criterion.type&&(s.criterion.values=e.criterion.values.map(e=>{const s=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(s,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(s)}}}checkCriterionTypeIsValid(e){return QT.contains(e.rule.criterion.type)?"Success":"UnknownDataValidationCriterionType"}checkCriterionHasValidNumberOfValues(e){const t=e.rule.criterion,s=QT.get(t.type).numberOfValues(t);return void 0!==s&&t.values.length!==s?"InvalidNumberOfCriterionValues":"Success"}checkCriterionValuesAreValid(e){const t=e.rule.criterion,s=QT.get(t.type);return t.values.some(e=>"onlyFormulas"===s.allowedValues&&!e.startsWith("=")||(e.startsWith("=")?"onlyLiterals"===s.allowedValues||sE(e).isBadExpression:!s.isCriterionValueValid(e)))?"InvalidDataValidationCriterionValue":"Success"}checkValidRange(e){const t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),s=t.map(t=>this.getters.getRangeString(t,e.sheetId));return s.some(e=>!this.getters.isRangeValid(e))?"InvalidRange":"Success"}}).add("cell",class extends XT{static getters=["zoneToXC","getCells","getTranslatedCellFormula","getCellStyle","getCellById","getFormulaString","getFormulaMovedInSheet"];nextId=1;cells={};adaptRanges(e,t,s){for(const o of Object.keys(this.cells))for(const i of Object.values(this.cells[o]||{}))if(i.isFormula)for(const n of i.compiledFormula.dependencies)if(n.sheetId===t||n.invalidSheetName===s.old){const t=e(n);"NONE"!==t.changeType&&this.history.update("cells",o,i.id,"compiledFormula","dependencies",i.compiledFormula.dependencies.indexOf(n),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&&void 0!==e.format&&this.setFormatter(e.sheetId,e.target,e.format);break;case"CLEAR_FORMATTING":this.clearFormatting(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?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(const s of ft(t))for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++){const s=this.getters.getCell({sheetId:e,col:t,row:o});(s?.isFormula||s?.content)&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:o})}}setFormatter(e,t,s){for(const o of ft(t))for(let t=o.top;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++)this.dispatch("UPDATE_CELL",{sheetId:e,col:i,row:t,format:s})}clearFormatting(e,t){for(const s of ft(t))for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,style:null,format:""})}clearCells(e,t){for(const s of t)for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,content:"",style:null,format:""})}handleAddColumnsRows(e,t){let s,o;"before"===e.position?(s=ge(e.base,e.base+e.quantity),o=e.base+e.quantity):(s=ge(e.base+1,e.base+e.quantity+1),o=e.base),t(e.sheetId,o,s)}import(e){for(const t of e.sheets){const s=t.id,o=new YT;for(const e in t.cells)if(t.cells[e]){const{col:s,row:i}=pt(e),n={sheetId:t.id,col:s,row:i};o.set(n,{content:t.cells[e]})}for(const[e,s]of[["style",t.styles],["format",t.formats]])for(const[i,n]of cb(t.id,s)){const t=o.get(i);t?t[e]=n:o.set(i,{[e]:n})}for(const i of o.keysForSheet(s)){const s=o.get(i);if(s?.content||s?.format||s?.style){const o=this.importCell(t.id,s?.content,s?.style?e.styles[s?.style]:void 0,s?.format?e.formats[s?.format]:void 0);this.history.update("cells",t.id,o.id,o),this.dispatch("UPDATE_CELL_POSITION",{cellId:o.id,...i})}}}}export(e){const t={},s={};for(const o of e.sheets){const e=[],i=[],n={},r=Object.keys(this.cells[o.id]||{}).map(e=>this.getters.getCellPosition(e)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(const o of r){const r=this.getters.getCell(o),a=mt(o.col,o.row),l=this.removeDefaultStyleValues(r.style);if(Object.keys(l).length){const s=ab(l,t);e[s]??=[],e[s].push(o)}if(r.format){const e=ab(r.format,s);i[e]??=[],i[e].push(o)}r.content&&(n[a]=r.content)}o.styles=lb(e),o.formats=lb(i),o.cells=n}e.styles=t,e.formats=s}importCell(e,t,s,o){const i=this.getNextUid();return this.createCell(i,t||"",o,s,e)}exportForExcel(e){this.export(e);const t=[];for(const s in e.formats||[])Hn(e.formats[s])||(t.push(Number(s)),delete e.formats[s]);if(t.length)for(const s of e.sheets)for(const e in s.formats){const o=s.formats[e];o&&t.includes(o)&&delete s.formats[e]}}removeDefaultStyleValues(e){const t={...e};for(const e in P)t[e]===P[e]&&delete t[e];return t}getCells(e){return this.cells[e]||{}}getCellById(e){const t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,s,o=!1){if(!s.length)return _e(t.map(e=>e.value));let i=0;return _e(t.map(t=>{if("REFERENCE"===t.type){const t=s[i++];return this.getters.getRangeString(t,e,{useBoundedReference:o})}return t.value}))}getTranslatedCellFormula(e,t,s,o){const i=this.getters.createAdaptedRanges(oE(o).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),t,s,e);return this.getFormulaString(e,o,i)}getFormulaMovedInSheet(e,t,s){const o=oE(s).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),i=this.getters.removeRangesSheetPrefix(t,o);return this.getFormulaString(t,s,i)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,s=[{colFixed:!1,rowFixed:!1}]){const o=mt((t=this.getters.expandZone(e,t)).left,t.top,s[0]),i=mt(t.right,t.bottom,s.length>1?s[1]:s[0]),n=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),r=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=n.col===r.col&&n.row===r.row;return o===i||a?o:o+":"+i}setStyle(e,t,s){for(const o of ft(t))for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++){const o=this.getters.getCell({sheetId:e,col:t,row:i});this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,style:s?{...o?.style,...s}:void 0})}}copyColumnStyle(e,t,s){for(let o=0;o<this.getters.getNumberRows(e);o++){const i=this.getFormat(e,t,o);if(i.style||i.format)for(const t of s)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,...i})}}copyRowStyle(e,t,s){for(let o=0;o<this.getters.getNumberCols(e);o++){const i=this.getFormat(e,o,t);if(i.style||i.format)for(const t of s)this.dispatch("UPDATE_CELL",{sheetId:e,col:o,row:t,...i})}}getFormat(e,t,s){const o={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:s}),n=this.getters.getCell(i);return n&&(n.style&&(o.style=n.style),n.format&&(o.format=n.format)),o}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,s,o){const i=this.getters.getCell({sheetId:e,col:t,row:s}),n="content"in o||"formula"in o,r=n?Ge(o?.content):i?.content||"";let a;a=void 0!==o.style?o.style||void 0:i?i.style:void 0;const l="format"in o?o.format:i&&i.format;if((n&&!r&&!o.formula||!n&&(!i||""===i.content))&&!a&&!l)return void(i&&(this.history.update("cells",e,i.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:s,sheetId:e})));const c=i?.id||this.getNextUid(),h=this.createCell(c,r,l,a,e);this.history.update("cells",e,h.id,h),this.dispatch("UPDATE_CELL_POSITION",{cellId:h.id,col:t,row:s,sheetId:e})}createCell(e,t,s,o,i){return t.startsWith("=")?this.createFormulaCell(e,t,s,o,i):this.createLiteralCell(e,t,s,o)}createLiteralCell(e,t,s,o){const i=this.getters.getLocale(),n=Xv(t,i);return zn(s=s||("number"==typeof n?Tn(t,i)||An(t):void 0))||t.startsWith("'")||mo(t)||(t=Eo(n)),{id:e,content:t,style:o,format:s,isFormula:!1,parsedValue:n}}createFormulaCell(e,t,s,o,i){const n=sE(t);return n.dependencies.length?this.createFormulaCellWithDependencies(e,n,s,o,i):{id:e,content:t,style:o,format:s,isFormula:!0,compiledFormula:{...n,dependencies:[]}}}createFormulaCellWithDependencies(e,t,s,o,i){const n=[];for(const e of t.dependencies)n.push(this.getters.getRangeFromSheetXC(i,e));return new KT(e,t,s,o,n,i,this.getters.getRangeString)}checkCellOutOfSheet(e){const{sheetId:t,col:s,row:o}=e;if(!this.getters.tryGetSheet(t))return"InvalidSheetId";return kt(s,o,this.getters.getSheetZone(t))?"Success":"TargetOutOfSheet"}checkUselessClearCell(e){const t=this.getters.getCell(e);return t&&(t.content||t.style||t.format)?"Success":"NoChanges"}checkUselessUpdateCell(e){const t=this.getters.getCell(e),s="style"in e,o="format"in e;return("content"in e||"formula"in e)&&t?.content!==e.content||s&&!Me(t?.style,e.style)||o&&t?.format!==e.format?"Success":"NoChanges"}}).add("merge",class extends XT{static getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge","getSelectionRangeString","isMainCellPosition"];nextId=1;merges={};mergeCellMap={};allowDispatch(e){const t="force"in e&&!!e.force;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":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;for(const s of Object.values(t).filter(Te))this.addMerge(e.sheetIdTo,s.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(e.sheetId,t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(Te)}getMerge({sheetId:e,col:t,row:s}){const o=this.mergeCellMap[e],i=o?t in o&&o[t]?.[s]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){const s=this.mergeCellMap[e];if(!s)return[];const o=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){const t=s[e]?.[i];t&&o.add(t)}return Array.from(o).map(t=>this.getMergeById(e,t)).filter(Te)}getSelectionRangeString(e,t){const s=this.getters.expandZone(e.sheetId,e.zone),o=bb({...e,zone:{...s,bottom:yb(e)?void 0:s.bottom,right:Ib(e)?void 0:s.right}},this.getters.getSheetSize),i=this.getters.getRangeString(o,t);if(this.isSingleCellOrMerge(e.sheetId,e.zone)){const{sheetName:e,xc:t}=tr(i);return sr(e,t.split(":")[0])}return i}doesIntersectMerge(e,t){for(const s of this.getMerges(e))if(Lt(t,s))return!0;return!1}doesColumnsHaveCommonMerges(e,t,s){const o=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(o.id,t,i,s,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,s){const o=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(o.id,i,t,i,s))return!0;return!1}expandZone(e,t){const{left:s,right:o,top:i,bottom:n}=t;let r={left:s,right:o,top:i,bottom:n};for(const t in this.merges[e]){const s=this.getMergeById(e,parseInt(t));s&&Lt(s,r)&&(r=Ft(s,r))}return Mt(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,s,o,i){const n=this.getMerge({sheetId:e,col:t,row:s}),r=this.getMerge({sheetId:e,col:o,row:i});return!(!n||!r)&&Mt(n,r)}isInMerge({sheetId:e,col:t,row:s}){const o=this.mergeCellMap[e];return!!o&&(t in o&&Boolean(o[t]?.[s]))}getMainCellPosition(e){const t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){const s=this.getters.getHiddenColsGroups(e),o=this.getters.getHiddenRowsGroups(e);for(const e of s)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(const e of o)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const s=this.getMerge({sheetId:e,col:t.left,row:t.top});if(s)return Mt(t,s);const{numberOfCols:o,numberOfRows:i}=Ut(t);return 1===o&&1===i}isMainCellPosition(e){return Me(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:s,right:o,top:i,bottom:n}=t;o=ue(o,0,this.getters.getNumberCols(e)-1),n=ue(n,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=n;t++)for(let n=s;n<=o;n++)if(n!==s||t!==i){const s=this.getters.getCell({sheetId:e,col:n,row:t});if(s&&""!==s.content)return!0}return!1}getMergeById(e,t){const s=this.merges[e]?.[t];return void 0!==s?aA(t,s):void 0}checkDestructiveMerge({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return"Success";return t.some(t=>this.isMergeDestructive(e,t))?"MergeIsDestructive":"Success"}checkOverlap({target:e}){for(const t of e)for(const s of e)if(t!==s&&Lt(t,s))return"MergeOverlap";return"Success"}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return"Success";const{xSplit:s,ySplit:o}=this.getters.getPaneDivisions(e);return Jt(t,s,o)?"FrozenPaneOverlap":"Success"}checkMergedContentUpdate(e){const{col:t,row:s,content:o}=e;if(void 0===o)return"Success";const{col:i,row:n}=this.getMainCellPosition(e);return i===t&&n===s?"Success":"CellIsMerged"}checkMergeExists(e){const{sheetId:t,target:s}=e;for(const e of s){const{left:s,top:o}=e,i=this.getMerge({sheetId:t,col:s,row:o});if(void 0===i||!Mt(e,i))return"InvalidTarget"}return"Success"}addMerge(e,t){let{left:s,right:o,top:i,bottom:n}=t;o=ue(o,0,this.getters.getNumberCols(e)-1),n=ue(n,0,this.getters.getNumberRows(e)-1);if(mt(s,i)===mt(o,n))return;const r=this.getters.getCell({sheetId:e,col:s,row:i}),a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,Tt({left:s,top:i,right:o,bottom:n})));const l=new Set;for(let t=i;t<=n;t++)for(let n=s;n<=o;n++){n===s&&t===i||this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,style:r?r.style:null,content:""});const o=this.getMerge({sheetId:e,col:n,row:t});o&&l.add(o.id),this.history.update("mergeCellMap",e,n,t,a)}for(const t of l){const{top:s,bottom:o,left:i,right:n}=this.getMergeById(e,t);for(let t=s;t<=o;t++)for(let s=i;s<=n;s++){const o={sheetId:e,col:s,row:t},i=this.getMerge(o);i&&i.id===a||(this.history.update("mergeCellMap",e,s,t,void 0),this.dispatch("CLEAR_CELL",o))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:s,top:o,bottom:i,right:n}=t,r=this.getMerge({sheetId:e,col:s,row:o});if(void 0!==r&&Mt(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=o;t<=i;t++)for(let o=s;o<=n;o++)this.history.update("mergeCellMap",e,o,t,void 0)}}applyRangeChangeOnSheet(e,t){const s=Object.entries(this.merges[e]||{});for(const[o,i]of s)if(i){const s=i.zone,n=t(i);switch(n.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,s);break;default:const{numberOfCols:t,numberOfRows:i}=Ut(n.range.zone);1===t&&1===i?this.removeMerge(e,s):this.history.update("merges",e,parseInt(o,10),n.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:s,row:o}of Bt(t))this.history.update("mergeCellMap",e,s,o,t.id)}import(e){const t=e.sheets||[];for(const 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(const s of t)this.addMerge(e,wt(s))}export(e){for(const t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...rA(e))}}exportForExcel(e){this.export(e)}}).add("headerSize",class extends XT{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,ae(this.sizes[e.sheetId]));break;case"DELETE_SHEET":const t={...this.sizes};delete t[e.sheetId],this.history.update("sizes",t);break;case"REMOVE_COLUMNS_ROWS":{const t=qe(this.sizes[e.sheetId][e.dimension],e.elements);this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=this.sizes[e.sheetId][e.dimension],s=Pe(e.position,e.base),o=t[e.base],i=Ze(t,Array(e.quantity).fill(o),s);this.history.update("sizes",e.sheetId,e.dimension,i);break}case"RESIZE_COLUMNS_ROWS":if("ROW"===e.dimension)for(const t of e.elements)this.history.update("sizes",e.sheetId,e.dimension,t,e.size||void 0);else for(const t of e.elements)this.history.update("sizes",e.sheetId,e.dimension,t,e.size||void 0)}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){const s=this.sizes[e]?.ROW[t];return s?Math.round(s):void 0}import(e){for(const t of e.sheets){const e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(const[s,o]of Object.entries(t.rows))o.size&&(e.ROW[s]=o.size);for(const[s,o]of Object.entries(t.cols))o.size&&(e.COL[s]=o.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(const s of e.sheets){void 0===s.rows&&(s.rows={});for(const e of ge(0,this.getters.getNumberRows(s.id)))(t||this.sizes[s.id].ROW[e])&&(s.rows[e]={...s.rows[e],size:this.getUserRowSize(s.id,e)??_});void 0===s.cols&&(s.cols={});for(const e of ge(0,this.getters.getNumberCols(s.id)))(t||this.sizes[s.id].COL[e])&&(s.cols[e]={...s.cols[e],size:this.getColSize(s.id,e)})}}}).add("borders",class extends XT{static getters=["getCellBorder","getBorders","getBordersColors","getCellBordersInZone"];borders={};allowDispatch(e){return"SET_BORDER"===e.type?this.checkValidations(e,this.checkBordersUnchanged,this.ensureHasBorder):"Success"}handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":this.history.update("borders",e.sheetIdTo,ae(this.borders[e.sheetId]));break;case"DELETE_SHEET":const t={...this.borders};delete t[e.sheetId],this.history.update("borders",t);break;case"SET_BORDER":e.border&&this.addBorders(e.sheetId,[Zt(e)],e.border);break;case"SET_BORDERS_ON_TARGET":for(const t of e.target)for(let s=t.left;s<=t.right;s++)for(let o=t.top;o<=t.bottom;o++)this.addBorder(e.sheetId,{left:s,right:s,top:o,bottom:o},e.border&&Object.keys(e.border).length?e.border:void 0);break;case"SET_ZONE_BORDERS":const s=e.target.map(t=>this.getters.expandZone(e.sheetId,t));"clear"===e.border.position?this.clearBorders(e.sheetId,s):this.addBorders(e.sheetId,s,this.borderDataToNewBorderData(e.border));break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target)}}beforeHandle(e){"REMOVE_COLUMNS_ROWS"===e.type&&("ROW"===e.dimension?this.onRowRemove(e.sheetId,e.elements):this.onColRemove(e.sheetId,e.elements))}adaptRanges(e,t){const s=[];for(const o of this.borders[t]??[]){const i=e(this.getters.getRangeFromZone(t,o.zone));switch(i.changeType){case"RESIZE":case"CHANGE":case"MOVE":s.push({...o,zone:i.range.unboundedZone});break;case"NONE":s.push(o)}}this.history.update("borders",t,s.filter(e=>!this.borderIsClear(e)))}onRowRemove(e,t){const s=new Set(t),o=[];for(const t of this.borders[e]??[]){let e=t;s.has(t.zone.top)&&(e=ae(t),e.style.top=t.style.horizontal),void 0!==t.zone.bottom&&s.has(t.zone.bottom)&&(e=e===t?ae(t):e,e.style.bottom=t.style.horizontal),o.push(e)}this.history.update("borders",e,o)}onColRemove(e,t){const s=new Set(t),o=[];for(const t of this.borders[e]??[]){let e=t;s.has(t.zone.left)&&(e=ae(t),e.style.left=t.style.vertical),void 0!==t.zone.right&&s.has(t.zone.right)&&(e=e===t?ae(t):e,e.style.right=t.style.vertical),o.push(e)}this.history.update("borders",e,o.filter(e=>!this.borderIsClear(e)))}getCellBorder(e){return this.getZoneExternalBorders(e.sheetId,Zt(e))}getZoneExternalBorders(e,t){const s={};for(const o of this.borders[e]??[])Lt(o.zone,t)&&(s.right=(t.right===o.zone.right?o.style.right:o.style.vertical)??s.right,s.left=(t.left===o.zone.left?o.style.left:o.style.vertical)??s.left,s.bottom=(t.bottom===o.zone.bottom?o.style.bottom:o.style.horizontal)??s.bottom,s.top=(t.top===o.zone.top?o.style.top:o.style.horizontal)??s.top);return s}getCellBordersInZone(e,t){const s=new YT;for(const o of this.borders[e]??[]){const{zone:i,style:n}=o,r=Pt(i,t);if(r)for(let t=r.left;t<=r.right;t++)for(let o=r.top;o<=r.bottom;o++){const r=s.get({sheetId:e,col:t,row:o})??{};r.right=(t===i.right?n.right:n.vertical)??r.right,r.left=(t===i.left?n.left:n.vertical)??r.left,r.bottom=(o===i.bottom?n.bottom:n.horizontal)??r.bottom,r.top=(o===i.top?n.top:n.horizontal)??r.top,s.set({sheetId:e,col:t,row:o},r)}}return s}getBordersColors(e){const t=new Set;for(const s of this.borders[e]??[])for(const e of Object.values(s.style))e?.color&&t.add(e.color);return[...t]}getBorders(e,t){const s=[];for(const o of this.borders[e]??[]){const e=Pt(o.zone,t);e&&s.push(this.computeBorderFromZone(e,o))}return s}computeBorderFromZone(e,t){const s=t.style,o=t.zone,i=e.top===o.top,n=e.bottom===o.bottom,r=e.left===o.left,a=e.right===o.right;return{zone:e,style:{top:i?s.top:s.horizontal,bottom:n?s.bottom:s.horizontal,left:r?s.left:s.vertical,right:a?s.right:s.vertical,vertical:s.vertical,horizontal:s.horizontal}}}borderIsClear(e){const t=e.style;if(t.left||t.right||t.bottom||t.top)return!1;const s=e.zone;return(!(void 0===s.bottom||s.top<s.bottom)||!t.horizontal)&&(!(void 0===s.right||s.left<s.right)||!t.vertical)}clearBorders(e,t){for(const s of t)this.removeAndClearAdjacent(e,s)}removeAndClearAdjacent(e,t){const s=[];for(const o of this.borders[e]??[])for(const e of ft([o.zone],[t]))for(const i of ts(e,t)){const e=this.computeBorderFromZone(i,o),n=Nt(i,t);switch(n?.position){case"left":e.style.left=void 0;break;case"right":e.style.right=void 0;break;case"top":e.style.top=void 0;break;case"bottom":e.style.bottom=void 0}s.push(e)}this.history.update("borders",e,s)}addBorders(e,t,s){for(const o of t)this.addBorder(e,o,s)}addBorder(e,t,s,o=!1){const i=[],n=s?{zone:t,style:s}:void 0,r={left:o||!!s?.left,right:o||!!s?.right,top:o||!!s?.top,bottom:o||!!s?.bottom};let a=[t];for(const s of this.borders[e]??[]){const e=Pt(s.zone,t);if(!e){const e=Nt(s.zone,t);if(e&&r[e.position])for(const e of ts(s.zone,t)){const o=this.computeBorderFromZone(e,s),n=Nt(e,t);switch(n?.position){case"left":o.style.left=void 0;break;case"right":o.style.right=void 0;break;case"top":o.style.top=void 0;break;case"bottom":o.style.bottom=void 0}i.push(o)}else i.push(s);continue}if(n){let t=this.computeBorderFromZone(e,n).style;o||(t={...this.computeBorderFromZone(e,s).style,...Ve(t)}),i.push({zone:e,style:t})}a=ft(a,[e]);for(const t of ft([s.zone],[e]))i.push(this.computeBorderFromZone(t,s))}n&&i.push(...a.map(e=>this.computeBorderFromZone(e,n))),this.history.update("borders",e,i.filter(e=>!this.borderIsClear(e)))}borderDataToNewBorderData(e){const t={},s={color:e.color??"#000000",style:e.style??"thin"};return["all","external","top"].includes(e.position)&&(t.top={...s}),["all","external","bottom"].includes(e.position)&&(t.bottom={...s}),["all","external","left"].includes(e.position)&&(t.left={...s}),["all","external","right"].includes(e.position)&&(t.right={...s}),["all","hv","v"].includes(e.position)&&(t.vertical={...s}),["all","hv","h"].includes(e.position)&&(t.horizontal={...s}),t}checkBordersUnchanged(e){const t=this.getCellBorder(e),s=!(e.border?.bottom||e.border?.left||e.border?.right||e.border?.top);return!t&&s||Me(t,e.border)?"NoChanges":"Success"}ensureHasBorder(e){return e.border?"Success":"NoChanges"}addBordersToMerge(e,t){const s={...this.getZoneExternalBorders(e,t),...Ve(this.getCellBorder({sheetId:e,col:t.left,row:t.top}))};this.addBorder(e,t,s,!0)}import(e){if(Object.keys(e.borders||{}).length)for(const t of e.sheets)for(const s in t.borders){const o=t.borders[s];this.addBorder(t.id,wt(s),e.borders[o])}for(const t of e.sheets)if(t.merges)for(const e of t.merges)this.addBordersToMerge(t.id,wt(e))}export(e){const t={};for(const s of e.sheets){s.borders={};for(const e of this.borders[s.id]??[])s.borders[Tt(e.zone)]=ab(e.style,t)}e.borders=t}exportForExcel(e){this.export(e)}}).add("conditional formatting",class extends XT{static getters=["getConditionalFormats","getRulesSelection","getRulesByCell","getAdaptedCfRanges"];cfRules={};adaptCFFormulas(e){for(const t in this.cfRules)for(const s of this.cfRules[t])if("DataBarRule"===s.rule.type&&s.rule.rangeValues){const o=e(s.rule.rangeValues);switch(o.changeType){case"REMOVE":this.history.update("cfRules",t,this.cfRules[t].indexOf(s),"rule","rangeValues",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",t,this.cfRules[t].indexOf(s),"rule","rangeValues",o.range)}}else if("CellIsRule"===s.rule.type)for(let o=0;o<s.rule.values.length;o++)this.history.update("cfRules",t,this.cfRules[t].indexOf(s),"rule","values",o,this.getters.adaptFormulaStringDependencies(t,s.rule.values[o],e));else if("IconSetRule"===s.rule.type)for(const o of["lowerInflectionPoint","upperInflectionPoint"])"formula"===s.rule[o].type&&this.history.update("cfRules",t,this.cfRules[t].indexOf(s),"rule",o,"value",this.getters.adaptFormulaStringDependencies(t,s.rule[o].value,e));else if("ColorScaleRule"===s.rule.type)for(const o of["minimum","maximum","midpoint"]){const i=s.rule[o];"formula"===i?.type&&i?.value&&this.history.update("cfRules",t,this.cfRules[t].indexOf(s),"rule",o,"value",this.getters.adaptFormulaStringDependencies(t,i.value,e))}}adaptCFRanges(e,t){for(const s of this.cfRules[e])for(const o of s.ranges){const i=t(o);switch(i.changeType){case"REMOVE":const t=s.ranges.slice();t.splice(s.ranges.indexOf(o),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(s),"ranges",t):this.removeConditionalFormatting(s.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(s),"ranges",s.ranges.indexOf(o),i.range)}}}adaptRanges(e,t){const s=t?[t]:Object.keys(this.cfRules);for(const t of s)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(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const s={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(s,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)}}import(e){for(const t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(const 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(const 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){const s=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{s.add(e)})}),Array.from(s)}getRulesByZone(e,t){const s=new Set;for(let o=t.top;o<=t.bottom;o++)for(let i=t.left;i<=t.right;i++){this.getRulesByCell(e,i,o).forEach(e=>{s.add(e.id)})}return s}getRulesByCell(e,t,s){const o=[];for(const i of this.cfRules[e])for(const e of i.ranges)kt(t,s,e.zone)&&o.push(i);return new Set(o.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,s,o){if(0===s.length&&0===o.length)return;const i=this.getters.getConditionalFormats(e),n=i.findIndex(e=>e.id===t.id);let r=[];n>-1&&(r=i[n].ranges.map(It));const a=ft(r,o);return ft([...s,...a],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:s}={useBoundedReference:!1}){const o=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:s}));return"DataBarRule"!==t.rule.type?{...t,rule:{...t.rule},ranges:o}:{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:s})},ranges:o}}mapToConditionalFormatInternal(e,t){const s=t.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t));return"DataBarRule"!==t.rule.type?{...t,rule:{...t.rule},ranges:s}:{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:s}}addConditionalFormatting(e,t){const s=this.cfRules[t].slice(),o=s.findIndex(t=>t.id===e.id),i=this.mapToConditionalFormatInternal(t,e);o>-1?s.splice(o,1,i):s.push(i),this.history.update("cfRules",t,s)}checkValidPriorityChange(e,t,s){if(!this.cfRules[s])return"InvalidSheetId";const o=this.cfRules[s].findIndex(t=>t.id===e);if(-1===o)return"InvalidConditionalFormatId";const i=o-t;return i<0||i>=this.cfRules[s].length?"InvalidConditionalFormatId":"Success"}checkEmptyRange(e){return e.ranges.length?"Success":"EmptyRange"}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues);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)))}return"Success"}checkCFHasChanged(e){const t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))}),s=this.cfRules[e.sheetId]?.find(t=>t.id===e.cf.id);return s&&Me(t,s)?"NoChanges":"Success"}checkOperatorArgsNumber(e){const t=QT.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(void 0===t||t>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");const s=[],o=e=>void 0===e||""===e;return t>=1&&o(e.values[0])&&s.push("FirstArgMissing"),t>=2&&o(e.values[1])&&s.push("SecondArgMissing"),s.length?s:"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("formula"!==e.type)return"Success";if(sE(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){const t=e.lowerInflectionPoint.value,s=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(s)?"LowerBiggerThanUpper":"Success"}checkMinBiggerThanMax(e){const t=e.minimum.value,s=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&nA(t)>=nA(s)?"MinBiggerThanMax":"Success"}checkMidBiggerThanMax(e){const t=e.midpoint?.value,s=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&nA(t)>=nA(s)?"MidBiggerThanMax":"Success"}checkMinBiggerThanMid(e){const t=e.minimum.value,s=e.midpoint?.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&nA(t)>=nA(s)?"MinBiggerThanMid":"Success"}checkCFValues(e){for(const t of e.values){if(!t.startsWith("="))continue;if(sE(t||"").isBadExpression)return"ValueCellIsInvalidFormula"}return"Success"}removeConditionalFormatting(e,t){const s=this.cfRules[t].findIndex(t=>t.id===e);if(-1!==s){const e=this.cfRules[t].slice();e.splice(s,1),this.history.update("cfRules",t,e)}}changeCFPriority(e,t,s){const o=this.cfRules[s].findIndex(t=>t.id===e),i=this.cfRules[s][o],n=o-t,r=[...this.cfRules[s]];r.splice(o,1),r.splice(n,0,i),this.history.update("cfRules",s,r)}}).add("figures",class extends XT{static getters=["getFigures","getFigure","getFigureSheetId"];figures={};insertionOrders=[];adaptRanges(e,t){for(const s of this.getFigures(t)){const o=e(this.getters.getRangeFromZone(t,{left:s.col,right:s.col,top:s.row,bottom:s.row}));if("MOVE"===o.changeType)this.history.update("figures",t,s.id,"col",o.range.zone.right),this.history.update("figures",t,s.id,"row",o.range.zone.bottom);else if("REMOVE"===o.changeType){const o=e(this.getters.getRangeFromZone(t,{left:0,right:s.col-1,top:0,bottom:s.row-1}));let{offset:i,col:n,row:r}=s;"NONE"!==o.changeType&&(n=o.range.zone.right+1,r=o.range.zone.bottom+1),({offset:i,col:n,row:r}=this.getPositionInSheet(t,{...s,col:n,row:r})),this.history.update("figures",t,s.id,"offset",i),this.history.update("figures",t,s.id,"col",n),this.history.update("figures",t,s.id,"row",r)}}}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){if("DELETE_SHEET"===e.type)this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch("DELETE_FIGURE",{figureId:t.id,sheetId:e.sheetId})})}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":const 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":"COL"===e.dimension?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break;case"DUPLICATE_SHEET":for(const t in this.figures[e.sheetId]){const s=this.figures[e.sheetId]?.[t];if(!s)continue;const o=t.split(z).pop(),i=`${e.sheetIdTo}${z}${o}`;this.dispatch("CREATE_FIGURE",{figureId:i,...s,size:{width:s.width,height:s.height},sheetId:e.sheetIdTo})}}}onColRemove(e){const t=this.getters.getNumberCols(e),s=new Array(t+1);s[t]=0;for(let o=t-1;o>=0;o--)s[o]=s[o+1]+this.getters.getColSize(e,o);for(const t of this.getFigures(e))if(t.offset.x+t.width>s[t.col]){let o=t.offset.x,i=t.col;for(o=Math.min(o,s[i]-t.width);o<0&&i>0;)i--,o=s[i]-t.width;o!==t.offset.x&&this.history.update("figures",e,t.id,"offset",{x:Math.max(o,0),y:t.offset.y}),i!==t.col&&this.history.update("figures",e,t.id,"col",i)}}onRowRemove(e){const t=this.getters.getNumberRows(e),s=new Array(t+1);s[t]=0;for(let o=t-1;o>=0;o--)s[o]=s[o+1]+(this.getters.getUserRowSize(e,o)??_);for(const t of this.getFigures(e))if(t.offset.y+t.height>s[t.row]){let o=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??_;t<o;t=this.getters.getUserRowSize(e,i)??_)i+=1,o-=t;for(o=Math.min(o,s[i]-t.height);o<0&&i>0;)i--,o=s[i]-t.height;o!==t.offset.y&&this.history.update("figures",e,t.id,"offset",{x:t.offset.x,y:Math.max(0,o)}),i!==t.row&&this.history.update("figures",e,t.id,"row",i)}else t.offset.y+t.height>s[0]&&this.history.update("figures",e,t.id,"offset",{x:t.offset.x,y:Math.max(s[0]-t.height,0)})}getPositionInSheet(e,t){const{numberOfRows:s,numberOfCols:o}=this.getters.getSheetSize(e);let i,n,r=0,a=0,{col:l,row:c}=t;const h={...t.offset};for(i=s;r<t.height&&i>0;i--)r+=this.getters.getUserRowSize(e,i-1)??_;for(c>i?(c=i,h.y=Math.max(r-t.height,0)):c===i&&(h.y=ue(h.y,0,Math.max(r-t.height,0))),n=o;a<t.width&&n>0;n--)a+=this.getters.getColSize(e,n-1);return l>n?(l=n,h.x=Math.max(a-t.width,0)):n===l&&(h.x=ue(h.x,0,Math.max(a-t.width,0))),{col:l,row:c,offset:h}}updateFigure(e){if(!("figureId"in e)||!("sheetId"in e))return;const{figureId:t,sheetId:s,...o}=e,i={...this.getFigure(s,t),...o};for(const[e,t]of Object.entries(o))switch(e){case"tag":case"offset":this.history.update("figures",s,i.id,e,t);break;case"col":case"row":case"width":case"height":void 0!==t&&this.history.update("figures",s,i.id,e,t)}}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 void 0===this.figures[e.sheetId]?.[e.figureId]?"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){const t=[];for(const s of this.insertionOrders){const o=this.figures[e]?.[s];o&&t.push(o)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>void 0!==this.figures[t]?.[e])}import(e){for(const t of e.sheets)for(const e of t.figures)this.addFigure(e,t.id)}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const s=void 0;t.figures.push({...e,data:s})}}exportForExcel(e){return this.export(e)}}).add("chart",class extends XT{static getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getFigureIdFromChartId","getContextCreationChart"];charts={};createChart=qy(this.getters);validateChartDefinition=e=>jy(this,e.definition);adaptRanges(e,t,s){for(const[o,i]of Object.entries(this.charts)){if(!i)continue;const n=i.chart.updateRanges(e,t,s);this.history.update("charts",o,n?{figureId:i.figureId,chart:n}:void 0)}}allowDispatch(e){switch(e.type){case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.checkFigureArguments,this.validateChartDefinition,this.checkChartDuplicate));case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists,this.checkChartChanged));case"DELETE_CHART":return this.checkChartExists(e);default:return"Success"}}handle(e){switch(e.type){case"CREATE_CHART":const{col:t,row:s,offset:o,size:i,sheetId:n,figureId:r}=e;this.getters.getFigure(n,r)||void 0===o||void 0===t||void 0===s||this.addFigure(r,n,t,s,o,i),this.addChart(e.figureId,e.chartId,e.definition);break;case"UPDATE_CHART":this.addChart(e.figureId,e.chartId,e.definition);break;case"DUPLICATE_SHEET":for(const t of this.getChartIds(e.sheetId)){const{chart:s,figureId:o}=this.charts[t]||{};if(!s||!o)continue;const i=this.getters.getFigure(e.sheetId,o);if(!i)continue;const n=o.split(z).pop(),r=`${e.sheetIdTo}${z}${n}`,a=t.split(z).pop(),l=`${e.sheetIdTo}${z}${a}`,c=s.duplicateInDuplicatedSheet(e.sheetIdTo);c&&this.dispatch("CREATE_CHART",{figureId:r,chartId:l,col:i.col,row:i.row,offset:i.offset,size:{width:i.width,height:i.height},definition:c.getDefinition(),sheetId:e.sheetIdTo})}break;case"DELETE_FIGURE":for(const t in this.charts)this.charts[t]?.figureId===e.figureId&&this.dispatch("DELETE_CHART",{chartId:t,sheetId:e.sheetId});break;case"DELETE_CHART":this.isChartDefined(e.chartId)&&this.history.update("charts",e.chartId,void 0);break;case"DELETE_SHEET":for(const t of this.getChartIds(e.sheetId))this.history.update("charts",t,void 0)}}getContextCreationChart(e){return this.charts[e]?.chart.getContextCreation()}getChart(e){return this.charts[e]?.chart}getFigureIdFromChartId(e){if(!this.charts[e])throw new Error(`Chart with id ${e} does not exist.`);return this.charts[e].figureId}getChartType(e){const t=this.charts[e]?.chart.type;if(!t)throw new Error("Chart not defined.");return t}isChartDefined(e){return e in this.charts&&void 0!==this.charts}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.chart.sheetId===e).map(([e])=>e)}getChartDefinition(e){const t=this.charts[e]?.chart.getDefinition();if(!t)throw new Error(`There is no chart with the given id: ${e}`);return t}import(e){for(const t of e.sheets)if(t.figures)for(const e of t.figures)if("chart"===e.tag){const s=e.data.chartId,o=this.createChart(e.id,e.data,t.id);this.charts[s]={chart:o,figureId:e.id}}else if("carousel"===e.tag)for(const s in e.data.chartDefinitions||{}){const o=e.data.chartDefinitions[s],i=this.createChart(e.id,o,t.id);this.charts[s]={chart:i,figureId:e.id}}}export(e){if(e.sheets)for(const t of e.sheets){const e=this.getters.getFigures(t.id),s=[];for(const t of e){const e=t,o=Object.keys(this.charts).find(e=>this.charts[e]?.figureId===t.id);if(e&&"chart"===e.tag&&o){const t=this.charts[o]?.chart.getDefinition();t&&(e.data={...t,chartId:o},s.push(e))}else if(e&&"carousel"===e.tag){const o=Object.keys(this.charts).filter(e=>this.charts[e]?.figureId===t.id),i={};for(const e of o)i[e]=this.charts[e]?.chart.getDefinition();e.data={chartDefinitions:i},s.push(e)}else s.push(e)}t.figures=s}}addFigure(e,t,s,o,i,n={width:536,height:335}){this.dispatch("CREATE_FIGURE",{sheetId:t,figureId:e,col:s,row:o,offset:i,size:n,tag:"chart"})}addChart(e,t,s){const o=this.getters.getFigureSheetId(e);if(o){const i=this.createChart(e,s,o);this.history.update("charts",t,{figureId:e,chart:i})}}checkChartDuplicate(e){return this.isChartDefined(e.chartId)?"DuplicatedChartId":"Success"}checkChartExists(e){return this.isChartDefined(e.chartId)?"Success":"ChartDoesNotExist"}checkChartChanged(e){return e.figureId!==this.charts[e.chartId]?.figureId?"Success":Me(this.getChartDefinition(e.chartId),e.definition)?"NoChanges":"Success"}checkFigureArguments(e){return this.getters.getFigure(e.sheetId,e.figureId)||void 0!==e.offset&&void 0!==e.col&&void 0!==e.row?"Success":"MissingFigureArguments"}}).add("carousel",class extends XT{static getters=["getCarousel","doesCarouselExist"];carousels={};allowDispatch(e){switch(e.type){case"CREATE_CAROUSEL":return this.getters.getFigure(e.sheetId,e.figureId)?"DuplicatedFigureId":"Success";case"UPDATE_CAROUSEL":return this.carousels[e.sheetId]?.[e.figureId]?"Success":"InvalidFigureId"}return"Success"}handle(e){switch(e.type){case"CREATE_CAROUSEL":this.getters.getFigure(e.sheetId,e.figureId)||this.dispatch("CREATE_FIGURE",{...e,tag:"carousel"}),this.history.update("carousels",e.sheetId,e.figureId,e.definition);break;case"UPDATE_CAROUSEL":this.removeDeletedCharts(e,this.getters.getCarousel(e.figureId).items),this.history.update("carousels",e.sheetId,e.figureId,e.definition);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const s of t)if("carousel"===s.tag){const t=s.id.split(z).pop(),o=`${e.sheetIdTo}${z}${t}`,i=this.getCarousel(s.id);if(i){const t={width:s.width,height:s.height};this.dispatch("CREATE_CAROUSEL",{sheetId:e.sheetIdTo,figureId:o,offset:s.offset,col:s.col,row:s.row,size:t,definition:{items:i.items.map(t=>{if("carouselDataView"===t.type)return{...t};const s=t.chartId.split(z).pop(),o=`${e.sheetIdTo}${z}${s}`;return{...t,chartId:o}})}})}}break}case"DELETE_FIGURE":this.history.update("carousels",e.sheetId,e.figureId,void 0);break;case"DELETE_SHEET":this.history.update("carousels",e.sheetId,void 0)}}doesCarouselExist(e){for(const t in this.carousels)if(this.carousels[t]?.[e])return!0;return!1}getCarousel(e){for(const t in this.carousels)if(this.carousels[t]?.[e])return this.carousels[t][e];throw new Error(`There is no carousel with the given figureId: ${e}`)}removeDeletedCharts(e,t){const s=new Set(e.definition.items.filter(e=>"chart"===e.type).map(e=>e.chartId));for(const o of t)"chart"!==o.type||s.has(o.chartId)||this.dispatch("DELETE_CHART",{chartId:o.chartId,sheetId:e.sheetId})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter(e=>"carousel"===e.tag);for(const s of e)this.history.update("carousels",t.id,s.id,{items:s.data.items,title:s.data.title})}}export(e){for(const t of e.sheets){const e=t.figures.filter(e=>"carousel"===e.tag);for(const s of e)this.carousels[t.id]?.[s.id]&&(s.data={...s.data,...this.carousels[t.id]?.[s.id]})}}}).add("image",class extends XT{static getters=["getImage","getImagePath","getImageSize"];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){return"CREATE_IMAGE"===e.type&&this.getters.getFigure(e.sheetId,e.figureId)?"InvalidFigureId":"Success"}handle(e){switch(e.type){case"CREATE_IMAGE":this.getters.getFigure(e.sheetId,e.figureId)||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":{const t=this.getters.getFigures(e.sheetId);for(const s of t)if("image"===s.tag){const t=s.id.split(z).pop(),o=`${e.sheetIdTo}${z}${t}`,i=this.getImage(s.id);if(i){const t={width:s.width,height:s.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:o,offset:s.offset,col:s.col,row:s.row,size:t,definition:ae(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)}}garbageCollectExternalResources(){const e=new Set(this.getAllImages().map(e=>e.path));for(const t of this.syncedImages)e.has(t)||this.fileStore?.delete(t)}getImage(e){for(const t of Object.values(this.images))if(t&&t[e])return t[e];throw new 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,s,o,i,n){this.dispatch("CREATE_FIGURE",{sheetId:t,figureId:e,col:s,row:o,offset:i,size:n,tag:"image"})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter(e=>"image"===e.tag);for(const s of e)this.history.update("images",t.id,s.id,s.data),this.syncedImages.add(s.data.path)}}export(e){for(const t of e.sheets){const e=t.figures.filter(e=>"image"===e.tag);for(const s of e)s.data=this.images[t.id]?.[s.id]}}exportForExcel(e){for(const t of e.sheets){t.images||(t.images=[]);const e=this.getters.getFigures(t.id),s=[];for(const t of e)if("image"===t?.tag){const e=this.getImage(t.id);e&&s.push({...t,data:ae(e)})}t.images=[...t.images,...s]}}getAllImages(){const e=[];for(const t in this.images)e.push(...Object.values(this.images[t]||{}).filter(Te));return e}}).add("pivot_core",class extends XT{static getters=["getPivotCoreDefinition","getPivotDisplayName","getPivotId","getPivotFormulaId","getPivotIds","getMeasureCompiledFormula","getPivotName","isExistingPivot"];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case"ADD_PIVOT":return this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid);case"UPDATE_PIVOT":return e.pivotId in this.pivots?Me(e.pivot,this.pivots[e.pivotId]?.definition)?"NoChanges":""===e.pivot.name?"EmptyName":this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid):"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":case"DUPLICATE_PIVOT":if(!(e.pivotId in this.pivots))return"PivotIdNotFound"}return"Success"}handle(e){switch(e.type){case"ADD_PIVOT":{const{pivotId:t,pivot:s}=e;this.addPivot(t,s);break}case"INSERT_PIVOT":{const{sheetId:t,col:s,row:o,pivotId:i,table:n}=e,r={sheetId:t,col:s,row:o},{cols:a,rows:l,measures:c,fieldsType:h}=n,d=new yA(a,l,c,h||{}),u=this.getPivotFormulaId(i);this.insertPivot(r,u,d);break}case"RENAME_PIVOT":this.history.update("pivots",e.pivotId,"definition","name",e.name);break;case"REMOVE_PIVOT":{const t={...this.pivots};delete t[e.pivotId];const s=this.getPivotFormulaId(e.pivotId);this.history.update("formulaIds",s,void 0),this.history.update("pivots",t);break}case"DUPLICATE_PIVOT":{const{pivotId:t,newPivotId:s}=e,o=ae(this.getPivotCore(t).definition);o.name=e.duplicatedPivotName??o.name+" (copy)",this.addPivot(s,o);break}case"UPDATE_PIVOT":this.history.update("pivots",e.pivotId,"definition",ae(e.pivot)),this.compileCalculatedMeasures(e.pivot.measures)}}adaptRanges(e){for(const t in this.compiledMeasureFormulas)for(const s in this.compiledMeasureFormulas[t]){const o=this.compiledMeasureFormulas[t][s],i=[];for(const t of o.dependencies){const s=e(t);"NONE"===s.changeType?i.push(t):i.push(s.range)}const n=this.getters.getFormulaString(t,o.tokens,i);n!==s&&this.replaceMeasureFormula(t,s,n)}}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){if(!e.computedBy)throw new Error(`Measure ${e.fieldName} is not computed by formula`);const t=e.computedBy.sheetId;return this.compiledMeasureFormulas[t][e.computedBy.formula]}addPivot(e,t,s=this.nextFormulaId.toString()){this.history.update("pivots",e,{definition:ae(t),formulaId:s}),this.compileCalculatedMeasures(t.measures),this.history.update("formulaIds",s,e),this.history.update("nextFormulaId",this.nextFormulaId+1)}compileCalculatedMeasures(e){for(const t of e)if(t.computedBy){const e=t.computedBy.sheetId,s=this.compileMeasureFormula(t.computedBy.sheetId,t.computedBy.formula);this.history.update("compiledMeasureFormulas",e,t.computedBy.formula,s)}}insertPivot(e,t,s){this.resizeSheet(e.sheetId,e,s);const o=s.getPivotCells();for(let s=0;s<o.length;s++)for(let i=0;i<o[s].length;i++){const n=o[s][i];this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col+s,row:e.row+i,content:ip(t,n)})}}resizeSheet(e,{col:t,row:s},o){const i=o.getNumberOfDataColumns()+1,n=this.getters.getNumberCols(e),r=n-t;r<i&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:n-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-r,position:"after"});const a=o.columns.length+o.rows.length,l=this.getters.getNumberRows(e),c=l-s;c<a&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:l-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a-c,position:"after"})}getPivotCore(e){const t=this.pivots[e];if(!t)throw new Error(`Pivot with id ${e} not found`);return t}compileMeasureFormula(e,t){const s=sE(t),o=s.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return{...s,dependencies:o}}replaceMeasureFormula(e,t,s){this.history.update("compiledMeasureFormulas",e,t,void 0),this.history.update("compiledMeasureFormulas",e,s,this.compileMeasureFormula(e,s));for(const o in this.pivots){const i=this.pivots[o];if(i)for(const n of i.definition.measures)if(n.computedBy?.formula===t){const t=i.definition.measures.indexOf(n);this.history.update("pivots",o,"definition","measures",t,"computedBy",{formula:s,sheetId:e})}}}checkSortedColumnInMeasures(e){const t=e.measures.map(e=>e.id);return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?"InvalidDefinition":"Success"}checkDuplicatedMeasureIds(e){const t=new Set(e.measures.map(e=>e.id));return e.measures.length!==t.size?"InvalidDefinition":"Success"}checkCustomFieldsAreValid(e){for(const t in e.customFields){const s=e.customFields[t],o=new Set,i=new Set;let n=!1;for(const e of s.groups){if(!e.name||i.has(e.name))return"InvalidPivotCustomField";if(e.values.some(e=>o.has(e)))return"InvalidPivotCustomField";if(e.isOtherGroup&&n)return"InvalidPivotCustomField";e.values.forEach(e=>o.add(e)),i.add(e.name),n||=!!e.isOtherGroup}}return"Success"}import(e){if(e.pivots)for(const[t,s]of Object.entries(e.pivots))this.addPivot(t,s,s.formulaId);this.history.update("nextFormulaId",e.pivotNextId||Kg(this.pivots)+1)}export(e){e.pivots={};for(const t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}}).add("spreadsheet_pivot_core",class extends XT{allowDispatch(e){switch(e.type){case"ADD_PIVOT":case"UPDATE_PIVOT":const t=e.pivot;return this.checkDataSetValidity(t)}return"Success"}adaptRanges(e){for(const t of this.getters.getPivotIds()){const s=this.getters.getPivotCoreDefinition(t);if("SPREADSHEET"===s.type&&s.dataSet){const{sheetId:o,zone:i}=s.dataSet,n=wA(this.getters.getRangeFromZone(o,i),e),r=n&&{sheetId:n.sheetId,zone:n.zone};this.dispatch("UPDATE_PIVOT",{pivotId:t,pivot:{...s,dataSet:r}})}}}checkDataSetValidity(e){if("SPREADSHEET"===e.type&&e.dataSet){const{zone:t,sheetId:s}=e.dataSet;return s&&this.getters.tryGetSheet(s)&&t&&Rt(t)?this.getters.checkZonesExistInSheet(s,[t]):"InvalidDataSet"}return"Success"}}).add("tableStyle",class extends XT{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(!TE[e.templateName])return"InvalidTableStyle";try{bv(e.primaryColor)}catch(e){return"InvalidTableStyle"}}return"Success"}handle(e){switch(e.type){case"CREATE_TABLE_STYLE":const t=AE(e.tableStyleName,e.templateName,e.primaryColor);this.history.update("styles",e.tableStyleId,t);break;case"REMOVE_TABLE_STYLE":const s={...this.styles};delete s[e.tableStyleId],this.history.update("styles",s);for(const t of this.getters.getSheetIds())for(const s of this.getters.getCoreTables(t))s.config.styleId===e.tableStyleId&&this.dispatch("UPDATE_TABLE",{sheetId:t,zone:s.range.zone,config:{styleId:hE.styleId}})}}getTableStyle(e){if(!this.styles[e])throw new Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return st(fs("Custom Table Style"),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!xE[e]}import(e){for(const e in xE)this.styles[e]=xE[e];for(const t in e.customTableStyles){const s=e.customTableStyles[t];this.styles[t]=AE(s.displayName,s.templateName,s.primaryColor)}}export(e){const t={};for(const e in this.styles)xE[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}}),F_=(new is).add("ui_sheet",class extends Ir{static getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getContiguousZone","computeTextYCoordinate"];ctx=kb();allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(const t of e.cols){const s=this.getColMaxWidth(e.sheetId,t);0!==s&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:s,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":this.autoResizeRows(e.sheetId,e.rows);break;case"DELETE_UNFILTERED_CONTENT":const t=[];for(const s of e.target){const o=pe(ge(s.top,s.bottom+1).filter(t=>!this.getters.isRowFiltered(e.sheetId,t)));for(const e of o)t.push({...s,top:e[0],bottom:e[e.length-1]})}this.dispatch("DELETE_CONTENT",{sheetId:e.sheetId,target:t})}}getCellWidth(e){const t=this.getters.getCellComputedStyle(e);let s=0;const o=this.getters.getEvaluatedCell(e).formattedValue;if(o){const e=Yb(this.ctx,o,t,void 0);s+=Math.max(...e.map(e=>zb(this.ctx,e,t)))}for(const t of this.getters.getCellIcons(e))s+=t.margin+t.size;if(this.getters.getDataValidationChipStyle(e)&&(s+=10),0===s)return 0;if(s+=8,"wrap"===t.wrapping){const t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,s)}return s}getTextWidth(e,t){return zb(this.ctx,e,t)}getCellText(e,t){const s=this.getters.getCell(e),o=this.getters.getLocale();if(t?.showFormula&&s?.isFormula)return sh(s.content,o);if(t?.showFormula&&!s?.content)return"";{const i=this.getters.getEvaluatedCell(e),n=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>zb(this.ctx,e,s?.style||{})}:void 0;return pn(i.value,{format:i.format,locale:o,formatWidth:n})}}getCellMultiLineText(e,t){const s=this.getters.getCellStyle(e),o=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.maxWidth});return Yb(this.ctx,o,s,t.wrapText?t.maxWidth:void 0)}computeTextYCoordinate(e,t,s=M,o=1){const i=e.y+1,n=Lb(t,o);if(e.height>n+8){if("middle"===s)return Math.ceil(i+(e.height-n)/2);if("bottom"===s)return i+e.height-n-4}return i+4}getContiguousZone(e,t){const s=t=>{for(const s of ge(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:s,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:s,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(const s of ge(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:s}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:s}))return{...t,right:t.right+1}}return t};let o=!1,i=t;do{o=!1;const e=s(i);Mt(i,e)||(o=!0,i=e)}while(o);return i}isCellEmpty(e){const t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===_d.empty}getColMaxWidth(e,t){const s=Bt(this.getters.getColsZone(e,t,t)).map(t=>this.getCellWidth({sheetId:e,...t}));return Math.max(0,Ke(s))}checkSheetExists(e){return"sheetId"in e&&void 0===this.getters.tryGetSheet(e.sheetId)?"InvalidSheetId":"Success"}checkZonesAreInSheet(e){const t="sheetId"in e?e.sheetId:this.getters.tryGetActiveSheetId();if("ranges"in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId)))return"InvalidSheetId";const s=this.getters.getCommandZones(e);return!t&&s.length>0?"NoActiveSheet":t&&s.length>0?this.getters.checkZonesExistInSheet(t,s):"Success"}autoResizeRows(e,t){const s=[];for(const o of t){let t=0;for(const s of this.getters.getRowCells(e,o)){const o=this.getters.getCellById(s);if(!o)continue;const i=this.getters.getCellPosition(o.id),n=this.getters.getColSize(e,i.col);if(o.isFormula||this.getters.getArrayFormulaSpreadingOn(i)){const e=this.getters.getEvaluatedCell(i).formattedValue,s=Vb(this.ctx,e,o?.style,n);s>t&&s>_&&(t=s)}else{const e=o.content,s=Vb(this.ctx,e,o?.style,n);s>=t&&s>_&&(t=0)}}s.push(t||null)}const o=new Map(s.map(e=>[e,[]]));for(let e=0;e<s.length;e++)o.get(s[e])?.push(t[e]);for(const[t,s]of o)this.dispatch("RESIZE_COLUMNS_ROWS",{elements:s,dimension:"ROW",size:t,sheetId:e})}}).add("ui_options",class extends Ir{static getters=["shouldShowFormulas"];showFormulas=!1;handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}).add("autofill",class extends Ir{static layers=["Autofill"];static getters=["getAutofillTooltip"];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){if("AUTOFILL_SELECT"===e.type){const t=this.getters.getActiveSheetId();return this.lastCellSelected.col=-1===e.col?this.lastCellSelected.col:ue(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:ue(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?"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()}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),s=this.autofillZone,o=[];switch(this.direction){case"down":for(let e=t.left;e<=t.right;e++){const i=[];for(let s=t.top;s<=t.bottom;s++)i.push(mt(e,s));const n=this.createGenerator(i);for(let t=s.top;t<=s.bottom;t++)o.push(this.computeNewCell(n,e,t))}break;case"up":for(let e=t.left;e<=t.right;e++){const i=[];for(let s=t.bottom;s>=t.top;s--)i.push(mt(e,s));const n=this.createGenerator(i);for(let t=s.bottom;t>=s.top;t--)o.push(this.computeNewCell(n,e,t))}break;case"left":for(let e=t.top;e<=t.bottom;e++){const i=[];for(let s=t.right;s>=t.left;s--)i.push(mt(s,e));const n=this.createGenerator(i);for(let t=s.right;t>=s.left;t--)o.push(this.computeNewCell(n,t,e))}break;case"right":for(let e=t.top;e<=t.bottom;e++){const i=[];for(let s=t.left;s<=t.right;s++)i.push(mt(s,e));const n=this.createGenerator(i);for(let t=s.left;t<=s.right;t++)o.push(this.computeNewCell(n,t,e))}}if(e){const e={},t={},s={},i=this.getters.getActiveSheetId();for(const n of o)this.collectBordersData(n,e),this.autofillMerge(i,n),this.autofillCell(i,n),this.collectConditionalFormatsData(i,n,t),this.collectDataValidationsData(i,n,s);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,s),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){const s=JSON.stringify(e.border);s in t||(t[s]=[]),t[s].push(Zt({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,s){const{originCol:o,originRow:i,col:n,row:r}=t,a=this.getters.getRulesByCell(e,o,i),l=mt(n,r);for(const e of a)e.id in s||(s[e.id]=[]),s[e.id].push(l)}collectDataValidationsData(e,t,s){const{originCol:o,originRow:i,col:n,row:r}=t,a={sheetId:e,col:o,row:i},l=this.getters.getValidationRuleForCell(a);l&&(l.id in s||(s[l.id]=[]),s[l.id].push(Zt({col:n,row:r})))}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(const s in t){const o="undefined"===s?void 0:JSON.parse(s);this.dispatch("SET_BORDERS_ON_TARGET",{sheetId:e,border:o,target:ft(t[s])})}}autofillConditionalFormats(e,t){for(const s in t){const o=t[s],i=this.getters.getConditionalFormats(e).find(e=>e.id===s);if(!i)continue;const n=this.getters.getAdaptedCfRanges(e,i,o.map(wt),[]);n&&this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:i.id,rule:i.rule,stopIfTrue:i.stopIfTrue},ranges:n,sheetId:e})}}autofillDataValidations(e,t){for(const s in t){const o=t[s],i=this.getters.getDataValidationRule(e,s);if(!i)continue;const n=i.ranges.map(e=>e.zone),r=ft(n.concat(o),[]);this.dispatch("ADD_DATA_VALIDATION_RULE",{rule:i,ranges:r.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}select(e,t){const s=this.getters.getSelectedZone();if(kt(e,t,s))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,s.top-1,s.left,s.right),this.steps=s.top-t;break;case"down":this.saveZone(s.bottom+1,t,s.left,s.right),this.steps=t-s.bottom;break;case"left":this.saveZone(s.top,s.bottom,e,s.left-1),this.steps=s.left-e;break;case"right":this.saveZone(s.top,s.bottom,s.right+1,e),this.steps=e-s.right}this.autofill(!1)}}autofillAuto(){const e=this.getters.getActivePosition(),t=this.getters.getTable(e);let s=t?t.range.zone.bottom:this.getAutofillAutoLastRow();const o=this.getters.getSelectedZone();for(let t=o.bottom+1;t<=s;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==_d.empty){s=t-1;break}s>o.bottom&&(this.select(e.col,s),this.autofill(!0))}getAutofillAutoLastRow(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let s=e.left,o=e.bottom;if(s>0){let e={sheetId:t,col:s-1,row:o};for(;this.getters.getEvaluatedCell(e).type!==_d.empty;)o+=1,e={sheetId:t,col:s-1,row:o}}if(o===e.bottom&&(s=e.right,s<=this.getters.getNumberCols(t))){let e={sheetId:t,col:s+1,row:o};for(;this.getters.getEvaluatedCell(e).type!==_d.empty;)o+=1,e={sheetId:t,col:s+1,row:o}}return o-1}computeNewCell(e,t,s){const{cellData:o,tooltip:i,origin:n}=e.next(),{content:r,style:a,border:l,format:c}=o;return this.tooltip=i,{originCol:n.col,originRow:n.row,col:t,row:s,content:r,style:a,border:l,format:c}}getRule(e,t){const s=t_.getAll().sort((e,t)=>e.sequence-t.sequence).find(s=>s.condition(e,t));return s&&this.direction&&s.generateRule(e,t,this.direction)}createGenerator(e){const t=[],s=[],o=this.getters.getActiveSheetId();for(const t of e){const{col:e,row:i}=pt(t),n=this.getters.getCell({sheetId:o,col:e,row:i});s.push({col:e,row:i,cell:n,sheetId:o})}const i=s.map(e=>e.cell);for(const e of s){let s={type:"COPY_MODIFIER"};if(e&&e.cell){s=this.getRule(e.cell,i)||s}const o=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:o},rule:s})}return new c_(t,this.getters,this.direction)}saveZone(e,t,s,o){this.autofillZone={top:e,bottom:t,left:s,right:o}}getDirection(e,t){const s=this.getters.getSelectedZone(),o={up:{number:s.top-t,value:"up"},down:{number:t-s.bottom,value:"down"},left:{number:s.left-e,value:"left"},right:{number:e-s.right,value:"right"}};if(1===Object.values(o).map(e=>e.number>0?1:0).reduce((e,t)=>e+t))return Object.values(o).find(e=>e.number>0?1:0).value;const i=o.up.number>0?"up":"down",n=o.left.number>0?"left":"right";return Math.abs(o[i].number)>=Math.abs(o[n].number)?o[i].value:o[n].value}autofillMerge(e,t){const{originCol:s,originRow:o,col:i,row:n}=t,r={sheetId:e,col:i,row:n},a={sheetId:e,col:s,row:o};if(this.getters.isInMerge(r)&&!this.getters.isInMerge(a)){const t=this.getters.getMerge(r);t&&this.dispatch("REMOVE_MERGE",{sheetId:e,target:[t]})}const l=this.getters.getMerge(a);l?.left===s&&l?.top===o&&this.dispatch("ADD_MERGE",{sheetId:e,target:[{top:n,bottom:n+l.bottom-l.top,left:i,right:i+l.right-l.left}]})}drawLayer(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:s}=e,{x:o,y:i,width:n,height:r}=this.getters.getVisibleRect(this.autofillZone);n>0&&r>0&&(t.strokeStyle="black",t.lineWidth=s,t.setLineDash([3]),t.strokeRect(o,i,n,r),t.setLineDash([]))}}).add("sort",class extends Ir{allowDispatch(e){return"SORT_CELLS"===e.type?kt(e.col,e.row,e.zone)?this.checkValidations(e,this.checkMerge,this.checkMergeSizes,this.checkArrayFormulaInSortZone):"InvalidSortAnchor":"Success"}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{})}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return"Success";return Bt(t).some(({col:t,row:s})=>!this.getters.isInMerge({sheetId:e,col:t,row:s}))?"InvalidSortZone":"Success"}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return"Success";const s=this.getters.getMerges(e).filter(e=>Lt(e,t)),o=Ut(s[0]),[i,n]=[o.numberOfCols,o.numberOfRows];return s.every(e=>{const[t,s]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&s===n})?"Success":"InvalidSortZone"}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return Bt(t).some(({col:t,row:s})=>{const o=this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:s});return o&&!Me(o,{sheetId:e,col:t,row:s})})?"SortZoneWithArrayFormulas":"Success"}hasHeader(e,t){if(1===t[0].length)return!1;let s=t.map(t=>t.map(({col:t,row:s})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:s}).type));return s[0][0]===_d.empty&&(s=s.slice(1)),!s.some(e=>e[0]===_d.empty)&&!!s.some(e=>e[1]!==_d.empty&&e[0]!==e[1])}sortZone(e,t,s,o,i){const[n,r]=this.mainCellsSteps(e,s),a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},s);let c=this.mainCells(e,s);!i.sortHeaders&&this.hasHeader(e,c)&&(l.top+=r),c=this.mainCells(e,l);const h=function(e,t,s){const o=e.map((e,t)=>({index:t,type:e.type,value:e.value}));return(s?o.map(e=>e.type===_d.empty?{...e,type:_d.number,value:0}:e):o).sort(Pd(t))}(c[a-l.left].map(e=>this.getters.getEvaluatedCell(e)),o,Boolean(i.emptyCellAsZero)),d=h.map(e=>e.index),[u,g]=[c.length,c[0].length],p=[];for(let e=0;e<u;e++)for(let t=0;t<g;t++){const{col:s,row:o,sheetId:i}=c[e][d[t]],a=this.getters.getCell({sheetId:i,col:s,row:o}),h=l.left+e*n,u=l.top+t*r,g={sheetId:i,col:h,row:u,content:""};if(a){let e=a.content;if(a.isFormula){const t=this.getters.getCellPosition(a.id);e=this.getters.getTranslatedCellFormula(i,0,u-t.row,a.compiledFormula.tokens)}g.style=a.style,g.content=e,g.format=a.format}p.push(g)}p.forEach(e=>this.dispatch("UPDATE_CELL",e))}mainCellsSteps(e,t){const s=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[s?s.right-s.left+1:1,s?s.bottom-s.top+1:1]}mainCells(e,t){const[s,o]=this.mainCellsSteps(e,t),i=[],n=ge(t.left,t.right+1,s),r=ge(t.top,t.bottom+1,o);for(const t of n){const s=[];i.push(s);for(const o of r)s.push({sheetId:e,col:t,row:o})}return i}}).add("automatic_sum",class extends Ir{static getters=["getAutomaticSums"];handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:s}=this.getters.getSelection();for(const o of t){const t=this.getAutomaticSums(e,o,s.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,s){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,s):this.sumData(e,t)}sumData(e,t){const s=this.dimensionsToSum(e,t),o=this.sumDimensions(e,t,s).filter(({zone:t})=>!this.getters.isEmpty(e,t));return s.has("ROW")&&s.has("COL")&&o.push(this.sumTotal(t)),o}sumAdjacentData(e,t,s){const{col:o,row:i}=kt(s.col,s.row,t)?s:{col:t.left,row:t.top},n=this.findAdjacentData(e,o,i);return n?this.getters.isSingleCellOrMerge(e,t)||Ht(Ft(n,t))?[{position:{col:o,row:i},zone:n}]:this.sumDimensions(e,Ft(n,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,s){const o=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:s}),n=this.findSuitableZoneToSum(o,i.col,i.row);if(n)return this.getters.expandZone(e,n)}findSuitableZoneToSum(e,t,s){const o=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:s-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:s});if(this.isNumber(i)&&!this.isNumber(o))return this.findHorizontalZone(e,t,s);const n=this.findVerticalZone(e,t,s);if(this.isZoneValid(n))return n;const r=this.findHorizontalZone(e,t,s);return this.isZoneValid(r)?r:void 0}findVerticalZone(e,t,s){const o={top:0,bottom:s-1,left:t,right:t},i=this.reduceZoneStart(e,o,o.bottom);return{...o,top:i}}findHorizontalZone(e,t,s){const o={top:s,bottom:s,left:0,right:t-1},i=this.reduceZoneStart(e,o,o.right);return{...o,left:i}}reduceZoneStart(e,t,s){const o=this.getters.getEvaluatedCellsInZone(e.id,t),i=ge(s,-1,-1),n=Ke(i.filter(e=>o[e]&&!o[e].isAutoSummable)),r=pe(i.filter(e=>this.isNumber(o[e])))[0]||[];return Ke(r)<n?1/0:Je(r)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===_d.number&&!(e.format&&wn(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){const s=new Set;return Ht(t)?(s.add(1===Ut(t).numberOfCols?"COL":"ROW"),s):(this.lastColIsEmpty(e,t)&&s.add("ROW"),this.lastRowIsEmpty(e,t)&&s.add("COL"),0===s.size&&s.add("COL"),s)}sumDimensions(e,t,s){return[...s.has("COL")?this.sumColumns(t,e):[],...s.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:s}=e;return{position:{col:s,row:t},zone:{...e,top:t,right:s-1}}}sumColumns(e,t){const s=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,s.bottom-1)},Bt(s).map(t=>({position:t,zone:{...e,right:t.col,left:t.col}}))}sumRows(e,t){const s=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,s.right-1)},Bt(s).map(t=>({position:t,zone:{...e,top:t.row,bottom:t.row}}))}dispatchCellUpdates(e,t){for(const s of t){const{col:t,row:o}=s.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,content:`=SUM(${this.getters.zoneToXC(e,s.zone)})`})}}nextEmptyRow(e,t){let s=t.bottom+1;const{left:o,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:s,top:s,left:o,right:i});)s++;return{...t,top:s,bottom:s}}nextEmptyCol(e,t){let s=t.right+1;const{top:o,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:s,right:s,top:o,bottom:i});)s++;return{...t,left:s,right:s}}transpose(e){return new Set([...e.values()].map(e=>"COL"===e?"ROW":"COL"))}}).add("format",class extends Ir{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)}}setContextualFormat(e,t,s){const o=[],i={};for(const s of ft(t))for(let t=s.left;t<=s.right;t++)for(let n=s.top;n<=s.bottom;n++){const s={sheetId:e,col:t,row:n},r=this.getters.getPivotCellFromPosition(s);if(this.isSpilledPivotValueFormula(s,r)){o.push(s);const e=this.getters.getPivotIdFromPosition(s)||"";i[e]??=new Set,i[e].add(r.measure)}}const n=ft(o.map(Zt));for(const e in i){const t=i[e],o=this.getters.getPivotCoreDefinition(e);this.dispatch("UPDATE_PIVOT",{pivotId:e,pivot:{...o,measures:o.measures.map(e=>t.has(e.id)?{...e,format:s}:e)}})}this.dispatch("SET_FORMATTING",{sheetId:e,target:n,format:""}),this.dispatch("SET_FORMATTING",{sheetId:e,target:ft(t,n),format:s})}isSpilledPivotValueFormula(e,t){const s=this.getters.getCell(e);return"VALUE"===t.type&&!s?.isFormula}setDecimal(e,t,s){const o={};for(const i of ft(t))for(const t of Bt(i)){const i=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==i){const e=Vn(i,s);o[e]=o[e]||[],o[e].push(t)}}for(const t in o){const s=ft(o[t].map(e=>Zt(e)));this.setContextualFormat(e,s,t)}}getCellNumberFormat(e){for(const t of[e]){const e=this.getters.getEvaluatedCell(t);if(!(e.type!==_d.number||e.format&&wn(e.format)))return e.format||xn(e.value)}}}).add("insert_pivot",class extends Ir{static getters=[];allowDispatch(e){if("DUPLICATE_PIVOT_IN_NEW_SHEET"===e.type){if(!this.getters.isExistingPivot(e.pivotId))return"PivotIdNotFound";if(!this.getters.getPivot(e.pivotId).isValid())return"PivotInError"}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){1===Kt(this.getters.getSelectedZone())&&this.selection.selectTableAroundSelection();const s=this.getters.getActiveSheetId();this.dispatch("ADD_PIVOT",{pivotId:e,pivot:{dataSet:{zone:this.getters.getSelectedZone(),sheetId:s},columns:[],rows:[],measures:[],name:fs("New pivot"),type:"SPREADSHEET"}});const o=this.getters.getSheetIds().findIndex(e=>e===s)+1,i=this.getters.getPivotFormulaId(e);this.dispatch("CREATE_SHEET",{sheetId:t,name:fs("Pivot #%(formulaId)s",{formulaId:i}),position:o}),this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:s,sheetIdTo:t});const n=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,n.getCollapsedTableStructure().export(),"dynamic")}duplicatePivotInNewSheet(e,t,s){this.dispatch("DUPLICATE_PIVOT",{pivotId:e,newPivotId:t,duplicatedPivotName:fs("%s (copy)",this.getters.getPivotCoreDefinition(e).name)});const o=this.getters.getActiveSheetId(),i=this.getters.getSheetIds().indexOf(o)+1,n=this.getters.getPivotFormulaId(t),r=this.getters.getPivotName(t);if(this.dispatch("CREATE_SHEET",{sheetId:s,name:this.getPivotDuplicateSheetName(fs("%(newPivotName)s (Pivot #%(formulaId)s)",{newPivotName:r,formulaId:n})),position:i}).isSuccessful){this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:o,sheetIdTo:s});const i=this.getters.getPivot(e);this.insertPivotWithTable(s,0,0,t,i.getCollapsedTableStructure().export(),"dynamic")}}getPivotDuplicateSheetName(e){const t=this.getters.getSheetIds().map(e=>this.getters.getSheetName(e));return st(de(e),t)}insertPivotWithTable(e,t,s,o,i,n){const{cols:r,rows:a,measures:l,fieldsType:c}=i,h=new yA(r,a,l,c||{}),d=h.columns.length-1;this.resizeSheet(e,t,s,h);const u=this.getters.getPivotFormulaId(o);let g;"dynamic"===n?(this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:s,content:`=PIVOT(${u})`}),g={left:t,right:t,top:s,bottom:s}):(this.dispatch("INSERT_PIVOT",{sheetId:e,col:t,row:s,pivotId:o,table:h.export()}),g={left:t,right:t+h.getNumberOfDataColumns(),top:s,bottom:s+d+h.rows.length}),this.dispatch("CREATE_TABLE",{tableType:n,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,g)],config:{...J,numberOfHeaders:d}})}resizeSheet(e,t,s,o){const i=o.getNumberOfDataColumns()+1,n=this.getters.getNumberCols(e),r=n-t;r<i&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:n-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-r,position:"after"});const a=o.columns.length+o.rows.length,l=this.getters.getNumberRows(e),c=l-s;c<a&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:l-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a-c,position:"after"})}splitPivotFormula(e,t,s,o){const i=this.getters.getSpreadZone({sheetId:e,col:t,row:s});if(!i)return;const n=this.getters.getPivotFormulaId(o),r=new Map;for(let t=i.left;t<=i.right;t++)for(let s=i.top;s<=i.bottom;s++){const o={sheetId:e,col:t,row:s};r.set(o,this.getters.getPivotCellFromPosition(o))}for(const[e,t]of r)this.dispatch("UPDATE_CELL",{...e,content:ip(n,t)});const a=this.getters.getCoreTable({sheetId:e,col:t,row:s});if("dynamic"===a?.type){const o=Zt({col:t,row:s}),n=this.getters.getRangeDataFromZone(e,i);this.dispatch("UPDATE_TABLE",{sheetId:e,zone:o,newTableRange:n,tableType:"static"})}}}).add("pivot_presence",class extends Ir{static getters=["getPivotPresenceTracker"];trackPresencePivotId;tracker;handle(e){switch(e.type){case"PIVOT_START_PRESENCE_TRACKING":this.tracker=new m_,this.trackPresencePivotId=e.pivotId;break;case"PIVOT_STOP_PRESENCE_TRACKING":this.trackPresencePivotId=void 0}}getPivotPresenceTracker(e){if(this.trackPresencePivotId===e){if(!this.tracker)throw new Error("Tracker not initialized");return this.tracker}}}).add("split_to_columns",class extends Ir{static getters=["getAutomaticSeparator"];allowDispatch(e){return"SPLIT_TEXT_INTO_COLUMNS"===e.type?this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e):"Success"}handle(e){if("SPLIT_TEXT_INTO_COLUMNS"===e.type)this.splitIntoColumns(e)}getAutomaticSeparator(){const e=this.getters.getSelectedCells();for(const t of e)if(t.value&&t.type===_d.text){const e=this.getAutoSeparatorForString(t.value);if(e)return e}return" "}getAutoSeparatorForString(e){const t=[X,";",","," ","."];for(const s of t)if(e.includes(s))return s}splitIntoColumns({separator:e,addNewColumns:t}){const s=this.getters.getSelectedZone(),o=this.getters.getActiveSheetId(),i=this.getSplittedCols(s,e);t&&this.addColsToAvoidCollisions(s,i),this.removeMergesInSplitZone(s,i),this.addColumnsToNotOverflowSheet(s,i);for(let e=0;e<i.length;e++){const t=s.top+e,n=i[e],r=s.left,a=this.getters.getCell({sheetId:o,col:r,row:t});if(1!==n.length||n[0]!==a?.content)for(const[e,s]of n.entries())this.dispatch("UPDATE_CELL",{sheetId:o,col:r+e,row:t,content:Kc(s,this.getters.getLocale()),format:"",style:a?.style||null})}}getSplittedCols(e,t){if(!t)throw new Error("Separator cannot be empty");const s=this.getters.getActiveSheetId(),o=[];for(const i of ge(e.top,e.bottom+1)){const n=this.getters.getEvaluatedCell({sheetId:s,col:e.left,row:i}).formattedValue;o.push(this.splitAndRemoveTrailingEmpty(n,t))}return o}splitAndRemoveTrailingEmpty(e,t){const s=e.split(t);for(;s.length>1&&""===s[s.length-1];)s.pop();return s}willSplittedColsOverwriteContent(e,t){const s=this.getters.getActiveSheetId();for(const o of ge(e.top,e.bottom+1)){const i=t[o-e.top];for(let t=1;t<i.length;t++){const i=this.getters.getCell({sheetId:s,col:e.left+t,row:o});if(i&&i.content)return!0}}return!1}removeMergesInSplitZone(e,t){const s=this.getters.getActiveSheetId(),o=Math.max(...t.map(e=>e.length)),i={...e,right:e.left+o-1},n=this.getters.getMergesInZone(s,i);this.dispatch("REMOVE_MERGE",{sheetId:s,target:n})}addColsToAvoidCollisions(e,t){const s=this.getters.getActiveSheetId();let o=0;for(const i of ge(e.top,e.bottom+1)){const n={sheetId:s,col:e.left,row:i},r=t[i-e.top],a=this.getColsToAddToAvoidCollision(n,r);o=Math.max(o,a)}o&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:e.left,sheetId:s,sheetName:this.getters.getSheetName(s),quantity:o,position:"after"})}getColsToAddToAvoidCollision(e,t){const s=t.length;for(let t=1;t<s;t++){const o=e.col+t,i=this.getters.getCell({...e,col:o});if(i&&i.content)return s-t}return 0}addColumnsToNotOverflowSheet(e,t){const s=this.getters.getActiveSheetId(),o=Math.max(...t.map(e=>e.length-1)),i=this.getters.getNumberCols(s)-1;e.left+o>i&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:i,sheetId:s,sheetName:this.getters.getSheetName(s),quantity:e.left+o-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";const t=this.getters.getSelectedZones()[0],s=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,s)?"SplitWillOverwriteContent":"Success"}checkSeparatorInSelection({separator:e}){const t=this.getters.getSelectedCells();for(const s of t)if(s.formattedValue.includes(e))return"Success";return"NoSplitSeparatorInSelection"}}).add("subtotal_evaluation",class extends Ir{subtotalCells=new Set;handle(e){switch(e.type){case"START":this.subtotalCells.clear();for(const e of this.getters.getSheetIds()){const t=this.getters.getCells(e);for(const e in t){const s=t[e];wr(s)&&this.subtotalCells.add(s.id)}}break;case"UPDATE_CELL":{if(!("content"in e))return;const t=this.getters.getCell(e);if(!t)return;wr(t)?this.subtotalCells.add(t.id):this.subtotalCells.delete(t.id);break}}pr.has(e.type)&&this.dispatch("EVALUATE_CELLS",{cellIds:Array.from(this.subtotalCells)})}}).add("collaborative",class extends Ir{static getters=["getClientsToDisplay","getClient","getCurrentClient","getConnectedClients","isFullySynchronized"];static layers=["Selection"];colors=new $v(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 zE)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const s of this.getters.getConnectedClients())s.id!==this.getters.getCurrentClient().id&&s.position&&s.position.sheetId===e&&this.isPositionValid(s.position)&&t.push({...s,position:s.position});return t}drawLayer(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:s}=e,o=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:i,col:n}=e.position,r=this.getters.expandZone(o,{top:i,bottom:i,left:n,right:n}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);if(c<=0||h<=0)continue;const d=e.color;t.fillStyle=`${d}10`,t.lineWidth=4*s,t.strokeStyle=d,t.globalCompositeOperation="multiply",t.fillRect(a,l,c,h),t.globalCompositeOperation="source-over",t.strokeRect(a,l,c,h),t.font=`bold ${L+1}px ${k}`}}}).add("history",class extends Ir{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"}return"Success"}handle(e){switch(e.type){case"REQUEST_UNDO":case"REQUEST_REDO":this.requestHistoryChange("REQUEST_UNDO"===e.type?"UNDO":"REDO")}}finalize(){}requestHistoryChange(e){const t="UNDO"===e?this.undoStack.pop():this.redoStack.pop();if(!t){const e=this.getPossibleRevisionToRepeat();if(!e)return;const t=p_(e,this.getters);if(!t)return;if(!Array.isArray(t))return void this.dispatch(t.type,t);for(const e of t)this.dispatch(e.type,e);return}"UNDO"===e?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t))}canUndo(){return this.undoStack.length>0}canRedo(){if(this.redoStack.length>0)return!0;const e=this.getPossibleRevisionToRepeat();return!(!(t=e)||!t.rootCommand||"object"!=typeof t.rootCommand)&&(vr(t.rootCommand)?u_.contains(t.rootCommand.type):g_.contains(t.rootCommand.type));var t}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}}).add("table_autofill",class extends Ir{handle(e){if("AUTOFILL_TABLE_COLUMN"===e.type){const t=this.getters.getCoreTable(e),s=this.getters.getCell(e);if(!t?.config.automaticAutofill||"dynamic"===t.type||!s?.isFormula)return;const{col:o,row:i}=e,n=function(e,t){const s=t.numberOfHeaders,o={...e,top:e.top+s};return o.top<=o.bottom?o:void 0}(t.range.zone,t.config);if(n&&kt(o,i,n)){const t=e.autofillRowStart??n.top,s=e.autofillRowEnd??n.bottom,o={...n,top:t,bottom:s};this.autofillTableZone(e,o)}}}autofillTableZone(e,t){if(t.top===t.bottom)return;const{col:s,row:o,sheetId:i}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==o&&this.getters.getEvaluatedCell({col:s,row:e,sheetId:i}).type!==_d.empty)return;const n={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(s,o),this.dispatch("AUTOFILL_SELECT",{col:s,row:t.bottom}),this.dispatch("AUTOFILL"),this.selection.selectCell(s,o),this.dispatch("AUTOFILL_SELECT",{col:s,row:t.top}),this.dispatch("AUTOFILL"),this.selection.selectZone(n)}}).add("table_ui_resize",class extends Ir{allowDispatch(e){if("RESIZE_TABLE"===e.type){const t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return"TableNotFound";const s=t.range.zone,o=this.getters.getRangeFromRangeData(e.newTableRange).zone;return o.top!==s.top||o.left!==s.left?"InvalidTableResize":this.canDispatch("UPDATE_TABLE",{...e}).reasons}return"Success"}handle(e){switch(e.type){case"RESIZE_TABLE":{const t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch("UPDATE_TABLE",{...e}),!t)return;const s=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(this.selection.selectCell(s.right,s.bottom),!t.config.automaticAutofill)return;const o=t.range.zone;if(s.bottom>=o.bottom){for(let t=s.left;t<=s.right;t++){const i={col:t,row:o.bottom,sheetId:e.sheetId};this.getters.getCell(i)?.content.startsWith("=")&&this.dispatch("AUTOFILL_TABLE_COLUMN",{...i,autofillRowStart:o.bottom,autofillRowEnd:s.bottom})}break}}}}}).add("datavalidation_insert",class extends Ir{handle(e){if("ADD_DATA_VALIDATION_RULE"===e.type)if("isBoolean"===e.rule.criterion.type){const t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));for(const e of xb(t)){const t=this.getters.getCell(e),s=this.getters.getEvaluatedCell(e);if(t?.content)if(t?.content&&s.type===_d.empty){let s;if(t.content.startsWith("=")){const o=this.getters.evaluateFormula(e.sheetId,t.content);s=(Ds(o)?o[0][0]:o)?.toString()}else s=t.content;s&&fe(s)||this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}else s.type!==_d.boolean&&this.dispatch("UPDATE_CELL",{...e,content:"FALSE"});else this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}}}}).add("checkbox_toggle",class extends Ir{static getters=["hasBooleanValidationInZones"];handle(e){if("TOGGLE_CHECKBOX"===e.type)this.toggleCheckbox(e.sheetId,e.target)}hasBooleanValidationInZones(e){const t=this.getters.getActiveSheetId();for(const s of e)for(let e=s.left;e<=s.right;e++)for(let o=s.top;o<=s.bottom;o++)if(this.getters.isCellValidCheckbox({col:e,row:o,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(const s of t)for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++){const s={col:t,row:o,sheetId:e};if(this.getters.isCellValidCheckbox(s)){const e=this.getters.getEvaluatedCell(s).value?"FALSE":"TRUE";this.dispatch("UPDATE_CELL",{...s,content:e})}}}}).add("dynamic_translate",class extends Ir{static getters=["dynamicTranslate"];dynamicTranslate(e){return e}}).add("geo_features",class extends Ir{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)return void console.error("No geoJsonService provided to the model");const t=this.geoJsonCache[e];return t instanceof Promise?void 0:void 0!==t?t??void 0:void(this.geoJsonCache[e]=new Promise(async t=>{const s=await(this.geoJsonService?.getTopoJson(e));this.geoJsonCache[e]=this.convertToGeoJson(s),this.dispatch("EVALUATE_CHARTS"),t()}))}geoFeatureNameToId(e,t){if(this.geoJsonService)return this.geoJsonService.geoFeatureNameToId(e,t);console.error("No geoJsonService provided to the model")}convertToGeoJson(e){if(!e)return null;if("Topology"===e.type){const t=globalThis.ChartGeo.topojson.feature(e,Object.values(e.objects)[0]);return"FeatureCollection"===t.type?t.features:[t]}if("FeatureCollection"===e.type)return e.features;throw new Error("Invalid TopoJSON")}}),P_=(new is).add("selection",class extends Ir{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(e){return"InvalidSheetId"}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return"Success"}handleEvent(e){const t=e.anchor;let s=[];switch(this.isUnbounded=e.options?.unbounded||!1,e.mode){case"overrideSelection":s=[t.zone];break;case"updateAnchor":s=[...this.gridSelection.zones];const o=s.findIndex(t=>Mt(t,e.previousAnchor.zone));o>=0&&(s[o]=t.zone);break;case"newAnchor":s=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,s),this.selection.resetDefaultAnchor(this,ae(this.gridSelection.anchor));const{col:o,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:o,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)}switch(e.type){case"START":const t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);const{col:s,row:o}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(s,o),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":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);const{col:s,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:s,row:o})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:s,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:s,row:o})}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":const i=Object.keys(this.sheetsData).filter(e=>!this.getters.tryGetSheet(e));for(const e of i)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:ae(t)}}this.fallbackToVisibleSheet();const n=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map(e=>this.getters.expandZone(n,e)),this.gridSelection.anchor.zone=this.getters.expandZone(n,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,ae(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(){const e=new Set;for(const t of this.gridSelection.zones)if(0===t.top&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let s=t.left;s<=t.right;s++)e.add(s);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(const s of this.gridSelection.zones)if(0===s.left&&s.right===this.getters.getNumberCols(t)-1)for(let t=s.top;t<=s.bottom;t++)e.add(t);return e}getCurrentStyle(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return ae(this.gridSelection.zones)}getSelectedZone(){return ae(this.gridSelection.anchor.zone)}getSelectecUnboundedZone(){return ae(this.isUnbounded?this.getters.getUnboundedZone(this.activeSheet.id,this.gridSelection.anchor.zone):this.gridSelection.anchor.zone)}getSelection(){return ae(this.gridSelection)}getSelectedCells(){const e=this.getters.getActiveSheetId(),t=[];for(const s of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,s));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();{const 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(){const e=this.getters.getSelectedZones();return 1===e.length&&e[0].left===e[0].right}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let s=[];const o="COL"===e?"left":"top",i="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[i]-e[o]+1},(t,s)=>e[o]+s);s=s.concat(t)}return[...new Set(s)].sort()}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:ae(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,ae(this.gridSelection.anchor));else{const{col:e,row:s}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,s)}const{col:s,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:s,row:o})}setSelectionMixin(e,t){const{anchor:s,zones:o}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=s,this.gridSelection.zones=function(e){return e.reverse().filter((e,t,s)=>t===s.findIndex(t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)).reverse()}(o)}selectCell(e,t){const s=this.getters.getActiveSheetId(),o=this.getters.expandZone(s,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:o,cell:{col:e,row:t}},[o])}setActiveSheet(e){this.activeSheet=this.getters.getSheet(e)}activateNextSheet(e){const t=this.getters.getSheetIds(),s=(t.findIndex(e=>e===this.activeSheet.id)+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[s]})}onColumnsRemoved(e){const{cell:t,zone:s}=this.gridSelection.anchor,o=_t(s,"left",[...e.elements]);let i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=_t(i,"left",[...e.elements]);const n={cell:{col:i.left,row:i.top},zone:o},r=this.gridSelection.zones.map(t=>_t(t,"left",[...e.elements]));this.setSelectionMixin(n,r)}onRowsRemoved(e){const{cell:t,zone:s}=this.gridSelection.anchor,o=_t(s,"top",[...e.elements]);let i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=_t(i,"top",[...e.elements]);const n={cell:{col:i.left,row:i.top},zone:o},r=this.gridSelection.zones.map(t=>_t(t,"top",[...e.elements]));this.setSelectionMixin(n,r)}onAddElements(e){const t="COL"===e.dimension?"left":"top",s=Dt(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),o=this.gridSelection.zones.map(s=>Dt(s,t,e.base,e.position,e.quantity)),i={cell:{col:s.left,row:s.top},zone:s};this.setSelectionMixin(i,o)}onMoveElements(e){const t=e.elements.length,s=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});const o="COL"===e.dimension,i=e.elements[0],n=e.elements[t-1],r=e.base<i,a=r&&o?t:0,l=r&&!o?t:0,c=r?e.elements.map(e=>e+t):e.elements,h={};for(const t of c)h[t]=this.getters.getHeaderSize(e.sheetId,e.dimension,t);const d=[{left:o?i+a:0,right:o?n+a:this.getters.getNumberCols(e.sheetId)-1,top:o?0:i+l,bottom:o?this.getters.getNumberRows(e.sheetId)-1:n+l}],u=this.getActiveSheetId(),g=r?e.base:e.base+1,p=[{left:o?g:0,right:o?g+t-1:this.getters.getNumberCols(e.sheetId)-1,top:o?0:g,bottom:o?this.getters.getNumberRows(e.sheetId)-1:g+t-1}],m=T_.cellHandlers.getKeys().map(e=>[e,new(T_.cellHandlers.get(e))(this.getters,this.dispatch)]),f={};for(const[e,t]of m)f[e]=t.copy(C_(u,d),!1,"shiftCells");for(const[e,t]of m)f[e]&&t.paste({zones:p,sheetId:u},f[e],{isCutOperation:!0});const v=p[0],b=v.left,S=v.top;this.setSelectionMixin({zone:v,cell:{col:b,row:S}},[v]);let C=r?e.base:e.base+1;const y={};for(const t of c){const s=h[t];s!==this.getters.getHeaderSize(e.sheetId,e.dimension,C)&&(y[s]??=[],y[s].push(C)),C+=1}for(const 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:c}),this.applyFigureUpdates(s)}getFiguresUpdates(e){const t=[],s={},o=e.elements[0]<e.base?e.base-e.elements.length+1:e.base;for(let t=0;t<e.elements.length;t++)s[e.elements[t]]=o+t;for(const o of this.getters.getFigures(e.sheetId))"COL"===e.dimension&&o.col in s&&t.push({type:"UPDATE_FIGURE",sheetId:e.sheetId,figureId:o.id,col:s[o.col],row:o.row}),"ROW"===e.dimension&&o.row in s&&t.push({type:"UPDATE_FIGURE",sheetId:e.sheetId,figureId:o.id,row:s[o.row],col:o.col});return t}applyFigureUpdates(e){for(const t of e)this.dispatch(t.type,{...t})}isMoveElementAllowed(e){const t="COL"===e.dimension,s=e.elements[0],o=e.elements[e.elements.length-1],i=e.sheetId,n=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(n(i,s-1,s)||n(i,o,o+1)||n(i,e.base-1,e.base))return"WillRemoveExistingMerge";const r=[e.base,...e.elements],a=t?this.getters.getNumberCols(i):this.getters.getNumberRows(i);return r.some(e=>e<0||e>=a)?"InvalidHeaderIndex":t||this.isTableRowMoveAllowed(i,e.elements)?"Success":"CannotMoveTableHeader"}isTableRowMoveAllowed(e,t){const s=this.getters.getCoreTables(e);if(0===s.length)return!0;const o=new Set(t);return s.every(({range:{zone:e},config:s})=>{const{top:i,bottom:n}=e;if(0===s.numberOfHeaders)return!0;const r=i+s.numberOfHeaders-1;if(!t.some(e=>e>=i&&e<=r))return!0;return ge(i,n+1).every(e=>o.has(e))})}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){const e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){const{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);const{col:t,row:s}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:s})}}clipSelection(e,t){const s=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;return{zones:t.zones.map(e=>({left:ue(e.left,0,s),right:ue(e.right,0,s),top:ue(e.top,0,o),bottom:ue(e.bottom,0,o)})),anchor:{cell:{col:ue(t.anchor.cell.col,0,s),row:ue(t.anchor.cell.row,0,o)},zone:{left:ue(t.anchor.zone.left,0,s),right:ue(t.anchor.zone.right,0,s),top:ue(t.anchor.zone.top,0,o),bottom:ue(t.anchor.zone.bottom,0,o)}}}}drawLayer(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:s}=e,o=this.getSelectedZones();t.fillStyle="#f3f7fe";const i=1===o.length&&o[0].left===o[0].right&&o[0].top===o[0].bottom;t.fillStyle=i?"#f3f7fe":"#e9f0ff",t.strokeStyle=l,t.lineWidth=1.5*s;for(const e of o){const{x:s,y:o,width:i,height:n}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(s,o,i,n),t.globalCompositeOperation="source-over",t.strokeRect(s,o,i,n)}t.globalCompositeOperation="source-over";const n=this.getActivePosition();let r;t.strokeStyle=l,t.lineWidth=3*s,r=this.getters.isInMerge(n)?this.getters.getMerge(n):Zt(n);const{x:a,y:c,width:h,height:d}=this.getters.getVisibleRect(r);h>0&&d>0&&t.strokeRect(a,c,h,d)}}).add("evaluation_filter",class extends Ir{static getters=["getFilterValue","getFilterHiddenValues","getFilterCriterionValue","getFirstTableInSelection","isRowFiltered","isFilterActive"];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){if("UPDATE_FILTER"===e.type)if(!this.getters.getFilterId(e))return"FilterNotFound";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(const 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]=ae(this.filterValues[e.sheetId])}}finalize(){if(this.isEvaluationDirty){for(const e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterValue(e){const t=this.getters.getFilterId(e),s=e.sheetId;return t?this.filterValues[s]?.[t]:void 0}getFilterHiddenValues(e){const t=this.getters.getFilterId(e),s=e.sheetId;if(!t||!this.filterValues[s])return[];const o=this.filterValues[s][t]||[];return"values"===o.filterType?o.hiddenValues:[]}getFilterCriterionValue(e){const t=this.getters.getFilterId(e),s=e.sheetId;if(!t||!this.filterValues[s])return D_;const o=this.filterValues[s][t];return o&&"criterion"===o.filterType?o:D_}isFilterActive(e){const t=this.getters.getFilterId(e);if(!t)return!1;const s=e.sheetId,o=this.filterValues[s]?.[t];return!!o&&("values"===o.filterType?o.hiddenValues.length>0:"none"!==o.type)}getFirstTableInSelection(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,value:s,sheetId:o}){const i=this.getters.getFilterId({sheetId:o,col:e,row:t});i&&(this.filterValues[o]||(this.filterValues[o]={}),this.filterValues[o][i]=s)}updateHiddenRows(e){const t=this.getters.getFilters(e).sort((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top),s=new Set;for(const o of t){const t=this.filterValues[e]?.[o.id],i=o.filteredRange?.zone;if(t&&i&&!s.has(o.rangeWithHeaders.zone.top)&&!this.getters.isRowHiddenByUser(e,o.rangeWithHeaders.zone.top))if("values"===t.filterType){const n=t.hiddenValues?.map(Xb);if(!n)continue;const r=new Set(n);for(let t=i.top;t<=i.bottom;t++){const i=this.getCellValueAsString(e,o.col,t);r.has(i)&&s.add(t)}}else{if("none"===t.type)continue;const n=QT.get(t.type),r=t.values.map(t=>t.startsWith("=")?this.getters.evaluateFormula(e,t)??"":Xv(t,Oc));if(r.some(bi))continue;const a={type:t.type,values:r.map(fi),dateValue:t.dateValue};for(let t=i.top;t<=i.bottom;t++){const i={sheetId:e,col:o.col,row:t},r=this.getters.getEvaluatedCell(i).value??"";n.isValueValid(r,a,this.getters,e)||s.add(t)}}}this.hiddenRows[e]=s}getCellValueAsString(e,t,s){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:s}).formattedValue.toLowerCase()}exportForExcel(e){for(const t of e.sheets){const e=t.id;for(const s of t.tables){const o=wt(s.range),i=[],n=[];for(const s of ge(0,Ut(o).numberOfCols)){const r={sheetId:t.id,col:o.left+s,row:o.top},a=this.getFilterHiddenValues(r),l=this.getters.getFilter(r),c=l?.filteredRange?Bt(l.filteredRange.zone).map(t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue):[];if(a.length){const e=c.filter(e=>e).filter(e=>!a.includes(e));i.push({colId:s,displayedValues:[...new Set(e)],displayBlanks:!a.includes("")&&c.some(e=>!e)})}const h=this.getters.getEvaluatedCell(r).formattedValue,d=this.getUniqueColNameForExcel(s,h,n);n.push(d);const u=mt(r.col,r.row);t.cells[u]=d,t.cellValues[u]=d}s.filters=i}}}getUniqueColNameForExcel(e,t,s){return t||(t=`Column${e}`),st(t,s,{compute:(e,s)=>t+String(s),start:2})}}).add("header_visibility_ui",class extends Ir{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,s){return"COL"===t?this.isColHidden(e,s):this.isRowHidden(e,s)}getNextVisibleCellPosition({sheetId:e,col:t,row:s}){return{sheetId:e,col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",s,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,s,o){if(s<=o)for(let i=s;i<=o;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i;if(s>o)for(let i=s;i>=o;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}findLastVisibleColRowIndex(e,t,{last:s,first:o}){return ge(s,o,-1).find(s=>!this.isHeaderHidden(e,t,s))||o}findFirstVisibleColRowIndex(e,t){const s=this.getters.getNumberHeaders(e,t);for(let o=0;o<s;o++){if("COL"===t&&!this.isColHidden(e,o))return o;if("ROW"===t&&!this.isRowHidden(e,o))return o}}exportForExcel(e){for(const t of e.sheets)for(const[e,s]of Object.entries(t.rows))s.isHidden=this.isRowHidden(t.id,Number(e))}}).add("cell_computed_style",class extends Ir{static getters=["getCellComputedBorder","getCellComputedStyle"];styles=new YT;borders=new YT;handle(e){if(cr.has(e.type)||"UPDATE_CELL"===e.type||"SET_FORMATTING"===e.type||"ADD_DATA_VALIDATION_RULE"===e.type||"REMOVE_DATA_VALIDATION_RULE"===e.type||"EVALUATE_CELLS"===e.type)return this.styles=new YT,void(this.borders=new YT);d_(e)?"sheetId"in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new YT,this.borders=new YT):ur.has(e.type)?this.styles=new YT:gr.has(e.type)&&(this.borders=new YT)}getCellComputedBorder(e,t){let s=this.borders.get(e);return void 0===s&&(this.precomputeCellBorders(e.sheetId,t??Zt(e)),s=this.borders.get(e)),s??null}precomputeCellBorders(e,t){const s=this.getters.getCellBordersInZone(e,t),o=this.getters.getCellTableBorderZone(e,t);for(let i=t.left;i<=t.right;i++)for(let n=t.top;n<=t.bottom;n++){const t={sheetId:e,col:i,row:n};if(void 0!==this.borders.get(t))continue;const r=s.get(t),a={...Ve(o.get(t)),...Ve(r)};Ae(a)?this.borders.set(t,null):this.borders.set(t,a)}}getCellComputedStyle(e){let t=this.styles.get(e);return void 0===t&&(t=this.computeCellStyle(e),this.styles.set(e,t)),t}computeCellStyle(e){const t=this.getters.getCell(e),s=this.getters.getCellConditionalFormatStyle(e),o=this.getters.getCellTableStyle(e),i=this.getters.getDataValidationCellStyle(e),n={...Ve(o),...Ve(i),...Ve(t?.style),...Ve(s)};return this.getters.getEvaluatedCell(e).link&&!n.textColor&&(n.textColor=d),n}}).add("table_computed_style",class extends Ir{static getters=["getCellTableStyle","getCellTableBorder","getCellTableBorderZone"];tableStyles={};handle(e){cr.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e)||"EVALUATE_CELLS"===e.type?this.tableStyles={}:d_(e)&&("sheetId"in e?delete this.tableStyles[e.sheetId]:this.tableStyles={})}finalize(){for(const e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(const t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){const t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}getCellTableBorder(e){const t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}getCellTableBorderZone(e,t){const s=new YT;for(const o of this.getters.getTablesOverlappingZones(e,[t])){const t=this.tableStyles[e][o.id]().borders;for(const[o,i]of Object.entries(t)){const t=parseInt(o);for(const[o,n]of Object.entries(i))n&&s.set({sheetId:e,col:t,row:parseInt(o)},n)}}return s}computeTableStyle(e,t){return Oe(()=>{const{config:s,numberOfCols:o,numberOfRows:i}=this.getTableRuntimeConfig(e,t),n=AA(s,this.getters.getTableStyle(t.config.styleId),o,i),r=this.getTableMapping(e,t),a={borders:{},styles:{}};for(let e=0;e<o;e++){const t=r.colMapping[e];a.borders[t]={},a.styles[t]={};for(let s=0;s<i;s++){const o=r.rowMapping[s];a.borders[t][o]=n.borders[e][s],a.styles[t][o]=n.styles[e][s]}}return a})}getTableRuntimeConfig(e,t){const s=t.range.zone,o={...t.config};let i=s.right-s.left+1,n=s.bottom-s.top+1;for(let i=s.top;i<=s.bottom;i++)this.getters.isRowHidden(e,i)&&(n--,i-s.top<t.config.numberOfHeaders&&(o.numberOfHeaders--,o.numberOfHeaders<0&&(o.numberOfHeaders=0)),i===s.bottom&&(o.totalRow=!1));for(let t=s.left;t<=s.right;t++)this.getters.isColHidden(e,t)&&(i--,t===s.left&&(o.firstColumn=!1),t===s.right&&(o.lastColumn=!1));return{config:o,numberOfCols:i,numberOfRows:n}}getTableMapping(e,t){const s={},o={};let i=0,n=0;const r=t.range.zone;for(let t=r.left;t<=r.right;t++)if(!this.getters.isColHidden(e,t)){s[i]=t,i++;for(let t=r.top;t<=r.bottom;t++)this.getters.isRowHidden(e,t)||(o[n]=t,n++)}return{colMapping:s,rowMapping:o}}}).add("header_positions",class extends Ir{static getters=["getColDimensions","getRowDimensions","getColRowOffset"];headerPositions={};isDirty=!0;handle(e){switch(cr.has(e.type)&&(this.headerPositions={},this.isDirty=!0),e.type){case"START":for(const e of this.getters.getSheetIds())this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e);break;case"UPDATE_CELL":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]=ae(this.headerPositions[e.sheetId])}}finalize(){for(const e of this.getters.getSheetIds())!this.isDirty&&this.headerPositions[e]||(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){const s=this.headerPositions[e].COL[t],o=this.getters.getColSize(e,t);return{start:s,size:o,end:s+(this.getters.isColHidden(e,t)?0:o)}}getRowDimensions(e,t){const s=this.headerPositions[e].ROW[t],o=this.getters.getRowSize(e,t);return{start:s,size:o,end:s+(this.getters.isRowHidden(e,t)?0:o)}}getColRowOffset(e,t,s,o=this.getters.getActiveSheetId()){const i=this.headerPositions[o][e][t];return this.headerPositions[o][e][s]-i}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,"COL"),ROW:this.computePositions(e,"ROW")}}computePositions(e,t){const s={};let o=0;for(let i=0;i<this.getters.getNumberHeaders(e,t)+1;i++)s[i]=o,this.getters.isHeaderHidden(e,t,i)||(o+=this.getters.getHeaderSize(e,t,i));return s}}).add("viewport",class extends Ir{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"];viewports={};sheetViewWidth=Y();sheetViewHeight=Y();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){const t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let{col:s,row:o}=qt(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const i=e.previousAnchor.zone,n=e.anchor.zone,{top:r,bottom:a,left:l,right:c}=this.getMainInternalViewport(t);i.left===n.left&&i.right===n.right&&(s=l>s||s>c?l:s),i.top===n.top&&i.bottom===n.bottom&&(o=r>o||o>a?r:o)}s=Math.min(s,this.getters.getNumberCols(t)-1),o=Math.min(o,this.getters.getNumberRows(t)-1),this.sheetsWithDirtyViewports.has(t)||this.refreshViewport(this.getters.getActiveSheetId(),{col:s,row:o})}}handle(e){if(cr.has(e.type))for(const 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(const 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":const t=this.getters.getActiveSheetId(),{top:s,viewportHeight:o,offsetCorrectionY:i}=this.getMainInternalViewport(t),n=this.getters.getRowDimensions(t,s);this.shiftVertically(n.start+o-i);break;case"SHIFT_VIEWPORT_UP":{const e=this.getters.getActiveSheetId(),{top:t,viewportHeight:s,offsetCorrectionY:o}=this.getMainInternalViewport(e),i=this.getters.getRowDimensions(e,t);this.shiftVertically(i.end-o-s);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":if("content"in e||"format"in e||void 0!==e.style?.fontSize)for(const 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})}}finalize(){for(const e of this.sheetsWithDirtyViewports)if(this.resetViewports(e),this.shouldAdjustViewports){const t=this.getters.getSheetPosition(e);this.getSubViewports(e).forEach(e=>{e.adjustPosition(t)})}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){const e=this.getters.getSheetIds();for(const t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getColIndex(e)))}getRowIndex(e){const 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(){const e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getSheetViewVisibleCols(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>ge(e.left,e.right+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,"COL",t))}getSheetViewVisibleRows(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>ge(e.top,e.bottom+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,"ROW",t))}getVisibleCellPositions(){const e=this.getSheetViewVisibleCols(),t=this.getSheetViewVisibleRows(),s=this.getters.getActiveSheetId(),o=[];for(const i of e)for(const e of t){const t={sheetId:s,col:i,row:e},n=this.getters.getMainCellPosition(t);n.row===e&&n.col===i&&o.push(t)}return o}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:s,ySplit:o}=this.getters.getPaneDivisions(e),{width:i,height:n}=t.getMaxSize();return{x:this.getters.getColDimensions(e,s).start,y:this.getters.getRowDimensions(e,o).start,width:i,height:n}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:s}=this.getMainViewportRect(),o=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-o.viewportWidth),maxOffsetY:Math.max(0,s-o.viewportHeight)}}getColRowOffsetInViewport(e,t,s){if(s<t)return-this.getColRowOffsetInViewport(e,s,t);const o=this.getters.getActiveSheetId(),i="COL"===e?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),n=i.findIndex(e=>t>=e);let r=i.findIndex(e=>s<=e);r=-1===r?i.length:r;const a=i.slice(n,r);let l=0;for(const t of a)l+=this.getters.getHeaderSize(o,e,t);return l}isVisibleInViewport({sheetId:e,col:t,row:s}){return this.getSubViewports(e).some(e=>e.isVisible(t,s))}getEdgeScrollCol(e,t,s){let o=!1,i=0,n=0;const{xSplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(o=!0,n=db(e-a),i=1):e<l&&s>=l&&c>0?(o=!0,n=db(l-e),i=-1):r&&t<l&&e>l&&(o=!0,n=db(e),i="reset"),{canEdgeScroll:o,direction:i,delay:n}}getEdgeScrollRow(e,t,s){let o=!1,i=0,n=0;const{ySplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(o=!0,n=db(e-a),i=1):e<l&&s>=l&&c>0?(o=!0,n=db(l-e),i=-1):r&&t<l&&e>l&&(o=!0,n=db(e),i="reset"),{canEdgeScroll:o,direction:i,delay:n}}getVisibleRect(e){const t=this.getVisibleRectWithoutHeaders(e);return{...t,x:t.x+this.gridOffsetX,y:t.y+this.gridOffsetY}}getVisibleRectWithoutHeaders(e){const t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getVisibleRect(e))}getRect(e){const t=this.getters.getActiveSheetId(),s=this.mapViewportsToRect(t,t=>t.getFullRect(e));return{...s,x:s.x+this.gridOffsetX,y:s.y+this.gridOffsetY}}getRectWithoutHeaders(e){const t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getFullRect(e))}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:s}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,s).start}}getColDimensionsInViewport(e,t){const{top:s}=this.getMainInternalViewport(e),o={left:t,right:t,top:s,bottom:s},{x:i,width:n}=this.getVisibleRect(o),r=i-this.gridOffsetX;return{start:r,size:n,end:r+n}}getRowDimensionsInViewport(e,t){const{left:s}=this.getMainInternalViewport(e),o={left:0,right:s,top:t,bottom:t},{y:i,height:n}=this.getVisibleRect(o),r=i-this.gridOffsetY;return{start:r,size:n,end:r+n}}getAllActiveViewportsZonesAndRect(){const 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(Te)}checkPositiveDimension(e){return e.width<0||e.height<0?"InvalidViewportSize":"Success"}checkValuesAreDifferent(e){const{height:t,width:s}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===s&&e.height===t?"ValuesNotChanged":"Success"}checkScrollingDirection({offsetX:e,offsetY:t}){const s=this.getMainInternalViewport(this.getters.getActiveSheetId());return!s.canScrollHorizontally&&e>0||!s.canScrollVertically&&t>0?"InvalidScrollingDirection":"Success"}checkIfViewportsWillChange({offsetX:e,offsetY:t}){const s=this.getters.getActiveSheetId(),{maxOffsetX:o,maxOffsetY:i}=this.getMaximumSheetOffset();return this.getSubViewports(s).some(s=>s.willNewOffsetScrollViewport(ue(e,0,o),ue(t,0,i)))?"Success":"ViewportScrollLimitsReached"}getMainViewport(e){const 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(){const e={};for(const t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,s=0,o=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=s,this.gridOffsetY=o,this.recomputeViewports()}recomputeViewports(){for(const e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){const s=this.getters.getActiveSheetId(),{maxOffsetX:o,maxOffsetY:i}=this.getMaximumSheetOffset();this.getSubViewports(s).forEach(s=>s.setViewportOffset(ue(e,0,o),ue(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;const{xSplit:t,ySplit:s}=this.getters.getPaneDivisions(e),o=this.getters.getNumberCols(e),i=this.getters.getNumberRows(e),n=Math.min(this.getters.getColRowOffset("COL",0,t,e),this.sheetViewWidth),r=Math.min(this.getters.getColRowOffset("ROW",0,s,e),this.sheetViewHeight),a=Math.max(this.sheetViewWidth-n,0),l=Math.max(this.sheetViewHeight-r,0),{xRatio:c,yRatio:h}=this.getFrozenSheetViewRatio(e),d=c<1,u=h<1,g=this.getViewportOffset(e),p={topLeft:s&&t&&new __(this.getters,e,{left:0,right:t-1,top:0,bottom:s-1},{width:n,height:r},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:s&&new __(this.getters,e,{left:t,right:o-1,top:0,bottom:s-1},{width:a,height:r},{canScrollHorizontally:d,canScrollVertically:!1},{x:d?g.x:0,y:0})||void 0,bottomLeft:t&&new __(this.getters,e,{left:0,right:t-1,top:s,bottom:i-1},{width:n,height:l},{canScrollHorizontally:!1,canScrollVertically:u},{x:0,y:u?g.y:0})||void 0,bottomRight:new __(this.getters,e,{left:t,right:o-1,top:s,bottom:i-1},{width:a,height:l},{canScrollHorizontally:d,canScrollVertically:u},{x:d?g.x:0,y:u?g.y:0})};this.viewports[e]=p}refreshViewport(e,t){this.getSubViewports(e).forEach(e=>{e.adjustViewportZone(),e.adjustPosition(t)})}shiftVertically(e){const t=this.getters.getActiveSheetId(),{top:s}=this.getMainInternalViewport(t),{scrollX:o}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(o,e);const{anchor:i}=this.getters.getSelection();if(i.cell.row>=this.getters.getPaneDivisions(t).ySplit){const e=this.getMainInternalViewport(t).top-s;this.selection.selectCell(i.cell.col,i.cell.row+e)}}getColIndexLeftOfMainViewport(e){if(e>=0)return-1;const t=this.getters.getActiveSheetId();let s=this.getActiveMainViewport().left,o=-this.getActiveSheetScrollInfo().scrollX-this.getters.getColRowOffset("COL",s,0);for(;e<o;s--)o-=this.getters.getColSize(t,s-1);return Math.max(s,0)}getRowIndexTopOfMainViewport(e){if(e>=0)return-1;const t=this.getters.getActiveSheetId();let s=this.getActiveMainViewport().top,o=-this.getActiveSheetScrollInfo().scrollY-this.getters.getColRowOffset("ROW",s,0);for(;e<o;s--)o-=this.getters.getRowSize(t,s-1);return Math.max(s,0)}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],s=this.getters.getFigures(e),{scrollX:o,scrollY:i}=this.getters.getActiveSheetScrollInfo(),{x:n,y:r}=this.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const c of s){const s=this.getFigureUI(e,c),{x:h,y:d}=s;h>=n&&(h+c.width<o+n||h>a+o+n)||(d>=r&&(d+c.height<i+r||d>l+i+r)||t.push(s))}return t}getFigureUI(e,t){const s=t.offset.x+this.getters.getColDimensions(e,t.col).start,o=t.offset.y+this.getters.getRowDimensions(e,t.row).start;return{...t,x:s,y:o}}getPositionAnchorOffset(e){const{scrollX:t,scrollY:s}=this.getters.getActiveSheetScrollInfo(),o=e.x-t,i=e.y-s,n=o>=0?this.getColIndex(o):this.getColIndexLeftOfMainViewport(o),r=i>=0?this.getRowIndex(i):this.getRowIndexTopOfMainViewport(i),{x:a,y:l}=this.getRect(Zt({col:n,row:r}));return{col:n,row:r,offset:{x:Math.max(o-a+this.gridOffsetX,0),y:Math.max(i-l+this.gridOffsetY,0)}}}isPixelPositionVisible(e){const{scrollX:t,scrollY:s}=this.getters.getActiveSheetScrollInfo(),{x:o,y:i}=this.getters.getMainViewportCoordinates(),{width:n,height:r}=this.getters.getSheetViewDimension();return!(e.x>=o&&(e.x<o+t||e.x>n+t+o))&&!(e.y>=i&&(e.y<i+s||e.y>r+s+i))}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:s}=this.getters.getPaneDivisions(e),o=this.getters.getColDimensions(e,t).start,i=this.getters.getRowDimensions(e,s).start;return{xRatio:o/(this.sheetViewWidth+this.gridOffsetX),yRatio:i/(this.sheetViewHeight+this.gridOffsetY)}}mapViewportsToRect(e,t){let s=1/0,o=1/0,i=0,n=0,r=!1;for(const a of this.getSubViewports(e)){const e=t(a);e&&(r=!0,s=Math.min(s,e.x),o=Math.min(o,e.y),i=Math.max(i,e.x+e.width),n=Math.max(n,e.y+e.height))}return r?{x:s,y:o,width:i-s,height:n-o}:{x:0,y:0,width:0,height:0}}}).add("clipboard",class extends Ir{static layers=["Clipboard"];static getters=["getClipboardTextAndImageContent","getClipboardId","getClipboardTextContent","isCutOperation"];status="invisible";originSheetId;copiedData;_isCutOperation=!1;clipboardId=(new lr).uuidv4();fileStore;uuidGenerator;constructor(e){super(e),this.fileStore=e.external.fileStore,this.uuidGenerator=new lr}allowDispatch(e){switch(e.type){case"CUT":const t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case"PASTE_FROM_OS_CLIPBOARD":{const t=this.convertTextToClipboardData(e.clipboardContent.text??""),s=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:s,isCutOperation:!1})}case"PASTE":{if(!this.copiedData)return"EmptyClipboard";const t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case"COPY_PASTE_CELLS_ABOVE":{const e=this.getters.getSelectedZones();if(e.length>1||0===e[0].top&&0===e[0].bottom)return"InvalidCopyPasteSelection";break}case"COPY_PASTE_CELLS_ON_LEFT":{const e=this.getters.getSelectedZones();if(e.length>1||0===e[0].left&&0===e[0].right)return"InvalidCopyPasteSelection";break}case"INSERT_CELL":{const{cut:t,paste:s}=this.getInsertCellsTargets(e.zone,e.shiftDimension),o=this.copy(t,"shiftCells");return this.isPasteAllowed(s,o,{isCutOperation:!0})}case"DELETE_CELL":{const{cut:t,paste:s}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),o=this.copy(t,"shiftCells");return this.isPasteAllowed(s,o,{isCutOperation:!0})}}return"Success"}handle(e){switch(e.type){case"COPY":case"CUT":const t=this.getters.getSelectedZones();this.status="visible",this.originSheetId=this.getters.getActiveSheetId(),this._isCutOperation="CUT"===e.type,this.copiedData=this.copy(t);break;case"PASTE_FROM_OS_CLIPBOARD":{this._isCutOperation=!1;const t=e.clipboardContent.data;if(e.clipboardContent.imageData){const t=this.getters.getActiveSheetId(),s=this.uuidGenerator.uuidv4(),o=e.clipboardContent.imageData,i=xy(this.getters,o.size);this.dispatch("CREATE_IMAGE",{definition:o,size:i,col:e.target[0].left,row:e.target[0].top,offset:{x:0,y:0},sheetId:t,figureId:s})}this.copiedData=t||this.convertTextToClipboardData(e.clipboardContent.text??"");const s=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:s,selectTarget:!0,isCutOperation:!1}),this.status="invisible",this.copiedData=void 0;break}case"PASTE":{const 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,this._isCutOperation=!1);break}case"COPY_PASTE_CELLS_ABOVE":{const e=this.getters.getSelectedZone(),t=e.top!==e.bottom,s={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};this.originSheetId=this.getters.getActiveSheetId();const o=this.copy([s]);this.paste([e],o,{isCutOperation:!1,selectTarget:!0})}break;case"COPY_PASTE_CELLS_ON_LEFT":{const e=this.getters.getSelectedZone(),t=e.left!==e.right,s={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};this.originSheetId=this.getters.getActiveSheetId();const o=this.copy([s]);this.paste([e],o,{isCutOperation:!1,selectTarget:!0})}break;case"CLEAN_CLIPBOARD_HIGHLIGHT":this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:s}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!Rt(t[0])){this.dispatch("CLEAR_CELLS",{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}const o=this.copy(t,"shiftCells");this.paste(s,o,{isCutOperation:!0});break}case"INSERT_CELL":{const{cut:t,paste:s}=this.getInsertCellsTargets(e.zone,e.shiftDimension),o=this.copy(t,"shiftCells");this.paste(s,o,{isCutOperation:!0});break}case"ADD_COLUMNS_ROWS":if(this.status="invisible",!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard("before"===e.position?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(const 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:vr(e)&&(this.status="invisible")}}convertTextToClipboardData(e){const t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({})),s={};for(const{handlerName:o,handler:i}of t){const t=i.convertTextToClipboardData(e);s[o]=t;const n=["sheetId","cells","zones","figureId"];for(const e of n)t&&e in t&&(s[e]=t[e])}return s}selectClipboardHandlers(e){const t="figureId"in e?T_.figureHandlers:T_.cellHandlers;return t.getKeys().map(e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)}))}isCutAllowedOn(e){const t=this.getClipboardData(e);for(const{handler:e}of this.selectClipboardHandlers(t)){const s=e.isCutAllowed(t);if("Success"!==s)return s}return"Success"}isPasteAllowed(e,t,s){for(const{handler:o}of this.selectClipboardHandlers(t)){const i=o.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...s});if("Success"!==i)return i}return"Success"}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;const{zones:s}=this.copiedData;for(const o of s){if("COL"===t&&e<=o.right)return!0;if("ROW"===t&&e<=o.bottom)return!0}return!1}copy(e,t="copyPaste"){const s={},o=this.getClipboardData(e);for(const{handlerName:e,handler:i}of this.selectClipboardHandlers(o)){const n=i.copy(o,this._isCutOperation,t);s[e]=n;const r=["sheetId","cells","zones","figureId"];for(const e of r)n&&e in n&&(s[e]=n[e])}return s}paste(e,t,s){if(!t)return;const o=this.getters.getActiveSheetId(),i=this.selectClipboardHandlers(t),{target:n,zone:r,selectedZones:a}=R_(o,e,t,i,s);void 0!==r&&this.addMissingDimensions(o,r.right-r.left+1,r.bottom-r.top+1,r.left,r.top),E_(i,t,n,s),s?.selectTarget&&x_(this.selection,e,a)}addMissingDimensions(e,t,s,o,i){const n=s+i-this.getters.getNumberRows(e);n>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:n,position:"after"});const r=t+o-this.getters.getNumberCols(e);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:r,position:"after"})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}async getClipboardTextAndImageContent(){const e=await this.getImageContent(),t=e?.type,s={[gI.PlainText]:this.getPlainTextContent(),[gI.Html]:await this.getHTMLContent()};return t&&e&&(s[t]=e),s}getSheetData(){const e={version:VT(),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("\t")).join("\n")||"\t"}async getHTMLContent(){let e="";const t=this.copiedData?.cells;if(t)if(1===t.length&&1===t[0].length)e=`${this.getters.getCellText(t[0][0].position)}`;else{if(!t[0][0])return"";{let s='<table border="1" style="border-collapse:collapse">';for(const e of t){s+="<tr>";for(const t of e){if(!t)continue;s+=`<td style="${Ey(Iy(this.getters.getCellComputedStyle(t.position)))}">`+aT(this.getters.getCellText(t.position))+"</td>"}s+="</tr>"}s+="</table>",e=s}}else if(this.copiedData?.figureId){const t=this.copiedData.figureId,s=this.getters.getFigureSheetId(t);e="image"===this.getters.getFigure(s,t).tag?await this.craftImageHTML(t):"\t"}else e="\t";return`<div data-osheet-clipboard='${aT(JSON.stringify(this.getSheetData()))}'>${e}</div>`}readFileAsDataURL(e){return new Promise(t=>{const s=new FileReader;s.onload=()=>t(s.result),s.readAsDataURL(e)})}async craftImageHTML(e){if(!this.fileStore)return"\t";const t=this.getters.getImage(e).path,s=await(this.fileStore?.getFile(t))||null;if(s){return`<img src="${aT(await this.readFileAsDataURL(s))}" />`}return"\t"}async getImageContent(){const e=this.copiedData?.figureId;if(!e)return;const t=this.getters.getFigureSheetId(e);let s;if("image"===this.getters.getFigure(t,e).tag){if(!this.fileStore)return;const t=this.getters.getImage(e).path;if(s=await(this.fileStore?.getFile(t)),"image/png"!==s.type){if(s.size>A_)return void this.ui.notifyUI({text:fs("The file you are trying to copy is too large (>%sMB).\nIt will not be added to your OS clipboard.\nYou can download it directly instead.",Math.round(5)),sticky:!1,type:"warning"});s=await async function(e){return new Promise((t,s)=>{const o=new Image;o.addEventListener("load",()=>{const e=document.createElement("canvas");e.width=o.width,e.height=o.height;const s=e.getContext("2d");s?.drawImage(o,0,0),e.toBlob(t,"image/png")}),o.addEventListener("error",s),o.src=e})}(t)}}return s?s instanceof File?s:new File([s],"image.png",{type:"image/png"}):void 0}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){const s=this.getters.getActiveSheetId();let o;return o="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(s)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(s)-1},{cut:[o],paste:[e]}}getInsertCellsTargets(e,t){const s=this.getters.getActiveSheetId();let o,i;return"COL"===t?(o={...e,right:this.getters.getNumberCols(s)-1},i={...e,left:e.right+1,right:e.right+1}):(o={...e,bottom:this.getters.getNumberRows(s)-1},i={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(s)-1}),{cut:[o],paste:[i]}}getClipboardData(e){const t=this.getters.getActiveSheetId(),s=this.getters.getSelectedFigureId();if(s)return{figureId:s,sheetId:t};const o=C_(t,e);return this._isCutOperation||(o.rowsIndexes=o.rowsIndexes.filter(e=>!this.getters.isRowFiltered(t,e))),o}drawLayer(e){if("visible"!==this.status||!this.copiedData)return;const{sheetId:t,zones:s}=this.copiedData;if(t!==this.getters.getActiveSheetId()||!s||!s.length)return;const{ctx:o,thinLineWidth:i}=e;o.setLineDash([8,5]),o.strokeStyle=l,o.lineWidth=3.3*i;for(const e of s){const{x:t,y:s,width:i,height:n}=this.getters.getVisibleRect(e);i>0&&n>0&&o.strokeRect(t,s,i,n)}}}).add("carousel_ui",class extends Ir{static getters=["getSelectedCarouselItem","getChartFromFigureId","getChartIdFromFigureId"];uuidGenerator=new lr;carouselStates={};allowDispatch(e){switch(e.type){case"ADD_FIGURE_CHART_TO_CAROUSEL":return this.getters.doesCarouselExist(e.carouselFigureId)&&"chart"===this.getters.getFigure(e.sheetId,e.chartFigureId)?.tag?"Success":"InvalidFigureId";case"ADD_NEW_CHART_TO_CAROUSEL":return this.getters.doesCarouselExist(e.figureId)?"Success":"InvalidFigureId";case"UPDATE_CAROUSEL_ACTIVE_ITEM":return this.getters.doesCarouselExist(e.figureId)?this.getters.getCarousel(e.figureId).items.some(t=>Me(t,e.item))?"Success":"InvalidCarouselItem":"InvalidFigureId"}return"Success"}handle(e){switch(e.type){case"ADD_NEW_CHART_TO_CAROUSEL":this.addNewChartToCarousel(e.figureId,e.sheetId);break;case"ADD_FIGURE_CHART_TO_CAROUSEL":this.addFigureChartToCarousel(e.carouselFigureId,e.chartFigureId,e.sheetId);break;case"UPDATE_CAROUSEL_ACTIVE_ITEM":this.carouselStates[e.figureId]=this.getCarouselItemId(e.item);break;case"POPOUT_CHART_FROM_CAROUSEL":this.popOutChartFromCarousel(e.carouselId,e.chartId,e.sheetId);break;case"DELETE_FIGURE":delete this.carouselStates[e.figureId];break;case"UPDATE_CAROUSEL":this.fixWrongCarouselState(e.figureId);break;case"DELETE_CHART":case"UNDO":case"REDO":case"DELETE_SHEET":for(const e in this.carouselStates)this.fixWrongCarouselState(e)}}popOutChartFromCarousel(e,t,s){const o=this.getters.getCarousel(e);if(!o)return;const i=this.getters.getFigure(s,e),n=this.getters.getChartDefinition(t);if(!n||!i)return;const r=this.getters.getFigureUI(s,i),a=this.getters.getPositionAnchorOffset({x:r.x+50,y:r.y+50}),l=this.uuidGenerator.smallUuid();this.dispatch("CREATE_CHART",{...a,chartId:this.uuidGenerator.smallUuid(),figureId:l,sheetId:s,size:{width:i.width,height:i.height},definition:{...n}});const c=o.items.filter(e=>"chart"!==e.type||e.chartId!==t);this.dispatch("UPDATE_CAROUSEL",{sheetId:s,figureId:e,definition:{...o,items:c}}),this.dispatch("SELECT_FIGURE",{figureId:l})}getSelectedCarouselItem(e){const t=this.getters.getCarousel(e);if(t.items.length)return this.carouselStates[e]?t.items.find(t=>this.getCarouselItemId(t)===this.carouselStates[e]):t.items[0]}getChartFromFigureId(e){if(!this.getters.getFigureSheetId(e))return;const t=this.getChartIdFromFigureId(e);return t?this.getters.getChart(t):void 0}getChartIdFromFigureId(e){const t=this.getters.getFigureSheetId(e);if(!t)return;const s=this.getters.getFigure(t,e);if(s&&("chart"===s.tag||"carousel"===s.tag)){if("carousel"===s.tag){const t=this.getSelectedCarouselItem(e);return"chart"===t?.type?t.chartId:void 0}return this.getters.getChartIds(t).find(t=>this.getters.getFigureIdFromChartId(t)===e)}}fixWrongCarouselState(e){if(!this.getters.doesCarouselExist(e))return void delete this.carouselStates[e];const t=this.getters.getCarousel(e);0===t.items.length?delete this.carouselStates[e]:this.carouselStates[e]&&t.items.some(t=>this.getCarouselItemId(t)===this.carouselStates[e])||(this.carouselStates[e]=this.getCarouselItemId(t.items[0]))}addNewChartToCarousel(e,t){const s=this.getters.getCarousel(e),o=this.uuidGenerator.smallUuid();this.dispatch("CREATE_CHART",{chartId:o,figureId:e,sheetId:t,definition:v_});const i={...s,items:[...s.items,{type:"chart",chartId:o}]};this.dispatch("UPDATE_CAROUSEL",{sheetId:t,figureId:e,definition:i})}addFigureChartToCarousel(e,t,s){const o=this.getChartIdFromFigureId(t);if(!o)return;const i=this.getters.getCarousel(e),n={...i,items:[...i.items,{type:"chart",chartId:o}]};this.dispatch("UPDATE_CAROUSEL",{sheetId:s,figureId:e,definition:n}),this.dispatch("UPDATE_CHART",{sheetId:s,chartId:o,figureId:e,definition:this.getters.getChartDefinition(o)}),this.dispatch("DELETE_FIGURE",{sheetId:s,figureId:t})}getCarouselItemId(e){return"chart"===e.type?e.chartId:"carouselDataView"}}),M_=(new is).add("evaluation",class extends MA{static getters=["evaluateFormula","evaluateFormulaResult","evaluateCompiledFormula","getCorrespondingFormulaCell","getRangeFormattedValues","getRangeValues","getRangeFormats","getEvaluatedCell","getEvaluatedCells","getEvaluatedCellsInZone","getEvaluatedCellsPositions","getSpreadZone","getArrayFormulaSpreadingOn","isEmpty"];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new gD(e.custom,this.getters)}beforeHandle(e){(cr.has(e.type)||dr.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case"UPDATE_CELL":if(!("content"in e)&&!("format"in e)||this.shouldRebuildDependenciesGraph)return;const 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":if(e.cellIds)for(let t=0;t<e.cellIds.length;t++)this.positionsToUpdate.push(this.getters.getCellPosition(e.cellIds[t]));else this.evaluator.evaluateAllCells()}}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){const s=this.evaluateFormulaResult(e,t);return Ds(s)?Vo(s,e=>e.value):s.value}evaluateFormulaResult(e,t){return this.evaluator.evaluateFormulaResult(e,t)}evaluateCompiledFormula(e,t,s){return this.evaluator.evaluateCompiledFormula(e,t,s)}getRangeFormattedValues(e){return void 0===this.getters.tryGetSheet(e.sheetId)?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).formattedValue)}getRangeValues(e){return void 0===this.getters.tryGetSheet(e.sheetId)?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).value)}getRangeFormats(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]: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 Bt(t).map(({col:t,row:s})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:s}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isEmpty(e,t){return Bt(t).map(({col:t,row:s})=>this.getEvaluatedCell({sheetId:e,col:t,row:s})).every(e=>e.type===_d.empty)}mapVisiblePositions(e,t){const{sheetId:s,zone:o}=e;return Bt(o).reduce((e,o)=>{const{col:i,row:n}=o;return this.getters.isColHidden(s,i)||this.getters.isRowHidden(s,n)||e.push(t({sheetId:s,...o})),e},[])}exportForExcel(e){for(const t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(const t of this.evaluator.getEvaluatedPositions()){const s=this.evaluator.getEvaluatedCell(t),o=mt(t.col,t.row),i=s.value;let n,r=!1,a=!0;const l=e.sheets.find(e=>e.id===t.sheetId),c=this.getCorrespondingFormulaCell(t);if(c){const h=this.getters.getCell(t);if(a=Lf(c.compiledFormula.tokens),r=a&&h?.content===c.content,!a&&""!==i){n=(i??"").toString();const t=s.format;if(t){const s=ab(t,e.formats);l.formats[o]=s}}}const h=l.cells[o];let d;d=a&&r&&c instanceof KT?c.contentWithFixedReferences:a?h:n,l.cells[o]=d,l.cellValues[o]="error"!==s.type?i:void 0;const u=this.getSpreadZone(t);u&&(l.formulaSpillRanges[o]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,u),t.sheetId))}}getCorrespondingFormulaCell(e){const t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;const s=this.getArrayFormulaSpreadingOn(e);if(void 0===s)return;const o=this.getters.getCell(s);return o?.isFormula?o:void 0}}).add("evaluation_chart",class extends MA{static getters=["getChartRuntime","getStyleOfSingleCellChart"];charts={};createRuntimeChart=Zy(this.getters);handle(e){if(cr.has(e.type)||ur.has(e.type)||hr.has(e.type))for(const e in this.charts)this.charts[e]=void 0;switch(e.type){case"UPDATE_CHART":case"CREATE_CHART":case"DELETE_CHART":this.charts[e.chartId]=void 0;break;case"DELETE_SHEET":for(const e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0)}}getChartRuntime(e){if(!this.charts[e]){const t=this.getters.getChart(e);if(!t)throw new 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:nC(e)};if(!t)return{background:c,fontColor:nC(c)};const s=t.zone.left,o=t.zone.top,i=t.sheetId,n=this.getters.getCellComputedStyle({sheetId:i,col:s,row:o}),r=n.fillColor||c;return{background:r,fontColor:n.textColor||nC(r)}}async exportForExcel(e){for(const t of e.sheets){t.images||(t.images=[]);const e=this.getters.getFigures(t.id),s=[];for(const o of e){if(!o||"chart"!==o.tag)continue;const e=this.getters.getChartIds(t.id).find(e=>this.getters.getFigureIdFromChartId(e)===o.id);if(!e)continue;const i=this.getters.getChart(e),n=i?.getDefinitionForExcel(this.getters);if(n)s.push({...o,data:n});else{if(!i)continue;const s=this.getters.getChartType(e),n=this.getters.getChartRuntime(e),r=await rI(n,o,s);r&&t.images.push({...o,tag:"image",data:{mimetype:"image/png",path:r,size:{width:o.width,height:o.height}}})}}t.charts=s}}}).add("evaluation_cf",class extends MA{static getters=["getConditionalIcon","getCellConditionalFormatStyle","getConditionalDataBar"];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(cr.has(e.type)||ur.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(const e of this.getters.getSheetIds())this.computedStyles[e]=Oe(()=>this.getComputedStyles(e)),this.computedIcons[e]=Oe(()=>this.getComputedIcons(e)),this.computedDataBars[e]=Oe(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){const{sheetId:t,col:s,row:o}=e,i=this.computedStyles[t]();return i&&i[s]?.[o]}getConditionalIcon({sheetId:e,col:t,row:s}){const o=this.computedIcons[e]();return o&&o[t]?.[s]}getConditionalDataBar({sheetId:e,col:t,row:s}){const o=this.computedDataBars[e]();return o&&o[t]?.[s]}getComputedStyles(e){const t={};for(const s of this.getters.getConditionalFormats(e).reverse())switch(s.rule.type){case"ColorScaleRule":for(const o of s.ranges)this.applyColorScale(e,o,s.rule,t);break;case"CellIsRule":const o=s.rule.values.map(e=>e.startsWith("=")?sE(e):void 0);for(const i of s.ranges){const n=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=n.top;i<=n.bottom;i++)for(let r=n.left;r<=n.right;r++){const a={sheetId:e,col:r,row:i},l=s.rule.values.map((t,s)=>{const a=o[s];return a?this.getters.getTranslatedCellFormula(e,r-n.left,i-n.top,a.tokens):t});this.getRuleResultForTarget(a,{...s.rule,values:l})&&(t[r]||(t[r]=[]),t[r][i]=Object.assign(t[r]?.[i]||{},s.rule.style))}}}return t}getComputedIcons(e){const t={};for(const s of this.getters.getConditionalFormats(e).reverse())if("IconSetRule"===s.rule.type)for(const o of s.ranges)this.applyIcon(e,o,s.rule,t);return t}getComputedDataBars(e){const t={};for(const s of this.getters.getConditionalFormats(e).reverse())if("DataBarRule"===s.rule.type)for(const o of s.ranges)this.applyDataBar(e,o,s.rule,t);return t}parsePoint(e,t,s,o){const i=this.getters.getEvaluatedCellsInZone(e,this.getters.getRangeFromSheetXC(e,t).zone).filter(e=>e.type===_d.number).map(e=>e.value);switch(s.type){case"value":return"max"===o?Ke(i):Je(i);case"number":return Number(s.value);case"percentage":const t=Je(i);return t+(Ke(i)-t)*Number(s.value)/100;case"percentile":return uo(i,Number(s.value)/100,!0);case"formula":const n=s.value&&this.getters.evaluateFormula(e,s.value);return"number"==typeof n?n:null;default:return null}}applyIcon(e,t,s,o){const i=this.parsePoint(e,t,s.lowerInflectionPoint),n=this.parsePoint(e,t,s.upperInflectionPoint);if(null===i||null===n||i>n)return;const r=this.getters.getRangeFromSheetXC(e,t).zone,a=[s.icons.upper,s.icons.middle,s.icons.lower];for(let t=r.top;t<=r.bottom;t++)for(let l=r.left;l<=r.right;l++){const r=this.getters.getEvaluatedCell({sheetId:e,col:l,row:t});if(r.type!==_d.number)continue;const c=this.computeIcon(r.value,n,s.upperInflectionPoint.operator,i,s.lowerInflectionPoint.operator,a);o[l]||(o[l]=[]),o[l][t]=c}}computeIcon(e,t,s,o,i,n){return"ge"===s&&e>=t||"gt"===s&&e>t?n[0]:"ge"===i&&e>=o||"gt"===i&&e>o?n[1]:n[2]}applyDataBar(e,t,s,o){const i=this.getters.getRangeFromSheetXC(e,s.rangeValues||t),n=Ke(this.getters.getEvaluatedCellsInZone(e,i.zone).filter(e=>e.type===_d.number).map(e=>e.value));if(n<=0)return;const r=s.color,a=this.getters.getRangeFromSheetXC(e,t).zone,l=i.zone;for(let t=a.top;t<=a.bottom;t++)for(let s=a.left;s<=a.right;s++){const i=s-a.left+l.left,c=t-a.top+l.top,h=this.getters.getEvaluatedCell({sheetId:e,col:i,row:c});!kt(i,c,l)||h.type!==_d.number||h.value<=0||(o[s]||(o[s]=[]),o[s][t]={color:fv(r),percentage:100*h.value/n})}}applyColorScale(e,t,s,o){const i=this.parsePoint(e,t,s.minimum,"min"),n=s.midpoint?this.parsePoint(e,t,s.midpoint):null,r=this.parsePoint(e,t,s.maximum,"max");if(null===i||null===r||i>=r||n&&(i>=n||n>=r))return;const a=this.getters.getRangeFromSheetXC(e,t).zone,l=[{value:i,color:s.minimum.color}];s.midpoint&&n&&l.push({value:n,color:s.midpoint.color}),l.push({value:r,color:s.maximum.color});const c=qv(l);for(let t=a.top;t<=a.bottom;t++)for(let s=a.left;s<=a.right;s++){const n=this.getters.getEvaluatedCell({sheetId:e,col:s,row:t});if(n.type===_d.number){const e=ue(n.value,i,r);o[s]||(o[s]=[]),o[s][t]=o[s]?.[t]||{},o[s][t].fillColor=c(e)}}}getRuleResultForTarget(e,t){const s=this.getters.getEvaluatedCell(e);if(s.type===_d.error)return!1;const{sheetId:o}=e,i=QT.get(t.operator),n=t.values.map(e=>e.startsWith("=")?this.getters.evaluateFormula(o,e)??"":Xv(e,Oc));if(n.some(bi))return!1;const r={type:t.operator,values:n.map(fi)};return i.isValueValid(s.value??"",r,this.getters,o)}}).add("row_size",class extends MA{static getters=["getRowSize","getHeaderSize","getMaxAnchorOffset"];tallestCellInRow={};ctx=kb();beforeHandle(e){if("ADD_COLUMNS_ROWS"===e.type){if("COL"===e.dimension)return;const t=Pe(e.position,e.base),s=Array(e.quantity).fill(void 0),o=Ze(this.tallestCellInRow[e.sheetId],s,t);this.history.update("tallestCellInRow",e.sheetId,o)}}handle(e){switch(e.type){case"START":for(const e of this.getters.getSheetIds())this.initializeSheet(e);break;case"CREATE_SHEET":this.initializeSheet(e.sheetId);break;case"DUPLICATE_SHEET":{const t=ae(this.tallestCellInRow[e.sheetId]);this.history.update("tallestCellInRow",e.sheetIdTo,t);break}case"DELETE_SHEET":const t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update("tallestCellInRow",t);break;case"REMOVE_COLUMNS_ROWS":{if("COL"===e.dimension)return;const t=qe(this.tallestCellInRow[e.sheetId],e.elements);this.history.update("tallestCellInRow",e.sheetId,t);break}case"RESIZE_COLUMNS_ROWS":{const t=e.sheetId;if("ROW"===e.dimension)for(const s of e.elements){const e=this.getRowTallestCell(t,s);this.history.update("tallestCellInRow",t,s,e)}else for(const s of ge(0,this.getters.getNumberRows(t)))for(const o of e.elements)this.updateRowSizeForCellChange(t,s,o)}break;case"UPDATE_CELL":this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case"ADD_MERGE":case"REMOVE_MERGE":for(const t of e.target)for(const s of Bt(t))this.updateRowSizeForCellChange(e.sheetId,s.row,s.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??_)}getMaxAnchorOffset(e,t,s){let{numberOfRows:o,numberOfCols:i}=this.getters.getSheetSize(e),n=0;for(;n<t&&o>0;o--)n+=this.getRowSize(e,o-1);let r=0;for(;r<s&&i>0;i--)r+=this.getters.getColSize(e,i-1);return{col:i,row:o,offset:{x:r-s,y:n-t}}}getHeaderSize(e,t,s){return this.getters.isHeaderHidden(e,t,s)?0:"ROW"===t?this.getRowSize(e,s):this.getters.getColSize(e,s)}updateRowSizeForCellChange(e,t,s){const o=this.tallestCellInRow[e]?.[t];if(o?.cell.col===s){const s=this.getRowTallestCell(e,t);this.history.update("tallestCellInRow",e,t,s)}const i=this.getCellHeight({sheetId:e,col:s,row:t});if(!(i<=_)&&(!o&&i>_||o&&i>o.size)){const o={cell:{sheetId:e,col:s,row:t},size:i};this.history.update("tallestCellInRow",e,t,o)}}initializeSheet(e){const t=[];for(let s=0;s<this.getters.getNumberRows(e);s++){const o=this.getRowTallestCell(e,s);t.push(o)}this.history.update("tallestCellInRow",e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return _;const t=this.getters.getCell(e),s=this.getters.getColSize(e.sheetId,e.col);return function(e,t,s){return t&&(t.isFormula||t.content)?Vb(e,t.isFormula?"":t.content,t.style,s):_}(this.ctx,t,s)}isInMultiRowMerge(e){const t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(void 0!==this.getters.getUserRowSize(e,t))return;const s=this.getters.getRowCells(e,t);let o,i=0;for(let e=0;e<s.length;e++){const t=this.getters.getCellById(s[e]);if(!t)continue;const n=this.getters.getCellPosition(t.id),r=this.getCellHeight(n);r>i&&r>_&&(i=r,o={cell:n,size:r})}return o&&o.size>_?o:void 0}}).add("data_validation_ui",class extends MA{static getters=["getDataValidationInvalidCriterionValueMessage","getInvalidDataValidationMessage","getValidationResultForCellValue","getDataValidationRangeValues","isCellValidCheckbox","getDataValidationCellStyle","getDataValidationChipStyle","isDataValidationInvalid"];validationResults={};handle(e){if(cr.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))this.validationResults={};else switch(e.type){case"ADD_DATA_VALIDATION_RULE":case"REMOVE_DATA_VALIDATION_RULE":delete this.validationResults[e.sheetId]}}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:C}}getInvalidDataValidationMessage(e){const t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){const s=QT.get(e);return t.startsWith("=")?"onlyLiterals"===s.allowedValues?fs("The value must not be a formula"):this.isValidFormula(t)?void 0:Ag.CriterionError.validFormula:"onlyFormulas"===s.allowedValues?fs("The value must be a formula"):s.isCriterionValueValid(t)?void 0:s.criterionValueErrorString}getDataValidationRangeValues(e,t){const s=this.getters.getRangeFromSheetXC(e,String(t.values[0])),o=[],i=new Set;for(const e of Bt(s.zone)){const t=this.getters.getEvaluatedCell({...e,sheetId:s.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),o.push({label:t.formattedValue,value:t.value?.toString()||""}))}return o}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;const t=this.getters.getValidationRuleForCell(e);return!(!t||"isBoolean"!==t.criterion.type)&&this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){const s=this.getters.getValidationRuleForCell(t);if(!s)return SD;const o=this.getRuleErrorForCellValue(e,t,s);return o?{error:o,rule:s,isValid:!1}:SD}hasChip(e){const t=this.getters.getValidationRuleForCell(e);return("isValueInList"===t?.criterion.type||"isValueInRange"===t?.criterion.type)&&"chip"===t.criterion.displayStyle}getDataValidationStyle(e){const t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;const s=this.getters.getEvaluatedCell(e),o=this.getValueColor(t,s.value);if(!o)return;return{fillColor:o,textColor:Pv(o)}}getValueColor(e,t){if("isValueInList"===e.criterion.type||"isValueInRange"===e.criterion.type)for(const s in e.criterion.colors)if(s.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[s]}isValidFormula(e){return!sE(e).isBadExpression}getValidationResultForCell(e){const{col:t,row:s,sheetId:o}=e;return this.validationResults[o]||(this.validationResults[o]=this.computeSheetValidationResults(o)),this.validationResults[o][t]?.[s]?.()||SD}computeSheetValidationResults(e){const t={},s=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(const e of xb(s.flat())){const{col:s,row:o}=e;t[s]||(t[s]=[]),t[s][o]=Oe(()=>{const t=this.getters.getEvaluatedCell(e);return t.type===_d.empty?SD:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,s){const{sheetId:o}=t,i=s.criterion,n=QT.get(i.type),r=this.getCellOffsetInRule(t,s),a=this.getEvaluatedCriterionValues(o,r,i);if(a.some(bi))return;const l={...i,values:a.map(fi)};return n.isValueValid(e,l,this.getters,o)?void 0:n.getErrorString(l,this.getters,o)}getCellOffsetInRule(e,t){const s=t.ranges.find(t=>kt(e.col,e.row,t.zone));if(!s)throw new Error("The cell is not in any range of the rule");return{col:e.col-s.zone.left,row:e.row-s.zone.top}}getEvaluatedCriterionValues(e,t,s){return s.values.map(s=>{if(!s.startsWith("="))return Xv(s,Oc);const o=sE(s),i=this.getters.getTranslatedCellFormula(e,t.col,t.row,o.tokens);return this.getters.evaluateFormula(e,i)})}}).add("dynamic_tables",class extends MA{static getters=["canCreateDynamicTableOnZones","doesZonesContainFilter","getFilter","getFilters","getTable","getTables","getTablesOverlappingZones","getFilterId","getFilterHeaders","isFilterHeader"];tables={};handle(e){if(cr.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e)||"EVALUATE_CELLS"===e.type)this.tables={};else switch(e.type){case"CREATE_TABLE":case"REMOVE_TABLE":case"UPDATE_TABLE":case"DELETE_CONTENT":this.tables={}}}finalize(){for(const e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){const t=[],s=this.getters.getCoreTables(e);for(const e of s)"dynamic"!==e.type&&t.push(e);const o=[...t];for(const i of s){if("dynamic"!==i.type)continue;const s=this.coreTableToTable(e,i);let n=s.range.zone;for(const e of o)Lt(n,e.range.zone)&&(n={...n,right:e.range.zone.left-1});t.push({...s,range:this.getters.getRangeFromZone(e,n)})}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){const 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:s}){return this.getTables(e).find(e=>kt(t,s,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>Lt(e.range.zone,t)))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some(e=>e.config.hasFilters)}getFilterHeaders(e){const t=[];for(const s of this.getTables(e)){if(!s.config.hasFilters)continue;const o=s.range.zone,i=o.top;for(let s=o.left;s<=o.right;s++)t.push({sheetId:e,col:s,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:s}){return this.getFilterHeaders(e).some(e=>e.col===t&&e.row===s)}canCreateDynamicTableOnZones(e,t){if(!Qt(t))return!1;const s=Ft(...t),o={col:s.left,row:s.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(o);if(!i){const e=this.getters.getEvaluatedCell(o);return e.value===bs.SpilledBlocked&&!e.errorOriginPosition}if(Me(i,o)&&1===Kt(s))return!0;return Me(s,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if("dynamic"!==t.type)return t;const s=t.range.zone,o={sheetId:e,col:s.left,row:s.top},i=this.getters.getSpreadZone(o)??t.range.zone,n=this.getters.getRangeFromZone(e,i),r=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:n,filters:r,config:t.config}}getDynamicTableFilters(e,t,s){const o=[],{top:i,bottom:n,left:r,right:a}=s;for(let s=r;s<=a;s++){const a=s-r,l={left:s,right:s,top:i,bottom:n},c=xA(this.getDynamicTableFilterId(t.id,a),this.getters.getRangeFromZone(e,l),t.config,this.getters.getRangeFromZone);o.push(c)}return o}getDynamicTableFilterId(e,t){return e+"_"+t}exportForExcel(e){for(const t of e.sheets)for(const e of t.tables){const s=wt(e.range),o={sheetId:t.id,col:s.left,row:s.top},i=this.getters.getCoreTable(o),n=this.getTable(o);"dynamic"===i?.type&&n&&(e.range=Tt(n.range.zone))}}}).add("custom_colors",class extends MA{customColors={};shouldUpdateColors=!0;static getters=["getCustomColors"];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case"START":for(const e of this.getters.getSheetIds())for(const t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));break;case"UPDATE_CHART":case"CREATE_CHART":this.tryToAddColors(this.getChartColors(e.chartId));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)}}finalize(){this.shouldUpdateColors&&(this.history.update("shouldUpdateColors",!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return function(e){const t=[{leadColor:yv(255,0,0),colors:[]},{leadColor:yv(255,128,0),colors:[]},{leadColor:yv(128,128,0),colors:[]},{leadColor:yv(128,255,0),colors:[]},{leadColor:yv(0,255,0),colors:[]},{leadColor:yv(0,255,128),colors:[]},{leadColor:yv(0,255,255),colors:[]},{leadColor:yv(0,127,255),colors:[]},{leadColor:yv(0,0,255),colors:[]},{leadColor:yv(127,0,255),colors:[]},{leadColor:yv(128,0,128),colors:[]},{leadColor:yv(255,0,128),colors:[]}];for(const s of e.map(Ev)){let e=500,o=0;t.forEach((t,i)=>{const n=(r=s,a=t.leadColor,Math.sqrt(Math.pow(r.r-a.r,2)+Math.pow(r.g-a.g,2)+Math.pow(r.b-a.b,2)));var r,a;e>n&&(e=n,o=i)}),t[o].colors.push(s)}return t.map(e=>e.colors.sort((e,t)=>xv(e).s-xv(t).s)).flat().map(wv)}(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(const t of this.getters.getSheetIds())e=e.concat(this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getColorsFromCells(e){const t=Object.values(this.getters.getCells(e)),s=new Set;for(const e of t)e.style?.textColor&&s.add(e.style.textColor),e.style?.fillColor&&s.add(e.style.fillColor);for(const t of this.getters.getBordersColors(e))s.add(t);return[...s]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),s=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(s.push(t.style.textColor),s.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(s.push(fv(t.minimum.color)),s.push(t.midpoint?fv(t.midpoint.color):void 0),s.push(fv(t.maximum.color)))}return s.filter(Te)}getChartColors(e){const t=this.getters.getChart(e);if(void 0===t)return[];return[...JSON.stringify(t.getDefinition()).matchAll(bD)].map(e=>e[1])}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{const t=e.config,s=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(s.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(s.headerRow):[],t.totalRow?this.getTableStyleElementColors(s.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(s.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(s.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(s.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(s.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(s.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(s.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(Te):[]}tryToAddColors(e){for(const t of e){if(!Sv(t))continue;const e=bv(t);t&&!T.includes(e)&&this.history.update("customColors",e,!0)}}}).add("pivot_ui",class extends MA{static getters=["getPivot","getFirstPivotFunction","getPivotCellSortDirection","getPivotIdFromPosition","getPivotCellFromPosition","generateNewCalculatedMeasureName","isPivotUnused","isSpillPivotFormula"];pivots={};unusedPivots;custom;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){if("START"===e.type)for(const e of this.getters.getPivotIds())this.setupPivot(e)}handle(e){if(cr.has(e.type))for(const e of this.getters.getPivotIds())XD.get(this.getters.getPivotCoreDefinition(e).type).externalData||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;const t=e.commands.filter(QD);for(const e of t){const t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case"UPDATE_LOCALE":!function(){for(const e in jD)jD[e].set.clear(),jD[e].values={}}()}}getPivotIdFromPosition(e){const t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){const s=this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(s){const e=s.args[0]?.toString();return e&&this.getters.getPivotId(e)}}}isSpillPivotFormula(e){const t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){const s=this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);return"PIVOT"===s?.functionName}return!1}getFirstPivotFunction(e,t){const s=MD(t);if(!s)return;const{functionName:o,args:i}=s;return{functionName:o,args:i.map(t=>{if("EMPTY"===t.type)return;if("STRING"===t.type||"BOOLEAN"===t.type||"NUMBER"===t.type)return t.value;const s=_D(t);return this.getters.evaluateFormula(e,s)})}}getPivotCellFromPosition(e){const t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||0===ND(t.compiledFormula.tokens))return IA;const s=this.getters.getCellPosition(t.id),o=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!o)return IA;let{functionName:i,args:n}=o;const r=n[0];if(!r)return IA;const a=this.getters.getPivotId(r.toString());if(!a)return IA;const l=this.getPivot(a);if(!l.isValid())return IA;if("PIVOT"===i&&!t.content.replaceAll(" ","").toUpperCase().startsWith("=PIVOT"))return IA;if("PIVOT"===i){const t=fi(n[2]),o=void 0===t||To(t),i=fi(n[3]),r=fi(n[5]),a=void 0===r||To(r),c={displayColumnHeaders:void 0===i||To(i),displayTotals:o,displayMeasuresRow:a},h=l.getCollapsedTableStructure().getPivotCells(c),d=e.col-s.col,u=e.row-s.row;return h[d][u]}try{const t=e.row-s.row,o=e.col-s.col;if(n=n.map(e=>Ds(e)?e[o][t]:e),"PIVOT.HEADER"===i&&"measure"===n.at(-2)){return{type:"MEASURE_HEADER",domain:l.parseArgsToPivotDomain(n.slice(1,-2).map(e=>({value:e}))),measure:n.at(-1)?.toString()||""}}if("PIVOT.HEADER"===i){const e=l.parseArgsToPivotDomain(n.slice(1).map(e=>({value:e})));return{type:"HEADER",domain:e,dimension:lA(l,e).colDomain.length?"COL":"ROW"}}const[r,...a]=n.slice(1);return{type:"VALUE",domain:l.parseArgsToPivotDomain(a.map(e=>({value:e}))),measure:r?.toString()||""}}catch(e){return IA}}generateNewCalculatedMeasureName(e){const t=e.map(e=>e.fieldName);return st(fs("Calculated measure 1"),t,{compute:(e,t)=>fs("Calculated measure %s",t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw new Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){return this._getUnusedPivots().includes(e)}getPivotCellSortDirection(e){const t=this.getters.getPivotIdFromPosition(e),s=this.getters.getPivotCellFromPosition(e);if("EMPTY"===s.type||"HEADER"===s.type||!t)return;const o=this.getters.getPivot(t),i=lA(o,s.domain).colDomain,n=o.definition.sortedColumn;return n?.measure===s.measure&&Me(n.domain,i)?n.order:"none"}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){const s=this.getters.getPivotCoreDefinition(e);if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(s);else{const t=kD(XD.get(s.type).ui);this.pivots[e]=new t(this.custom,{definition:s,getters:this.getters})}}_getUnusedPivots(){if(void 0!==this.unusedPivots)return this.unusedPivots;const e=new Set(this.getters.getPivotIds());for(const t of this.getters.getSheetIds())for(const s in this.getters.getCells(t)){const t=this.getters.getCellPosition(s),o=this.getPivotIdFromPosition(t);if(o&&(e.delete(o),!e.size))return this.unusedPivots=[],[]}return this.unusedPivots=[...e],this.unusedPivots}}).add("cell_icon",class extends MA{static getters=["doesCellHaveGridIcon","getCellIcons","getCellIconRect"];cellIconsCache={};handle(e){"SET_VIEWPORT_OFFSET"!==e.type&&(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){const s=e.position,o=this.getters.getCell(s);return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,o?.style?.verticalAlign),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,s){const o=e.x,i=e.x+e.width;switch(t){case"right":return i-s.margin-s.size;case"left":return o+s.margin;default:const e=Math.floor((i-o-s.size)/2);return i-s.size-e}}computeCellIcons(e){const t={left:void 0,right:void 0,center:void 0},s=vD.getAll();for(const o of s){const s=o(this.getters,e);s&&(!t[s.horizontalAlign]||s.priority>t[s.horizontalAlign].priority)&&(t[s.horizontalAlign]=s)}if(t.center&&(t.left||t.right)){const 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(Te)}doesCellHaveGridIcon(e){return Boolean(this.getCellIcons(e).length)}});class N_{getters;providers=[];constructor(e){this.getters=e}static getters=["adaptFormulaStringDependencies","copyFormulaStringForSheet","extendRange","getRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeData","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData","getRangeFromZone","getRangesUnion","recomputeRanges","isRangeValid","removeRangesSheetPrefix"];allowDispatch(e){return"MOVE_RANGES"===e.type?1===e.target.length?"Success":"InvalidZones":"Success"}beforeHandle(e){}handle(e){const t=Tb(e);t?.applyChange&&this.executeOnAllRanges(t.applyChange,t.sheetId,t.sheetName)}finalize(){}verifyRangeRemoved(e){return t=>{const s=e(t);return"NONE"===s.changeType||Rt(s.range.zone)?s:{range:s.range,changeType:"REMOVE"}}}executeOnAllRanges(e,t,s){const o=this.verifyRangeRemoved(e);for(const e of this.providers)e(o,t,s)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,s,o){return e.map(e=>{if(!Rt(e.zone))return e;const i=e.prefixSheet?e.sheetId:o,n=Ib(e),r=yb(e),a={...e.unboundedZone,left:n&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:n?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:r&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:s),bottom:r?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:s)};return function(e){if(xt(e.zone))return e;const t={...e.unboundedZone},s={...e.zone};let o=e.parts;if(void 0!==t.right&&t.right<t.left){const e=t.right;t.right=t.left,t.left=e,s.right=s.left,s.left=e,o=[{colFixed:o[1]?.colFixed||!1,rowFixed:o[0]?.rowFixed||!1},{colFixed:o[0]?.colFixed||!1,rowFixed:o[1]?.rowFixed||!1}]}if(void 0!==t.bottom&&t.bottom<t.top){const e=t.bottom;t.bottom=t.top,t.top=e,s.bottom=s.top,s.top=e,o=[{colFixed:o[0]?.colFixed||!1,rowFixed:o[1]?.rowFixed||!1},{colFixed:o[1]?.colFixed||!1,rowFixed:o[0]?.rowFixed||!1}]}return{unboundedZone:t,zone:s,parts:o,invalidXc:e.invalidXc,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}(bb({...e,sheetId:i,zone:a},this.getters.getSheetSize))})}removeRangesSheetPrefix(e,t){return t.map(t=>t.prefixSheet&&t.sheetId===e?{...t,prefixSheet:!1}:t)}extendRange(e,t,s){const o="COL"===t?e.zone.right+s:e.zone.right,i="ROW"===t?e.zone.bottom+s:e.zone.bottom,n={left:e.zone.left,top:e.zone.top,right:Ib(e)?void 0:o,bottom:yb(e)?void 0:i};return bb({...e,zone:n},this.getters.getSheetSize)}getRangeFromSheetXC(e,t){if(!Xn.test(t)||!this.getters.tryGetSheet(e))return Cb(t);const{sheetName:s}=tr(t);return Sb({xc:t,sheetId:this.getters.getSheetIdByName(s)||e,invalidSheetName:s&&!this.getters.getSheetIdByName(s)?s:void 0},this.getters.getSheetSize)}getRangeString(e,t,s={useBoundedReference:!1,useFixedReference:!1}){return e?e.invalidXc?e.invalidXc:this.getters.tryGetSheet(e.sheetId)?wb(e,t,this.getters.getSheetName,s):bs.InvalidReference:bs.InvalidReference}getRangeDataFromXc(e,t){const s=this.getters.getRangeFromSheetXC(e,t);return this.getRangeDataFromZone(s.sheetId,s.unboundedZone)}getRangeDataFromZone(e,t){return{_sheetId:e,_zone:t=this.getters.getUnboundedZone(e,t)}}getRangeData(e){return this.getRangeDataFromZone(e.sheetId,e.unboundedZone)}getRangeFromZone(e,t){return bb({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){const s=e.map(e=>e.unboundedZone),o=t.map(e=>e.unboundedZone);return ft(s,o).map(t=>this.getRangeFromZone(e[0].sheetId,t))}getRangeFromRangeData(e){if(!this.getters.tryGetSheet(e._sheetId))return Cb(bs.InvalidReference);return bb({prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]},this.getters.getSheetSize)}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:s}=tr(e);return null!==t.match(Xn)&&(!s||void 0!==this.getters.getSheetIdByName(s))}getRangesUnion(e){const t=e.map(e=>e.unboundedZone),s=function(...e){return{top:Math.min(...e.map(e=>e.top)),left:Math.min(...e.map(e=>e.left)),bottom:e.some(e=>void 0===e.bottom)?void 0:Math.max(...e.map(e=>e.bottom)),right:e.some(e=>void 0===e.right)?void 0:Math.max(...e.map(e=>e.right))}}(...t);return this.getRangeFromZone(e[0].sheetId,s)}adaptFormulaStringDependencies(e,t,s){if(!t.startsWith("="))return t;const o=sE(t),i=o.dependencies.map(t=>{const o=this.getters.getRangeFromSheetXC(e,t),i=s(o);return"NONE"===i.changeType?o:i.range});return this.getters.getFormulaString(e,o.tokens,i)}copyFormulaStringForSheet(e,t,s,o){if(!s.startsWith("="))return s;const i=sE(s),n=i.dependencies.map(s=>{const i=this.getters.getRangeFromSheetXC(e,s);return"keepSameReference"===o?i:Eb(e,t,i)});return this.getters.getFormulaString(t,i.tokens,n)}}class L_{observers=new Map;defaultSubscription;mainSubscription;registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||(this.mainSubscription=this.defaultSubscription)}observe(e,t){this.observers.set(e,{owner:e,callbacks:t})}capture(e,t){if(this.observers.get(e))throw new 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))}}class k_{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new L_,this.anchor={cell:{col:0,row:0},zone:Zt({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,s){this.stream.capture(e,s),this.anchor=t}registerAsDefault(e,t,s){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,s),this.defaultAnchor=t,this.capture(e,t,s)}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,s){const o=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(o,e.zone)},this.processEvent({options:s,anchor:e,mode:t})}selectZone(e,t={scrollIntoView:!0}){return this.modifyAnchor(e,"overrideSelection",t)}selectCell(e,t){const s=Zt({col:e,row:t});return this.selectZone({zone:s,cell:{col:e,row:t}},{scrollIntoView:!0})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new br("InvalidSelectionStep");const{col:s,row:o}=this.getNextAvailablePosition(e,t);return this.selectCell(s,o)}setAnchorCorner(e,t){const s=this.getters.getActiveSheetId(),{col:o,row:i}=this.anchor.cell,n={left:Math.min(o,e),top:Math.min(i,t),right:Math.max(o,e),bottom:Math.max(i,t)},r={zone:this.getters.expandZone(s,n),cell:{col:o,row:i}};return this.processEvent({mode:"updateAnchor",anchor:r,options:{scrollIntoView:!1}})}addCellToSelection(e,t){const s=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:s,col:e,row:t}));const o=this.getters.expandZone(s,Zt({col:e,row:t}));return this.processEvent({options:{scrollIntoView:!0},anchor:{zone:o,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new br("InvalidSelectionStep");const s=this.getters.getActiveSheetId(),o=this.anchor,{col:i,row:n}=o.cell,{left:r,right:a,top:l,bottom:c}=o.zone,h=this.getStartingPosition(e),[d,u]=this.deltaToTarget(h,e,t);if(0===d&&0===u)return br.Success;let g=o.zone;const p=e=>{e=Wt(e);const{left:t,right:o,top:i,bottom:n}=this.getters.expandZone(s,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(s)-1,o),top:Math.max(0,i),bottom:Math.min(this.getters.getNumberRows(s)-1,n)}},{cell:m,zone:f}=this.getReferenceAnchor(),{col:v,row:b}=m;let S=0;for(;null!==g;){if(S++,d<0){const e=this.getNextAvailableCol(d,a-(S-1),b);g=f.right<=a-S?p({top:l,left:r,bottom:c,right:e}):null}if(d>0){const e=this.getNextAvailableCol(d,r+(S-1),b);g=r+S<=f.left?p({top:l,left:e,bottom:c,right:a}):null}if(u<0){const e=this.getNextAvailableRow(u,v,c-(S-1));g=f.bottom<=c-S?p({top:l,left:r,bottom:e,right:a}):null}if(u>0){const e=this.getNextAvailableRow(u,v,l+(S-1));g=l+S<=f.top?p({top:e,left:r,bottom:c,right:a}):null}if(g=g?Wt(g):g,g&&!Mt(g,o.zone))return this.processEvent({options:{scrollIntoView:!0},mode:"updateAnchor",anchor:{zone:g,cell:{col:i,row:n}}})}g=p(Ft({top:n,bottom:n,left:i,right:i},Wt({top:this.getNextAvailableRow(u,v,l),left:this.getNextAvailableCol(d,r,b),bottom:this.getNextAvailableRow(u,v,c),right:this.getNextAvailableCol(d,a,b)})));const C={zone:g,cell:{col:i,row:n}};return this.processEvent({anchor:C,mode:"updateAnchor",options:{scrollIntoView:!0}})}selectColumn(e,t){const s=this.getters.getActiveSheetId(),o=this.getters.getNumberRows(s)-1;let i={left:e,right:e,top:0,bottom:o};const n=this.getters.findFirstVisibleColRowIndex(s,"ROW");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=e,a=n;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),i=Ft(i,{left:r,right:r,top:n,bottom:o})}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:r,row:a}},mode:t})}selectRow(e,t){const s=this.getters.getActiveSheetId(),o=this.getters.getNumberCols(s)-1;let i={top:e,bottom:e,left:0,right:o};const n=this.getters.findFirstVisibleColRowIndex(s,"COL");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=n,a=e;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),i=Ft(i,{left:n,right:o,top:a,bottom:a})}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:r,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(Mt(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:Zt(t.cell)},"updateAnchor",{scrollIntoView:!1});const s=this.getters.getContiguousZone(e,t.zone);return Me(s,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:s},"updateAnchor",{scrollIntoView:!1})}selectTableAroundSelection(){const e=this.getters.getActiveSheetId(),t=this.getters.getContiguousZone(e,this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:t},"updateAnchor",{scrollIntoView:!1})}selectAll(){const 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){const t={...e,previousAnchor:ae(this.anchor)},s=this.checkEventAnchorZone(t);return"Success"!==s?new br(s):(this.anchor=t.anchor,this.stream.send(t),br.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:s}=e;if(!kt(t.col,t.row,s))return"InvalidAnchorZone";const{left:o,right:i,top:n,bottom:r}=s,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",o,i);return void 0===this.getters.findVisibleHeader(a,"ROW",n,r)||void 0===l?"SelectionOutOfBound":"Success"}checkAnchorZoneOrThrow(e){if("InvalidAnchorZone"===this.checkAnchorZone(e))throw new Error("The provided anchor is invalid. The cell must be part of the zone.")}getNextAvailablePosition(e,t=1){const{col:s,row:o}=this.anchor.cell,i=this.deltaToTarget({col:s,row:o},e,t);return{col:this.getNextAvailableCol(i[0],s,o),row:this.getNextAvailableRow(i[1],s,o)}}getNextAvailableCol(e,t,s){const o=this.getters.getActiveSheetId(),i={col:t,row:s};return this.getNextAvailableHeader(e,"COL",t,i,e=>this.getters.isInSameMerge(o,t,s,e,s))}getNextAvailableRow(e,t,s){const o=this.getters.getActiveSheetId(),i={col:t,row:s};return this.getNextAvailableHeader(e,"ROW",s,i,e=>this.getters.isInSameMerge(o,t,s,t,e))}getNextAvailableHeader(e,t,s,o,i){const n=this.getters.getActiveSheetId();if(0===e)return s;const r=Math.sign(e);let a=s+e;for(;i(a);)a+=r;for(;this.getters.isHeaderHidden(n,t,a);)a+=r;return a<0||a>this.getters.getNumberHeaders(n,t)-1?this.getters.isHeaderHidden(n,t,s)?this.getNextAvailableHeader(-r,t,s,o,i):s:a}getReferenceAnchor(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:s,right:o,top:i,bottom:n}=t.zone,{col:r,row:a}=t.cell,l=this.getters.isColHidden(e,r)&&this.getters.findVisibleHeader(e,"COL",s,o)||r,c=this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",i,n)||a;return{cell:{col:l,row:c},zone:this.getters.expandZone(e,{left:l,right:l,top:c,bottom:c})}}deltaToTarget(e,t,s){switch(t){case"up":return"end"!==s?[0,-s]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==s?[0,s]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==s?[-s,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==s?[s,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:s}=this.getPosition();const o=this.anchor.zone;switch(e){case"down":case"up":s=s===o.top?o.bottom:o.top;break;case"left":case"right":t=t===o.right?o.left:o.right}return{col:t,row:s}}getEndOfCluster(e,t,s){const o=this.getters.getActiveSheetId();let i=e;const n=this.getNextCellPosition(e,t,s),r=this.isCellSkippableInCluster({...i,sheetId:o})||this.isCellSkippableInCluster({...n,sheetId:o})?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(i,t,s);if(i.col===e.col&&i.row===e.row)break;const n=this.isCellSkippableInCluster({...e,sheetId:o});if("endOfCluster"===r&&n)break;if("nextCluster"===r&&!n){i=e;break}i=e}return"cols"===t?i.col:i.row}getNextCellPosition(e,t,s){const o={...e};return o["cols"===t?"col":"row"]="cols"===t?this.getNextAvailableCol(s,o.col,o.row):this.getNextAvailableRow(s,o.col,o.row),{col:o.col,row:o.row}}getPosition(){return{...this.anchor.cell}}isCellSkippableInCluster(e){const t=this.getters.getMainCellPosition(e),s=this.getters.getEvaluatedCell(t);return s.type===_d.empty||s.type===_d.text&&""===s.value}}class V_{changes;commands=[];recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop();let s=e[0];const o=e.at(-1),i=e.length-2;for(let t=1;t<=i;t++){const o=e[t];if(void 0===s[o]){const i=e[t+1];s[o]=ar(i)}s=s[o]}s[o]!==t&&(this.changes?.push({key:o,target:s,before:s[o]}),void 0===t?delete s[o]:s[o]=t)}}const U_=17781237,H_=17781238,z_=88853993,B_=88853994;function G_(e,t,s){const o=[["xmlns:r",LS],["xmlns:a",IS],["xmlns:c",wS]],i=W_({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let n=gT``;if(e.data.title?.text){const t=uI(rC(e.data.backgroundColor)),s=e.data.title.fontSize??R;n=gT`
|
|
4
|
+
<c:title>
|
|
5
|
+
${q_(e.data.title.text,t,s,e.data.title)}
|
|
6
|
+
<c:overlay val="0" />
|
|
7
|
+
</c:title>
|
|
8
|
+
`}let r=gT``;switch(e.data.type){case"bar":r=function(e){const t=e.horizontal?"bar":"col",s=e.dataSets.map(e=>e.backgroundColor??""),o=new Gv(e.dataSets.length,s),i=[],n=[];for(const[t,s]of Object.entries(e.dataSets)){const r=uI(o.next()),a=W_({backgroundColor:r,line:{color:r}}),l=gT`
|
|
9
|
+
<c:ser>
|
|
10
|
+
<c:idx val="${t}"/>
|
|
11
|
+
<c:order val="${t}"/>
|
|
12
|
+
${j_(s.trend,r)}
|
|
13
|
+
${X_(s.label)}
|
|
14
|
+
${a}
|
|
15
|
+
${e.labelRange?gT`<c:cat>${Q_(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
|
|
16
|
+
<c:val> <!-- x-coordinate values -->
|
|
17
|
+
${eO(s.range)}
|
|
18
|
+
</c:val>
|
|
19
|
+
</c:ser>
|
|
20
|
+
`;s.rightYAxis?n.push(l):i.push(l)}const r=e.stacked?"stacked":"clustered",a=e.stacked?100:-20;return gT`
|
|
21
|
+
${i.length?gT`
|
|
22
|
+
<c:barChart>
|
|
23
|
+
<c:barDir val="${t}"/>
|
|
24
|
+
<c:grouping val="${r}"/>
|
|
25
|
+
<c:overlap val="${a}"/>
|
|
26
|
+
<c:gapWidth val="70"/>
|
|
27
|
+
<!-- each data marker in the series does not have a different color -->
|
|
28
|
+
<c:varyColors val="0"/>
|
|
29
|
+
${uT(i)}
|
|
30
|
+
<c:axId val="${U_}" />
|
|
31
|
+
<c:axId val="${z_}" />
|
|
32
|
+
</c:barChart>
|
|
33
|
+
${"col"===t?J_("b","c:catAx",U_,z_,e.axesDesign?.x?.title,e.fontColor):J_("b","c:catAx",U_,z_,e.axesDesign?.y?.title,e.fontColor,void 0,"maxMin")}
|
|
34
|
+
${"col"===t?J_("l","c:valAx",z_,U_,e.axesDesign?.y?.title,e.fontColor):J_("l","c:valAx",z_,U_,e.axesDesign?.x?.title,e.fontColor,void 0,void 0,"max")}
|
|
35
|
+
`:""}
|
|
36
|
+
${n.length?gT`
|
|
37
|
+
<c:barChart>
|
|
38
|
+
<c:barDir val="col"/>
|
|
39
|
+
<c:grouping val="${r}"/>
|
|
40
|
+
<c:overlap val="${a}"/>
|
|
41
|
+
<c:gapWidth val="70"/>
|
|
42
|
+
<!-- each data marker in the series does not have a different color -->
|
|
43
|
+
<c:varyColors val="0"/>
|
|
44
|
+
${uT(n)}
|
|
45
|
+
<c:axId val="${17781238}" />
|
|
46
|
+
<c:axId val="${88853994}" />
|
|
47
|
+
</c:barChart>
|
|
48
|
+
${J_("b","c:catAx",17781238,88853994,e.axesDesign?.x?.title,e.fontColor,i.length?1:0)}
|
|
49
|
+
${J_("r","c:valAx",88853994,17781238,e.axesDesign?.y1?.title,e.fontColor)}
|
|
50
|
+
`:""}`}(e.data);break;case"combo":r=function(e){const t=e.dataSets,s=t.map(e=>e.backgroundColor??""),o=new Gv(t.length,s);let i=t[0];const n=uI(o.next()),r=i.rightYAxis??!1,a=gT`
|
|
51
|
+
<c:ser>
|
|
52
|
+
<c:idx val="0"/>
|
|
53
|
+
<c:order val="0"/>
|
|
54
|
+
${j_(i.trend,n)}
|
|
55
|
+
${X_(i.label)}
|
|
56
|
+
${W_({backgroundColor:n,line:{color:n}})}
|
|
57
|
+
${e.labelRange?gT`<c:cat>${Q_(e.labelRange)}</c:cat>`:""}
|
|
58
|
+
<!-- x-coordinate values -->
|
|
59
|
+
<c:val>
|
|
60
|
+
${eO(i.range)}
|
|
61
|
+
</c:val>
|
|
62
|
+
</c:ser>
|
|
63
|
+
`,l=[],c=[];for(let s=1;s<t.length;s++){i=t[s];const n=uI(o.next()),r=W_({backgroundColor:n,line:{color:n}}),a=gT`
|
|
64
|
+
<c:ser>
|
|
65
|
+
<c:idx val="${s}"/>
|
|
66
|
+
<c:order val="${s}"/>
|
|
67
|
+
<c:smooth val="0"/>
|
|
68
|
+
<c:marker>
|
|
69
|
+
<c:symbol val="circle" />
|
|
70
|
+
<c:size val="5"/>
|
|
71
|
+
${r}
|
|
72
|
+
</c:marker>
|
|
73
|
+
${j_(i.trend,n)}
|
|
74
|
+
${X_(i.label)}
|
|
75
|
+
${r}
|
|
76
|
+
${e.labelRange?gT`<c:cat>${Q_(e.labelRange)}</c:cat>`:""}
|
|
77
|
+
<!-- x-coordinate values -->
|
|
78
|
+
<c:val>
|
|
79
|
+
${eO(i.range)}
|
|
80
|
+
</c:val>
|
|
81
|
+
</c:ser>
|
|
82
|
+
`;i.rightYAxis?c.push(a):l.push(a)}const h=e.stacked?100:-20;return gT`
|
|
83
|
+
<c:barChart>
|
|
84
|
+
<c:barDir val="col"/>
|
|
85
|
+
<c:grouping val="clustered"/>
|
|
86
|
+
<c:overlap val="${h}"/>
|
|
87
|
+
<c:gapWidth val="70"/>
|
|
88
|
+
<!-- each data marker in the series does not have a different color -->
|
|
89
|
+
<c:varyColors val="0"/>
|
|
90
|
+
${a}
|
|
91
|
+
<c:axId val="${r?H_:U_}" />
|
|
92
|
+
<c:axId val="${r?B_:z_}" />
|
|
93
|
+
</c:barChart>
|
|
94
|
+
${l.length?gT`
|
|
95
|
+
<c:lineChart>
|
|
96
|
+
<c:grouping val="standard"/>
|
|
97
|
+
<!-- each data marker in the series does not have a different color -->
|
|
98
|
+
<c:varyColors val="0"/>
|
|
99
|
+
${uT(l)}
|
|
100
|
+
<c:axId val="${U_}" />
|
|
101
|
+
<c:axId val="${z_}" />
|
|
102
|
+
</c:lineChart>
|
|
103
|
+
`:""}
|
|
104
|
+
${c.length?gT`
|
|
105
|
+
<c:lineChart>
|
|
106
|
+
<c:grouping val="standard"/>
|
|
107
|
+
<!-- each data marker in the series does not have a different color -->
|
|
108
|
+
<c:varyColors val="0"/>
|
|
109
|
+
${uT(c)}
|
|
110
|
+
<c:axId val="${H_}" />
|
|
111
|
+
<c:axId val="${B_}" />
|
|
112
|
+
</c:lineChart>
|
|
113
|
+
`:""}
|
|
114
|
+
${!r||l.length?gT`
|
|
115
|
+
${J_("b","c:catAx",U_,z_,e.axesDesign?.x?.title,e.fontColor,0)}
|
|
116
|
+
${J_("l","c:valAx",z_,U_,e.axesDesign?.y?.title,e.fontColor)}
|
|
117
|
+
`:""}
|
|
118
|
+
${r||c.length?gT`
|
|
119
|
+
${J_("b","c:catAx",H_,B_,e.axesDesign?.x?.title,e.fontColor,l.length||!r?1:0)}
|
|
120
|
+
${J_("r","c:valAx",B_,H_,e.axesDesign?.y1?.title,e.fontColor)}
|
|
121
|
+
`:""}
|
|
122
|
+
`}(e.data);break;case"pyramid":r=function(e){const t=e.dataSets,s=t.map(e=>e.backgroundColor??""),o=new Gv(t.length,s),i=t[0],n=t[1],r=uI(o.next()),a=uI(o.next()),{maxValue:l,majorUnit:c}=function(e){const t=3,s=((e,t)=>{let s=Math.ceil(e);for(;s%t!==0;)s++;return s})(e,t),o=s/t;return{maxValue:s,majorUnit:o}}(e.maxValue),h=e.labelRange?gT`<c:cat>${Q_(e.labelRange)}</c:cat>`:"",d=gT`
|
|
123
|
+
<c:ser>
|
|
124
|
+
<c:idx val="0"/>
|
|
125
|
+
<c:order val="0"/>
|
|
126
|
+
<c:invertIfNegative val="0" />
|
|
127
|
+
${X_(i.label)}
|
|
128
|
+
${W_({backgroundColor:r,line:{color:r}})}
|
|
129
|
+
${h}
|
|
130
|
+
<!-- x-coordinate values -->
|
|
131
|
+
<c:val>
|
|
132
|
+
${eO(i.range)}
|
|
133
|
+
</c:val>
|
|
134
|
+
</c:ser>
|
|
135
|
+
`,u=gT`
|
|
136
|
+
<c:ser>
|
|
137
|
+
<c:idx val="1"/>
|
|
138
|
+
<c:order val="1"/>
|
|
139
|
+
<c:invertIfNegative val="0" />
|
|
140
|
+
${X_(n.label)}
|
|
141
|
+
${W_({backgroundColor:a,line:{color:a}})}
|
|
142
|
+
${e.labelRange?gT`<c:cat>${Q_(e.labelRange)}</c:cat>`:""}
|
|
143
|
+
<!-- x-coordinate values -->
|
|
144
|
+
<c:val>
|
|
145
|
+
${eO(n.range)}
|
|
146
|
+
</c:val>
|
|
147
|
+
</c:ser>
|
|
148
|
+
`;return gT`
|
|
149
|
+
<c:barChart>
|
|
150
|
+
<c:barDir val="bar"/>
|
|
151
|
+
<c:grouping val="clustered"/>
|
|
152
|
+
<c:varyColors val="0" />
|
|
153
|
+
${d}
|
|
154
|
+
<c:gapWidth val="50" />
|
|
155
|
+
<c:axId val="${U_}" />
|
|
156
|
+
<c:axId val="${z_}" />
|
|
157
|
+
</c:barChart>
|
|
158
|
+
<c:barChart>
|
|
159
|
+
<c:barDir val="bar"/>
|
|
160
|
+
<c:grouping val="clustered"/>
|
|
161
|
+
<c:varyColors val="0" />
|
|
162
|
+
${u}
|
|
163
|
+
<c:gapWidth val="50" />
|
|
164
|
+
<c:axId val="${H_}" />
|
|
165
|
+
<c:axId val="${B_}" />
|
|
166
|
+
</c:barChart>
|
|
167
|
+
${J_("r","c:catAx",U_,z_,e.axesDesign?.y?.title,e.fontColor,0,"maxMin","autoZero","high")}
|
|
168
|
+
${J_("b","c:valAx",z_,U_,e.axesDesign?.x?.title,e.fontColor,0,"maxMin","max","nextTo",l,c,"#0;#0")}
|
|
169
|
+
${J_("t","c:valAx",B_,H_,void 0,e.fontColor,1)}
|
|
170
|
+
${J_("l","c:catAx",H_,B_,void 0,e.fontColor,1,"maxMin")}
|
|
171
|
+
`}(e.data);break;case"line":r=function(e){const t=e.dataSets.map(e=>e.backgroundColor??""),s=new Gv(e.dataSets.length,t),o=[],i=[];for(const[t,n]of Object.entries(e.dataSets)){const r=uI(s.next()),a=W_({line:{width:2.5,style:"solid",color:r}}),l=gT`
|
|
172
|
+
<c:ser>
|
|
173
|
+
<c:idx val="${t}"/>
|
|
174
|
+
<c:order val="${t}"/>
|
|
175
|
+
<c:smooth val="0"/>
|
|
176
|
+
<c:marker>
|
|
177
|
+
<c:symbol val="circle" />
|
|
178
|
+
<c:size val="5"/>
|
|
179
|
+
${W_({backgroundColor:r,line:{color:r}})}
|
|
180
|
+
</c:marker>
|
|
181
|
+
${j_(n.trend,r)}
|
|
182
|
+
${X_(n.label)}
|
|
183
|
+
${a}
|
|
184
|
+
${e.labelRange?gT`<c:cat>${Q_(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
|
|
185
|
+
<c:val> <!-- x-coordinate values -->
|
|
186
|
+
${eO(n.range)}
|
|
187
|
+
</c:val>
|
|
188
|
+
</c:ser>
|
|
189
|
+
`;n.rightYAxis?i.push(l):o.push(l)}const n=e.stacked?"stacked":"standard";return gT`
|
|
190
|
+
${o.length?gT`
|
|
191
|
+
<c:lineChart>
|
|
192
|
+
<c:grouping val="${n}"/>
|
|
193
|
+
<!-- each data marker in the series does not have a different color -->
|
|
194
|
+
<c:varyColors val="0"/>
|
|
195
|
+
${uT(o)}
|
|
196
|
+
<c:axId val="${U_}" />
|
|
197
|
+
<c:axId val="${z_}" />
|
|
198
|
+
</c:lineChart>
|
|
199
|
+
${J_("b","c:catAx",U_,z_,e.axesDesign?.x?.title,e.fontColor)}
|
|
200
|
+
${J_("l","c:valAx",z_,U_,e.axesDesign?.y?.title,e.fontColor)}
|
|
201
|
+
`:""}
|
|
202
|
+
${i.length?gT`
|
|
203
|
+
<c:lineChart>
|
|
204
|
+
<c:grouping val="${n}"/>
|
|
205
|
+
<!-- each data marker in the series does not have a different color -->
|
|
206
|
+
<c:varyColors val="0"/>
|
|
207
|
+
${uT(i)}
|
|
208
|
+
<c:axId val="${17781238}" />
|
|
209
|
+
<c:axId val="${88853994}" />
|
|
210
|
+
</c:lineChart>
|
|
211
|
+
${J_("b","c:catAx",17781238,88853994,e.axesDesign?.x?.title,e.fontColor,o.length?1:0)}
|
|
212
|
+
${J_("r","c:valAx",88853994,17781238,e.axesDesign?.y1?.title,e.fontColor)}
|
|
213
|
+
`:""}
|
|
214
|
+
`}(e.data);break;case"scatter":r=function(e){const t=e.dataSets.map(e=>e.backgroundColor??""),s=new Gv(e.dataSets.length,t),o=[],i=[];for(const[t,n]of Object.entries(e.dataSets)){const r=uI(s.next()),a=gT`
|
|
215
|
+
<c:ser>
|
|
216
|
+
<c:idx val="${t}"/>
|
|
217
|
+
<c:order val="${t}"/>
|
|
218
|
+
<c:smooth val="0"/>
|
|
219
|
+
<c:spPr>
|
|
220
|
+
<a:ln w="19050" cap="rnd">
|
|
221
|
+
<a:noFill/>
|
|
222
|
+
<a:round/>
|
|
223
|
+
</a:ln>
|
|
224
|
+
<a:effectLst/>
|
|
225
|
+
</c:spPr>
|
|
226
|
+
<c:marker>
|
|
227
|
+
<c:symbol val="circle" />
|
|
228
|
+
<c:size val="5"/>
|
|
229
|
+
${W_({backgroundColor:r,line:{color:r}})}
|
|
230
|
+
</c:marker>
|
|
231
|
+
${j_(n.trend,r)}
|
|
232
|
+
${X_(n.label)}
|
|
233
|
+
${e.labelRange?gT`<c:xVal> <!-- x-coordinate values -->
|
|
234
|
+
${eO(e.labelRange)}
|
|
235
|
+
</c:xVal>`:""}
|
|
236
|
+
<c:yVal> <!-- y-coordinate values -->
|
|
237
|
+
${eO(n.range)}
|
|
238
|
+
</c:yVal>
|
|
239
|
+
</c:ser>
|
|
240
|
+
`;n.rightYAxis?i.push(a):o.push(a)}return gT`
|
|
241
|
+
${o.length?gT`
|
|
242
|
+
<c:scatterChart>
|
|
243
|
+
<!-- each data marker in the series does not have a different color -->
|
|
244
|
+
<c:varyColors val="0"/>
|
|
245
|
+
<c:scatterStyle val="lineMarker"/>
|
|
246
|
+
${uT(o)}
|
|
247
|
+
<c:axId val="${U_}" />
|
|
248
|
+
<c:axId val="${z_}" />
|
|
249
|
+
</c:scatterChart>
|
|
250
|
+
${J_("b","c:valAx",U_,z_,e.axesDesign?.x?.title,e.fontColor)}
|
|
251
|
+
${J_("l","c:valAx",z_,U_,e.axesDesign?.y?.title,e.fontColor)}
|
|
252
|
+
`:""}
|
|
253
|
+
${i.length?gT`
|
|
254
|
+
<c:scatterChart>
|
|
255
|
+
<!-- each data marker in the series does not have a different color -->
|
|
256
|
+
<c:varyColors val="0"/>
|
|
257
|
+
<c:scatterStyle val="lineMarker"/>
|
|
258
|
+
${uT(i)}
|
|
259
|
+
<c:axId val="${17781238}" />
|
|
260
|
+
<c:axId val="${88853994}" />
|
|
261
|
+
</c:scatterChart>
|
|
262
|
+
${J_("b","c:valAx",17781238,88853994,e.axesDesign?.x?.title,e.fontColor,o.length?1:0)}
|
|
263
|
+
${J_("r","c:valAx",88853994,17781238,e.axesDesign?.y1?.title,e.fontColor)}
|
|
264
|
+
`:""}`}(e.data);break;case"pie":r=function(e,t,s){const o=Ke(e.dataSets.map(e=>Rx(e.range,t,s))),i=new Gv(o),n=ge(0,o).map(()=>uI(i.next())),r=[];for(const[o,i]of Object.entries(e.dataSets).reverse()){const a=Rx(i.range,t,s),l=[];for(const e of ge(0,a)){const t=W_({backgroundColor:n[e],line:{color:"FFFFFF",width:1.5}});l.push(gT`
|
|
265
|
+
<c:dPt>
|
|
266
|
+
<c:idx val="${e}"/>
|
|
267
|
+
${t}
|
|
268
|
+
</c:dPt>
|
|
269
|
+
`)}r.push(gT`
|
|
270
|
+
<c:ser>
|
|
271
|
+
<c:idx val="${o}"/>
|
|
272
|
+
<c:order val="${o}"/>
|
|
273
|
+
${X_(i.label)}
|
|
274
|
+
${uT(l)}
|
|
275
|
+
${K_({showLeaderLines:!0})}
|
|
276
|
+
${e.labelRange?gT`<c:cat>${Q_(e.labelRange)}</c:cat>`:""}
|
|
277
|
+
<c:val>
|
|
278
|
+
${eO(i.range)}
|
|
279
|
+
</c:val>
|
|
280
|
+
</c:ser>
|
|
281
|
+
`)}return gT`
|
|
282
|
+
<c:doughnutChart>
|
|
283
|
+
<c:varyColors val="1" />
|
|
284
|
+
<c:holeSize val="${e.pieHolePercentage??(e.isDoughnut?50:0)}" />
|
|
285
|
+
${K_()}
|
|
286
|
+
${uT(r)}
|
|
287
|
+
</c:doughnutChart>
|
|
288
|
+
`}(e.data,t,s);break;case"radar":r=function(e){const t=e.dataSets.map(e=>e.backgroundColor??""),s=new Gv(e.dataSets.length,t),o=[];for(const[t,i]of Object.entries(e.dataSets)){const n=uI(s.next()),r=W_({line:{width:2.5,style:"solid",color:n}}),a=gT`
|
|
289
|
+
<c:ser>
|
|
290
|
+
<c:idx val="${t}"/>
|
|
291
|
+
<c:order val="${t}"/>
|
|
292
|
+
<c:smooth val="0"/>
|
|
293
|
+
<c:marker>
|
|
294
|
+
<c:symbol val="circle" />
|
|
295
|
+
<c:size val="5"/>
|
|
296
|
+
${W_({backgroundColor:n,line:{color:n}})}
|
|
297
|
+
</c:marker>
|
|
298
|
+
${X_(i.label)}
|
|
299
|
+
${r}
|
|
300
|
+
${e.labelRange?gT`<c:cat>${Q_(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
|
|
301
|
+
<c:val> <!-- x-coordinate values -->
|
|
302
|
+
${eO(i.range)}
|
|
303
|
+
</c:val>
|
|
304
|
+
</c:ser>
|
|
305
|
+
`;o.push(a)}return gT`
|
|
306
|
+
${gT`
|
|
307
|
+
<c:radarChart>
|
|
308
|
+
<c:radarStyle val="marker"/>
|
|
309
|
+
<c:varyColors val="0"/>
|
|
310
|
+
${uT(o)}
|
|
311
|
+
<c:axId val="${U_}" />
|
|
312
|
+
<c:axId val="${z_}" />
|
|
313
|
+
</c:radarChart>
|
|
314
|
+
${J_("b","c:catAx",U_,z_,e.axesDesign?.x?.title,e.fontColor)}
|
|
315
|
+
${J_("l","c:valAx",z_,U_,e.axesDesign?.y?.title,e.fontColor)}
|
|
316
|
+
`}
|
|
317
|
+
`}(e.data)}let a="none";switch(e.data.legendPosition){case"bottom":a="b";break;case"left":a="l";break;case"right":a="r";break;case"top":a="t"}const l=e.data.fontColor,c=gT`
|
|
318
|
+
<c:chartSpace ${lT(o)}>
|
|
319
|
+
<c:roundedCorners val="0" />
|
|
320
|
+
<!-- <manualLayout/> to manually position the chart in the figure container -->
|
|
321
|
+
${i}
|
|
322
|
+
<c:chart>
|
|
323
|
+
${n}
|
|
324
|
+
<c:autoTitleDeleted val="0" />
|
|
325
|
+
<c:plotArea>
|
|
326
|
+
<!-- how the chart element is placed on the chart -->
|
|
327
|
+
<c:layout />
|
|
328
|
+
${r}
|
|
329
|
+
${W_({backgroundColor:e.data.backgroundColor})}
|
|
330
|
+
</c:plotArea>
|
|
331
|
+
${"none"!==a?function(e,t){return gT`
|
|
332
|
+
<c:legend>
|
|
333
|
+
<c:legendPos val="${e}"/>
|
|
334
|
+
<c:overlay val="0"/>
|
|
335
|
+
${Z_(10,t)}
|
|
336
|
+
</c:legend>
|
|
337
|
+
`}(a,l):""}
|
|
338
|
+
</c:chart>
|
|
339
|
+
</c:chartSpace>
|
|
340
|
+
`;return cT(c)}function W_(e){return gT`
|
|
341
|
+
<c:spPr>
|
|
342
|
+
${e.backgroundColor?$_(e.backgroundColor):""}
|
|
343
|
+
${e.line?function(e){const t=[["cmpd","sng"]];e.width&&t.push(["w",Ex(e.width)]);const s=e.style?gT`<a:prstDash val="${e.style}"/>`:"";return gT`
|
|
344
|
+
<a:ln ${lT(t)}>
|
|
345
|
+
${$_(e.color)}
|
|
346
|
+
${s}
|
|
347
|
+
</a:ln>
|
|
348
|
+
`}(e.line):""}
|
|
349
|
+
</c:spPr>
|
|
350
|
+
`}function $_(e){return gT`
|
|
351
|
+
<a:solidFill>
|
|
352
|
+
<a:srgbClr val="${e}"/>
|
|
353
|
+
</a:solidFill>
|
|
354
|
+
`}function q_(e,t="000000",s=16,o={}){return gT`
|
|
355
|
+
<c:tx>
|
|
356
|
+
<c:rich>
|
|
357
|
+
<a:bodyPr />
|
|
358
|
+
<a:lstStyle />
|
|
359
|
+
<a:p>
|
|
360
|
+
<a:pPr lvl="0">
|
|
361
|
+
<a:defRPr b="${o?.bold?1:0}" i="${o?.italic?1:0}">
|
|
362
|
+
${$_(t)}
|
|
363
|
+
<a:latin typeface="+mn-lt"/>
|
|
364
|
+
</a:defRPr>
|
|
365
|
+
</a:pPr>
|
|
366
|
+
<a:r> <!-- Runs -->
|
|
367
|
+
<a:rPr b="${o?.bold?1:0}" i="${o?.italic?1:0}" sz="${100*s}"/>
|
|
368
|
+
<a:t>${e}</a:t>
|
|
369
|
+
</a:r>
|
|
370
|
+
</a:p>
|
|
371
|
+
</c:rich>
|
|
372
|
+
</c:tx>
|
|
373
|
+
`}function Z_(e=12,t="000000",s=!1,o=!1){return gT`
|
|
374
|
+
<c:txPr>
|
|
375
|
+
<a:bodyPr/>
|
|
376
|
+
<a:lstStyle/>
|
|
377
|
+
<a:p>
|
|
378
|
+
<a:pPr lvl="0">
|
|
379
|
+
<a:defRPr ${lT([["b",s?"1":"0"],["i",o?"1":"0"],["sz",100*e]])}>
|
|
380
|
+
${$_(t)}
|
|
381
|
+
<a:latin typeface="+mn-lt"/>
|
|
382
|
+
</a:defRPr>
|
|
383
|
+
</a:pPr>
|
|
384
|
+
</a:p>
|
|
385
|
+
</c:txPr>
|
|
386
|
+
`}function j_(e,t){if(!e)return gT``;const{type:s,order:o,window:i}=e,n=[];switch(s){case"poly":o&&o>1?(n.push(gT`<c:trendlineType val="poly" />`),n.push(gT`<c:order val="${o}" />`)):n.push(gT`<c:trendlineType val="linear" />`);break;case"movingAvg":n.push(gT`<c:trendlineType val="movingAvg" />`),i&&n.push(gT`<c:period val="${i}" />`);break;default:n.push(gT`<c:trendlineType val="${s}" />`)}return gT`
|
|
387
|
+
<c:trendline>
|
|
388
|
+
${function(e,t){if(!e)return gT``;const s=[["val",e.color?uI(e.color).slice(-6):Y_(t)]];return gT`
|
|
389
|
+
<c:spPr>
|
|
390
|
+
<a:ln w="19050" cap="rnd">
|
|
391
|
+
<a:solidFill>
|
|
392
|
+
<a:srgbClr ${lT(s)}/>
|
|
393
|
+
</a:solidFill>
|
|
394
|
+
<a:prstDash val="sysDot" />
|
|
395
|
+
</a:ln>
|
|
396
|
+
<a:effectLst />
|
|
397
|
+
</c:spPr>
|
|
398
|
+
<c:dispRSqr val="0" />
|
|
399
|
+
<c:dispEq val="0" />
|
|
400
|
+
`}(e,t)}
|
|
401
|
+
${uT(n)}
|
|
402
|
+
</c:trendline>
|
|
403
|
+
`}function Y_(e){return uI(Ov(e,.5))}function X_(e){return e?"text"in e&&e.text?gT`
|
|
404
|
+
<c:tx><c:v>${e.text}</c:v></c:tx>
|
|
405
|
+
`:"reference"in e&&e.reference?gT`
|
|
406
|
+
<c:tx>
|
|
407
|
+
${Q_(e.reference)}
|
|
408
|
+
</c:tx>
|
|
409
|
+
`:gT``:gT``}function K_({showLeaderLines:e}={showLeaderLines:!1}){return gT`
|
|
410
|
+
<dLbls>
|
|
411
|
+
<c:showLegendKey val="0"/>
|
|
412
|
+
<c:showVal val="0"/>
|
|
413
|
+
<c:showCatName val="0"/>
|
|
414
|
+
<c:showSerName val="0"/>
|
|
415
|
+
<c:showPercent val="0"/>
|
|
416
|
+
<c:showBubbleSize val="0"/>
|
|
417
|
+
<c:showLeaderLines val="${e?"1":"0"}"/>
|
|
418
|
+
</dLbls>
|
|
419
|
+
`}function J_(e,t,s,o,i,n,r=0,a="minMax",l,c="nextTo",h,d,u="General"){const g=i?.color?uI(i.color):n,p=i?.fontSize??12;return gT`
|
|
420
|
+
<${t}>
|
|
421
|
+
<c:axId val="${s}"/>
|
|
422
|
+
<c:crossAx val="${o}"/> <!-- reference to the other axe of the chart -->
|
|
423
|
+
<c:crosses val="${l||("b"===e||"l"===e?"min":"max")}"/>
|
|
424
|
+
<c:auto val="1"/>
|
|
425
|
+
${"c:valAx"===t?gT`<c:crossBetween val="between" />`:""}
|
|
426
|
+
<c:delete val="${r}"/> <!-- by default, axis are not displayed -->
|
|
427
|
+
<c:scaling>
|
|
428
|
+
<c:orientation val="${a}" />
|
|
429
|
+
${h?gT`<c:max val="${h}" />`:""}
|
|
430
|
+
${h?gT`<c:min val="${-h}" />`:""}
|
|
431
|
+
</c:scaling>
|
|
432
|
+
${d?gT`<c:majorUnit val="${d}" />`:""}
|
|
433
|
+
<c:axPos val="${e}" />
|
|
434
|
+
<c:tickLblPos val="${c}" />
|
|
435
|
+
${function(e="B7B7B7"){return gT`
|
|
436
|
+
<c:majorGridlines>
|
|
437
|
+
${W_({line:{color:e}})}
|
|
438
|
+
</c:majorGridlines>
|
|
439
|
+
`}()}
|
|
440
|
+
<c:majorTickMark val="out" />
|
|
441
|
+
<c:minorTickMark val="none" />
|
|
442
|
+
<c:numFmt formatCode="${u}" sourceLinked="${"General"===u?"1":"0"}" />
|
|
443
|
+
<c:title>
|
|
444
|
+
${q_(i?.text??"",g,p,i)}
|
|
445
|
+
</c:title>
|
|
446
|
+
${Z_(10,n)}
|
|
447
|
+
</${t}>
|
|
448
|
+
<!-- <tickLblPos/> omitted -->
|
|
449
|
+
`}function Q_(e){return gT`
|
|
450
|
+
<c:strRef>
|
|
451
|
+
<c:f>${e}</c:f>
|
|
452
|
+
</c:strRef>
|
|
453
|
+
`}function eO(e){return gT`
|
|
454
|
+
<c:numRef>
|
|
455
|
+
<c:f>${e}</c:f>
|
|
456
|
+
<c:numCache />
|
|
457
|
+
</c:numRef>
|
|
458
|
+
`}function tO(e,t,s){if(!e)return{attrs:[],node:gT``};const o=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n";default:return}}(t);if(void 0===o)return{attrs:[],node:gT``};var i;return{attrs:[["cm","1"],["t",o]],node:gT`<f t="array" ref="${s}">${oO(e)}</f><v>${(i=t)===bs.InvalidReference?"#REF!":i}</v>`}}function sO(e,t,s=!1){let o=e;const i=[],n=o.trim().toUpperCase();return!s&&["TRUE","FALSE"].includes(n)?(o="TRUE"===n?"1":"0",i.push(["t","b"])):!s&&lo(o,Oc)||(o=Cx(e,t),i.push(["t","s"])),{attrs:i,node:gT`<v>${o}</v>`}}function oO(e){let t;"="===e[0]&&(e=e.slice(1));try{t=Df(e)}catch(t){return e}return t=Of(t,"STRING",iO),t=Of(t,"FUNCALL",e=>e=function(e){const t=e.value.toUpperCase(),s=e.args,o=zS[t];if(o){const i=uf.content[t].args.filter(e=>!e.optional),n=i.length-e.args.length;if(n)for(let t=e.args.length;t<i.length;t++){const e=o[t-n];s.push({type:e.type,value:e.value,tokenEndIndex:0,tokenStartIndex:0})}}return{...e,args:s}}(e=function(e){const t=e.value.toUpperCase();return{...e,value:BS.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()}))),t=Of(t,"REFERENCE",e=>e.value===bs.InvalidReference?{...e,value:"#REF!"}:e),t?_D(t):e}function iO(e){const t=e.value.replace(new RegExp('"',"g"),""),s=Zs(t,Oc);if(s){const o=[];return(Vs.test(t)||Us.test(t))&&o.push("yyyy-mm-dd"),Gs.test(t)&&o.push("hh:mm:ss"),{...e,value:pn(s.value,{format:o.join(" "),locale:Oc})}}return{...e,value:e.value.replace(/\\"/g,'""')}}function nO(e,t){const s=[];for(const o of t)switch(o.rule.type){case"CellIsRule":s.push(rO(o,o.rule,e));break;case"ColorScaleRule":s.push(lO(o,o.rule));break;case"IconSetRule":s.push(cO(o,o.rule));break;case"DataBarRule":s.push(aO(o,o.rule));break;default:console.warn(`Conditional formatting ${o.rule.type} not implemented`)}return s}function rO(e,t,s){const o=hO(e),i=dx(t.operator);o.push(...function(e){const t=dx(e.operator);switch(e.operator){case"containsText":case"notContainsText":case"beginsWithText":case"endsWithText":return[["type",t],["text",e.values[0]]];case"isEmpty":case"isNotEmpty":return[["type",t]];case"isEqual":case"isNotEqual":case"isGreaterThan":case"isGreaterOrEqualTo":case"isLessThan":case"isLessOrEqualTo":case"isBetween":case"isNotBetween":return[["type","cellIs"]];case"customFormula":return[["type","expression"]]}}(t)),i.length&&o.push(["operator",i]);const n=function(e,t){const s=e[0].split(":")[0],o=t.values;switch(t.operator){case"containsText":return[`NOT(ISERROR(SEARCH("${o[0]}",${s})))`];case"notContainsText":return[`ISERROR(SEARCH("${o[0]}",${s}))`];case"beginsWithText":return[`LEFT(${s},LEN("${o[0]}"))="${o[0]}"`];case"endsWithText":return[`RIGHT(${s},LEN("${o[0]}"))="${o[0]}"`];case"isEmpty":return[`LEN(TRIM(${s}))=0`];case"isNotEmpty":return[`LEN(TRIM(${s}))>0`];case"isEqual":case"isNotEqual":case"isGreaterThan":case"isGreaterOrEqualTo":case"isLessThan":case"isLessOrEqualTo":return[o[0]];case"customFormula":return o[0].startsWith("=")?[o[0].slice(1)]:[o[0]];case"isBetween":case"isNotBetween":return[o[0],o[1]]}}(e.ranges,t).map(e=>gT`<formula>${e}</formula>`),r={font:{color:{rgb:t.style.textColor},bold:t.style.bold,italic:t.style.italic,strike:t.style.strikethrough,underline:t.style.underline}};return t.style.fillColor&&(r.fill={fgColor:{rgb:t.style.fillColor}}),o.push(["dxfId",Cx(r,s)]),gT`
|
|
459
|
+
<conditionalFormatting sqref="${e.ranges.join(" ")}">
|
|
460
|
+
<cfRule ${lT(o)}>
|
|
461
|
+
${uT(n)}
|
|
462
|
+
</cfRule>
|
|
463
|
+
</conditionalFormatting>
|
|
464
|
+
`}function aO(e,t){const s=hO(e);return s.push(["type","dataBar"]),gT`
|
|
465
|
+
<conditionalFormatting sqref="${e.ranges.join(" ")}">
|
|
466
|
+
<cfRule ${lT(s)}>
|
|
467
|
+
<dataBar>
|
|
468
|
+
<cfvo type="min" val="0"/>
|
|
469
|
+
<cfvo type="max" val="100"/>
|
|
470
|
+
<color rgb="${uI(fv(t.color))}"/>
|
|
471
|
+
</dataBar>
|
|
472
|
+
</cfRule>
|
|
473
|
+
</conditionalFormatting>
|
|
474
|
+
`}function lO(e,t){const s=hO(e);s.push(["type","colorScale"]);const o=[];for(const i of e.ranges){const e=[],n=[];let r=!0;for(const s of["minimum","midpoint","maximum"]){const o=t[s];o&&("formula"!==o.type?(e.push(pO(o,s)),n.push([["rgb",uI(fv(o.color))]])):r=!1)}if(!r){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const a=e.map(e=>gT`<cfvo ${lT(e)}/>`),l=n.map(e=>gT`<color ${lT(e)}/>`);o.push(gT`
|
|
475
|
+
<conditionalFormatting sqref="${i}">
|
|
476
|
+
<cfRule ${lT(s)}>
|
|
477
|
+
<colorScale>
|
|
478
|
+
${uT(a)}
|
|
479
|
+
${uT(l)}
|
|
480
|
+
</colorScale>
|
|
481
|
+
</cfRule>
|
|
482
|
+
</conditionalFormatting>
|
|
483
|
+
`)}return uT(o)}function cO(e,t){const s=hO(e);s.push(["type","iconSet"]);const o=[];for(const i of e.ranges){const e=[[["type","percent"],["val",0]]];let n=!0;for(const s of["lowerInflectionPoint","upperInflectionPoint"]){if("formula"===t[s].type){n=!1;continue}const o=t[s];e.push([...pO(o,s),["gte","ge"===o.operator?"1":"0"]])}if(!n){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const r=e.map(e=>gT`<cfvo ${lT(e)} />`),a=[["iconSet",uO(t.icons)]];dO(t.icons)&&a.push(["reverse","1"]),o.push(gT`
|
|
484
|
+
<conditionalFormatting sqref="${i}">
|
|
485
|
+
<cfRule ${lT(s)}>
|
|
486
|
+
<iconSet ${lT(a)}>
|
|
487
|
+
${uT(r)}
|
|
488
|
+
</iconSet>
|
|
489
|
+
</cfRule>
|
|
490
|
+
</conditionalFormatting>
|
|
491
|
+
`)}return uT(o)}function hO(e){return[["priority",1],["stopIfTrue",e.stopIfTrue?1:0]]}function dO(e){const t=pR[gO(e)];return e.upper===t.bad&&e.lower===t.good}function uO(e){return hS[gO(e)]}function gO(e){return Object.keys(pR).find(t=>Object.values(pR[t]).includes(e.upper))||"dots"}function pO(e,t){const s=function(e,t){switch(e){case"value":return"minimum"===t?"min":"max";case"number":return"num";case"percentage":return"percent";default:return e}}(e.type,t),o=[["type",s]];if("min"!==s&&"max"!==s){let t=e.value;if("formula"===s)try{t=oO(e.value)}catch(s){t=e.value}o.push(["val",t])}return o}function mO(e){const t=e.length;if(0===t)return[];const s=[new eR(`<dataValidations count="${t}">`)];for(const t of e)switch(t.criterion.type){case"dateIs":case"dateIsBefore":case"dateIsOnOrBefore":case"dateIsAfter":case"dateIsOnOrAfter":case"dateIsBetween":case"dateIsNotBetween":s.push(fO(t));break;case"isEqual":case"isNotEqual":case"isGreaterThan":case"isGreaterOrEqualTo":case"isLessThan":case"isLessOrEqualTo":case"isBetween":case"isNotBetween":s.push(vO(t));break;case"isValueInRange":case"isValueInList":s.push(bO(t));break;case"customFormula":s.push(SO(t));break;default:console.warn(`Data validation ${t.criterion.type} is not supported in xlsx.`)}return s.push(new eR("</dataValidations>")),s}function fO(e){const t=e.criterion,s=oO(t.values[0]),o=t.values[1]?oO(t.values[1]):void 0,i=function(e){return Object.keys(YR).find(t=>YR[t]===e)}(e.criterion.type),n=CO(e);return n.push(["type","date"],["operator",i]),o?gT`
|
|
492
|
+
<dataValidation ${lT(n)}>
|
|
493
|
+
<formula1>${bo(s,Oc)}</formula1>
|
|
494
|
+
<formula2>${bo(o,Oc)}</formula2>
|
|
495
|
+
</dataValidation>
|
|
496
|
+
`:gT`
|
|
497
|
+
<dataValidation ${lT(n)}>
|
|
498
|
+
<formula1>${bo(s,Oc)}</formula1>
|
|
499
|
+
</dataValidation>
|
|
500
|
+
`}function vO(e){const t=e.criterion,s=oO(t.values[0]),o=t.values[1]?oO(t.values[1]):void 0,i=function(e){return Object.keys(jR).find(t=>jR[t]===e)}(e.criterion.type),n=CO(e);return n.push(["type","decimal"],["operator",i]),o?gT`
|
|
501
|
+
<dataValidation ${lT(n)}>
|
|
502
|
+
<formula1>${s}</formula1>
|
|
503
|
+
<formula2>${o}</formula2>
|
|
504
|
+
</dataValidation>
|
|
505
|
+
`:gT`
|
|
506
|
+
<dataValidation ${lT(n)}>
|
|
507
|
+
<formula1>${s}</formula1>
|
|
508
|
+
</dataValidation>
|
|
509
|
+
`}function bO(e){const t=e.criterion,s="isValueInRange"===e.criterion.type?oO(t.values[0]):`"${t.values.join(",")}"`,o=CO(e);return o.push(["type","list"]),gT`
|
|
510
|
+
<dataValidation ${lT(o)}>
|
|
511
|
+
<formula1>${s}</formula1>
|
|
512
|
+
</dataValidation>
|
|
513
|
+
`}function SO(e){const t=oO(e.criterion.values[0]),s=CO(e);return s.push(["type","custom"]),gT`
|
|
514
|
+
<dataValidation ${lT(s)}>
|
|
515
|
+
<formula1>${t}</formula1>
|
|
516
|
+
</dataValidation>
|
|
517
|
+
`}function CO(e){return[["allowBlank","1"],["showInputMessage","1"],["showErrorMessage","1"],["errorStyle",e.isBlocking?"":"warning"],["sqref",e.ranges.join(" ")]]}function yO(e,t,s,o){const i=[["xmlns:xdr",vS],["xmlns:r",LS],["xmlns:a",IS],["xmlns:c",wS]],n=[];for(const[i,r]of Object.entries(s))switch(r?.tag){case"chart":n.push(EO(r,t,e[i],o));break;case"image":n.push(RO(r,t,e[i]))}return cT(gT`
|
|
518
|
+
<xdr:wsDr ${lT(i)}>
|
|
519
|
+
${uT(n)}
|
|
520
|
+
</xdr:wsDr>
|
|
521
|
+
`)}function IO(e,t){const{col:s,row:o,offset:i,width:n,height:r}=e,{x:a,y:l}=i,c=Object.values(t.rows),{index:h,offset:d}=wO(c,o,l),{index:u,offset:g}=wO(c,o,l+r),p=Object.values(t.cols),{index:m,offset:f}=wO(p,s,a),{index:v,offset:b}=wO(p,s,a+n);return{from:{col:m,colOff:f,row:h,rowOff:d},to:{col:v,colOff:b,row:u,rowOff:g}}}function wO(e,t,s){let o=0;for(const[i,n]of e.slice(t).entries()){if(o<=s&&s<o+n.size)return{index:t+i,offset:Ex(s-o+1)};i<e.length-1&&(o+=n.size)}return{index:e.length-1,offset:Ex(s-o+1)}}function EO(e,t,s,o){const{from:i,to:n}=IO(e,t),r=yx(e.id,o),a=[["id",r],["name",`Chart ${r}`],["title","Chart"]];return gT`
|
|
522
|
+
<xdr:twoCellAnchor>
|
|
523
|
+
<xdr:from>
|
|
524
|
+
<xdr:col>${i.col}</xdr:col>
|
|
525
|
+
<xdr:colOff>${i.colOff}</xdr:colOff>
|
|
526
|
+
<xdr:row>${i.row}</xdr:row>
|
|
527
|
+
<xdr:rowOff>${i.rowOff}</xdr:rowOff>
|
|
528
|
+
</xdr:from>
|
|
529
|
+
<xdr:to>
|
|
530
|
+
<xdr:col>${n.col}</xdr:col>
|
|
531
|
+
<xdr:colOff>${n.colOff}</xdr:colOff>
|
|
532
|
+
<xdr:row>${n.row}</xdr:row>
|
|
533
|
+
<xdr:rowOff>${n.rowOff}</xdr:rowOff>
|
|
534
|
+
</xdr:to>
|
|
535
|
+
<xdr:graphicFrame>
|
|
536
|
+
<xdr:nvGraphicFramePr>
|
|
537
|
+
<xdr:cNvPr ${lT(a)} />
|
|
538
|
+
<xdr:cNvGraphicFramePr />
|
|
539
|
+
</xdr:nvGraphicFramePr>
|
|
540
|
+
<xdr:xfrm>
|
|
541
|
+
<a:off x="0" y="0"/>
|
|
542
|
+
<a:ext cx="0" cy="0"/>
|
|
543
|
+
</xdr:xfrm>
|
|
544
|
+
<a:graphic>
|
|
545
|
+
<a:graphicData uri="${wS}">
|
|
546
|
+
<c:chart r:id="${s}" />
|
|
547
|
+
</a:graphicData>
|
|
548
|
+
</a:graphic>
|
|
549
|
+
</xdr:graphicFrame>
|
|
550
|
+
<xdr:clientData fLocksWithSheet="0"/>
|
|
551
|
+
</xdr:twoCellAnchor>
|
|
552
|
+
`}function RO(e,t,s){const{from:o,to:i}=IO(e,t),n=wx(e.id),r=[["id",n],["name",`Image ${n}`],["title","Image"]],a=Ex(e.width),l=Ex(e.height);return gT`
|
|
553
|
+
<xdr:twoCellAnchor editAs="oneCell">
|
|
554
|
+
<xdr:from>
|
|
555
|
+
<xdr:col>${o.col}</xdr:col>
|
|
556
|
+
<xdr:colOff>${o.colOff}</xdr:colOff>
|
|
557
|
+
<xdr:row>${o.row}</xdr:row>
|
|
558
|
+
<xdr:rowOff>${o.rowOff}</xdr:rowOff>
|
|
559
|
+
</xdr:from>
|
|
560
|
+
<xdr:to>
|
|
561
|
+
<xdr:col>${i.col}</xdr:col>
|
|
562
|
+
<xdr:colOff>${i.colOff}</xdr:colOff>
|
|
563
|
+
<xdr:row>${i.row}</xdr:row>
|
|
564
|
+
<xdr:rowOff>${i.rowOff}</xdr:rowOff>
|
|
565
|
+
</xdr:to>
|
|
566
|
+
<xdr:pic>
|
|
567
|
+
<xdr:nvPicPr>
|
|
568
|
+
<xdr:cNvPr ${lT(r)}/>
|
|
569
|
+
<xdr:cNvPicPr preferRelativeResize="0"/>
|
|
570
|
+
</xdr:nvPicPr>
|
|
571
|
+
<xdr:blipFill>
|
|
572
|
+
<a:blip cstate="print" r:embed="${s}"/>
|
|
573
|
+
<a:stretch>
|
|
574
|
+
<a:fillRect/>
|
|
575
|
+
</a:stretch>
|
|
576
|
+
</xdr:blipFill>
|
|
577
|
+
<xdr:spPr>
|
|
578
|
+
<a:xfrm>
|
|
579
|
+
<a:ext cx="${a}" cy="${l}" />
|
|
580
|
+
</a:xfrm>
|
|
581
|
+
<a:prstGeom prst="rect">
|
|
582
|
+
<a:avLst/>
|
|
583
|
+
</a:prstGeom>
|
|
584
|
+
<a:noFill/>
|
|
585
|
+
</xdr:spPr>
|
|
586
|
+
</xdr:pic>
|
|
587
|
+
<xdr:clientData fLocksWithSheet="0"/>
|
|
588
|
+
</xdr:twoCellAnchor>
|
|
589
|
+
`}function xO(e){return Ae(e)?gT``:gT`
|
|
590
|
+
<font>
|
|
591
|
+
${e.bold?gT`<b />`:""}
|
|
592
|
+
${e.italic?gT`<i />`:""}
|
|
593
|
+
${e.underline?gT`<u />`:""}
|
|
594
|
+
${e.strike?gT`<strike />`:""}
|
|
595
|
+
${e.size?gT`<sz val="${e.size}" />`:""}
|
|
596
|
+
${e.color&&e.color.rgb?gT`<color rgb="${uI(e.color.rgb)}" />`:""}
|
|
597
|
+
${e.name?gT`<name val="${e.name}" />`:""}
|
|
598
|
+
</font>
|
|
599
|
+
`}function TO(e){return e?lT([["style",e.style]]):gT``}function AO(e){return e?gT`
|
|
600
|
+
<color ${lT([["rgb",uI(e.color.rgb)]])}/>
|
|
601
|
+
`:gT``}function DO(e,t,s){const o=gT`
|
|
602
|
+
<table ${lT([["id",t],["name",`Table${t}`],["displayName",`Table${t}`],["ref",e.range],["headerRowCount",e.config.numberOfHeaders],["totalsRowCount",e.config.totalRow?1:0],["xmlns",bS],["xmlns:xr",SS],["xmlns:xr3",CS],["xmlns:mc",yS]])}>
|
|
603
|
+
${e.config.hasFilters?function(e){const t=[["ref",e.range]];return gT`
|
|
604
|
+
<autoFilter ${lT(t)}>
|
|
605
|
+
${uT(function(e){const t=[];for(const s of e.filters){const e=gT`
|
|
606
|
+
<filterColumn ${lT([["colId",s.colId]])}>
|
|
607
|
+
${_O(s)}
|
|
608
|
+
</filterColumn>
|
|
609
|
+
`;t.push(e)}return t}(e))}
|
|
610
|
+
</autoFilter>
|
|
611
|
+
`}(e):""}
|
|
612
|
+
${function(e,t){const s=wt(e.range),o=[];for(const i of ge(0,Ut(s).numberOfCols)){const n=mt(s.left+i,s.top),r=[["id",i+1],["name",t.cells[n]||`col${i}`]];if(e.config.totalRow){const e=mt(s.left+i,s.bottom),o=t.cells[e];o?.startsWith("=")&&r.push(["totalsRowFunction","custom"])}o.push(gT`<tableColumn ${lT(r)}/>`)}return gT`
|
|
613
|
+
<tableColumns ${lT([["count",o.length]])}>
|
|
614
|
+
${uT(o)}
|
|
615
|
+
</tableColumns>
|
|
616
|
+
`}(e,s)}
|
|
617
|
+
${function(e){const t=[["name",e.config.styleId],["showFirstColumn",e.config.firstColumn?1:0],["showLastColumn",e.config.lastColumn?1:0],["showRowStripes",e.config.bandedRows?1:0],["showColumnStripes",e.config.bandedColumns?1:0]];return gT`<tableStyleInfo ${lT(t)}/>`}(e)}
|
|
618
|
+
</table>
|
|
619
|
+
`;return cT(o)}function _O(e){const t=e.displayedValues.map(e=>gT`<filter ${lT([["val",e]])}/>`);return gT`
|
|
620
|
+
<filters ${lT(e.displayBlanks?[["blank",1]]:[])}>
|
|
621
|
+
${uT(t)}
|
|
622
|
+
</filters>
|
|
623
|
+
`}function OO(e){if(!Object.values(e).length)return gT``;const t=[];for(const[s,o]of Object.entries(e)){const e=[["min",parseInt(s)+1],["max",parseInt(s)+1],["width",gx(o.size||96)],["customWidth",1],["hidden",o.isHidden?1:0]];o.outlineLevel&&e.push(["outlineLevel",o.outlineLevel]),o.collapsed&&e.push(["collapsed",1]),t.push(gT`
|
|
624
|
+
<col ${lT(e)}/>
|
|
625
|
+
`)}return gT`
|
|
626
|
+
<cols>
|
|
627
|
+
${uT(t)}
|
|
628
|
+
</cols>
|
|
629
|
+
`}function FO(e,t,s){const o=[],i=new YT(cb(s.id,s.styles)),n=new YT(cb(s.id,s.borders)),r=new YT(cb(s.id,s.formats));for(let a=0;a<s.rowNumber;a++){const l=[["r",a+1]],c=s.rows[a]||{};c.size&&c.size!==_&&l.push(["ht",ux(c.size)],["customHeight",1]),c.isHidden&&l.push(["hidden",1]),c.outlineLevel&&l.push(["outlineLevel",c.outlineLevel]),c.collapsed&&l.push(["collapsed",1]);const h=[];for(let o=0;o<s.colNumber;o++){const l=mt(o,a),c=s.cells[l],d=s.cellValues[l],u={sheetId:s.id,col:o,row:a},g=i.get(u),p=r.get(u),m=n.get(u);if(c||g||p||m||void 0!==d){const i=[["r",l]],n=vx(e,fx(t,c,g,p,m));n&&i.push(["s",n]);let r=[],u=gT``;if(c?.startsWith("=")&&void 0!==d){const e=tO(c,d,s.formulaSpillRanges[l]??l);if(!e)continue;({attrs:r,node:u}=e)}else if(c&&Se(c)){const{label:t}=Ie(c);({attrs:r,node:u}=sO(t,e.sharedStrings))}else if(c&&""!==c){const i=PO(o,a,s),n=MO(o,a,s),l=!(!p||!zn(t.formats[p]));({attrs:r,node:u}=sO(c,e.sharedStrings,i||n||l))}i.push(...r),h.push(gT`<c ${lT(i)}>
|
|
630
|
+
${u}
|
|
631
|
+
</c>`)}}(h.length||c.size!==_||c.isHidden||c.outlineLevel||c.collapsed)&&o.push(gT`
|
|
632
|
+
<row ${lT(l)}>
|
|
633
|
+
${uT(h)}
|
|
634
|
+
</row>
|
|
635
|
+
`)}return gT`
|
|
636
|
+
<sheetData>
|
|
637
|
+
${uT(o)}
|
|
638
|
+
</sheetData>
|
|
639
|
+
`}function PO(e,t,s){return s.tables.some(s=>{const o=wt(s.range),i={...o,bottom:o.top};return kt(e,t,i)})}function MO(e,t,s){return s.tables.some(s=>{if(!s.config.totalRow)return!1;const o=wt(s.range),i={...o,top:o.bottom};return kt(e,t,i)})}function NO(e,t,s){const o=t.sheets[s].cells,i=[];for(const n in o){const r=o[n];if(r&&Se(r)){const{label:o,url:a}=Ie(r);if(Ee(a)){const e=xe(a),s=t.sheets.find(t=>t.id===e),r=[["display",o],["location",s?`${s.name}!A1`:bs.InvalidReference],["ref",n]];i.push(gT`
|
|
640
|
+
<hyperlink ${lT(r)}/>
|
|
641
|
+
`)}else{const t=[["r:id",bx(e.relsFiles,`xl/worksheets/_rels/sheet${s}.xml.rels`,{target:Vf(a),type:PS,targetMode:"External"})],["ref",n]];i.push(gT`
|
|
642
|
+
<hyperlink ${lT(t)}/>
|
|
643
|
+
`)}}}return i.length?gT`
|
|
644
|
+
<hyperlinks>
|
|
645
|
+
${uT(i)}
|
|
646
|
+
</hyperlinks>
|
|
647
|
+
`:gT``}function LO(e){if(e.length){const t=e.map(e=>gT`<mergeCell ref="${e}" />`);return gT`
|
|
648
|
+
<mergeCells count="${e.length}">
|
|
649
|
+
${uT(t)}
|
|
650
|
+
</mergeCells>
|
|
651
|
+
`}return gT``}function kO(e){const t=e.panes;let s=gT``;if(t&&(t.xSplit||t.ySplit)){const e=mt(t.xSplit,t.ySplit),o=t.xSplit?gT`xSplit="${t.xSplit}"`:"",i=t.ySplit?gT`ySplit="${t.ySplit}"`:"",n=t.xSplit?gT`<selection pane="topRight"/>`:"",r=t.ySplit?gT`<selection pane="bottomLeft"/>`:"",a=t.xSplit&&t.ySplit?gT`<selection pane="bottomRight"/>`:"";s=gT`
|
|
652
|
+
<pane
|
|
653
|
+
${o}
|
|
654
|
+
${i}
|
|
655
|
+
topLeftCell="${e}"
|
|
656
|
+
activePane="${t.xSplit?t.ySplit?"bottomRight":"topRight":"bottomLeft"}"
|
|
657
|
+
state="frozen"/>
|
|
658
|
+
${n}
|
|
659
|
+
${r}
|
|
660
|
+
${a}
|
|
661
|
+
`}return gT`
|
|
662
|
+
<sheetViews>
|
|
663
|
+
<sheetView ${lT([["showGridLines",e.areGridLinesVisible?1:0],["workbookViewId",0]])}>
|
|
664
|
+
${s}
|
|
665
|
+
</sheetView>
|
|
666
|
+
</sheetViews>
|
|
667
|
+
`}function VO(e){return e.color?gT`
|
|
668
|
+
<sheetPr>
|
|
669
|
+
<tabColor ${lT([["rgb",uI(e.color)]])} />
|
|
670
|
+
</sheetPr>
|
|
671
|
+
`:""}function UO(e){const t=[],s=function(e){const t=[{},...Object.values(e.borders).map(e=>({left:hT(e.left),right:hT(e.right),bottom:hT(e.bottom),top:hT(e.top)}))];return{relsFiles:[],sharedStrings:[],chartIds:[],imageIds:[],styles:[{fontId:0,fillId:0,numFmtId:0,borderId:0,alignment:{}}],fonts:[{size:L,family:2,color:{rgb:"000000"},name:"Arial"}],fills:[{reservedAttribute:"none"},{reservedAttribute:"gray125"}],borders:t,numFmts:[],dxfs:[]}}(e=function(e){for(const t of e.sheets)t.tables=t.tables.filter(e=>Ut(wt(e.range)).numberOfRows>1);return e}(e=function(e){const t={},s=[];for(const o of e.sheets){let e=o.name.slice(0,31);e=st(e,s,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),s.push(e),e!==o.name&&(t[o.name]=e,o.name=e)}if(!Object.keys(t).length)return e;const o=Object.keys(t).sort((e,t)=>t.length-e.length);let i=JSON.stringify(e);for(const e of o){const s=new RegExp(`'?${re(e)}'?!`,"g");i=i.replaceAll(s,s=>{const o=t[e];return s.replace(e,o)})}return JSON.parse(i)}(e)));return t.push(function(e,t){const s=[["xmlns",fS],["xmlns:r",LS]],o=[];for(const[s,i]of Object.entries(e.sheets)){const e=[["state",i.isVisible?"visible":"hidden"],["name",i.name],["sheetId",parseInt(s)+1],["r:id",`rId${parseInt(s)+1}`]];o.push(gT`
|
|
672
|
+
<sheet ${lT(e)} />
|
|
673
|
+
`),bx(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:xS,target:`worksheets/sheet${s}.xml`})}return rT(cT(gT`
|
|
674
|
+
<workbook ${lT(s)}>
|
|
675
|
+
<sheets>
|
|
676
|
+
${uT(o)}
|
|
677
|
+
</sheets>
|
|
678
|
+
</workbook>
|
|
679
|
+
`),"xl/workbook.xml","workbook")}(e,s)),t.push(...function(e,t){const s=[];let o=1;for(const[i,n]of Object.entries(e.sheets)){const r=[["xmlns",mS],["xmlns:r",LS]],a=[["defaultRowHeight",ux(_)],["defaultColWidth",gx(96)]],l=HO(n,i,o,t,s);o+=n.tables.length;let c=gT``;const h=[];for(const o of n.charts){const n=yx(o.id,t),r=bx(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../charts/chart${n}.xml`,type:OS});h.push(r),s.push(rT(G_(o,i,e),`xl/charts/chart${n}.xml`,"chart"))}for(const e of n.images){const o=e.data.mimetype;if(void 0===o)continue;const n=qR[o];if(void 0===n)continue;const r=`image${wx(e.id)}.${n}`,a=bx(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../media/${r}`,type:MS});h.push(a),s.push({path:`xl/media/${r}`,imageSrc:e.data.path})}const d=[...n.charts,...n.images];if(d.length){const e=bx(t.relsFiles,`xl/worksheets/_rels/sheet${i}.xml.rels`,{target:`../drawings/drawing${i}.xml`,type:_S});s.push(rT(yO(h,n,d,t),`xl/drawings/drawing${i}.xml`,"drawing")),c=gT`<drawing r:id="${e}" />`}const u=gT`
|
|
680
|
+
<worksheet ${lT(r)}>
|
|
681
|
+
${VO(n)}
|
|
682
|
+
${kO(n)}
|
|
683
|
+
<sheetFormatPr ${lT(a)} />
|
|
684
|
+
${OO(n.cols)}
|
|
685
|
+
${FO(t,e,n)}
|
|
686
|
+
${LO(n.merges)}
|
|
687
|
+
${uT(nO(t.dxfs,n.conditionalFormats))}
|
|
688
|
+
${uT(mO(n.dataValidationRules))}
|
|
689
|
+
${NO(t,e,i)}
|
|
690
|
+
${c}
|
|
691
|
+
${l}
|
|
692
|
+
</worksheet>
|
|
693
|
+
`;s.push(rT(cT(u),`xl/worksheets/sheet${i}.xml`,"sheet"))}const i=gT`
|
|
694
|
+
<metadata xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:xda="http://schemas.microsoft.com/office/spreadsheetml/2017/dynamicarray">
|
|
695
|
+
<metadataTypes count="1">
|
|
696
|
+
<metadataType name="XLDAPR" minSupportedVersion="120000" copy="1" pasteAll="1"
|
|
697
|
+
pasteValues="1" merge="1" splitFirst="1" rowColShift="1" clearFormats="1"
|
|
698
|
+
clearComments="1" assign="1" coerce="1" cellMeta="1" />
|
|
699
|
+
</metadataTypes>
|
|
700
|
+
<futureMetadata name="XLDAPR" count="1">
|
|
701
|
+
<bk>
|
|
702
|
+
<extLst>
|
|
703
|
+
<ext uri="{${NS}}">
|
|
704
|
+
<xda:dynamicArrayProperties fDynamic="1" fCollapsed="0" />
|
|
705
|
+
</ext>
|
|
706
|
+
</extLst>
|
|
707
|
+
</bk>
|
|
708
|
+
</futureMetadata>
|
|
709
|
+
<cellMetadata count="1">
|
|
710
|
+
<bk>
|
|
711
|
+
<rc t="1" v="0" />
|
|
712
|
+
</bk>
|
|
713
|
+
</cellMetadata>
|
|
714
|
+
</metadata>
|
|
715
|
+
`;return s.push(rT(cT(i),"xl/metadata.xml","metadata")),bx(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:AS,target:"sharedStrings.xml"}),bx(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:DS,target:"styles.xml"}),bx(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:TS,target:"metadata.xml"}),s}(e,s)),t.push(function(e){const t=gT`
|
|
716
|
+
<styleSheet ${lT([["xmlns",dS],["xmlns:r",LS]])}>
|
|
717
|
+
${function(e){const t=[];for(const[s,o]of Object.entries(e)){const e=[["numFmtId",parseInt(s)+164],["formatCode",o.format]];t.push(gT`
|
|
718
|
+
<numFmt ${lT(e)}/>
|
|
719
|
+
`)}return gT`
|
|
720
|
+
<numFmts count="${e.length}">
|
|
721
|
+
${uT(t)}
|
|
722
|
+
</numFmts>
|
|
723
|
+
`}(e.numFmts)}
|
|
724
|
+
${s=e.fonts,gT`
|
|
725
|
+
<fonts count="${s.length}">
|
|
726
|
+
${uT(Object.values(s).map(xO))}
|
|
727
|
+
</fonts>
|
|
728
|
+
`}
|
|
729
|
+
${function(e){const t=[];for(const s of Object.values(e))void 0!==s.reservedAttribute?t.push(gT`
|
|
730
|
+
<fill>
|
|
731
|
+
<patternFill patternType="${s.reservedAttribute}" />
|
|
732
|
+
</fill>
|
|
733
|
+
`):t.push(gT`
|
|
734
|
+
<fill>
|
|
735
|
+
<patternFill patternType="solid">
|
|
736
|
+
<fgColor rgb="${uI(s.fgColor.rgb)}" />
|
|
737
|
+
<bgColor indexed="64" />
|
|
738
|
+
</patternFill>
|
|
739
|
+
</fill>
|
|
740
|
+
`);return gT`
|
|
741
|
+
<fills count="${e.length}">
|
|
742
|
+
${uT(t)}
|
|
743
|
+
</fills>
|
|
744
|
+
`}(e.fills)}
|
|
745
|
+
${function(e){const t=[];for(const s of Object.values(e))t.push(gT`
|
|
746
|
+
<border>
|
|
747
|
+
<left ${TO(s.left)}>
|
|
748
|
+
${AO(s.left)}
|
|
749
|
+
</left>
|
|
750
|
+
<right ${TO(s.right)}>
|
|
751
|
+
${AO(s.right)}
|
|
752
|
+
</right>
|
|
753
|
+
<top ${TO(s.top)}>
|
|
754
|
+
${AO(s.top)}
|
|
755
|
+
</top>
|
|
756
|
+
<bottom ${TO(s.bottom)}>
|
|
757
|
+
${AO(s.bottom)}
|
|
758
|
+
</bottom>
|
|
759
|
+
<diagonal ${TO(s.diagonal)}>
|
|
760
|
+
${AO(s.diagonal)}
|
|
761
|
+
</diagonal>
|
|
762
|
+
</border>
|
|
763
|
+
`);return gT`
|
|
764
|
+
<borders count="${e.length}">
|
|
765
|
+
${uT(t)}
|
|
766
|
+
</borders>
|
|
767
|
+
`}(e.borders)}
|
|
768
|
+
${function(e){const t=[];for(const s of e){const e=[["numFmtId",s.numFmtId],["fillId",s.fillId],["fontId",s.fontId],["borderId",s.borderId]],o=[];s.alignment&&s.alignment.vertical&&o.push(["vertical",s.alignment.vertical]),s.alignment&&s.alignment.horizontal&&o.push(["horizontal",s.alignment.horizontal]),s.alignment&&s.alignment.wrapText&&o.push(["wrapText","1"]),o.length>0?(e.push(["applyAlignment","1"]),t.push(gT`<xf ${lT(e)}><alignment ${lT(o)} /></xf> `)):t.push(gT`<xf ${lT(e)} />`)}return gT`
|
|
769
|
+
<cellXfs count="${e.length}">
|
|
770
|
+
${uT(t)}
|
|
771
|
+
</cellXfs>
|
|
772
|
+
`}(e.styles)}
|
|
773
|
+
${function(e){const t=[];for(const s of e){let e=gT``;s.font&&(e=xO(s.font));let o=gT``;s.fill&&(o=gT`
|
|
774
|
+
<fill>
|
|
775
|
+
<patternFill>
|
|
776
|
+
<bgColor rgb="${uI(s.fill.fgColor.rgb)}" />
|
|
777
|
+
</patternFill>
|
|
778
|
+
</fill>
|
|
779
|
+
`),t.push(gT`
|
|
780
|
+
<dxf>
|
|
781
|
+
${e}
|
|
782
|
+
${o}
|
|
783
|
+
</dxf>
|
|
784
|
+
`)}return gT`
|
|
785
|
+
<dxfs count="${e.length}">
|
|
786
|
+
${uT(t)}
|
|
787
|
+
</dxfs>
|
|
788
|
+
`}(e.dxfs)}
|
|
789
|
+
</styleSheet>
|
|
790
|
+
`;var s;return rT(cT(t),"xl/styles.xml","styles")}(s)),t.push(function(e){const t=[["xmlns",uS],["count",e.length],["uniqueCount",e.length]],s=e.map(e=>e.trim()!==e?gT`<si><t xml:space="preserve">${e}</t></si>`:gT`<si><t>${e}</t></si>`);return rT(cT(gT`
|
|
791
|
+
<sst ${lT(t)}>
|
|
792
|
+
${uT(s)}
|
|
793
|
+
</sst>
|
|
794
|
+
`),"xl/sharedStrings.xml","sharedStrings")}(s.sharedStrings)),t.push(...function(e){const t=[];for(const s of e){const e=[];for(const t of s.rels){const s=[["Id",t.id],["Target",t.target],["Type",t.type]];t.targetMode&&s.push(["TargetMode",t.targetMode]),e.push(gT`
|
|
795
|
+
<Relationship ${lT(s)} />
|
|
796
|
+
`)}const o=gT`
|
|
797
|
+
<Relationships xmlns="${gS}">
|
|
798
|
+
${uT(e)}
|
|
799
|
+
</Relationships>
|
|
800
|
+
`;t.push(rT(cT(o),s.path))}return t}(s.relsFiles)),t.push(function(e){const t=[],s=Object.entries(qR).map(([e,t])=>function(e,t){return gT`
|
|
801
|
+
<Default Extension="${e}" ContentType="${t}" />
|
|
802
|
+
`}(t,e));for(const s of e)"contentType"in s&&s.contentType&&t.push(dT("/"+s.path,ES[s.contentType]));const o=[["Extension","rels"],["ContentType","application/vnd.openxmlformats-package.relationships+xml"]],i=[["Extension","xml"],["ContentType","application/xml"]];return rT(cT(gT`
|
|
803
|
+
<Types xmlns="${pS}">
|
|
804
|
+
${uT(Object.values(s))}
|
|
805
|
+
<Default ${lT(o)} />
|
|
806
|
+
<Default ${lT(i)} />
|
|
807
|
+
${uT(t)}
|
|
808
|
+
</Types>
|
|
809
|
+
`),"[Content_Types].xml")}(t)),t.push(rT(cT(gT`
|
|
810
|
+
<Relationships xmlns="${gS}">
|
|
811
|
+
<Relationship ${lT([["Id","rId1"],["Type",RS],["Target","xl/workbook.xml"]])} />
|
|
812
|
+
</Relationships>
|
|
813
|
+
`),"_rels/.rels")),{name:"my_spreadsheet.xlsx",files:t}}function HO(e,t,s,o,i){let n=s;if(!e.tables.length)return new eR("");const r=`xl/worksheets/_rels/sheet${t}.xml.rels`,a=[];for(const t of e.tables){const s=bx(o.relsFiles,r,{target:`../tables/table${n}.xml`,type:FS});i.push(rT(DO(t,n,e),`xl/tables/table${n}.xml`,"table")),a.push(gT`<tablePart r:id="${s}" />`),n++}return gT`
|
|
814
|
+
<tableParts count="${e.tables.length}">
|
|
815
|
+
${uT(a)}
|
|
816
|
+
</tableParts>
|
|
817
|
+
`}var zO;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(zO||(zO={}));function BO(e,t={}){const s=ae(t);return s.type=e,s}function GO(e){return e.dataRange&&!Xn.test(e.dataRange)?"InvalidGaugeDataRange":"Success"}function WO(e,t){return t(t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):"Success",t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):"Success")}function $O(e,t){if(""===e)switch(t){case"rangeMin":return"EmptyGaugeRangeMin";case"rangeMax":return"EmptyGaugeRangeMax"}return"Success"}function qO(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"}class ZO extends ny{dataRange;sectionRule;background;type="gauge";constructor(e,t,s){super(e,t,s),this.dataRange=Rb(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,GO,e.chainValidations(WO($O,e.batchValidations),WO(qO,e.batchValidations)),e.chainValidations((s=qO,(0,e.batchValidations)(e=>e.sectionRule?s(e.sectionRule.lowerInflectionPoint.value,"lowerInflectionPointValue"):"Success",e=>e.sectionRule?s(e.sectionRule.upperInflectionPoint.value,"upperInflectionPointValue"):"Success"))));var s}static transformDefinition(e,t,s){let o;if(t.dataRange){const i=$S(e,t.dataRange,s);i!==bs.InvalidReference&&(o=i)}return{...t,dataRange:o}}static getDefinitionFromContextCreation(e){return{background:e.background,title:e.title||{text:""},type:"gauge",dataRange:e.range?e.range[0].dataRange:void 0,sectionRule:{colors:{lowerColor:"#EA6175",middleColor:"#FFD86D",upperColor:"#43C5B1"},rangeMin:"0",rangeMax:"100",lowerInflectionPoint:{type:"percentage",value:"15",operator:"<="},upperInflectionPoint:{type:"percentage",value:"40",operator:"<="}},humanize:e.humanize}}duplicateInDuplicatedSheet(e){const t=JS(this.sheetId,e,this.dataRange),s=KO(this.sectionRule,t=>this.getters.copyFormulaStringForSheet(this.sheetId,e,t,"moveReference")),o=this.getDefinitionWithSpecificRanges(t,s,e);return new ZO(o,e,this.getters)}copyInSheetId(e){const t=KO(this.sectionRule,t=>this.getters.copyFormulaStringForSheet(this.sheetId,e,t,"keepSameReference")),s=this.getDefinitionWithSpecificRanges(this.dataRange,t,e);return new ZO(s,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.dataRange,this.sectionRule)}getDefinitionWithSpecificRanges(e,t,s){return{background:this.background,sectionRule:t,title:this.title,type:"gauge",dataRange:e?this.getters.getRangeString(e,s||this.sheetId):void 0,humanize:this.humanize}}getDefinitionForExcel(){}getContextCreation(){return{...this,range:this.dataRange?[{dataRange:this.getters.getRangeString(this.dataRange,this.sheetId)}]:void 0}}updateRanges(e,t,s){const o=QS(this.dataRange,e),i=KO(this.sectionRule,o=>WS(this.sheetId,o,{applyChange:e,sheetId:t,sheetName:s})),n=this.getDefinitionWithSpecificRanges(o,i);return new ZO(n,this.sheetId,this.getters)}}function jO(e,t){const s=t.getLocale(),o=e.sectionRule.colors;let i,n,r;const a=e.dataRange;if(void 0!==a){const e=t.getEvaluatedCell({sheetId:a.sheetId,col:a.zone.left,row:a.zone.top});e.type===_d.number&&(i=e.value,n=e.formattedValue,r=e.format)}let l=XO(e.sheetId,e.sectionRule.rangeMin,t),c=XO(e.sheetId,e.sectionRule.rangeMax,t);if(void 0===l||void 0===c)return function(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:bs.GenericError},inflectionValues:[],colors:[]}}(e,t);c<l&&([l,c]=[c,l]);const h=e.sectionRule.lowerInflectionPoint,d=e.sectionRule.upperInflectionPoint,u=YO(e.sheetId,e.sectionRule.lowerInflectionPoint,l,c,t),g=YO(e.sheetId,e.sectionRule.upperInflectionPoint,l,c,t),p=[],m=[];return void 0!==u&&(p.push({value:u,label:gn(u,r,s,e.humanize),operator:h.operator}),m.push(o.lowerColor)),void 0!==g&&g!==u&&(p.push({value:g,label:gn(g,r,s,e.humanize),operator:d.operator}),m.push(o.middleColor)),void 0!==g&&void 0!==u&&u>g&&(p.reverse(),m.reverse()),m.push(o.upperColor),{background:t.getStyleOfSingleCellChart(e.background,a).background,title:{...e.title,text:e.title.text?t.dynamicTranslate(e.title.text):""},minValue:{value:l,label:gn(l,r,s,e.humanize)},maxValue:{value:c,label:gn(c,r,s,e.humanize)},gaugeValue:void 0!==i&&n?{value:i,label:e.humanize?Mn({value:i,format:r},s):n}:void 0,inflectionValues:p,colors:m}}function YO(e,t,s,o,i){const n=XO(e,t.value,i);if(void 0===n)return;return ue("number"===t.type?n:s+(o-s)*n/100,s,o)}function XO(e,t,s){const o=s.evaluateFormula(e,t);return bi(o)?void 0:So(fi(o),s.getLocale())}function KO(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)}}}class JO extends ny{dataSets;labelRange;background;legendPosition;labelsAsText;stacked;aggregated;type="line";dataSetsHaveTitle;cumulative;dataSetDesign;axesDesign;fillArea;showValues;hideDataMarkers;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=eC(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(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,this.zoomable=e.zoomable}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static transformDefinition(e,t,s){return iC(e,t,s)}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,zoomable:e.zoomable,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"line",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||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,zoomable:this.zoomable,humanize:this.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new JO(i,this.sheetId,this.getters)}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,cC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:uI(this.background||c),fontColor:uI(nC(this.background)),dataSets:e,labelRange:t,verticalAxis:hC(s)}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new JO(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new JO(t,e,this.getters)}}function QO(e,t){const s=e.getDefinition(),o=OI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"line",data:{labels:o.labels,datasets:NC(s,o)},options:{...nI,layout:QI(0,o),scales:uw(s,o),plugins:{title:Dw(s,t),legend:sw(s),tooltip:Mw(s,o),chartShowValuesPlugin:Rw(s,o)}}},background:e.background||c}}class eF extends ny{dataSets;labelRange;background;legendPosition;type="pie";aggregated;dataSetsHaveTitle;isDoughnut;showValues;pieHolePercentage;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,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,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}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:e.isDoughnut,pieHolePercentage:e.pieHolePercentage,showValues:e.showValues,humanize:e.humanize}}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,s){return{type:"pie",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,s||this.sheetId)})),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,isDoughnut:this.isDoughnut,showValues:this.showValues,pieHolePercentage:this.pieHolePercentage,humanize:this.humanize}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new eF(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new eF(t,e,this.getters)}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,cC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:uI(this.background||c),fontColor:uI(nC(this.background)),dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new eF(i,this.sheetId,this.getters)}}function tF(e,t){const s=e.getDefinition(),o=FI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:e.isDoughnut?"doughnut":"pie",data:{labels:o.labels,datasets:kC(s,o)},options:{...nI,cutout:e.isDoughnut&&void 0!==s.pieHolePercentage?s.pieHolePercentage+"%":void 0,layout:QI(0,o),plugins:{title:Dw(s,t),legend:ow(s,o),tooltip:Nw(s,o),chartShowValuesPlugin:Rw(s,o)}}},background:e.background||c}}class sF extends ny{dataSets;labelRange;background;verticalAxisPosition;legendPosition;aggregated;type="waterfall";dataSetsHaveTitle;showSubTotals;firstValueAsSubtotal;showConnectorLines;positiveValuesColor;negativeValuesColor;subTotalValuesColor;dataSetDesign;axesDesign;showValues;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,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,this.zoomable=e.zoomable}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}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,zoomable:e.zoomable??!1,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new sF(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new sF(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"waterfall",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,s||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,zoomable:this.zoomable,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new sF(i,this.sheetId,this.getters)}}function oF(e,t){const s=e.getDefinition(),o=DI(s,e.dataSets,e.labelRange,t),{labels:i,datasets:n}=MC(s,o);return{chartJsConfig:{type:"bar",data:{labels:i,datasets:n},options:{...nI,layout:QI(0,o),scales:pw(s,o),plugins:{title:Dw(s,t),legend:rw(s),tooltip:Lw(s,o),chartShowValuesPlugin:Aw(s,o),waterfallLinesPlugin:{showConnectorLines:s.showConnectorLines}}}},background:e.background||c}}var iF=Object.freeze({__proto__:null,AbstractChart:ny,BarChart:qw,CHART_AXIS_CHOICES:gC,CHART_COMMON_OPTIONS:nI,GaugeChart:ZO,LineChart:JO,MOVING_AVERAGE_TREND_LINE_XAXIS_ID:jS,PieChart:eF,SPREADSHEET_TO_EXCEL_TRENDLINE_TYPE_MAPPING:YS,ScorecardChart:gy,TREND_LINE_XAXIS_ID:ZS,WaterfallChart:sF,adaptChartRange:QS,chartFactory:qy,chartFontColor:nC,chartMutedFontColor:rC,chartRuntimeFactory:Zy,chartToImageFile:aI,chartToImageUrl:rI,checkDataset:aC,checkLabelRange:lC,createBarChartRuntime:Zw,createDataSets:eC,createGaugeChartRuntime:jO,createLineChartRuntime:QO,createPieChartRuntime:tF,createScorecardChartRuntime:my,createWaterfallChartRuntime:oF,drawScoreChart:py,duplicateDataSetsInDuplicatedSheet:KS,duplicateLabelRangeInDuplicatedSheet:JS,formatChartDatasetValue:dC,formatTickValue:uC,getChartPositionAtCenterOfViewport:function(e,t){const{x:s,y:o}=e.getMainViewportCoordinates(),{scrollX:i,scrollY:n}=e.getActiveSheetScrollInfo(),{width:r,height:a}=e.getVisibleRect(e.getActiveMainViewport());return{x:s+i+Math.max(0,(r-t.width)/2),y:o+n+Math.max(0,(a-t.height)/2)}},getDefinedAxis:hC,getPieColors:pC,isTrendLineAxis:fC,shouldRemoveFirstLabel:cC,toExcelDataset:sC,toExcelLabelRange:oC,transformChartDefinitionWithDataSetsWithZone:iC,transformDefinition:Yy,truncateLabel:mC,updateChartRangesWithDataSets:XS,validateChartDefinition:jy});function nF(e,t,s){if(!s.model.getters.getChartIdFromFigureId(e))return[];return qf([{id:"edit",name:fs("Edit"),execute:()=>{s.model.dispatch("SELECT_FIGURE",{figureId:e}),s.openSidePanel("ChartPanel")},icon:"o-spreadsheet-Icon.EDIT",isEnabled:e=>!e.isSmall},rF(e,s),aF(e,s),lF(e,s),cF(e,s),hF(e,t,s)]).filter(e=>!s.model.getters.isReadonly()||e.isReadonlyAllowed)}function rF(e,t,s){return{id:"copy",name:fs("Copy"),description:"Ctrl+C",execute:async()=>{t.model.dispatch("SELECT_FIGURE",{figureId:e}),t.model.dispatch("COPY");const o=await t.model.getters.getClipboardTextAndImageContent();await t.clipboard.write(o),s&&t.notifyUser({sticky:!1,type:"success",text:s})},icon:"o-spreadsheet-Icon.CLIPBOARD"}}function aF(e,t){return{id:"cut",name:fs("Cut"),description:"Ctrl+X",execute:async()=>{t.model.dispatch("SELECT_FIGURE",{figureId:e}),t.model.dispatch("CUT"),await t.clipboard.write(await t.model.getters.getClipboardTextAndImageContent())},icon:"o-spreadsheet-Icon.CUT"}}function lF(e,t){return{id:"copy_as_image",name:fs("Copy as image"),icon:"o-spreadsheet-Icon.COPY_AS_IMAGE",execute:async()=>{const s=t.model.getters.getFigureSheetId(e),o=t.model.getters.getFigure(s,e),i=t.model.getters.getChartIdFromFigureId(e);if(!i)return;const n=t.model.getters.getChartType(i),r=t.model.getters.getChartRuntime(i),a=await aI(r,o,n);if(!a)return;const l=await new Promise(e=>{const t=new FileReader;t.addEventListener("loadend",s=>{const o=t.result;e(o)}),t.readAsArrayBuffer(a)}),c=`<img src="data:image/png;base64,${new Uint8Array(l).toBase64()}" />`;t.clipboard.write({"text/html":c,"image/png":a}),t.notifyUser({sticky:!1,type:"success",text:fs("Chart copied to clipboard")})},isReadonlyAllowed:!0}}function cF(e,t){return{id:"download",name:fs("Download"),icon:"o-spreadsheet-Icon.DOWNLOAD",execute:async()=>{const s=t.model.getters.getFigureSheetId(e),o=t.model.getters.getFigure(s,e),i=t.model.getters.getChartIdFromFigureId(e);if(!i)return;const n=t.model.getters.getChartType(i),r=t.model.getters.getChartRuntime(i),a=await rI(r,o,n);a&&zy(a,"chart")},isReadonlyAllowed:!0}}function hF(e,t,s){return{id:"delete",name:fs("Delete"),execute:()=>{s.model.dispatch("DELETE_FIGURE",{sheetId:s.model.getters.getActiveSheetId(),figureId:e}),t()},icon:"o-spreadsheet-Icon.TRASH"}}const dF=[ZS,jS],uF=["x",...dF];class gF extends hv{mutators=["resetAxisLimits","updateAxisLimits","updateTrendLineConfiguration","clearAxisLimits"];originalAxisLimits={};currentAxesLimits={};idConversion={};handle(e){switch(e.type){case"DELETE_FIGURE":if(e.figureId&&this.idConversion[e.figureId])for(const t of this.idConversion[e.figureId])delete this.originalAxisLimits[t],delete this.currentAxesLimits[t];break;case"UPDATE_CHART":const t=`${e.definition.type}-${e.figureId}`;this.idConversion[e.figureId]||(this.idConversion[e.figureId]=new Set),this.idConversion[e.figureId].add(t),"zoomable"in e.definition&&e.definition.zoomable||this.clearAxisLimits(t)}}clearAxisLimits(e){return delete this.originalAxisLimits[e],delete this.currentAxesLimits[e],"noStateChange"}resetAxisLimits(e,t){for(const s of uF)t?.[s]?(this.originalAxisLimits[e]?.[s]||(this.originalAxisLimits[e]={...this.originalAxisLimits[e],[s]:{}}),this.originalAxisLimits[e][s].min=t[s].min,this.originalAxisLimits[e][s].max=t[s].max):this.originalAxisLimits[e]?.[s]&&delete this.originalAxisLimits[e][s];return"noStateChange"}updateAxisLimits(e,t){if(void 0===t)return delete this.currentAxesLimits[e],"noStateChange";let{min:s,max:o}=t;return s>o&&([s,o]=[o,s]),this.currentAxesLimits[e]={x:{min:s,max:o}},"noStateChange"}updateTrendLineConfiguration(e){if(!this.originalAxisLimits[e])return"noStateChange";const t=this.originalAxisLimits[e].x;if(void 0===t)return"noStateChange";for(const s of dF){if(!this.originalAxisLimits[e][s])continue;if(this.currentAxesLimits[e]?.[s]||(this.currentAxesLimits[e]={...this.currentAxesLimits[e],[s]:{}}),void 0===this.currentAxesLimits[e]?.x)return"noStateChange";const o=t.max-t.min,i=this.originalAxisLimits[e][s],n=(i.max-i.min)/o,r=i.min-t.min*n,a=this.currentAxesLimits[e].x.min,l=this.currentAxesLimits[e].x.max;this.currentAxesLimits[e][s].min=a*n+r,this.currentAxesLimits[e][s].max=l*n+r}return"noStateChange"}}const pF={id:"zoomWindowPlugin",afterDatasetsDraw:function(e,t,s){if(!s.getLowerBound||!s.getUpperBound)return;const{ctx:o,chartArea:{left:i,right:n,top:r,bottom:a}}=e;let l=s.getLowerBound()??i,c=s.getUpperBound()??n;l>c&&([l,c]=[c,l]),l=Math.max(i,l),c=Math.min(n,c),l===i&&(l-=1),c===n&&(c+=1),o.save(),o.fillStyle="rgba(255,255,255,0.5)",o.beginPath(),o.rect(i,a,l-i,r-a),o.rect(c,a,n-c,r-a),o.fill(),o.beginPath(),o.strokeStyle="#bbb",o.rect(l,a,c-l,r-a),o.stroke(),o.lineWidth=2,o.beginPath(),o.moveTo(l-3,(r+a)/2-7),o.lineTo(l-3,(r+a)/2+7),o.stroke(),o.beginPath(),o.moveTo(c+3,(r+a)/2-7),o.lineTo(c+3,(r+a)/2+7),o.stroke(),o.restore()}};sS.add("zoomWindowPlugin",{register:e=>e.register(pF),unregister:e=>e.unregister(pF)});class mF extends iy{static template="o-spreadsheet-ZoomableChartJsComponent";store;masterChartCanvas=t.useRef("masterChartCanvas");masterChart;mode;hasLinearScale;isBarChart;chartId="";datasetBoundaries={xMin:0,xMax:0};removeEventListeners=()=>{};setup(){this.store=ev(gF),super.setup()}unmount(){super.unmount(),this.masterChart?.destroy(),this.removeEventListeners()}get containerStyle(){return`\n height:${this.sliceable?"calc(100% - 60px)":"100%"};\n `}get sliceable(){if(this.props.isFullScreen)return!0;const e=this.env.model.getters.getChartDefinition(this.props.chartId);return("zoomable"in e&&e?.zoomable)??!1}get axisOffset(){return!this.hasLinearScale&&this.isBarChart?.5:0}getMasterChartConfiguration(e){const t=e;return{...t,options:{...t.options,plugins:{...t.options.plugins,zoomWindowPlugin:{getLowerBound:()=>this.lowerBound,getUpperBound:()=>this.upperBound}}}}}getDetailChartConfiguration(e){if(!this.sliceable)return e;const t=this.store.currentAxesLimits[this.chartId]?.x,s={...e.options.scales?.x};return void 0!==t?.min&&(s.min=this.hasLinearScale?t.min:Math.ceil(t.min)-this.axisOffset),void 0!==t?.max&&(s.max=this.hasLinearScale?t.max:Math.floor(t.max)-this.axisOffset),{...e,options:{...e.options,scales:{...e.options.scales,x:s},layout:{...e.options.layout,padding:{...e.options.layout?.padding,bottom:5}}}}}getAxisLimitsFromDataset(e){const t=e.data.datasets.map(e=>e.data).flat().map((e,t)=>"object"==typeof e&&null!==e?e.x:t);return{xMin:Math.min(...t),xMax:Math.max(...t)}}createChart(e){const t=e.chartJsConfig;if(this.isBarChart="bar"===t.type,this.chartId=`${t.type}-${this.props.chartId}`,this.datasetBoundaries=this.getAxisLimitsFromDataset(t),this.sliceable){const s=this.getDetailChartConfiguration(t);e.chartJsConfig=s}if(super.createChart(e),this.hasLinearScale="linear"===this.chart?.scales?.x.type,!this.sliceable||!("masterChartConfig"in e))return;this.masterChart?.destroy();const s=this.masterChartCanvas.el.getContext("2d");this.masterChart=new window.Chart(s,this.getMasterChartConfiguration(e.masterChartConfig)),this.resetAxesLimits(),this.chart?.options&&(this.chart.options.animation=!1)}updateChartJs(e){const t=e.chartJsConfig,s=this.getAxisLimitsFromDataset(t);if(this.datasetBoundaries.xMin===s.xMin&&this.datasetBoundaries.xMax===s.xMax||(this.store.clearAxisLimits(this.chartId),this.datasetBoundaries=s),this.isBarChart="bar"===t?.type,this.chartId=`${t.type}-${this.props.chartId}`,this.sliceable){const s=this.getDetailChartConfiguration(t);e.chartJsConfig=s}if(super.updateChartJs(e),this.hasLinearScale="linear"===this.chart?.scales?.x.type,this.sliceable&&"masterChartConfig"in e){const t=this.getMasterChartConfiguration(e.masterChartConfig);if(this.masterChart)this.masterChart.data=t.data,this.masterChart.config.options=t.options,this.masterChart.update();else{const e=this.masterChartCanvas.el.getContext("2d");this.masterChart=new window.Chart(e,t)}}else this.masterChart=void 0;this.resetAxesLimits(),this.chart?.options&&(this.chart.options.animation=!1)}resetAxesLimits(){if(!this.chart)return;const e=this.store.originalAxisLimits[this.chartId];if(void 0===e?.x?.min&&void 0===e?.x?.max){let e=this.masterChart?this.masterChart.scales:this.chart.scales;return!this.hasLinearScale&&e?.x&&(e={...e,x:{min:Math.ceil(e.x.min)-this.axisOffset,max:Math.floor(e.x.max)+this.axisOffset}}),void this.store.resetAxisLimits(this.chartId,e)}this.updateTrendingLineAxes(),this.chart.update(),this.masterChart&&this.masterChart.update()}updateTrendingLineAxes(){this.store.updateTrendLineConfiguration(this.chartId);const e=this.store.currentAxesLimits[this.chartId];for(const t of[ZS,jS])this.chart?.config.options?.scales?.[t]&&e?.[t]&&(this.chart.config.options.scales[t].min=e[t].min,this.chart.config.options.scales[t].max=e[t].max)}get upperBound(){return this.computePosition(this.store.currentAxesLimits[this.chartId]?.x?.max)}get lowerBound(){return this.computePosition(this.store.currentAxesLimits[this.chartId]?.x?.min)}computePosition(e){if(void 0===e||!this.masterChart?.scales?.x)return;const t=this.masterChart.scales.x;if(this.hasLinearScale)return t.getPixelForValue(e);if(!this.masterChart.chartArea)return;const{left:s,right:o}=this.masterChart.chartArea,{min:i,max:n}=t,r=this.axisOffset;return s+(o-s)*(r+e-i)/(2*r+n-i)}computeCoordinate(e){if(!this.masterChart)return;const t=this.masterChart.scales.x;if(this.hasLinearScale){const s=t.getValueForPixel(e);if(void 0===s)return;return Math.round(100*s)/100}const{left:s,right:o}=this.masterChart.chartArea,i=this.axisOffset;return t.min-i+(t.max+2*i-t.min)*(e-s)/(o-s)}updateAxisLimits(e,t){this.hasLinearScale?(this.chart.config.options.scales.x.min=e,this.chart.config.options.scales.x.max=t):(this.chart.config.options.scales.x.min=Math.ceil(e),this.chart.config.options.scales.x.max=Math.floor(t)),this.store.updateAxisLimits(this.chartId,{min:e,max:t}),this.updateTrendingLineAxes(),this.masterChart?.update(),this.chart?.update()}onPointerDownInMasterChart(e){this.removeEventListeners();const t=e.offsetX;if(!this.masterChart?.chartArea||!this.chart?.scales?.x)return;const{left:s,right:o,top:i,bottom:n}=this.masterChart.chartArea,r=this.upperBound??o,a=this.lowerBound??s;if(t<s-5||t>o+5||e.offsetY<i||e.offsetY>n)return;let l,c,h;e.preventDefault(),e.stopPropagation();const d=e.clientX-(this.masterChartCanvas.el?.getBoundingClientRect().left??0);if((a!==s||r!==o)&&t>a+5&&t<r-5){l=e.offsetX-a,this.mode="moveInMaster";const t=this.store.currentAxesLimits[this.chartId]?.x;c=(t?.max??this.chart.scales.x.max)-(t?.min??this.chart.scales.x.min)}else this.mode="selectInMaster",l=Math.abs(t-a)<5?r:Math.abs(t-r)<5?a:ue(t,s,o),h=this.computeCoordinate(l);const u=this.store.originalAxisLimits[this.chartId].x.min,g=this.store.originalAxisLimits[this.chartId].x.max,p=e=>{let t,s;const{left:o,right:i}=this.masterChart.chartArea;if("moveInMaster"===this.mode)t=this.computeCoordinate(e-l),t<u?t=u:t>g-c&&(t=g-c),s=t+c;else if("selectInMaster"===this.mode){const n=ue(e,o,i);if(Math.abs(l-n)>5){const e=this.computeCoordinate(n);if(void 0===h||void 0===e)return{};t=Math.min(h,e),s=Math.max(h,e)}}return{min:t,max:s}},m=e=>{const t=e.clientX-(this.masterChartCanvas.el?.getBoundingClientRect().left??0);if(Math.abs(t-d)<5)return;const{min:s,max:o}=p(t);void 0!==s&&void 0!==o&&this.updateAxisLimits(s,o)},f=e=>{this.removeEventListeners();const t=e.clientX-(this.masterChartCanvas.el?.getBoundingClientRect().left??0);if(Math.abs(t-d)>5){let{min:e,max:s}=p(t);void 0!==e&&void 0!==s&&(this.hasLinearScale||("moveInMaster"===this.mode&&c&&!this.isBarChart?(e=Math.round(e)-this.axisOffset,s=e+c):(e=Math.ceil(e)-this.axisOffset,s=Math.floor(s)+this.axisOffset)),this.updateAxisLimits(e,s))}this.mode=void 0};this.removeEventListeners=()=>{window.removeEventListener("pointermove",m,!0),window.removeEventListener("pointerup",f,!0)},window.addEventListener("pointermove",m,!0),window.addEventListener("pointerup",f,!0)}onPointerMoveInMasterChart(e){const{offsetX:t,offsetY:s}=e;if(void 0===this.mode){const o=e.target;if(!this.masterChart?.chartArea)return void(o.style.cursor="default");const{left:i,right:n,top:r,bottom:a}=this.masterChart.chartArea,l=this.lowerBound??i,c=this.upperBound??n;s<r||s>a?o.style.cursor="default":Math.abs(l-t)<5||Math.abs(c-t)<5?o.style.cursor="ew-resize":o.style.cursor=l<t&&t<c&&(l!==i||c!==n)?"grab":"crosshair"}}onMouseLeaveMasterChart(e){const t=e.target;t&&(t.style.cursor="default")}onDoubleClickInMasterChart(e){this.mode=void 0;const t=e.offsetX;if(!this.masterChart?.chartArea||!this.chart?.scales.x)return;const{left:s,right:o,top:i,bottom:n}=this.masterChart.chartArea;let r=this.upperBound??o,a=this.lowerBound??s;if(r<a&&([r,a]=[a,r]),t<s-5||t>o+5||e.offsetY<i||e.offsetY>n)return;e.preventDefault(),e.stopPropagation();let{min:l,max:c}=this.store.currentAxesLimits[this.chartId]?.x??this.chart.scales.x;const h=this.store.originalAxisLimits[this.chartId].x;if(!h)return;let d=h.min,u=h.max;if(this.hasLinearScale&&(d=Math.ceil(d)-this.axisOffset,u=Math.floor(u)+this.axisOffset),Math.abs(t-a)<5)l=d;else if(Math.abs(t-r)<5)c=u;else{if(!(a<t&&t<r))return;l=d,c=u}this.updateAxisLimits(l,c)}}const fF=new Og;fF.add("animatedBackgroundColorChange",{id:"animatedBackgroundColorChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>e?.style?.fillColor!==t?.style?.fillColor,updateAnimation:function(e,t,s,o){const i=qv([{value:0,color:s.style.fillColor||"#ffffff"},{value:1,color:o.style.fillColor||"#ffffff"}]);t.style.fillColor=i(vF[this.easingFn](e))}}),fF.add("animatedTextColorChange",{id:"animatedTextColorChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>e?.style?.textColor!==t?.style?.textColor,updateAnimation:function(e,t,s,o){const i=qv([{value:0,color:s.style.textColor||"#000000"},{value:1,color:o.style.textColor||"#000000"}]);t.style.textColor=i(vF[this.easingFn](e))}}),fF.add("animatedDataBar",{id:"animatedDataBar",easingFn:"easeOutCubic",hasAnimation:(e,t)=>e?.dataBarFill?.percentage!==t?.dataBarFill?.percentage,updateAnimation:function(e,t,s,o){const i=s?.dataBarFill?.percentage||0,n=i+((o?.dataBarFill?.percentage||0)-i)*vF[this.easingFn](e);t.dataBarFill={color:o.dataBarFill?.color||s.dataBarFill?.color||"#ffffff",percentage:n}}}),fF.add("textFadeIn",{id:"textFadeIn",easingFn:"easeInCubic",hasAnimation:(e,t)=>{const s=e?.content?.textLines?.join("\n"),o=t?.content?.textLines?.join("\n");return Boolean(!s&&o)},updateAnimation:function(e,t,s,o){t.textOpacity=vF[this.easingFn](e)}}),fF.add("textFadeOut",{id:"textFadeOut",easingFn:"easeOutCubic",hasAnimation:(e,t)=>{const s=e?.content?.textLines?.join("\n"),o=t?.content?.textLines?.join("\n");return Boolean(s&&!o)},updateAnimation:function(e,t,s,o){const i=1-vF[this.easingFn](e),n={...s.style};delete n.fillColor,t.textOpacity=i,t.content=s.content,t.clipRect=s.clipRect,Object.assign(t.style,n)}}),fF.add("iconFadeIn",{id:"iconFadeIn",easingFn:"easeInCubic",hasAnimation:(e,t)=>Boolean(!e?.icons?.left&&t?.icons?.left||!e?.icons?.right&&t?.icons?.right||!e?.icons?.center&&t?.icons?.center),updateAnimation:function(e,t,s,o){const i=vF[this.easingFn](e);t.icons.left&&o.icons.left&&!s.icons.left&&(t.icons.left.opacity=i),t.icons.right&&o.icons.right&&!s.icons.right&&(t.icons.right.opacity=i),t.icons.center&&o.icons.center&&!s.icons.center&&(t.icons.center.opacity=i)}}),fF.add("iconFadeOut",{id:"iconFadeOut",easingFn:"easeOutCubic",hasAnimation:(e,t)=>Boolean(e?.icons?.left&&!t?.icons?.left||e?.icons?.right&&!t?.icons?.right||e?.icons?.center&&!t?.icons?.center),updateAnimation:function(e,t,s,o){const i=1-vF[this.easingFn](e);t.icons||(t.icons={}),s.icons.left&&!o.icons.left&&(t.icons.left={...s.icons.left,opacity:i}),s.icons.right&&!o.icons.right&&(t.icons.right={...s.icons.right,opacity:i}),s.icons.center&&!o.icons.center&&(t.icons.center={...s.icons.center,opacity:i})}}),fF.add("textChange",{id:"textChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>{const s=e?.content?.textLines?.join("\n"),o=t?.content?.textLines?.join("\n");return Boolean(s&&o&&(s!==o||CF(t,e)))},updateAnimation:function(e,t,s,o){const i=vF[this.easingFn](e),n=o.y+(i-1)*o.height,r=o.y+i*o.height,a=CF(o,s),l={id:o.id+"-text-slide-in",x:o.x,y:n,width:o.width,height:o.height,style:{...o.style},skipCellGridLines:!0,content:o.content?{...o.content}:void 0,clipRect:o.clipRect||{...o,x:Math.max(0,o.x-(o.content?.width||0)),width:o.width+2*(o.content?.width||0)},icons:a?SF(o.icons,o):bF(o.icons)},c={id:s.id+"-text-slide-out",x:o.x,y:r,width:o.width,height:o.height,style:{...s.style},skipCellGridLines:!0,content:s.content?{...s.content}:void 0,clipRect:s.clipRect||{...o,x:Math.max(0,o.x-(s.content?.width||0)),width:o.width+2*(s.content?.width||0)},icons:a?SF(s.icons,o):bF(s.icons)};if(o.content&&s.content&&l.content&&c.content){const e=o.content.y+(i-1)*o.height,t=o.content.y+i*o.height;l.content.y=e,c.content.y=t}return c.style.fillColor=l.style.fillColor=void 0,t.content=void 0,t.icons=a?{}:t.icons,{newBoxes:[l,c]}}}),fF.add("borderFadeIn",{id:"borderFadeIn",easingFn:"easeInCubic",hasAnimation:(e,t)=>Boolean(!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,s,o){const i=vF[this.easingFn](e);t.border?.top&&o.border?.top&&!s.border?.top&&(t.border.top.opacity=i),t.border?.bottom&&o.border?.bottom&&!s.border?.bottom&&(t.border.bottom.opacity=i),t.border?.left&&o.border?.left&&!s.border?.left&&(t.border.left.opacity=i),t.border?.right&&o.border?.right&&!s.border?.right&&(t.border.right.opacity=i)}}),fF.add("borderFadeOut",{id:"borderFadeOut",easingFn:"easeOutCubic",hasAnimation:(e,t)=>Boolean(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,s,o){const i=1-vF[this.easingFn](e);t.border||(t.border={}),s.border?.top&&!o.border?.top&&(t.border.top={...s.border.top,opacity:i}),s.border?.bottom&&!o.border?.bottom&&(t.border.bottom={...s.border.bottom,opacity:i}),s.border?.left&&!o.border?.left&&(t.border.left={...s.border.left,opacity:i}),s.border?.right&&!o.border?.right&&(t.border.right={...s.border.right,opacity:i})}}),fF.add("borderColorChange",{id:"borderColorChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>{const s=e?.border,o=t?.border;return!(!s||!o)&&Boolean(s.bottom?.color!==o.bottom?.color||s.top?.color!==o.top?.color||s.left?.color!==o.left?.color||s.right?.color!==o.right?.color)},updateAnimation:function(e,t,s,o){const i=i=>{const n=s?.border?.[i],r=o?.border?.[i],a=t.border?.[i];if(n&&r&&a){const t=qv([{value:0,color:n.color||"#000000"},{value:1,color:r.color||"#000000"}]);a.color=t(vF[this.easingFn](e))}};i("top"),i("bottom"),i("left"),i("right")}}),fF.add("iconChange",{id:"iconChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>!CF(t,e)&&Boolean(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,s,o){const i=vF[this.easingFn](e),n=o.y+(i-1)*o.height,r=o.y+i*o.height,a=[],l=e=>{const i=s.icons?.[e],l=o.icons?.[e],c={id:`${o.id}-icon-${e}-slide-in`,style:{verticalAlign:o.style.verticalAlign},x:o.x,y:n,width:o.width,height:o.height,skipCellGridLines:!0,icons:{[e]:{...l,clipRect:o}}},h={id:`${o.id}-icon-${e}-slide-out`,style:{verticalAlign:s.style.verticalAlign},x:o.x,y:r,width:o.width,height:o.height,skipCellGridLines:!0,icons:{[e]:{...i,clipRect:o}}};t.icons[e]=bF(o.icons)[e],a.push(c,h)};return l("left"),l("right"),l("center"),{newBoxes:a}}});const vF={linear:e=>e,easeInCubic:e=>e*e*e,easeOutCubic:e=>(e-=1)*e*e+1,easeInOutCubic:e=>(e/=.5)<1?.5*e*e*e:.5*((e-=2)*e*e+2),easeOutQuart:e=>-((e-=1)*e*e*e-1)};function bF(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 SF(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 CF(e,t){const s=(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 s(e?.icons.left,t?.icons.left)||s(e?.icons.right,t?.icons.right)||s(e?.icons.center,t?.icons.center)}class yF extends t.Component{static template="o-spreadsheet-GaugeChartComponent";static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=t.useRef("chartContainer");animationStore;get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}setup(){this.env.model.getters.isDashboard()&&(this.animationStore=ev(iS));let e,s=null;t.useEffect(()=>(this.env.isDashboard()&&void 0===e&&"gauge"!==this.animationStore?.animationPlayed[this.animationChartId]||this.env.isDashboard()&&void 0!==e&&!Me(this.runtime,e)?(s=this.drawGaugeWithAnimation(),this.animationStore?.disableAnimationForChart(this.animationChartId,"gauge")):Jy(this.canvasEl,this.runtime),e=this.runtime,()=>s?.stop()),()=>{const e=this.canvasEl.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}drawGaugeWithAnimation(){Jy(this.canvasEl,{...this.runtime,animationValue:0});const e=this.runtime.gaugeValue?.value||0,t=this.runtime.maxValue.value,s=Math.sign(e)*Math.min(Math.abs(e),Math.abs(t));if(0===s)return null;const o=this.runtime.minValue.value,i=new IF(o,s,1e3,e=>Jy(this.canvasEl,{...this.runtime,animationValue:e}));return i.start(),i}get canvasEl(){return this.canvas.el}get animationChartId(){return this.props.isFullScreen?this.props.chartId+"-fullscreen":this.props.chartId}}class IF{startValue;endValue;duration;callback;startTime=void 0;animationFrameId=null;constructor(e,t,s,o){this.startValue=e,this.endValue=t,this.duration=s,this.callback=o}start(){this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}stop(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}animate(e){this.startTime||(this.startTime=e);const t=e-this.startTime,s=Math.min(t/this.duration,1),o=this.startValue+(this.endValue-this.startValue)*vF.easeOutQuart(s);this.callback(o),s<1?this.animationFrameId=requestAnimationFrame(this.animate.bind(this)):this.stop()}}const wF=new Og;wF.add("line",mF),wF.add("bar",mF),wF.add("combo",mF),wF.add("pie",iy),wF.add("gauge",yF),wF.add("scatter",mF),wF.add("scorecard",Cy),wF.add("waterfall",mF),wF.add("pyramid",iy),wF.add("radar",iy),wF.add("geo",iy),wF.add("funnel",iy),wF.add("sunburst",iy),wF.add("treemap",iy);class EF extends hv{mutators=["toggleFullScreenFigure"];fullScreenFigure=void 0;toggleFullScreenFigure(e){this.fullScreenFigure?.id===e?this.fullScreenFigure=void 0:this.makeFullScreen(e)}makeFullScreen(e){const t=this.getters.getActiveSheetId(),s=this.getters.getFigure(t,e);s&&(this.fullScreenFigure={...s,x:0,y:0,width:0,height:0})}}class RF extends t.Component{static template="o-spreadsheet-Menu";static props={menuItems:Array,onClose:Function,onClickMenu:{type:Function,optional:!0},onMouseEnter:{type:Function,optional:!0},onMouseOver:{type:Function,optional:!0},onMouseLeave:{type:Function,optional:!0},width:{type:Number,optional:!0},isActive:{type:Function,optional:!0},onScroll:{type:Function,optional:!0}};static components={};static defaultProps={};hoveredMenu=void 0;setup(){t.onWillUnmount(()=>{this.hoveredMenu?.onStopHover?.(this.env)})}get menuItemsAndSeparators(){const e=[];for(let t=0;t<this.props.menuItems.length;t++){const s=this.props.menuItems[t];!s.isVisible(this.env)||this.isRoot(s)&&!this.hasVisibleChildren(s)||e.push(s),s.separator&&t!==this.props.menuItems.length-1&&"separator"!==e[e.length-1]&&e.push("separator")}return"separator"===e[e.length-1]&&e.pop(),1===e.length&&"separator"===e[0]?[]:e}get childrenHaveIcon(){return this.props.menuItems.some(e=>!!this.getIconName(e))}getIconName(e){return e.icon(this.env)?e.icon(this.env):e.isActive?.(this.env)?"o-spreadsheet-Icon.CHECK":""}getColor(e){return Ey({color:e.textColor})}getIconColor(e){return Ey({color:e.iconColor})}getName(e){return e.name(this.env)}isRoot(e){return!e.execute}hasVisibleChildren(e){return e.children(this.env).some(e=>e.isVisible(this.env))}isEnabled(e){return!!e.isEnabled(this.env)&&(!this.env.model.getters.isReadonly()||e.isReadonlyAllowed)}get menuStyle(){return this.props.width?Ey({width:this.props.width+"px"}):""}onMouseEnter(e,t){this.hoveredMenu=e,e.onStartHover?.(this.env),this.props.onMouseEnter?.(e,t)}onMouseLeave(e,t){this.hoveredMenu=void 0,e.onStopHover?.(this.env),this.props.onMouseLeave?.(e,t)}onClickMenu(e,t){this.isEnabled(e)&&this.props.onClickMenu?.(e,t)}}function xF(e){return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}function TF(e){if(e)return{x:e.left,y:e.top,width:e.right-e.left,height:e.bottom-e.top}}function AF(){const e=t.useState({x:0,y:0,width:0,height:0});let s=null;function o(){if(s||(s=document.querySelector(".o-spreadsheet")),s){const{top:t,left:o,width:i,height:n}=s.getBoundingClientRect();e.x=o,e.y=t,e.width=i,e.height=n}}return t.onMounted(o),t.onPatched(o),e}class DF 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:()=>{}};popoverRef=t.useRef("popover");popoverContentRef=t.useRef("popoverContent");currentPosition=void 0;currentDisplayValue=void 0;spreadsheetRect=AF();containerRect;setup(){this.containerRect=function(){const e=t.useState({x:0,y:0,width:0,height:0}),s=t.useComponent(),o=AF();function i(){const t=s.env,i="getPopoverContainerRect"in t&&t.getPopoverContainerRect?t.getPopoverContainerRect():o;e.x=i.x,e.y=i.y,e.width=i.width,e.height=i.height}return i(),t.onMounted(i),t.onPatched(i),e}();const e=new ResizeObserver(this.computePopoverPosition.bind(this));t.onMounted(()=>{e.observe(this.popoverContentRef.el)}),t.onWillUnmount(()=>{e.disconnect()}),t.useEffect(this.computePopoverPosition.bind(this))}computePopoverPosition(){if(!this.containerRect)throw new Error("Popover container is not defined");const e=this.popoverRef.el,t=this.popoverContentRef.el,s=(o=this.props.anchorRect,i=this.containerRect,TF(Pt(xF(o),xF(i))));var o,i;const n=s?"block":"none";if("none"!==this.currentDisplayValue&&"none"===n&&this.props.onPopoverHidden?.(),e.style.display=n,this.currentDisplayValue=n,!s)return;const r={width:this.props.maxWidth,height:this.props.maxHeight};let a={width:t.getBoundingClientRect().width,height:t.getBoundingClientRect().height};const l=this.spreadsheetRect,c="bottom-left"===this.props.positioning?new OF(s,this.containerRect,r,l,this.currentPosition):new FF(s,this.containerRect,r,l,this.currentPosition);e.style["max-height"]=c.getMaxHeight(a.height)+"px",e.style["max-width"]=c.getMaxWidth(a.width)+"px",a={width:e.getBoundingClientRect().width,height:e.getBoundingClientRect().height};const h=c.getCss(a,this.props.verticalOffset);for(const t of Object.keys(h))e.style[t]=h[t];const d=c.getCurrentPosition(a);this.currentPosition&&d!==this.currentPosition&&this.props.onPopoverMoved?.(),this.currentPosition=d}}class _F{anchorRect;containerRect;propsMaxSize;spreadsheetOffset;lastPosition;constructor(e,t,s,o,i){this.anchorRect=e,this.containerRect=t,this.propsMaxSize=s,this.spreadsheetOffset=o,this.lastPosition=i}shouldRenderAtBottom(e){if("top-left"===this.lastPosition||"top-right"===this.lastPosition){return!(e<=this.availableHeightUp||this.availableHeightUp>=this.availableHeightDown)}return e<=this.availableHeightDown||this.availableHeightDown>=this.availableHeightUp}shouldRenderAtRight(e){if("bottom-left"===this.lastPosition||"top-left"===this.lastPosition){return!(e<=this.availableWidthLeft||this.availableWidthLeft>=this.availableWidthRight)}return e<=this.availableWidthRight||this.availableWidthRight>=this.availableWidthLeft}getMaxHeight(e){const t=this.shouldRenderAtBottom(e)?this.availableHeightDown:this.availableHeightUp;return this.propsMaxSize.height?Math.min(t,this.propsMaxSize.height):t}getMaxWidth(e){const t=this.shouldRenderAtRight(e)?this.availableWidthRight:this.availableWidthLeft;return this.propsMaxSize.width?Math.min(t,this.propsMaxSize.width):t}getCss(e,t){const s=this.getMaxHeight(e.height),o=this.getMaxWidth(e.width),i=Math.min(s,e.height),n=Math.min(o,e.width),r=this.shouldRenderAtBottom(e.height),a=this.shouldRenderAtRight(e.width);return t=r?t:-t,{top:this.getTopCoordinate(i,r)-this.spreadsheetOffset.y-t+"px",left:this.getLeftCoordinate(n,a)-this.spreadsheetOffset.x+"px"}}getCurrentPosition(e){const t=this.shouldRenderAtBottom(e.height),s=this.shouldRenderAtRight(e.width);return t&&s?"bottom-right":t&&!s?"bottom-left":!t&&s?"top-right":"top-left"}}class OF extends _F{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}}class FF extends _F{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}}class PF extends t.Component{static template="o-spreadsheet-Menu-Popover";static props={anchorRect:Object,popoverPositioning:{type:String,optional:!0},menuItems:Array,depth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},onClose:Function,onMenuClicked:{type:Function,optional:!0},menuId:{type:String,optional:!0},onMouseOver:{type:Function,optional:!0},width:{type:Number,optional:!0}};static components={MenuPopover:PF,Menu:RF,Popover:DF};static defaultProps={depth:1,popoverPositioning:"top-right"};subMenu=t.useState({isOpen:!1,anchorRect:null,scrollOffset:0,menuItems:[],isHoveringChild:!1});menuRef=t.useRef("menu");hoveredMenu=void 0;openingTimeOut=function(){let e;function s(){void 0!==e&&(clearTimeout(e),e=void 0)}return t.onWillUnmount(s),{clear:s,schedule:function(t,o){s(),e=setTimeout(t,o)}}}();setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0}),t.useExternalListener(window,"contextmenu",this.onExternalClick,{capture:!0}),t.onWillUpdateProps(e=>{e.menuItems!==this.props.menuItems&&this.closeSubMenu()}),t.onWillUnmount(()=>{this.hoveredMenu?.onStopHover?.(this.env)})}get menuProps(){return{menuItems:this.props.menuItems,onClose:this.close.bind(this),onClickMenu:this.onClickMenu.bind(this),onMouseOver:this.onMouseOver.bind(this),onMouseLeave:this.onMouseLeave.bind(this),width:this.props.width||250,isActive:this.isActive.bind(this),onScroll:this.onScroll.bind(this)}}get subMenuAnchorRect(){const e=Object.assign({},this.subMenu.anchorRect);return e.y-=this.subMenu.scrollOffset||0,e}get popoverProps(){const e=1===this.props.depth;return{anchorRect:{x:this.props.anchorRect.x,y:this.props.anchorRect.y,width:e?this.props.anchorRect.width:this.props.width||250,height:e?this.props.anchorRect.height:26},positioning:this.props.popoverPositioning,verticalOffset:e?0:6,onPopoverHidden:()=>this.closeSubMenu(),onPopoverMoved:()=>this.closeSubMenu(),maxHeight:this.props.maxHeight}}get childrenHaveIcon(){return this.props.menuItems.some(e=>!!this.getIconName(e))}getIconName(e){return e.icon(this.env)?e.icon(this.env):e.isActive?.(this.env)?"o-spreadsheet-Icon.CHECK":""}getColor(e){return Ey({color:e.textColor})}getIconColor(e){return Ey({color:e.iconColor})}async activateMenu(e,t){const s=await(e.execute?.(this.env,t));this.close(),this.props.onMenuClicked?.({detail:s})}close(){this.closeSubMenu(),this.props.onClose()}onExternalClick(e){this.menuRef.el&&Array.from(document.querySelectorAll(".o-spreadsheet .o-menu")).some(t=>Dy(t,e))||(e.closedMenuId=this.props.menuId,this.close())}getName(e){return e.name(this.env)}isRoot(e){return!e.execute}isEnabled(e){return!!e.isEnabled(this.env)&&(!this.env.model.getters.isReadonly()||e.isReadonlyAllowed)}isActive(e){return!!this.subMenu?.isHoveringChild&&this.isParentMenu(this.subMenu,e)}onScroll(e){this.subMenu.scrollOffset=e.target.scrollTop}openSubMenu(e,t){if(!t)return;const s=t.getBoundingClientRect().top;this.subMenu.anchorRect={x:Oy(this.menuRef).x,y:s-(this.subMenu.scrollOffset||0),width:this.props.width||250,height:26},this.subMenu.menuItems=e.children(this.env),this.subMenu.isOpen=!0,this.subMenu.parentMenu=e}isParentMenu(e,t){return e.parentMenu?.id===t.id}closeSubMenu(){this.subMenu.isHoveringChild||(this.subMenu.isOpen=!1,this.subMenu.parentMenu=void 0)}onClickMenu(e,t){this.isRoot(e)?this.openSubMenu(e,t.currentTarget):this.activateMenu(e,Hy(t))}onMouseOver(e,t){if(this.isEnabled(e)){if(this.isParentMenu(this.subMenu,e))return void this.openingTimeOut.clear();const s=t.currentTarget;this.isRoot(e)&&this.openingTimeOut.schedule(()=>{this.openSubMenu(e,s)},250)}}onMouseOverMainMenu(){this.props.onMouseOver?.(),this.subMenu.isHoveringChild=!1}onMouseOverChildMenu(){this.subMenu.isHoveringChild=!0,this.openingTimeOut.clear()}onMouseLeave(e){this.openingTimeOut.schedule(this.closeSubMenu.bind(this),250)}get menuStyle(){return this.props.width?Ey({width:this.props.width+"px"}):""}}class MF extends t.Component{static template="o-spreadsheet-ChartDashboardMenu";static components={MenuPopover:PF};static props={chartId:String,hasFullScreenButton:{type:Boolean,optional:!0}};static defaultProps={hasFullScreenButton:!0};fullScreenFigureStore;menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});setup(){super.setup(),this.fullScreenFigureStore=ev(EF)}getMenuItems(){return[this.fullScreenMenuItem].filter(Te)}get backgroundColor(){return"background-color: "+(this.env.model.getters.getChartDefinition(this.props.chartId).background||c)}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.anchorRect=Fy(e.currentTarget);const t=this.env.model.getters.getFigureIdFromChartId(this.props.chartId);this.menuState.menuItems=nF(t,()=>{},this.env)}get fullScreenMenuItem(){if(!this.props.hasFullScreenButton)return;const e=this.env.model.getters.getChartDefinition(this.props.chartId),t=this.env.model.getters.getFigureIdFromChartId(this.props.chartId);if("scorecard"===e.type)return;const s=t===this.fullScreenFigureStore.fullScreenFigure?.id;return{id:"fullScreenChart",label:fs(s?"Exit Full Screen":"Full Screen"),class:"text-muted fa "+(s?"fa-compress":"fa-expand"),onClick:()=>{this.fullScreenFigureStore.toggleFullScreenFigure(t)}}}}class NF extends t.Component{static template="o-spreadsheet-CarouselFigure";static props={figureUI:Object,onFigureDeleted:Function,editFigureStyle:{type:Function,optional:!0},isFullScreen:{type:Boolean,optional:!0},openContextMenu:{type:Function,optional:!0}};static components={ChartDashboardMenu:MF,MenuPopover:PF};carouselTabsRef=t.useRef("carouselTabs");carouselTabsDropdownRef=t.useRef("carouselTabsDropdown");menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});hiddenItems=[];animationStore;fullScreenFigureStore;setup(){this.animationStore=ev(iS),this.fullScreenFigureStore=ev(EF),t.useEffect(()=>{"carouselDataView"===this.selectedCarouselItem?.type?this.props.editFigureStyle?.({"pointer-events":"none"}):this.props.editFigureStyle?.({"pointer-events":"auto"}),this.updateTabsVisibility()})}get carousel(){return this.env.model.getters.getCarousel(this.props.figureUI.id)}get selectedCarouselItem(){return this.env.model.getters.getSelectedCarouselItem(this.props.figureUI.id)}get chartComponent(){const e=this.selectedCarouselItem;if("chart"!==e?.type)throw new Error("Selected item is not a chart");const t=this.env.model.getters.getChartType(e.chartId),s=wF.get(t);if(!s)throw new Error(`Component is not defined for type ${t}`);return s}onCarouselDoubleClick(){this.env.model.dispatch("SELECT_FIGURE",{figureId:this.props.figureUI.id}),this.env.openSidePanel("CarouselPanel",{figureId:this.props.figureUI.id})}isItemSelected(e){return Me(this.selectedCarouselItem,e)}getItemTitle(e){return b_(this.env.model.getters,e)}onCarouselTabClick(e){if(this.env.model.dispatch("UPDATE_CAROUSEL_ACTIVE_ITEM",{figureId:this.props.figureUI.id,sheetId:this.env.model.getters.getActiveSheetId(),item:e}),"chart"===e.type){const t=e.chartId+(this.props.isFullScreen?"-fullscreen":"");this.animationStore?.enableAnimationForChart(t)}}get headerStyle(){const e={};if("chart"===this.selectedCarouselItem?.type){const t=this.env.model.getters.getChartRuntime(this.selectedCarouselItem.chartId);e["background-color"]=t.background}else e["background-color"]="#ffffff";return Ey(e)}get title(){return this.carousel.title?.text??""}get titleStyle(){return Ey(wy(function(e){return{bold:e.bold,italic:e.italic,fontSize:e.fontSize,textColor:e.color,align:e.align}}({...te,...this.carousel.title})))}updateTabsVisibility(){const e=this.carouselTabsRef.el,t=this.carouselTabsDropdownRef.el;if(!e||!t)return;this.hiddenItems=[];const s=Fy(e),o=Array.from(e.children);for(const e of o)e.style.display="block";const i=o.map(e=>Fy(e).width);let n=0;for(let e=0;e<o.length;e++){const t=n+i[e]>s.width;n+=i[e],t&&(o[e].style.display="none",this.hiddenItems.push(this.carousel.items[e]))}t.style.display=this.hiddenItems.length?"block":"none"}get menuId(){return"carousel-tabs-menu-"}toggleMenu(e){if(e.closedMenuId===this.menuId)return void(this.menuState.isOpen=!1);const t=Oy(this.carouselTabsDropdownRef),s=this.hiddenItems.map(e=>({name:this.getItemTitle(e),execute:()=>this.onCarouselTabClick(e),isActive:()=>this.isItemSelected(e),isReadonlyAllowed:!0}));this.menuState.isOpen=!0,this.menuState.anchorRect=t,this.menuState.menuItems=qf(s)}toggleFullScreen(){"chart"===this.selectedCarouselItem?.type&&this.fullScreenFigureStore.toggleFullScreenFigure(this.props.figureUI.id)}get fullScreenButtonTitle(){return this.props.isFullScreen?fs("Exit Full Screen"):fs("Full Screen")}get visibleCarouselItems(){return this.carousel.items.filter(e=>"carouselDataView"!==e.type||!this.props.isFullScreen)}openContextMenu(e){const t=e.currentTarget;t&&this.props.openContextMenu?.(Fy(t))}}class LF extends t.Component{static template="o-spreadsheet-ChartFigure";static props={figureUI:Object,onFigureDeleted:Function,editFigureStyle:{type:Function,optional:!0},isFullScreen:{type:Boolean,optional:!0},openContextMenu:{type:Function,optional:!0}};static components={ChartDashboardMenu:MF};onDoubleClick(){this.env.model.dispatch("SELECT_FIGURE",{figureId:this.props.figureUI.id}),this.env.openSidePanel("ChartPanel")}get chartType(){return this.env.model.getters.getChartType(this.chartId)}get chartId(){const e=this.env.model.getters.getChartIdFromFigureId(this.props.figureUI.id);if(!e)throw new Error(`No chart found for figure ID: ${this.props.figureUI.id}`);return e}get chartComponent(){const e=this.chartType,t=wF.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}class kF extends t.Component{static template="o-spreadsheet-ImageFigure";static props={figureUI:Object,onFigureDeleted:Function,editFigureStyle:{type:Function,optional:!0},openContextMenu:{type:Function,optional:!0}};static components={};get figureId(){return this.props.figureUI.id}get getImagePath(){return this.env.model.getters.getImagePath(this.figureId)}}const VF=new Og;VF.add("chart",{Component:LF,SidePanelComponent:"ChartPanel",menuBuilder:nF}),VF.add("image",{Component:kF,keepRatio:!0,minFigSize:20,borderWidth:0,menuBuilder:function(e,t,s){return qf([rF(e,s,fs("Image copied to clipboard")),aF(e,s),{id:"reset_size",name:fs("Reset size"),execute:async()=>{const t=s.model.getters.getActiveSheetId(),o=s.model.getters.getFigure(t,e);if(!o)return;const i=s.model.getters.getImagePath(e),n=s.model.getters.getImageSize(e)??await(s.imageProvider?.getImageOriginalSize(i));if(!s.model.getters.getImageSize(e)){s.model.getters.getImage(e).size=n}const{col:r,row:a}=o,{height:l,width:c}=xy(s.model.getters,n);s.model.dispatch("UPDATE_FIGURE",{sheetId:t,figureId:e,height:l,width:c,col:r,row:a})},icon:"o-spreadsheet-Icon.REFRESH"},{id:"download",name:fs("Download"),execute:async()=>{s.model.dispatch("SELECT_FIGURE",{figureId:e});zy(s.model.getters.getImagePath(e),"image")},icon:"o-spreadsheet-Icon.DOWNLOAD"},hF(e,t,s)])}}),VF.add("carousel",{Component:NF,menuBuilder:function(e,t,s){const o=t=>"chart"===t.model.getters.getSelectedCarouselItem(e)?.type;return qf([{id:"edit_carousel",name:fs("Edit carousel"),execute:()=>{s.model.dispatch("SELECT_FIGURE",{figureId:e}),s.openSidePanel("CarouselPanel",{figureId:e})},icon:"o-spreadsheet-Icon.EDIT",isEnabled:e=>!e.isSmall},{...rF(e,s,fs("Carousel copied to clipboard")),name:fs("Copy carousel")},{...aF(e,s),name:fs("Cut carousel")},{...hF(e,t,s),name:fs("Delete carousel"),separator:!0},{id:"edit_chart",name:fs("Edit chart"),execute:()=>{s.model.dispatch("SELECT_FIGURE",{figureId:e}),s.openSidePanel("ChartPanel",{})},icon:"o-spreadsheet-Icon.EDIT",isEnabled:e=>!e.isSmall,isVisible:o},{...lF(e,s),isVisible:o,name:fs("Copy chart as image")},{...cF(e,s),isVisible:o,name:fs("Download chart")},{id:"popout_chart",name:fs("Pop out chart"),icon:"o-spreadsheet-Icon.EXTERNAL",execute:()=>{const t=s.model.getters.getSelectedCarouselItem(e);t&&"chart"===t.type&&s.model.dispatch("POPOUT_CHART_FROM_CAROUSEL",{carouselId:e,chartId:t.chartId,sheetId:s.model.getters.getActiveSheetId()})},isVisible:o},{id:"delete_carousel_item",name:t=>{const s=t.model.getters.getSelectedCarouselItem(e);return fs("chart"===s?.type?"Delete chart":"Delete data view")},execute:()=>{const t=s.model.getters.getSelectedCarouselItem(e);if(!t)return;const o=s.model.getters.getCarousel(e),i=o.items.filter(e=>!xC(e,t));s.model.dispatch("UPDATE_CAROUSEL",{figureId:e,sheetId:s.model.getters.getActiveSheetId(),definition:{...o,items:i}})},icon:"o-spreadsheet-Icon.TRASH",isVisible:t=>t.model.getters.getCarousel(e).items.length>=1}]).filter(e=>!s.model.getters.isReadonly()||e.isReadonlyAllowed)}});class UF extends t.Component{static template="o-spreadsheet-FigureComponent";static props={figureUI:Object,style:{type:String,optional:!0},class:{type:String,optional:!0},onFigureDeleted:{type:Function,optional:!0},onMouseDown:{type:Function,optional:!0},onClickAnchor:{type:Function,optional:!0}};static components={MenuPopover:PF};static defaultProps={onFigureDeleted:()=>{},onMouseDown:()=>{},onClickAnchor:()=>{}};menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});figureRef=t.useRef("figure");figureWrapperRef=t.useRef("figureWrapper");menuButtonRef=t.useRef("menuButton");borderWidth;get isSelected(){return this.env.model.getters.getSelectedFigureId()===this.props.figureUI.id}get figureRegistry(){return VF}getBorderWidth(){return this.env.isDashboard()?0:this.isSelected?2:this.borderWidth}getBorderStyle(e){return`border-${e}-width: ${this.getBorderWidth()}px;`}get wrapperStyle(){const{x:e,y:t,width:s,height:o}=this.props.figureUI;return Ey({left:`${e}px`,top:`${t}px`,width:`${s}px`,height:`${o}px`})}getResizerPosition(e){const t={};return e.includes("top")?t.top="-3px":e.includes("bottom")?t.bottom="-3px":t.bottom="calc(50% - 3px)",e.includes("left")?t.left="-3px":e.includes("right")?t.right="-3px":t.right="calc(50% - 3px)",Ey(t)}setup(){const e=VF.get(this.props.figureUI.tag).borderWidth;this.borderWidth=void 0!==e?e:1,t.useEffect((e,t,s)=>{e===t&&s?.focus({preventScroll:!0})},()=>[this.env.model.getters.getSelectedFigureId(),this.props.figureUI.id,this.figureRef.el]),t.onWillUnmount(()=>{this.props.onFigureDeleted()})}clickAnchor(e,t,s){this.props.onClickAnchor(e,t,s)}onMouseDown(e){this.env.isMobile()||this.props.onMouseDown(e)}onClick(e){this.env.isMobile()&&this.props.onMouseDown(e)}onKeyDown(e){const t=ky(e);switch(t){case"Delete":case"Backspace":this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),figureId:this.props.figureUI.id}),this.props.onFigureDeleted(),e.preventDefault(),e.stopPropagation();break;case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":const{col:s,row:o,offset:i}=this.postionInBoundary(this.props.figureUI,e.key);this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),figureId:this.props.figureUI.id,offset:i,col:s,row:o}),e.preventDefault(),e.stopPropagation();break;case"Ctrl+A":e.preventDefault(),e.stopPropagation();break;case"Ctrl+Y":case"Ctrl+Z":"Ctrl+Y"===t?this.env.model.dispatch("REQUEST_REDO"):"Ctrl+Z"===t&&this.env.model.dispatch("REQUEST_UNDO"),e.preventDefault(),e.stopPropagation()}}postionInBoundary(e,t){const s=this.env.model.getters.getActiveSheetId();let{col:o,row:i,offset:n}=e;switch(n={...n},t){case"ArrowUp":0===n.y?(i--,n.y=this.env.model.getters.getRowSize(s,i)-1):n.y--;break;case"ArrowLeft":0===n.x?(o--,n.x=this.env.model.getters.getColSize(s,o)-1):n.x--;break;case"ArrowDown":n.y===this.env.model.getters.getRowSize(s,i)?(i++,n.y=0):n.y++;break;case"ArrowRight":n.x===this.env.model.getters.getColSize(s,i)?(o++,n.x=0):n.x++}return{col:o,row:i,offset:n}}onContextMenu(e){this.env.isDashboard()||this.openContextMenu({x:e.clientX,y:e.clientY,width:0,height:0})}showMenu(){this.openContextMenu(Oy(this.menuButtonRef))}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.anchorRect=e,this.menuState.menuItems=VF.get(this.props.figureUI.tag).menuBuilder(this.props.figureUI.id,this.props.onFigureDeleted,this.env)}editWrapperStyle(e){if(this.figureWrapperRef.el)for(const t in e)this.figureWrapperRef.el.style.setProperty(t,e[t]||null)}}class HF extends hv{mutators=["clear","hover"];col;row;handle(e){if("ACTIVATE_SHEET"===e.type)this.clear()}hover(e){if(e.col===this.col&&e.row===this.row)return"noStateChange";this.col=e.col,this.row=e.row}clear(){if(void 0===this.col&&void 0===this.row)return"noStateChange";this.col=void 0,this.row=void 0}}class zF{jsDate;constructor(e,t,s,o=0,i=0,n=0){this.jsDate=new Date(Date.UTC(e,t,s,o,i,n,0))}static fromTimestamp(e){const t=new Date(e);return new zF(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds())}static now(){const e=new Date;return new zF(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.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(){const e=new Date(this.jsDate.getTime()),t=e.getUTCDay()||7;e.setUTCDate(e.getUTCDate()+4-t);const s=new Date(Date.UTC(e.getUTCFullYear(),0,1));return Math.ceil(((e.getTime()-s.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)}}const BF=new zF(1899,11,30);zF.now().getFullYear(),zF.now().getMonth();const GF=zF.fromTimestamp(0).getTime()-BF.getTime();DC(function(e){return e=yC(e),new RegExp(`(?:^-?\\d+(?:${e}?\\d*(?:e(\\+|-)?\\d+)?)?|^-?${e}\\d+)(?!\\w|!)`)}),DC(function(e){const t=yC(e.decimalSeparator),s="(?:\\s*"+`(?:\\d+(?:${yC(e.thousandsSeparator||"")}\\d{3,})*(?:${t}\\d*)?)`+"|"+`(?:${t}\\d+)`+")(?:e(?:\\+|-)?\\d+)?(?:\\s*%)?",o="(?:\\s*-)?",i="(?:\\s*[\\$€])?",n="^(?:(?:"+[o+i+s,o+s+i,i+o+s].join(")|(?:")+"))$";return new RegExp(n,"i")}),DC(function(e){return new RegExp(`[$€${yC(e.thousandsSeparator||"")}]`,"g")});const WF=function(e,...t){return new $F(e,t)};class $F extends String{values;constructor(e,t){super(e),this.values=t}valueOf(){return function(e,...t){if(1!==t.length||"object"!=typeof t[0]||t[0]instanceof String)t.length>0&&(e=e.replace(/\%s/g,()=>t.shift()));else{const s=t[0];e=e.replace(/\%\(([^\)]+)\)s/g,(e,t)=>s[t])}return e}(super.valueOf(),...this.values)}toString(){return this.valueOf()}}var qF;function ZF(e){let t;if('"'===e.current?(e.shift(),t='"'):e.currentStartsWith("[$")&&(e.advanceBy(2),t="]"),!t)return null;let s="";for(;e.current&&e.current!==t;)s+=e.shift();if(e.current!==t)throw new Error("Unterminated string in format");return e.shift(),{type:"STRING",value:s}}new Set(Object.values({NotAvailable:"#N/A",InvalidReference:"#REF",BadExpression:"#BAD_EXPR",CircularDependency:"#CYCLE",UnknownFunction:"#NAME?",DivisionByZero:"#DIV/0!",SpilledBlocked:"#SPILL!",GenericError:"#ERROR",NullError:"#NULL!"})),function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(qF||(qF={})),DC(function(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"")}),DC(function(e){if("*"===e)return/.+/;let t="",s="";for(const o of e)"?"===o&&"~"!==s?t+=".":"*"===o&&"~"!==s?t+=".*":("*"!==o&&"?"!==o||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(o)&&(t+="\\"),t+=o),s=o;return new RegExp("^"+t+"$","i")}),WF("[[FUNCTION_NAME]] has no valid input data.");const jF=new Set("$+-/():!^&~{}<>= ");function YF(e){if("\\"===e.current){e.shift();const t=e.shift();if(!t)throw new Error("Unexpected end of format string");return{type:"CHAR",value:t}}return jF.has(e.current)?{type:"CHAR",value:e.shift()}:null}function XF(e){return","===e.current?(e.shift(),{type:"THOUSANDS_SEPARATOR",value:","}):null}function KF(e){return"@"===e.current?(e.shift(),{type:"TEXT_PLACEHOLDER",value:"@"}):null}function JF(e){return"."===e.current?(e.shift(),{type:"DECIMAL_POINT",value:"."}):null}function QF(e){return"%"===e.current?(e.shift(),{type:"PERCENT",value:"%"}):null}function eP(e){if("0"===e.current||"#"===e.current){const t=e.current;return e.shift(),{type:"DIGIT",value:t}}return null}const tP=new Set("dmqyhsa");function sP(e){if(!tP.has(e.current))return null;const t=e.current;let s="";for(;e.current===t;)s+=e.shift();return{type:"DATE_PART",value:s}}function oP(e){if("*"!==e.current)return null;e.shift();const t=e.shift();if(!t)throw new Error("Unexpected end of format string");return{type:"REPEATED_CHAR",value:t}}const iP={};function nP(e){let t=iP[e];return void 0===t&&(t=function(e){const t=function(e){const t=new OC(e),s=[];let o=[];for(s.push(o);!t.isOver();){if(";"===t.current){o=[],s.push(o),t.shift();continue}const e=eP(t)||ZF(t)||YF(t)||XF(t)||JF(t)||QF(t)||sP(t)||KF(t)||oP(t);if(!e)throw new Error("Unknown token at "+t.remaining());o.push(e)}return s}(e);for(const e of t){const t=e.filter(e=>"REPEATED_CHAR"===e.type);for(const e of t.slice(1))e.type="CHAR"}const s=aP(t[0])||rP(t[0])||lP(t[0]);if(!s)throw new Error("Invalid first format part of: "+e);if(t.length>1&&"text"===s.type)throw new Error("The first format in a multi-part format must be a number format: "+e);const o=aP(t[1])||rP(t[1]);if(t[1]?.length&&!o)throw new Error("Invalid second format part of: "+e);const i=aP(t[2])||rP(t[2]);if(t[2]?.length&&!i)throw new Error("Invalid third format part of: "+e);const n=lP(t[3]);if(t[3]?.length&&!n)throw new Error("Invalid fourth format part of: "+e);return{positive:s,negative:o,zero:i,text:n}}(e),iP[e]=t),t}function rP(e){if(!e||!function(e){return e.every(e=>"DIGIT"===e.type||"DECIMAL_POINT"===e.type||"THOUSANDS_SEPARATOR"===e.type||"PERCENT"===e.type||"STRING"===e.type||"CHAR"===e.type||"REPEATED_CHAR"===e.type)}(e))return;const t=[];let s,o=t,i=0,n=0,r=e.findLastIndex(e=>"DIGIT"===e.type),a=!1,l=0;for(let c=0;c<e.length;c++){const h=e[c];switch(h.type){case"DIGIT":o===t?o.push(h):l<20&&(o.push(h),l++);break;case"DECIMAL_POINT":if(o!==t)throw new Error("Multiple decimal points in a number format");s=[],o=s;break;case"REPEATED_CHAR":case"CHAR":case"STRING":o.push(h);break;case"PERCENT":i++,o.push(h);break;case"THOUSANDS_SEPARATOR":c-1===r?(n+=1,r++,o.push(h)):"DIGIT"===e[c+1]?.type&&"DIGIT"===e[c-1]?.type?(o===t&&(a=!0),o.push(h)):o.push({type:"CHAR",value:","})}}return{type:"number",integerPart:t,decimalPart:s,percentSymbols:i,thousandsSeparator:a,magnitude:n}}function aP(e){const t=e&&function(e){return e.every(e=>"DATE_PART"===e.type||"DECIMAL_POINT"===e.type||"THOUSANDS_SEPARATOR"===e.type||"STRING"===e.type||"CHAR"===e.type||"REPEATED_CHAR"===e.type)}(e)?{type:"date",tokens:e}:void 0;if(!t)return;if(t.tokens.length&&t.tokens.every(e=>"DATE_PART"===e.type&&"a"===e.value))throw new Error("Invalid date format");const s=function(e){const t=e.filter(e=>"DATE_PART"===e.type);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}(t.tokens.map(e=>"THOUSANDS_SEPARATOR"===e.type||"DECIMAL_POINT"===e.type?{type:"CHAR",value:e.value}:e));return{type:"date",tokens:s}}function lP(e){return e&&function(e){return e.every(e=>"STRING"===e.type||"TEXT_PLACEHOLDER"===e.type||"CHAR"===e.type||"REPEATED_CHAR"===e.type)}(e)?{type:"text",tokens:e}:void 0}const cP="REPEATED_CHAR_PLACEHOLDER_",hP={0:WF("January"),1:WF("February"),2:WF("March"),3:WF("April"),4:WF("May"),5:WF("June"),6:WF("July"),7:WF("August"),8:WF("September"),9:WF("October"),10:WF("November"),11:WF("December")},dP={0:WF("Sunday"),1:WF("Monday"),2:WF("Tuesday"),3:WF("Wednesday"),4:WF("Thursday"),5:WF("Friday"),6:WF("Saturday")};function uP(e,{format:t,locale:s,formatWidth:o}){switch("boolean"==typeof e&&(e=e?"TRUE":"FALSE"),typeof e){case"string":{if(e.includes('\\"')&&(e=e.replaceAll(/\\"/g,'"')),!t)return e;const s=gP(e,nP(t)).format;return s&&"text"===s.type?pP(e,s,o):e}case"number":t||(t=function(e){let{integerDigits:t,decimalDigits:s}=vP(e);if(!s)return"0";const o=t.replace("-","").length;if(o+2>11)return"0";const i=11-o-1;return({decimalDigits:s}=vP(e,Math.min(i,s.length))),s?"0."+"0".repeat(s.length):"0"}(e));const i=nP(t),{format:n,isNegativeFormat:r}=gP(e,i);if(!n)return e.toString();if("text"===n.type)return pP(e.toString(),n,o);if(r&&(e=Math.abs(e)),"date"===n.type)return mP(function(e,t){const s=function(e){const t=Math.trunc(e),s=zF.fromTimestamp(864e5*t-GF);let o=e-t;o=o<0?1+o:o;const i=Math.round(24*o),n=Math.round(24*(o-i/24)*60),r=Math.round(24*(o-i/24-n/24/60)*60*60);return s.setHours(i),s.setMinutes(n),s.setSeconds(r),s}(e),o=t.tokens.some(e=>"DATE_PART"===e.type&&"a"===e.value);let i="";for(const e of t.tokens)switch(e.type){case"DATE_PART":i+=CP(s,e.value,o);break;case"REPEATED_CHAR":i+=cP+e.value;break;default:i+=e.value}return i}(e,n),o);const a=e<0,l=mP(function(e,t,s){if(e===1/0)return"∞"+(t.percentSymbols?"%":"");const o=2*t.percentSymbols-3*t.magnitude;e*=10**o;let i=0;void 0!==t.decimalPart&&(i=t.decimalPart.filter(e=>"DIGIT"===e.type).length);const{integerDigits:n,decimalDigits:r}=vP(Math.abs(e),i);let a=function(e,t,s){let o=t.integerPart;o.some(e=>"DIGIT"===e.type)||(o=[...o,{type:"DIGIT",value:"#"}]);"0"===e&&(e="");let i="";const n=o.findIndex(e=>"DIGIT"===e.type);let r=e.length-1;function a(t,o){if("0"===o&&(t=t||"0"),!t)return;const n=e.length-1-r;i=s&&n>0&&n%3==0?t+s+i:t+i}for(let t=o.length-1;t>=0;t--){const s=o[t];switch(s.type){case"DIGIT":if(a(e[r],s.value),r--,n===t)for(;r>=0;)a(e[r],"0"),r--;break;case"THOUSANDS_SEPARATOR":break;case"REPEATED_CHAR":i=cP+s.value+i;break;default:i=s.value+i}}return i}(n,t,t.thousandsSeparator?s.thousandsSeparator:void 0);void 0!==t.decimalPart&&(a+=s.decimalSeparator+function(e,t){if(!t.decimalPart)return"";let s="",o=0;for(const i of t.decimalPart)switch(i.type){case"DIGIT":s+="#"===i.value?e[o]||"":e[o]||"0",o++;break;case"THOUSANDS_SEPARATOR":break;case"REPEATED_CHAR":s+=cP+i.value;break;default:s+=i.value}return s}(r||"",t));return a}(Math.abs(e),n,s),o);return a?"-"+l:l;case"object":return""}}function gP(e,t){let s,o=!1;switch(typeof e){case"number":e<0&&t.negative?(s=t.negative,o=!0):s=0===e&&t.zero?t.zero:t.positive;break;case"string":const i=t.text||t.positive;"text"===i.type&&(s=i)}return{format:s,isNegativeFormat:o}}function pP(e,t,s){let o="";for(const s of t.tokens)switch(s.type){case"TEXT_PLACEHOLDER":o+=e;break;case"CHAR":case"STRING":o+=s.value;break;case"REPEATED_CHAR":o+=cP+s.value}return mP(o,s)}function mP(e,t){const s=e.indexOf(cP);if(-1===s)return e;const o=e.slice(0,s),i=e.slice(s+26+1),n=e[s+26];const{timesToRepeat:r,padding:a}=function(){if(!t)return{timesToRepeat:0,padding:""};const e=t.measureText(o+i),s=t.measureText(n),r=t.availableWidth-e;if(r<=0)return{timesToRepeat:0,padding:""};const a=Math.floor(r/s),l=r-a*s,c=t.measureText(" ");return{timesToRepeat:a,padding:" ".repeat(Math.floor(l/c))}}();return o+n.repeat(r)+a+i}const fP=[];function vP(e,t=20){const s=e.toString();if(s.includes("e"))return function(e,t=20){let s=fP[t];s||(s=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),fP[t]=s);const[o,i]=s.format(e).split(".");return{integerDigits:o,decimalDigits:i}}(e,t);if(Number.isInteger(e))return{integerDigits:s,decimalDigits:void 0};const o=s.indexOf(".");let i=s.substring(0,o),n=s.substring(o+1);if(0===t)return Number(n[0])>=5&&(i=(Number(i)+1).toString()),{integerDigits:i,decimalDigits:void 0};if(n.length>t){const{integerDigits:e,decimalDigits:s}=function(e,t){let s="0",o=e;const i=e.slice(0,t),n=t;if(Number(e[n])<5)return{integerDigits:s,decimalDigits:i};const r=i.match(SP)?.[0]||"",a=(Number(i)+1).toString(),l=i.slice(r.length),c=a.length>l.length;c&&!r?(s="1",o=void 0):o=c?r.slice(0,-1)+a:r+a;return{integerDigits:s,decimalDigits:o}}(n,t);n=s,"0"!==e&&(i=(Number(i)+Number(e)).toString())}return{integerDigits:i,decimalDigits:bP(n||"")}}function bP(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const SP=/^0+/;function CP(e,t,s){switch(t){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return dP[e.getDay()].slice(0,3);case"dddd":return dP[e.getDay()].toString();case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return hP[e.getMonth()].slice(0,3);case"mmmm":return hP[e.getMonth()].toString();case"mmmmm":return hP[e.getMonth()].slice(0,1);case"qq":return WF("Q%(quarter)s",{quarter:e.getQuarter()}).toString();case"qqqq":return WF("Quarter %(quarter)s",{quarter:e.getQuarter()}).toString();case"yy":const o=String(e.getFullYear()).replace("-","").padStart(2,"0");return o.slice(o.length-2);case"yyyy":return e.getFullYear();case"hhhh":return Math.floor((e.getTime()-BF.getTime())/36e5).toString();case"hh":let i=e.getHours();return s&&(i=0===i?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 new Error(`invalid date format token: ${t}`)}}function yP(e,t){const s=uP(e,{format:"0,00",locale:t});return WF("Oops—this pivot table is quite large (%s cells). Try simplifying it using the side panel.",s)}DC(function(e){if(!e)return!1;try{return"date"===nP(e).positive.type}catch(e){return!1}}),DC(function(e){return new RegExp(`[0-9]+${yC(e.decimalSeparator)}[0-9]`)}),WF("The range is invalid"),WF("The argument is missing. Please provide a value"),WF("The second argument is missing. Please provide a value"),WF("The minpoint must be a number"),WF("The midpoint must be a number"),WF("The maxpoint must be a number"),WF("The first value must be a number"),WF("The second value must be a number"),WF("Minimum must be smaller then Maximum"),WF("Minimum must be smaller then Midpoint"),WF("Midpoint must be smaller then Maximum"),WF("Lower inflection point must be smaller than upper inflection point"),WF("Invalid Minpoint formula"),WF("Invalid Maxpoint formula"),WF("Invalid Midpoint formula"),WF("Invalid upper inflection point formula"),WF("Invalid lower inflection point formula"),WF("A range needs to be defined"),WF("At least one of the provided values is an invalid formula"),WF("The rule is invalid for an unknown reason"),WF("Color scale"),WF("Icon set"),WF("Data bar"),WF("Series"),WF("Background color"),WF("Stacked bar chart"),WF("Stacked line chart"),WF("Stacked area chart"),WF("Stacked column chart"),WF("Cumulative data"),WF("Treat labels as text"),WF("Aggregate"),WF("The chart definition is invalid for an unknown reason"),WF("The dataset is invalid"),WF("Labels are invalid"),WF("The key value is invalid"),WF("The baseline value is invalid"),WF("The data range is invalid"),WF("A minimum range limit value is needed"),WF("The minimum range limit value must be a number"),WF("A maximum range limit value is needed"),WF("The maximum range limit value must be a number"),WF("The lower inflection point value must be a number"),WF("The upper inflection point value must be a number"),WF("Blues"),WF("Cividis"),WF("Greens"),WF("Greys"),WF("Oranges"),WF("Purples"),WF("Rainbow"),WF("Reds"),WF("Viridis"),WF("Custom"),WF("Merged cells are preventing this operation. Unmerge those cells and try again."),WF("The header row of a table can't be moved."),WF("Cannot split the selection for an unknown reason"),WF("There is no match for the selected separator in the selection"),WF("Only a selection from a single column can be split"),WF("Splitting will overwrite existing content"),WF("Cannot remove duplicates for an unknown reason"),WF("Please select only one range of cells"),WF("Please select a range of cells containing values."),WF("Please select at latest one column to analyze."),WF("This operation is not possible due to a merge. Please remove the merges first than try again."),WF("today"),WF("yesterday"),WF("tomorrow"),WF("in the past week"),WF("in the past month"),WF("in the past year"),WF("today"),WF("yesterday"),WF("tomorrow"),WF("one week ago"),WF("one month ago"),WF("one year ago"),WF("The value must not be empty"),WF("The value must be a number"),WF("The value must be a date"),WF("The value must be a valid range"),WF("The formula must be valid"),WF("The range is invalid."),WF("One or more of the provided criteria values are invalid. Please review and correct them."),WF("One or more of the provided criteria values are missing."),WF("The rule is invalid for an unknown reason."),WF("The table zone is invalid for an unknown reason"),WF("You cannot create overlapping tables."),WF("A table can only be created on a continuous selection."),WF("The range is invalid"),WF("The range is out of the sheet"),WF("Filter button"),WF("Header row(s)"),WF("Banded rows"),WF("First column"),WF("Last column"),WF("Banded columns"),WF("Automatically autofill formulas"),WF("Total row"),WF("Auto-adjust to formula result"),WF("Cannot have filters without a header row"),WF("For tables based on array formulas only"),WF("No calculations"),WF("% of grand total"),WF("% of column total"),WF("% of row total"),WF("% of"),WF("% of parent row total"),WF("% of parent column total"),WF("% of parent total"),WF("Difference from"),WF("% difference from"),WF("Running total"),WF("% Running total"),WF("Rank smallest to largest"),WF("Rank largest to smallest"),WF("Index"),WF("Displays the value that is entered in the field."),WF("Displays values as a percentage of the grand total of all the values or data points in the report."),WF("Displays all the values in each column or series as a percentage of the total for the column or series."),WF("Displays the value in each row or category as a percentage of the total for the row or category."),WF("Displays values as a percentage of the value of the Base item in the Base field."),WF("Calculates values as follows:\n(value for the item) / (value for the parent item on rows)"),WF("Calculates values as follows:\n(value for the item) / (value for the parent item on columns)"),WF("Calculates values as follows:\n(value for the item) / (value for the parent item of the selected Base field)"),WF("Displays values as the difference from the value of the Base item in the Base field."),WF("Displays values as the percentage difference from the value of the Base item in the Base field."),WF("Displays the value for successive items in the Base field as a running total."),WF("Calculates the value as a percentage for successive items in the Base field that are displayed as a running total."),WF("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."),WF("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."),WF("Calculates values as follows:\n((value in cell) x (Grand Total of Grand Totals)) / ((Grand Row Total) x (Grand Column Total))");const IP=new Og;class wP extends hv{mutators=["open","close"];persistentPopover;hoveredCell=this.get(HF);handle(e){if("ACTIVATE_SHEET"===e.type)this.close()}open({col:e,row:t},s){const o=this.getters.getActiveSheetId();IP.contains(s)&&(this.persistentPopover={col:e,row:t,sheetId:o,type:s})}close(){if(!this.persistentPopover)return"noStateChange";this.persistentPopover=void 0}get persistentCellPopover(){return this.persistentPopover&&{isOpen:!0,...this.persistentPopover}||{isOpen:!1}}get isOpen(){return void 0!==this.persistentPopover}get cellPopover(){const e=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){const e=this.getters.getMainCellPosition(this.persistentPopover),t=IP.get(this.persistentPopover.type).onOpen?.(e,this.getters);return t?.isOpen?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}const{col:t,row:s}=this.hoveredCell;if(void 0===t||void 0===s||!this.getters.isVisibleInViewport({sheetId:e,col:t,row:s}))return{isOpen:!1};const o=this.getters.getMainCellPosition({sheetId:e,col:t,row:s}),i=IP.getAll().map(e=>e.onHover?.(o,this.getters)).find(e=>e?.isOpen);return i?.isOpen?{...i,anchorRect:this.computePopoverAnchorRect(o)}:{isOpen:!1}}computePopoverAnchorRect({col:e,row:t}){const s=this.getters.getActiveSheetId(),o=this.getters.getMerge({sheetId:s,col:e,row:t});return o?this.getters.getVisibleRect(o):this.getters.getVisibleRect(Zt({col:e,row:t}))}}class EP extends t.Component{static maxSize={maxHeight:80};static template="o-spreadsheet-ErrorToolTip";static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};get dataValidationErrorMessage(){return this.env.model.getters.getInvalidDataValidationMessage(this.props.cellPosition)}get evaluationError(){const e=this.env.model.getters.getEvaluatedCell(this.props.cellPosition);if(e.message)return e}get errorOriginPositionString(){if(this.env.model.getters.isDashboard())return"";const e=this.evaluationError,t=e?.errorOriginPosition;if(!t||Me(t,this.props.cellPosition))return"";const s=t.sheetId;return this.env.model.getters.getRangeString(this.env.model.getters.getRangeFromZone(s,Zt(t)),this.env.model.getters.getActiveSheetId())}selectCell(){const e=this.evaluationError?.errorOriginPosition;if(!e)return;const t=this.env.model.getters.getActiveSheetId();e.sheetId!==t&&this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:e.sheetId}),this.env.model.selection.selectCell(e.col,e.row)}}const RP={onHover:(e,t)=>{const s=t.getEvaluatedCell(e);return s.type===_d.error&&s.message||t.getInvalidDataValidationMessage(e)?{isOpen:!0,props:{cellPosition:e},Component:EP,cellCorner:"top-right"}:{isOpen:!1}}};function xP(e,t,s,o,i){let n=o.right>o.left;if(e.model.getters.doesIntersectMerge(t,o)){let s;n=!1;for(let i=o.top;i<=o.bottom;i++){s=[];for(let n=o.left;n<=o.right;n++){const o=e.model.getters.getMerge({sheetId:t,col:n,row:i});o&&!s.includes(o.id.toString())&&s.push(o.id.toString())}if(s.length>=2){n=!0;break}}}if(n)return void TP(e,t,s,o,i);const r=e.model.getters.getContiguousZone(t,o);Mt(r,o)?TP(e,t,s,o,i):e.askConfirmation(fs("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?"),()=>TP(e,t,s,r,i),()=>TP(e,t,s,o,i))}function TP(e,t,s,o,i,n){const r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:s.col,row:s.row,zone:o,sortDirection:i,sortOptions:n});if(r.isCancelledBecause("InvalidSortZone")){const{col:t,row:i}=s;e.model.selection.selectZone({cell:{col:t,row:i},zone:o}),e.raiseError(fs("Cannot sort. To sort, select only cells or only merges that have the same size."))}if(r.isCancelledBecause("SortZoneWithArrayFormulas")){const{col:t,row:i}=s;e.model.selection.selectZone({cell:{col:t,row:i},zone:o}),e.raiseError(fs("Cannot sort a zone with array formulas."))}}class AP extends t.Component{static template="o-spreadsheet-Collapse";static props={isCollapsed:Boolean,slots:Object};contentRef=t.useRef("content");setup(){t.onMounted(()=>{this.props.isCollapsed&&this.contentRef.el?.classList.add("d-none")}),t.onWillUpdateProps(e=>{e.isCollapsed!==this.props.isCollapsed&&this.startTransition(e.isCollapsed)})}startTransition(e){const t=this.contentRef.el;if(!t)return;t.classList.remove("d-none"),t.classList.add("overflow-hidden");const s=e?t.scrollHeight:0,o=e?0:t.scrollHeight;t.animate([{maxHeight:s+"px"},{maxHeight:o+"px"}],{duration:350,easing:"ease"}).onfinish=()=>{t.classList.remove("overflow-hidden"),this.props.isCollapsed&&t.classList.add("d-none")}}}class DP extends t.Component{static template="o-spreadsheet-SidePanelCollapsible";static props={slots:Object,title:{type:String,optional:!0},isInitiallyCollapsed:{type:Boolean,optional:!0},class:{type:String,optional:!0}};static components={Collapse:AP};state=t.useState({isCollapsed:this.props.isInitiallyCollapsed});toggle(){this.state.isCollapsed=!this.state.isCollapsed}}class _P extends t.Component{static props={criterion:Object,onCriterionChanged:Function,disableFormulas:{type:Boolean,optional:!0}};setup(){const e=ev(uv);t.onMounted(()=>{e.activeComposer.stopEdition()})}updateCriterion(e){const t={...this.props.criterion,...e};this.props.onCriterionChanged(t)}}class OP{mutators=["setFocusableElement","focus"];focusableElement=void 0;setFocusableElement(e){return this.focusableElement=e,"noStateChange"}focus(){if(this.focusableElement===document.activeElement)return"noStateChange";this.focusableElement?.focus()}}const FP={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function PP(e,t){const s=FP[e.key];e.shiftKey?t.resizeAnchorZone(s,Uy(e)?"end":1):t.moveAnchorCell(s,Uy(e)?"end":1)}class MP extends t.Component{static template="o-spreadsheet-TextValueProvider";static props={proposals:Array,selectedIndex:{type:Number,optional:!0},onValueSelected:Function,onValueHovered:Function};autoCompleteListRef=t.useRef("autoCompleteList");setup(){t.useEffect(()=>{const e=this.props.selectedIndex;if(void 0===e)return;const t=this.autoCompleteListRef.el?.children[e];t?.scrollIntoView?.({block:"nearest"})},()=>[this.props.selectedIndex,this.autoCompleteListRef.el])}getCss(e){return Ey({color:e.color||"#000000",background:e.backgroundColor})}}class NP{el;constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){const s=window.getSelection(),{start:o,end:i}=this.getCurrentSelection();if(o===e&&i===t)return;if(0===s.rangeCount){const e=document.createRange();s.addRange(e)}const n=s.getRangeAt(0);let r;if(this.el.contains(n.startContainer)?r=n:(r=document.createRange(),s.removeAllRanges(),s.addRange(r)),e===t&&0===e)r.setStart(this.el,0),r.setEnd(this.el,0);else{const s=this.getText().length;(e<0||t>s)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${s}`),e<0&&(e=0),t>s&&(t=s),e>s&&(e=s));const o=this.findChildAtCharacterIndex(e),i=this.findChildAtCharacterIndex(t);e<=t?(r.setStart(o.node,o.offset),r.setEnd(i.node,i.offset)):(r.setStart(i.node,i.offset),r.setEnd(o.node,o.offset))}}findChildAtCharacterIndex(e){const t=Py(this.el);let s,o,i=e,n=!0;do{s=t.next(),s.done||s.value.hasChildNodes()||(s.value.textContent&&s.value.textContent.length<i?i-=s.value.textContent.length:s.value.textContent&&s.value.textContent.length>=i&&t.return(s.value),o=s.value),s.done||"P"!==s.value.nodeName||(n?n=!1:i--)}while(!s.done&&i);return s.value?{node:s.value,offset:i}:{node:o,offset:i}}setText(e){if(0===e.length)return void this.removeAll();const t=Array.from(this.el.childNodes),s=e.length;for(let o=0;o<s;o++){const s=e[o],i=t[o];let n,r=!1;i&&"P"===i.nodeName?n=i:(r=!0,n=document.createElement("p"));const a=s.length,l=Array.from(n.childNodes);for(let e=0;e<a;e++){const t=s[e],o=l[e];if(o&&"tagName"in o&&"SPAN"===o.tagName&&LP(t,o))continue;if(!t.value&&!t.classes?.length){o&&n.removeChild(o);continue}const i=document.createElement("span");i.innerText=t.value,i.style.color=t.color||"",i.addEventListener("mousemove",()=>{t.onHover?.(Fy(i))}),i.addEventListener("mouseleave",()=>{t.onStopHover?.()}),i.classList.add(...t.classes||[]),o?n.replaceChild(i,o):n.appendChild(i)}if(l.length>a)for(let e=a;e<l.length;e++)n.removeChild(l[e]);n.hasChildNodes()||n.appendChild(document.createElement("span")),r&&(i?this.el.replaceChild(n,i):this.el.appendChild(n))}if(t.length>s)for(let e=s;e<t.length;e++)this.el.removeChild(t[e])}scrollSelectionIntoView(){const e=document.getSelection()?.focusNode;if(!e||!this.el.contains(e))return;const t=e instanceof HTMLElement?e:e.parentElement;t?.scrollIntoView?.({block:"nearest"})}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){return My(this.el)}getText(){let e="",t=!0,s=!1;const o=Py(this.el);for(let i=o.next();!i.done;i=o.next())"P"===i.value.nodeName||"DIV"===i.value.nodeName&&i.value!==this.el?(t?t=!1:e+=X,s=["<br>","<span><br></span>"].includes(i.value.innerHTML)):i.value.hasChildNodes()||("BR"!==i.value.nodeName||s||(e+=X),e+=i.value.textContent);return e}}function LP(e,t){const s=(e.color?bv(e.color):"")===(t.style?.color?bv(t.style.color):""),o=Me(e.classes,[...t.classList]),i=t.innerText===e.value;return s&&o&&i}class kP extends t.Component{static template="o-spreadsheet-FunctionDescriptionProvider";static props={functionDescription:Object,argsToFocus:Array};static components={Collapse:AP};state=t.useState({isCollapsed:!0});toggle(){this.state.isCollapsed=!this.state.isCollapsed}getContext(){return this.props}get formulaArgSeparator(){return this.env.model.getters.getLocale().formulaArgSeparator+" "}}class VP extends t.Component{static template="o-spreadsheet-SpeechBubble";static props={content:String,anchorRect:Object};static components={};spreadsheetRect=AF();bubbleRef=t.useRef("bubble");setup(){t.useEffect(()=>{const e=this.bubbleRef.el;if(!e)return;const t=this.props.anchorRect,s=Fy(e),o=t.x+t.width/2-s.width/2-this.spreadsheetRect.x,i=t.y-s.height-7-this.spreadsheetRect.y;e.style.left=`${o}px`,e.style.top=`${i}px`})}}const UP=uf.content,HP=300;class zP 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:MP,FunctionDescriptionProvider:kP,SpeechBubble:VP};static defaultProps={inputStyle:"",isDefaultFocus:!1,inputMode:"text",showAssistant:!0};DOMFocusableElementStore;composerRef=t.useRef("o_composer");contentHelper=new NP(this.composerRef.el);composerState=t.useState({positionStart:0,positionEnd:0,hoveredRect:void 0});functionDescriptionState=t.useState({showDescription:!1,functionDescription:{},argsToFocus:[]});assistant=t.useState({forcedClosed:!1});compositionActive=!1;spreadsheetRect=AF();lastHoveredTokenIndex=void 0;debouncedHover=De((e,t)=>{const s=this.contentHelper.getCurrentSelection();if(s.start!==s.end)return;const o=this.props.composerStore.hoveredTokens;this.props.composerStore.hoverToken(e),Me(o,this.props.composerStore.hoveredTokens)||(this.composerState.hoveredRect=t)},120);get assistantStyleProperties(){const e=this.composerRef.el.getBoundingClientRect(),t={},s=Math.min(this.props.rect?.width||1/0,HP);t["min-width"]=`${s}px`;const o=this.props.composerStore.autoCompleteProposals,i=o?.some(e=>e.description);if((this.functionDescriptionState.showDescription||i)&&(t.width="300px"),this.props.delimitation&&this.props.rect){const{x:e,y:s,height:o}=this.props.rect,i=this.props.delimitation.height-(s+o);if(t["max-height"]=`${i}px`,s>i){const e=s;t["max-height"]=e-9+"px",t.transform=`translate(0, calc(-100% - ${o+3}px))`}e+HP>this.props.delimitation.width&&(t.right="0px")}else t["max-height"]=this.spreadsheetRect.height-e.bottom-1+"px",e.left+HP+O+9>this.spreadsheetRect.width&&(t.right="9px");return t}get assistantStyle(){const e=this.assistantStyleProperties;return Ey({"max-height":e["max-height"],width:e.width,"min-width":e["min-width"]})}get assistantContainerStyle(){const e=this.assistantStyleProperties;return Ey({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=ev(OP),t.onMounted(()=>{const e=this.composerRef.el;this.props.isDefaultFocus&&this.DOMFocusableElementStore.setFocusableElement(e),this.contentHelper.updateEl(e)}),t.onWillUnmount(()=>{this.debouncedHover.stopDebounce()}),t.useEffect(()=>{this.processContent(),document.activeElement!==this.contentHelper.el||"inactive"!==this.props.composerStore.editionMode||this.props.isDefaultFocus||this.DOMFocusableElementStore.focus()}),t.useEffect(()=>{this.processTokenAtCursor()},()=>["inactive"!==this.props.composerStore.editionMode]),t.useEffect(()=>{this.contentHelper.scrollSelectionIntoView()},()=>[this.props.composerStore.composerSelection.start,this.props.composerStore.composerSelection.end])}processArrowKeys(e){const t=this.props.composerStore.tokenAtCursor;if((this.props.composerStore.isSelectingRange||"inactive"===this.props.composerStore.editionMode)&&(!["ArrowUp","ArrowDown"].includes(e.key)||!this.props.composerStore.isAutoCompleteDisplayed||"REFERENCE"===t?.type))return this.functionDescriptionState.showDescription=!1,this.props.composerStore.hideHelp(),e.preventDefault(),e.stopPropagation(),void PP(e,this.env.model.selection);const s=this.props.composerStore.currentContent;"cellFocus"!==this.props.focus||this.props.composerStore.isAutoCompleteDisplayed||ot(s)?(e.stopPropagation(),this.handleArrowKeysForAutocomplete(e)):this.props.composerStore.stopEdition()}handleArrowKeysForAutocomplete(e){["ArrowUp","ArrowDown"].includes(e.key)&&this.props.composerStore.isAutoCompleteDisplayed&&(e.preventDefault(),this.props.composerStore.moveAutoCompleteSelection("ArrowDown"===e.key?"next":"previous"))}processTabKey(e,t){e.preventDefault(),e.stopPropagation(),this.assistant.forcedClosed||this.props.composerStore.autoCompleteOrStop(t)}processEnterKey(e,t){e.preventDefault(),e.stopPropagation(),this.assistant.forcedClosed||this.props.composerStore.autoCompleteOrStop(t)}processNewLineEvent(e){e.preventDefault(),e.stopPropagation();const t=this.contentHelper.getText(),s=this.contentHelper.getCurrentSelection(),o=Math.min(s.start,s.end),i=Math.max(s.start,s.end);this.props.composerStore.stopComposerRangeSelection(),this.props.composerStore.setCurrentContent(t.slice(0,o)+X+t.slice(i),{start:o+1,end:o+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();const t=this.env.model.getters.getLocale(),s=this.contentHelper.getCurrentSelection(),o=this.props.composerStore.currentContent,i=o.slice(0,s.start)+t.decimalSeparator+o.slice(s.end);this.props.composerStore.setCurrentContent(i,{start:s.start+1,end:s.start+1}),this.processContent()}onCompositionStart(){this.compositionActive=!0}onCompositionEnd(){this.compositionActive=!1}onKeydown(e){if("inactive"===this.props.composerStore.editionMode)return;if(e.key.startsWith("Arrow"))return void this.processArrowKeys(e);const t=this.keyMapping[ky(e)]||this.keyCodeMapping[ky(e,"code")];t?t.call(this,e):e.stopPropagation()}onPaste(e){"inactive"!==this.props.composerStore.editionMode?e.stopPropagation():e.preventDefault()}onInput(e){if(!this.shouldProcessInputEvents)return;let t;if(e.stopPropagation(),t="inactive"===this.props.composerStore.editionMode?e.data||"":this.contentHelper.getText(),"inactive"===this.props.focus)return this.props.onComposerCellFocused?.(t);const s=this.contentHelper.getCurrentSelection();this.props.composerStore.stopComposerRangeSelection(),this.props.composerStore.setCurrentContent(t,s),this.processTokenAtCursor()}onKeyup(e){if(this.contentHelper.el===document.activeElement){if(this.props.composerStore.isAutoCompleteDisplayed&&["ArrowUp","ArrowDown"].includes(e.key))return;if(this.props.composerStore.isSelectingRange&&e.key?.startsWith("Arrow"))return;const{start:t,end:s}=this.props.composerStore.composerSelection,{start:o,end:i}=this.contentHelper.getCurrentSelection();o===t&&i===s||this.props.composerStore.changeComposerCursorSelection(o,i),this.processTokenAtCursor()}}onBlur(e){if("inactive"===this.props.composerStore.editionMode)return;const t=e.relatedTarget;t&&t instanceof HTMLElement?t.attributes.getNamedItem("composerFocusableElement")?this.contentHelper.el.focus():t.classList.contains("o-composer")||this.props.composerStore.stopEdition():this.props.composerStore.stopEdition()}onMousedown(e){e.button>0||this.env.isMobile()&&!Gy()||(this.debouncedHover.stopDebounce(),this.contentHelper.removeSelection())}onMouseup(){if(this.env.model.getters.isReadonly())return;const e=this.contentHelper.getCurrentSelection();e.start!==e.end&&this.props.composerStore.hoverToken(void 0)}onClick(){if(this.env.model.getters.isReadonly())return;const e=this.contentHelper.getCurrentSelection();this.props.composerStore.stopComposerRangeSelection();const t="inactive"===this.props.composerStore.editionMode;this.props.onComposerContentFocused(e),t||this.props.composerStore.changeComposerCursorSelection(e.start,e.end),this.processTokenAtCursor()}onDblClick(){if(this.env.model.getters.isReadonly())return;const e=this.props.composerStore.currentContent;if(ot(e)){const t=this.props.composerStore.currentTokens,s=this.contentHelper.getCurrentSelection();if(s.start===s.end)return;const o=e.substring(s.start,s.end),i=t.filter(e=>e.value.includes(o)&&e.start<=s.start&&e.end>=s.end)[0];if(!i)return;"REFERENCE"===i.type&&this.props.composerStore.changeComposerCursorSelection(i.start,i.end)}}onContextMenu(e){"inactive"===this.props.composerStore.editionMode&&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,"inactive"!==this.props.focus&&document.activeElement!==this.contentHelper.el&&this.contentHelper.el.focus();const e=this.getContentLines();if(this.contentHelper.setText(e),0!==e.length&&0!==e.length[0]&&"inactive"!==this.props.focus){const{start:e,end:t}=this.props.composerStore.composerSelection;this.contentHelper.selectRange(e,t)}this.shouldProcessInputEvents=!0}getContentLines(){const e=this.props.composerStore.currentContent,t=ot(e);return""===e?[]:t&&"inactive"!==this.props.focus?this.splitHtmlContentIntoLines(this.getHtmlContentFromTokens()):this.splitHtmlContentIntoLines([{value:e,classes:[]}])}getHtmlContentFromTokens(){const e=this.props.composerStore.currentTokens,t=[],{end:s,start:o}=this.props.composerStore.composerSelection;for(let i=0;i<e.length;i++){const n=e[i];let r=n.color||se;n.isBlurred&&(r=_v(r,.5));const a=[];"REFERENCE"===n.type&&this.props.composerStore.tokenAtCursor===n&&"selecting"===this.props.composerStore.editionMode&&a.push("text-decoration-underline"),s===o&&n.isParenthesisLinkedToCursor&&a.push("highlight-parenthesis-flag"),n.isInHoverContext&&a.push("highlight-flag"),this.props.composerStore.showSelectionIndicator&&s===o&&s===n.end&&a.push("selector-flag"),t.push({value:n.value,color:r,classes:a,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){const t=[];let s=[];for(const o of e)if(o.value.includes(X)){const e=o.value.split(X),i=e.pop();for(const i of e)s.push({color:o.color,value:i}),t.push(s),s=[];s.push({...o,value:i})}else s.push(o);s.length&&t.push(s);const o=[];for(const e of t)e.every(this.isContentEmpty)?o.push([e[0]]):o.push(e.filter(e=>!this.isContentEmpty(e)));return o}isContentEmpty(e){return!(e.value||e.classes?.length)}processTokenAtCursor(){const e=this.props.composerStore;this.functionDescriptionState.showDescription=!1;const t=this.props.composerStore.tokenAtCursor;if(ot(e.currentContent)&&t&&"SYMBOL"!==t.type){const e=t.functionContext,s=e?.parent.toUpperCase();if(e&&s&&s in UP&&"UNKNOWN"!==t.type){const o=UP[s],i=e.argPosition,n=e.args.length;this.functionDescriptionState.functionDescription=o;const r=this.props.composerStore.currentTokens.some(e=>"RIGHT_PAREN"===e.type&&e.parenthesesCode===t.parenthesesCode);this.functionDescriptionState.argsToFocus=this.getArgsToFocus(r,o,n,i),this.functionDescriptionState.showDescription=!0}}}getArgsToFocus(e,t,s,o){const{nbrArgRepeating:i,minArgRequired:n,nbrArgOptional:r,maxArgPossible:a}=t;if(e){const e=cs(t,Math.max(Math.min(a,s),n))(o);return void 0!==e?[e]:[]}const l=Math.max(s,n),c=i?n+Math.ceil((l-n)/i)*i+r:a,h=[];for(let e=l;e<=c;e++){const s=cs(t,e)(o);void 0!==s&&h.push(s)}return[...new Set(h)]}autoComplete(e){!e||this.assistant.forcedClosed&&this.props.composerStore.canBeToggled||(this.props.composerStore.insertAutoCompleteValue(e),this.processTokenAtCursor())}get displaySpeechBubble(){return!("inactive"===this.props.focus||!this.composerState.hoveredRect||!this.props.composerStore.hoveredContentEvaluation)}}function BP(e,t){return function(e){for(const t of e)if(t.functionContext){const{argsTokens:e,args:s}=t.functionContext;if(delete t.functionContext.argsTokens,s.length||!e)continue;"LEFT_PAREN"===e[0]?.[0]?.type&&(e[0]=e[0].slice(1));for(const t of e){let e=t;"ARG_SEPARATOR"===e.at(0)?.type&&(e=e.slice(1));try{s.push(_f(e))}catch(e){s.push(void 0)}}}return e}(function(e){const t=[];let s="";function o(e){if(0===t.length)return;const s=t.at(-1);if(s&&s.argsTokens){const{argsTokens:t,argPosition:o}=s;t[o]||(t[o]=[]),t[o].push({value:e.value,type:e.type})}}return e.map((e,i)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(s=""),e.type){case"SYMBOL":o(e),s=e.value;break;case"LEFT_PAREN":t.push({parent:s,argPosition:0,argsTokens:[],args:[]}),o(e),s="";break;case"RIGHT_PAREN":const i=t.pop();i?.argsTokens?.flat().forEach(o),o(e);break;case"ARG_SEPARATOR":t.length&&t[t.length-1].argPosition++,o(e);break;default:o(e)}if(t.length){const s=t[t.length-1];s.parent&&(e.functionContext=Object.assign({},s))}return e})}(function(e){const t=[];let s=0;return e.map((o,i)=>{if("LEFT_PAREN"===o.type){t.push(s+1),s=0;for(let s=i-1;s>=0;s--){if("SPACE"!==e[s].type){"SYMBOL"===e[s].type&&(e[s].parenthesesCode=t.join(":"));break}e[s].parenthesesCode=t.join(":")}}return o.parenthesesCode=t.join(":"),"RIGHT_PAREN"===o.type&&t.length&&(s=t.pop()),o})}(function(e){let t=0;return e.map(e=>{const s=e.value.toString().length,o=Object.assign({},e,{start:t,end:t+s,length:s});return t=o.end,o})}(Sf(e,t)))))}class GP{lastId=0;add(e){this.lastId++;const t=this.lastId;return new Promise((s,o)=>{e.then(e=>{this.lastId===t&&s(e)}).catch(e=>{this.lastId===t&&o(e)})})}}function WP(e,t,s){const o=(t.startsWith("=")?BP(t,s):[]).filter(t=>t.start<=e.start&&t.end>=e.start||t.start>=e.start&&t.start<e.end),i=o.filter(e=>"REFERENCE"===e.type);if(0===i.length)return;const n=o.map(or).map(e=>e.value).join(""),r=o[0].start,a=o[o.length-1].end,l=t.slice(0,r)+n+t.slice(a),c=l.length-t.length,h={start:i[0].start,end:i[i.length-1].end+c};return 1===i.length&&e.start===e.end&&(h.start=h.end),{content:l,selection:h}}const $P=new Og;function qP(e,t,s){const{x:i,y:n,width:r,height:a}=s;if(r<0||a<0)return;const l=t.color||o,{ctx:c}=e;c.save(),t.noBorder||(t.dashed&&c.setLineDash([5,3]),c.strokeStyle=l,t.thinLine?(c.lineWidth=1,c.strokeRect(i,n,r,a)):(c.lineWidth=2,c.strokeRect(i+.5,n+.5,r,a))),t.noFill||(c.fillStyle=_v(bv(l),t.fillAlpha??.12),c.fillRect(i,n,r,a)),c.restore()}class ZP extends hv{mutators=["register","unRegister"];providers=[];constructor(e){super(e),this.onDispose(()=>{this.providers=[]})}get renderingLayers(){return["Highlights"]}get highlights(){const e=this.getters.getActiveSheetId();return this.providers.flatMap(e=>e.highlights).filter(t=>t.range.sheetId===e).map(e=>{const{numberOfRows:t,numberOfCols:s}=Ut(e.range.zone),o=t*s===1?this.getters.expandZone(e.range.sheetId,e.range.zone):e.range.unboundedZone;return{...e,range:this.model.getters.getRangeFromZone(e.range.sheetId,o)}})}register(e){this.providers.push(e)}unRegister(e){this.providers=this.providers.filter(t=>t!==e)}drawLayer(e,t){if("Highlights"===t)for(const t of this.highlights){qP(e,t,this.getters.getVisibleRect(t.range.zone))}}}class jP{mutators=["notifyUser","raiseError","askConfirmation","updateNotificationCallbacks"];notifyUser=e=>window.alert(e.text);askConfirmation=(e,t,s)=>{window.confirm(e)?t():s?.()};raiseError=(e,t)=>{window.alert(e),t?.()};updateNotificationCallbacks(e){this.notifyUser=e.notifyUser||this.notifyUser,this.raiseError=e.raiseError||this.raiseError,this.askConfirmation=e.askConfirmation||this.askConfirmation}}class YP extends hv{mutators=["useProvider","moveSelection","hide","selectIndex"];selectedIndex=void 0;provider;get selectedProposal(){if(void 0!==this.selectedIndex&&void 0!==this.provider)return this.provider.proposals[this.selectedIndex]}useProvider(e){this.provider=e,this.selectedIndex=e.autoSelectFirstProposal?0:void 0}hide(){this.provider=void 0,this.selectedIndex=void 0}selectIndex(e){this.selectedIndex=e}moveSelection(e){this.provider&&(void 0!==this.selectedIndex?"previous"===e?(this.selectedIndex--,this.selectedIndex<0&&(this.selectedIndex=this.provider.proposals.length-1)):this.selectedIndex=(this.selectedIndex+1)%this.provider.proposals.length:this.selectedIndex=0)}}class XP extends hv{mutators=["startEdition","setCurrentContent","stopEdition","stopComposerRangeSelection","cancelEdition","cycleReferences","hideHelp","autoCompleteOrStop","insertAutoCompleteValue","moveAutoCompleteSelection","selectAutoCompleteIndex","toggleEditionMode","changeComposerCursorSelection","replaceComposerCursorSelection","hoverToken"];col=0;row=0;editionMode="inactive";sheetId="";_currentContent="";currentTokens=[];selectionStart=0;selectionEnd=0;initialContent="";colorIndexByRange={};autoComplete=new YP(this.get);hoveredTokens=[];hoveredContentEvaluation="";autoCompleteKeepLast=new GP;notificationStore=this.get(jP);highlightStore=this.get(ZP);constructor(e){super(e),this.highlightStore.register(this),this.onDispose(()=>{this.highlightStore.unRegister(this)})}handleEvent(e){this.hideHelp();const t=this.getters.getActiveSheetId();let s;if(s=e.options.unbounded?this.getters.getUnboundedZone(t,e.anchor.zone):e.anchor.zone,"newAnchor"===e.mode)"selecting"===this.editionMode&&this.insertSelectedRange(s);else"selecting"===this.editionMode?this.replaceSelectedRange(s):this.updateComposerRange(e.previousAnchor.zone,s)}changeComposerCursorSelection(e,t){this.isSelectionValid(this._currentContent.length,e,t)&&(this.selectionStart=e,this.selectionEnd=t,this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor(),this.updateAutoCompleteProvider())}stopComposerRangeSelection(){this.isSelectingRange&&(this.editionMode="editing")}startEdition(e,t){const{col:s,row:o}=this.getters.getActivePosition();this.model.dispatch("SELECT_FIGURE",{figureId:null}),this.model.dispatch("SCROLL_TO_CELL",{col:s,row:o}),"inactive"!==this.editionMode&&e?this.setContent(e,t):this._startEdition(e,t),this.updateTokenColor(),this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor(),this.updateAutoCompleteProvider()}cancelEdition(){this.resetContent(),this.cancelEditionAndActivateSheet()}setCurrentContent(e,t){t&&!this.isSelectionValid(e.length,t.start,t.end)||(this.setContent(e,t,!0),this.updateTokenColor(),this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor())}replaceComposerCursorSelection(e){this.replaceSelection(e)}handle(e){switch(e.type){case"SELECT_FIGURE":e.figureId&&(this.resetContent(),this.cancelEditionAndActivateSheet());break;case"START_CHANGE_HIGHLIGHT":const{left:t,top:s}=e.zone;this.isSelectingRange&&(this.editionMode="editing"),this.model.selection.resetAnchor(this,{cell:{col:t,row:s},zone:e.zone})}}get currentContent(){return"inactive"===this.editionMode?this.getComposerContent(this.getters.getActivePosition()).text:this._currentContent}get composerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}get isSelectingRange(){return"selecting"===this.editionMode}get showSelectionIndicator(){return this.isSelectingRange&&this.canStartComposerRangeSelection()}get tokenAtCursor(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return e===t&&0===t?void 0:this.currentTokens.find(s=>s.start<=e&&s.end>=t)}get autoCompleteProposals(){return this.autoComplete.provider?.proposals||[]}get autoCompleteSelectedIndex(){return this.autoComplete.selectedIndex}get isAutoCompleteDisplayed(){return!!this.autoComplete.provider}get canBeToggled(){return this.autoComplete.provider?.canBeToggled??!0}cycleReferences(){const e=this.getters.getLocale(),t=WP(this.composerSelection,this._currentContent,e);void 0!==t&&this.setCurrentContent(t.content,t.selection)}toggleEditionMode(){if("inactive"===this.editionMode)return;const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd),s=[...this.currentTokens].reverse().find(s=>s.end>=e&&t>=s.start&&"REFERENCE"===s.type);if("editing"===this.editionMode&&s){const e=this.getters.getActiveSheetId(),{sheetName:t,xc:o}=tr(s.value),i=this.getters.getSheetIdByName(t);i&&i!==e&&this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:i}),this.selectionStart=this.selectionEnd=s.end;const n=this.getters.getRangeFromSheetXC(this.sheetId,o).zone;this.captureSelection(n),this.editionMode="selecting"}else this.editionMode="editing"}hoverToken(e){this.currentTokens.forEach(e=>e.isInHoverContext=void 0);const t=[...this.currentTokens];if(void 0===e||["ARG_SEPARATOR","SPACE"].includes(t[e].type))return this.hoveredContentEvaluation="",void(this.hoveredTokens=[]);const s=this.getNumberOfMissingParenthesis(t);s>0&&t.push(...Array(s).fill({value:")",type:"RIGHT_PAREN"}));let o=t;if(0!==e){const s=this.getRelatedTokens(t,e),i=t.filter(e=>!s.includes(e)&&"SPACE"!==e.type);o=1===i.length&&i[0]===t[0]?t:s}o.forEach(e=>e.isInHoverContext=!0);let i=o.map(e=>e.value).join("");ot(i)||(i=`=${i}`);const n=Kc(i,this.getters.getLocale()),r=this.getters.evaluateFormulaResult(this.sheetId,n);this.hoveredTokens=o,this.hoveredContentEvaluation=this.evaluationResultToDisplayString(r)}getRelatedTokens(e,t){try{const s=_f(e);let o;for(const e of Ff(s))if(t>=e.tokenStartIndex&&t<=e.tokenEndIndex)o=e;else if(t<e.tokenStartIndex)break;return o?e.slice(o.tokenStartIndex,o.tokenEndIndex+1):e}catch(t){if(t instanceof Cs)return e;throw t}}evaluationResultToDisplayString(e){const t=this.getters.getLocale();if(Ds(e)){const s=","===t.decimalSeparator?"/":",";return`{${Uo(e).map(e=>e.map(e=>this.cellValueToDisplayString(e)).join(s)).join(";")}}`}return this.cellValueToDisplayString(e)}cellValueToDisplayString(e){const t=e.value;switch(typeof t){case"number":return pn(t,{locale:this.getters.getLocale(),format:e.format});case"string":return mo(t)?t:`"${t}"`;case"boolean":return t?"TRUE":"FALSE"}return"0"}captureSelection(e,t,s){this.model.selection.capture(this,{cell:{col:t??e.left,row:s??e.right},zone:e},{handleEvent:this.handleEvent.bind(this),release:()=>{this._stopEdition()}})}isSelectionValid(e,t,s){return t>=0&&t<=e&&s>=0&&s<=e}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){const e=Zt({col:this.col,row:this.row});this.model.selection.resetAnchor(this,{cell:{col:this.col,row:this.row},zone:e})}this.editionMode="selecting"}_startEdition(e,t){const s=this.getters.getActiveCell(),o=this.getters.getLocale();e&&s.format?.includes("%")&&lo(e,o)&&(t=t||{start:e.length,end:e.length},e=`${e}%`);const{col:i,row:n,sheetId:r}=this.getters.getActivePosition();this.col=i,this.sheetId=r,this.row=n,this.editionMode="editing";const{text:a,adjustedSelection:l}=this.getComposerContent({sheetId:r,col:i,row:n},t);this.initialContent=a,this.setContent(e||this.initialContent,l??t),this.colorIndexByRange={};const c=Zt({col:this.col,row:this.row});this.captureSelection(c,i,n)}_stopEdition(){if("inactive"!==this.editionMode){this.cancelEditionAndActivateSheet();let e=this.getCurrentCanonicalContent();if(!(this.initialContent!==e))return;if(e&&ot(e)){const t=this.getNumberOfMissingParenthesis(this.currentTokens);t>0&&(e+=_e(new Array(t).fill(")")))}this.confirmEdition(e)}}getCurrentCanonicalContent(){return Kc(this._currentContent,this.getters.getLocale())}cancelEditionAndActivateSheet(){if("inactive"===this.editionMode)return;this._cancelEdition();this.getters.getActiveSheetId()!==this.sheetId&&this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}_cancelEdition(){"inactive"!==this.editionMode&&(this.editionMode="inactive",this.model.selection.release(this),this.colorIndexByRange={},this.hoveredTokens=[],this.hoveredContentEvaluation="")}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,s){const o=this._currentContent!==e;if(this._currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,o||"inactive"!==this.editionMode){const t=this.getters.getLocale();this.currentTokens=ot(e)?BP(e,t):[];this.currentTokens.filter(e=>"SPACE"!==e.type).length>1e3&&s&&this.notificationStore.raiseError(fs("This formula has over 1000 parts. It can't be processed properly, consider splitting it into multiple cells"))}this.canStartComposerRangeSelection()&&this.startComposerRangeSelection(),this.updateAutoCompleteProvider()}getAutoCompleteProviders(){return $P.getAll()}insertSelectedRange(e){const t=Math.min(this.selectionStart,this.selectionEnd),s=this.getZoneReference(e);this.canStartComposerRangeSelection()?this.insertText(s,t):this.insertText(","+s,t)}replaceSelectedRange(e){const t=this.getZoneReference(e),s=this.tokenAtCursor,o="REFERENCE"===s?.type?s.start:this.selectionStart;this.replaceText(t,o,this.selectionEnd)}updateComposerRange(e,t){const s=this.getters.getActiveSheetId(),o=this.tokenAtCursor,i=(o?[o,...this.currentTokens]:this.currentTokens).filter(e=>"REFERENCE"===e.type).find(t=>{const{xc:o,sheetName:i}=tr(t.value),n=i||this.getters.getSheetName(this.sheetId);if(!vb(this.getters.getSheetName(s),n))return!1;const r=this.getters.getRangeFromSheetXC(s,o);return Mt(this.getters.expandZone(s,r.zone),e)});if(!i)return;const n=this.getters.getRangeFromSheetXC(s,i.value);this.selectionStart=i.start,this.selectionEnd=this.selectionStart+i.value.length;const r=this.getters.getRangeFromZone(s,t),a=this.getRangeReference(r,n.parts);this.replaceSelection(a)}getZoneReference(e){const t=this.sheetId,s=this.getters.getActiveSheetId(),o=this.getters.getRangeFromZone(s,e);return this.getters.getSelectionRangeString(o,t)}getRangeReference(e,t){const s={...e,parts:[...t]};return this.getters.getSelectionRangeString(s,this.sheetId)}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),s=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,s)}replaceText(e,t,s){this._currentContent=this._currentContent.slice(0,t)+this._currentContent.slice(s,this._currentContent.length),this.insertText(e,t)}insertText(e,t){const s=this._currentContent.slice(0,t)+e+this._currentContent.slice(t),o=t+e.length;this.setCurrentContent(s,{start:o,end:o})}updateTokenColor(){this.updateRangeColor();for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].color=this.getTokenColor(this.currentTokens[e])}getTokenColor(e){if("REFERENCE"===e.type){const{xc:t,sheetName:s}=tr(e.value);return this.rangeColor(t,s)||se}if("SYMBOL"===e.type){const t=e.value.toUpperCase();if("TRUE"===t||"FALSE"===t)return ie.NUMBER;if(t in uf.content)return ie.FUNCTION}return["LEFT_PAREN","RIGHT_PAREN"].includes(e.type)&&""===e.parenthesesCode?ie.ORPHAN_RIGHT_PAREN:ie[e.type]||se}rangeColor(e,t){const s=t?this.model.getters.getSheetIdByName(t):this.sheetId,o=this.highlights.find(t=>{if(t.range.sheetId!==s)return!1;let o=this.model.getters.getRangeFromSheetXC(s,e).zone;return o=1===Kt(o)?this.model.getters.expandZone(s,o):o,Mt(o,t.range.zone)});return o&&o.color?o.color:void 0}computeFormulaCursorContext(){for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].isBlurred=!1;if(this.selectionStart!==this.selectionEnd)return;const e=this.getParenthesesCodeAfterCursor(),t=[...this.currentTokens].reverse().find(t=>e.startsWith(t.parenthesesCode)&&"SYMBOL"===t.type);if(t)for(let e=0;e<this.currentTokens.length;e++)(this.currentTokens[e].parenthesesCode||"").startsWith(t.parenthesesCode||"")||(this.currentTokens[e].isBlurred=!0)}getParenthesesCodeAfterCursor(){const e=this.tokenAtCursor?.parenthesesCode||"";return"RIGHT_PAREN"===this.tokenAtCursor?.type?e.slice(0,-1)||"":e}computeParenthesisRelatedToCursor(){for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].isParenthesisLinkedToCursor=!1;const e=this.tokenAtCursor;if(e&&""!==e.parenthesesCode&&["LEFT_PAREN","RIGHT_PAREN"].includes(e.type))for(let t=0;t<this.currentTokens.length;t++){const s=this.currentTokens[t];["LEFT_PAREN","RIGHT_PAREN"].includes(s.type)&&s.parenthesesCode===e.parenthesesCode&&s!==e&&(this.currentTokens[t].isParenthesisLinkedToCursor=!0,this.tokenAtCursor.isParenthesisLinkedToCursor=!0)}}updateRangeColor(){if(!ot(this._currentContent)||"inactive"===this.editionMode)return;const e=this.sheetId,t=this.getReferencedRanges().map(t=>this.getters.getRangeString(t,e)),s={};for(const e of t)void 0!==this.colorIndexByRange[e]&&(s[e]=this.colorIndexByRange[e]);const o=new Set(Object.values(s));let i=0;const n=()=>{for(;o.has(i);)i++;return o.add(i),i};for(const e of t){const t=e in s?s[e]:n();s[e]=t}this.colorIndexByRange=s}get highlights(){if(!ot(this.currentContent)||"inactive"===this.editionMode)return[];const e=this.sheetId,t=e=>{const t=this.colorIndexByRange[e];return mv[t%mv.length]};return this.getReferencedRanges().map(s=>{const o=this.getters.getRangeString(s,e),{numberOfRows:i,numberOfCols:n}=Ut(s.zone),r=i*n===1?this.getters.expandZone(s.sheetId,s.zone):s.unboundedZone;return{range:this.model.getters.getRangeFromZone(s.sheetId,r),color:t(o),interactive:!0}})}getReferencedRanges(){const e=this.sheetId;return this.currentTokens.filter(e=>"REFERENCE"===e.type).map(t=>this.getters.getRangeFromSheetXC(e,t.value)).filter(e=>!e.invalidSheetName&&!e.invalidXc)}async updateAutoCompleteProvider(){this.autoComplete.hide();const e=await this.autoCompleteKeepLast.add(this.findAutocompleteProvider());e&&(this.autoComplete.useProvider(e),this.model.trigger("update"))}async findAutocompleteProvider(){const e=this.currentContent,t=ot(e)?this.tokenAtCursor:{type:"STRING",value:e};if("inactive"===this.editionMode||!t||["TRUE","FALSE"].includes(t.value.toUpperCase())||!this.canStartComposerRangeSelection()&&!["SYMBOL","STRING","UNKNOWN"].includes(t.type))return;const s={composer:this,getters:this.getters},o=this.getAutoCompleteProviders().sort((e,t)=>(e.sequence??1/0)-(t.sequence??1/0)).map(o=>({...o,getProposals:o.getProposals.bind(s,t,e),selectProposal:o.selectProposal.bind(s,t)}));for(const e of o){let s=await e.getProposals();const o=s?.find(e=>e.text===t.value),i=t.value.replace(/[ ,\(\)]/g,"");if(this._currentContent===this.initialContent&&e.displayAllOnInitialContent&&s?.length)return{proposals:s,selectProposal:e.selectProposal,autoSelectFirstProposal:e.autoSelectFirstProposal??!1,canBeToggled:e.canBeToggled};if(o&&this._currentContent!==this.initialContent)return;if(i&&s&&!["ARG_SEPARATOR","LEFT_PAREN","OPERATOR"].includes(t.type)){const e=tS(i,s,e=>e.fuzzySearchKey||e.text);o&&!e.length||(s=e)}if(e.maxDisplayedProposals&&(s=s?.slice(0,e.maxDisplayedProposals)),s?.length)return{proposals:s,selectProposal:e.selectProposal,autoSelectFirstProposal:e.autoSelectFirstProposal??!1,canBeToggled:e.canBeToggled}}}hideHelp(){this.autoComplete.hide()}autoCompleteOrStop(e){if("inactive"!==this.editionMode){const t=this.autoComplete;if(t.provider&&void 0!==t.selectedIndex){const e=t.provider.proposals[t.selectedIndex]?.text;if(e)return void this.autoComplete.provider?.selectProposal(e)}this.stopEdition(e)}}insertAutoCompleteValue(e){this.autoComplete.provider?.selectProposal(e)}selectAutoCompleteIndex(e){this.autoComplete.selectIndex(ue(0,e,10))}moveAutoCompleteSelection(e){this.autoComplete.moveSelection(e)}canStartComposerRangeSelection(){if(ot(this._currentContent)){const e=this.tokenAtCursor;if(!e)return!1;const t=this.currentTokens.map(e=>e.start).indexOf(e.start);let s=t,o=e;for(;!["ARG_SEPARATOR","LEFT_PAREN","OPERATOR"].includes(o.type)||Fc.includes(o.value);){if("SPACE"!==o.type||s<1)return!1;s--,o=this.currentTokens[s]}for(s=t+1,o=this.currentTokens[s];o&&!["ARG_SEPARATOR","RIGHT_PAREN","OPERATOR"].includes(o.type);){if("SPACE"!==o.type)return!1;s++,o=this.currentTokens[s]}return!0}return!1}getNumberOfMissingParenthesis(e){return e.filter(e=>"LEFT_PAREN"===e.type).length-e.filter(e=>"RIGHT_PAREN"===e.type).length}}class KP extends XP{args;constructor(e,t){super(e),this.args=t,this._currentContent=this.getComposerContent().text}getAutoCompleteProviders(){const e=super.getAutoCompleteProviders(),t=this.args().contextualAutocomplete;return t&&e.push(t),e}getZoneReference(e){const t=super.getZoneReference(e);return this.args().defaultStatic?nr(t,"colrow"):t}getComposerContent(){let e=this._currentContent;if("inactive"===this.editionMode){const t=this.args().defaultRangeSheetId;e=Sf(this.args().content).map(e=>{if("REFERENCE"===e.type){const s=this.getters.getRangeFromSheetXC(t,e.value);return this.getters.getRangeString(s,this.getters.getActiveSheetId())}return e.value}).join("")}return{text:Qc(e,this.getters.getLocale())}}stopEdition(){this._stopEdition()}confirmEdition(e){this.args().onConfirm(e)}getTokenColor(e){if("SYMBOL"===e.type){const t=this.args().getContextualColoredSymbolToken?.(e);if(t)return t}return super.getTokenColor(e)}}class JP extends t.Component{static template="o-spreadsheet-StandaloneComposer";static props={composerContent:{type:String,optional:!0},defaultRangeSheetId:{type:String,optional:!0},defaultStatic:{type:Boolean,optional:!0},onConfirm:Function,contextualAutocomplete:{type:Object,optional:!0},placeholder:{type:String,optional:!0},title:{type:String,optional:!0},class:{type:String,optional:!0},invalid:{type:Boolean,optional:!0},getContextualColoredSymbolToken:{type:Function,optional:!0}};static components={Composer:zP};static defaultProps={composerContent:"",defaultStatic:!1};composerFocusStore;standaloneComposerStore;composerInterface;spreadsheetRect=AF();setup(){this.composerFocusStore=ev(uv);const e=tv(KP,()=>({onConfirm:this.props.onConfirm,content:this.props.composerContent,defaultStatic:this.props.defaultStatic??!1,contextualAutocomplete:this.props.contextualAutocomplete,defaultRangeSheetId:this.props.defaultRangeSheetId,getContextualColoredSymbolToken:this.props.getContextualColoredSymbolToken}));this.standaloneComposerStore=e,this.composerInterface={id:"standaloneComposer",get editionMode(){return e.editionMode},startEdition:this.standaloneComposerStore.startEdition,setCurrentContent:this.standaloneComposerStore.setCurrentContent,stopEdition:this.standaloneComposerStore.stopEdition}}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get composerStyle(){return this.props.invalid?Ey({padding:"1px 0px 0px 0px"}):Ey({padding:"1px 0px"})}get containerClass(){return["inactive"===this.focus?"":"active",this.props.invalid?"o-invalid":"",this.props.class||""].join(" ")}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}}class QP extends t.Component{static template="o-spreadsheet-CriterionInput";static props={value:{type:String,optional:!0},criterionType:String,onValueChanged:Function,onKeyDown:{type:Function,optional:!0},focused:{type:Boolean,optional:!0},onBlur:{type:Function,optional:!0},onFocus:{type:Function,optional:!0},disableFormulas:{type:Boolean,optional:!0}};static defaultProps={value:"",onKeyDown:()=>{},focused:!1,onBlur:()=>{}};static components={StandaloneComposer:JP};inputRef=t.useRef("input");setup(){t.useEffect(()=>{this.props.focused&&this.inputRef.el.focus()},()=>[this.props.focused,this.inputRef.el])}state=t.useState({shouldDisplayError:!!this.props.value});get placeholder(){return"onlyFormulas"===this.allowedValues?fs("Formula"):"onlyLiterals"===this.allowedValues?fs("Value"):fs("Value or formula")}get allowedValues(){const e=QT.get(this.props.criterionType);if("onlyFormulas"===e.allowedValues&&this.props.disableFormulas)throw new Error(`Cannot disable formulas for criterion type ${this.props.criterionType} that accept only formulas`);return(this.props.disableFormulas?"onlyLiterals":e.allowedValues)??"any"}onInputValueChanged(e){this.state.shouldDisplayError=!0,this.props.onValueChanged(e.target.value)}onChangeComposerValue(e){this.state.shouldDisplayError=!0,this.props.onValueChanged(e)}getDataValidationRuleInputComposerProps(){return{onConfirm:e=>this.onChangeComposerValue(e),composerContent:this.props.value,placeholder:this.placeholder,class:"o-sidePanel-composer",defaultRangeSheetId:this.env.model.getters.getActiveSheetId(),invalid:this.state.shouldDisplayError&&!!this.errorMessage,defaultStatic:!0}}get errorMessage(){if(this.state.shouldDisplayError)return this.env.model.getters.getDataValidationInvalidCriterionValueMessage(this.props.criterionType,Jc(this.props.value,this.env.model.getters.getLocale()))}}const eM={today:fs("today"),yesterday:fs("yesterday"),tomorrow:fs("tomorrow"),lastWeek:fs("in the past week"),lastMonth:fs("in the past month"),lastYear:fs("in the past year"),exactDate:fs("exact date")};class tM extends _P{static template="o-spreadsheet-DataValidationDateCriterion";static components={CriterionInput:QP};setup(){super.setup();const e=e=>{void 0===e.criterion.dateValue&&this.updateCriterion({dateValue:"exactDate"})};t.onWillUpdateProps(e),t.onWillStart(()=>e(this.props))}onValueChanged(e){this.updateCriterion({values:[e]})}onDateValueChanged(e){const t=e.target.value;this.updateCriterion({dateValue:t})}get dateValues(){return Object.keys(eM).map(e=>({value:e,title:eM[e]}))}}class sM extends _P{static template="o-spreadsheet-DoubleInputCriterionForm";static components={CriterionInput:QP};onFirstValueChanged(e){const t=this.props.criterion.values;this.updateCriterion({values:[e,t[1]||""]})}onSecondValueChanged(e){const t=this.props.criterion.values;this.updateCriterion({values:[t[0]||"",e]})}}class oM extends _P{static template="o-spreadsheet-SingleInputCriterionForm";static components={CriterionInput:QP};onValueChanged(e){const t=ae(this.props.criterion);t.values[0]=e,this.updateCriterion(t)}}function iM(e,t){const s=()=>{window.removeEventListener("pointerup",o,{capture:!0}),window.removeEventListener("dragstart",i),window.removeEventListener("pointermove",e),window.removeEventListener("wheel",e)},o=e=>{t(e),s()};function i(e){e.preventDefault()}return window.addEventListener("pointerup",o,{capture:!0}),window.addEventListener("dragstart",i),window.addEventListener("pointermove",e),window.addEventListener("wheel",e,{passive:!1}),s}const nM=216;class rM extends t.Component{static template="o-spreadsheet-ColorPicker";static props={onColorPicked:Function,currentColor:{type:String,optional:!0},maxHeight:{type:Number,optional:!0},anchorRect:Object,disableNoColor:{type:Boolean,optional:!0}};static defaultProps={currentColor:""};static components={Popover:DF};COLORS=T;state=t.useState({showGradient:!1,currentHslaColor:Sv(this.props.currentColor)?{...Av(this.props.currentColor),a:1}:{h:0,s:100,l:100,a:1},customHexColor:Sv(this.props.currentColor)?bv(this.props.currentColor):""});get colorPickerStyle(){return void 0!==this.props.maxHeight&&this.props.maxHeight<=0?Ey({display:"none"}):""}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"bottom-left",verticalOffset:0}}get gradientHueStyle(){return Ey({background:`hsl(${this.state.currentHslaColor?.h||0} 100% 50%)`})}get sliderStyle(){const e=this.state.currentHslaColor?.h||0;return Ey({"margin-left":`${ue(Math.round(e/360*nM),1,nM)-9}px`})}get pointerStyle(){const{s:e,l:t}=this.state.currentHslaColor||{s:0,l:0};return Ey({left:`${-8+Math.round(nM*ue(e/100,0,1))}px`,top:`${-8+Math.round(186*ue(1-2*t/(200-e),0,1))}px`,background:Tv(this.state.currentHslaColor)})}get colorPreviewStyle(){return Ey({"background-color":Tv(this.state.currentHslaColor)})}get checkmarkColor(){return nC(this.props.currentColor)}get isHexColorInputValid(){return!this.state.customHexColor||Sv(this.state.customHexColor)}setCustomGradient({x:e,y:t}){const s=ue(e,0,nM),o=ue(t,0,186),i=s/nM,n=100*i,r=100*(1-o/186)*(1-.5*i);this.updateColor({s:n,l:r})}setCustomHue(e){const t=Math.round(ue(360*e/nM,0,359));this.updateColor({h:t})}updateColor(e){this.state.currentHslaColor={...this.state.currentHslaColor,...e},this.state.customHexColor=Tv(this.state.currentHslaColor)}onColorClick(e){e&&this.props.onColorPicked(bv(e))}resetColor(){this.props.onColorPicked("")}toggleColorPicker(){this.state.showGradient=!this.state.showGradient}dragGradientPointer(e){const t={x:e.offsetX,y:e.offsetY};this.setCustomGradient(t);const s=e.clientX,o=e.clientY;iM(e=>{const i=e.clientX,n=e.clientY,r={x:t.x+(i-s),y:t.y+(n-o)};this.setCustomGradient(r)},()=>{})}dragHuePointer(e){const t=e.offsetX,s=e.clientX;this.setCustomHue(t);iM(e=>{const o=e.clientX,i=t+(o-s);this.setCustomHue(i)},()=>{})}setHexColor(e){const t=e.target.value.replace("##","#").slice(0,7);this.state.customHexColor=t,Sv(t)&&(this.state.currentHslaColor={...Av(t),a:1})}addCustomColor(e){(function(e){try{return Tv(e),!0}catch(e){return!1}})(this.state.currentHslaColor)&&Sv(this.state.customHexColor)&&this.props.onColorPicked(bv(this.state.customHexColor))}isSameColor(e,t){return function(e,t,s=0){if(!Sv(e)||!Sv(t))return!1;const o=Ev(e),i=Ev(t);return o.a===i.a&&Math.sqrt(((o.r-i.r)/255)**2+((o.g-i.g)/255)**2+((o.b-i.b)/255)**2)<=s}(e,t)}}class aM extends t.Component{static template="o_spreadsheet.Section";static props={class:{type:String,optional:!0},title:{type:String,optional:!0},slots:Object}}class lM extends t.Component{static template="o-spreadsheet.RoundColorPicker";static components={Section:aM,ColorPicker:rM};static props={currentColor:{type:String,optional:!0},title:{type:String,optional:!0},onColorPicked:Function,disableNoColor:{type:Boolean,optional:!0}};colorPickerButtonRef=t.useRef("colorPickerButton");state;setup(){this.state=t.useState({pickerOpened:!1}),t.useExternalListener(window,"click",this.closePicker)}closePicker(){this.state.pickerOpened=!1}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.props.onColorPicked(e),this.state.pickerOpened=!1}get colorPickerAnchorRect(){return Fy(this.colorPickerButtonRef.el)}get buttonStyle(){return Ey({background:this.props.currentColor})}}function cM(){let e;const s=document.body.style.cursor;let o=[];const i=()=>{e=void 0,document.body.style.cursor=s,o.forEach(e=>e()),o=[]};t.onWillUnmount(()=>{i()});const n=t.useState({itemsStyle:{},draggedItemId:void 0,start:(t,r)=>{n.cancel=()=>{n.draggedItemId=void 0,n.itemsStyle={},document.body.style.cursor=s,r.onCancel?.(),i()};document.body.style.cursor="move",n.draggedItemId=r.draggedItemId;const a="horizontal"===t?new gM(r.scrollableContainerEl):new uM(r.scrollableContainerEl);e=new hM({...r,container:a,onChange:()=>{document.body.style.cursor="move",e&&(Object.assign(n.itemsStyle,e.getItemStyles()),r.onChange?.())},onDragEnd:(e,t)=>{n.draggedItemId=void 0,n.itemsStyle={},document.body.style.cursor=s,r.onDragEnd?.(e,t),i()},onCancel:n.cancel});const l=iM(e.onMouseMove.bind(e),e.onMouseUp.bind(e));o.push(l);const c=e.onScroll.bind(e);r.scrollableContainerEl.addEventListener("scroll",c),o.push(()=>r.scrollableContainerEl.removeEventListener("scroll",c)),o.push(e.destroy.bind(e))},cancel:()=>{}});return n}class hM{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(){const e={};for(const t of this.items)e[t.id]=this.getItemStyle(t.id);return e}getItemStyle(e){const t=this.container.cssPositionProperty,s={position:"relative"};return s[t]=(this.getItemsPositions()[e]||0)+"px",s.transition=`${t} 0.5s`,s["pointer-events"]="none",this.draggedItemId===e&&(s.transition=`${t} 0s`,s["z-index"]="1000"),Ey(s)}onScroll(){this.moveDraggedItemToPosition(this.currentMousePosition+this.scrollOffset)}onMouseMove(e){if(e.button>1)return void this.onCancel();const t=this.container.getMousePosition(e);this.currentMousePosition=t,t<this.container.start||t>this.container.end?this.startEdgeScroll(t<this.container.start?-1:1):(this.stopEdgeScroll(),this.moveDraggedItemToPosition(t+this.scrollOffset))}moveDraggedItemToPosition(e){const t=this.getHoveredItemIndex(e,this.items),s=this.items.findIndex(e=>e.id===this.draggedItemId),o=this.items[s];if(this.deadZone&&this.isInZone(e,this.deadZone))return void this.onChange(this.getItemsPositions());if(this.isInZone(e,{start:o.position,end:o.position+o.size})&&(this.deadZone=void 0),s===t)return void this.onChange(this.getItemsPositions());const i=Math.min(s,t),n=Math.max(s,t),r=Math.sign(t-s);let a=0;for(let e=i;e<=n;e++)e!==s&&(this.items[e].position-=r*o.size,a+=this.items[e].size);o.position+=r*a,this.items.sort((e,t)=>e.position-t.position),this.deadZone=r>0?{start:e,end:o.position}:{start:o.position+o.size,end:e},this.onChange(this.getItemsPositions())}onMouseUp(e){0!==e.button&&this.onCancel(),e.stopPropagation(),e.preventDefault();const t=this.items.findIndex(e=>e.id===this.draggedItemId);return this.onDragEnd(this.draggedItemId,t),this.stopEdgeScroll(),!1}startEdgeScroll(e){this.edgeScrollIntervalId||(this.edgeScrollIntervalId=window.setInterval(()=>{const t=3*e;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(){const e={};for(const t of this.items){if(t.id!==this.draggedItemId){e[t.id]=t.position-t.positionAtStart;continue}let s=this.currentMousePosition-this.initialMousePosition+this.scrollOffset;s=Math.max(this.minPosition-t.positionAtStart,s),s=Math.min(this.maxPosition-t.positionAtStart-t.size,s),e[t.id]=s}return e}isInZone(e,t){return e>=t.start&&e<=t.end}get scrollOffset(){return this.container.scroll-this.initialScroll}destroy(){this.stopEdgeScroll()}}class dM{el;constructor(e){this.el=e}get containerRect(){return this.el.getBoundingClientRect()}}class uM extends dM{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}}class gM extends dM{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}}class pM{mutators=["focus","unfocus"];focusedElement=null;focus(e){this.focusedElement=e}unfocus(e){this.focusedElement&&this.focusedElement===e&&(this.focusedElement=null)}}class mM extends hv{initialRanges;inputHasSingleRange;colors;disabledRanges;mutators=["resetWithRanges","focusById","unfocus","addEmptyRange","removeRange","changeRange","reset","confirm","updateColors","updateDisabledRanges"];ranges=[];focusedRangeIndex=null;inputSheetId;focusStore=this.get(pM);highlightStore=this.get(ZP);constructor(e,t=[],s=!1,o=[],i=[]){if(super(e),this.initialRanges=t,this.inputHasSingleRange=s,this.colors=o,this.disabledRanges=i,s&&t.length>1)throw new 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(null===this.focusedRangeIndex)return;const t=this.inputSheetId,s=this.getters.getActiveSheetId(),o=e.options.unbounded?this.getters.getUnboundedZone(s,e.anchor.zone):e.anchor.zone,i=this.getters.getRangeFromZone(s,o);if("newAnchor"===e.mode&&!this.inputHasSingleRange&&""!==this.ranges[this.focusedRangeIndex].xc.trim()){const e=this.getters.getSelectionRangeString(i,t);this.insertNewRange(this.ranges.length,[e]),this.focusLast()}else{let e=i.parts;const s=this.ranges[this.focusedRangeIndex].xc.trim();s&&(e=this.getters.getRangeFromSheetXC(t,s).parts);const o={...i,parts:e},n=this.getters.getSelectionRangeString(o,t);this.setRange(this.focusedRangeIndex,[n])}}handle(e){switch(e.type){case"ACTIVATE_SHEET":if(e.sheetIdFrom!==e.sheetIdTo){const{col:t,row:s}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),o=this.getters.expandZone(e.sheetIdTo,Zt({col:t,row:s}));this.model.selection.resetAnchor(this,{cell:{col:t,row:s},zone:o})}break;case"START_CHANGE_HIGHLIGHT":const t=this.getters.getActiveSheetId(),s=this.getters.expandZone(t,e.zone),o=this.ranges.findIndex(e=>{const{xc:o,sheetName:i}=tr(e.xc),n=i||this.getters.getSheetName(this.inputSheetId);if(this.getters.getSheetName(t)!==n)return!1;const r=this.getters.getRangeFromSheetXC(t,o);return Mt(this.getters.expandZone(t,r.zone),s)});if(-1!==o){this.focus(o);const{left:e,top:t}=s;this.model.selection.resetAnchor(this,{cell:{col:e,row:t},zone:s})}}}changeRange(e,t){if(this.inputHasSingleRange&&t.split(",").length>1)return;const s=this.getIndex(e);if(null!==s&&this.focusedRangeIndex!==s&&this.focus(s),null!==s){const e=t.replace(/^,+/,"").split(",").map(e=>e.trim());this.setRange(s,e),this.captureSelection()}}addEmptyRange(){this.inputHasSingleRange&&1===this.ranges.length||(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}removeRange(e){if(1===this.ranges.length)return;const t=this.getIndex(e);null!==t&&this.removeRangeByIndex(t)}updateColors(e){this.colors=e;const t=new Gv(this.ranges.length,this.colors);this.ranges=this.ranges.map(e=>({...e,color:t.next()}))}updateDisabledRanges(e){this.disabledRanges=e}confirm(){for(const e of this.selectionInputs)""===e.xc&&this.removeRange(e.id);const 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&&null!==this.focusedRangeIndex&&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(){const 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(null===this.focusedRangeIndex)return;const e=this.ranges[this.focusedRangeIndex],t=this.getters.getActiveSheetId(),s=this.getters.getRangeFromSheetXC(t,e?.xc||"A1").zone;this.model.selection.capture(this,{cell:{col:s.left,row:s.top},zone:s},{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),0===this.ranges.length&&(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){const s=Math.max(0,...this.ranges.map(e=>Number(e.id))),o=new Gv(this.ranges.length,this.colors);for(let t=0;t<e;t++)o.next();this.ranges.splice(e,0,...t.map((e,t)=>({xc:e,id:s+t+1,color:o.next()})))}setRange(e,t){const[,...s]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,s),s.length&&this.focus(e+s.length)}removeRangeByIndex(e){this.ranges.splice(e,1),null!==this.focusedRangeIndex&&this.focusLast()}inputToHighlights({xc:e,color:t}){const s=this.cleanInputs([e]).filter(e=>this.getters.isRangeValid(e)).filter(e=>this.shouldBeHighlighted(this.inputSheetId,e));return s.map(e=>{const{sheetName:s}=tr(e),o=s&&this.getters.getSheetIdByName(s)||this.inputSheetId;return{range:this.getters.getRangeFromSheetXC(o,e),color:t,interactive:!0}})}cleanInputs(e){return e.map(e=>e.split(",")).flat().map(e=>e.trim()).filter(e=>""!==e)}shouldBeHighlighted(e,t){const{sheetName:s}=tr(t),o=this.getters.getSheetIdByName(s),i=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(o===i||void 0===o&&i===e)}getIndex(e){const t=this.ranges.findIndex(t=>t.id===e);return t>=0?t:null}}class fM extends t.Component{static template="o-spreadsheet-SelectionInput";static props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},required:{type:Boolean,optional:!0},isInvalid:{type:Boolean,optional:!0},class:{type:String,optional:!0},onSelectionChanged:{type:Function,optional:!0},onSelectionConfirmed:{type:Function,optional:!0},onSelectionReordered:{type:Function,optional:!0},onSelectionRemoved:{type:Function,optional:!0},colors:{type:Array,optional:!0,default:[]},disabledRanges:{type:Array,optional:!0,default:[]},disabledRangeTitle:{type:String,optional:!0}};state=t.useState({isMissing:!1,mode:"select-range"});dragAndDrop=cM();focusedInput=t.useRef("focusedInput");selectionRef=t.useRef("o-selection");store;get ranges(){return this.store.selectionInputs}get canAddRange(){return!this.props.hasSingleRange}get isInvalid(){return this.props.isInvalid||this.state.isMissing}get isConfirmable(){return this.store.isConfirmable}get isResettable(){return this.store.isResettable}get hasDisabledRanges(){return this.store.disabledRanges.some(Boolean)}setup(){t.useEffect(()=>this.focusedInput.el?.focus(),()=>[this.focusedInput.el]),this.store=tv(mM,this.props.ranges,this.props.hasSingleRange||!1,this.props.colors,this.props.disabledRanges),t.onWillUpdateProps(e=>{e.ranges.join()!==this.store.selectionInputValues.join()&&this.triggerChange(),e.ranges.join()!==this.props.ranges.join()&&e.ranges.join()!==this.store.selectionInputValues.join()&&this.store.resetWithRanges(e.ranges),e.colors?.join()!==this.props.colors?.join()&&e.colors?.join()!==this.store.colors.join()&&this.store.updateColors(e.colors||[]),Me(e.disabledRanges,this.props.disabledRanges)||Me(e.disabledRanges,this.store.disabledRanges)||this.store.updateDisabledRanges(e.disabledRanges||[])})}startDragAndDrop(e,t){if(0!==t.button||"SELECT"===t.target.tagName)return;const s=this.getRangeElementsRects(),o=this.ranges.map(e=>e.id),i=o.map((e,t)=>({id:e.toString(),size:s[t].height,position:s[t].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.toString(),initialMousePosition:t.clientY,items:i,scrollableContainerEl:this.selectionRef.el,onDragEnd:(t,s)=>{const i=o.findIndex(t=>t===e);if(i===s)return;const n=ge(0,o.length);n.splice(i,1),n.splice(s,0,i),this.props.onSelectionReordered?.(n),this.props.onSelectionConfirmed?.(),this.store.confirm()}})}getRangeElementsRects(){return Array.from(this.selectionRef.el.children).map(e=>e.getBoundingClientRect())}getColor(e){return e.color?Ey({color:e.color}):""}triggerChange(){const e=this.store.selectionInputValues;this.props.onSelectionChanged?.(e)}onKeydown(e){if("F2"===e.key)e.preventDefault(),e.stopPropagation(),this.state.mode="select-range"===this.state.mode?"text-edit":"select-range";else if(e.key.startsWith("Arrow"))e.stopPropagation(),"select-range"===this.state.mode&&(e.preventDefault(),PP(e,this.env.model.selection));else if("Enter"===e.key){e.target.blur(),this.isConfirmable&&this.confirm()}}extractRanges(e){return this.props.hasSingleRange?e.split(",")[0]:e}focus(e){this.state.isMissing=!1,this.state.mode="select-range",this.store.focusById(e)}addEmptyInput(){this.store.addEmptyRange()}removeInput(e){const t=this.store.selectionInputs.findIndex(t=>t.id===e);this.ranges.find(t=>t.id===e)?.xc&&(this.props.onSelectionRemoved?.(t),this.props.onSelectionConfirmed?.()),this.store.removeRange(e)}onInputChanged(e,t){const s=t.target,o=this.extractRanges(s.value);this.store.changeRange(e,o),this.triggerChange()}reset(){this.store.reset(),this.triggerChange()}confirm(){this.store.confirm();const e=this.store.selectionInputs.some(e=>this.env.model.getters.isRangeValid(e.xc));this.props.required&&!e&&(this.state.isMissing=!0),this.props.onSelectionChanged?.(this.store.selectionInputValues),this.props.onSelectionConfirmed?.()}}const vM={list:10,text:20,date:30,number:40,misc:50},bM=new Og;function SM(e,t){const s=bM.getAll().filter(e=>t.has(e.type)).sort((e,t)=>e.category===t.category?e.sequence-t.sequence:vM[e.category]-vM[t.category]);return qf(s.map((t,o)=>({name:QT.get(t.type).name,id:t.type,separator:t.category!==s[o+1]?.category,execute:()=>e(t.type)})))}bM.add("containsText",{type:"containsText",component:oM,category:"text",sequence:10}),bM.add("notContainsText",{type:"notContainsText",component:oM,category:"text",sequence:20}),bM.add("beginsWithText",{type:"beginsWithText",component:oM,category:"text",sequence:25}),bM.add("endsWithText",{type:"endsWithText",component:oM,category:"text",sequence:26}),bM.add("isEqualText",{type:"isEqualText",component:oM,category:"text",sequence:30}),bM.add("isEmail",{type:"isEmail",component:void 0,category:"text",sequence:40}),bM.add("isLink",{type:"isLink",component:void 0,category:"text",sequence:50}),bM.add("dateIs",{type:"dateIs",component:tM,category:"date",sequence:20}),bM.add("dateIsBefore",{type:"dateIsBefore",component:tM,category:"date",sequence:30}),bM.add("dateIsOnOrBefore",{type:"dateIsOnOrBefore",component:tM,category:"date",sequence:40}),bM.add("dateIsAfter",{type:"dateIsAfter",component:tM,category:"date",sequence:50}),bM.add("dateIsOnOrAfter",{type:"dateIsOnOrAfter",component:tM,category:"date",sequence:60}),bM.add("dateIsBetween",{type:"dateIsBetween",component:sM,category:"date",sequence:70}),bM.add("dateIsNotBetween",{type:"dateIsNotBetween",component:sM,category:"date",sequence:80}),bM.add("dateIsValid",{type:"dateIsValid",component:void 0,category:"date",sequence:10}),bM.add("isEqual",{type:"isEqual",component:oM,category:"number",sequence:10}),bM.add("isNotEqual",{type:"isNotEqual",component:oM,category:"number",sequence:20}),bM.add("isGreaterThan",{type:"isGreaterThan",component:oM,category:"number",sequence:50}),bM.add("isGreaterOrEqualTo",{type:"isGreaterOrEqualTo",component:oM,category:"number",sequence:60}),bM.add("isLessThan",{type:"isLessThan",component:oM,category:"number",sequence:30}),bM.add("isLessOrEqualTo",{type:"isLessOrEqualTo",component:oM,category:"number",sequence:40}),bM.add("isBetween",{type:"isBetween",component:sM,category:"number",sequence:70}),bM.add("isNotBetween",{type:"isNotBetween",component:sM,category:"number",sequence:80}),bM.add("isBoolean",{type:"isBoolean",component:void 0,category:"misc",sequence:10}),bM.add("isValueInList",{type:"isValueInList",component:class extends _P{static template="o-spreadsheet-ListCriterionForm";static components={CriterionInput:QP,RoundColorPicker:lM};state=t.useState({numberOfValues:Math.max(this.props.criterion.values.length,2)});setup(){super.setup();const e=e=>{void 0===e.criterion.displayStyle&&this.updateCriterion({displayStyle:"chip"})};t.onWillUpdateProps(e),t.onWillStart(()=>e(this.props))}onValueChanged(e,t){const s=[...this.displayedValues];s[t]=e,this.updateCriterion({values:s})}onColorChanged(e,t){const s={...this.props.criterion.colors};s[t]=e||void 0,this.updateCriterion({colors:s})}onAddAnotherValue(){this.state.numberOfValues++}removeItem(e){const t=[...this.displayedValues];t.splice(e,1),this.state.numberOfValues--,this.updateCriterion({values:t})}onChangedDisplayStyle(e){const t=e.target.value;this.updateCriterion({displayStyle:t})}onKeyDown(e,t){"Enter"!==e.key&&"Tab"!==e.key||t!==this.state.numberOfValues-1?"Enter"===e.key&&(this.state.focusedValueIndex=t+1):(this.onAddAnotherValue(),this.state.focusedValueIndex=t+1,e.preventDefault())}onBlurInput(){this.state.focusedValueIndex=void 0}get displayedValues(){const e=[];for(let t=0;t<this.state.numberOfValues;t++)e.push(this.props.criterion.values[t]||"");return e}},category:"list",sequence:10}),bM.add("isValueInRange",{type:"isValueInRange",component:class extends _P{static template="o-spreadsheet-ValueInRangeCriterionForm";static components={RoundColorPicker:lM,SelectionInput:fM};setup(){super.setup();const e=e=>{void 0===e.criterion.displayStyle&&this.updateCriterion({displayStyle:"chip"})};t.onWillUpdateProps(e),t.onWillStart(()=>e(this.props))}onRangeChanged(e){this.updateCriterion({values:[e]})}onChangedDisplayStyle(e){const t=e.target.value;this.updateCriterion({displayStyle:t})}onColorChanged(e,t){const s={...this.props.criterion.colors};s[t]=e||void 0,this.updateCriterion({colors:s})}get values(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getDataValidationRangeValues(e,this.props.criterion);return new Set(t)}},category:"list",sequence:20}),bM.add("customFormula",{type:"customFormula",component:oM,category:"misc",sequence:20}),bM.add("isEmpty",{type:"isEmpty",component:void 0,category:"misc",sequence:5}),bM.add("isNotEmpty",{type:"isNotEmpty",component:void 0,category:"misc",sequence:6});class CM extends t.Component{static template="o-spreadsheet-SelectMenu";static props={menuItems:Array,selectedValue:String,class:{type:String,optional:!0}};static components={MenuPopover:PF};menuId=(new lr).uuidv4();selectRef=t.useRef("select");state=t.useState({isMenuOpen:!1});onClick(e){e.closedMenuId!==this.menuId&&(this.state.isMenuOpen=!this.state.isMenuOpen)}onMenuClosed(){this.state.isMenuOpen=!1}get menuAnchorRect(){return Oy(this.selectRef)}}class yM extends t.Component{static template="o-spreadsheet-FilterMenuCriterion";static props={filterPosition:Object,onCriterionChanged:Function,criterionOperators:Array};static components={SelectMenu:CM};state;setup(){t.onWillUpdateProps(e=>{Me(e.filterPosition,this.props.filterPosition)||(this.state.criterion=this.getFilterCriterionValue(e.filterPosition))}),this.state=t.useState({criterion:this.getFilterCriterionValue(this.props.filterPosition)})}getFilterCriterionValue(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getFilterCriterionValue({sheetId:t,...e});return"criterion"===s?.filterType?ae(s):{filterType:"criterion",type:"none",values:[]}}get criterionMenuItems(){return[jf({name:fs("None"),id:"none",separator:!0,execute:()=>this.onCriterionTypeChange("none")}),...SM(e=>this.onCriterionTypeChange(e),new Set(this.props.criterionOperators))]}get selectedCriterionName(){return"none"===this.state.criterion.type?fs("None"):QT.get(this.state.criterion.type).name}get criterionComponent(){return"none"===this.state.criterion.type?void 0:bM.get(this.state.criterion.type).component}onCriterionChanged(e){this.state.criterion.values=e.values,this.state.criterion.dateValue=e.dateValue,this.props.onCriterionChanged(this.state.criterion)}onCriterionTypeChange(e){this.state.criterion.type=e,this.props.onCriterionChanged(this.state.criterion)}}class IM extends t.Component{static template="o-spreadsheet.Checkbox";static props={label:{type:String,optional:!0},value:{type:Boolean,optional:!0},className:{type:String,optional:!0},name:{type:String,optional:!0},title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},onChange:Function};static defaultProps={value:!1};onChange(e){const t=e.target.checked;this.props.onChange(t)}}class wM extends t.Component{static template="o-spreadsheet-FilterMenuValueItem";static components={Checkbox:IM};static props={value:String,isChecked:Boolean,isSelected:Boolean,onMouseMove:Function,onClick:Function,scrolledTo:{type:String,optional:!0}};itemRef=t.useRef("menuValueItem");setup(){t.onWillPatch(()=>{this.props.scrolledTo&&this.scrollListToSelectedValue()})}scrollListToSelectedValue(){this.itemRef.el&&this.itemRef.el.scrollIntoView?.({block:"bottom"===this.props.scrolledTo?"end":"start"})}}class EM extends t.Component{static template="o-spreadsheet-FilterMenuValueList";static props={filterPosition:Object,onUpdateHiddenValues:Function};static components={FilterMenuValueItem:wM};state=t.useState({values:[],displayedValues:[],textFilter:"",selectedValue:void 0,numberOfDisplayedValues:50,hasMoreValues:!1});searchBar=t.useRef("filterMenuSearchBar");setup(){t.onWillUpdateProps(e=>{Me(e.filterPosition,this.props.filterPosition)||(this.state.values=this.getFilterHiddenValues(e.filterPosition),this.computeDisplayedValues())}),this.state.values=this.getFilterHiddenValues(this.props.filterPosition),this.computeDisplayedValues()}getFilterHiddenValues(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getFilter({sheetId:t,...e});if(!s)return[];const o=this.env.model.getters.getFilterValue({sheetId:t,...e});let i=(s.filteredRange?Bt(s.filteredRange.zone):[]).map(e=>({position:e,cellValue:this.env.model.getters.getEvaluatedCell({sheetId:t,...e}).formattedValue}));"criterion"!==o?.filterType&&(i=i.filter(e=>!this.env.model.getters.isRowHidden(t,e.position.row)));const n=i.map(e=>e.cellValue),r="values"===o?.filterType?o.hiddenValues:[],a=new Set(r.map(Xb)),l=new Set,c=[],h=e=>{const t=Xb(e);l.has(t)||(c.push({string:e||"",checked:"criterion"!==o?.filterType&&!a.has(t),normalizedValue:t}),l.add(t))};return n.forEach(h),r.forEach(h),c.sort((e,t)=>e.normalizedValue.localeCompare(t.normalizedValue,void 0,{numeric:!0,sensitivity:"base"}))}checkValue(e){this.state.selectedValue=e.string,e.checked=!e.checked,this.searchBar.el?.focus(),this.updateHiddenValues()}onMouseMove(e){this.state.selectedValue=e.string}selectAll(){this.state.displayedValues.forEach(e=>e.checked=!0),this.props.onUpdateHiddenValues([])}clearAll(){this.state.displayedValues.forEach(e=>e.checked=!1);const e=this.state.values.map(e=>e.string);this.props.onUpdateHiddenValues(e)}updateHiddenValues(){const e=this.state.values.filter(e=>!e.checked).map(e=>e.string);this.props.onUpdateHiddenValues(e)}updateSearch(e){const t=e.target;this.state.textFilter=t.value,this.state.selectedValue=void 0,this.computeDisplayedValues()}computeDisplayedValues(){const e=this.state.textFilter?tS(this.state.textFilter,this.state.values,e=>e.string):this.state.values;this.state.displayedValues=e.slice(0,this.state.numberOfDisplayedValues),this.state.hasMoreValues=e.length>this.state.numberOfDisplayedValues}loadMoreValues(){this.state.numberOfDisplayedValues+=100,this.computeDisplayedValues()}onKeyDown(e){const t=this.state.displayedValues;if(0===t.length)return;let s;if(void 0!==this.state.selectedValue){const e=t.findIndex(e=>e.string===this.state.selectedValue);s=-1===e?void 0:e}switch(e.key){case"ArrowDown":s=void 0===s?0:Math.min(s+1,t.length-1),e.preventDefault(),e.stopPropagation();break;case"ArrowUp":s=void 0===s?t.length-1:Math.max(s-1,0),e.preventDefault(),e.stopPropagation();break;case"Enter":void 0!==s&&this.checkValue(t[s]),e.stopPropagation(),e.preventDefault()}this.state.selectedValue=void 0!==s?t[s].string:void 0,"ArrowUp"!==e.key&&"ArrowDown"!==e.key||this.scrollListToSelectedValue(e.key)}clearScrolledToValue(){this.state.values.forEach(e=>e.scrolledTo=void 0)}scrollListToSelectedValue(e){this.clearScrolledToValue();const t=this.state.values.find(e=>e.string===this.state.selectedValue);t&&(t.scrolledTo="ArrowUp"===e?"top":"bottom")}}class RM extends t.Component{static template="o-spreadsheet-FilterMenu";static props={filterPosition:Object,onClosed:{type:Function,optional:!0}};static components={FilterMenuValueList:EM,SidePanelCollapsible:DP,FilterMenuCriterion:yM};criterionCategory="text";updatedCriterionValue;setup(){t.onWillUpdateProps(e=>{Me(e.filterPosition,this.props.filterPosition)||(this.updatedCriterionValue=void 0,this.criterionCategory=this.getCriterionCategory(e.filterPosition))}),this.criterionCategory=this.getCriterionCategory(this.props.filterPosition)}get isSortable(){if(!this.table)return!1;const e=this.env.model.getters.getCoreTableMatchingTopLeft(this.table.range.sheetId,this.table.range.zone);return!this.env.model.getters.isReadonly()&&"dynamic"!==e?.type}get table(){const e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition;return this.env.model.getters.getTable({sheetId:e,...t})}get filterValueType(){const e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition,s=this.env.model.getters.getFilterValue({sheetId:e,...t});return s?.filterType}getCriterionCategory(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getFilter({sheetId:t,...e});if(!s||!s.filteredRange)return"text";const o={text:0,number:0,date:0},i=s.filteredRange.zone;for(let s=i.top;s<=i.bottom&&!(s>100);s++){const i=this.env.model.getters.getEvaluatedCell({sheetId:t,row:s,col:e.col});i.type===_d.text||i.type===_d.boolean?o.text++:i.type===_d.number&&(i.format&&wn(i.format)?o.date++:o.number++)}const n=Math.max(o.text,o.number,o.date);return Object.keys(o).find(e=>o[e]===n)||"text"}onUpdateHiddenValues(e){this.updatedCriterionValue={filterType:"values",hiddenValues:e}}onCriterionChanged(e){this.updatedCriterionValue=e}confirm(){if(!this.updatedCriterionValue)return void this.props.onClosed?.();const e=this.props.filterPosition;this.env.model.dispatch("UPDATE_FILTER",{...e,sheetId:this.env.model.getters.getActiveSheetId(),value:this.updatedCriterionValue}),this.props.onClosed?.()}get criterionOperators(){return"date"===this.criterionCategory?CI:"number"===this.criterionCategory?SI:bI}cancel(){this.props.onClosed?.()}sortFilterZone(e){const t=this.props.filterPosition,s=this.table,o=s?.range.zone;if(!t||!o||o.top===o.bottom)return;const i=this.env.model.getters.getActiveSheetId(),n={...o,top:o.top+1},r={col:t.col,row:n.top};TP(this.env,i,r,n,e,{emptyCellAsZero:!0,sortHeaders:!0}),this.props.onClosed?.()}}const xM={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:RM,cellCorner:"bottom-left"})};class TM extends t.Component{static template="o-spreadsheet-LinkDisplay";static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};cellPopovers;setup(){this.cellPopovers=ev(wP)}get cell(){const{col:e,row:t}=this.props.cellPosition,s=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getEvaluatedCell({sheetId:s,col:e,row:t})}get link(){if(this.cell.link)return this.cell.link;const{col:e,row:t}=this.props.cellPosition;throw new Error(`LinkDisplay Component can only be used with link cells. ${mt(e,t)} is not a link.`)}getUrlRepresentation(e){return Gf(e,this.env.model.getters)}openLink(e){Wf(this.link,this.env,Hy(e))}edit(){const{col:e,row:t}=this.props.cellPosition;this.env.model.selection.selectCell(e,t),this.cellPopovers.open({col:e,row:t},"LinkEditor")}unlink(){const e=this.env.model.getters.getActiveSheetId(),{col:t,row:s}=this.props.cellPosition,o=this.env.model.getters.getCellComputedStyle({sheetId:e,col:t,row:s}),i=o?.textColor===d?void 0:o?.textColor;this.env.model.dispatch("UPDATE_CELL",{col:t,row:s,sheetId:e,content:this.link.label,style:{...o,textColor:i,underline:void 0}})}}const AM={onHover:(e,t)=>{const s=t.getEvaluatedCell(e);return!t.isDashboard()&&s.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:TM,props:{cellPosition:e},cellCorner:"bottom-left"}:{isOpen:!1}}},DM={name:fs("Link sheet"),children:[e=>e.model.getters.getSheetIds().map(t=>e.model.getters.getSheet(t)).map(e=>({id:e.id,name:e.name,execute:()=>ye(e.name,Re(e.id))}))]},_M={name:fs("Delete"),isVisible:e=>e.model.getters.getVisibleSheetIds().length>1,execute:e=>e.askConfirmation(fs("Are you sure you want to delete this sheet?"),()=>{e.model.dispatch("DELETE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName()})}),icon:"o-spreadsheet-Icon.TRASH"},OM={name:fs("Duplicate"),execute:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSheetName(t),o=e.model.uuidGenerator.smallUuid(),i=e.model.getters.getDuplicateSheetName(s);e.model.dispatch("DUPLICATE_SHEET",{sheetId:t,sheetIdTo:o,sheetNameTo:i}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})},icon:"o-spreadsheet-Icon.COPY"},FM=e=>({name:fs("Rename"),execute:e.renameSheetCallback,icon:"o-spreadsheet-Icon.RENAME_SHEET"}),PM=e=>({name:fs("Change color"),execute:e.openSheetColorPickerCallback,icon:"o-spreadsheet-Icon.PAINT_FORMAT"}),MM={name:fs("Move right"),isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getVisibleSheetIds();return s.indexOf(t)!==s.length-1},execute:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),delta:1}),icon:"o-spreadsheet-Icon.MOVE_SHEET_RIGHT"},NM={name:fs("Move left"),isVisible:e=>{const t=e.model.getters.getActiveSheetId();return e.model.getters.getVisibleSheetIds()[0]!==t},execute:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),delta:-1}),icon:"o-spreadsheet-Icon.MOVE_SHEET_LEFT"},LM={name:fs("Hide sheet"),isVisible:e=>1!==e.model.getters.getVisibleSheetIds().length,execute:e=>e.model.dispatch("HIDE_SHEET",{sheetId:e.model.getters.getActiveSheetId()}),icon:"o-spreadsheet-Icon.HIDE_SHEET"};class kM extends Og{replace(e,t){return void 0===t.id&&(t.id=e),this.content[e]=t,this}addChild(e,t,s){return this._replaceChild(e,t,s,{force:!1})}replaceChild(e,t,s){return this._replaceChild(e,t,s,{force:!0})}_replaceChild(e,t,s,o={force:!0}){"function"!=typeof s&&void 0===s.id&&(s.id=e);const i=t.splice(0,1)[0];let n=this.content[i];if(!n)throw new Error(`Path ${i+":"+t.join(":")} not found`);for(const e of t){const s=n.children;if(!s||"function"==typeof s)throw new Error(`${e} is either not a node or it's dynamically computed`);if(n=s.find(t=>t.id===e),!n)throw new Error(`Path ${i+":"+t.join(":")} not found`)}n.children||(n.children=[]);const r=n.children;if(!r||"function"==typeof r)throw new Error(`${t} is either not a node or it's dynamically computed`);if("id"in s){const e=r.findIndex(e=>"id"in e&&e.id===s.id);if(e>-1){if(!o.force)throw new Error(`A child with the id "${s.id}" already exists.`);return n.children.splice(e,1,s),this}}return n.children.push(s),this}getMenuItems(){return qf(this.getAll())}}const VM=new kM;VM.add("sheet",{...DM,sequence:10});class UM extends t.Component{static template="o-spreadsheet-LinkEditor";static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};static components={MenuPopover:PF};menuItems=VM.getMenuItems();link=t.useState(this.defaultState);menu=t.useState({isOpen:!1});linkEditorMenuButtonRef=t.useRef("linkEditorMenuButton");urlInput=t.useRef("urlInput");setup(){t.onMounted(()=>this.urlInput.el?.focus())}get defaultState(){const{col:e,row:t}=this.props.cellPosition,s=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getEvaluatedCell({sheetId:s,col:e,row:t});return o.link?{url:o.link.url,label:o.formattedValue,isUrlEditable:o.link.isUrlEditable}:{label:o.formattedValue,url:"",isUrlEditable:!0}}get menuButtonRect(){return Oy(this.linkEditorMenuButtonRef)}onSpecialLink(e){const{detail:t}=e,s=$f(t);s&&(this.link.url=s.url,this.link.label=s.label,this.link.isUrlEditable=s.isUrlEditable)}getUrlRepresentation(e){return Gf(e,this.env.model.getters)}openMenu(){this.menu.isOpen=!0}removeLink(){this.link.url="",this.link.isUrlEditable=!0}save(){const{col:e,row:t}=this.props.cellPosition,s=this.env.model.getters.getLocale(),o=this.link.label?Kc(this.link.label,s):this.link.url;this.env.model.dispatch("UPDATE_CELL",{col:e,row:t,sheetId:this.env.model.getters.getActiveSheetId(),content:ye(o,this.link.url)}),this.props.onClosed?.()}cancel(){this.props.onClosed?.()}onKeyDown(e){switch(e.key){case"Enter":this.link.url&&this.save(),e.stopPropagation(),e.preventDefault();break;case"Escape":this.cancel(),e.stopPropagation()}}}const HM={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:UM,cellCorner:"bottom-left"})};IP.add("ErrorToolTip",RP).add("LinkCell",AM).add("LinkEditor",HM).add("FilterMenu",xM);const zM=7,BM=6,GM=3,WM=12,$M=100;function qM(e,t){return Tt(e.getUnboundedZone(e.getActiveSheetId(),t))}function ZM(e){if(!e.length)return"empty";const t={number:0,text:0,date:0,percentage:0};let s=0,o="empty";for(const i of e){let e=null;if(i.type===_d.number?e=i.format&&wn(i.format)?"date":i.format?.includes("%")?"percentage":"number":i.type===_d.text&&(e="text"),e){const i=++t[e];i>s&&(s=i,o=e)}}return o}function jM(e,t){const s={number:[],text:[],date:[]};for(const o of function(e){const t=new Map;for(const s of e)for(let e=s.left;e<=s.right;e++){const o=t.get(e);o?(o.top=Math.min(o.top,s.top),o.bottom=Math.max(o.bottom,s.bottom)):t.set(e,{left:e,right:e,top:s.top,bottom:s.bottom})}return Array.from(t.values())}(e)){const e=ZM(t.getEvaluatedCellsInZone(t.getActiveSheetId(),o));if("empty"!==e){s["percentage"===e?"number":e].push({zone:o,type:e})}}return s}function YM(e,t){const s=e.getEvaluatedCellsInZone(e.getActiveSheetId(),t),o=new Set;let i=0,n=0;for(let e=0;e<s.length;e++){const{value:t}=s[e],r=t?.toString().trim();if(!r)continue;o.add(r),i++;const a=Number(t);isNaN(a)||(n+=100*Math.abs(a))}return{uniqueCount:o.size,totalCount:i,percentageSum:n}}function XM(e,t){const s=e.getEvaluatedCell({sheetId:e.getActiveSheetId(),col:t.zone.left,row:t.zone.top});return![_d.number,_d.empty].includes(s.type)}function KM(e,t,s={}){return{type:e,title:{},dataSets:t,legendPosition:"none",...s}}function JM(e,t){const s=jM(e,t),{number:o,text:i,date:n}=s;switch(o.length+i.length+n.length){case 0:return KM("bar",[{dataRange:qM(t,e[0])}],{dataSetsHaveTitle:!1});case 1:const r=o[0]||i[0]||n[0];return 1===Kt(r.zone)?function(e,t){const s=t.getCell({sheetId:t.getActiveSheetId(),col:e.left,row:e.top});return{type:"scorecard",title:{},keyValue:qM(t,e),background:s?.style?.fillColor,baselineMode:B,baselineColorUp:G,baselineColorDown:W}}(r.zone,t):function(e,t){const{type:s,zone:o}=e,i=t.getActiveSheetId(),n=XM(t,e),r=qM(t,o),a=t.getEvaluatedCell({sheetId:i,col:o.left,row:o.top});switch(s){case"percentage":const{percentageSum:e}=YM(t,o);return KM("pie",[{dataRange:r}],{title:n?{text:String(a.value)}:{},dataSetsHaveTitle:n,isDoughnut:e<$M});case"text":const s=t.getEvaluatedCellsInZone(i,o).reduce((e,t)=>t.value===a.value?e+1:e,0),l=null!==a.value&&1===s;return KM("pie",[{dataRange:r}],{title:l?{text:String(a.value)}:{},labelRange:r,dataSetsHaveTitle:l,isDoughnut:!1,aggregated:!0,legendPosition:"top"});case"date":return KM("line",[{dataRange:r}],{labelRange:r,dataSetsHaveTitle:n,cumulative:!1,labelsAsText:!1})}return KM("bar",[{dataRange:r}],{dataSetsHaveTitle:n})}(r,t);case 2:return function(e,t){const{number:s,text:o,date:i}=e;if(2===s.length)return KM("scatter",[{dataRange:qM(t,s[1].zone)}],{labelRange:qM(t,s[0].zone),dataSetsHaveTitle:XM(t,s[1]),labelsAsText:!1});if(1===i.length&&1===s.length)return KM("line",[{dataRange:qM(t,s[0].zone)}],{labelRange:qM(t,i[0].zone),dataSetsHaveTitle:XM(t,s[0]),aggregated:!1,cumulative:!1,labelsAsText:!1});if(1===o.length&&1===s.length){const[e]=o,[i]=s,{uniqueCount:n,totalCount:r}=YM(t,e.zone),a=XM(t,i),l=a?zM:BM,c=qM(t,e.zone),h=qM(t,i.zone);if(n<=l){const{percentageSum:e}=YM(t,i.zone);return KM("pie",[{dataRange:h}],{labelRange:c,dataSetsHaveTitle:a,isDoughnut:"percentage"===i.type&&e<$M,aggregated:!0,legendPosition:"top"})}return n!==r?KM("treemap",[{dataRange:c}],{labelRange:h,dataSetsHaveTitle:a}):KM("bar",[{dataRange:h}],{labelRange:c,dataSetsHaveTitle:a})}const n=o[0]||i[0]||s[0],r=s[0]||o[0]||i[0];return KM("line",[{dataRange:qM(t,r.zone)}],{labelRange:qM(t,n.zone),dataSetsHaveTitle:XM(t,r),cumulative:!1,labelsAsText:!0})}(s,t);default:return function(e,t){const{number:s,text:o,date:i}=e,n=s.some(e=>XM(t,e));if(o.length>=2&&1===s.length){const e=o.sort((e,s)=>YM(t,e.zone).uniqueCount-YM(t,s.zone).uniqueCount).map(({zone:e})=>({dataRange:qM(t,e)}));return KM(o.length>=3?"sunburst":"treemap",e,{labelRange:qM(t,s[0].zone),dataSetsHaveTitle:n})}const r=ft(s.map(e=>e.zone)).map(e=>({dataRange:qM(t,e)}));if(1===i.length&&s.length>1)return KM("line",r,{labelRange:qM(t,i[0].zone),dataSetsHaveTitle:n,cumulative:!1,labelsAsText:!1,legendPosition:"top"});if(1===o.length&&s.length>=2){const[e]=o,i=t.getEvaluatedCell({sheetId:t.getActiveSheetId(),row:e.zone.top,col:e.zone.left}),{uniqueCount:a,totalCount:l}=YM(t,e.zone),c=(n&&i.value?a-1:a)*s.length+(n?s.length:0),h=s.reduce((e,s)=>e+YM(t,s.zone).totalCount,0);if(a===l&&a>=GM&&a<=WM&&c===h)return KM("radar",r,{title:n&&i.value?{text:String(i.value)}:{},labelRange:qM(t,e.zone),dataSetsHaveTitle:n,legendPosition:"top"})}const a=o[0]||i[0]||s[0];return KM("bar",r,{labelRange:r.length?qM(t,a.zone):"",dataSetsHaveTitle:n,aggregated:!0,legendPosition:"top"})}(s,t)}}const QM={wrongPasteSelection:fs("This operation is not allowed with multiple selections."),willRemoveExistingMerge:Tg.Errors.WillRemoveExistingMerge,wrongFigurePasteOption:fs("Cannot do a special paste of a figure."),frozenPaneOverlap:fs("This operation is not allowed due to an overlapping frozen pane.")};function eN(e,t){t.isSuccessful||(t.reasons.includes("WrongPasteSelection")?e.raiseError(QM.wrongPasteSelection):t.reasons.includes("WillRemoveExistingMerge")?e.raiseError(QM.willRemoveExistingMerge):t.reasons.includes("WrongFigurePasteOption")?e.raiseError(QM.wrongFigurePasteOption):t.reasons.includes("FrozenPaneOverlap")&&e.raiseError(QM.frozenPaneOverlap))}function tN(e,t,s){const o=e.model.dispatch("PASTE",{target:t,pasteOption:s});eN(e,o)}async function sN(e,t,s,o){let i;try{const n=s;if(s.imageBlob){try{const t=await(e.imageProvider?.uploadFile(s.imageBlob));n.imageData=t}catch(t){const s=fs("An error occurred while uploading the image. %s",t.message);console.error(t),e.raiseError(s)}delete s.imageBlob}i=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,clipboardContent:s,pasteOption:o})}catch(n){const r=s.data;r?.version!==VT()?e.raiseError(fs("An unexpected error occurred while pasting content. This is probably due to a spreadsheet version mismatch.")):(e.raiseError(fs("An unexpected error occurred while pasting content. Additional information can be found in the browser console.")),console.error(n)),i=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,clipboardContent:{text:s.text},pasteOption:o})}eN(e,i)}function oN(e,t,s=hE){let o=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,o);1!==o.length||i||1!==Kt(o[0])||(e.model.selection.selectTableAroundSelection(),o=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,o));const n=o.map(s=>e.model.getters.getRangeDataFromZone(t,s)),r=e.model.dispatch("CREATE_TABLE",{ranges:n,sheetId:t,config:s,tableType:i?"dynamic":"static"});return r.isCancelledBecause("TableOverlap")?e.raiseError(Dg.Errors.TableOverlap):r.isCancelledBecause("NonContinuousTargets")&&e.raiseError(Dg.Errors.NonContinuousTargets),r}function iN(e,t){e.model.dispatch("SET_FORMATTING_WITH_PIVOT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function nN(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const rN=async e=>aN(e,"asValue");async function aN(e,t){const s=await e.clipboard.read();switch(s.status){case"ok":const o=e.model.getters.getClipboardId(),i=w_(s.content),n=i.data?.clipboardId,r=e.model.getters.getSelectedZones();o!==n?await sN(e,r,i,t):tN(e,r,t),e.model.getters.isCutOperation()&&"asValue"!==t&&await e.clipboard.write({[gI.PlainText]:""});break;case"notImplemented":e.raiseError(fs("Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead."));break;case"permissionDenied":e.raiseError(fs("Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings."))}}const lN=(e,t)=>{if("COL"===e&&t.model.getters.getActiveRows().size>0||"ROW"===e&&t.model.getters.getActiveCols().size>0)return!1;const s=t.model.getters.getActiveSheetId(),o=t.model.getters.getElementsFromSelection(e),i=t.model.getters.checkElementsIncludeAllVisibleHeaders(s,e,o),n=t.model.getters.checkElementsIncludeAllNonFrozenHeaders(s,e,o);return!i&&!n},cN=e=>{const t=e.model.getters.getActiveRows();let s,o;if(t.size)s=Je([...t]),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];s=t.top,o=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:"before",base:s,quantity:o,dimension:"ROW"})},hN=e=>{const t=e.model.getters.getActiveCols();let s,o;if(t.size)s=Je([...t]),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];s=t.left,o=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:"before",dimension:"COL",base:s,quantity:o})},dN=e=>{const t=e.model.getters.getActiveCols();let s,o;if(t.size)s=Ke([...t]),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];s=t.right,o=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:"after",dimension:"COL",base:s,quantity:o})};const uN=async e=>{if(e.imageProvider){const t=e.model.getters.getActiveSheetId(),s=e.model.uuidGenerator.smallUuid(),o=await async function(e){try{return await e.imageProvider.requestImage()}catch{return void e.raiseError(fs("An unexpected error occurred during the image transfer"))}}(e);if(!o)return;const i=xy(e.model.getters,o.size),{col:n,row:r,offset:a}=Ry(e.model.getters,i);e.model.dispatch("CREATE_IMAGE",{sheetId:t,figureId:s,col:n,row:r,offset:a,size:i,definition:o})}},gN=e=>{const{col:t,row:s}=e.model.getters.getActivePosition();e.getStore(wP).open({col:t,row:s},"LinkEditor")},pN=e=>{const t=e.model.getters.getFirstTableInSelection();return t?.config.hasFilters||!1},mN=e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSelectedZones();return 1===e.model.getters.getTablesOverlappingZones(t,s).length},fN=e=>Qt(e.model.getters.getSelectedZones()),vN=e=>1===e.model.getters.getSelectedZones().length,bN=(e,t)=>{if(!vN(e))return!1;const s="COL"===t?e.model.getters.getActiveCols():e.model.getters.getActiveRows(),o="COL"===t?e.model.getters.getActiveRows():e.model.getters.getActiveCols(),i=e.model.getters.getActiveSheetId(),n=Mt(e.model.getters.getSelectedZone(),e.model.getters.getSheetZone(i));return We(s)&&(0===o.size||n)},SN={name:e=>pN(e)?fs("Remove selected filters"):fs("Add filters"),isEnabled:e=>fN(e),execute:e=>pN(e)?(e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getFirstTableInSelection();s&&e.model.dispatch("UPDATE_TABLE",{sheetId:t,zone:s.range.zone,config:{hasFilters:!1}})})(e):(e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getFirstTableInSelection();s?e.model.dispatch("UPDATE_TABLE",{sheetId:t,zone:s.range.zone,config:{hasFilters:!0}}):oN(e,t,{...hE,hasFilters:!0,bandedRows:!1,styleId:"TableStyleLight11"})})(e),icon:"o-spreadsheet-Icon.FILTER_ICON_ACTIVE"};function CN(e,t,s){const o=e.model.getters.getActiveSheetId(),i="COL"===t?"FREEZE_COLUMNS":"FREEZE_ROWS";e.model.dispatch(i,{sheetId:o,quantity:s}).isCancelledBecause("MergeOverlap")&&e.raiseError(Eg)}class yN extends hv{mutators=["enable","disable"];isInvalidated=!1;fingerprintColors={[IN]:"#D9D9D9"};isEnabled=!1;colors=new YT;handle(e){switch(vr(e)&&this.isEnabled&&(this.isInvalidated=!0),e.type){case"UNDO":case"REDO":case"ACTIVATE_SHEET":this.isEnabled&&(this.isInvalidated=!0)}}finalize(){this.isInvalidated&&(this.isInvalidated=!1,this.computeFingerprints())}enable(){this.isEnabled=!0,this.computeFingerprints()}disable(){this.isEnabled=!1,this.colors=new YT}computeFingerprints(){this.colors=new YT;const e=new YT,t=new Set,s=this.getters.getActiveSheetId(),o=this.getters.getCells(s);for(const s in o){const i=this.computeFingerprint(o[s]);if(!i)continue;t.add(i);const n=this.getters.getCellPosition(s);e.set(n,i)}this.assignColors(t);for(const[t,s]of e.entries()){const e=this.fingerprintColors[s];this.colors.set(t,e),this.colorSpreadZone(t,e)}}colorSpreadZone(e,t){const s=this.getters.getSpreadZone(e);if(!s)return;const o=e.sheetId;for(let e=s.top;e<=s.bottom;e++)for(let i=s.left;i<=s.right;i++){const s={sheetId:o,col:i,row:e};this.colors.set(s,t)}}assignColors(e){const t=new Wv(e.size);Object.keys(this.fingerprintColors).forEach(()=>t.next());for(const s of e)this.fingerprintColors[s]||(this.fingerprintColors[s]=_v(t.next(),.8))}computeFingerprint(e){const t=this.getters.getCellPosition(e.id);return e.isFormula?this.computeFormulaFingerprint(t,e):this.getLiteralFingerprint(t)}computeFormulaFingerprint(e,t){const s=t.compiledFormula.dependencies,o=e.col,i=e.row,n=this.getters.getSheetIds().indexOf(e.sheetId),r={dx:0,dy:0,dSheet:0};for(const e of s){const t=e.zone,[s,a]=e.parts,l=this.getters.getSheetIds().indexOf(e.sheetId);r.dSheet=l-n;const c=Ib(e)&&!e.unboundedZone.hasHeader,h=yb(e)&&!e.unboundedZone.hasHeader,d=c||s?.colFixed?0:o,u=h||s?.rowFixed?0:i,g=!a&&s?.colFixed||a?.colFixed,p=!a&&s.rowFixed||a?.rowFixed,m=void 0===e.unboundedZone.right||g?0:o,f=void 0===e.unboundedZone.bottom||p?0:i,v=Wt({top:t.top-u,left:t.left-d,right:t.right-m,bottom:t.bottom-f});for(let e=v.top;e<=v.bottom;e++)for(let t=v.left;t<=v.right;t++)r.dx+=t,r.dy+=e}const a=t.compiledFormula.normalizedFormula;return l=r,Object.entries(l).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t).join(",")+a;var l}getLiteralFingerprint(e){switch(this.getters.getEvaluatedCell(e).type){case _d.number:case _d.boolean:return IN;case _d.text:case _d.empty:case _d.error:return}}}const IN="DATA_FINGERPRINT",wN={name:e=>{const t=e.model.getters.getElementsFromSelection("COL"),s=t[0],o=t[t.length-1];return 1===t.length?fs("Hide column %s",it(s).toString()):o-s+1===t.length?fs("Hide columns %s - %s",it(s).toString(),it(o).toString()):fs("Hide columns")},execute:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getElementsFromSelection("COL");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"COL",s)},icon:"o-spreadsheet-Icon.HIDE_COL"},EN={name:fs("Unhide columns"),execute:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("COL").some(e=>t.includes(e))},icon:"o-spreadsheet-Icon.UNHIDE_COL"},RN={name:fs("Unhide all columns"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"COL",elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0,icon:"o-spreadsheet-Icon.UNHIDE_COL"},xN={name:e=>{const t=e.model.getters.getElementsFromSelection("ROW"),s=t[0],o=t[t.length-1];return 1===t.length?fs("Hide row %s",(s+1).toString()):o-s+1===t.length?fs("Hide rows %s - %s",(s+1).toString(),(o+1).toString()):fs("Hide rows")},execute:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getElementsFromSelection("ROW");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"ROW",s)},icon:"o-spreadsheet-Icon.HIDE_ROW"},TN={name:fs("Unhide rows"),execute:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("ROW").some(e=>t.includes(e))},icon:"o-spreadsheet-Icon.UNHIDE_ROW"},AN={name:fs("Unhide all rows"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"ROW",elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0,icon:"o-spreadsheet-Icon.UNHIDE_ROW"},DN={name:fs("Unfreeze"),isVisible:e=>{const{xSplit:t,ySplit:s}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+s>0},execute:e=>e.model.dispatch("UNFREEZE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),icon:"o-spreadsheet-Icon.UNFREEZE"},_N={name:fs("Freeze"),icon:"o-spreadsheet-Icon.FREEZE"},ON={name:fs("No rows"),execute:e=>e.model.dispatch("UNFREEZE_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit},FN={name:fs("1 row"),execute:e=>CN(e,"ROW",1),isReadonlyAllowed:!0},PN={name:fs("2 rows"),execute:e=>CN(e,"ROW",2),isReadonlyAllowed:!0},MN={name:fs("Up to current row"),execute:e=>{const{bottom:t}=e.model.getters.getSelectedZone();CN(e,"ROW",t+1)},isReadonlyAllowed:!0},NN={name:fs("No columns"),execute:e=>e.model.dispatch("UNFREEZE_COLUMNS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit},LN={name:fs("1 column"),execute:e=>CN(e,"COL",1),isReadonlyAllowed:!0},kN={name:fs("2 columns"),execute:e=>CN(e,"COL",2),isReadonlyAllowed:!0},VN={name:fs("Up to current column"),execute:e=>{const{right:t}=e.model.getters.getSelectedZone();CN(e,"COL",t+1)},isReadonlyAllowed:!0},UN={name:fs("Gridlines"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},isActive:e=>{const t=e.model.getters.getActiveSheetId();return e.model.getters.getGridLinesVisibility(t)}},HN={name:fs("Irregularity map"),execute:e=>{const t=e.getStore(yN);t.isEnabled?t.disable():t.enable()},isReadonlyAllowed:!0,icon:"o-spreadsheet-Icon.IRREGULARITY_MAP"},zN={name:fs("Formulas"),isActive:e=>e.model.getters.shouldShowFormulas(),execute:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0},BN={name:e=>{const t=e.model.getters.getSelectedZone();return t.left===t.right?fs("Group column %s",it(t.left)):fs("Group columns %s - %s",it(t.left),it(t.right))},execute:e=>qN(e,"COL"),isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSelectedZone(),o=e.model.getters.getHeaderGroupsInZone(t,"COL",s);return vN(e)&&!o.some(e=>e.start===s.left&&e.end===s.right)},icon:"o-spreadsheet-Icon.GROUP_COLUMNS"},GN={name:e=>{const t=e.model.getters.getSelectedZone();return t.top===t.bottom?fs("Group row %s",String(t.top+1)):fs("Group rows %s - %s",String(t.top+1),String(t.bottom+1))},execute:e=>qN(e,"ROW"),isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSelectedZone(),o=e.model.getters.getHeaderGroupsInZone(t,"ROW",s);return vN(e)&&!o.some(e=>e.start===s.top&&e.end===s.bottom)},icon:"o-spreadsheet-Icon.GROUP_ROWS"},WN={name:e=>{const t=e.model.getters.getSelectedZone();return t.left===t.right?fs("Ungroup column %s",it(t.left)):fs("Ungroup columns %s - %s",it(t.left),it(t.right))},execute:e=>ZN(e,"COL"),icon:"o-spreadsheet-Icon.UNGROUP_COLUMNS"},$N={name:e=>{const t=e.model.getters.getSelectedZone();return t.top===t.bottom?fs("Ungroup row %s",String(t.top+1)):fs("Ungroup rows %s - %s",String(t.top+1),String(t.bottom+1))},execute:e=>ZN(e,"ROW"),icon:"o-spreadsheet-Icon.UNGROUP_ROWS"};function qN(e,t){const s=e.model.getters.getSelectedZone(),o=e.model.getters.getActiveSheetId();e.model.dispatch("GROUP_HEADERS",{sheetId:o,dimension:t,start:"COL"===t?s.left:s.top,end:"COL"===t?s.right:s.bottom})}function ZN(e,t){const s=e.model.getters.getSelectedZone(),o=e.model.getters.getActiveSheetId();e.model.dispatch("UNGROUP_HEADERS",{sheetId:o,dimension:t,start:"COL"===t?s.left:s.top,end:"COL"===t?s.right:s.bottom})}function jN(e,t){const s=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return 1===o.length&&e.model.getters.getHeaderGroupsInZone(s,t,o[0]).length>0}function YN(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause("WrongCutSelection")&&e.raiseError(fs("This operation is not allowed with multiple selections."))}const XN={MergeIsDestructive:fs("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),MergeInFilter:fs("You can't merge cells inside of an existing filter.")};const KN={name:fs("Undo"),description:"Ctrl+Z",execute:e=>e.model.dispatch("REQUEST_UNDO"),isEnabled:e=>e.model.getters.canUndo(),icon:"o-spreadsheet-Icon.UNDO"},JN={name:fs("Redo"),description:"Ctrl+Y",execute:e=>e.model.dispatch("REQUEST_REDO"),isEnabled:e=>e.model.getters.canRedo(),icon:"o-spreadsheet-Icon.REDO"},QN={name:fs("Copy"),description:"Ctrl+C",isReadonlyAllowed:!0,execute:async e=>{e.model.dispatch("COPY"),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},icon:"o-spreadsheet-Icon.CLIPBOARD"},eL={name:fs("Cut"),description:"Ctrl+X",execute:async e=>{YN(e),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},icon:"o-spreadsheet-Icon.CUT"},tL={name:fs("Paste"),description:"Ctrl+V",execute:async e=>aN(e),icon:"o-spreadsheet-Icon.PASTE"},sL={name:fs("Paste special"),isVisible:e=>!e.model.getters.isCutOperation(),icon:"o-spreadsheet-Icon.PASTE"},oL={name:fs("Paste as value"),description:"Ctrl+Shift+V",execute:rN},iL={name:fs("Paste format only"),execute:e=>aN(e,"onlyFormat")},nL={name:fs("Find and replace"),description:"Ctrl+H",isReadonlyAllowed:!0,execute:e=>{e.openSidePanel("FindAndReplace",{})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.SEARCH"},rL={name:fs("Delete values"),execute:e=>e.model.dispatch("DELETE_UNFILTERED_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},aL={name:e=>{if(e.model.getters.getSelectedZones().length>1)return fs("Delete rows");let t,s;const o=e.model.getters.getActiveRows();if(0!==o.size)t=Je([...o]),s=Ke([...o]);else{const o=e.model.getters.getSelectedZones()[0];t=o.top,s=o.bottom}return t===s?fs("Delete row %s",(t+1).toString()):fs("Delete rows %s - %s",(t+1).toString(),(s+1).toString())},execute:e=>{const t=[...e.model.getters.getActiveRows()];if(!t.length){const s=e.model.getters.getSelectedZones()[0];for(let e=s.top;e<=s.bottom;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),dimension:"ROW",elements:t})},isVisible:e=>lN("ROW",e)},lL={...aL,isVisible:vN},cL={name:e=>{if(e.model.getters.getSelectedZones().length>1)return fs("Clear rows");let t,s;const o=e.model.getters.getActiveRows();if(0!==o.size)t=Je([...o]),s=Ke([...o]);else{const o=e.model.getters.getSelectedZones()[0];t=o.top,s=o.bottom}return t===s?fs("Clear row %s",(t+1).toString()):fs("Clear rows %s - %s",(t+1).toString(),(s+1).toString())},execute:e=>{const t=e.model.getters.getActiveSheetId(),s=[...e.model.getters.getActiveRows()].map(s=>e.model.getters.getRowsZone(t,s,s));e.model.dispatch("DELETE_CONTENT",{target:s,sheetId:e.model.getters.getActiveSheetId()})}},hL={name:e=>{if(e.model.getters.getSelectedZones().length>1)return fs("Delete columns");let t,s;const o=e.model.getters.getActiveCols();if(0!==o.size)t=Je([...o]),s=Ke([...o]);else{const o=e.model.getters.getSelectedZones()[0];t=o.left,s=o.right}return t===s?fs("Delete column %s",it(t)):fs("Delete columns %s - %s",it(t),it(s))},execute:e=>{const t=[...e.model.getters.getActiveCols()];if(!t.length){const s=e.model.getters.getSelectedZones()[0];for(let e=s.left;e<=s.right;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),dimension:"COL",elements:t})},isVisible:e=>lN("COL",e)},dL={...hL,isVisible:vN},uL={name:e=>{if(e.model.getters.getSelectedZones().length>1)return fs("Clear columns");let t,s;const o=e.model.getters.getActiveCols();if(0!==o.size)t=Je([...o]),s=Ke([...o]);else{const o=e.model.getters.getSelectedZones()[0];t=o.left,s=o.right}return t===s?fs("Clear column %s",it(t)):fs("Clear columns %s - %s",it(t),it(s))},execute:e=>{const t=e.model.getters.getActiveSheetId(),s=[...e.model.getters.getActiveCols()].map(s=>e.model.getters.getColsZone(t,s,s));e.model.dispatch("DELETE_CONTENT",{target:s,sheetId:e.model.getters.getActiveSheetId()})}},gL={name:fs("Delete cells"),isVisible:vN},pL={name:fs("Delete cell and shift up"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});eN(e,s)}},mL={name:fs("Delete cell and shift left"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});eN(e,s)}},fL={name:fs("Merge cells"),isEnabled:e=>!SL(e),isActive:e=>CL(e),execute:e=>function(e){if(SL(e))return;const t=e.model.getters.getSelectedZones(),s=e.model.getters.getActiveSheetId();if(CL(e)){const o=t.flatMap(t=>e.model.getters.getMergesInZone(s,t));e.model.dispatch("REMOVE_MERGE",{sheetId:s,target:o})}else!function(e,t,s){const o=e.model.dispatch("ADD_MERGE",{sheetId:t,target:s});o.isCancelledBecause("MergeInTable")?e.raiseError(XN.MergeInFilter):o.isCancelledBecause("MergeIsDestructive")&&e.askConfirmation(XN.MergeIsDestructive,()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:s,force:!0})})}(e,s,t)}(e),icon:"o-spreadsheet-Icon.MERGE_CELL"},vL={name:()=>fs("Edit table"),execute:e=>e.openSidePanel("TableSidePanel",{}),icon:"o-spreadsheet-Icon.EDIT_TABLE"},bL={name:()=>fs("Delete table"),execute:e=>{const t=e.model.getters.getActivePosition(),s=e.model.getters.getTable(t);s&&e.model.dispatch("REMOVE_TABLE",{sheetId:t.sheetId,target:[s.range.zone]})},icon:"o-spreadsheet-Icon.DELETE_TABLE"};function SL(e){const t=e.model.getters.getSelectedZones(),{sheetId:s}=e.model.getters.getActivePosition(),{xSplit:o,ySplit:i}=e.model.getters.getPaneDivisions(s);return t.every(e=>1===Kt(e))||Jt(t,o,i)||function(e){for(let t=0;t<e.length-1;t++)for(let s=t+1;s<e.length;s++)if(Lt(e[t],e[s]))return!0;return!1}(t)}function CL(e){if(SL(e))return!1;const t=e.model.getters.getActiveSheetId();return e.model.getters.getSelectedZones().some(s=>e.model.getters.getMergesInZone(t,s).length>0)}const yL={name:e=>{const t=QL(e);return 1===t?fs("Insert row"):fs("Insert %s rows",t.toString())},isVisible:e=>bN(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW"},IL={name:e=>{const t=QL(e);return 1===t?fs("Insert row above"):fs("Insert %s rows above",t.toString())},execute:cN,isVisible:e=>bN(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},wL={...IL,name:e=>{const t=QL(e);return 1===t?fs("Row above"):fs("%s Rows above",t.toString())}},EL={...IL,name:e=>{const t=QL(e);return 1===t?fs("Insert row"):fs("Insert %s rows",t.toString())},isVisible:vN,icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},RL={execute:e=>{const t=e.model.getters.getActiveRows();let s,o;if(t.size)s=Ke([...t]),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];s=t.bottom,o=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:"after",base:s,quantity:o,dimension:"ROW"})},name:e=>{const t=QL(e);return 1===t?fs("Insert row below"):fs("Insert %s rows below",t.toString())},isVisible:e=>bN(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_AFTER"},xL={...RL,name:e=>{const t=QL(e);return 1===t?fs("Row below"):fs("%s Rows below",t.toString())}},TL={name:e=>{const t=ek(e);return 1===t?fs("Insert column"):fs("Insert %s columns",t.toString())},isVisible:e=>bN(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL"},AL={name:e=>{const t=ek(e);return 1===t?fs("Insert column left"):fs("Insert %s columns left",t.toString())},execute:hN,isVisible:e=>bN(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},DL={...AL,name:e=>{const t=ek(e);return 1===t?fs("Column left"):fs("%s Columns left",t.toString())}},_L={...AL,name:e=>{const t=ek(e);return 1===t?fs("Insert column"):fs("Insert %s columns",t.toString())},isVisible:vN,icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},OL={name:e=>{const t=ek(e);return 1===t?fs("Insert column right"):fs("Insert %s columns right",t.toString())},execute:dN,isVisible:e=>bN(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_AFTER"},FL={...OL,name:e=>{const t=ek(e);return 1===t?fs("Column right"):fs("%s Columns right",t.toString())},execute:dN},PL={name:fs("Insert cells"),isVisible:e=>vN(e)&&0===e.model.getters.getActiveCols().size&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_CELL"},ML={name:fs("Insert cells and shift down"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});eN(e,s)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_DOWN"},NL={name:fs("Insert cells and shift right"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});eN(e,s)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_RIGHT"},LL={name:fs("Chart"),execute:e=>{const t=e.model.getters,s=e.model.uuidGenerator.smallUuid(),o=t.getActiveSheetId();let i=t.getSelectedZones();1===i.length&&1===Kt(i[0])&&(e.model.selection.selectTableAroundSelection(),i=t.getSelectedZones());const n={width:536,height:335},{col:r,row:a,offset:l}=Ry(t,n);e.model.dispatch("CREATE_CHART",{sheetId:o,figureId:s,chartId:e.model.uuidGenerator.smallUuid(),col:r,row:a,offset:l,size:n,definition:JM(i,e.model.getters)}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{figureId:s}),e.openSidePanel("ChartPanel"))},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.INSERT_CHART"},kL={name:fs("Carousel"),execute:e=>{const t=e.model.getters,s=e.model.uuidGenerator.smallUuid(),o=t.getActiveSheetId(),i={width:536,height:335},{col:n,row:r,offset:a}=Ry(t,i);e.model.dispatch("CREATE_CAROUSEL",{sheetId:o,figureId:s,col:n,row:r,offset:a,size:i,definition:{items:[]}}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{figureId:s}),e.openSidePanel("CarouselPanel",{figureId:s}))},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.CAROUSEL"},VL={name:fs("Pivot table"),execute:e=>{const t=e.model.uuidGenerator.smallUuid(),s=e.model.uuidGenerator.smallUuid();e.model.dispatch("INSERT_NEW_PIVOT",{pivotId:t,newSheetId:s}).isSuccessful&&e.openSidePanel("PivotSidePanel",{pivotId:t})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.PIVOT"},UL={name:fs("Image"),description:"Ctrl+O",execute:uN,isVisible:e=>void 0!==e.imageProvider,isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.INSERT_IMAGE"},HL={name:()=>fs("Table"),execute:e=>{const t=e.model.getters.getActiveSheetId();oN(e,t).isSuccessful&&e.openSidePanel("TableSidePanel",{})},isVisible:e=>fN(e)&&!e.model.getters.getFirstTableInSelection(),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.PAINT_TABLE"},zL={name:fs("Function"),icon:"o-spreadsheet-Icon.FORMULA"},BL={name:fs("SUM"),execute:e=>e.startCellEdition("=SUM(")},GL={name:fs("AVERAGE"),execute:e=>e.startCellEdition("=AVERAGE(")},WL={name:fs("COUNT"),execute:e=>e.startCellEdition("=COUNT(")},$L={name:fs("MAX"),execute:e=>e.startCellEdition("=MAX(")},qL={name:fs("MIN"),execute:e=>e.startCellEdition("=MIN(")},ZL={name:fs("All"),children:[function(){return JL(uf.getKeys().filter(e=>!uf.get(e).hidden))}]};const jL={name:fs("Link"),execute:gN,icon:"o-spreadsheet-Icon.INSERT_LINK"},YL={name:fs("Checkbox"),execute:e=>{const t=e.model.getters.getSelectedZones(),s=e.model.getters.getActiveSheetId(),o=t.map(t=>e.model.getters.getRangeDataFromZone(s,t));e.model.dispatch("ADD_DATA_VALIDATION_RULE",{ranges:o,sheetId:s,rule:{id:e.model.uuidGenerator.smallUuid(),criterion:{type:"isBoolean",values:[]}}})},icon:"o-spreadsheet-Icon.INSERT_CHECKBOX"},XL={name:fs("Dropdown list"),execute:e=>{const t=e.model.getters.getSelectedZones(),s=e.model.getters.getActiveSheetId(),o=t.map(t=>e.model.getters.getRangeDataFromZone(s,t)),i=e.model.uuidGenerator.smallUuid();e.model.dispatch("ADD_DATA_VALIDATION_RULE",{ranges:o,sheetId:s,rule:{id:i,criterion:{type:"isValueInList",values:[],displayStyle:"chip"}}});const n=e.model.getters.getDataValidationRule(s,i);n&&e.openSidePanel("DataValidationEditor",{rule:ah(n,e.model.getters.getLocale()),onExit:()=>{e.replaceSidePanel("DataValidation","DataValidationEditor")}})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.INSERT_DROPDOWN"},KL={name:fs("Insert sheet"),execute:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSheetIds().indexOf(t)+1,o=e.model.uuidGenerator.smallUuid();e.model.dispatch("CREATE_SHEET",{sheetId:o,position:s,name:e.model.getters.getNextSheetName()}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})},icon:"o-spreadsheet-Icon.INSERT_SHEET"};function JL(e){return e.sort().map((e,t)=>({name:e,sequence:10*t,execute:t=>t.startCellEdition(`=${e}(`)}))}function QL(e){const t=e.model.getters.getActiveRows();if(t.size)return t.size;{const t=e.model.getters.getSelectedZones()[0];return t.bottom-t.top+1}}function ek(e){const t=e.model.getters.getActiveCols();if(t.size)return t.size;{const t=e.model.getters.getSelectedZones()[0];return t.right-t.left+1}}const tk={name:fs("See pivot properties"),execute(e){const t=e.model.getters.getActivePosition(),s=e.model.getters.getPivotIdFromPosition(t);e.openSidePanel("PivotSidePanel",{pivotId:s})},isVisible:e=>{const t=e.model.getters.getActivePosition(),s=e.model.getters.getPivotIdFromPosition(t);return!e.isSmall&&s&&e.model.getters.isExistingPivot(s)||!1},isReadonlyAllowed:!0,icon:"o-spreadsheet-Icon.PIVOT"},sk={name:fs("Ascending"),execute:e=>pk(e,e.model.getters.getActivePosition(),"asc"),isActive:e=>"asc"===e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())},ok={name:fs("Descending"),execute:e=>pk(e,e.model.getters.getActivePosition(),"desc"),isActive:e=>"desc"===e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())},ik={name:fs("No sorting"),execute:e=>pk(e,e.model.getters.getActivePosition(),"none"),isActive:e=>"none"===e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())},nk={name:fs("Convert to individual formulas"),execute(e){const t=e.model.getters.getActivePosition(),s=e.model.getters.getCorrespondingFormulaCell(t),o=e.model.getters.getPivotIdFromPosition(t);if(!s||!o)return;const{sheetId:i,col:n,row:r}=e.model.getters.getCellPosition(s.id),a=e.model.getters.getPivot(o);a.init(),a.isValid()&&e.model.dispatch("SPLIT_PIVOT_FORMULA",{sheetId:i,col:n,row:r,pivotId:o})},isVisible:e=>{const t=e.model.getters.getActivePosition(),s=e.model.getters.getPivotIdFromPosition(t);if(!s)return!1;const o=e.model.getters.getPivot(s),i=e.model.getters.getEvaluatedCell(t);return o.isValid()&&e.model.getters.isSpillPivotFormula(t)&&i.type!==_d.error},icon:"o-spreadsheet-Icon.PIVOT"},rk={name:fs("Group pivot dimensions"),execute:e=>{const t=mk(e);if(!t)return;const{pivotId:s,values:o,field:i}=t,n=e.model.getters.getPivot(s),r=ae(e.model.getters.getPivotCoreDefinition(s));if(i.isCustomField){const e=(r.customFields||{})[i.name];if(!e)return;!function(e,t){const s=new Set,o=[];for(const i of t){const t=e.groups.find(e=>e.name===i);t?(o.push(t),t.values.forEach(e=>s.add(e))):s.add(i)}if(o.some(e=>e.isOtherGroup))e.groups=e.groups.filter(e=>e.isOtherGroup||!o.includes(e));else if(0===o.length){const s={name:pp(fs("Group"),e),values:t};e.groups.push(s)}else{const t=o.slice(1);e.groups=e.groups.filter(e=>!t.includes(e)),o[0].values=Array.from(s)}}(e,o)}else!function(e,t,s,o){const i=Sp(e,s,o);vp(t,i);const n={name:pp(fs("Group"),i),values:t};i.groups.push(n),e.customFields||(e.customFields={});e.customFields[i.name]=i,bp(e,s.name,i.name)}(r,o,i,n.getFields());e.model.dispatch("UPDATE_PIVOT",{pivotId:s,pivot:r})},isVisible:e=>{const t=mk(e);if(!t)return!1;const{pivotId:s,values:o,field:i}=t,n=e.model.getters.getPivot(s);return o.length>1&&(i.isCustomField||XD.get(n.type).canHaveCustomGroup(i))}},ak={name:fs("Group all remaining dimensions"),execute:e=>{const t=mk(e);if(!t)return;const{pivotId:s,field:o}=t,i=e.model.getters.getPivot(s),n=ae(e.model.getters.getPivotCoreDefinition(s)),r=o.isCustomField?(n.customFields||{})[o.name]:Sp(n,o,i.getFields());r&&(r.groups.push({name:pp(fs("Others"),r),values:[],isOtherGroup:!0}),bp(n,o.name,r.name),e.model.dispatch("UPDATE_PIVOT",{pivotId:s,pivot:n}))},isVisible:e=>{const t=mk(e);if(!t)return!1;const{pivotId:s,field:o,values:i}=t;return function(e,t,s,o){const i=e.model.getters.getPivot(t),n=e.model.getters.getPivotCoreDefinition(t),r=o.isCustomField?(n.customFields||{})[o.name]:Object.values(n.customFields||{}).find(e=>e.parentField===o.name),a=i.definition.getDimension(o.name);if(!a||!r||fk(n,s,o,i.getFields()))return!1;const l=new Set(i.getPossibleFieldValues(a).map(e=>e.value)),c=o.isCustomField?r.groups.map(e=>e.name):r.groups.flatMap(e=>e.values);for(const e of[...s,...c])l.delete(e);return 0===l.size}(e,s,i,o)}},lk={name:fs("Ungroup pivot dimensions"),execute:e=>{const t=mk(e);if(!t)return;const{pivotId:s,values:o,field:i}=t,n=e.model.getters.getPivot(s),r=ae(e.model.getters.getPivotCoreDefinition(s));!function(e,t,s,o){let i;if(s.isCustomField){if(i=(e.customFields||{})[s.name],!i)return;i.groups=i.groups.filter(e=>!t.includes(e.name))}else i=Sp(e,s,o),i.groups.some(e=>e.isOtherGroup)&&t.some(e=>!i?.groups.some(t=>t.values.includes(e)))&&(i.groups=i.groups.filter(e=>!e.isOtherGroup)),vp(t,i);i.groups.every(e=>0===e.values.length&&!e.isOtherGroup)&&(!function(e,t){const s=e.customFields?.[t];if(!s)return;const o=[...e.rows,...e.columns].some(e=>e.fieldName===s.parentField);for(const i of[e.rows,e.columns]){const e=i.findIndex(e=>e.fieldName===t);-1!==e&&(o?i.splice(e,1):i.splice(e,1,{fieldName:s.parentField}))}}(e,i.name),delete e.customFields?.[i.name])}(r,o,i,n.getFields()),e.model.dispatch("UPDATE_PIVOT",{pivotId:s,pivot:r})},isVisible:e=>{const t=mk(e);if(!t)return!1;const{pivotId:s,values:o,field:i}=t,n=e.model.getters.getPivot(s),r=e.model.getters.getPivotCoreDefinition(s);if(!i.isCustomField){const e=Sp(r,i,n.getFields());if(![...r.rows,...r.columns].some(t=>t.fieldName===e.name))return!1}return fk(r,o,i,n.getFields())}},ck={name:e=>{const t=e.model.getters.getActivePosition(),s=uk(e.model.getters,t);return s.isPivotGroup?s.isCollapsed?fs("Expand"):fs("Collapse"):""},execute(e){Cp(e.model.getters.getActivePosition(),e)},isVisible:e=>{const t=e.model.getters.getActivePosition();return uk(e.model.getters,t).isPivotGroup}},hk={name:fs("Collapse all"),execute(e){const t=e.model.getters.getActivePosition(),s=uk(e.model.getters,t);if(!s.isPivotGroup)return;const{pivotCell:o,pivotId:i,siblingDomains:n}=s,r=ae(e.model.getters.getPivotCoreDefinition(i));r.collapsedDomains=r.collapsedDomains||{COL:[],ROW:[]};const a=[...r.collapsedDomains[o.dimension]||[],...n],l=a.filter((e,t)=>t===a.findIndex(t=>Me(t,e)));r.collapsedDomains[o.dimension]=l,e.model.dispatch("UPDATE_PIVOT",{pivotId:i,pivot:r})},isVisible:e=>{const t=e.model.getters.getActivePosition(),s=uk(e.model.getters,t);if(!s.isPivotGroup)return!1;const{pivotCell:o,pivotId:i,siblingDomains:n}=s,r=e.model.getters.getPivotCoreDefinition(i);return!n.every(e=>(r.collapsedDomains?.[o.dimension]||[]).some(t=>Me(t,e)))}},dk={name:fs("Expand all"),execute(e){const t=e.model.getters.getActivePosition(),s=uk(e.model.getters,t);if(!s.isPivotGroup)return;const{pivotCell:o,pivotId:i,siblingDomains:n}=s,r=ae(e.model.getters.getPivotCoreDefinition(i));r.collapsedDomains=r.collapsedDomains||{COL:[],ROW:[]};const a=(r.collapsedDomains[o.dimension]||[]).filter(e=>!n.find(t=>Me(t,e)));r.collapsedDomains[o.dimension]=a,e.model.dispatch("UPDATE_PIVOT",{pivotId:i,pivot:r})},isVisible:e=>{const t=e.model.getters.getActivePosition(),s=uk(e.model.getters,t);if(!s.isPivotGroup)return!1;const{pivotCell:o,pivotId:i,siblingDomains:n}=s,r=e.model.getters.getPivotCoreDefinition(i);return(r.collapsedDomains?.[o.dimension]||[]).some(e=>n.some(t=>Me(t,e)))}};function uk(e,t){if(!e.isSpillPivotFormula(t))return{isPivotGroup:!1};const s=e.getPivotCellFromPosition(t),o=e.getPivotIdFromPosition(t);if("HEADER"!==s.type||!o||!s.domain.length)return{isPivotGroup:!1};const i=e.getPivotCoreDefinition(o),n=e.isDashboard(),r="COL"===s.dimension?i.columns:i.rows;if(!(!n&&s.domain.length!==r.length))return{isPivotGroup:!1};const a=(i.collapsedDomains?.[s.dimension]??[]).some(e=>Me(e,s.domain)),l=e.getPivot(o).getExpandedTableStructure(),c=s.domain.length-1,h="ROW"===s.dimension?l.getRowDomainsAtDepth(c):l.getColumnDomainsAtDepth(c);return{isPivotGroup:!0,isCollapsed:a,pivotCell:s,pivotId:o,siblingDomains:h}}function gk(e,t){const s=e.getPivotIdFromPosition(t);if(!s||!e.isExistingPivot(s)||!e.isSpillPivotFormula(t))return!1;if(!e.getPivot(s).isValid())return!1;const o=e.getPivotCellFromPosition(t);return"VALUE"===o.type||"MEASURE_HEADER"===o.type}function pk(e,t,s){const o=e.model.getters.getPivotIdFromPosition(t),i=e.model.getters.getPivotCellFromPosition(t);if("EMPTY"===i.type||"HEADER"===i.type||!o)return;if("none"===s)return void e.model.dispatch("UPDATE_PIVOT",{pivotId:o,pivot:{...e.model.getters.getPivotCoreDefinition(o),sortedColumn:void 0}});const n=lA(e.model.getters.getPivot(o),i.domain).colDomain;e.model.dispatch("UPDATE_PIVOT",{pivotId:o,pivot:{...e.model.getters.getPivotCoreDefinition(o),sortedColumn:{domain:n,order:s,measure:i.measure}}})}function mk(e){let t,s;const o=[];for(const i of e.model.getters.getSelectedZones()){const n=e.model.getters.getActiveSheetId();for(const r of Gt(n,i)){const i=e.model.getters.getPivotIdFromPosition(r);if(t){if(i&&t!==i)return}else t=i;if(!t)continue;const n=e.model.getters.getPivotCellFromPosition(r);if("HEADER"!==n.type||!e.model.getters.isSpillPivotFormula(r))continue;const a=n.domain.at(-1)?.field;if(!s&&a)s=a;else if(s&&a&&s!==a)return;o.push(n)}}if(!t||!s||0===o.length)return;const i=e.model.getters.getPivot(t).getFields()[s];if(!i)return;return{pivotId:t,values:o.map(e=>e.domain.at(-1)?.value).filter(e=>void 0!==e),field:i}}function fk(e,t,s,o){if(s.isCustomField){const o=(e.customFields||{})[s.name];return!!o&&o.groups.some(e=>t.includes(e.name))}return Sp(e,s,o).groups.some(e=>e.isOtherGroup||t.some(t=>e.values.includes(t)))}const vk=new kM;vk.add("cut",{...eL,sequence:10}).add("copy",{...QN,sequence:20}).add("paste",{...tL,sequence:30}).add("paste_special",{...sL,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...oL,sequence:10}).addChild("paste_format_only",["paste_special"],{...iL,sequence:20}).add("add_row_before",{...EL,sequence:70}).add("add_column_before",{..._L,sequence:90}).add("insert_cell",{...PL,sequence:100,separator:!0}).addChild("insert_cell_down",["insert_cell"],{...ML,name:fs("Shift down"),sequence:10}).addChild("insert_cell_right",["insert_cell"],{...NL,name:fs("Shift right"),sequence:20}).add("delete_row",{...lL,sequence:110,icon:"o-spreadsheet-Icon.TRASH"}).add("delete_column",{...dL,sequence:120,icon:"o-spreadsheet-Icon.TRASH"}).add("delete_cell",{...gL,sequence:130,separator:!0,icon:"o-spreadsheet-Icon.TRASH"}).addChild("delete_cell_up",["delete_cell"],{...pL,name:fs("Shift up"),sequence:10,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_UP"}).addChild("delete_cell_left",["delete_cell"],{...mL,name:fs("Shift left"),sequence:20,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_LEFT"}).add("edit_table",{...vL,isVisible:mN,isEnabled:e=>!e.isSmall,sequence:140}).add("delete_table",{...bL,isVisible:mN,sequence:145,separator:!0}).add("insert_link",{...jL,name:e=>{const t=e.model.getters.getActiveSheetId(),{col:s,row:o}=e.model.getters.getActivePosition(),i=e.model.getters.getEvaluatedCell({sheetId:t,col:s,row:o});return i&&i.link?fs("Edit link"):fs("Insert link")},sequence:150,separator:!0}).add("pivot_headers_group",{sequence:155,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",...rk}).add("pivot_group_remaining",{sequence:155,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",...ak}).add("pivot_headers_ungroup",{sequence:155,icon:"o-spreadsheet-Icon.MINUS_IN_BOX",...lk}).add("collapse_pivot",{sequence:156,name:fs("Expand/Collapse"),icon:"o-spreadsheet-Icon.COLLAPSE"}).addChild("toggle_collapse_pivot_cell",["collapse_pivot"],{sequence:10,...ck}).addChild("collapse_all_pivot",["collapse_pivot"],{sequence:20,...hk}).addChild("expand_all_pivot",["collapse_pivot"],{sequence:30,...dk}).add("pivot_sorting",{name:fs("Sort pivot"),sequence:155,icon:"o-spreadsheet-Icon.SORT_RANGE",isVisible:e=>{const t=e.model.getters.getActivePosition();return gk(e.model.getters,t)}}).add("pivot_fix_formulas",{...nk,sequence:160}).add("pivot_properties",{...tk,sequence:170,separator:!0}).addChild("pivot_sorting_asc",["pivot_sorting"],{...sk,sequence:10}).addChild("pivot_sorting_desc",["pivot_sorting"],{...ok,sequence:20}).addChild("pivot_sorting_none",["pivot_sorting"],{...ik,sequence:30});const bk={name:fs("Sort range"),isVisible:vN,icon:"o-spreadsheet-Icon.SORT_RANGE"},Sk={name:fs("Ascending (A ⟶ Z)"),execute:e=>{const{anchor:t,zones:s}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();xP(e,o,t.cell,s[0],"asc")},icon:"o-spreadsheet-Icon.SORT_ASCENDING"},Ck={name:fs("Data cleanup"),icon:"o-spreadsheet-Icon.DATA_CLEANUP"},yk={name:fs("Remove duplicates"),execute:e=>{1===Kt(e.model.getters.getSelectedZone())&&e.model.selection.selectTableAroundSelection(),e.openSidePanel("RemoveDuplicates",{})},isEnabled:e=>!e.isSmall},Ik={name:fs("Trim whitespace"),execute:e=>{e.model.dispatch("TRIM_WHITESPACE")}},wk={name:fs("Descending (Z ⟶ A)"),execute:e=>{const{anchor:t,zones:s}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();xP(e,o,t.cell,s[0],"desc")},icon:"o-spreadsheet-Icon.SORT_DESCENDING"},Ek={...SN},Rk={...SN,isActive:e=>pN(e)},xk={name:fs("Split text to columns"),sequence:1,execute:e=>e.openSidePanel("SplitToColumns",{}),isEnabled:e=>!e.isSmall&&e.model.getters.isSingleColSelected(),icon:"o-spreadsheet-Icon.SPLIT_TEXT"},Tk={id:"reinsert_dynamic_pivot",name:fs("Re-insert dynamic pivot"),sequence:60,icon:"o-spreadsheet-Icon.INSERT_PIVOT",children:[e=>e.model.getters.getPivotIds().map((t,s)=>({id:`reinsert_dynamic_pivot_${e.model.getters.getPivotFormulaId(t)}`,name:e.model.getters.getPivotDisplayName(t),sequence:s,execute:e=>{const s=e.model.getters.getSelectedZone(),o=e.model.getters.getPivot(t).getCollapsedTableStructure().export();e.model.dispatch("INSERT_PIVOT_WITH_TABLE",{pivotId:t,table:o,col:s.left,row:s.top,sheetId:e.model.getters.getActiveSheetId(),pivotMode:"dynamic"}),e.model.dispatch("REFRESH_PIVOT",{id:t})},isVisible:e=>e.model.getters.getPivot(t).isValid()}))],isVisible:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.getPivot(t).isValid())},Ak={id:"reinsert_static_pivot",name:fs("Re-insert static pivot"),sequence:70,icon:"o-spreadsheet-Icon.INSERT_PIVOT",children:[e=>e.model.getters.getPivotIds().map((t,s)=>({id:`reinsert_static_pivot_${e.model.getters.getPivotFormulaId(t)}`,name:e.model.getters.getPivotDisplayName(t),sequence:s,execute:e=>{const s=e.model.getters.getSelectedZone(),o=e.model.getters.getPivot(t).getExpandedTableStructure();o.numberOfCells>Q?e.notifyUser({type:"warning",text:yP(o.numberOfCells,e.model.getters.getLocale()),sticky:!0}):(e.model.dispatch("INSERT_PIVOT_WITH_TABLE",{pivotId:t,table:o.export(),col:s.left,row:s.top,sheetId:e.model.getters.getActiveSheetId(),pivotMode:"static"}),e.model.dispatch("REFRESH_PIVOT",{id:t}))},isVisible:e=>e.model.getters.getPivot(t).isValid()}))],isVisible:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.getPivot(t).isValid())};function Dk({name:e,format:t,descriptionValue:s}){const o="function"==typeof t?t:()=>t;return{name:e,description:e=>pn(s,{format:o(e),locale:e.model.getters.getLocale()}),execute:e=>iN(e,o(e)),isActive:e=>RV(e,o(e)),format:t}}const _k={name:fs("Automatic"),execute:e=>iN(e,""),isActive:e=>function(e){const t=e.model.getters.getActivePosition(),s=e.model.getters.getPivotCellFromPosition(t);if("VALUE"===s.type)return!e.model.getters.getEvaluatedCell(t).format;return!e.model.getters.getCell(t)?.format}(e)},Ok={name:fs("Plain text"),execute:e=>iN(e,"@"),isActive:e=>RV(e,"@")},Fk=Dk({name:fs("Number"),descriptionValue:1000.12,format:"#,##0.00"}),Pk={name:fs("Format as percent"),execute:e=>iN(e,"0.00%"),icon:"o-spreadsheet-Icon.PERCENT"},Mk=Dk({name:fs("Percent"),descriptionValue:.1012,format:"0.00%"}),Nk=Dk({name:fs("Currency"),descriptionValue:1000.12,format:e=>Dn(e.model.config.defaultCurrency||ee)}),Lk={...Dk({name:fs("Currency rounded"),descriptionValue:1e3,format:e=>Fn(Dn(e.model.config.defaultCurrency||ee))}),isVisible:e=>{const t=Dn(e.model.config.defaultCurrency||ee);return t!==Fn(t)}},kk=Dk({name:fs("Accounting"),descriptionValue:-1000.12,format:e=>_n(e.model.config.defaultCurrency||ee)}),Vk=Xv("2023/09/26 10:43:00 PM",Oc),Uk={name:fs("Custom currency"),isVisible:e=>void 0!==e.loadCurrencies&&!e.isSmall,execute:e=>e.openSidePanel("CustomCurrency",{})},Hk=Dk({name:fs("Date"),descriptionValue:Vk,format:e=>e.model.getters.getLocale().dateFormat}),zk=Dk({name:fs("Time"),descriptionValue:Vk,format:e=>e.model.getters.getLocale().timeFormat}),Bk=Dk({name:fs("Date time"),descriptionValue:Vk,format:e=>hh(e.model.getters.getLocale())}),Gk=Dk({name:fs("Duration"),descriptionValue:"27:51:38",format:"hhhh:mm:ss"}),Wk=Dk({name:fs("Quarter"),descriptionValue:Vk,format:"qq yyyy"}),$k=Dk({name:fs("Full quarter"),descriptionValue:Vk,format:"qqqq yyyy"}),qk={name:fs("More date formats"),execute:e=>e.openSidePanel("MoreFormats",{})},Zk=Dk({name:fs("Full date time"),format:"dddd d mmmm yyyy hh:mm:ss a",descriptionValue:Vk}),jk=Dk({name:fs("ISO Date"),format:"yyyy-mm-dd",descriptionValue:Vk}),Yk=Dk({name:fs("ISO Date time"),format:"yyyy-mm-dd hh:mm:ss",descriptionValue:Vk}),Xk=Dk({name:fs("Full week day and month"),format:"dddd d mmmm yyyy",descriptionValue:Vk}),Kk=Dk({name:fs("Day and full month"),format:"d mmmm yyyy",descriptionValue:Vk}),Jk=Dk({name:fs("Short week day"),format:"ddd d mmm yyyy",descriptionValue:Vk}),Qk=Dk({name:fs("Day and short month"),format:"d mmm yyyy",descriptionValue:Vk}),eV=Dk({name:fs("Full month"),format:"mmmm yyyy",descriptionValue:Vk}),tV=Dk({name:fs("Short month"),format:"mmm yyyy",descriptionValue:Vk}),sV={name:fs("Increase decimal places"),icon:"o-spreadsheet-Icon.INCREASE_DECIMAL",execute:e=>e.model.dispatch("SET_DECIMAL",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:1})},oV={name:fs("Decrease decimal places"),icon:"o-spreadsheet-Icon.DECRASE_DECIMAL",execute:e=>e.model.dispatch("SET_DECIMAL",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:-1})},iV={name:fs("Bold"),description:"Ctrl+B",execute:e=>nN(e,{bold:!e.model.getters.getCurrentStyle().bold}),icon:"o-spreadsheet-Icon.BOLD",isActive:e=>!!e.model.getters.getCurrentStyle().bold},nV={name:fs("Italic"),description:"Ctrl+I",execute:e=>nN(e,{italic:!e.model.getters.getCurrentStyle().italic}),icon:"o-spreadsheet-Icon.ITALIC",isActive:e=>!!e.model.getters.getCurrentStyle().italic},rV={name:fs("Underline"),description:"Ctrl+U",execute:e=>nN(e,{underline:!e.model.getters.getCurrentStyle().underline}),icon:"o-spreadsheet-Icon.UNDERLINE",isActive:e=>!!e.model.getters.getCurrentStyle().underline},aV={name:fs("Strikethrough"),execute:e=>nN(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),icon:"o-spreadsheet-Icon.STRIKE",isActive:e=>!!e.model.getters.getCurrentStyle().strikethrough},lV={name:fs("Font size"),children:K.map(e=>({name:e.toString(),sequence:e,id:`font_size_${e}`,execute:t=>nN(t,{fontSize:e}),isActive:t=>function(e,t){const s=e.model.getters.getCurrentStyle().fontSize||L;return s===t}(t,e)})),icon:"o-spreadsheet-Icon.FONT_SIZE"},cV={name:fs("Alignment"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},hV={name:fs("Horizontal align"),icon:e=>function(e){switch(xV(e)){case"right":return"o-spreadsheet-Icon.ALIGN_RIGHT";case"center":return"o-spreadsheet-Icon.ALIGN_CENTER";default:return"o-spreadsheet-Icon.ALIGN_LEFT"}}(e)},dV={name:fs("Left"),description:"Ctrl+Shift+L",execute:e=>nN(e,{align:"left"}),isActive:e=>"left"===xV(e),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},uV={name:fs("Center"),description:"Ctrl+Shift+E",execute:e=>nN(e,{align:"center"}),isActive:e=>"center"===xV(e),icon:"o-spreadsheet-Icon.ALIGN_CENTER"},gV={name:fs("Right"),description:"Ctrl+Shift+R",execute:e=>nN(e,{align:"right"}),isActive:e=>"right"===xV(e),icon:"o-spreadsheet-Icon.ALIGN_RIGHT"},pV={name:fs("Vertical align"),icon:e=>function(e){switch(TV(e)){case"top":return"o-spreadsheet-Icon.ALIGN_TOP";case"middle":return"o-spreadsheet-Icon.ALIGN_MIDDLE";default:return"o-spreadsheet-Icon.ALIGN_BOTTOM"}}(e)},mV={name:fs("Top"),execute:e=>nN(e,{verticalAlign:"top"}),isActive:e=>"top"===TV(e),icon:"o-spreadsheet-Icon.ALIGN_TOP"},fV={name:fs("Middle"),execute:e=>nN(e,{verticalAlign:"middle"}),isActive:e=>"middle"===TV(e),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},vV={name:fs("Bottom"),execute:e=>nN(e,{verticalAlign:"bottom"}),isActive:e=>"bottom"===TV(e),icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"},bV={name:fs("Wrapping"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},SV={name:fs("Wrapping"),icon:e=>function(e){switch(AV(e)){case"wrap":return"o-spreadsheet-Icon.WRAPPING_WRAP";case"clip":return"o-spreadsheet-Icon.WRAPPING_CLIP";default:return"o-spreadsheet-Icon.WRAPPING_OVERFLOW"}}(e)},CV={name:fs("Overflow"),execute:e=>nN(e,{wrapping:"overflow"}),isActive:e=>"overflow"===AV(e),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},yV={name:fs("Wrap"),execute:e=>nN(e,{wrapping:"wrap"}),isActive:e=>"wrap"===AV(e),icon:"o-spreadsheet-Icon.WRAPPING_WRAP"},IV={name:fs("Clip"),execute:e=>nN(e,{wrapping:"clip"}),isActive:e=>"clip"===AV(e),icon:"o-spreadsheet-Icon.WRAPPING_CLIP"};fs("Text Color"),fs("Fill Color");const wV={name:fs("Conditional formatting"),execute:e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.CONDITIONAL_FORMAT"},EV={name:fs("Clear formatting"),description:"Ctrl+<",execute:e=>e.model.dispatch("CLEAR_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()}),icon:"o-spreadsheet-Icon.CLEAR_FORMAT"};function RV(e,t){const s=e.model.getters.getActivePosition();return"VALUE"===e.model.getters.getPivotCellFromPosition(s).type?e.model.getters.getEvaluatedCell(s).format===t:e.model.getters.getCell(s)?.format===t}function xV(e){const t=e.model.getters.getCurrentStyle();if(t.align)return t.align;return e.model.getters.getActiveCell().defaultAlign}function TV(e){const t=e.model.getters.getCurrentStyle();return t.verticalAlign?t.verticalAlign:M}function AV(e){const t=e.model.getters.getCurrentStyle();return t.wrapping?t.wrapping:N}const DV=new kM;DV.add("cut",{...eL,sequence:10}).add("copy",{...QN,sequence:20}).add("paste",{...tL,sequence:30}).add("paste_special",{...sL,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...oL,sequence:10}).addChild("paste_format_only",["paste_special"],{...iL,sequence:20}).add("sort_columns",{...bk,name:e=>e.model.getters.getActiveCols().size>1?fs("Sort columns"):fs("Sort column"),sequence:50,separator:!0}).addChild("sort_ascending",["sort_columns"],{...Sk,sequence:10}).addChild("sort_descending",["sort_columns"],{...wk,sequence:20}).add("add_column_before",{...AL,sequence:70}).add("add_column_after",{...OL,sequence:80}).add("delete_column",{...hL,sequence:90,icon:"o-spreadsheet-Icon.TRASH"}).add("clear_column",{...uL,sequence:100,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_columns",{...wN,sequence:105,separator:!0}).add("unhide_columns",{...EN,sequence:106,separator:!0}).add("conditional_formatting",{...wV,sequence:110,separator:!0}).add("edit_table",{...vL,isVisible:mN,sequence:120}).add("delete_table",{...bL,isVisible:mN,sequence:125,separator:!0}).add("group_columns",{sequence:150,...BN}).add("ungroup_columns",{sequence:155,...WN,isVisible:e=>jN(e,"COL")});const _V={CannotHideAllRows:fs("Cannot hide all the rows of a sheet."),CannotHideAllColumns:fs("Cannot hide all the columns of a sheet.")};function OV(e,t,s,o,i){const n=e.model.getters.getHeaderGroup(t,s,o,i);if(!n)return;const r=n.isFolded?"UNFOLD_HEADER_GROUP":"FOLD_HEADER_GROUP",a=e.model.dispatch(r,{sheetId:t,dimension:s,start:n.start,end:n.end});if(!a.isSuccessful&&a.isCancelledBecause("NotEnoughElements")){const t="ROW"===s?_V.CannotHideAllRows:_V.CannotHideAllColumns;e.raiseError(t)}}function FV(e,t){return qf([{id:"unfold_all",name:fs("ROW"===t?"Expand all row groups":"Expand all column groups"),execute:s=>{s.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:e,dimension:t})},icon:"o-spreadsheet-Icon.EXPAND"},{id:"fold_all",name:fs("ROW"===t?"Collapse all row groups":"Collapse all column groups"),execute:s=>{s.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:e,dimension:t})},icon:"o-spreadsheet-Icon.COLLAPSE"}])}const PV=new kM;PV.add("group_columns",{sequence:10,...BN,isVisible:()=>!0,isEnabled:BN.isVisible}).add("group_rows",{sequence:20,...GN,isVisible:()=>!0,isEnabled:GN.isVisible});const MV=new kM;MV.add("ungroup_columns",{sequence:10,...WN,isEnabled:e=>jN(e,"COL")}).add("ungroup_rows",{sequence:20,...$N,isEnabled:e=>jN(e,"ROW")});const NV=new kM;NV.add("cut",{...eL,sequence:10}).add("copy",{...QN,sequence:20}).add("paste",{...tL,sequence:30}).add("paste_special",{...sL,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...oL,sequence:10}).addChild("paste_format_only",["paste_special"],{...iL,sequence:20}).add("add_row_before",{...IL,sequence:50}).add("add_row_after",{...RL,sequence:60}).add("delete_row",{...aL,sequence:70,icon:"o-spreadsheet-Icon.TRASH"}).add("clear_row",{...cL,sequence:80,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_rows",{...xN,sequence:85,separator:!0}).add("unhide_rows",{...TN,sequence:86,separator:!0}).add("conditional_formatting",{...wV,sequence:90,separator:!0}).add("group_rows",{sequence:100,...GN}).add("ungroup_rows",{sequence:110,...$N,isVisible:e=>jN(e,"ROW")});class LV extends hv{highlightStore=this.get(ZP);constructor(e){super(e),this.highlightStore.register(this)}get highlights(){const e=this.model.getters.getActivePosition(),t=this.getters.getEvaluatedCell(e),s=this.model.getters.getArrayFormulaSpreadingOn(e),o=s?this.model.getters.getSpreadZone(s,{ignoreSpillError:!0}):this.model.getters.getSpreadZone(e,{ignoreSpillError:!0});return o?[{range:this.model.getters.getRangeFromZone(e.sheetId,o),dashed:t.value===bs.SpilledBlocked,color:"#17A2B8",noFill:!0,thinLine:!0}]:[]}}class kV extends hv{mutators=["focusClient","unfocusClient","showClientTag","hideClientTag","jumpToClient"];_showClientTag=!1;clientFocusTimeout={};constructor(e){super(e),this.onDispose(()=>{for(const e in this.clientFocusTimeout)this.unfocusClient(e)})}get focusedClients(){const e=new Set;return this.model.getters.getConnectedClients().forEach(t=>{(this._showClientTag||void 0!==this.clientFocusTimeout[t.id])&&e.add(t.id)}),e}jumpToClient(e){const t=this.model.getters.getClient(e);this.focusClient(e),t.position&&(this.model.dispatch("ACTIVATE_SHEET",{sheetIdTo:t.position.sheetId,sheetIdFrom:this.getters.getActiveSheetId()}),this.model.dispatch("SCROLL_TO_CELL",{col:t.position.col,row:t.position.row}))}showClientTag(){this._showClientTag=!0}hideClientTag(){this._showClientTag=!1}focusClient(e){this.clientFocusTimeout[e]&&clearTimeout(this.clientFocusTimeout[e]),this.clientFocusTimeout[e]=setTimeout(()=>this.unfocusClient(e),3e3)}unfocusClient(e){this.clientFocusTimeout[e]&&clearTimeout(this.clientFocusTimeout[e]),this.clientFocusTimeout[e]=void 0}}function VV(e){let s,o,i,n,r=null,a="all";const l=e.model.getters;let c=[];const h=()=>{clearTimeout(r),r=null,c.forEach(e=>e()),c=[]};let d,u;const g=t=>{if(s=t,r)return;const c=l.getActiveSheetId(),h=_y(),{x:u,y:p}=l.getMainViewportCoordinates(),{top:m,left:f,bottom:v,right:b}=l.getActiveMainViewport();let{scrollX:S,scrollY:C}=l.getActiveSheetScrollInfo();const{xSplit:y,ySplit:I}=l.getPaneDivisions(c);let w=!1,E=140;const R=s.clientX-h.left;let x=l.getColIndex(R);if("vertical"!==a){const t=o.clientX-h.left,s=l.getEdgeScrollCol(R,t,i);if(s.canEdgeScroll){w=!0,E=Math.min(E,s.delay);let t=x;switch(s.direction){case"reset":x=t=y;break;case 1:x=b,t=f+1;break;case-1:for(x=f-1;e.model.getters.isColHidden(c,x);)x--;t=x}S=l.getColDimensions(c,t).start-u}}const T=s.clientY-h.top;let A=l.getRowIndex(T);if("horizontal"!==a){const t=o.clientY-h.top,s=l.getEdgeScrollRow(T,t,n);if(s.canEdgeScroll){w=!0,E=Math.min(E,s.delay);let t=A;switch(s.direction){case"reset":A=t=I;break;case 1:A=v,t=m+1;break;case-1:for(A=m-1;e.model.getters.isRowHidden(c,A);)A--;t=A}C=e.model.getters.getRowDimensions(c,t).start-p}}w||(x=UV(x,R,l.getNumberCols(c)-1),A=UV(A,T,l.getNumberRows(c)-1)),d?.(x,A,s),w&&(e.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:S,offsetY:C}),r=setTimeout(()=>{r=null,g(s)},Math.round(E))),o={clientX:s.clientX,clientY:s.clientY}},p=()=>{u?.(),h()};return t.onWillUnmount(()=>{h()}),t.useEffect(()=>{h()},()=>[l.getActiveSheetId()]),{start:(e,t,s,r="all")=>{h();const l=_y();a=r,i=e.clientX-l.left,n=e.clientY-l.top,o={clientX:e.clientX,clientY:e.clientY},d=t,u=s,c.push(iM(g,p))}}}function UV(e,t,s){return-1===e?t<0?0:s:e}class HV extends t.Component{static template="o-spreadsheet-Autofill";static props={position:Object,isVisible:Boolean};state=t.useState({position:{left:0,top:0},handler:!1});dragNDropGrid=VV(this.env);get style(){const{left:e,top:t}=this.props.position;return Ey({top:`${t}px`,left:`${e}px`,visibility:this.props.isVisible?"visible":"hidden"})}get handlerStyle(){const{left:e,top:t}=this.state.handler?this.state.position:this.props.position;return Ey({top:`${t}px`,left:`${e}px`})}get styleNextValue(){const{left:e,top:t}=this.state.position;return Ey({top:`${t+5}px`,left:`${e+15}px`})}getTooltip(){const e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=zV),e}onMouseDown(e){let t,s;this.state.handler=!0;const o=e.clientX-this.props.position.left,i=e.clientY-this.props.position.top;this.dragNDropGrid.start(e,(e,n,r)=>{if(this.state.position={left:r.clientX-o,top:r.clientY-i},t!==e||s!==n){const o=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getNumberCols(o),r=this.env.model.getters.getNumberRows(o);t=-1===e?t:ue(e,0,i),s=-1===n?s:ue(n,0,r),void 0!==t&&void 0!==s&&this.env.model.dispatch("AUTOFILL_SELECT",{col:t,row:s})}},()=>{this.state.handler=!1,this.state.position={...this.props.position},this.env.model.dispatch("AUTOFILL")})}onDblClick(){this.env.model.dispatch("AUTOFILL_AUTO")}}class zV extends t.Component{static props={content:String};static template=t.xml`
|
|
818
|
+
<div t-esc="props.content"/>
|
|
819
|
+
`}class BV extends t.Component{static template="o-spreadsheet-ClientTag";static props={active:Boolean,name:String,color:String,col:Number,row:Number};get tagStyle(){const{col:e,row:t,color:s}=this.props,{height:o}=this.env.model.getters.getSheetViewDimensionWithHeaders(),i=this.env.model.getters.isVisibleInViewport({sheetId:this.env.model.getters.getActiveSheetId(),col:e,row:t}),{x:n,y:r}=this.env.model.getters.getVisibleRect({left:e,top:t,right:e,bottom:t});return Ey({bottom:o-r+15+"px",left:n-1+"px",border:`1px solid ${s}`,"background-color":s,visibility:i?"visible":"hidden"})}}const GV=fs("The cell you are trying to edit has been deleted.");class WV extends XP{canStopEdition(){return"inactive"===this.editionMode||this.checkDataValidation()}stopEdition(e){if(this.canStopEdition())return this._stopEdition(),void(e&&this.model.selection.moveAnchorCell(e,1));const t=this.currentEditedCell,s=mt(t.col,t.row),o=this.getters.getValidationRuleForCell(t);if(!o)return;const i=QT.get(o.criterion.type).getErrorString(o.criterion,this.getters,t.sheetId);this.notificationStore.raiseError(fs("The data you entered in %s violates the data validation rule set on the cell:\n%s",s,i)),this.cancelEdition()}handle(e){switch(super.handle(e),e.type){case"SET_FORMATTING":this.cancelEdition();break;case"ADD_COLUMNS_ROWS":this.onAddElements(e);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case"ACTIVATE_SHEET":if(ot(this._currentContent)||(this._cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){const t=this.getters.getActivePosition(),{col:s,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),i=this.getters.expandZone(e.sheetIdTo,Zt({col:s,row:o}));this.model.selection.resetAnchor(this,{cell:{col:s,row:o},zone:i})}break;case"DELETE_SHEET":case"UNDO":case"REDO":!!this.getters.tryGetSheet(this.sheetId)||"inactive"===this.editionMode||(this.sheetId=this.getters.getActiveSheetId(),this.resetContent(),this.cancelEditionAndActivateSheet(),this.notificationStore.raiseError(GV))}}get placeholder(){const e=this.getters.getActivePosition(),t=this.model.getters.getArrayFormulaSpreadingOn(e);if(t)return this.getters.getCellText(t,{showFormula:!0})}get currentEditedCell(){return{sheetId:this.sheetId,col:this.col,row:this.row}}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.editionMode)return this.cancelEdition(),void this.notificationStore.raiseError(GV);const{top:t,left:s}=_t({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",[...e.elements]);this.col=s,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.editionMode)return this.cancelEdition(),void this.notificationStore.raiseError(GV);const{top:t,left:s}=_t({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",[...e.elements]);this.col=s,this.row=t}onAddElements(e){const{top:t,left:s}=Dt({left:this.col,right:this.col,top:this.row,bottom:this.row},"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.col=s,this.row=t}confirmEdition(e){if(e){const t=this.getters.getActiveSheetId(),s=this.getters.getEvaluatedCell({sheetId:t,col:this.col,row:this.row});s.link&&!ot(e)&&(e=ye(e,s.link.url)),this.addHeadersForSpreadingFormula(e),this.model.dispatch("UPDATE_CELL",{...this.currentEditedCell,content:e})}else this.model.dispatch("UPDATE_CELL",{...this.currentEditedCell,content:""});this.model.dispatch("AUTOFILL_TABLE_COLUMN",{...this.currentEditedCell}),this.setContent("")}getComposerContent(e,t){const s=this.getters.getLocale(),o=this.getters.getCell(e);if(o?.isFormula){const l=this.getPrettifiedFormula(o);function c(e){let t=0,s=0;for(;s<e;){t++;const e=l[t];"\n"!==e&&"\t"!==e&&s++}return t}let h=t;return t&&(h={start:c(t.start),end:c(t.end)}),{text:sh(l,s),adjustedSelection:h}}if(this.model.getters.getArrayFormulaSpreadingOn(e))return{text:""};if(o?.content.startsWith("'"))return{text:o.content};const{format:i,value:n,type:r,formattedValue:a}=this.getters.getEvaluatedCell(e);switch(r){case _d.empty:return{text:""};case _d.text:case _d.error:return{text:n};case _d.boolean:return{text:a};case _d.number:if(i&&wn(i)){if(null!==Zs(a,s))return{text:a};return{text:pn(n,{locale:s,format:Number.isInteger(n)?s.dateFormat:hh(s)})}}return{text:this.numberComposerContent(n,i,s)}}}getPrettifiedFormula(e){if(e.compiledFormula.isBadExpression)return e.content;const t="inactive"===this.editionMode?1/0:80;return yD(_f(e.compiledFormula.tokens),t)}numberComposerContent(e,t,s){return t?.includes("%")?`${In(100*e,s.decimalSeparator)}%`:In(e,s.decimalSeparator)}addHeadersForSpreadingFormula(e){if(!ot(e))return;const t=this.getters.evaluateFormula(this.sheetId,e);if(!Ds(t))return;const s=this.getters.getNumberRows(this.sheetId),o=this.getters.getNumberCols(this.sheetId),i=this.row+t[0].length-s,n=this.col+t.length-o;n>0&&this.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:this.sheetId,sheetName:this.getters.getSheetName(this.sheetId),dimension:"COL",base:o-1,position:"after",quantity:n+20}),i>0&&this.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:this.sheetId,sheetName:this.getters.getSheetName(this.sheetId),dimension:"ROW",base:s-1,position:"after",quantity:i+50})}checkDataValidation(){const e={sheetId:this.sheetId,col:this.col,row:this.row},t=this.getCurrentCanonicalContent(),s=ot(t)?this.getters.evaluateFormula(this.sheetId,t):Xv(t,this.getters.getLocale());if(bi(s))return!0;const o=this.getters.getValidationResultForCellValue(fi(s),e);return!(!o.isValid&&o.rule.isBlocking)}}const $V=3*.4*window.devicePixelRatio||1;class qV extends t.Component{static template="o-spreadsheet-GridComposer";static props={gridDims:Object,onInputContextMenu:Function};static components={Composer:zP};rect=this.defaultRect;isEditing=!1;isCellReferenceVisible=!1;currentEditedCell={col:0,row:0,sheetId:this.env.model.getters.getActiveSheetId()};composerStore;composerFocusStore;composerInterface;get defaultRect(){return{x:0,y:0,width:0,height:0}}setup(){const e=ev(WV);this.composerStore=e,this.composerFocusStore=ev(uv),this.composerInterface={id:"gridComposer",get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition},this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"inactive"}),t.onWillUpdateProps(()=>{this.updateComponentPosition(),this.updateCellReferenceVisibility()})}get shouldDisplayCellReference(){return!this.env.isMobile()&&this.isCellReferenceVisible}get cellReference(){const{col:e,row:t,sheetId:s}=this.composerStore.currentEditedCell;return sr(s!==this.env.model.getters.getActiveSheetId()?this.env.model.getters.getSheetName(s):void 0,mt(e,t))}get cellReferenceStyle(){const{x:e,y:t}=this.rect;return Ey({left:e-$V+"px",top:t-28+"px"})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get composerProps(){const{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders(),s=this.props.gridDims.height-this.rect.y-2*$V;return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,isDefaultFocus:!0,onComposerContentFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus",selection:e}),onComposerCellFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"cellFocus",content:e}),onInputContextMenu:this.props.onInputContextMenu,composerStore:this.composerStore,inputStyle:`max-height: ${s}px;`,inputMode:"inactive"===this.composerStore.editionMode?"none":void 0}}get containerStyle(){if("inactive"===this.composerStore.editionMode||this.env.isMobile())return"z-index: -1000; opacity: 0;";const e=ot(this.composerStore.currentContent),t=this.env.model.getters.getActiveCell(),s=this.env.model.getters.getActivePosition(),o=this.env.model.getters.getCellComputedStyle(s),{x:i,y:n,width:r,height:a}=this.rect,c=!e&&o.fillColor||"#ffffff",h=!e&&o.textColor||"#000000",d=!e&&o.fontSize||10,u=!e&&o.bold?"bold":void 0,g=!e&&o.italic?"italic":"normal",p=e?"none":yy(o);let m="left";e||(m=o.align||t.defaultAlign);const f=this.props.gridDims.height-this.rect.y,v=this.props.gridDims.width-this.rect.x,b=Math.min(a+1,f),S=Math.min(r+1,v);return Ey({left:i-1+"px",top:`${n}px`,border:`${$V}px solid ${l}`,"min-width":`${S}px`,"min-height":`${b}px`,"max-width":`${v}px`,"max-height":`${f}px`,background:c,color:h,"font-size":`${$b(d)}px`,"font-weight":u,"font-style":g,"text-decoration":p,"text-align":m})}updateComponentPosition(){const e="inactive"!==this.composerFocusStore.activeComposer.editionMode;e||this.composerFocusStore.activeComposer===this.composerInterface||this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"inactive"});let t=!Me(this.currentEditedCell,this.composerStore.currentEditedCell);if(this.isEditing!==e){if(this.isEditing=e,!e)return void(this.rect=this.defaultRect);this.currentEditedCell=this.composerStore.currentEditedCell,t=!0}if(t){const e=this.env.model.getters.getActivePosition(),t=this.env.model.getters.expandZone(e.sheetId,Zt(e));this.rect=this.env.model.getters.getVisibleRect(t)}}updateCellReferenceVisibility(){if("inactive"===this.composerStore.editionMode)return void(this.isCellReferenceVisible=!1);if(this.isCellReferenceVisible)return;const e=this.env.model.getters.getActiveSheetId(),t=Zt(this.env.model.getters.getSelection().anchor.cell);Me(this.env.model.getters.getVisibleRect(t),this.rect)&&e===this.composerStore.currentEditedCell.sheetId||(this.isCellReferenceVisible=!0)}onFocus(){this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"})}}function ZV(e,t,s){return s.map(s=>XV(e,t,!1,s)).filter(s=>function(e,t,s){const{x:o,y:i}=e.getMainViewportCoordinates(),n=[];switch(s.axisType){case"top":case"bottom":case"vCenter":if(t.y<i)return!0;n.push({x:t.x,y:s.position}),n.push({x:t.x+t.width,y:s.position});break;case"left":case"right":case"hCenter":if(t.x<o)return!0;n.push({x:s.position,y:t.y}),n.push({x:s.position,y:t.y+t.height})}return n.some(e.isPixelPositionVisible)}(e,t,s))}function jV(e,t,s,o,i){const n=s.map(s=>XV(e,t,!0,s));let r;for(const t of o){const s=ZV(e,t,i);for(const e of n)for(const o of s){if(!YV(e.position,o.position))continue;const s=e.position-o.position;r&&s===r.snapOffset?r.matchedFigIds.push(t.id):(!r||Math.abs(s)<=Math.abs(r.snapOffset))&&(r={matchedFigIds:[t.id],snapOffset:s,snappedAxisType:e.axisType,position:o.position})}}return r}function YV(e,t){return Math.abs(e-t)<=5}function XV(e,t,s,o){let i=0;const{scrollX:n,scrollY:r}=e.getActiveSheetScrollInfo(),{x:a,y:l}=e.getMainViewportCoordinates(),c=!s&&t.y<l?t.y+r:t.y,h=!s&&t.x<a?t.x+n:t.x;switch(o){case"top":i=c;break;case"bottom":i=c+t.height-1;break;case"vCenter":i=c+Math.floor(t.height/2)-1;break;case"left":i=h;break;case"right":i=h+t.width-1;break;case"hCenter":i=h+Math.floor(t.width/2)-1}return{position:i,axisType:o}}class KV extends t.Component{static template="o-spreadsheet-FiguresContainer";static props={onFigureDeleted:Function};static components={FigureComponent:UF};dnd=t.useState({draggedFigure:void 0,horizontalSnap:void 0,verticalSnap:void 0,cancelDnd:void 0,overlappingCarousel:void 0});setup(){t.onMounted(()=>{this.render()}),t.onWillUpdateProps(()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.dnd.draggedFigure?.id;t&&!this.env.model.getters.getFigure(e,t)&&(this.dnd.cancelDnd&&this.dnd.cancelDnd(),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0,this.dnd.cancelDnd=void 0)})}getVisibleFigures(){const e=this.env.model.getters.getVisibleFigures();return this.dnd.draggedFigure&&!e.some(e=>e.id===this.dnd.draggedFigure?.id)&&this.dnd.draggedFigure&&e.push(this.dnd.draggedFigure),e}get containers(){const e=this.getVisibleFigures(),t=[];for(const s of["topLeft","topRight","bottomLeft","bottomRight"]){const o=e.filter(e=>this.getFigureContainer(e)===s);o.length>0&&t.push({type:s,figures:o,style:this.getContainerStyle(s),inverseViewportStyle:this.getInverseViewportPositionStyle(s)})}return this.dnd.draggedFigure&&t.push({type:"dnd",figures:[this.getDndFigure()],style:this.getContainerStyle("dnd"),inverseViewportStyle:this.getInverseViewportPositionStyle("dnd")}),t}getContainerStyle(e){return this.rectToCss(this.getContainerRect(e))}rectToCss(e){return Ey({left:`${e.x}px`,top:`${e.y}px`,width:`${e.width}px`,height:`${e.height}px`})}getContainerRect(e){const{width:t,height:s}=this.env.model.getters.getSheetViewDimension(),{x:o,y:i}=this.env.model.getters.getMainViewportCoordinates(),n=["bottomRight","topRight"].includes(e)?o:0,r=t-n,a=["bottomRight","bottomLeft"].includes(e)?i:0;return{x:n,y:a,width:r,height:s-a}}getInverseViewportPositionStyle(e){const{scrollX:t,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo(),{x:o,y:i}=this.env.model.getters.getMainViewportCoordinates();let n=0,r=0;return"dnd"===e&&(n=-t,r=-s),["bottomRight","topRight"].includes(e)&&(n=-t-o),["bottomRight","bottomLeft"].includes(e)&&(r=-s-i),Ey({left:`${n}px`,top:`${r}px`})}getFigureContainer(e){const{x:t,y:s}=this.env.model.getters.getMainViewportCoordinates();return e.id===this.dnd.draggedFigure?.id?"dnd":e.x<t&&e.y<s?"topLeft":e.x<t?"bottomLeft":e.y<s?"topRight":"bottomRight"}toBottomRightViewport(e){const t=this.getFigureContainer(e),s=this.env.model.getters.getActiveSheetScrollInfo(),o={...e};return["bottomLeft","topLeft"].includes(t)&&(o.x+=s.scrollX),["topLeft","topRight"].includes(t)&&(o.y+=s.scrollY),o}startDraggingFigure(e,t){if(t.button>0||this.env.model.getters.isReadonly())return;if(!this.env.model.dispatch("SELECT_FIGURE",{figureId:e.id}).isSuccessful)return;if(this.env.isMobile())return;const s=this.env.model.getters.getActiveSheetId(),o={x:t.clientX,y:t.clientY},i=this.env.model.getters.getActiveSheetScrollInfo(),n=this.toBottomRightViewport(e),r={maxX:this.env.model.getters.getColDimensions(s,this.env.model.getters.getNumberCols(s)-1).end,maxY:this.env.model.getters.getRowDimensions(s,this.env.model.getters.getNumberRows(s)-1).end};let a=!1;this.dnd.cancelDnd=iM(e=>{const t=this.env.model.getters,s={x:e.clientX,y:e.clientY},l=Math.abs(s.x-o.x),c=Math.abs(s.y-o.y);if(!a&&l<5&&c<5)return;a=!0;const h=function({x:e,y:t},{x:s,y:o},i,{maxX:n,maxY:r},{scrollX:a,scrollY:l},{scrollX:c,scrollY:h}){const d=e-s+c-a,u=ue(i.x+d,0,n-i.width),g=t-o+h-l,p=ue(i.y+g,0,r-i.height);return{...i,x:u,y:p}}(s,o,n,r,i,t.getActiveSheetScrollInfo()),d=this.getOtherFigures(n.id),u=this.getCarouselOverlappingChart(h,d);if(this.dnd.overlappingCarousel=u,u)this.dnd.draggedFigure=h,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0;else{const e=function(e,t,s){const o=jV(e,t,["hCenter","right","left"],s,["hCenter","right","left"]),i=jV(e,t,["vCenter","bottom","top"],s,["vCenter","bottom","top"]),{y:n,x:r}=e.getMainViewportCoordinates(),{scrollY:a,scrollX:l}=e.getActiveSheetScrollInfo();if(i){t.y-=i.snapOffset;const e=t.y<n,s=t.y<n;e&&!s?t.y+=a:!e&&s&&(t.y-=a)}if(o){t.x-=o.snapOffset;const e=t.x<r,s=t.x<r;e&&!s?t.x+=l:!e&&s&&(t.x-=l)}return{snappedFigure:t,verticalSnapLine:o,horizontalSnapLine:i}}(t,h,d);this.dnd.draggedFigure=e.snappedFigure,this.dnd.horizontalSnap=this.getSnap(e.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(e.verticalSnapLine)}},t=>{if(!this.dnd.draggedFigure)return;const{col:o,row:i,offset:n}=this.env.model.getters.getPositionAnchorOffset(this.dnd.draggedFigure);this.dnd.overlappingCarousel?(this.env.model.dispatch("ADD_FIGURE_CHART_TO_CAROUSEL",{sheetId:s,carouselFigureId:this.dnd.overlappingCarousel.id,chartFigureId:e.id}),this.props.onFigureDeleted()):this.env.model.dispatch("UPDATE_FIGURE",{sheetId:s,figureId:e.id,offset:n,col:o,row:i}),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0})}startResize(e,t,s,o){o.stopPropagation();const i={x:o.clientX,y:o.clientY},n=this.env.model.getters.getActiveSheetScrollInfo(),r=VF.get(e.tag).keepRatio||!1,a=VF.get(e.tag).minFigSize||80,l=this.env.model.getters.getActiveSheetId(),c={maxX:this.env.model.getters.getColDimensions(l,this.env.model.getters.getNumberCols(l)-1).end,maxY:this.env.model.getters.getRowDimensions(l,this.env.model.getters.getNumberRows(l)-1).end};this.dnd.cancelDnd=iM(o=>{const l={x:o.clientX,y:o.clientY},h=function(e,t,s,{x:o,y:i},{x:n,y:r},a,l,{scrollX:c,scrollY:h},{scrollX:d,scrollY:u},{maxX:g,maxY:p}){let{x:m,y:f,width:v,height:b}=e;if(a&&0!==t&&0!==s){const e=Math.min(t*(n-o+d-c),v-l),a=Math.min(s*(r-i+u-h),b-l),g=Math.min(e/v,a/b);t<0&&(m+=v*g),s<0&&(f+=b*g),v*=1-g,b*=1-g}else{const e=Math.max(t*(o-n+d-c),l-v),a=Math.max(s*(i-r+u-h),l-b);v+=e,b+=a,t<0&&(m-=e),s<0&&(f-=a)}return m+d<=0?(v=v+m+d,m=-d):m+v>g&&(v=g-m),f+u<=0?(b=b+f+u,f=-u):f+b>p&&(b=p-f),{...e,x:m,y:f,width:v,height:b}}(e,t,s,l,i,r,a,n,this.env.model.getters.getActiveSheetScrollInfo(),c),d=this.getOtherFigures(e.id),u=function(e,t,s,o,i){const n=jV(e,o,[-1===t?"left":"right"],i,["right","left"]);n&&(1===t?o.width-=n.snapOffset:-1===t&&(o.x-=n.snapOffset,o.width+=n.snapOffset));const r=jV(e,o,[-1===s?"top":"bottom"],i,["bottom","top"]);return r&&(1===s?o.height-=r.snapOffset:-1===s&&(o.y-=r.snapOffset,o.height+=r.snapOffset)),o.x=Math.round(o.x),o.y=Math.round(o.y),o.height=Math.round(o.height),o.width=Math.round(o.width),{snappedFigure:o,verticalSnapLine:n,horizontalSnapLine:r}}(this.env.model.getters,t,s,h,d);this.dnd.draggedFigure=u.snappedFigure,this.dnd.horizontalSnap=this.getSnap(u.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(u.verticalSnapLine)},o=>{if(!this.dnd.draggedFigure)return;const i=this.env.model.getters.getPositionAnchorOffset(this.dnd.draggedFigure);t&&(i.width=this.dnd.draggedFigure.width),s&&(i.height=this.dnd.draggedFigure.height),this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),figureId:e.id,...i}),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0})}getOtherFigures(e){return this.getVisibleFigures().filter(t=>t.id!==e)}getDndFigure(){const e=this.dnd.draggedFigure;if(!e)throw new Error("Dnd figure not found");return e}getFigureStyle(e){return e.id!==this.dnd.draggedFigure?.id?"":Ey({opacity:this.dnd.overlappingCarousel?.id?"0.6":"0.9",cursor:"grabbing"})}getFigureClass(e){return e.id!==this.dnd.overlappingCarousel?.id?"":"o-add-to-carousel"}getSnap(e){if(!e||!this.dnd.draggedFigure)return;const{scrollX:t,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo(),o=e.matchedFigIds.map(e=>this.getVisibleFigures().find(t=>t.id===e)).filter(Te).map(e=>({x:e.x-t,y:e.y-s,width:e.width,height:e.height})).filter(Te),i=function(...e){return TF(Ft(...e.map(xF)))}({...this.dnd.draggedFigure,x:this.dnd.draggedFigure.x-t,y:this.dnd.draggedFigure.y-s},...o);return{line:e,containerStyle:this.rectToCss(i),lineStyle:this.getSnapLineStyle(e,i)}}getSnapLineStyle(e,t){if(!e)return"";const{scrollX:s,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo();return["top","vCenter","bottom"].includes(e.snappedAxisType)?Ey({top:e.position-t.y-o+"px",left:"0px",width:"100%"}):Ey({top:"0px",left:e.position-t.x-s+"px",height:"100%"})}getCarouselOverlappingChart(e,t){if("chart"!==e.tag)return;const s=e.x+e.width/2,o=e.y+e.height/2;let i,n=1/0;for(const r of t){if("carousel"!==r.tag)continue;const t=r.x+r.width/2,a=r.y+r.height/2,l=Math.abs(s-t),c=Math.abs(o-a),h=l**2+c**2;l<=e.width/2&&c<=e.height/2&&h<n&&(n=h,i=r)}return i}}class JV extends t.Component{static template="o-spreadsheet-ValidationMessages";static props={messages:Array,msgType:String,singleBox:{type:Boolean,optional:!0}};get divClasses(){return"warning"===this.props.msgType?"o-validation-warning":"info"===this.props.msgType?"o-validation-info":"o-validation-error"}get alertBoxes(){return this.props.singleBox?[this.props.messages]:this.props.messages.map(e=>[e])}}class QV extends t.Component{static template="o-spreadsheet-GridAddRowsFooter";static props={focusGrid:Function};static components={ValidationMessages:JV};inputRef=t.useRef("inputRef");state=t.useState({inputValue:"100",errorFlag:!1});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}get addRowsPosition(){const e=this.env.model.getters.getActiveSheetId(),{numberOfRows:t}=this.env.model.getters.getSheetSize(e),{scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo();return Ey({top:`${this.env.model.getters.getRowDimensions(e,t-1).end-s}px`})}get errorMessages(){return[fs("Please enter a number between 0 and 10000.")]}onKeydown(e){"ESCAPE"===e.key.toUpperCase()?this.props.focusGrid():"ENTER"===e.key.toUpperCase()&&this.onConfirm()}onInput(e){const t=e.target.value;this.state.inputValue=t;const s=Number(t);this.state.errorFlag=Number.isNaN(s)||s<=0||s>1e4}onConfirm(){if(this.state.errorFlag)return;const e=Number(this.state.inputValue),t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getNumberRows(t);this.env.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:t,sheetName:this.env.model.getters.getSheetName(t),position:"after",base:s-1,quantity:e,dimension:"ROW"}),this.props.focusGrid();const{scrollX:o}=this.env.model.getters.getActiveSheetScrollInfo(),{end:i}=this.env.model.getters.getRowDimensions(t,s+e-1);this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o,offsetY:i})}onExternalClick(e){this.inputRef.el===document.activeElement&&e.target!==this.inputRef.el&&this.props.focusGrid()}}function eU(e,...s){t.useEffect(e=>(e?.addEventListener(...s),()=>e?.removeEventListener(...s)),()=>[e.el])}const tU=["cell","border","table","conditionalFormat","merge"];class sU extends hv{mutators=["activate","cancel","pasteFormat"];highlightStore=this.get(ZP);status="inactive";copiedData;constructor(e){super(e),this.highlightStore.register(this),this.onDispose(()=>{this.highlightStore.unRegister(this)})}handle(e){if("PAINT_FORMAT"===e.type)this.paintFormat(e.sheetId,e.target)}activate(e){this.copiedData=this.copyFormats(),this.status=e.persistent?"persistent":"oneOff"}cancel(){this.status="inactive",this.copiedData=void 0}pasteFormat(e){this.model.dispatch("PAINT_FORMAT",{target:e,sheetId:this.getters.getActiveSheetId()})}get isActive(){return"inactive"!==this.status}get clipboardHandlers(){return tU.map(e=>({handlerName:e,handler:new(T_.cellHandlers.get(e))(this.getters,this.model.dispatch)}))}copyFormats(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones(),s={zones:t,sheetId:e};for(const{handlerName:o,handler:i}of this.clipboardHandlers){const n=i.copy(C_(e,t),!1);void 0!==n&&(s[o]=n)}return s}paintFormat(e,t){if(!this.copiedData)return;const s={isCutOperation:!1,pasteOption:"onlyFormat"},{target:o,selectedZones:i}=R_(e,t,this.copiedData,this.clipboardHandlers,s);E_(this.clipboardHandlers,this.copiedData,o,s),x_(this.model.selection,t,i),"oneOff"===this.status&&this.cancel()}get highlights(){const e=this.copiedData;return e?e.zones.map(t=>({range:this.model.getters.getRangeFromZone(e.sheetId,t),color:l,dashed:!0,sheetId:e.sheetId,noFill:!0,thinLine:!0,interactive:!1})):[]}}class oU extends hv{mutators=["clear","hover"];col;row;overlayColors=new YT;handle(e){if("ACTIVATE_SHEET"===e.type)this.clear()}hover(e){if(!this.getters.isDashboard()||e.col===this.col&&e.row===this.row)return"noStateChange";this.col=e.col,this.row=e.row,this.computeOverlay()}clear(){this.col=void 0,this.row=void 0}computeOverlay(){this.overlayColors=new YT;const{col:e,row:t}=this;if(void 0===e||void 0===t)return;const s=this.getters.getActiveSheetId(),o=this.getters.getTable({sheetId:s,col:e,row:t});if(!o)return;const{left:i,right:n,top:r}=o.range.zone,a=t<r+o.config.numberOfHeaders,l=ge(i,n+1).some(e=>!this.getters.isColHidden(s,e)&&this.getters.getEvaluatedCell({sheetId:s,col:e,row:t}).formattedValue);if(!a&&l)for(let e=i;e<=n;e++)this.overlayColors.set({sheetId:s,col:e,row:t},"#017E8414")}}class iU extends hv{mutators=["setHoveredIcon"];hoveredIcon=void 0;setHoveredIcon(e){this.hoveredIcon=e}}function nU(e,s){const o=ev(HF),i=ev(oU),n={col:void 0,row:void 0},{Date:r}=window;let a,l,c=0;function h(){if(void 0===a||void 0===l)return{col:-1,row:-1};return{col:e.model.getters.getColIndex(a),row:e.model.getters.getRowIndex(l)}}function d(e){const t=Fy(s.el);return{x:e.clientX-t.x,y:e.clientY-t.y}}const{pause:u,resume:g}=function(e,s){let o;const{setInterval:i,clearInterval:n}=window,r=()=>{n(o),o=void 0},a=()=>{try{e()}catch(e){throw r(),e}};return t.useEffect(()=>(o=i(a,s),()=>n(o)),()=>[s]),{pause:r,resume:()=>{void 0===o&&(o=i(a,s))}}}(function(){const{col:e,row:t}=h(),s=r.now()-c;s>300&&(e!==n.col||t!==n.row)&&m(void 0,void 0);if(s>300){if(e<0||t<0)return;m(e,t)}},200);function p(e){Dy(s.el,e)&&(({x:a,y:l}=d(e)),c=r.now(),i.hover(h()))}function m(e,t){e===n.col&&t===n.row||(n.col=e,n.row=t,o.hover({col:e,row:t}))}return eU(s,"pointermove",t=>!e.isMobile()&&p(t)),eU(s,"mouseleave",function(e){const{x:t,y:o}=d(e),i=Fy(s.el);return o<0||o>i.height||t<0||t>i.width?p(e):u()}),eU(s,"mouseenter",g),eU(s,"pointerdown",function(){const{col:e,row:t}=h();e===n.col&&t===n.row||m(void 0,void 0)}),eU(s,"pointerdown",t=>e.isMobile()&&p(t)),t.useExternalListener(window,"click",function(e){const t=e.target;s.el.contains(t)||m(void 0,void 0)}),n}class rU extends t.Component{static template="o-spreadsheet-GridOverlay";static props={onCellDoubleClicked:{type:Function,optional:!0},onCellClicked:{type:Function,optional:!0},onCellRightClicked:{type:Function,optional:!0},onGridResized:{type:Function,optional:!0},onFigureDeleted:{type:Function,optional:!0},onGridMoved:Function,gridOverlayDimensions:String,slots:{type:Object,optional:!0},getGridSize:Function};static components={FiguresContainer:KV,GridAddRowsFooter:QV};static defaultProps={onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{},onFigureDeleted:()=>{}};gridOverlay=t.useRef("gridOverlay");cellPopovers;paintFormatStore;hoveredIconStore;setup(){nU(this.env,this.gridOverlay);const e=new ResizeObserver(()=>{const e=this.gridOverlayEl.getBoundingClientRect(),{width:t,height:s}=this.props.getGridSize();this.props.onGridResized({x:e.left,y:e.top,height:s,width:t})});t.onMounted(()=>{e.observe(this.gridOverlayEl)}),t.onWillUnmount(()=>{e.disconnect()}),this.cellPopovers=ev(wP),this.paintFormatStore=ev(sU),this.hoveredIconStore=ev(iU)}get gridOverlayEl(){if(!this.gridOverlay.el)throw new Error("GridOverlay el is not defined.");return this.gridOverlay.el}get style(){return this.props.gridOverlayDimensions+Ey({cursor:this.hoveredIconStore.hoveredIcon?"pointer":"default"})}get isPaintingFormat(){return this.paintFormatStore.isActive}onPointerMove(e){if(this.env.isMobile())return;const t=this.getInteractiveIconAtEvent(e),s=t?.type?{id:t.type,position:t.position}:void 0;Me(s,this.hoveredIconStore.hoveredIcon)||this.hoveredIconStore.setHoveredIcon(s)}onPointerDown(e){e.button>0||this.env.isMobile()||this.onCellClicked(e)}onClick(e){e.button>0||!this.env.isMobile()||this.onCellClicked(e)}onCellClicked(e){const t=this.cellPopovers.persistentCellPopover,[s,o]=this.getCartesianCoordinates(e),i=this.getInteractiveIconAtEvent(e);i&&this.env.model.selection.getBackToDefault(),this.props.onCellClicked(s,o,{expandZone:e.shiftKey,addZone:Uy(e)},e),i?.onClick&&i.onClick(i.position,this.env),e.target===this.gridOverlay.el&&this.cellPopovers.isOpen&&Me(t,this.cellPopovers.persistentCellPopover)&&this.cellPopovers.close()}onDoubleClick(e){if(this.getInteractiveIconAtEvent(e))return;const[t,s]=this.getCartesianCoordinates(e);this.props.onCellDoubleClicked(t,s)}onContextMenu(e){const[t,s]=this.getCartesianCoordinates(e);this.props.onCellRightClicked(t,s,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){const t=Oy(this.gridOverlay),s=e.clientX-t.x,o=e.clientY-t.y;return[this.env.model.getters.getColIndex(s),this.env.model.getters.getRowIndex(o)]}getInteractiveIconAtEvent(e){const t=Oy(this.gridOverlay),s=this.env.model.getters.getGridOffset(),o=e.clientX-t.x+s.x,i=e.clientY-t.y+s.y,[n,r]=this.getCartesianCoordinates(e),a=this.env.model.getters.getActiveSheetId();let l={col:n,row:r,sheetId:a};const c=this.env.model.getters.getMerge(l);c&&(l={col:c.left,row:c.top,sheetId:a});const h=this.env.model.getters.getCellIcons(l).find(e=>{const t=this.env.model.getters.getMerge(l)||Zt(l),s=this.env.model.getters.getRect(t);return function(e,t,s){return e>=s.x&&e<=s.x+s.width&&t>=s.y&&t<=s.y+s.height}(o,i,this.env.model.getters.getCellIconRect(e,s))});return h?.onClick?h:void 0}}class aU extends t.Component{static template="o-spreadsheet-GridPopover";static props={onClosePopover:Function,onMouseWheel:Function,gridRect:Object};static components={Popover:DF};cellPopovers;setup(){this.cellPopovers=ev(wP)}get cellPopover(){const e=this.cellPopovers.cellPopover;if(!e.isOpen)return{isOpen:!1};const t=e.anchorRect;return{...e,anchorRect:{...t,x:t.x+this.props.gridRect.x,y:t.y+this.props.gridRect.y}}}}class lU extends t.Component{static template="o-spreadsheet-UnhideRowHeaders";static props={headersGroups:Array,headerRange:Object,offset:{type:Number,optional:!0}};static defaultProps={offset:0};get sheetId(){return this.env.model.getters.getActiveSheetId()}getUnhidePreviousButtonStyle(e){const t=this.env.model.getters.getRect(Zt({col:0,row:e}));return Ey({top:t.y+t.height-A-this.props.offset+"px","margin-right":"1px"})}getUnhideNextButtonStyle(e){return Ey({top:this.env.model.getters.getRect(Zt({col:0,row:e})).y-A-this.props.offset+"px","margin-right":"1px"})}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.sheetId,dimension:"ROW",elements:e})}isVisible(e){return e>=this.props.headerRange.start&&e<=this.props.headerRange.end}}class cU extends t.Component{static template="o-spreadsheet-UnhideColumnHeaders";static props={headersGroups:Array,headerRange:Object,offset:{type:Number,optional:!0}};static defaultProps={offset:0};get sheetId(){return this.env.model.getters.getActiveSheetId()}getUnhidePreviousButtonStyle(e){const t=this.env.model.getters.getRect(Zt({col:e,row:0}));return Ey({left:t.x+t.width-D-this.props.offset+"px"})}getUnhideNextButtonStyle(e){return Ey({left:this.env.model.getters.getRect(Zt({col:e,row:0})).x-D-this.props.offset+"px"})}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.sheetId,dimension:"COL",elements:e})}isVisible(e){return e>=this.props.headerRange.start&&e<=this.props.headerRange.end}}class hU extends t.Component{static props={onOpenContextMenu:Function};composerFocusStore;PADDING=0;MAX_SIZE_MARGIN=0;MIN_ELEMENT_SIZE=0;lastSelectedElementIndex=null;state=t.useState({resizerIsActive:!1,isResizing:!1,isMoving:!1,isSelecting:!1,waitingForMove:!1,activeElement:0,draggerLinePosition:0,draggerShadowPosition:0,draggerShadowThickness:0,delta:0,base:0,position:"before"});dragNDropGrid=VV(this.env);setup(){this.composerFocusStore=ev(uv)}_computeHandleDisplay(e){const t=this._getEvOffset(e),s=this._getElementIndex(t);if(s<0)return;const o=this._getDimensionsInViewport(s);t-o.start<this.PADDING&&s!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=o.start,this.state.activeElement=this._getPreviousVisibleElement(s)):o.end-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=o.end,this.state.activeElement=s):this.state.resizerIsActive=!1}_computeGrabDisplay(e){const t=this._getElementIndex(this._getEvOffset(e)),s=this._getActiveElements(),o=this._getSelectedZoneStart(),i=this._getSelectedZoneEnd();s.has(o)&&o<=t&&t<=i?this.state.waitingForMove=!0:this.state.waitingForMove=!1}onMouseMove(e){this.env.isMobile()||this.state.isResizing||this.state.isMoving||this.state.isSelecting||(this._computeHandleDisplay(e),this._computeGrabDisplay(e))}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(e){this._fitElementSize(this.state.activeElement),this.state.isResizing=!1,this._computeHandleDisplay(e),this._computeGrabDisplay(e)}onMouseDown(e){this.state.isResizing=!0,this.state.delta=0;const t=this._getClientPosition(e),s=this.state.draggerLinePosition,o=this._getElementSize(this.state.activeElement),i=s-o+this.MIN_ELEMENT_SIZE,n=this._getMaxSize();iM(e=>{this.state.delta=this._getClientPosition(e)-t,this.state.draggerLinePosition=s+this.state.delta,this.state.draggerLinePosition<i&&(this.state.draggerLinePosition=i,this.state.delta=this.MIN_ELEMENT_SIZE-o),this.state.draggerLinePosition>n&&(this.state.draggerLinePosition=n,this.state.delta=n-s)},e=>{this.state.isResizing=!1,0!==this.state.delta&&this._updateSize()})}onClick(e){if(!this.env.isMobile())return;if(e.button>0)return;const t=this._getElementIndex(this._getEvOffset(e));this._selectElement(t,!1)}select(e){if(this.env.isMobile())return;if(e.button>0)return;const t=this._getElementIndex(this._getEvOffset(e));t<0||(this.state.waitingForMove?this.env.model.getters.isGridSelectionActive()?this.startMovement(e):this._selectElement(t,!1):("editing"===this.composerFocusStore.activeComposer.editionMode&&this.env.model.selection.getBackToDefault(),this.startSelection(e,t)))}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;const t=this._getDimensionsInViewport(this._getSelectedZoneStart()),s=this._getDimensionsInViewport(this._getSelectedZoneEnd()),o=t.start;this.state.draggerLinePosition=o,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=o,this.state.draggerShadowThickness=s.end-t.start;this.dragNDropGrid.start(e,(e,s)=>{const o="COL"===this._getType()?e:s;if(o>=0){const e=this._getDimensionsInViewport(o);o<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=e.start,this.state.draggerShadowPosition=e.start,this.state.base=o,this.state.position="before"):this._getSelectedZoneEnd()<o?(this.state.draggerLinePosition=e.end,this.state.draggerShadowPosition=e.end-this.state.draggerShadowThickness,this.state.base=o,this.state.position="after"):(this.state.draggerLinePosition=t.start,this.state.draggerShadowPosition=t.start,this.state.base=this._getSelectedZoneStart())}},()=>{this.state.isMoving=!1,this.state.base!==this._getSelectedZoneStart()&&this._moveElements(),this._computeGrabDisplay(e)})}startSelection(e,t){if(this.env.isMobile())return;this.state.isSelecting=!0,e.shiftKey?this._increaseSelection(t):this._selectElement(t,Uy(e)),this.lastSelectedElementIndex=t;this.dragNDropGrid.start(e,(e,t)=>{const s="COL"===this._getType()?e:t;s!==this.lastSelectedElementIndex&&-1!==s&&(this._increaseSelection(s),this.lastSelectedElementIndex=s)},()=>{this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this._computeGrabDisplay(e)})}onMouseUp(e){this.lastSelectedElementIndex=null}onContextMenu(e){e.preventDefault();const t=this._getElementIndex(this._getEvOffset(e));if(t<0)return;this._getActiveElements().has(t)||this._selectElement(t,!1);const s=this._getType();this.props.onOpenContextMenu(s,e.clientX,e.clientY)}}class dU extends hU{static props={onOpenContextMenu:Function};static template="o-spreadsheet-ColResizer";static components={UnhideColumnHeaders:cU};colResizerRef;setup(){super.setup(),this.colResizerRef=t.useRef("colResizer"),this.PADDING=15,this.MAX_SIZE_MARGIN=90,this.MIN_ELEMENT_SIZE=5}get sheetId(){return this.env.model.getters.getActiveSheetId()}_getEvOffset(e){return e.offsetX}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().left}_getClientPosition(e){return e.clientX}_getElementIndex(e){return this.env.model.getters.getColIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().left}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().right}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollCol(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getColDimensionsInViewport(this.sheetId,e)}_getElementSize(e){return this.env.model.getters.getColSize(this.sheetId,e)}_getMaxSize(){return this.colResizerRef.el.clientWidth}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),s=this.env.model.getters.getActiveCols();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"COL",sheetId:this.sheetId,elements:s.has(e)?[...s]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),s=this._getSelectedZoneEnd();for(let o=t;o<=s;o++)e.push(o);const o=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.sheetId,sheetName:this.env.model.getters.getActiveSheetName(),dimension:"COL",base:this.state.base,elements:e,position:this.state.position});!o.isSuccessful&&o.reasons.includes("WillRemoveExistingMerge")&&this.env.raiseError(Eg)}_selectElement(e,t){this.env.model.selection.selectColumn(e,t?"newAnchor":"overrideSelection")}_increaseSelection(e){this.env.model.selection.selectColumn(e,"updateAnchor")}_fitElementSize(e){const t=this.env.model.getters.getActiveCols();this.env.model.dispatch("AUTORESIZE_COLUMNS",{sheetId:this.sheetId,cols:t.has(e)?[...t]:[e]})}_getType(){return"COL"}_getActiveElements(){return this.env.model.getters.getActiveCols()}_getPreviousVisibleElement(e){const t=this.sheetId;let s;for(s=e-1;s>=0&&this.env.model.getters.isColHidden(t,s);s--);return s}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.sheetId,elements:e,dimension:"COL"})}get mainUnhideHeadersProps(){const{left:e,right:t}=this.env.model.getters.getActiveMainViewport(),{xSplit:s}=this.env.model.getters.getPaneDivisions(this.sheetId),o=this.env.model.getters.getHiddenColsGroups(this.sheetId),i=o.findIndex(e=>e[0]>=s-1);return{headersGroups:o.slice(i),offset:this.env.model.getters.getMainViewportCoordinates().x,headerRange:{start:e,end:t}}}get frozenUnhideHeadersProps(){const{xSplit:e}=this.env.model.getters.getPaneDivisions(this.sheetId),t=this.env.model.getters.getHiddenColsGroups(this.sheetId),s=t.findIndex(t=>t[0]>=e-1);return{headersGroups:t.slice(0,s+1),headerRange:{start:0,end:e-1}}}get frozenContainerStyle(){return Ey({width:this.env.model.getters.getMainViewportCoordinates().x+"px"})}get hasFrozenPane(){return this.env.model.getters.getPaneDivisions(this.sheetId).xSplit>0}}class uU extends hU{static props={onOpenContextMenu:Function};static template="o-spreadsheet-RowResizer";static components={UnhideRowHeaders:lU};setup(){super.setup(),this.rowResizerRef=t.useRef("rowResizer"),this.PADDING=5,this.MAX_SIZE_MARGIN=60,this.MIN_ELEMENT_SIZE=10}rowResizerRef;get sheetId(){return this.env.model.getters.getActiveSheetId()}_getEvOffset(e){return e.offsetY}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().top}_getClientPosition(e){return e.clientY}_getElementIndex(e){return this.env.model.getters.getRowIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().top}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().bottom}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollRow(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getRowDimensionsInViewport(this.sheetId,e)}_getElementSize(e){return this.env.model.getters.getRowSize(this.sheetId,e)}_getMaxSize(){return this.rowResizerRef.el.clientHeight}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),s=this.env.model.getters.getActiveRows();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"ROW",sheetId:this.sheetId,elements:s.has(e)?[...s]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),s=this._getSelectedZoneEnd();for(let o=t;o<=s;o++)e.push(o);const o=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.sheetId,sheetName:this.env.model.getters.getActiveSheetName(),dimension:"ROW",base:this.state.base,elements:e,position:this.state.position});o.isSuccessful||(o.reasons.includes("WillRemoveExistingMerge")?this.env.raiseError(Eg):o.reasons.includes("CannotMoveTableHeader")&&this.env.raiseError(Rg))}_selectElement(e,t){this.env.model.selection.selectRow(e,t?"newAnchor":"overrideSelection")}_increaseSelection(e){this.env.model.selection.selectRow(e,"updateAnchor")}_fitElementSize(e){const t=this.env.model.getters.getActiveRows();this.env.model.dispatch("AUTORESIZE_ROWS",{sheetId:this.sheetId,rows:t.has(e)?[...t]:[e]})}_getType(){return"ROW"}_getActiveElements(){return this.env.model.getters.getActiveRows()}_getPreviousVisibleElement(e){const t=this.sheetId;let s;for(s=e-1;s>=0&&this.env.model.getters.isRowHidden(t,s);s--);return s}get mainUnhideHeadersProps(){const{top:e,bottom:t}=this.env.model.getters.getActiveMainViewport(),{ySplit:s}=this.env.model.getters.getPaneDivisions(this.sheetId),o=this.env.model.getters.getHiddenRowsGroups(this.sheetId),i=o.findIndex(e=>e[0]>=s-1);return{headersGroups:o.slice(i),offset:this.env.model.getters.getMainViewportCoordinates().y,headerRange:{start:e,end:t}}}get frozenUnhideHeadersProps(){const{ySplit:e}=this.env.model.getters.getPaneDivisions(this.sheetId),t=this.env.model.getters.getHiddenRowsGroups(this.sheetId),s=t.findIndex(t=>t[0]>=e-1);return{headersGroups:t.slice(0,s+1),headerRange:{start:0,end:e-1}}}get frozenContainerStyle(){return Ey({height:this.env.model.getters.getMainViewportCoordinates().y+"px"})}get hasFrozenPane(){return this.env.model.getters.getPaneDivisions(this.sheetId).ySplit>0}}class gU extends t.Component{static props={onOpenContextMenu:Function};static template="o-spreadsheet-HeadersOverlay";static components={ColResizer:dU,RowResizer:uU};selectAll(){this.env.model.selection.selectAll()}}class pU extends hv{fingerprints;hoveredTables;hoveredIcon;lastRenderBoxes=new Map;preventNewAnimationsInNextFrame=!1;zonesWithPreventedAnimationsInNextFrame=[];animations=new Map;constructor(e){super(e),this.getters=e(nv).getters,this.fingerprints=e(yN),this.hoveredTables=e(oU),this.hoveredIcon=e(iU)}handle(e){switch(e.type){case"START":case"ACTIVATE_SHEET":case"ADD_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":this.animations.clear(),this.preventNewAnimationsInNextFrame=!0;break;case"RESIZE_COLUMNS_ROWS":this.preventNewAnimationsInNextFrame=!0;break;case"REDO":this.zonesWithPreventedAnimationsInNextFrame=[];break;case"UNDO":for(const t of e.commands)if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type||"RESIZE_COLUMNS_ROWS"===t.type){this.animations.clear(),this.preventNewAnimationsInNextFrame=!0;break}break;case"PASTE":this.zonesWithPreventedAnimationsInNextFrame.push(...this.getters.getSelectedZones());break;case"UPDATE_CELL":const t=this.getters.getCommandZones(e);this.zonesWithPreventedAnimationsInNextFrame.push(...t)}}get renderingLayers(){return["Background","Headers"]}drawLayer(e,t,s){switch(t){case"Background":this.drawGlobalBackground(e);const t=this.lastRenderBoxes;this.lastRenderBoxes=new Map;for(const{zone:o,rect:i}of this.getters.getAllActiveViewportsZonesAndRect()){const{ctx:n}=e;n.save(),n.beginPath(),n.rect(i.x,i.y,i.width,i.height),n.clip();const r=this.getGridBoxes(o),a=this.getBoxesWithAnimations(r,t,s);this.drawBackground(e,a),this.drawOverflowingCellBackground(e,a),this.drawCellBackground(e,a),this.drawBorders(e,a),this.drawTexts(e,a),this.drawIcon(e,a),n.restore()}this.drawFrozenPanes(e),this.preventNewAnimationsInNextFrame=!1,this.zonesWithPreventedAnimationsInNextFrame=[];break;case"Headers":this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e))}}drawGlobalBackground(e){const{ctx:t}=e,{width:o,height:i}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle="#ffffff",t.fillRect(0,0,o+s,i+s)}drawBackground(e,t){const{ctx:s,thinLineWidth:o}=e,i=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),n=i?.1*o:0;if(i)for(const e of t)e.skipCellGridLines||(s.strokeStyle="#E2E3E3",s.lineWidth=o,s.strokeRect(e.x+n,e.y+n,e.width-2*n,e.height-2*n))}drawCellBackground(e,t){const{ctx:s}=e;for(const e of t){const t=e.style;if(t.fillColor&&"#ffffff"!==t.fillColor&&(s.fillStyle=t.fillColor||"#ffffff",s.fillRect(e.x,e.y,e.width,e.height)),e.dataBarFill){s.fillStyle=e.dataBarFill.color;const t=e.dataBarFill.percentage,o=e.width*(t/100);s.fillRect(e.x,e.y,o,e.height)}if(e?.chip){s.save(),s.beginPath(),s.rect(e.x,e.y,e.width,e.height),s.clip();const t=e.chip;s.fillStyle=t.color;const o=10;s.beginPath(),s.roundRect(t.x,t.y,t.width,t.height,o),s.fill(),s.restore()}e.overlayColor&&(s.fillStyle=e.overlayColor,s.fillRect(e.x,e.y,e.width,e.height)),e.isError&&(s.fillStyle="red",s.beginPath(),s.moveTo(e.x+e.width-5,e.y),s.lineTo(e.x+e.width,e.y),s.lineTo(e.x+e.width,e.y+5),s.fill())}}drawOverflowingCellBackground(e,t){const{ctx:s,thinLineWidth:o}=e;for(const e of t)if(e.content&&e.isOverflow){const t=e.content.align||"left";let i,n;const r=e.y+o/2,a=e.height-o,l=Math.min(e.clipRect?.width||1/0,e.content.width);"left"===t?(i=e.x+o/2,n=l-2*o):"right"===t?(i=e.x+e.width-o/2,n=2*o-l):(i=(e.clipRect?.x||e.x+e.width/2-e.content.width/2)+o/2,n=l-2*o),s.fillStyle="#ffffff",s.fillRect(i,r,n,a)}}drawBorders(e,t){const{ctx:s}=e;for(const e of t){const t=e.border;if(t){const{x:s,y:i,width:n,height:r}=e;t.left&&o(t.left,s,i,s,i+r),t.top&&o(t.top,s,i,s+n,i),t.right&&o(t.right,s+n,i,s+n,i+r),t.bottom&&o(t.bottom,s,i+r,s+n,i+r)}}function o({color:e,style:t,opacity:o},i,n,r,a){switch(s.globalAlpha=o??1,s.strokeStyle=e,t){case"medium":s.lineWidth=2,n+=(i+=n===a?-.5:.5)===(r+=n===a?1.5:.5)?-.5:.5,a+=i===r?1.5:.5;break;case"thick":s.lineWidth=3,n===a&&(i--,r++),i===r&&(n--,a++);break;case"dashed":s.lineWidth=1,s.setLineDash([1,3]);break;case"dotted":s.lineWidth=1,n===a&&(i+=.5,r+=.5),i===r&&(n+=.5,a+=.5),s.setLineDash([1,1]);break;default:s.lineWidth=1}s.beginPath(),s.moveTo(i,n),s.lineTo(r,a),s.stroke(),s.lineWidth=1,s.setLineDash([]),s.globalAlpha=1}}drawTexts(e,t){const{ctx:s}=e;let o;s.textBaseline="top";for(const e of t)if(e.content){s.globalAlpha=e.textOpacity??1;const t=e.style||{},i=e.content.align||"left",n=qb(t);if(n!==o&&(o=n,s.font=n),s.fillStyle=t.textColor||"#000",s.textAlign=i,e.clipRect){s.save(),s.beginPath();const{x:t,y:o,width:i,height:n}=e.clipRect;s.rect(t,o,i,n),s.clip()}const r=e.content.x;let a=e.content.y;for(const o of e.content.textLines)Qb(s,o,{x:r,y:a},t.underline,t.strikethrough),a+=4+e.content.fontSizePx;e.clipRect&&s.restore(),s.globalAlpha=1}}drawIcon(e,t){const{ctx:s}=e;for(const e of t)for(const t of Object.values(e.icons)){if(!t)continue;const o=Me({id:t.type,position:t.position},this.hoveredIcon.hoveredIcon)&&t.hoverSvg||t.svg;if(!o)continue;s.save(),s.globalAlpha=t.opacity??1,s.beginPath();const i=t.clipRect||e;s.rect(i.x,i.y,i.width,i.height),s.clip();const n=t.size,{x:r,y:a}=this.getters.getCellIconRect(t,e);s.translate(r,a),s.scale(n/o.width,n/o.height);for(const e of o.paths)s.fillStyle=e.fillColor,s.fill(fR(e.path));s.restore()}}drawHeaders(e){const{ctx:t,thinLineWidth:s}=e,o=this.getters.getSheetViewVisibleCols(),l=o[0],c=this.getters.getSheetViewVisibleRows(),h=c[0],{width:d,height:u}=this.getters.getSheetViewDimensionWithHeaders(),g=this.getters.getSelectedZones(),p=function(e){const t=new Set;for(const s of ft(e))for(const e of ge(s.left,s.right+1))t.add(e);return t}(g),m=function(e){const t=new Set;for(const s of ft(e))for(const e of ge(s.top,s.bottom+1))t.add(e);return t}(g),f=this.getters.getActiveSheetId(),v=this.getters.getNumberCols(f),b=this.getters.getNumberRows(f),S=this.getters.getActiveCols(),C=this.getters.getActiveRows();t.font=`400 11px ${k}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=s,t.strokeStyle="#333";for(const e of o){const s={left:e,right:e,top:0,bottom:b-1},{x:o,width:a}=this.getters.getVisibleRect(s),l=S.has(e),c=p.has(e);t.fillStyle=l?r:c?n:i,t.fillRect(o,0,a,A)}for(const e of c){const s={top:e,bottom:e,left:0,right:v-1},{y:o,height:a}=this.getters.getVisibleRect(s),l=C.has(e),c=m.has(e);t.fillStyle=l?r:c?n:i,t.fillRect(0,o,D,a)}t.beginPath(),t.moveTo(D,0),t.lineTo(D,u),t.moveTo(0,A),t.lineTo(d,A),t.strokeStyle="#C0C0C0",t.stroke();for(const e of o){const s=it(e);t.fillStyle=S.has(e)?"#fff":a;const o={left:e,right:e,top:h,bottom:h},{x:i,width:n}=this.getters.getRect(o),{x:r,width:l}=this.getters.getVisibleRect(o);t.save(),t.beginPath(),t.rect(r,0,l,A),t.clip(),t.fillText(s,i+n/2,13),t.restore(),t.beginPath(),t.moveTo(i+n,0),t.lineTo(i+n,A),t.stroke()}for(const e of c){t.fillStyle=C.has(e)?"#fff":a;const s={top:e,bottom:e,left:l,right:l},{y:o,height:i}=this.getters.getRect(s),{y:n,height:r}=this.getters.getVisibleRect(s);t.save(),t.beginPath(),t.rect(0,n,D,r),t.clip(),t.fillText(String(e+1),24,o+i/2),t.restore(),t.beginPath(),t.moveTo(0,o+i),t.lineTo(D,o+i),t.stroke()}}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:s}=e,{x:o,y:i}=this.getters.getMainViewportCoordinates(),n=this.getters.isDashboard()?0:D,r=this.getters.isDashboard()?0:A;t.lineWidth=6*s,t.strokeStyle="#BCBCBC",t.beginPath(),o&&(t.moveTo(n+o,0),t.lineTo(n+o,r)),i&&(t.moveTo(0,r+i),t.lineTo(n,r+i)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:s}=e,{x:o,y:i}=this.getters.getMainViewportCoordinates(),n=this.getters.getSheetViewVisibleCols(),r=n[0],a=n[n.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:r,right:a,top:l[0],bottom:l[l.length-1]},h=this.getters.getVisibleRect(c),d=this.getters.isDashboard()?0:D,u=this.getters.isDashboard()?0:A;t.lineWidth=6*s,t.strokeStyle="#DADFE8",t.beginPath(),o&&(t.moveTo(d+o,u),t.lineTo(d+o,h.height+u)),i&&(t.moveTo(d,u+i),t.lineTo(h.width+d,u+i)),t.stroke()}findNextEmptyCol(e,t,s){const o=this.getters.getActiveSheetId();let i=e;for(;i<t;){const e={sheetId:o,col:i+1,row:s},t=this.getters.getEvaluatedCell(e),n=this.getters.getCellComputedBorder(e),r=this.getters.doesCellHaveGridIcon(e);if(t.type!==_d.empty||this.getters.isInMerge(e)||n?.left||r)return i;i++}return i}findPreviousEmptyCol(e,t,s){const o=this.getters.getActiveSheetId();let i=e;for(;i>t;){const e={sheetId:o,col:i-1,row:s},t=this.getters.getEvaluatedCell(e),n=this.getters.getCellComputedBorder(e),r=this.getters.doesCellHaveGridIcon(e);if(t.type!==_d.empty||this.getters.isInMerge(e)||n?.right||r)return i;i--}return i}computeCellAlignment(e,t){const s=this.getters.getCell(e);if(s?.isFormula&&this.getters.shouldShowFormulas())return"left";const{align:o}=this.getters.getCellStyle(e),i=this.getters.getEvaluatedCell(e);return function(e,t){if(!t)return!1;try{const s=sn(t),{format:o}=mn(e,s);if("text"===o?.type||"date"===o?.type)return o.tokens.some(e=>"REPEATED_CHAR"===e.type);if("number"===o?.type)return o.integerPart.some(e=>"REPEATED_CHAR"===e.type)||!!o.decimalPart&&o.decimalPart.some(e=>"REPEATED_CHAR"===e.type)}catch{}return!1}(i.value,i.format)?"left":t&&i.type===_d.number?"center"!==o?"left":o:o||i.defaultAlign}createZoneBox(e,t,s,o){const{left:i,right:n}=s,r=t.left,a=t.top,l={sheetId:e,col:r,row:a},c=this.getters.getEvaluatedCell(l),h=this.getters.shouldShowFormulas(),{x:d,y:u,width:g,height:p}=this.getters.getRect(t),m=this.getters.getDataValidationChipStyle(l),f=this.getters.getCellComputedBorder(l,o);let v=this.getters.getCellComputedStyle(l);if(this.fingerprints.isEnabled){const e=this.fingerprints.colors.get(l);v={...v,fillColor:e}}m?.textColor&&(v={...v,textColor:m.textColor});const b=this.fingerprints.isEnabled?void 0:this.getters.getConditionalDataBar(l),S=this.getters.getCellIcons(l),C={left:S.find(e=>"left"===e?.horizontalAlign),right:S.find(e=>"right"===e?.horizontalAlign),center:S.find(e=>"center"===e?.horizontalAlign)},y={id:Tt(t),x:d,y:u,width:g,height:p,border:f||void 0,style:v,dataBarFill:b,overlayColor:this.hoveredTables.overlayColors.get(l),isError:c.type===_d.error&&!!c.message||this.getters.isDataValidationInvalid(l),icons:C,disabledAnimation:this.zonesWithPreventedAnimationsInNextFrame.some(e=>Vt(t,e)||Lt(t,e))},I=Zb(y.style);if(c.type===_d.empty||y.icons.center)return y;const w=v.wrapping||"overflow",E="wrap"===w&&!h,R=g-8,x=this.getters.getCellMultiLineText(l,{maxWidth:R,wrapText:E}),T=Math.max(...x.map(e=>this.getters.getTextWidth(e,v)+4)),A=m?5:0,D=(y.icons.left?y.icons.left.size+y.icons.left.margin:0)+A,_=(y.icons.right?y.icons.right.size+y.icons.right.margin:0)+A,O=D+T+_,F=this.computeCellAlignment(l,O>g),P=x.length,M=Math.round(this.getters.computeTextYCoordinate(y,I,v.verticalAlign,P));let N=y.x;N+="left"===F?4+D:"right"===F?y.width-4-_:y.width/2,N=Math.round(N);const L=Lb(I,P);if(y.content={textLines:x,width:"overflow"===w?T:g,align:F,x:N,y:M,fontSizePx:I},m?.fillColor){const e=D,t=5;y.chip={color:m.fillColor,width:y.width-e-t,height:L+2,x:y.x+e,y:M-2}}const k=O>g||I>p;if(y.icons.left||y.icons.right||y.chip)y.clipRect={x:y.x+D,y:y.y,width:Math.max(0,g-D-_),height:p};else if(k&&"overflow"===w){let e,s;switch(this.getters.isInMerge(l)?(e=this.getters.getMerge(l).right,s=r):(e=y.border?.right?t.right:this.findNextEmptyCol(r,n,a),s=y.border?.left?t.left:this.findPreviousEmptyCol(r,i,a),y.isOverflow=!0),F){case"left":{const s=Zt({col:e,row:a}),{x:o,y:i,width:n,height:r}=this.getters.getVisibleRect(Ft(t,s));(n<O||I>r||x.length>1)&&(y.clipRect={x:o,y:i,width:n,height:r});break}case"right":{const e=Zt({col:s,row:a}),{x:o,y:i,width:n,height:r}=this.getters.getVisibleRect(Ft(t,e));(n<O||I>r||x.length>1)&&(y.clipRect={x:o,y:i,width:n,height:r});break}case"center":{const o={...t,left:s,right:e},{x:i,y:n,height:r,width:a}=this.getters.getVisibleRect(o),l=O/2,c=y.x+y.width/2;if(i+a<c+l||i>c-l||I>r||x.length>1){const e=i>c-l?i:c-l,t=i+a-e;y.clipRect={x:e,y:n,width:t,height:r}}break}}}else("clip"===w||"wrap"===w||x.length>1)&&(y.clipRect={x:y.x,y:y.y,width:g,height:p});return y}getGridBoxes(e){const t=[],s=this.getters.getSheetViewVisibleCols().filter(t=>t>=e.left&&t<=e.right),o=s[0],i=s[s.length-1],n=this.getters.getSheetViewVisibleRows().filter(t=>t>=e.top&&t<=e.bottom),r={left:o,right:i,top:n[0],bottom:n[n.length-1]},a=this.getters.getActiveSheetId();for(const o of n)for(const i of s){const s={sheetId:a,col:i,row:o};this.getters.isInMerge(s)||t.push(this.createZoneBox(a,Zt(s),r,e))}for(const s of this.getters.getMerges(a))if(!this.getters.isMergeHidden(a,s)&&Lt(s,r)){const o=this.createZoneBox(a,s,r,e),i=this.getters.getCellComputedBorder({sheetId:a,col:s.right,row:s.bottom},e);o.border={...o.border,bottom:i?i.bottom:void 0,right:i?i.right:void 0},o.isMerge=!0,t.push(o)}return t}getBoxesWithAnimations(e,t,s){return this.updateAnimationsProgress(s),this.addNewAnimations(e,t,s),this.animations.size>0?(this.renderer.startAnimation("grid_renderer_animation"),this.updateBoxesWithAnimations(e)):(this.renderer.stopAnimation("grid_renderer_animation"),e)}updateBoxesWithAnimations(e){const t=[];for(const s of e){const e=this.animations.get(s.id);if(!e){t.push(s);continue}const o=ae(s);t.push(o);for(const i of e.animationTypes){const n=fF.get(i).updateAnimation(e.progress,o,e.oldBox,s);n&&t.push(...n.newBoxes)}}return t}updateAnimationsProgress(e){if(void 0!==e)for(const t of this.animations.keys()){const s=this.animations.get(t);if(void 0===s.startTime){s.startTime=e;continue}const o=e-s.startTime,i=Math.min(1,o/200);i>=1&&this.animations.delete(t),s.progress=i}}addNewAnimations(e,t,s){for(const o of e){this.lastRenderBoxes.set(o.id,o);const e=t.get(o.id);if(this.preventNewAnimationsInNextFrame||!e||o.disabledAnimation)continue;const i=[];for(const t of fF.getAll())t.hasAnimation(e,o)&&i.push(t.id);const n=i.length>0?{animationTypes:i,oldBox:e,progress:0,startTime:s}:void 0;n&&this.animations.set(o.id,n)}}}function mU(e,s,o){const i=t.useRef(e);t.useEffect(function(){const e=i.el,t=window.devicePixelRatio||1,s=e.getContext("2d",{alpha:!1}),r={ctx:s,dpr:t,thinLineWidth:.4*t},{width:a,height:l}=o();if(e.style.width=`${a}px`,e.style.height=`${l}px`,e.width=a*t,e.height=l*t,e.setAttribute("style",`width:${a}px;height:${l}px;`),0===a||0===l)return;s.translate(-.5,-.5),s.scale(t,t),n.draw(r)});const n=ev(cv);ev(pU)}function fU(e,t,s){let o=0,i=0,n=0,r=0,a=!1,l=0,c=null;function h(){if(Math.abs(n)<.05&&(n=0),Math.abs(r)<.05&&(r=0),!n&&!r)return;const e=Date.now(),s=Math.abs(e-l);t(1*(n*s),1*(r*s)),l=e,n*=.95,r*=.95,requestAnimationFrame(h)}eU(e,"touchstart",function(e){a=!0,({clientX:o,clientY:i}=e.touches[0]),n=0,r=0},{capture:!1}),eU(e,"touchmove",function(e){if(!a)return;c&&(clearTimeout(c),c=null);const h=Date.now(),{clientX:d,clientY:u}=e.touches[0],g=o-d,p=i-u,m=h-l;if(!m)return;n=g/m,r=p/m,o=d,i=u,l=h,s()&&(e.cancelable&&e.preventDefault(),e.stopPropagation());c=setTimeout(()=>{n=0,r=0},100),t(1*g,1*p)},{capture:!1}),eU(e,"touchend",function(e){a=!1,o=i=0,c&&clearTimeout(c);n*=1.2,r*=1.2,requestAnimationFrame(h)},{capture:!1})}function vU(e){function t(e,t){return e*(0===t?1:_)}return s=>{const o=t(s.shiftKey&&!Vy()?s.deltaY:s.deltaX,s.deltaMode),i=t(s.shiftKey&&!Vy()?s.deltaX:s.deltaY,s.deltaMode);e(o,i)}}class bU extends t.Component{static template="o-spreadsheet-Border";static props={zone:Object,orientation:String,isMoving:Boolean,onMoveHighlight:Function};get style(){const e=["n","w","e"].includes(this.props.orientation),t=["n","w","s"].includes(this.props.orientation),s=["n","s"].includes(this.props.orientation),o=["w","e"].includes(this.props.orientation),i=this.props.zone,n=this.env.model.getters.getVisibleRect(i),r=n.x,a=n.x+n.width-4,l=n.y,c=n.y+n.height-4;return Ey({left:`${t?r:a}px`,top:`${e?l:c}px`,width:`${s?a-r:4}px`,height:`${o?c-l:4}px`})}onMouseDown(e){this.props.onMoveHighlight(e)}}class SU extends t.Component{static template="o-spreadsheet-Corner";static props={zone:Object,color:String,orientation:String,isResizing:Boolean,onResizeHighlight:Function};dirX;dirY;setup(){const{dirX:e,dirY:t}=function(e){const t=e.includes("w")?-1:e.includes("e")?1:0,s=e.includes("n")?-1:e.includes("s")?1:0;return{dirX:t,dirY:s}}(this.props.orientation);this.dirX=e,this.dirY=t}get handlerStyle(){const e=this.props.zone,t=this.env.model.getters.getVisibleRect({left:1===this.dirX?e.right:e.left,right:-1===this.dirX?e.left:e.right,top:1===this.dirY?e.bottom:e.top,bottom:-1===this.dirY?e.top:e.bottom});if(t.width*t.height===0)return"display: none !important;";const s=t.x+t.width/2+this.dirX*t.width/2,o=t.y+t.height/2+this.dirY*t.height/2,i=this.getHandlerEdgeLength(),n={left:s-i/2+"px",top:o-i/2+"px",height:`${i}px`,width:`${i}px`};return this.env.isMobile()&&(n["border-radius"]=i/2+"px"),Ey(n)}getHandlerEdgeLength(){return this.env.isMobile()?40:8}get buttonLook(){const e={"background-color":this.props.color,cursor:`${this.props.orientation}-resize`};return this.env.isMobile()&&(e["border-radius"]="4px"),Ey(e)}onMouseDown(e){this.props.onResizeHighlight(e,this.dirX,this.dirY)}}class CU extends t.Component{static template="o-spreadsheet-Highlight";static props={range:Object,color:String};static components={Corner:SU,Border:bU};highlightState=t.useState({shiftingMode:"none"});dragNDropGrid=VV(this.env);get cornerOrientations(){if(!this.env.isMobile())return["nw","ne","sw","se"];const e=this.props.range.unboundedZone;return void 0===e.bottom?["w","e"]:void 0===e.right?["n","s"]:["nw","se"]}onResizeHighlight(e,t,s){const o=this.env.model.getters.getActiveSheetId();this.highlightState.shiftingMode="isResizing";const i=this.props.range.zone,n=1===t?i.left:i.right,r=1===s?i.top:i.bottom;let a=1===t?i.right:i.left,l=1===s?i.bottom:i.top,c=i,h="all";this.env.isMobile()&&(h=0===t?"vertical":0===s?"horizontal":"all"),this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{zone:c});this.dragNDropGrid.start(e,(e,t)=>{if(a!==e||l!==t){let{left:s,right:i,top:d,bottom:u}=c;"horizontal"!==h&&(l=l=ue(-1===t?l:t,0,this.env.model.getters.getNumberRows(o)-1),d=Math.min(r,l),u=Math.max(r,l)),"vertical"!==h&&(a=ue(-1===e?a:e,0,this.env.model.getters.getNumberCols(o)-1),s=Math.min(n,a),i=Math.max(n,a));const g={left:s,right:i,top:d,bottom:u};Mt(g,c)||(this.env.model.selection.selectZone({cell:{col:g.left,row:g.top},zone:g},{unbounded:!0}),c=g)}},()=>{this.highlightState.shiftingMode="none"},h)}onMoveHighlight(e){this.highlightState.shiftingMode="isMoving";const t=this.props.range.zone,s=_y(),o=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getColIndex(e.clientX-s.left),n=this.env.model.getters.getRowIndex(e.clientY-s.top),r=-t.left,a=this.env.model.getters.getNumberCols(o)-t.right-1,l=-t.top,c=this.env.model.getters.getNumberRows(o)-t.bottom-1;let h=t;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{zone:h});let d=i,u=n;this.dragNDropGrid.start(e,(e,s)=>{if(d!==e||u!==s){d=-1===e?d:e,u=-1===s?u:s;const o=ue(d-i,r,a),g=ue(u-n,l,c),p={left:t.left+o,top:t.top+g,right:t.right+o,bottom:t.bottom+g};Mt(p,h)||(this.env.model.selection.selectZone({cell:{col:p.left,row:p.top},zone:p},{unbounded:!0}),h=p)}},()=>{this.highlightState.shiftingMode="none"})}}let yU=class{direction;el;constructor(e,t){this.el=e,this.direction=t}get scroll(){return"horizontal"===this.direction?this.el.scrollLeft:this.el.scrollTop}set scroll(e){"horizontal"===this.direction?this.el.scrollLeft=e:this.el.scrollTop=e}};class IU extends t.Component{static props={width:{type:Number,optional:!0},height:{type:Number,optional:!0},direction:String,position:Object,offset:Number,onScroll:Function};static template=t.xml`
|
|
820
|
+
<div
|
|
821
|
+
t-attf-class="o-scrollbar {{props.direction}}"
|
|
822
|
+
t-on-scroll="onScroll"
|
|
823
|
+
t-ref="scrollbar"
|
|
824
|
+
t-att-style="positionCss">
|
|
825
|
+
<div t-att-style="sizeCss"/>
|
|
826
|
+
</div>
|
|
827
|
+
`;static defaultProps={width:1,height:1};scrollbarRef;scrollbar;setup(){this.scrollbarRef=t.useRef("scrollbar"),this.scrollbar=new yU(this.scrollbarRef.el,this.props.direction),t.onMounted(()=>{this.scrollbar.el=this.scrollbarRef.el}),t.useEffect(()=>{this.scrollbar.scroll!==this.props.offset&&(this.scrollbar.scroll=this.props.offset)},()=>[this.scrollbar.scroll,this.props.offset])}get sizeCss(){return Ey({width:`${this.props.width}px`,height:`${this.props.height}px`})}get positionCss(){return Ey(this.props.position)}onScroll(e){this.props.offset!==this.scrollbar.scroll&&this.props.onScroll(this.scrollbar.scroll)}}class wU extends t.Component{static props={leftOffset:{type:Number,optional:!0}};static components={ScrollBar:IU};static template=t.xml`
|
|
828
|
+
<ScrollBar
|
|
829
|
+
t-if="isDisplayed"
|
|
830
|
+
width="width"
|
|
831
|
+
position="position"
|
|
832
|
+
offset="offset"
|
|
833
|
+
direction="'horizontal'"
|
|
834
|
+
onScroll.bind="onScroll"
|
|
835
|
+
/>`;static defaultProps={leftOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollX}get width(){return this.env.model.getters.getMainViewportRect().width}get isDisplayed(){const{xRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){const{x:e}=this.env.model.getters.getMainViewportRect();return{left:`${this.props.leftOffset+e}px`,bottom:"0px",height:"15px",right:By()?"15px":"0"}}onScroll(e){const{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:e,offsetY:t})}}class EU extends t.Component{static props={topOffset:{type:Number,optional:!0}};static components={ScrollBar:IU};static template=t.xml`
|
|
836
|
+
<ScrollBar
|
|
837
|
+
t-if="isDisplayed"
|
|
838
|
+
height="height"
|
|
839
|
+
position="position"
|
|
840
|
+
offset="offset"
|
|
841
|
+
direction="'vertical'"
|
|
842
|
+
onScroll.bind="onScroll"
|
|
843
|
+
/>`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){const{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){const{y:e}=this.env.model.getters.getMainViewportRect();return{top:`${this.props.topOffset+e}px`,right:"0px",width:"15px",bottom:By()?"15px":"0"}}onScroll(e){const{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:t,offsetY:e})}}class RU extends t.Component{static template="o-spreadsheet-Selection";static props={};static components={Highlight:CU};get highlightProps(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getUnboundedZone(e,this.env.model.getters.getSelectedZone());return{range:this.env.model.getters.getRangeFromZone(e,t),color:l}}}function xU({refName:e}){const s=t.useRef(e);t.useEffect(e=>{e?.focus()},()=>[s.el])}class TU extends t.Component{static template="o-spreadsheet-TextInput";static props={value:String,onChange:Function,class:{type:String,optional:!0},id:{type:String,optional:!0},placeholder:{type:String,optional:!0},autofocus:{type:Boolean,optional:!0},alwaysShowBorder:{type:Boolean,optional:!0}};inputRef=t.useRef("input");setup(){t.useExternalListener(window,"click",e=>{e.target!==this.inputRef.el&&this.inputRef.el?.value!==this.props.value&&this.save()},{capture:!0}),this.props.autofocus&&xU({refName:"input"})}onKeyDown(e){switch(e.key){case"Enter":this.save(),e.preventDefault(),e.stopPropagation();break;case"Escape":this.inputRef.el&&(this.inputRef.el.value=this.props.value,this.inputRef.el.blur()),e.preventDefault(),e.stopPropagation()}}save(){const e=(this.inputRef.el?.value||"").trim();e!==this.props.value&&this.props.onChange(e),this.inputRef.el?.blur()}onMouseDown(e){e.target!==document.activeElement&&(e.preventDefault(),e.stopPropagation())}onMouseUp(e){const t=e.target;t!==document.activeElement&&(t.focus(),t.select(),e.preventDefault(),e.stopPropagation())}get inputClass(){return[this.props.class,this.props.alwaysShowBorder?"o-input-border":void 0].filter(Te).join(" ")}}class AU extends t.Component{static template="o-spreadsheet-ActionButton";static props={action:Object,hasTriangleDownIcon:{type:Boolean,optional:!0},selectedColor:{type:String,optional:!0},class:{type:String,optional:!0},onClick:{type:Function,optional:!0}};actionButton=jf(this.props.action);setup(){t.onWillUpdateProps(e=>{e.action!==this.props.action&&(this.actionButton=jf(e.action))})}get isVisible(){return this.actionButton.isVisible(this.env)}get isEnabled(){return this.actionButton.isEnabled(this.env)}get isActive(){return this.actionButton.isActive?.(this.env)}get title(){const e=this.actionButton.name(this.env),t=this.actionButton.description(this.env);return e+(t?` (${t})`:"")}get iconTitle(){return this.actionButton.icon(this.env)}onClick(e){this.isEnabled&&(this.props.onClick?.(e),this.actionButton.execute?.(this.env))}get buttonStyle(){return this.props.selectedColor?Ey({"border-bottom":`4px solid ${this.props.selectedColor}`,height:"16px","margin-top":"2px"}):""}}class DU extends t.Component{static template="o-spreadsheet-ColorPickerWidget";static props={currentColor:{type:String,optional:!0},toggleColorPicker:Function,showColorPicker:Boolean,onColorPicked:Function,icon:String,title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={ColorPicker:rM};colorPickerButtonRef=t.useRef("colorPickerButton");get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:"border-bottom-style: hidden"}get colorPickerAnchorRect(){const e=this.colorPickerButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}}class _U extends t.Component{static template="o-spreadsheet-FontSizeEditor";static props={currentFontSize:Number,onFontSizeChanged:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String};static defaultProps={onFocusInput:()=>{}};static components={Popover:DF};fontSizes=K;dropdown=t.useState({isOpen:!1});inputRef=t.useRef("inputFontSize");rootEditorRef=t.useRef("FontSizeEditor");fontSizeListRef=t.useRef("fontSizeList");setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}get popoverProps(){const{x:e,y:t,width:s,height:o}=this.rootEditorRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:s,height:o},positioning:"bottom-left",verticalOffset:0}}onExternalClick(e){Dy(this.fontSizeListRef.el,e)||Dy(this.rootEditorRef.el,e)||this.closeFontList()}toggleFontList(){this.dropdown.isOpen?this.closeFontList():(this.props.onToggle?.(),this.inputRef.el.focus())}closeFontList(){this.dropdown.isOpen=!1}setSize(e){const t=ue(Math.floor(parseFloat(e)),1,400);this.props.onFontSizeChanged(t),this.closeFontList()}setSizeFromInput(e){this.setSize(e.target.value)}setSizeFromList(e){this.setSize(e)}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if("Enter"===e.key||"Escape"===e.key){this.closeFontList();const t=e.target;"Escape"===e.key&&(t.value=`${this.props.currentFontSize}`),this.props.onToggle?.()}}}class OU extends t.Component{static template="o-spreadsheet.TextStyler";static components={ColorPickerWidget:DU,ActionButton:AU,FontSizeEditor:_U};static props={style:Object,updateStyle:{type:Function,optional:!0},defaultStyle:{type:Object,optional:!0},hasVerticalAlign:{type:Boolean,optional:!0},hasHorizontalAlign:{type:Boolean,optional:!0},hasBackgroundColor:{type:Boolean,optional:!0},class:{type:String,optional:!0}};openedEl=null;setup(){t.useExternalListener(window,"click",this.onExternalClick)}state=t.useState({activeTool:""});updateFontSize(e){this.props.updateStyle?.({...this.props.style,fontSize:e})}toggleDropdownTool(e,t){const s=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=s?"":e,this.openedEl=s?null:t.target}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onTextColorChange(e){this.props.updateStyle?.({...this.props.style,color:e}),this.closeMenus()}onFillColorChange(e){this.props.updateStyle?.({...this.props.style,fillColor:e}),this.closeMenus()}updateAlignment(e){this.props.updateStyle?.({...this.props.style,align:e}),this.closeMenus()}updateVerticalAlignment(e){this.props.updateStyle?.({...this.props.style,verticalAlign:e}),this.closeMenus()}toggleBold(){this.props.updateStyle?.({...this.props.style,bold:!this.bold})}toggleItalic(){this.props.updateStyle?.({...this.props.style,italic:!this.italic})}closeMenus(){this.state.activeTool="",this.openedEl=null}get align(){return this.props.style.align??this.props.defaultStyle?.align}get verticalAlign(){return this.props.style.verticalAlign||this.props.defaultStyle?.verticalAlign}get bold(){return this.props.style.bold??this.props.defaultStyle?.bold}get italic(){return this.props.style.italic??this.props.defaultStyle?.italic}get currentFontSize(){return this.props.style.fontSize??this.props.defaultStyle?.fontSize??P.fontSize}get boldButtonAction(){return{name:fs("Bold"),execute:()=>this.toggleBold(),isActive:()=>this.bold||!1,icon:"o-spreadsheet-Icon.BOLD"}}get italicButtonAction(){return{name:fs("Italic"),execute:()=>this.toggleItalic(),isActive:()=>this.italic||!1,icon:"o-spreadsheet-Icon.ITALIC"}}get horizontalAlignButtonAction(){let e="o-spreadsheet-Icon.ALIGN_LEFT";return"center"===this.align?e="o-spreadsheet-Icon.ALIGN_CENTER":"right"===this.align&&(e="o-spreadsheet-Icon.ALIGN_RIGHT"),{name:fs("Horizontal alignment"),icon:e}}get horizontalAlignActions(){return[{name:fs("Left"),execute:()=>this.updateAlignment("left"),isActive:()=>"left"===this.align,icon:"o-spreadsheet-Icon.ALIGN_LEFT"},{name:fs("Center"),execute:()=>this.updateAlignment("center"),isActive:()=>"center"===this.align,icon:"o-spreadsheet-Icon.ALIGN_CENTER"},{name:fs("Right"),execute:()=>this.updateAlignment("right"),isActive:()=>"right"===this.align,icon:"o-spreadsheet-Icon.ALIGN_RIGHT"}]}get verticalAlignButtonAction(){let e="o-spreadsheet-Icon.ALIGN_MIDDLE";return"top"===this.verticalAlign?e="o-spreadsheet-Icon.ALIGN_TOP":"bottom"===this.verticalAlign&&(e="o-spreadsheet-Icon.ALIGN_BOTTOM"),{name:fs("Vertical alignment"),icon:e}}get verticalAlignActions(){return[{name:fs("Top"),execute:()=>this.updateVerticalAlignment("top"),isActive:()=>"top"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_TOP"},{name:fs("Middle"),execute:()=>this.updateVerticalAlignment("middle"),isActive:()=>"middle"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},{name:fs("Bottom"),execute:()=>this.updateVerticalAlignment("bottom"),isActive:()=>"bottom"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"}]}}class FU extends t.Component{static template="o-spreadsheet-CogWheelMenu";static components={MenuPopover:PF};static props={items:Array};buttonRef=t.useRef("button");menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});menuId=this.env.model.uuidGenerator.uuidv4();toggleMenu(e){e.closedMenuId!==this.menuId&&(this.menuState.isOpen=!this.menuState.isOpen,this.menuState.anchorRect=Fy(this.buttonRef.el),this.menuState.menuItems=qf(this.props.items))}}class PU extends t.Component{static template="o-spreadsheet-CarouselPanel";static props={onCloseSidePanel:Function,figureId:String};static components={Section:aM,TextInput:TU,TextStyler:OU,CogWheelMenu:FU};DEFAULT_CAROUSEL_TITLE_STYLE=te;dragAndDrop=cM();previewListRef=t.useRef("previewList");setup(){let e=[...this.carouselItems];t.onWillUpdateProps(()=>{Me(this.carouselItems,e)||this.dragAndDrop.cancel(),e=[...this.carouselItems]})}get carouselItems(){return this.env.model.getters.getCarousel(this.props.figureId).items}get title(){return this.env.model.getters.getCarousel(this.props.figureId).title}get carousel(){return this.env.model.getters.getCarousel(this.props.figureId)}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[this.getItemId(e)]||""}getItemId(e){return"chart"===e.type?e.chartId:"transparent-carousel"}addNewChartToCarousel(){this.env.model.dispatch("ADD_NEW_CHART_TO_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId})}get hasDataView(){return this.carouselItems.some(e=>"carouselDataView"===e.type)}isCarouselItemActive(e){return Me(this.env.model.getters.getSelectedCarouselItem(this.props.figureId),e)}addDataViewToCarousel(){const e=this.env.model.getters.getCarousel(this.props.figureId);this.updateItems([...e.items,{type:"carouselDataView"}])}activateCarouselItem(e){this.env.model.dispatch("UPDATE_CAROUSEL_ACTIVE_ITEM",{figureId:this.props.figureId,sheetId:this.carouselSheetId,item:e})}editCarouselItem(e){"chart"===e.type&&(this.activateCarouselItem(e),this.env.model.dispatch("SELECT_FIGURE",{figureId:this.props.figureId}),this.env.openSidePanel("ChartPanel",{chartId:e.chartId}))}renameCarouselItem(e,t){const s=t.trim();if(!s||s===this.getItemTitle(e).toString())return;const o=[...this.carouselItems],i=this.carouselItems.findIndex(t=>Me(t,e));-1!==i&&(o[i]={...e,title:s},this.updateItems(o))}deleteCarouselItem(e){const t=this.env.model.getters.getCarousel(this.props.figureId).items.filter(t=>!Me(t,e));this.updateItems(t)}popOutCarouselItem(e){"chart"===e.type&&this.env.model.dispatch("POPOUT_CHART_FROM_CAROUSEL",{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId})}onDragHandleMouseDown(e,t){if(0!==t.button)return;const s=Array.from(this.previewListRef.el.children).map(e=>Fy(e)),o=this.carouselItems.map((e,t)=>({id:this.getItemId(e),size:s[t].height,position:s[t].y}));this.dragAndDrop.start("vertical",{draggedItemId:this.getItemId(e),initialMousePosition:t.clientY,items:o,scrollableContainerEl:this.previewListRef.el,onDragEnd:(t,s)=>this.onDragEnd(e,s)})}onDragEnd(e,t){const s=this.carouselItems.findIndex(t=>Me(t,e));if(-1===s||s===t)return;const o=[...this.env.model.getters.getCarousel(this.props.figureId).items];o.splice(s,1),o.splice(t,0,e),this.updateItems(o)}getItemTitle(e){return b_(this.env.model.getters,e)}getItemPreview(e){return function(e,t){if("carouselDataView"===t.type)return"o-spreadsheet-Icon.DATA";const s=e.getChartDefinition(t.chartId);return(f_.getAll().find(e=>e.matcher?.(s))||f_.get(s.type)).preview}(this.env.model.getters,e)}updateItems(e){this.env.model.dispatch("UPDATE_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...this.carousel,items:e}})}updateTitleText(e){const t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch("UPDATE_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,text:e}}})}updateTitleStyle(e){const t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch("UPDATE_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,...e}}})}get carouselAddChartInfoMessage(){return fs("Add a chart to the carousel. You can also add a chart by dragging and dropping it over the carousel figure.")}getCogWheelMenuItems(e){const t=[];return"chart"===e.type&&(t.push({name:fs("Edit chart"),execute:()=>this.editCarouselItem(e),icon:"o-spreadsheet-Icon.EDIT"}),t.push({name:fs("Pop out chart"),execute:()=>this.popOutCarouselItem(e),icon:"o-spreadsheet-Icon.EXTERNAL"})),t.push({name:fs("Delete item"),execute:()=>this.deleteCarouselItem(e),icon:"o-spreadsheet-Icon.TRASH"}),t}get carouselSheetId(){const e=this.env.model.getters.getFigureSheetId(this.props.figureId);if(!e)throw new Error("Could not find the sheetId of the carousel figure");return e}get carouselDataViewMessage(){return fs("The data view makes the carousel transparent, revealing the data underneath.")}}class MU extends t.Component{static template="o-spreadsheet.ChartDataSeries";static components={SelectionInput:fM,Section:aM};static props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},onSelectionChanged:Function,onSelectionReordered:{type:Function,optional:!0},onSelectionRemoved:{type:Function,optional:!0},onSelectionConfirmed:Function,title:{type:String,optional:!0},maxNumberOfUsedRanges:{type:Number,optional:!0},datasetOrientation:{type:String,optional:!0},canChangeDatasetOrientation:{type:Boolean,optional:!0},onFlipAxis:{type:Function,optional:!0}};get ranges(){return this.props.ranges.map(e=>e.dataRange)}get disabledRanges(){return this.props.ranges.map((e,t)=>!!this.props.maxNumberOfUsedRanges&&t>=this.props.maxNumberOfUsedRanges)}get colors(){return this.props.ranges.map(e=>e.backgroundColor)}get title(){return this.props.title?this.props.title:this.props.hasSingleRange?fs("Data range"):fs("Data series")}}class NU extends t.Component{static template="o-spreadsheet.ChartErrorSection";static components={Section:aM,ValidationMessages:JV};static props={messages:{type:Array,element:String}}}class LU extends t.Component{static template="o-spreadsheet.ChartLabelRange";static components={SelectionInput:fM,Checkbox:IM,Section:aM};static props={title:{type:String,optional:!0},range:String,isInvalid:Boolean,onSelectionChanged:Function,onSelectionConfirmed:Function,options:{type:Array,optional:!0}};static defaultProps={title:fs("Categories / Labels"),options:[]}}class kU extends t.Component{static template="o-spreadsheet-GenericChartConfigPanel";static components={ChartDataSeries:MU,ChartLabelRange:LU,Section:aM,Checkbox:IM,ChartErrorSection:NU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};state=t.useState({datasetDispatchResult:void 0,labelsDispatchResult:void 0});dataSets=[];labelRange;datasetOrientation=void 0;chartTerms=Ig;setup(){this.dataSets=this.props.definition.dataSets,this.labelRange=this.props.definition.labelRange,this.datasetOrientation=this.computeDatasetOrientation()}get errorMessages(){return[...this.state.datasetDispatchResult?.reasons||[],...this.state.labelsDispatchResult?.reasons||[]].filter(e=>"NoChanges"!==e).map(e=>Ig.Errors[e]||Ig.Errors.Unexpected)}get isDatasetInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause("InvalidDataSet")}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.isCancelledBecause("InvalidLabelRange")}get dataSetsHaveTitleLabel(){return"rows"===this.datasetOrientation?fs("Use col %(column_name)s as headers",{column_name:it(this.calculateHeaderPosition()||0)}):fs("Use row %(row_position)s as headers",{row_position:this.calculateHeaderPosition()||""})}getLabelRangeOptions(){const e=this.props.definition;return[{name:"aggregated",label:this.chartTerms.AggregatedChart,value:("aggregated"in e&&e.aggregated)??!1,onChange:this.onUpdateAggregated.bind(this)},{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:e.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.chartId,{dataSetsHaveTitle:e})}get canChangeDatasetOrientation(){const e=new Set,t=[],s=this.env.model.getters.getActiveSheetName(),o=this.dataSets.map(e=>e.dataRange);this.labelRange&&o.push(this.labelRange);for(const i of o){if(!Et(i))return!1;const o=tr(i),n=It(o.xc);if(void 0===n.bottom||void 0===n.right)return!1;if(t.push(n),e.add(o.sheetName||s),e.size>1)return!1}const i=es(t);if(1!==i.length)return!1;const{left:n,right:r,top:a,bottom:l}=i[0];return!t.some(e=>!(e.top===a&&e.bottom===l||e.left===n&&e.right===r))}computeDatasetOrientation(){let e=!1,t=!1;for(const s of this.dataSets){if(!Et(s.dataRange))return;const o=It(s.dataRange);if(void 0===o.bottom||void 0===o.right)return;o.top===o.bottom&&(e=!0),o.left===o.right&&(t=!0)}return e&&!t?"rows":!e&&t?"columns":void 0}setDatasetOrientation(e){const t=this.props.definition.dataSets.map(e=>e.dataRange),s=this.transposeDataSet([this.props.definition.labelRange,...t],e);if(0===s.length)return;const o=s.length>1?s.shift().dataRange:"";this.props.updateChart(this.props.chartId,{labelRange:o,dataSets:s}),this.dataSets=s,this.labelRange=o,this.datasetOrientation=e}onDataSeriesRangesChanged(e){this.dataSets=e.map((e,t)=>({...this.dataSets?.[t],dataRange:e})),this.state.datasetDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesReordered(e){const t=KC({dataSets:this.dataSets},this.dataSets.length);this.datasetOrientation=void 0;const s=this.dataSets.map(e=>t.next());this.dataSets=e.map(e=>({backgroundColor:s[e],...this.dataSets[e]})),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesRemoved(e){const t=KC({dataSets:this.dataSets},this.dataSets.length),s=this.dataSets.map(e=>t.next());this.dataSets=this.dataSets.map((e,t)=>({backgroundColor:s[t],...e})).filter((t,s)=>s!==e),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesConfirmed(){this.dataSets=this.splitRanges,this.datasetOrientation=this.computeDatasetOrientation(),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets}),this.state.datasetDispatchResult.isSuccessful&&(this.dataSets=this.env.model.getters.getChartDefinition(this.props.chartId).dataSets)}get splitRanges(){const e=[];for(const t of this.dataSets){const s=t.dataRange;if(!this.env.model.getters.isRangeValid(s)){e.push(t);continue}const{sheetName:o}=tr(s),i=o?`${o}!`:"",n=It(s);if(n.bottom!==n.top&&n.left!==n.right){if("rows"!==this.datasetOrientation){if(void 0!==n.right)for(let s=n.left;s<=n.right;++s){const o=s===n.left?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Tt({left:s,right:s,top:n.top,bottom:n.bottom})}`})}else if(void 0!==n.bottom)for(let s=n.top;s<=n.bottom;++s){const o=s===n.top?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Tt({left:n.left,right:n.right,top:s,bottom:s})}`})}}else if(void 0!==n.bottom)for(let s=n.top;s<=n.bottom;++s){const o=s===n.top?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Tt({left:n.left,right:n.right,top:s,bottom:s})}`})}else if(void 0!==n.right)for(let s=n.left;s<=n.right;++s){const o=s===n.left?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Tt({left:s,right:s,top:n.top,bottom:n.bottom})}`})}}else e.push(t)}return e}getDataSeriesRanges(){return this.dataSets}onLabelRangeChanged(e){this.labelRange=e[0],this.state.labelsDispatchResult=this.props.canUpdateChart(this.props.chartId,{labelRange:this.labelRange})}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.chartId,{labelRange:this.labelRange})}getLabelRange(){return this.labelRange||""}onUpdateAggregated(e){this.props.updateChart(this.props.chartId,{aggregated:e})}calculateHeaderPosition(){if(this.isDatasetInvalid||this.isLabelInvalid)return;const e=this.env.model.getters,t=e.getActiveSheetId(),s=Rb(e,t,this.labelRange),o=eC(e,this.dataSets,t,this.props.definition.dataSetsHaveTitle);return o.length?"rows"===this.datasetOrientation?o[0].dataRange.zone.left:o[0].dataRange.zone.top+1:s?s.zone.top+1:void 0}get maxNumberOfUsedRanges(){return $y.get(this.props.definition.type).dataSeriesLimit}transposeDataSet(e,t){const s=this.env.model.getters;if(void 0===t)return e.filter(Te).map(e=>({dataRange:e}));const o={},i=[],n=s.getFigureIdFromChartId(this.props.chartId),r=s.getFigureSheetId(n);let a=s.getActiveSheet().name;r&&(a=s.getSheet(r).name);for(const t of e){if(!t)continue;if(!Et(t))return e.filter(Te).map(e=>({dataRange:e}));let{sheetName:s,xc:i}=tr(t);s=s??a,o[s]||(o[s]=[]),o[s].push(wt(i))}for(const e in o){const s=es(o[e]);if("columns"===t)for(const t of s)for(let s=t.left;s<=t.right;s++){const o=`${e===a?"":e+"!"}${Tt({...t,left:s,right:s})}`;i.push({dataRange:o})}else for(const t of s)for(let s=t.top;s<=t.bottom;s++){const o=`${e===a?"":e+"!"}${Tt({...t,top:s,bottom:s})}`;i.push({dataRange:o})}}return i}}class VU extends kU{static template="o-spreadsheet-BarConfigPanel";get stackedLabel(){return this.props.definition.horizontal?this.chartTerms.StackedBarChart:this.chartTerms.StackedColumnChart}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}}class UU extends t.Component{static template="o-spreadsheet.BadgeSelection";static props={choices:Array,onChange:Function,selectedValue:String}}class HU extends t.Component{static template="o-spreadsheet.ChartTitle";static components={Section:aM,TextStyler:OU};static props={title:{type:String,optional:!0},placeholder:{type:String,optional:!0},updateTitle:Function,name:{type:String},style:Object,defaultStyle:{type:Object,optional:!0},updateStyle:Function};static defaultProps={title:"",placeholder:""};updateTitle(e){this.props.updateTitle(e.target.value)}}class zU extends t.Component{static template="o-spreadsheet-AxisDesignEditor";static components={Section:aM,ChartTitle:HU,BadgeSelection:UU};static props={chartId:String,definition:Object,updateChart:Function,axesList:Array};state=t.useState({currentAxis:"x"});defaultFontSize=12;get axisTitleStyle(){return this.props.definition.axesDesign?.[this.state.currentAxis]?.title??{}}get badgeAxes(){return this.props.axesList.map(e=>({value:e.id,label:e.name}))}updateAxisEditor(e){this.state.currentAxis=e.target.value}getAxisTitle(){const e=this.props.definition.axesDesign??{};return e[this.state.currentAxis]?.title.text||""}updateAxisTitle(e){const t=ae(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:{...t?.[this.state.currentAxis]?.title,text:e}},this.props.updateChart(this.props.chartId,{axesDesign:t})}updateAxisTitleStyle(e){const t=ae(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:e},this.props.updateChart(this.props.chartId,{axesDesign:t})}}class BU extends t.Component{static template="o-spreadsheet.RadioSelection";static props={choices:Array,onChange:Function,selectedValue:{optional:!1},name:String,direction:{type:String,optional:!0}};static defaultProps={direction:"horizontal"}}class GU extends t.Component{static template="o-spreadsheet-GeneralDesignEditor";static components={RoundColorPicker:lM,ChartTitle:HU,Section:aM,SidePanelCollapsible:DP,RadioSelection:BU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function,defaultChartTitleFontSize:{type:Number,optional:!0},slots:{type:Object,optional:!0}};static defaultProps={defaultChartTitleFontSize:R};state;setup(){this.state=t.useState({activeTool:""})}get title(){return this.props.definition.title}toggleDropdownTool(e,t){const s=this.state.activeTool===e;this.state.activeTool=s?"":e}updateBackgroundColor(e){this.props.updateChart(this.props.chartId,{background:e})}updateTitle(e){const t={...this.title,text:e};this.props.updateChart(this.props.chartId,{title:t})}updateChartTitleStyle(e){const t={...this.title,...e};this.props.updateChart(this.props.chartId,{title:t}),this.state.activeTool=""}}class WU extends t.Component{static template="o-spreadsheet-ChartHumanizeNumbers";static components={Checkbox:IM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function}}class $U extends t.Component{static template="o-spreadsheet-ChartLegend";static components={Section:aM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e.target.value})}}class qU extends t.Component{static template="o-spreadsheet-SeriesDesignEditor";static components={SidePanelCollapsible:DP,Section:aM,RoundColorPicker:lM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function,slots:{type:Object,optional:!0}};state=t.useState({index:0});getDataSeries(){const e=this.env.model.getters.getChartRuntime(this.props.chartId);return e&&"chartJsConfig"in e?e.chartJsConfig.data.datasets.filter(e=>!fC(e.xAxisID??"")).map(e=>e.label):[]}updateEditedSeries(e){this.state.index=e.target.selectedIndex}updateDataSeriesColor(e){const t=this.props.definition.dataSets;t?.[this.state.index]&&(t[this.state.index]={...t[this.state.index],backgroundColor:e},this.props.updateChart(this.props.chartId,{dataSets:t}))}getDataSeriesColor(){const e=this.props.definition.dataSets;if(!e?.[this.state.index])return"";const t=e[this.state.index].backgroundColor;return t?bv(t):zv(this.state.index,Bv(this.props.definition.dataSets.length))}updateDataSeriesLabel(e){const t=e.target.value,s=this.props.definition.dataSets;s?.[this.state.index]&&(s[this.state.index]={...s[this.state.index],label:t},this.props.updateChart(this.props.chartId,{dataSets:s}))}getDataSeriesLabel(){const e=this.props.definition.dataSets;return e[this.state.index]?.label||this.getDataSeries()[this.state.index]}}class ZU extends t.Component{static template="o-spreadsheet-SeriesWithAxisDesignEditor";static components={SeriesDesignEditor:qU,Checkbox:IM,RadioSelection:BU,Section:aM,RoundColorPicker:lM};static props={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function,slots:{type:Object,optional:!0}};axisChoices=gC;updateDataSeriesAxis(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],yAxisId:"left"===t?"y":"y1"},this.props.updateChart(this.props.chartId,{dataSets:s}))}getDataSerieAxis(e){const t=this.props.definition.dataSets;return t?.[e]&&"y1"===t[e].yAxisId?"right":"left"}get canHaveTwoVerticalAxis(){return!("horizontal"in this.props.definition&&this.props.definition.horizontal)}toggleDataTrend(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],trend:{type:"polynomial",order:1,...s[e].trend,display:t}},this.props.updateChart(this.props.chartId,{dataSets:s}))}getTrendLineConfiguration(e){const t=this.props.definition.dataSets;return t?.[e]?.trend}getTrendType(e){return e?"polynomial"===e.type&&1===e.order?"linear":e.type:""}onChangeTrendType(e,t){const s=t.target.value;let o;switch(s){case"linear":case"polynomial":o={type:"polynomial",order:"linear"===s?1:this.getMaxPolynomialDegree(e)};break;case"exponential":case"logarithmic":case"trailingMovingAverage":o={type:s};break;default:return}this.updateTrendLineValue(e,o)}getPolynomialDegrees(e){return ge(1,this.getMaxPolynomialDegree(e)+1)}onChangePolynomialDegree(e,t){const s=t.target;this.updateTrendLineValue(e,{order:parseInt(s.value)})}getMaxPolynomialDegree(e){const t=this.env.model.getters.getChartRuntime(this.props.chartId);return Math.min(10,t.chartJsConfig.data.datasets[e].data.length-1)}get defaultWindowSize(){return 2}onChangeMovingAverageWindow(e,t){const s=t.target;let o=parseInt(s.value)||2;o<=1&&(o=2),this.updateTrendLineValue(e,{window:o})}getDataSeriesColor(e){const t=this.props.definition.dataSets;if(!t?.[e])return"";const s=t[e].backgroundColor;return s?bv(s):zv(e,Bv(this.props.definition.dataSets.length))}getTrendLineColor(e){return this.getTrendLineConfiguration(e)?.color??_v(this.getDataSeriesColor(e),.5)}updateTrendLineColor(e,t){this.updateTrendLineValue(e,{color:t})}updateTrendLineValue(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],trend:{...s[e].trend,...t}},this.props.updateChart(this.props.chartId,{dataSets:s}))}}class jU extends t.Component{static template="o-spreadsheet-ChartShowValues";static components={Checkbox:IM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function,defaultValue:{type:Boolean,optional:!0}}}class YU extends t.Component{static template="o-spreadsheet-ChartWithAxisDesignPanel";static components={GeneralDesignEditor:GU,SidePanelCollapsible:DP,Section:aM,AxisDesignEditor:zU,SeriesWithAxisDesignEditor:ZU,ChartLegend:$U,ChartShowValues:jU,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function};get axesList(){const{useLeftAxis:e,useRightAxis:t}=hC(this.props.definition),s=[{id:"x",name:fs("Horizontal axis")}];return e&&s.push({id:"y",name:fs(t?"Left axis":"Vertical axis")}),t&&s.push({id:"y1",name:fs(e?"Right axis":"Vertical axis")}),s}}class XU extends t.Component{static template="o-spreadsheet-ChartShowDataMarkers";static components={Checkbox:IM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function}}class KU extends YU{static template="o-spreadsheet-GenericZoomableChartDesignPanel";static components={...YU.components,Checkbox:IM};onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}}class JU extends KU{static template="o-spreadsheet-ComboChartDesignPanel";static components={...KU.components,ChartShowDataMarkers:XU,RadioSelection:BU};seriesTypeChoices=[{value:"bar",label:fs("Bar")},{value:"line",label:fs("Line")}];updateDataSeriesType(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],type:t},this.props.updateChart(this.props.chartId,{dataSets:s}))}getDataSeriesType(e){const t=this.props.definition.dataSets;return t?.[e]?t[e].type??"line":"bar"}}class QU extends t.Component{static template="o-spreadsheet-FunnelChartDesignPanel";static components={ChartShowValues:jU,GeneralDesignEditor:GU,SidePanelCollapsible:DP,RoundColorPicker:lM,Section:aM,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};getFunnelColorItems(){const e=this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig.data.labels||[],t=BC(e,this.props.definition.funnelColors);return e.map((e,s)=>({label:e||fs("Value %s",s+1),color:t[s]}))}updateFunnelItemColor(e,t){const s=je(this.props.definition.funnelColors||[],t,e);this.props.updateChart(this.props.chartId,{funnelColors:s})}}class eH extends t.Component{static template="o-spreadsheet-GaugeChartConfigPanel";static components={ChartErrorSection:NU,ChartDataSeries:MU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};state=t.useState({dataRangeDispatchResult:void 0});dataRange=this.props.definition.dataRange;get configurationErrorMessages(){return[...this.state.dataRangeDispatchResult?.reasons||[]].map(e=>Ig.Errors[e]||Ig.Errors.Unexpected)}get isDataRangeInvalid(){return!!this.state.dataRangeDispatchResult?.isCancelledBecause("InvalidGaugeDataRange")}onDataRangeChanged(e){this.dataRange=e[0],this.state.dataRangeDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataRange:this.dataRange})}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.chartId,{dataRange:this.dataRange})}getDataRange(){return{dataRange:this.dataRange||""}}}class tH extends t.Component{static template="o-spreadsheet-GaugeChartDesignPanel";static components={SidePanelCollapsible:DP,Section:aM,RoundColorPicker:lM,GeneralDesignEditor:GU,ChartErrorSection:NU,StandaloneComposer:JP,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};state;setup(){this.state=t.useState({sectionRuleCancelledReasons:this.checkSectionRuleFormulasAreValid(this.props.definition.sectionRule),sectionRule:ae(this.props.definition.sectionRule)})}get designErrorMessages(){return[...this.state.sectionRuleCancelledReasons||[]].map(e=>Ig.Errors[e]||Ig.Errors.Unexpected)}get isRangeMinInvalid(){return!(!this.state.sectionRuleCancelledReasons?.includes("EmptyGaugeRangeMin")&&!this.state.sectionRuleCancelledReasons?.includes("GaugeRangeMinNaN"))}get isRangeMaxInvalid(){return!(!this.state.sectionRuleCancelledReasons?.includes("EmptyGaugeRangeMax")&&!this.state.sectionRuleCancelledReasons?.includes("GaugeRangeMaxNaN"))}get isLowerInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.includes("GaugeLowerInflectionPointNaN")}get isUpperInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.includes("GaugeUpperInflectionPointNaN")}updateSectionColor(e,t){const s=ae(this.state.sectionRule);s.colors[e]=t,this.updateSectionRule(s)}updateSectionRule(e){this.state.sectionRuleCancelledReasons=[],this.state.sectionRuleCancelledReasons.push(...this.checkSectionRuleFormulasAreValid(this.state.sectionRule));const t=this.props.updateChart(this.props.chartId,{sectionRule:e});t.isSuccessful?this.state.sectionRule=ae(e):this.state.sectionRuleCancelledReasons.push(...t.reasons)}onConfirmGaugeRange(e,t){this.state.sectionRule={...this.state.sectionRule,[e]:t},this.updateSectionRule(this.state.sectionRule)}getGaugeInflectionComposerProps(e){const t="lowerColor"===e?"lowerInflectionPoint":"upperInflectionPoint",s=this.state.sectionRule[t];return{onConfirm:e=>{this.state.sectionRule={...this.state.sectionRule,[t]:{...s,value:e}},this.updateSectionRule(this.state.sectionRule)},composerContent:s.value,invalid:"lowerColor"===e?this.isLowerInflectionPointInvalid:this.isUpperInflectionPointInvalid,defaultRangeSheetId:this.sheetId,class:t,placeholder:fs("Value"),title:fs("Value or formula")}}checkSectionRuleFormulasAreValid(e){const t=[];return this.valueIsValidNumber(e.rangeMin)||t.push("GaugeRangeMinNaN"),this.valueIsValidNumber(e.rangeMax)||t.push("GaugeRangeMaxNaN"),this.valueIsValidNumber(e.lowerInflectionPoint.value)||t.push("GaugeLowerInflectionPointNaN"),this.valueIsValidNumber(e.upperInflectionPoint.value)||t.push("GaugeUpperInflectionPointNaN"),t}valueIsValidNumber(e){const t=this.env.model.getters.getLocale();if(!e.startsWith("="))return void 0!==So(e,t);const s=this.env.model.getters.evaluateFormula(this.sheetId,e);return!bi(s)&&void 0!==So(fi(s),t)}get sheetId(){const e=this.env.model.getters.getChart(this.props.chartId);if(!e)throw new Error("Chart not found with id "+this.props.chartId);return e.sheetId}}class sH extends t.Component{static template="o-spreadsheet-GeoChartRegionSelectSection";static components={Section:aM};static props={chartId:String,definition:Object,updateChart:Function};updateSelectedRegion(e){const t=e.target.value;this.props.updateChart(this.props.chartId,{region:t})}get availableRegions(){return this.env.model.getters.getGeoChartAvailableRegions()}get selectedRegion(){return this.props.definition.region||this.availableRegions[0]?.id}}class oH extends kU{static template="o-spreadsheet-GeoChartConfigPanel";static components={...kU.components,GeoChartRegionSelectSection:sH};get dataRanges(){return this.getDataSeriesRanges()}get disabledRanges(){return this.props.definition.dataSets.map((e,t)=>t>0)}getLabelRangeOptions(){return[{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}}const iH={minColor:"#FFF5EB",midColor:"#FD8D3C",maxColor:"#7F2704"};class nH extends YU{static template="o-spreadsheet-GeoChartDesignPanel";static components={...YU.components,RoundColorPicker:lM};colorScalesChoices=Ig.GeoChart.ColorScales;updateColorScaleType(e){const t=e.target.value;"custom"===t?this.updateColorScale(iH):this.updateColorScale(t)}updateColorScale(e){this.props.updateChart(this.props.chartId,{colorScale:e})}updateMissingValueColor(e){this.props.updateChart(this.props.chartId,{missingValueColor:e})}updateLegendPosition(e){const t=e.target.value;this.props.updateChart(this.props.chartId,{legendPosition:t})}get selectedColorScale(){return"object"==typeof this.props.definition.colorScale?"custom":this.props.definition.colorScale||"oranges"}get selectedMissingValueColor(){return this.props.definition.missingValueColor||"#ffffff"}get customColorScale(){if("object"==typeof this.props.definition.colorScale)return this.props.definition.colorScale}getCustomColorScaleColor(e){return this.customColorScale?.[e]??""}setCustomColorScaleColor(e,t){t||"midColor"===e||(t="#fff");const s=this.customColorScale;s&&this.updateColorScale({...s,[e]:t})}}class rH extends kU{static template="o-spreadsheet-HierarchicalChartConfigPanel";static components={...kU.components};getLabelRangeOptions(){return[{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}}class aH extends kU{static template="o-spreadsheet-LineConfigPanel";get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.chartId);return!!(e&&e instanceof JO)&&HI(e.getDefinition(),e.dataSets,e.labelRange,this.env.model.getters)}get stackedLabel(){return this.props.definition.fillArea?this.chartTerms.StackedAreaChart:this.chartTerms.StackedLineChart}getLabelRangeOptions(){const e=super.getLabelRangeOptions();return this.canTreatLabelsAsText&&e.push({name:"labelsAsText",value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}onUpdateLabelsAsText(e){this.props.updateChart(this.props.chartId,{labelsAsText:e})}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}}class lH extends KU{static template="o-spreadsheet-LineChartDesignPanel";static components={...KU.components,ChartShowDataMarkers:XU}}class cH extends t.Component{static template="o-spreadsheet.PieHoleSize";static components={Section:aM};static props={onValueChange:Function,value:Number};debouncedOnChange=De(this.onChange.bind(this),100);onChange(e){isNaN(Number(e))||this.props.onValueChange(ue(Number(e),0,95))}}class hH extends t.Component{static template="o-spreadsheet-PieChartDesignPanel";static components={GeneralDesignEditor:GU,Section:aM,ChartLegend:$U,ChartShowValues:jU,PieHoleSize:cH,Checkbox:IM,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}get defaultHoleSize(){return 50}}class dH extends t.Component{static template="o-spreadsheet-RadarChartDesignPanel";static components={GeneralDesignEditor:GU,SeriesDesignEditor:qU,Section:aM,ChartLegend:$U,ChartShowValues:jU,ChartShowDataMarkers:XU,Checkbox:IM,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function}}class uH extends ny{dataSets;labelRange;background;legendPosition;labelsAsText;aggregated;type="scatter";dataSetsHaveTitle;dataSetDesign;axesDesign;showValues;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=eC(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(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,this.zoomable=e.zoomable}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static transformDefinition(e,t,s){return iC(e,t,s)}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,zoomable:e.zoomable,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"scatter",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues,zoomable:this.zoomable,humanize:this.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new uH(i,this.sheetId,this.getters)}getDefinitionForExcel(){const e=this.dataSets.map(e=>sC(this.getters,e)).filter(e=>""!==e.range),t=oC(this.getters,this.labelRange,cC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:uI(this.background||c),fontColor:uI(nC(this.background)),dataSets:e,labelRange:t,verticalAxis:hC(s)}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new uH(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new uH(t,e,this.getters)}}class gH extends t.Component{static template="o-spreadsheet-ScorecardChartConfigPanel";static components={SelectionInput:fM,ChartErrorSection:NU,Section:aM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};state=t.useState({keyValueDispatchResult:void 0,baselineDispatchResult:void 0});keyValue=this.props.definition.keyValue;baseline=this.props.definition.baseline;get errorMessages(){return[...this.state.keyValueDispatchResult?.reasons||[],...this.state.baselineDispatchResult?.reasons||[]].map(e=>Ig.Errors[e]||Ig.Errors.Unexpected)}get isKeyValueInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause("InvalidScorecardKeyValue")}get isBaselineInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause("InvalidScorecardBaseline")}onKeyValueRangeChanged(e){this.keyValue=e[0],this.state.keyValueDispatchResult=this.props.canUpdateChart(this.props.chartId,{keyValue:this.keyValue})}updateKeyValueRange(){this.state.keyValueDispatchResult=this.props.updateChart(this.props.chartId,{keyValue:this.keyValue})}getKeyValueRange(){return this.keyValue||""}onBaselineRangeChanged(e){this.baseline=e[0],this.state.baselineDispatchResult=this.props.canUpdateChart(this.props.chartId,{baseline:this.baseline})}updateBaselineRange(){this.state.baselineDispatchResult=this.props.updateChart(this.props.chartId,{baseline:this.baseline})}getBaselineRange(){return this.baseline||""}updateBaselineMode(e){this.props.updateChart(this.props.chartId,{baselineMode:e.target.value})}}class pH extends t.Component{static template="o-spreadsheet-ScorecardChartDesignPanel";static components={GeneralDesignEditor:GU,RoundColorPicker:lM,SidePanelCollapsible:DP,Section:aM,Checkbox:IM,ChartTitle:HU,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};get colorsSectionTitle(){return"progress"===this.props.definition.baselineMode?fs("Progress bar colors"):fs("Baseline colors")}get defaultScorecardTitleFontSize(){return 14}translate(e){return this.env.model.getters.dynamicTranslate(e)}setColor(e,t){switch(t){case"backgroundColor":this.props.updateChart(this.props.chartId,{background:e});break;case"baselineColorDown":this.props.updateChart(this.props.chartId,{baselineColorDown:e});break;case"baselineColorUp":this.props.updateChart(this.props.chartId,{baselineColorUp:e})}}get keyStyle(){return{align:"center",fontSize:32,...this.props.definition.keyDescr}}get baselineStyle(){return{align:"center",fontSize:16,...this.props.definition.baselineDescr}}setKeyText(e){this.props.updateChart(this.props.chartId,{keyDescr:{...this.props.definition.keyDescr,text:e}})}updateKeyStyle(e){const t={...this.keyStyle,...e};this.props.updateChart(this.props.chartId,{keyDescr:t})}setBaselineText(e){this.props.updateChart(this.props.chartId,{baselineDescr:{...this.props.definition.baselineDescr,text:e}})}updateBaselineStyle(e){const t={...this.baselineStyle,...e};this.props.updateChart(this.props.chartId,{baselineDescr:t})}}class mH extends t.Component{static template="o-spreadsheet-SunburstChartDesignPanel";static components={GeneralDesignEditor:GU,Section:aM,SidePanelCollapsible:DP,ChartShowValues:jU,Checkbox:IM,TextStyler:OU,RoundColorPicker:lM,ChartLegend:$U,PieHoleSize:cH};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};defaults=Ew;get showValues(){return this.props.definition.showValues??Ew.showValues}get showLabels(){return this.props.definition.showLabels??Ew.showLabels}get groupColors(){const e=this.props.chartId,t=this.env.model.getters.getChartRuntime(e).chartJsConfig.data.datasets[0];return t?.groupColors||[]}onGroupColorChanged(e,t){const s=ae(this.props.definition.groupColors)??[];s[e]=t,this.props.updateChart(this.props.chartId,{groupColors:s})}onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}}class fH extends t.Component{static template="o-spreadsheet-TreeMapCategoryColors";static components={Checkbox:IM,RoundColorPicker:lM};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){const e=this.props.definition.coloringOptions??CC.coloringOptions;if("categoryColor"!==e.type)throw new Error("Coloring options is not solid color");return e}getTreeGroupAndColors(){const e=this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig;return e.data.datasets[0]?.groupColors||[]}onGroupColorChanged(e,t){const s=ae(this.coloringOptions);s.colors[e]=t||void 0,this.props.onColorChanged(s)}useValueBasedGradient(e){if("categoryColor"!==this.coloringOptions.type)throw new Error("Coloring options is not solid color");this.props.onColorChanged({...this.coloringOptions,useValueBasedGradient:e})}}class vH extends t.Component{static template="o-spreadsheet-TreeMapColorScale";static components={RoundColorPicker:lM};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){const e=this.props.definition.coloringOptions??CC.coloringOptions;if("colorScale"!==e.type)throw new Error("Coloring options is not a color scale");return e}setColorScaleColor(e,t){this.props.onColorChanged({...this.coloringOptions,[e]:t})}}const bH={type:"colorScale",minColor:"#FFF5EB",midColor:"#FD8D3C",maxColor:"#7F2704"},SH={type:"categoryColor",colors:[],useValueBasedGradient:!0};class CH extends t.Component{static template="o-spreadsheet-TreeMapChartDesignPanel";static components={GeneralDesignEditor:GU,Section:aM,SidePanelCollapsible:DP,ChartShowValues:jU,Checkbox:IM,TextStyler:OU,RoundColorPicker:lM,BadgeSelection:UU,TreeMapCategoryColors:fH,TreeMapColorScale:vH};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};savedColors={categoryColors:SH,colorScale:bH};defaults=CC;get showHeaders(){return this.props.definition.showHeaders??CC.showHeaders}get showValues(){return this.props.definition.showValues??CC.showValues}get showLabels(){return this.props.definition.showLabels??CC.showLabels}get coloringOptions(){return this.props.definition.coloringOptions??CC.coloringOptions}changeColoringOption(e){const t="categoryColor"===e?this.savedColors.categoryColors:this.savedColors.colorScale;this.props.updateChart(this.props.chartId,{coloringOptions:t})}onCategoryColorChange(e){this.savedColors.categoryColors=e,this.props.updateChart(this.props.chartId,{coloringOptions:e})}onColorScaleChange(e){this.savedColors.colorScale=e,this.props.updateChart(this.props.chartId,{coloringOptions:e})}get coloringOptionChoices(){return[{label:fs("Category color"),value:"categoryColor"},{label:fs("Color scale"),value:"colorScale"}]}}class yH extends t.Component{static template="o-spreadsheet-WaterfallChartDesignPanel";static components={GeneralDesignEditor:GU,ChartShowValues:jU,Checkbox:IM,SidePanelCollapsible:DP,Section:aM,RoundColorPicker:lM,AxisDesignEditor:zU,RadioSelection:BU,ChartLegend:$U,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};axisChoices=gC;onUpdateShowSubTotals(e){this.props.updateChart(this.props.chartId,{showSubTotals:e})}onUpdateShowConnectorLines(e){this.props.updateChart(this.props.chartId,{showConnectorLines:e})}onUpdateFirstValueAsSubtotal(e){this.props.updateChart(this.props.chartId,{firstValueAsSubtotal:e})}updateColor(e,t){this.props.updateChart(this.props.chartId,{[e]:t})}get axesList(){return[{id:"x",name:fs("Horizontal axis")},{id:"y",name:fs("Vertical axis")}]}get positiveValuesColor(){return this.props.definition.positiveValuesColor||m}get negativeValuesColor(){return this.props.definition.negativeValuesColor||f}get subTotalValuesColor(){return this.props.definition.subTotalValuesColor||v}updateVerticalAxisPosition(e){this.props.updateChart(this.props.chartId,{verticalAxisPosition:e})}onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}}const IH=new Og;IH.add("line",{configuration:aH,design:lH}).add("scatter",{configuration:class extends kU{static template="o-spreadsheet-ScatterConfigPanel";get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.chartId);return!!(e&&e instanceof uH)&&HI(e.getDefinition(),e.dataSets,e.labelRange,this.env.model.getters)}onUpdateLabelsAsText(e){this.props.updateChart(this.props.chartId,{labelsAsText:e})}getLabelRangeOptions(){const e=super.getLabelRangeOptions();return this.canTreatLabelsAsText&&e.push({name:"labelsAsText",value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}},design:KU}).add("bar",{configuration:VU,design:KU}).add("combo",{configuration:kU,design:JU}).add("pie",{configuration:kU,design:hH}).add("gauge",{configuration:eH,design:tH}).add("scorecard",{configuration:gH,design:pH}).add("waterfall",{configuration:kU,design:yH}).add("pyramid",{configuration:kU,design:YU}).add("radar",{configuration:kU,design:dH}).add("sunburst",{configuration:rH,design:mH}).add("geo",{configuration:oH,design:nH}).add("funnel",{configuration:class extends kU{getLabelRangeOptions(){const e=this.props.definition;return[{name:"aggregated",label:this.chartTerms.AggregatedChart,value:e.aggregated??!1,onChange:this.onUpdateAggregated.bind(this)},{name:"cumulative",label:this.chartTerms.CumulativeData,value:e.cumulative??!1,onChange:this.onUpdateCumulative.bind(this)},{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:e.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}},design:QU}).add("treemap",{configuration:rH,design:CH});const wH={line:fs("Line"),column:fs("Column"),bar:fs("Bar"),area:fs("Area"),pie:fs("Pie"),hierarchical:fs("Hierarchical"),misc:fs("Miscellaneous")};class EH extends t.Component{static template="o-spreadsheet-ChartTypePicker";static components={Section:aM,Popover:DF};static props={chartId:String,chartPanelStore:Object};categories=wH;chartTypeByCategories={};popoverRef=t.useRef("popoverRef");selectRef=t.useRef("selectRef");state=t.useState({popoverProps:void 0,popoverStyle:""});setup(){t.useExternalListener(window,"pointerdown",this.onExternalClick,{capture:!0});for(const e of f_.getAll())this.chartTypeByCategories[e.category]?this.chartTypeByCategories[e.category].push(e):this.chartTypeByCategories[e.category]=[e]}onExternalClick(e){Dy(this.popoverRef.el?.parentElement,e)||Dy(this.selectRef.el,e)||this.closePopover()}onTypeChange(e){this.props.chartPanelStore.changeChartType(this.props.chartId,e),this.closePopover()}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}getSelectedChartSubtypeProperties(){const e=this.getChartDefinition(this.props.chartId);return f_.getAll().find(t=>t.matcher?.(e)||!1)||f_.get(e.type)}onPointerDown(e){if(this.state.popoverProps)return void this.closePopover();const t=e.currentTarget,{bottom:s,right:o,width:i}=t.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:o,y:s,width:0,height:0},positioning:"top-right",verticalOffset:0},this.state.popoverStyle=Ey({width:`${i}px`})}closePopover(){this.state.popoverProps=void 0}}class RH extends hv{mutators=["activatePanel","changeChartType"];panel="configuration";creationContexts={};activatePanel(e){this.panel=e}changeChartType(e,t){const s=this.getters.getContextCreationChart(e),o=this.creationContexts[e]||{};let i=s?.range;i?.every((e,t)=>Me(e,o.range?.[t]))&&(i=Object.assign([],o.range,s?.range)),this.creationContexts[e]={...o,...s,range:i};const n=this.getters.getFigureIdFromChartId(e),r=this.getters.getFigureSheetId(n);if(!r)return;const a=this.getChartDefinitionFromContextCreation(e,t);this.model.dispatch("UPDATE_CHART",{definition:a,chartId:e,figureId:n,sheetId:r})}getChartDefinitionFromContextCreation(e,t){const s=f_.get(t);return{...$y.get(s.chartType).getChartDefinitionFromContextCreation(this.creationContexts[e]),...s.subtypeDefinition}}}class xH extends t.Component{static template="o-spreadsheet-ChartPanel";static components={Section:aM,ChartTypePicker:EH};static props={onCloseSidePanel:Function,chartId:String};panelContentRef;scrollPositions={configuration:0,design:0};store;get chartId(){return this.props.chartId}setup(){this.store=tv(RH),this.panelContentRef=t.useRef("panelContent"),t.useEffect(()=>{const e=this.panelContentRef.el,t=this.store.panel;e&&(e.scrollTop=this.scrollPositions[t])},()=>[this.store.panel])}switchPanel(e){const t=this.panelContentRef.el;t&&(this.scrollPositions[this.store.panel]=t.scrollTop),this.store.activatePanel(e)}updateChart(e,t){const s=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId)return;const o={...this.getChartDefinition(this.chartId),...t};return this.env.model.dispatch("UPDATE_CHART",{definition:o,chartId:e,figureId:s,sheetId:this.env.model.getters.getFigureSheetId(s)})}canUpdateChart(e,t){const s=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId||!this.env.model.getters.isChartDefined(e))return;const o={...this.getChartDefinition(this.chartId),...t};return this.env.model.canDispatch("UPDATE_CHART",{definition:o,chartId:e,figureId:s,sheetId:this.env.model.getters.getFigureSheetId(s)})}onTypeChange(e){this.chartId&&this.store.changeChartType(this.chartId,e)}get chartPanel(){if(!this.chartId)throw new Error("Chart not defined.");const e=this.env.model.getters.getChartType(this.chartId);if(!e)throw new Error("Chart not defined.");const t=IH.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}}class TH extends t.Component{static template="o-spreadsheet-IconPicker";static props={onIconPicked:Function};icons=gR;iconSets=pR;onIconClick(e){e&&this.props.onIconPicked(e)}}function AH(e,s){const o=function(e){const s=t.useState({hovered:!1});return eU(e,"mouseenter",()=>s.hovered=!0),eU(e,"mouseleave",()=>s.hovered=!1),s}(e);DH({get highlights(){return o.hovered?s.highlights:[]}})}function DH(e){const s=Qf(),o=tv(ZP);t.onMounted(()=>{o.register(e)});let i=e.highlights;t.useEffect(e=>{Me(e,i)||(i=e,s.trigger("store-updated"))},()=>[e.highlights])}class _H extends t.Component{static template="o-spreadsheet-ConditionalFormatPreview";icons=gR;ref=t.useRef("cfPreview");setup(){AH(this.ref,this)}getPreviewImageStyle(){const e=this.props.conditionalFormat.rule;if("CellIsRule"===e.type)return Ey(Iy(e.style));if("ColorScaleRule"===e.type){const t=fv(e.minimum.color),s=e.midpoint?fv(e.midpoint.color):null,o=fv(e.maximum.color),i="background-image: linear-gradient(to right, ";return s?i+t+", "+s+", "+o+")":i+t+", "+o+")"}if("DataBarRule"===e.type){return`background-image: linear-gradient(to right, ${fv(e.color)} 50%, white 50%)`}return""}getDescription(){const e=this.props.conditionalFormat;switch(e.rule.type){case"CellIsRule":return QT.get(e.rule.operator).getPreview({...e.rule,type:e.rule.operator},this.env.model.getters);case"ColorScaleRule":return yg.ColorScale;case"IconSetRule":return yg.IconSet;case"DataBarRule":return yg.DataBar}}deleteConditionalFormat(){this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:this.props.conditionalFormat.id,sheetId:this.env.model.getters.getActiveSheetId()})}onMouseDown(e){this.props.onMouseDown(e)}get highlights(){const e=this.env.model.getters.getActiveSheetId();return this.props.conditionalFormat.ranges.map(t=>({range:this.env.model.getters.getRangeFromSheetXC(e,t),color:o,fillAlpha:.06}))}}_H.props={conditionalFormat:Object,onPreviewClick:Function,onMouseDown:Function,class:String};class OH extends t.Component{static template="o-spreadsheet-ConditionalFormatPreviewList";static props={conditionalFormats:Array,onPreviewClick:Function,onAddConditionalFormat:Function};static components={ConditionalFormatPreview:_H};icons=gR;dragAndDrop=cM();cfListRef=t.useRef("cfList");setup(){t.onWillUpdateProps(e=>{Me(this.props.conditionalFormats,e.conditionalFormats)||this.dragAndDrop.cancel()})}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[e.id]||""}onPreviewMouseDown(e,t){if(0!==t.button)return;const s=Array.from(this.cfListRef.el.children).map(e=>Fy(e)),o=this.props.conditionalFormats.map((e,t)=>({id:e.id,size:s[t].height,position:s[t].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.id,initialMousePosition:t.clientY,items:o,scrollableContainerEl:this.cfListRef.el,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){const s=this.props.conditionalFormats.findIndex(t=>t.id===e)-t;0!==s&&this.env.model.dispatch("CHANGE_CONDITIONAL_FORMAT_PRIORITY",{cfId:e,delta:s,sheetId:this.env.model.getters.getActiveSheetId()})}}class FH extends t.Component{static template="o-spreadsheet-ConditionalFormattingEditor";static props={editedCf:Object,onCancel:Function,onExit:Function,isNewCf:Boolean};static components={SelectionInput:fM,IconPicker:TH,ColorPickerWidget:DU,ConditionalFormatPreviewList:OH,Section:aM,RoundColorPicker:lM,StandaloneComposer:JP,BadgeSelection:UU,ValidationMessages:JV,SelectMenu:CM};icons=gR;iconSets=pR;getTextDecoration=yy;colorNumberToHex=fv;state;setup(){switch(this.state=t.useState({errors:[],currentCFType:this.props.editedCf.rule.type,ranges:this.props.editedCf.ranges,rules:this.getDefaultRules(),hasEditedCf:this.props.isNewCf}),this.props.editedCf.rule.type){case"CellIsRule":this.state.rules.cellIs=this.props.editedCf.rule;break;case"ColorScaleRule":this.state.rules.colorScale=this.props.editedCf.rule;break;case"IconSetRule":this.state.rules.iconSet=this.props.editedCf.rule;break;case"DataBarRule":this.state.rules.dataBar=this.props.editedCf.rule}t.useExternalListener(window,"click",this.closeMenus)}get isRangeValid(){return this.state.errors.includes("EmptyRange")}get errorMessages(){return this.state.errors.map(e=>yg.Errors[e]||yg.Errors.Unexpected)}get cfTypesValues(){return[{value:"CellIsRule",label:fs("Single color")},{value:"ColorScaleRule",label:fs("Color scale")},{value:"IconSetRule",label:fs("Icon set")},{value:"DataBarRule",label:fs("Data bar")}]}updateConditionalFormat(e){const t=e.ranges||this.state.ranges;if(this.state.ranges.some(e=>!e.match(Xn)))return e.suppressErrors||(this.state.errors=["InvalidRange"]),["InvalidRange"];const s=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getLocale(),i=e.rule||this.getEditedRule(this.state.currentCFType),n=this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{rule:nh(i,o),id:this.props.editedCf.id},ranges:t.map(e=>this.env.model.getters.getRangeDataFromXc(s,e)),sheetId:s});n.isSuccessful&&(this.state.hasEditedCf=!0);const r=n.reasons.filter(e=>"NoChanges"!==e);return e.suppressErrors||(this.state.errors=r),r}getEditedRule(e){switch(e){case"CellIsRule":return this.state.rules.cellIs;case"ColorScaleRule":return this.state.rules.colorScale;case"IconSetRule":return this.state.rules.iconSet;case"DataBarRule":return this.state.rules.dataBar}}onSave(){0===this.updateConditionalFormat({}).length&&this.props.onExit()}onCancel(){this.state.hasEditedCf?this.props.onCancel():this.props.onExit()}getDefaultRules(){return{cellIs:{type:"CellIsRule",operator:"isNotEmpty",values:[],style:{fillColor:"#b6d7a8"}},colorScale:{type:"ColorScaleRule",minimum:{type:"value",color:KR("EFF7FF")},midpoint:void 0,maximum:{type:"value",color:6989903}},iconSet:{type:"IconSetRule",icons:{upper:"arrowGood",middle:"arrowNeutral",lower:"arrowBad"},upperInflectionPoint:{type:"percentage",value:"66",operator:"gt"},lowerInflectionPoint:{type:"percentage",value:"33",operator:"gt"}},dataBar:{type:"DataBarRule",color:14281427}}}changeRuleType(e){this.state.currentCFType!==e&&(this.state.errors=[],this.state.currentCFType=e,this.updateConditionalFormat({rule:this.getEditedRule(e),suppressErrors:!0}))}onRangeUpdate(e){this.state.ranges=e}onRangeConfirmed(){this.updateConditionalFormat({ranges:this.state.ranges})}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){return this.state.errors.includes("FirstArgMissing")||this.state.errors.includes("ValueCellIsInvalidFormula")}get isValue2Invalid(){return this.state.errors.includes("SecondArgMissing")}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.updateConditionalFormat({rule:this.state.rules.cellIs}),this.closeMenus()}onKeydown(e){if("F4"===e.key){const t=e.target,s=WP({start:t.selectionStart??0,end:t.selectionEnd??0},t.value,this.env.model.getters.getLocale());if(!s)return;t.value=s.content,t.setSelectionRange(s.selection.start,s.selection.end),t.dispatchEvent(new Event("input"))}}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.updateConditionalFormat({rule:this.state.rules.cellIs}),this.closeMenus()}editOperator(e){this.state.rules.cellIs.operator=e,this.updateConditionalFormat({rule:this.state.rules.cellIs,suppressErrors:!0}),this.closeMenus()}get cfCriterionMenuItems(){return SM(e=>this.editOperator(e),pI)}get selectedCriterionName(){return QT.get(this.state.rules.cellIs.operator).name}get criterionComponent(){return bM.get(this.state.rules.cellIs.operator).component}get genericCriterion(){return{type:this.state.rules.cellIs.operator,values:this.state.rules.cellIs.values}}onRuleValuesChanged(e){this.state.rules.cellIs.values=e.values,this.updateConditionalFormat({rule:{...this.state.rules.cellIs,values:e.values}})}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes("MinInvalidFormula")||this.state.errors.includes("MinBiggerThanMid")||this.state.errors.includes("MinBiggerThanMax")||this.state.errors.includes("MinNaN");case"midpoint":return this.state.errors.includes("MidInvalidFormula")||this.state.errors.includes("MidNaN")||this.state.errors.includes("MidBiggerThanMax");case"maximum":return this.state.errors.includes("MaxInvalidFormula")||this.state.errors.includes("MaxNaN");default:return!1}}setColorScaleColor(e,t){if(!Sv(t))return;const s=this.state.rules.colorScale[e];s&&(s.color=vv(t)),this.updateConditionalFormat({rule:this.state.rules.colorScale}),this.closeMenus()}getPreviewGradient(){const e=this.state.rules.colorScale,t=fv(e.minimum.color),s=fv(e.midpoint?.color||h),o=fv(e.maximum.color),i="background-image: linear-gradient(to right, ";return void 0===e.midpoint?i+t+", "+o+")":i+t+", "+s+", "+o+")"}getThresholdColor(e){return fv(e?e.color:h)}onMidpointChange(e){const t=e.target.value,s=this.state.rules.colorScale;s.midpoint="none"===t?void 0:{color:h,value:"",...s.midpoint,type:t},this.updateConditionalFormat({rule:s,suppressErrors:!0})}updateThresholdType(e,t){this.state.rules.colorScale[e].type=t,this.updateConditionalFormat({rule:this.state.rules.colorScale,suppressErrors:!0})}updateThresholdValue(e,t){this.state.rules.colorScale[e].value=t,this.updateConditionalFormat({rule:this.state.rules.colorScale})}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes("ValueLowerInflectionNaN")||this.state.errors.includes("ValueLowerInvalidFormula")||this.state.errors.includes("LowerBiggerThanUpper");case"upperInflectionPoint":return this.state.errors.includes("ValueUpperInflectionNaN")||this.state.errors.includes("ValueUpperInvalidFormula")||this.state.errors.includes("LowerBiggerThanUpper");default:return!0}}reverseIcons(){const e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setIconSet(e){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setIcon(e,t){this.state.rules.iconSet.icons[e]=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionOperator(e,t){this.state.rules.iconSet[e].operator=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionValue(e,t){this.state.rules.iconSet[e].value=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionType(e,t,s){this.state.rules.iconSet[e].type=t,this.updateConditionalFormat({rule:this.state.rules.iconSet,suppressErrors:!0})}getColorScaleComposerProps(e){const t=this.state.rules.colorScale[e];if(!t)throw new Error("Threshold not found");const s=this.isValueInvalid(e);return{onConfirm:e=>{t.value=e,this.updateConditionalFormat({rule:this.state.rules.colorScale})},composerContent:t.value||"",placeholder:fs("Formula"),defaultStatic:!0,invalid:s,class:"o-sidePanel-composer",defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getColorIconSetComposerProps(e){const t=this.state.rules.iconSet[e],s=this.isInflectionPointInvalid(e);return{onConfirm:e=>{t.value=e,this.updateConditionalFormat({rule:this.state.rules.iconSet})},composerContent:t.value||"",placeholder:fs("Formula"),defaultStatic:!0,invalid:s,class:"o-sidePanel-composer",defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getRangeValues(){return[this.state.rules.dataBar.rangeValues||""]}updateDataBarColor(e){Sv(e)&&(this.state.rules.dataBar.color=Number.parseInt(e.slice(1),16),this.updateConditionalFormat({rule:this.state.rules.dataBar}))}onDataBarRangeUpdate(e){this.state.rules.dataBar.rangeValues=e[0]}onDataBarRangeChange(){this.updateConditionalFormat({rule:this.state.rules.dataBar})}}class PH extends t.Component{static template="o-spreadsheet-ConditionalFormattingPanel";static props={selection:{type:Object,optional:!0},onCloseSidePanel:Function};static components={ConditionalFormatPreviewList:OH,ConditionalFormattingEditor:FH,Section:aM};activeSheetId;originalEditedCf=void 0;state=t.useState({mode:"list"});setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId();const e=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(1===s.length){const e=this.conditionalFormats.find(e=>e.id===s[0]);e&&this.editConditionalFormat(e)}t.onWillUpdateProps(e=>{const t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(1===s.length){const e=this.conditionalFormats.find(e=>e.id===s[0]);e&&this.editConditionalFormat(e)}else this.switchToList()}else this.editedCF||this.switchToList()})}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId()).map(e=>({...e,rule:rh(e.rule,this.env.model.getters.getLocale())}))}switchToList(){this.state.mode="list",this.state.editedCfId=void 0,this.originalEditedCf=void 0}addConditionalFormat(){const e=this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{sheetId:this.activeSheetId,ranges:this.env.model.getters.getSelectedZones().map(e=>this.env.model.getters.getRangeDataFromZone(this.activeSheetId,e)),cf:{id:e,rule:{type:"CellIsRule",operator:"isNotEmpty",style:{fillColor:"#b6d7a8"},values:[]}}}),this.state.editedCfId=e,this.state.mode="edit",this.originalEditedCf=void 0}editConditionalFormat(e){this.state.mode="edit",this.state.editedCfId=e.id,this.originalEditedCf=e}cancelEdition(){this.originalEditedCf?this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{sheetId:this.activeSheetId,ranges:this.originalEditedCf.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.activeSheetId,e)),cf:this.originalEditedCf}):this.state.editedCfId&&this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{sheetId:this.activeSheetId,id:this.state.editedCfId}),this.switchToList()}get editedCF(){return this.conditionalFormats.find(e=>e.id===this.state.editedCfId)}}const MH=new Og;class NH extends t.Component{static template="o-spreadsheet-CustomCurrencyPanel";static components={Section:aM,Checkbox:IM};static props={onCloseSidePanel:Function};availableCurrencies;state;setup(){this.availableCurrencies=[],this.state=t.useState({selectedCurrencyIndex:0,currencyCode:"",currencySymbol:"",selectedFormatIndex:0,isAccountingFormat:!1}),t.onWillStart(()=>this.updateAvailableCurrencies())}get formatProposals(){const e=this.availableCurrencies[this.state.selectedCurrencyIndex],t=e.position,s="before"===e.position?"after":"before",o=this.state.currencySymbol.trim()?this.state.currencySymbol:"",i=this.state.currencyCode.trim()?this.state.currencyCode:"",n=e.decimalPlaces;if(!o&&!i)return[];const r=[{symbol:o,position:t,decimalPlaces:0},{symbol:o,position:t,decimalPlaces:n},{symbol:o,position:t,decimalPlaces:0,code:i},{symbol:o,position:t,decimalPlaces:n,code:i},{symbol:o,position:s,decimalPlaces:0},{symbol:o,position:s,decimalPlaces:n},{symbol:o,position:s,decimalPlaces:0,code:i},{symbol:o,position:s,decimalPlaces:n,code:i}],a=new Set,l=this.env.model.getters.getLocale();return r.map(e=>{const t=Dn(e);if((e.symbol||e.code)&&!a.has(t))return a.add(t),{format:t,accountingFormat:_n(e),example:pn(1e3,{format:t,locale:l})}}).filter(Te)}get isSameFormat(){return!!this.selectedFormat&&this.selectedFormat===this.getCommonFormat()}async updateAvailableCurrencies(){if(0===MH.getAll().length){(await(this.env.loadCurrencies?.())||[]).forEach((e,t)=>{MH.add(t.toString(),e)})}const e={name:wg.Custom,code:"",symbol:"",decimalPlaces:2,position:"after"};this.availableCurrencies=[e,...MH.getAll()]}updateSelectCurrency(e){const t=e.target;this.state.selectedCurrencyIndex=parseInt(t.value,10);const s=this.availableCurrencies[this.state.selectedCurrencyIndex];this.state.currencyCode=s.code,this.state.currencySymbol=s.symbol}updateCode(e){const t=e.target;this.state.currencyCode=t.value,this.initAvailableCurrencies()}updateSymbol(e){const t=e.target;this.state.currencySymbol=t.value,this.initAvailableCurrencies()}updateSelectFormat(e){const t=e.target;this.state.selectedFormatIndex=parseInt(t.value,10)}apply(){this.env.model.dispatch("SET_FORMATTING_WITH_PIVOT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),format:this.selectedFormat})}initAvailableCurrencies(){this.state.selectedCurrencyIndex=0}getCommonFormat(){const e=this.env.model.getters.getSelectedZones(),t=this.env.model.getters.getActiveSheetId(),s=e.map(e=>this.env.model.getters.getEvaluatedCellsInZone(t,e)).flat(),o=s[0].format;return s.every(e=>e.format===o)?o:void 0}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:"")}toggleAccountingFormat(){this.state.isAccountingFormat=!this.state.isAccountingFormat}getFormatExamples(){const e=this.selectedFormat,t=this.env.model.getters.getLocale();return[{label:fs("positive")+":",value:pn(1234.56,{format:e,locale:t})},{label:fs("negative")+":",value:pn(-1234.56,{format:e,locale:t})},{label:fs("zero")+":",value:pn(0,{format:e,locale:t})}]}get selectedFormat(){const e=this.formatProposals[this.state.selectedFormatIndex];return this.state.isAccountingFormat?e?.accountingFormat:e?.format}}class LH extends t.Component{static template="o-spreadsheet-DataValidationEditor";static components={SelectionInput:fM,SelectMenu:CM,Section:aM,ValidationMessages:JV};static props={rule:{type:Object,optional:!0},onExit:Function,onCloseSidePanel:{type:Function,optional:!0}};state=t.useState({rule:this.defaultDataValidationRule,errors:[]});editingSheetId;setup(){this.editingSheetId=this.env.model.getters.getActiveSheetId(),this.props.rule&&(this.state.rule={...this.props.rule,ranges:this.props.rule.ranges.map(e=>this.env.model.getters.getRangeString(e,this.editingSheetId))},this.state.rule.criterion.type=this.props.rule.criterion.type)}onCriterionTypeChanged(e){this.state.rule.criterion.type=e}onRangesChanged(e){this.state.rule.ranges=e}onCriterionChanged(e){this.state.rule.criterion=e}changeRuleIsBlocking(e){const t=e.target.value;this.state.rule.isBlocking="true"===t}onSave(){if(this.state.rule){const e=this.env.model.dispatch("ADD_DATA_VALIDATION_RULE",this.dispatchPayload);e.isSuccessful?this.props.onExit():this.state.errors=e.reasons}}get dispatchPayload(){const e={...this.state.rule,ranges:void 0},t=this.env.model.getters.getLocale(),s=e.criterion,o=QT.get(s.type),i=s.values.slice(0,o.numberOfValues(s)).map(e=>e?.trim()).filter(e=>""!==e&&void 0!==e).map(e=>Jc(e,t));return e.criterion={...s,values:i},{sheetId:this.editingSheetId,ranges:this.state.rule.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.editingSheetId,e)),rule:e}}get dvCriterionMenuItems(){return SM(e=>this.onCriterionTypeChanged(e),mI)}get selectedCriterionName(){const e=this.state.rule.criterion.type;return QT.get(e).name}get defaultDataValidationRule(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones().map(t=>Tt(this.env.model.getters.getUnboundedZone(e,t)));return{id:this.env.model.uuidGenerator.smallUuid(),criterion:{type:"containsText",values:[""]},ranges:t}}get criterionComponent(){return bM.get(this.state.rule.criterion.type).component}get errorMessages(){return this.state.errors.map(e=>Ag.Errors[e]||Ag.Errors.Unexpected)}}class kH extends t.Component{static template="o-spreadsheet-DataValidationPreview";static props={onClick:Function,rule:Object};ref=t.useRef("dvPreview");setup(){AH(this.ref,this)}deleteDataValidation(){const e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("REMOVE_DATA_VALIDATION_RULE",{sheetId:e,id:this.props.rule.id})}get highlights(){return this.props.rule.ranges.map(e=>({range:e,color:o,fillAlpha:.06}))}get rangesString(){const e=this.env.model.getters.getActiveSheetId();return this.props.rule.ranges.map(t=>this.env.model.getters.getRangeString(t,e)).join(", ")}get descriptionString(){return QT.get(this.props.rule.criterion.type).getPreview(this.props.rule.criterion,this.env.model.getters)}}class VH extends t.Component{static template="o-spreadsheet-DataValidationPanel";static props={onCloseSidePanel:Function};static components={DataValidationPreview:kH,DataValidationEditor:LH};state=t.useState({mode:"list",activeRule:void 0});onPreviewClick(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getDataValidationRule(t,e);s&&(this.state.mode="edit",this.state.activeRule=s)}addDataValidationRule(){this.state.mode="edit",this.state.activeRule=void 0}onExitEditMode(){this.state.mode="list",this.state.activeRule=void 0}localizeDVRule(e){if(!e)return e;return ah(e,this.env.model.getters.getLocale())}get validationRules(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getDataValidationRules(e)}}const UH="#8B008B";var HH;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(HH||(HH={}));class zH extends hv{mutators=["updateSearchOptions","updateSearchContent","searchFormulas","selectPreviousMatch","selectNextMatch","replace"];allSheetsMatches=[];activeSheetMatches=[];specificRangeMatches=[];currentSearchRegex=null;initialShowFormulaState;preserveSelectedMatchIndex=!1;irreplaceableMatchCount=0;isSearchDirty=!1;shouldFinalizeUpdateSelection=!1;notificationStore=this.get(jP);selectedMatchIndex=null;toSearch="";toReplace="";searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1,searchScope:"activeSheet",specificRange:void 0};constructor(e){super(e),this.initialShowFormulaState=this.model.getters.shouldShowFormulas(),this.searchOptions.searchFormulas=this.initialShowFormulaState;const t=e(ZP);t.register(this),this.onDispose(()=>{this.model.dispatch("SET_FORMULA_VISIBILITY",{show:this.initialShowFormulaState}),t.unRegister(this)})}get searchMatches(){switch(this.searchOptions.searchScope){case"allSheets":return this.allSheetsMatches;case"activeSheet":return this.activeSheetMatches;case"specificRange":return this.specificRangeMatches}}updateSearchContent(e){this._updateSearch(e,this.searchOptions)}updateSearchOptions(e){this._updateSearch(this.toSearch,{...this.searchOptions,...e})}searchFormulas(e){this.model.dispatch("SET_FORMULA_VISIBILITY",{show:e}),this.updateSearchOptions({searchFormulas:e})}selectPreviousMatch(){this.selectNextCell(HH.previous,{jumpToMatchSheet:!0,updateSelection:!0})}selectNextMatch(){this.selectNextCell(HH.next,{jumpToMatchSheet:!0,updateSelection:!0})}handle(e){switch(e.type){case"SET_FORMULA_VISIBILITY":this.updateSearchOptions({searchFormulas:e.show});break;case"UNDO":case"REDO":case"REMOVE_TABLE":case"UPDATE_FILTER":case"REMOVE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"EVALUATE_CELLS":case"UPDATE_CELL":this.isSearchDirty=!0;break;case"ACTIVATE_SHEET":this.isSearchDirty=!0,this.shouldFinalizeUpdateSelection=!0;break;case"REPLACE_SEARCH":for(const t of e.matches)this.replaceMatch(t,e.searchString,e.replaceWith,e.searchOptions);this.irreplaceableMatchCount>0&&this.showReplaceWarningMessage(e.matches.length,this.irreplaceableMatchCount),this.irreplaceableMatchCount=0}}finalize(){this.isSearchDirty&&(this.refreshSearch({jumpToMatchSheet:!1,updateSelection:this.shouldFinalizeUpdateSelection}),this.shouldFinalizeUpdateSelection=!1,this.isSearchDirty=!1)}get allSheetMatchesCount(){return this.allSheetsMatches.length}get activeSheetMatchesCount(){return this.activeSheetMatches.length}get specificRangeMatchesCount(){return this.specificRangeMatches.length}_updateSearch(e,t){this.searchOptions=t,e!==this.toSearch&&(this.selectedMatchIndex=null),this.toSearch=e,this.currentSearchRegex=Xe(this.toSearch,this.searchOptions),this.refreshSearch({jumpToMatchSheet:!0,updateSelection:!0})}refreshSearch(e){this.preserveSelectedMatchIndex||(this.selectedMatchIndex=null),this.findMatches(),this.selectNextCell(HH.current,e)}getSheetsInSearchOrder(){switch(this.searchOptions.searchScope){case"allSheets":const e=this.getters.getSheetIds(),t=e.findIndex(e=>e===this.getters.getActiveSheetId());return[e[t],...e.slice(t+1),...e.slice(0,t)];case"activeSheet":return[this.getters.getActiveSheetId()];case"specificRange":const s=this.searchOptions.specificRange;return s&&s?[s.sheetId]:[]}}findMatches(){const e=[];if(this.toSearch)for(const t of this.getters.getSheetIds())e.push(...this.findMatchesInSheet(t));if(this.allSheetsMatches=e,this.activeSheetMatches=e.filter(e=>e.sheetId===this.getters.getActiveSheetId()),this.searchOptions.specificRange){const{sheetId:t,zone:s}=this.searchOptions.specificRange;this.specificRangeMatches=e.filter(e=>e.sheetId===t&&kt(e.col,e.row,s))}else this.specificRangeMatches=[]}findMatchesInSheet(e){const t=[],{left:s,right:o,top:i,bottom:n}=this.getters.getSheetZone(e);for(let r=i;r<=n;r++)for(let i=s;i<=o;i++){const s=this.getters.isColHidden(e,i),o=this.getters.isRowHidden(e,r);if(s||o)continue;const n={sheetId:e,col:i,row:r};if(this.currentSearchRegex?.test(this.getSearchableString(n))){const s={sheetId:e,col:i,row:r};t.push(s)}}return t}selectNextCell(e,t){const s=this.searchMatches;if(!s.length)return void(this.selectedMatchIndex=null);let o;if(null===this.selectedMatchIndex){let e=-1;for(const t of this.getSheetsInSearchOrder())if(e=s.findIndex(e=>e.sheetId===t),-1!==e)break;o=e}else o=this.selectedMatchIndex+e;o=(o+s.length)%s.length,this.selectedMatchIndex=o;const i=s[o];t.jumpToMatchSheet&&this.getters.getActiveSheetId()!==i.sheetId&&(this.preserveSelectedMatchIndex=!0,this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:i.sheetId}),this.preserveSelectedMatchIndex=!1,this.isSearchDirty=!1),this.model.selection.getBackToDefault(),t.updateSelection&&this.model.selection.selectCell(i.col,i.row)}replace(){null!==this.selectedMatchIndex&&(this.preserveSelectedMatchIndex=!0,this.shouldFinalizeUpdateSelection=!0,this.model.dispatch("REPLACE_SEARCH",{searchString:this.toSearch,replaceWith:this.toReplace,matches:[this.searchMatches[this.selectedMatchIndex]],searchOptions:this.searchOptions}),this.preserveSelectedMatchIndex=!1)}replaceAll(){this.model.dispatch("REPLACE_SEARCH",{searchString:this.toSearch,replaceWith:this.toReplace,matches:this.searchMatches,searchOptions:this.searchOptions})}showReplaceWarningMessage(e,t){const s=e-t;0===s?this.notificationStore.notifyUser({type:"warning",sticky:!1,text:fs("Match(es) cannot be replaced as they are part of a formula.")}):this.notificationStore.notifyUser({type:"warning",sticky:!1,text:fs("%(replaceable_count)s match(es) replaced. %(irreplaceable_count)s match(es) cannot be replaced as they are part of a formula.",{replaceable_count:s,irreplaceable_count:t})})}replaceMatch(e,t,s,o){const i=this.getters.getCell(e);if(!i?.content)return;if(i?.isFormula&&!o.searchFormulas)return void this.irreplaceableMatchCount++;const n=Xe(t,o),r=new RegExp(n.source,n.flags+"g"),a=Kc(this.getters.getCellText(e,{showFormula:o.searchFormulas}).replace(r,s),this.getters.getLocale());this.model.dispatch("UPDATE_CELL",{...e,content:a})}getSearchableString(e){return this.getters.getCellText(e,{showFormula:this.searchOptions.searchFormulas})}get highlights(){const e=[],t=this.getters.getActiveSheetId();for(const[s,o]of this.searchMatches.entries()){if(o.sheetId!==t)continue;const i=Zt(o),n=this.getters.expandZone(t,i),{width:r,height:a}=this.getters.getVisibleRect(n);r>0&&a>0&&e.push({range:this.model.getters.getRangeFromZone(t,n),color:UH,noBorder:s!==this.selectedMatchIndex,thinLine:!0,fillAlpha:.2})}if("specificRange"===this.searchOptions.searchScope){const s=this.searchOptions.specificRange;s&&s.sheetId===t&&e.push({range:s,color:UH,noFill:!0,thinLine:!0})}return e}}class BH extends t.Component{static template="o-spreadsheet-FindAndReplacePanel";static components={SelectionInput:fM,Section:aM,Checkbox:IM,ValidationMessages:JV};static props={onCloseSidePanel:Function};searchInput=t.useRef("searchInput");store;state;updateSearchContent;get hasSearchResult(){return null!==this.store.selectedMatchIndex}get searchOptions(){return this.store.searchOptions}get allSheetsMatchesCount(){return fs("%s matches in all sheets",this.store.allSheetMatchesCount)}get currentSheetMatchesCount(){return fs("%(matches)s matches in %(sheetName)s",{matches:this.store.activeSheetMatchesCount,sheetName:this.env.model.getters.getSheetName(this.env.model.getters.getActiveSheetId())})}get specificRangeMatchesCount(){const e=this.searchOptions.specificRange;if(!e)return"";const{sheetId:t,zone:s}=e;return fs("%(matches)s matches in range %(range)s of %(sheetName)s",{matches:this.store.specificRangeMatchesCount,range:Tt(s),sheetName:this.env.model.getters.getSheetName(t)})}get searchInfo(){return this.store.toSearch?[this.specificRangeMatchesCount,this.currentSheetMatchesCount,this.allSheetsMatchesCount]:[]}setup(){this.store=tv(zH),this.state=t.useState({dataRange:""}),t.onMounted(()=>this.searchInput.el?.focus()),t.onWillUnmount(()=>this.updateSearchContent.stopDebounce()),this.updateSearchContent=De(this.store.updateSearchContent,200),t.useExternalListener(window,"keydown",e=>{const t=ky(e);"Ctrl+F"!==t&&"Ctrl+H"!==t||(this.searchInput.el?.focus(),e.preventDefault(),e.stopPropagation())},{capture:!0})}onFocusSearch(){this.updateDataRange()}onSearchInput(e){this.updateSearchContent(e.target.value)}onKeydownSearch(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),e.shiftKey?this.store.selectPreviousMatch():this.store.selectNextMatch())}onKeydownReplace(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),this.store.replace())}searchFormulas(e){this.store.searchFormulas(e)}searchExactMatch(e){this.store.updateSearchOptions({exactMatch:e})}searchMatchCase(e){this.store.updateSearchOptions({matchCase:e})}changeSearchScope(e){const t=e.target.value;this.store.updateSearchOptions({searchScope:t})}onSearchRangeChanged(e){this.state.dataRange=e[0]}updateDataRange(){if(!this.state.dataRange||"specificRange"!==this.searchOptions.searchScope)return;const e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.dataRange);this.store.updateSearchOptions({specificRange:e})}get pendingSearch(){return this.updateSearchContent.isDebouncePending()}}const GH=qf([Zk,jk,Yk,Xk,Kk,Jk,Qk,eV,tV,Hk,zk,Bk,Gk,Wk,$k]);class WH extends t.Component{static template="o-spreadsheet-MoreFormatsPanel";static props={onCloseSidePanel:Function};get dateFormatsActions(){return GH}}class $H extends hv{pivotId;initialMeasure;mutators=["cancelMeasureDisplayEdition","updateMeasureDisplayType","updateMeasureDisplayField","updateMeasureDisplayValue"];measureDisplay;constructor(e,t,s){super(e),this.pivotId=t,this.initialMeasure=s,this.measureDisplay=s.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){const t=ae(this.model.getters.getPivotCoreDefinition(this.pivotId)),s=this.getMeasureIndex(this.initialMeasure.id,t),o={...t.measures[s],display:e};t.measures[s]=o;this.model.dispatch("UPDATE_PIVOT",{pivot:t,pivotId:this.pivotId}).isSuccessful&&(this.measureDisplay=e)}getMeasureDisplay(e,t,s){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||(t=this.fields[0]?.nameWithGranularity),{type:e,fieldNameWithGranularity:t};case"%_of":case"difference_from":case"%_difference_from":t||(t=this.fields[0]?.nameWithGranularity);const o=this.getPossibleValues(t);return void 0!==s&&o.find(e=>e.value===s)||(s=fI),{type:e,fieldNameWithGranularity:t,value:s??fI}}}getMeasureIndex(e,t){const s=t.measures.findIndex(t=>t.id===e);if(-1===s)throw new Error(`Measure with id ${e} not found in pivot.`);return s}get doesDisplayNeedsField(){return["%_of_parent_total","running_total","%_running_total","rank_asc","rank_desc"].includes(this.measureDisplay.type)||this.doesDisplayNeedsValue}get fields(){const e=this.getters.getPivot(this.pivotId).definition;return[...e.columns,...e.rows].map(e=>({...e,displayName:dp(e)}))}get doesDisplayNeedsValue(){return this.isDisplayValueDependant(this.measureDisplay)}isDisplayValueDependant(e){return["%_of","difference_from","%_difference_from"].includes(e.type)}get values(){const e=this.measureDisplay;return this.isDisplayValueDependant(e)?this.getPossibleValues(e.fieldNameWithGranularity):[]}getPossibleValues(e){const t=[{value:fI,label:fs("(previous)")},{value:vI,label:fs("(next)")}],s=this.fields.find(t=>t.nameWithGranularity===e);if(!s)return[];return[...t,...this.getters.getPivot(this.pivotId).getPossibleFieldValues(s)]}cancelMeasureDisplayEdition(){const e=ae(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})}}class qH extends t.Component{static template="o-spreadsheet-PivotMeasureDisplayPanel";static props={onCloseSidePanel:Function,pivotId:String,measure:Object};static components={Section:aM,Checkbox:IM,RadioSelection:BU};measureDisplayTypeLabels=_g.labels;measureDisplayDescription=_g.documentation;store;setup(){this.store=tv($H,this.props.pivotId,this.props.measure)}onSave(){this.env.replaceSidePanel("PivotSidePanel",`pivot_measure_display_${this.props.pivotId}_${this.props.measure.id}`,{pivotId:this.props.pivotId})}onCancel(){this.store.cancelMeasureDisplayEdition(),this.env.replaceSidePanel("PivotSidePanel",`pivot_measure_display_${this.props.pivotId}_${this.props.measure.id}`,{pivotId:this.props.pivotId})}get fieldChoices(){return this.store.fields.map(e=>({value:e.nameWithGranularity,label:e.displayName}))}}function ZH(e,t){const s=e.getActiveSheetId(),i=function(e,t){const s=[],o=e.getActiveSheetId();for(const i of e.getSheetViewVisibleCols())for(const n of e.getSheetViewVisibleRows()){const r={sheetId:o,col:i,row:n};t===e.getPivotIdFromPosition(r)&&s.push(r)}return s}(e,t);return es(i.map(Zt)).map(t=>({range:e.getRangeFromZone(s,t),noFill:!0,color:o}))}class jH extends t.Component{static template="o-spreadsheet-PivotDeferUpdate";static props={deferUpdate:Boolean,isDirty:Boolean,toggleDeferUpdate:Function,discard:Function,apply:Function};static components={Section:aM,Checkbox:IM};get deferUpdatesLabel(){return fs("Defer updates")}get deferUpdatesTooltip(){return fs("Changing the pivot definition requires to reload the data. It may take some time.")}}class YH extends t.Component{static template="o-spreadsheet-PivotCustomGroupsCollapsible";static props={pivotId:String,customField:Object,onCustomFieldUpdated:Function};static components={SidePanelCollapsible:DP,TextInput:TU,Checkbox:IM};get groups(){return this.props.customField.groups.sort((e,t)=>e.isOtherGroup||t.isOtherGroup?e.isOtherGroup?1:-1:0)}get hasOthersGroup(){return this.props.customField.groups.some(e=>e.isOtherGroup)}addOthersGroup(){if(this.hasOthersGroup)return;const e={name:pp(fs("Others"),this.props.customField),values:[],isOtherGroup:!0},t=[...this.props.customField.groups,e];this.updateCustomField({...this.props.customField,groups:t})}onDeleteGroup(e){const t=[...this.props.customField.groups];t.splice(e,1),this.updateCustomField({...this.props.customField,groups:t})}onRenameGroup(e,t){const s=ae(this.props.customField.groups),o=s[e];o&&(o.name=pp(t,this.props.customField),this.updateCustomField({...this.props.customField,groups:s}))}updateCustomField(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.props.onCustomFieldUpdated({customFields:{...t.customFields,[e.name]:e}})}}function XH(e,t,s,o){const i=[];e=e.toLowerCase();for(const n of e){const e=t.toLocaleLowerCase().indexOf(n);-1!==e&&(i.push({value:t.slice(0,e),color:""},{value:t[e],color:s,classes:[o]}),t=t.slice(e+1))}return i.push({value:t}),i.filter(e=>e.value)}class KH extends t.Component{static template="o-spreadsheet-AddDimensionButton";static components={Popover:DF,TextValueProvider:MP};static props={onFieldPicked:Function,fields:Array,slots:{type:Object,optional:!0}};buttonRef=t.useRef("button");popover=t.useState({isOpen:!1});search=t.useState({input:""});autoComplete;setup(){this.autoComplete=tv(YP),this.autoComplete.useProvider(this.getProvider()),t.useExternalListener(window,"click",e=>{e.target!==this.buttonRef.el&&(this.popover.isOpen=!1)}),xU({refName:"autofocus"})}getProvider(){return{proposals:this.proposals,autoSelectFirstProposal:!1,selectProposal:e=>{const t=this.props.fields.find(t=>t.string===e);t&&this.pickField(t)}}}get proposals(){let e;return e=this.search.input?tS(this.search.input,this.props.fields,e=>e.string):this.props.fields,e.map(e=>{const t=e.string;return{text:t,fuzzySearchKey:t,htmlContent:XH(this.search.input,t,g,"o-semi-bold")}})}get popoverProps(){const{x:e,y:t,width:s,height:o}=this.buttonRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:s,height:o},positioning:"bottom-left"}}updateSearch(e){this.search.input=e,this.autoComplete.useProvider(this.getProvider())}pickField(e){this.props.onFieldPicked(e.name),this.togglePopover()}togglePopover(){this.popover.isOpen=!this.popover.isOpen,this.search.input="",this.autoComplete.useProvider(this.getProvider())}onKeyDown(e){switch(e.key){case"Enter":const t=this.autoComplete.provider?.proposals;1===t?.length&&this.autoComplete.provider?.selectProposal(t[0].text||"");const s=this.autoComplete.selectedProposal;this.autoComplete.provider?.selectProposal(s?.text||"");break;case"ArrowUp":case"ArrowDown":this.autoComplete.moveSelection("ArrowDown"===e.key?"next":"previous");break;case"Escape":this.popover.isOpen=!1}}}class JH extends t.Component{static template="o-spreadsheet-PivotDimension";static props={dimension:Object,onRemoved:{type:Function,optional:!0},onNameUpdated:{type:Function,optional:!0},slots:{type:Object,optional:!0}};static components={CogWheelMenu:FU,TextInput:TU};updateName(e){this.props.onNameUpdated?.(this.props.dimension,""===e||e.startsWith("=")?void 0:e)}}class QH extends t.Component{static template="o-spreadsheet-PivotDimensionGranularity";static props={dimension:Object,onUpdated:Function,availableGranularities:Set,allGranularities:Array};periods=Jg}class ez extends t.Component{static template="o-spreadsheet-PivotDimensionOrder";static props={dimension:Object,onUpdated:Function}}class tz extends t.Component{static template="o-spreadsheet-PivotMeasureEditor";static components={PivotDimension:JH,StandaloneComposer:JP};static props={definition:Object,measure:Object,onMeasureUpdated:Function,onRemoved:Function,generateMeasureId:Function,aggregators:Object,pivotId:String};getMeasureAutocomplete(){return e=this.props.definition,t=this.props.measure,{sequence:0,autoSelectFirstProposal:!0,getProposals(s){const o=e.measures.filter(e=>e!==t).map(e=>{const t=he(e.id);return{text:t,description:e.displayName,htmlContent:[{value:t,color:x}],fuzzySearchKey:e.displayName+t+e.fieldName}}),i=e.rows.concat(e.columns).map(e=>{const t=he(e.nameWithGranularity);return{text:t,description:e.displayName,htmlContent:[{value:t,color:x}],fuzzySearchKey:e.displayName+t+e.fieldName}});return o.concat(i)},selectProposal(e,t){let s=e.end;"SYMBOL"===e.type&&(s=e.start);const o=e.end;this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)}};var e,t}updateMeasureFormula(e){this.props.onMeasureUpdated({...this.props.measure,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:"="===e[0]?e:"="+e}})}updateAggregator(e){this.props.onMeasureUpdated({...this.props.measure,aggregator:e,id:this.props.generateMeasureId(this.props.measure.fieldName,e)})}updateName(e,t){this.props.measure.computedBy&&t?this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t,id:this.props.generateMeasureId(t,this.props.measure.aggregator),fieldName:t}):this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t})}toggleMeasureVisibility(){this.props.onMeasureUpdated({...this.props.measure,isHidden:!this.props.measure.isHidden})}openShowValuesAs(){this.env.replaceSidePanel("PivotMeasureDisplayPanel",`pivot_key_${this.props.pivotId}`,{pivotId:this.props.pivotId,measure:this.props.measure})}getColoredSymbolToken(e){if("SYMBOL"!==e.type)return;const t=ce(e.value,"'");return this.props.definition.columns.some(e=>e.nameWithGranularity===t)||this.props.definition.rows.some(e=>e.nameWithGranularity===t)||this.props.definition.measures.some(e=>e.id===t&&e.id!==this.props.measure.id)?x:void 0}get isCalculatedMeasureInvalid(){return sE(this.props.measure.computedBy?.formula??"").isBadExpression}}class sz extends t.Component{static template="o-spreadsheet-PivotSortSection";static components={Section:aM};static props={definition:Object,pivotId:String};get hasValidSort(){const e=this.env.model.getters.getPivot(this.props.pivotId);return!!this.props.definition.sortedColumn&&gp(this.props.definition.sortedColumn,e)}get sortDescription(){const e="asc"===this.props.definition.sortedColumn?.order?fs("ascending"):fs("descending");return fs("Sorted on column (%(ascOrDesc)s):",{ascOrDesc:e})}get sortValuesAndFields(){const e=this.props.definition.sortedColumn;if(!e)return[];const t=this.env.model.getters.getPivot(this.props.pivotId),s=this.env.model.getters.getLocale(),o=[],i=[];for(const n of e.domain){o.push(n);const{value:e,format:r}=t.getPivotHeaderValueAndFormat(o),a=pn(e,{format:r,locale:s}),l=t.definition.getDimension(n.field);i.push({field:dp(l),value:a})}0===e.domain.length&&i.push({value:fs("Total")});const n=t.getMeasure(e.measure).displayName;return i.push({value:n,field:fs("Measure")}),i}}class oz extends t.Component{static template="o-spreadsheet-PivotLayoutConfigurator";static components={AddDimensionButton:KH,PivotDimension:JH,PivotDimensionOrder:ez,PivotDimensionGranularity:QH,PivotMeasureEditor:tz,PivotSortSection:sz,PivotCustomGroupsCollapsible:YH};static props={definition:Object,onDimensionsUpdated:Function,unusedGroupableFields:Array,measureFields:Array,unusedGranularities:Object,dateGranularities:Array,datetimeGranularities:Array,getScrollableContainerEl:{type:Function,optional:!0},pivotId:String};dimensionsRef=t.useRef("pivot-dimensions");dragAndDrop=cM();AGGREGATORS=Yg;composerFocus;isDateOrDatetimeField=tp;setup(){this.composerFocus=ev(uv)}startDragAndDrop(e,t){if(0!==t.button||"SELECT"===t.target.tagName)return;const s=this.getDimensionElementsRects(),o=this.props.definition,{columns:i,rows:n}=o,r=[...i.map(e=>e.nameWithGranularity),"__rows_title__",...n.map(e=>e.nameWithGranularity)],a=i.concat(n),l=r.map((e,t)=>({id:e,size:s[t+1].height,position:s[t+1].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:l,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{const s=r.findIndex(t=>t===e);if(s===t)return;const o=[...r];o.splice(s,1),o.splice(t,0,e);const i=o.slice(0,o.indexOf("__rows_title__")),n=o.slice(o.indexOf("__rows_title__")+1);this.props.onDimensionsUpdated({columns:i.map(e=>a.find(t=>t.nameWithGranularity===e)).filter(Te),rows:n.map(e=>a.find(t=>t.nameWithGranularity===e)).filter(Te)})}})}getGranularitiesFor(e){return tp(e)?"date"===e.type?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(0!==t.button||"SELECT"===t.target.tagName||"INPUT"===t.target.tagName||"inactive"!==this.composerFocus.focusMode)return;const s=this.getDimensionElementsRects(),o=this.props.definition,{measures:i,columns:n,rows:r}=o,a=i.map(e=>e.id),l=3+n.length+r.length,c=a.map((e,t)=>({id:e,size:s[t+l].height,position:s[t+l].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{const s=a.findIndex(t=>t===e);if(s===t)return;const o=[...a];o.splice(s,1),o.splice(t,0,e),this.props.onDimensionsUpdated({measures:o.map(e=>i.find(t=>t.id===e)).filter(Te)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{const t=getComputedStyle(e),s=e.getBoundingClientRect();return{x:s.x,y:s.y,width:s.width+parseInt(t.marginLeft||"0")+parseInt(t.marginRight||"0"),height:s.height+parseInt(t.marginTop||"0")+parseInt(t.marginBottom||"0")}})}removeDimension(e){const{columns:t,rows:s}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:s.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){const{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){const{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:"asc"}])})}addRowDimension(e){const{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:"asc"}])})}addMeasureDimension(e){const{measures:t}=this.props.definition,s=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,s),fieldName:e,aggregator:s}])})}updateMeasure(e,t){const{measures:s}=this.props.definition,o={measures:s.map(s=>s.id===e.id?t:s)};this.props.definition.sortedColumn?.measure===e.id&&(o.sortedColumn={...this.props.definition.sortedColumn,measure:t.id}),this.props.onDimensionsUpdated(o)}getMeasureId(e,t){const s=e.replaceAll("'","")+(t?`:${t}`:"");let o=s,i=2;for(;this.props.definition.measures.some(e=>e.id===o);)o=`${s}:${i}`,i++;return o}getDefaultMeasureAggregator(e){const t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:"count"}addCalculatedMeasure(){const{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"}}])})}getCustomField(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);return t.customFields?.[e.nameWithGranularity]}updateOrder(e,t){const{rows:s,columns:o}=this.props.definition;this.props.onDimensionsUpdated({rows:s.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,order:t||void 0}:s),columns:o.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,order:t||void 0}:s)})}updateGranularity(e,t){const{rows:s,columns:o}=this.props.definition;this.props.onDimensionsUpdated({rows:s.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,granularity:t}:s),columns:o.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,granularity:t}:s)})}getMeasureDescription(e){const t=e.display;if(!t||"no_calculations"===t.type)return"";const s=this.env.model.getters.getPivot(this.props.pivotId),o=[...s.definition.columns,...s.definition.rows].find(e=>e.nameWithGranularity===t.fieldNameWithGranularity),i=o?dp(o):"";return _g.descriptions[t.type](i)}getHugeDimensionErrorMessage(e){const t=this.env.model.getters.getPivot(this.props.pivotId).getPossibleFieldValues(e);return t.length>100?fs("This dimension contains a lot of values (%s), and might slow down the pivot table.",t.length):void 0}}class iz extends t.Component{static template="o-spreadsheet-PivotTitleSection";static components={CogWheelMenu:FU,Section:aM,TextInput:TU};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:fs("Flip axes"),icon:"o-spreadsheet-Icon.EXCHANGE",execute:this.props.flipAxis},{name:fs("Duplicate"),icon:"o-spreadsheet-Icon.COPY",execute:()=>this.duplicatePivot()},{name:fs("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(){const e=this.env.model.uuidGenerator.smallUuid(),t=this.env.model.uuidGenerator.smallUuid(),s=this.env.model.dispatch("DUPLICATE_PIVOT_IN_NEW_SHEET",{pivotId:this.props.pivotId,newPivotId:e,newSheetId:t});let o;o=s.isSuccessful?fs("Pivot duplicated."):s.isCancelledBecause("PivotInError")?fs("Cannot duplicate a pivot in error."):fs("Pivot duplication failed.");const i=s.isSuccessful?"success":"danger";this.env.notifyUser({text:o,sticky:!1,type:i}),s.isSuccessful&&this.env.openSidePanel("PivotSidePanel",{pivotId:e})}delete(){this.env.askConfirmation(fs("Are you sure you want to delete this pivot?"),()=>{this.env.model.dispatch("REMOVE_PIVOT",{pivotId:this.props.pivotId})})}onNameChanged(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch("UPDATE_PIVOT",{pivotId:this.props.pivotId,pivot:{...t,name:e}})}}class nz extends hv{pivotId;mutators=["reset","deferUpdates","applyUpdate","discardPendingUpdate","update"];updatesAreDeferred;draft=null;notification=this.get(jP);alreadyNotified=!1;alreadyNotifiedForPivotSize=!1;constructor(e,t){super(e),this.pivotId=t,this.updatesAreDeferred=this.getters.getPivotCoreDefinition(this.pivotId).deferUpdates??!1}handle(e){if("UPDATE_PIVOT"===e.type)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(){const e=XD.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(){const e=[{name:"__count",string:fs("Count"),type:"integer",aggregator:"sum"}],t=this.fields;for(const s in t){const o=t[s];o&&(XD.get(this.pivot.type).isMeasureCandidate(o)&&e.push(o))}return e.sort((e,t)=>e.string.localeCompare(t.string))}get unusedGroupableFields(){const e=[],t=this.fields;for(const s in t){const o=t[s];o&&(XD.get(this.pivot.type).isGroupable(o)&&e.push(o))}const{columns:s,rows:o,measures:i}=this.definition,n=i.concat(o).concat(s).map(e=>e.fieldName),r=this.unusedGranularities;return e.filter(e=>tp(e)?!n.includes(e.name)||r[e.name].size>0:!n.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get datetimeGranularities(){return XD.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return XD.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){!1===e&&this.draft?(this.draft.deferUpdates=!1,this.applyUpdate()):this.update({deferUpdates:e}),this.updatesAreDeferred=e}applyUpdate(){if(this.draft){if(this.model.dispatch("UPDATE_PIVOT",{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&this.isUpdatedPivotVisibleInViewportOnlyAsStaticPivot()){const e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:"info",text:fs("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})}const e=this.getters.getPivot(this.pivotId),t=e.isValid()?e.getExpandedTableStructure().numberOfCells:0;!this.alreadyNotifiedForPivotSize&&t>Q&&(this.alreadyNotifiedForPivotSize=!0,this.notification.notifyUser({type:"warning",text:yP(t,this.getters.getLocale()),sticky:!0}))}}discardPendingUpdate(){this.draft=null}update(e){const t=this.getters.getPivotCoreDefinition(this.pivotId),s={...t,...this.draft,...e},o={...s,columns:s.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:s.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:s.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(s)?s.sortedColumn:void 0};if(o.collapsedDomains){const{COL:e,ROW:t}=o.collapsedDomains;o.collapsedDomains={COL:e.filter(e=>this.areDomainFieldsValid(e,o.columns)),ROW:t.filter(e=>this.areDomainFieldsValid(e,o.rows))}}if(!this.draft&&Me(t,o))return;const i=this.addDefaultDateTimeGranularity(this.fields,o);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0;const t=this.getters.getPivotFormulaId(this.pivotId);for(const s of this.getters.getVisibleCellPositions()){const o=this.getters.getCell(s);if(o?.isFormula){const s=MD(o.compiledFormula.tokens),i=s?.args[0]?.value;if(s&&t===i.toString()){if("PIVOT"===s.functionName)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){const{columns:s,rows:o}=t,i=ae(s),n=ae(o),r=this.getUnusedGranularities(e,t);for(const t of i.concat(n)){const s=e[t.fieldName]?.type;if(("date"===s||"datetime"===s)&&!t.granularity){const e=r[t.fieldName]?.values().next().value||"year";r[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:n}}getUnusedGranularities(e,t){const{columns:s,rows:o,measures:i}=t,n=s.concat(o).concat(i).filter(t=>{const s=e[t.fieldName]?.type;return"date"===s||"datetime"===s}),r={};for(const t of n)r[t.fieldName]=new Set("date"===e[t.fieldName]?.type?this.dateGranularities:this.datetimeGranularities);for(const e of n)r[e.fieldName].delete(e.granularity||"month");return r}shouldKeepSortedColumn(e){const{sortedColumn:t}=e;if(!t)return!0;const s=this.getters.getPivotCoreDefinition(this.pivotId);return e.measures.find(e=>e.id===t.measure)&&Me(s.columns,e.columns)}areDomainFieldsValid(e,t){const s=t.map(({fieldName:e,granularity:t})=>e+(t?`:${t}`:""));for(let t=0;t<e.length;t++)if(e[t].field!==s[t])return!1;return!0}}class rz extends t.Component{static template="o-spreadsheet-PivotSpreadsheetSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:oz,Section:aM,SelectionInput:fM,Checkbox:IM,PivotDeferUpdate:jH,PivotTitleSection:iz};store;state;pivotSidePanelRef=t.useRef("pivotSidePanel");setup(){this.store=tv(nz,this.props.pivotId),this.state=t.useState({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return(!this.store.isDirty||!this.state.rangeHasChanged)&&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){const e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;const t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){const{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}}const az=new Og;az.add("SPREADSHEET",{editor:rz});class lz extends t.Component{static template="o-spreadsheet-PivotSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:oz,Section:aM};setup(){DH(this)}get sidePanelEditor(){const e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw new Error("pivotId does not correspond to a pivot.");return az.get(e.type).editor}get highlights(){return ZH(this.env.model.getters,this.props.pivotId)}}class cz extends t.Component{static template="o-spreadsheet-RemoveDuplicatesPanel";static components={ValidationMessages:JV,Section:aM,Checkbox:IM};static props={onCloseSidePanel:Function};state=t.useState({hasHeader:!1,columns:{}});setup(){this.updateColumns(),t.onWillUpdateProps(()=>this.updateColumns())}toggleHasHeader(){this.state.hasHeader=!this.state.hasHeader}toggleAllColumns(){const e=!this.isEveryColumnSelected;for(const t in this.state.columns)this.state.columns[t]=e}toggleColumn(e){this.state.columns[e]=!this.state.columns[e]}onRemoveDuplicates(){this.env.model.dispatch("REMOVE_DUPLICATES",{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()})}getColLabel(e){const t=parseInt(e);let s=fs("Column %s",it(t));if(this.state.hasHeader){const e=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSelectedZone().top,i=this.env.model.getters.getEvaluatedCell({sheetId:e,col:t,row:o});"empty"!==i.type&&(s+=` - ${i.value}`)}return s}get isEveryColumnSelected(){return Object.values(this.state.columns).every(e=>e)}get errorMessages(){const e=this.env.model.canDispatch("REMOVE_DUPLICATES",{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()}).reasons,t=new Set;for(const s of e)t.add(Tg.Errors[s]||Tg.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){const e=Ut(this.env.model.getters.getSelectedZone());return fs("%(row_count)s rows and %(column_count)s columns selected",{row_count:e.numberOfRows,column_count:e.numberOfCols})}get canConfirm(){return 0===this.errorMessages.length}updateColumns(){const e=this.env.model.getters.getSelectedZone(),t=this.state.columns,s={};for(let o=e.left;o<=e.right;o++)s[o]=!(o in t)||t[o];this.state.columns=s}getColsToAnalyze(){return Object.keys(this.state.columns).filter(e=>this.state.columns[e]).map(e=>parseInt(e))}}class hz extends t.Component{static template="o-spreadsheet-SettingsPanel";static components={Section:aM,ValidationMessages:JV,BadgeSelection:UU};static props={onCloseSidePanel:Function};loadedLocales=[];setup(){t.onWillStart(()=>this.loadLocales())}onLocaleChange(e){const t=this.loadedLocales.find(t=>t.code===e);t&&this.env.model.dispatch("UPDATE_LOCALE",{locale:t})}async loadLocales(){this.loadedLocales=(await this.env.loadLocales()).filter(e=>{const t=Xc(e);return t||console.warn(`Invalid locale: ${e.code} ${e}`),t}).sort((e,t)=>e.name.localeCompare(t.name))}get numberFormatPreview(){return pn(1234567.89,{format:"#,##0.00",locale:this.env.model.getters.getLocale()})}get dateFormatPreview(){const e=this.env.model.getters.getLocale();return pn(1.6,{format:e.dateFormat,locale:e})}get dateTimeFormatPreview(){const e=this.env.model.getters.getLocale();return pn(1.6,{format:hh(e),locale:e})}get firstDayOfWeek(){const e=this.env.model.getters.getLocale().weekStart;return un[e%7]}get currentLocale(){return this.env.model.getters.getLocale()}get supportedLocales(){const e=this.currentLocale,t=this.loadedLocales.find(t=>t.code===e.code);if(!t)return[...this.loadedLocales,e].sort((e,t)=>e.name.localeCompare(t.name));if(!Me(e,t)){const s=this.loadedLocales.indexOf(t),o=[...this.loadedLocales];return o[s]=e,o.sort((e,t)=>e.name.localeCompare(t.name)),o}return this.loadedLocales}}const dz={SplitIsDestructive:fs("This will overwrite data in the subsequent columns. Split anyway?")};const uz=[{name:fs("Detect automatically"),value:"auto"},{name:fs("Custom separator"),value:"custom"},{name:fs("Space"),value:" "},{name:fs("Comma"),value:","},{name:fs("Semicolon"),value:";"},{name:fs("Line Break"),value:X}];class gz extends t.Component{static template="o-spreadsheet-SplitIntoColumnsPanel";static components={ValidationMessages:JV,Section:aM,Checkbox:IM};static props={onCloseSidePanel:Function};state=t.useState({separatorValue:"auto",addNewColumns:!1,customSeparator:""});setup(){const e=ev(uv);t.useEffect(e=>{"inactive"!==e&&this.props.onCloseSidePanel()},()=>[e.focusMode]),t.onMounted(()=>{e.activeComposer.stopEdition()})}onSeparatorChange(e){this.state.separatorValue=e}updateCustomSeparator(e){e.target&&(this.state.customSeparator=e.target.value)}updateAddNewColumnsCheckbox(e){this.state.addNewColumns=e}confirm(){(function(e,t,s){let o=e.model.dispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:t,addNewColumns:s});return o.isCancelledBecause("SplitWillOverwriteContent")&&e.askConfirmation(dz.SplitIsDestructive,()=>{o=e.model.dispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:t,addNewColumns:s,force:!0})}),o})(this.env,this.separatorValue,this.state.addNewColumns).isSuccessful&&this.props.onCloseSidePanel()}get errorMessages(){const e=this.env.model.canDispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!0}).reasons,t=new Set;for(const s of e)switch(s){case"SplitWillOverwriteContent":case"EmptySplitSeparator":break;default:t.add(xg.Errors[s]||xg.Errors.Unexpected)}return Array.from(t)}get warningMessages(){const e=[];return this.env.model.canDispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!1}).reasons.includes("SplitWillOverwriteContent")&&e.push(xg.Errors.SplitWillOverwriteContent),e}get separatorValue(){return"custom"===this.state.separatorValue?this.state.customSeparator:"auto"===this.state.separatorValue?this.env.model.getters.getAutomaticSeparator():this.state.separatorValue}get separators(){return uz}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}}function pz(e,t,s,o){e.resetTransform(),function(e,t,s,o){e.save();for(let i=0;i<5;i++)for(let n=0;n<5;n++)e.fillStyle=t.styles[i][n].fillColor||"#fff",e.fillRect(i*s,n*o,s,o);e.restore()}(e,t,s,o),function(e,t,s,o){e.save(),e.translate(0,.5),e.lineWidth=1;for(let i=0;i<5;i++)for(let n=0;n<5;n++){const r=t.borders[i][n];r.top&&(e.strokeStyle=r.top.color,e.beginPath(),e.moveTo(i*s,n*o),e.lineTo(i*s+s,n*o),e.stroke()),r.bottom&&(e.strokeStyle=r.bottom.color,e.beginPath(),e.moveTo(i*s,n*o+o),e.lineTo(i*s+s,n*o+o),e.stroke())}e.resetTransform(),e.translate(.5,0);for(let i=0;i<5;i++)for(let n=0;n<5;n++){const r=t.borders[i][n];r.left&&(e.strokeStyle=r.left.color,e.beginPath(),e.moveTo(i*s,n*o),e.lineTo(i*s,n*o+o),e.stroke()),r.right&&(e.strokeStyle=r.right.color,e.beginPath(),e.moveTo(i*s+s,n*o),e.lineTo(i*s+s,n*o+o+1),e.stroke())}e.restore()}(e,t,s,o),function(e,t,s,o){e.save(),e.translate(0,.5),e.lineWidth=1;const i=Math.floor(s/4),n=Math.floor(o/2);for(let r=0;r<5;r++)for(let a=0;a<5;a++)e.strokeStyle=t.styles[r][a].textColor||"#000",e.beginPath(),e.moveTo(r*s+i+1,a*o+n),e.lineTo(r*s+s-i,a*o+n),e.stroke();e.restore()}(e,t,s,o)}class mz extends t.Component{static template="o-spreadsheet-TableStylePreview";static components={MenuPopover:PF};static props={tableConfig:Object,tableStyle:Object,class:String,styleId:{type:String,optional:!0},selected:{type:Boolean,optional:!0},onClick:{type:Function,optional:!0}};canvasRef=t.useRef("canvas");menu=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});setup(){t.onWillUpdateProps(e=>{Me(this.props.tableConfig,e.tableConfig)&&Me(this.props.tableStyle,e.tableStyle)||this.drawTable(e)}),t.onMounted(()=>this.drawTable(this.props))}drawTable(e){const t=this.canvasRef.el.getContext("2d"),{width:s,height:o}=this.canvasRef.el.getBoundingClientRect();this.canvasRef.el.width=s,this.canvasRef.el.height=o;pz(t,AA(e.tableConfig,e.tableStyle,5,5),(s-1)/5,(o-1)/5)}onContextMenu(e){var t,s;this.props.styleId&&(this.menu.menuItems=(t=this.env,s=this.props.styleId,t.model.getters.isTableStyleEditable(s)?qf([{id:"editTableStyle",name:fs("Edit table style"),execute:e=>e.openSidePanel("TableStyleEditorPanel",{styleId:s}),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.EDIT"},{id:"deleteTableStyle",name:fs("Delete table style"),execute:e=>e.model.dispatch("REMOVE_TABLE_STYLE",{tableStyleId:s}),icon:"o-spreadsheet-Icon.TRASH"}]):[]),this.menu.isOpen=!0,this.menu.anchorRect={x:e.clientX,y:e.clientY,width:0,height:0})}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get styleName(){return this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId).displayName:""}get isStyleEditable(){return!!this.props.styleId&&this.env.model.getters.isTableStyleEditable(this.props.styleId)}editTableStyle(){this.env.openSidePanel("TableStyleEditorPanel",{styleId:this.props.styleId})}}class fz extends t.Component{static template="o-spreadsheet-TableStylesPopover";static components={Popover:DF,TableStylePreview:mz};static props={tableConfig:Object,popoverProps:{type:Object,optional:!0},closePopover:Function,onStylePicked:Function,selectedStyleId:{type:String,optional:!0}};categories=cE;tableStyleListRef=t.useRef("tableStyleList");state=t.useState({selectedCategory:this.initialSelectedCategory});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}onExternalClick(e){this.tableStyleListRef.el&&!Dy(this.tableStyleListRef.el,e)&&(this.props.closePopover(),e.hasClosedTableStylesPopover=!0)}get displayedStyles(){const e=this.env.model.getters.getTableStyles();return Object.keys(e).filter(t=>e[t].category===this.state.selectedCategory)}get initialSelectedCategory(){return this.props.selectedStyleId?this.env.model.getters.getTableStyle(this.props.selectedStyleId).category:"medium"}newTableStyle(){this.props.closePopover(),this.env.openSidePanel("TableStyleEditorPanel",{onStylePicked:this.props.onStylePicked})}}class vz extends t.Component{static template="o-spreadsheet-TableStylePicker";static components={TableStylesPopover:fz,TableStylePreview:mz};static props={table:Object};state=t.useState({popoverProps:void 0});getDisplayedTableStyles(){const e=this.env.model.getters.getTableStyles(),t=e[this.props.table.config.styleId].category,s=Object.keys(e).filter(s=>e[s].category===t),o=s.indexOf(this.props.table.config.styleId);if(-1===o)return o;const i=4*Math.floor(o/4);return s.slice(i)}onStylePicked(e){const t=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("UPDATE_TABLE",{sheetId:t,zone:this.props.table.range.zone,config:{styleId:e}}),this.closePopover()}onArrowButtonClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps)return void this.closePopover();const t=e.currentTarget,{bottom:s,right:o}=t.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:o,y:s,width:0,height:0},positioning:"top-right",verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}}class bz extends t.Component{static template="o-spreadsheet-TablePanel";static components={TableStylePicker:vz,SelectionInput:fM,ValidationMessages:JV,Checkbox:IM,Section:aM};static props={onCloseSidePanel:Function,table:Object};state;setup(){const e=this.env.model.getters.getActiveSheetId();this.state=t.useState({tableZoneErrors:[],tableXc:this.env.model.getters.getRangeString(this.props.table.range,e),filtersEnabledIfPossible:this.props.table.config.hasFilters})}updateHasFilters(e){this.state.filtersEnabledIfPossible=e,this.updateTableConfig("hasFilters",e)}updateTableConfig(e,t){const s=this.env.model.getters.getActiveSheetId();return this.env.model.dispatch("UPDATE_TABLE",{sheetId:s,zone:this.props.table.range.zone,config:{[e]:t}})}updateHasHeaders(e){const t=e?1:0;this.updateNumberOfHeaders(t)}updateTableIsDynamic(e){const t=e?"dynamic":"forceStatic";if(t===this.props.table.type)return;const s=this.env.model.getters.getTable(RA(this.props.table));if(!s)return;const o=this.env.model.getters.getActiveSheetId(),i=this.env.model.dispatch("UPDATE_TABLE",{sheetId:o,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(s.range),tableType:t}),n=this.env.model.getters.getCoreTable(RA(this.props.table));if(i.isSuccessful&&n){const e=n.range;this.state.tableXc=this.env.model.getters.getRangeString(e,o),this.state.tableZoneErrors=[]}}onChangeNumberOfHeaders(e){const t=e.target,s=parseInt(t.value);this.updateNumberOfHeaders(s).isSuccessful||(t.value=this.props.table.config.numberOfHeaders.toString())}updateNumberOfHeaders(e){const t=e>0&&(this.tableConfig.hasFilters||this.state.filtersEnabledIfPossible);return this.env.model.dispatch("UPDATE_TABLE",{sheetId:this.env.model.getters.getActiveSheetId(),zone:this.props.table.range.zone,config:{numberOfHeaders:e,hasFilters:t}})}onRangeChanged(e){const t=this.env.model.getters.getActiveSheetId();this.state.tableXc=e[0];const s=this.env.model.getters.getRangeFromSheetXC(t,this.state.tableXc);this.state.tableZoneErrors=this.env.model.canDispatch("UPDATE_TABLE",{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromXc(t,this.state.tableXc),tableType:this.getNewTableType(s.zone)}).reasons}onRangeConfirmed(){const e=this.env.model.getters.getActiveSheetId();let t=this.env.model.getters.getRangeFromSheetXC(e,this.state.tableXc);if(1===Kt(t.zone)){const s=this.env.model.getters.getContiguousZone(e,t.zone);t=this.env.model.getters.getRangeFromZone(e,s)}const s=t.zone,o=this.props.table.range.zone,i=s.top===o.top&&s.left===o.left?"RESIZE_TABLE":"UPDATE_TABLE",n=this.env.model.dispatch(i,{sheetId:e,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(t),tableType:this.getNewTableType(t.zone)}),r={sheetId:e,col:t.zone.left,row:t.zone.top},a=this.env.model.getters.getCoreTable(r);if(n.isSuccessful&&a){const t=RA(a);this.env.model.selection.selectZone({zone:Zt(t),cell:t});const s=a.range;this.state.tableXc=this.env.model.getters.getRangeString(s,e)}}deleteTable(){const e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("REMOVE_TABLE",{sheetId:e,target:[this.props.table.range.zone]})}getNewTableType(e){if("forceStatic"===this.props.table.type)return"forceStatic";const t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.canCreateDynamicTableOnZones(t,[e])?"dynamic":"static"}get tableConfig(){return this.props.table.config}get errorMessages(){return(this.state.tableZoneErrors||[]).map(e=>Dg.Errors[e]||Dg.Errors.Unexpected)}getCheckboxLabel(e){return Dg.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:Dg.Tooltips.filterWithoutHeader}get canBeDynamic(){const e=this.env.model.getters.getActiveSheetId();return"dynamic"===this.props.table.type||this.env.model.getters.canCreateDynamicTableOnZones(e,[this.props.table.range.zone])}get dynamicTableTooltip(){return Dg.Tooltips.isDynamic}}const Sz="#3C78D8";class Cz extends t.Component{static template="o-spreadsheet-TableStyleEditorPanel";static components={Section:aM,RoundColorPicker:lM,TableStylePreview:mz};static props={onCloseSidePanel:Function,onStylePicked:{type:Function,optional:!0},styleId:{type:String,optional:!0}};state=t.useState(this.getInitialState());setup(){t.useExternalListener(window,"click",()=>this.state.pickerOpened=!1)}getInitialState(){const e=this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId):null;return{pickerOpened:!1,primaryColor:e?.primaryColor||Sz,selectedTemplateName:e?.templateName||"lightColoredText",styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=Sv(e)?e:Sz,this.state.pickerOpened=!1}onTemplatePicked(e){this.state.selectedTemplateName=e}onConfirm(){const e=this.props.styleId||this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch("CREATE_TABLE_STYLE",{tableStyleId:e,tableStyleName:this.state.styleName,templateName:this.state.selectedTemplateName,primaryColor:this.state.primaryColor}),this.props.onStylePicked?.(e),this.props.onCloseSidePanel()}onCancel(){this.props.onCloseSidePanel()}onDelete(){this.props.styleId&&(this.env.model.dispatch("REMOVE_TABLE_STYLE",{tableStyleId:this.props.styleId}),this.props.onCloseSidePanel())}get colorPreviewStyle(){return Ey({background:this.state.primaryColor})}get tableTemplates(){return Object.keys(TE).filter(e=>"none"!==e)}get previewTableConfig(){return{bandedColumns:!1,bandedRows:!0,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,totalRow:!0,hasFilters:!0,styleId:""}}get selectedStyle(){return this.computeTableStyle(this.state.selectedTemplateName)}computeTableStyle(e){return AE(this.state.styleName,e,this.state.primaryColor)}}const yz=new Og;yz.add("ConditionalFormatting",{title:fs("Conditional formatting"),Body:PH}),yz.add("ChartPanel",{title:fs("Chart"),Body:xH,computeState:(e,t)=>{const s=e.getSelectedFigureId(),o=s?e.getChartIdFromFigureId(s):t.chartId;return o&&e.isChartDefined(o)?{isOpen:!0,props:{chartId:o}}:{isOpen:!1}}}),yz.add("FindAndReplace",{title:fs("Find and Replace"),Body:BH}),yz.add("CustomCurrency",{title:fs("Custom currency format"),Body:NH}),yz.add("SplitToColumns",{title:fs("Split text into columns"),Body:gz}),yz.add("Settings",{title:fs("Spreadsheet settings"),Body:hz}),yz.add("RemoveDuplicates",{title:fs("Remove duplicates"),Body:cz}),yz.add("DataValidation",{title:fs("Data validation"),Body:VH}),yz.add("DataValidationEditor",{title:fs("Data validation"),Body:LH}),yz.add("MoreFormats",{title:fs("More date formats"),Body:WH}),yz.add("TableSidePanel",{title:fs("Edit table"),Body:bz,computeState:e=>{const t=e.getFirstTableInSelection();if(!t)return{isOpen:!1};return{isOpen:!0,props:{table:e.getCoreTable(RA(t))},key:t.id}}}),yz.add("TableStyleEditorPanel",{title:fs("Create custom table style"),Body:Cz,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??"new"})}),yz.add("PivotSidePanel",{title:(e,t)=>fs("Pivot #%s",e.model.getters.getPivotFormulaId(t.pivotId)),Body:lz,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),yz.add("PivotMeasureDisplayPanel",{title:(e,t)=>{const s=e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id);return fs('Measure "%s" options',s.displayName)},Body:qH,computeState:(e,t)=>{try{return e.getPivot(t.pivotId).getMeasure(t.measure.id),{isOpen:!0,props:t,key:`pivot_measure_display_${t.pivotId}_${t.measure.id}`}}catch(e){return{isOpen:!1}}}}),yz.add("CarouselPanel",{title:fs("Carousel"),Body:PU,computeState:(e,t)=>{const s=t.figureId||e.getSelectedFigureId();return s&&e.doesCarouselExist(s)?{isOpen:!0,props:{figureId:s}}:{isOpen:!1}}});class Iz{mutators=["setSmallThreshhold"];_isSmallCallback=()=>!1;get isSmall(){return this._isSmallCallback()}setSmallThreshhold(e){this._isSmallCallback=e}}const wz=350,Ez=150;class Rz extends hv{mutators=["open","replace","toggle","close","changePanelSize","resetPanelSize","togglePinPanel","closeMainPanel","changeSpreadsheetWidth","toggleCollapsePanel"];mainPanel=void 0;secondaryPanel;availableWidth=0;screenWidthStore=this.get(Iz);get isMainPanelOpen(){return!(!this.mainPanel||!this.mainPanel.componentTag)&&this.computeState(this.mainPanel).isOpen}get isSecondaryPanelOpen(){return!(!this.secondaryPanel||!this.secondaryPanel.componentTag)&&this.computeState(this.secondaryPanel).isOpen}get mainPanelProps(){return this.mainPanel?this.getPanelProps(this.mainPanel):void 0}get mainPanelKey(){return this.mainPanel?this.getPanelKey(this.mainPanel):void 0}get secondaryPanelProps(){return this.secondaryPanel?this.getPanelProps(this.secondaryPanel):void 0}get secondaryPanelKey(){return this.secondaryPanel?this.getPanelKey(this.secondaryPanel):void 0}get totalPanelSize(){return(this.mainPanel?.size||0)+(this.secondaryPanel?.size??0)}getPanelProps(e){const t=this.computeState(e);return t.isOpen?t.props??{}:{}}getPanelKey(e){const t=this.computeState(e);if(t.isOpen)return t.key}open(e,t={}){if(this.screenWidthStore.isSmall)return;const s={initialPanelProps:t,componentTag:e,size:wz},o=this.computeState(s);if(!o.isOpen)return;if(!this.mainPanel||!this.mainPanel.isPinned||this.mainPanelKey===o.key)return void this._openPanel("mainPanel",s,o);const i=this.mainPanel.isCollapsed?wz:this.mainPanel.size;!this.secondaryPanel&&i+wz>this.availableWidth?this.get(jP).notifyUser({sticky:!1,type:"warning",text:fs("The window is too small to display multiple side panels.")}):this._openPanel("secondaryPanel",s,o)}replace(e,t,s={}){const o={initialPanelProps:s,componentTag:e,size:wz},i=this.computeState(o);if(!i.isOpen)return;const n=()=>{this.mainPanel?.isCollapsed&&this.toggleCollapsePanel("mainPanel")},r=this.mainPanelKey===i.key,a=this.secondaryPanelKey===i.key;if(r&&this.secondaryPanel)return this.close(),void n();if(a)return this.closeMainPanel(),this.togglePinPanel(),void n();const l=this.mainPanelKey===t?"mainPanel":"secondaryPanel";this._openPanel(l,o,i)}_openPanel(e,t,s){const o=this[e];o&&t.componentTag!==o.componentTag&&o.initialPanelProps?.onCloseSidePanel?.(),this[e]={initialPanelProps:s.props??{},componentTag:t.componentTag,size:o?.size||wz,isCollapsed:o?.isCollapsed||!1,isPinned:!(!o||!("isPinned"in o))&&o.isPinned},this[e].isCollapsed&&this.toggleCollapsePanel(e)}toggle(e,t){const s=this.mainPanel?.isPinned?this.secondaryPanel:this.mainPanel;s&&e===s.componentTag?this.close():this.open(e,t)}close(){this.mainPanel?.isPinned?this.secondaryPanel&&(this.secondaryPanel.initialPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0):(this.mainPanel?.initialPanelProps.onCloseSidePanel?.(),this.mainPanel=void 0)}closeMainPanel(){this.mainPanel?.initialPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel||void 0,this.secondaryPanel=void 0}changePanelSize(e,t){const s=this[e];if(!s||"isCollapsed"in s&&s.isCollapsed)return;t=Math.max(t,wz);let o="mainPanel"===e?this.secondaryPanel?.size||0:this.mainPanel?.size||0;t>this.availableWidth-o&&("mainPanel"===e&&this.secondaryPanel&&(this.secondaryPanel.size=Math.max(this.availableWidth-t,wz),o=this.secondaryPanel.size),t=Math.max(this.availableWidth-o,wz)),s.size=t}resetPanelSize(e){this[e]&&(this[e].size=wz)}togglePinPanel(){this.mainPanel&&(this.mainPanel.isPinned=!this.mainPanel.isPinned,!this.mainPanel.isPinned&&this.secondaryPanel&&(this.secondaryPanel?.initialPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel,this.secondaryPanel=void 0))}toggleCollapsePanel(e){const t=this[e];t&&(t.isCollapsed?(t.isCollapsed=!1,this.changePanelSize(e,wz)):(t.isCollapsed=!0,t.size=45))}computeState({componentTag:e,initialPanelProps:t}){const s=yz.get(e).computeState,o=s?s(this.getters,t):{isOpen:!0,props:t};return o.isOpen?{...o,key:o.key||e}:o}changeSpreadsheetWidth(e){this.availableWidth=e-Ez,this.secondaryPanel&&e-this.totalPanelSize<Ez&&(this.secondaryPanel?.initialPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0),this.mainPanel&&e-this.totalPanelSize<Ez&&(this.mainPanel.size=Math.max(e-Ez,wz))}}class xz extends t.Component{static template="o-spreadsheet-TableResizer";static props={table:Object};state=t.useState({highlightZone:void 0});dragNDropGrid=VV(this.env);setup(){DH(this)}get containerStyle(){const e=this.props.table.range.zone,t={...e,left:e.right,top:e.bottom},s=this.env.model.getters.getVisibleRect(t);return 0===s.height||0===s.width?Ey({display:"none"}):Ey({top:s.y+s.height-6+"px",left:s.x+s.width-6+"px"})}onMouseDown(e){const t=this.props.table.range.zone,s={col:t.left,row:t.top};document.body.style.cursor="nwse-resize";this.dragNDropGrid.start(e,(e,t,o)=>{this.state.highlightZone={left:s.col,top:s.row,right:Math.max(e,s.col),bottom:Math.max(t,s.row)}},()=>{document.body.style.cursor="";const e=this.state.highlightZone;if(!e)return;const t=this.props.table.range.sheetId;this.env.model.dispatch("RESIZE_TABLE",{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromZone(t,e)}),this.state.highlightZone=void 0})}get highlights(){return this.state.highlightZone?[{range:this.env.model.getters.getRangeFromZone(this.props.table.range.sheetId,this.state.highlightZone),color:"#777",noFill:!0}]:[]}}const Tz={ROW:NV,COL:DV,CELL:vk,GROUP_HEADERS:PV,UNGROUP_HEADERS:MV};class Az extends t.Component{static template="o-spreadsheet-Grid";static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:qV,GridOverlay:rU,GridPopover:aU,HeadersOverlay:gU,MenuPopover:PF,Autofill:HV,ClientTag:BV,Highlight:CU,Popover:DF,VerticalScrollBar:EU,HorizontalScrollBar:wU,TableResizer:xz,Selection:RU};HEADER_HEIGHT=A;HEADER_WIDTH=D;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=VV(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=ev(ZP),this.menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.hoveredCell=ev(HF),this.composerFocusStore=ev(uv),this.DOMFocusableElementStore=ev(OP),this.sidePanel=ev(Rz),this.paintFormatStore=ev(sU),this.clientFocusStore=ev(kV),ev(LV),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),t.useExternalListener(document.body,"cut",this.copy.bind(this,!0)),t.useExternalListener(document.body,"copy",this.copy.bind(this,!1)),t.useExternalListener(document.body,"paste",this.paste),t.onMounted(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),mU("canvas",this.env.model,()=>this.env.model.getters.getSheetViewDimensionWithHeaders()),this.onMouseWheel=vU((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=ev(wP),t.useEffect((e,t)=>{e||t||this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),fU(this.gridRef,this.moveCanvas.bind(this),()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){return Ey({top:"26px",left:"48px",height:"calc(100% - 41px)",width:"calc(100% - 63px)"})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>{this.env.model.getters.getActiveCell().type===_d.empty?this.onComposerCellFocused():this.onComposerContentFocused()},Tab:()=>this.env.model.selection.moveAnchorCell("right",1),"Shift+Tab":()=>this.env.model.selection.moveAnchorCell("left",1),F2:()=>{this.env.model.getters.getActiveCell().type===_d.empty?this.onComposerCellFocused():this.onComposerContentFocused()},Delete:()=>{this.env.model.dispatch("DELETE_UNFILTERED_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch("DELETE_UNFILTERED_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Escape:()=>{this.cellPopovers.isOpen?this.cellPopovers.close():this.menuState.isOpen?this.closeMenu():this.paintFormatStore.isActive?this.paintFormatStore.cancel():this.env.model.dispatch("CLEAN_CLIPBOARD_HIGHLIGHT")},"Ctrl+A":()=>this.env.model.selection.loopSelection(),"Ctrl+Z":()=>this.env.model.dispatch("REQUEST_UNDO"),"Ctrl+Y":()=>this.env.model.dispatch("REQUEST_REDO"),F4:()=>this.env.model.dispatch("REQUEST_REDO"),"Ctrl+B":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"Ctrl+I":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"Ctrl+U":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"Ctrl+O":()=>uN(this.env),"Alt+=":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:s}=this.env.model.getters.getSelection(),o=this.env.model.getters.getAutomaticSums(e,t,s.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&o.length<=1){const t=o[0]?.zone,s=t?this.env.model.getters.zoneToXC(e,o[0].zone):"",i=`=SUM(${s})`;this.onComposerCellFocused(i,{start:5,end:5+s.length})}else this.env.model.dispatch("SUM_SELECTION")},"Alt+Enter":()=>{const e=this.env.model.getters.getActiveCell();e.link&&Wf(e.link,this.env)},"Ctrl+Home":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:s}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,s)},"Ctrl+End":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,"COL",this.env.model.getters.getNumberCols(e)-1,0),s=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,s)},"Shift+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},s=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:s,zone:t})},"Ctrl+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},s=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:s,zone:t})},"Ctrl+D":async()=>this.env.model.dispatch("COPY_PASTE_CELLS_ABOVE"),"Ctrl+R":async()=>this.env.model.dispatch("COPY_PASTE_CELLS_ON_LEFT"),"Ctrl+H":()=>this.sidePanel.open("FindAndReplace",{}),"Ctrl+F":()=>this.sidePanel.open("FindAndReplace",{}),"Ctrl+Shift+E":()=>this.setHorizontalAlign("center"),"Ctrl+Shift+L":()=>this.setHorizontalAlign("left"),"Ctrl+Shift+R":()=>this.setHorizontalAlign("right"),"Ctrl+Shift+V":()=>rN(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{const e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),s=1===this.env.model.getters.getSelectedZones().length,o=e.size>0&&s,i=t.size>0&&s;o&&!i?hN(this.env):i&&!o&&cN(this.env)},"Ctrl+Alt+-":()=>{const e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&0===t.length?this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:"COL",elements:e}):t.length>0&&0===e.length&&this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:"ROW",elements:t})},"Shift+PageDown":()=>{this.env.model.dispatch("ACTIVATE_NEXT_SHEET")},"Shift+PageUp":()=>{this.env.model.dispatch("ACTIVATE_PREVIOUS_SHEET")},PageDown:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PageUp:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP"),"Ctrl+K":()=>gN(this.env),"Alt+Shift+ArrowRight":()=>this.processHeaderGroupingKey("right"),"Alt+Shift+ArrowLeft":()=>this.processHeaderGroupingKey("left"),"Alt+Shift+ArrowUp":()=>this.processHeaderGroupingKey("up"),"Alt+Shift+ArrowDown":()=>this.processHeaderGroupingKey("down")};focusDefaultElement(){this.env.model.getters.getSelectedFigureId()||"inactive"!==this.composerFocusStore.activeComposer.editionMode||this.DOMFocusableElementStore.focus()}get gridEl(){if(!this.gridRef.el)throw new Error("Grid el is not defined.");return this.gridRef.el}getAutofillPosition(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{left:t.x+t.width-4,top:t.y+t.height-4}}get isAutofillVisible(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(0===t.width||0===t.height)}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t-D,height:e-A,gridOffsetX:D,gridOffsetY:A})}moveCanvas(e,t){const{scrollX:s,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:s+e,offsetY:o+t})}processSpaceKey(e){this.env.model.getters.hasBooleanValidationInZones(this.env.model.getters.getSelectedZones())&&(e.preventDefault(),e.stopPropagation(),this.env.model.dispatch("TOGGLE_CHECKBOX",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()}))}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}get focusedClients(){return this.clientFocusStore.focusedClients}getGridRect(){return{...Oy(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,s,o){if(o.preventDefault(),"editing"===this.composerFocusStore.activeComposer.editionMode&&this.composerFocusStore.activeComposer.stopEdition(),s.expandZone?this.env.model.selection.setAnchorCorner(e,t):s.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t),this.env.isMobile())return;let i=e,n=t;this.dragNDropGrid.start(o,(e,t,s)=>{s.preventDefault(),(e!==i&&-1!==e||t!==n&&-1!==t)&&(i=-1===e?i:e,n=-1===t?n:t,this.env.model.selection.setAnchorCorner(i,n))},()=>{this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())})}onCellDoubleClicked(e,t){const s=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:s,col:e,row:t}));this.env.model.getters.getEvaluatedCell({sheetId:s,col:e,row:t}).type===_d.empty?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),PP(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){const t=ky(e),s=this.keyDownMapping[t];if(s)return e.preventDefault(),e.stopPropagation(),void s();" "!==t?e.key.startsWith("Arrow")&&this.processArrows(e):this.processSpaceKey(e)}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:s,top:o}=t;let i="CELL";this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(s)?i="COL":this.env.model.getters.getActiveRows().has(o)&&(i="ROW");const{x:n,y:r,width:a}=this.env.model.getters.getVisibleRect(t),l=this.getGridRect();this.toggleContextMenu(i,l.x+n+a,l.y+r)}onCellRightClicked(e,t,{x:s,y:o}){const i=this.env.model.getters.getSelectedZones();let n="CELL";kt(e,t,i[i.length-1])?this.env.model.getters.getActiveCols().has(e)?n="COL":this.env.model.getters.getActiveRows().has(t)&&(n="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(n,s,o)}toggleContextMenu(e,t,s){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.anchorRect={x:t,y:s,width:0,height:0},this.menuState.menuItems=Tz[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement))return;if("inactive"!==this.composerFocusStore.activeComposer.editionMode)return;e?YN(this.env):this.env.model.dispatch("COPY");const s=await this.env.model.getters.getClipboardTextAndImageContent();await this.env.clipboard.write(s),t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();const t=e.clipboardData;if(!t)return;const s=[...t.files]?.find(e=>S_.includes(e.type)),o={content:{[gI.PlainText]:t?.getData(gI.PlainText),[gI.Html]:t?.getData(gI.Html)}};s&&(o.content[s.type]=s);const i=this.env.model.getters.getSelectedZones(),n=this.env.model.getters.isCutOperation(),r=this.env.model.getters.getClipboardId(),a=w_(o.content),l=a.data?.clipboardId;r===l?tN(this.env,i):await sN(this.env,i,a),n&&await this.env.clipboard.write({[gI.PlainText]:""})}clearFormatting(){this.env.model.dispatch("CLEAR_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}processHeaderGroupingKey(e){if(1!==this.env.model.getters.getSelectedZones().length)return;const t=this.env.model.getters.getActiveRows().size>0,s=this.env.model.getters.getActiveCols().size>0;s&&t?this.processHeaderGroupingEventOnWholeSheet(e):s?this.processHeaderGroupingEventOnHeaders(e,"COL"):t?this.processHeaderGroupingEventOnHeaders(e,"ROW"):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){const s=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSelectedZone(),i="COL"===t?o.left:o.top,n="COL"===t?o.right:o.bottom;switch(e){case"right":this.env.model.dispatch("GROUP_HEADERS",{sheetId:s,dimension:t,start:i,end:n});break;case"left":this.env.model.dispatch("UNGROUP_HEADERS",{sheetId:s,dimension:t,start:i,end:n});break;case"down":this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:s,dimension:t,zone:o});break;case"up":this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:s,dimension:t,zone:o})}}processHeaderGroupingEventOnWholeSheet(e){const t=this.env.model.getters.getActiveSheetId();"up"===e?(this.env.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"ROW"}),this.env.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"COL"})):"down"===e&&(this.env.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"ROW"}),this.env.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"COL"}))}processHeaderGroupingEventOnGrid(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getSelectedZone();switch(e){case"down":this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"ROW",zone:s}),this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"COL",zone:s});break;case"up":this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"ROW",zone:s}),this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"COL",zone:s});break;case"right":{const{x:e,y:t,width:o}=this.env.model.getters.getVisibleRect(s),i=this.getGridRect();this.toggleContextMenu("GROUP_HEADERS",e+o+i.x,t+i.y);break}case"left":{if(!jN(this.env,"COL")&&!jN(this.env,"ROW"))return;const{x:e,y:t,width:o}=this.env.model.getters.getVisibleRect(s),i=this.getGridRect();this.toggleContextMenu("UNGROUP_HEADERS",e+o+i.x,t+i.y);break}}}onComposerCellFocused(e,t){this.composerFocusStore.focusActiveComposer({content:e,selection:t,focusMode:"cellFocus"})}onComposerContentFocused(){this.composerFocusStore.focusActiveComposer({focusMode:"contentFocus"})}get staticTables(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(TA)}get displaySelectionHandler(){return this.env.isMobile()&&"inactive"===this.composerFocusStore.activeComposer.editionMode}}function Dz(e,t){const s=`"${t?`${e.name}:${t}`:e.name}"`,o=e.string!==e.name?e.string+s:s;return{text:s,description:e.string+(e.help?` (${e.help})`:""),htmlContent:[{value:s,color:ie.STRING}],fuzzySearchKey:o}}function _z(e){const t=e.functionContext?.args[0];if(t&&["STRING","NUMBER"].includes(t.type))return t.value}const Oz=new Og;Oz.add("SPREADSHEET",!1);class Fz extends t.Component{static template="o-spreadsheet-ClickableCellSortIcon";static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=ev(oU)}get style(){const e=this.env.model.getters.getCellComputedStyle(this.props.position);return Ey({color:e.textColor||I,"background-color":this.getBackgroundColor(e)})}get verticalJustifyClass(){switch(this.env.model.getters.getCellComputedStyle(this.props.position).verticalAlign){case"top":return"justify-content-start";case"middle":return"justify-content-center";default:return"justify-content-end"}}getBackgroundColor(e){const t=this.hoveredTableStore.overlayColors.get(this.props.position);return t?function(e,t){const s=Ev(t),o=Ev(e),i=s.a+o.a*(1-s.a);return wv({r:Math.round((s.r*s.a+o.r*o.a*(1-s.a))/i),g:Math.round((s.g*s.a+o.g*o.a*(1-s.a))/i),b:Math.round((s.b*s.a+o.b*o.a*(1-s.a))/i),a:i})}(e.fillColor||"#FFFFFF",t):e.fillColor||"#FFFFFF"}}class Pz extends t.Component{static template="o-spreadsheet-FullScreenFigure";static props={};static components={ChartFigure:LF};fullScreenFigureStore;ref=t.useRef("fullScreenFigure");spreadsheetRect=AF();figureRegistry=VF;setup(){this.fullScreenFigureStore=ev(EF);const e=ev(iS);let s;t.onWillUpdateProps(()=>{s!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+"-fullscreen"),s=this.figureUI?.id}),t.useEffect(e=>e?.focus(),()=>[this.ref.el])}get figureUI(){return this.fullScreenFigureStore.fullScreenFigure}get chartId(){if(this.figureUI)return this.env.model.getters.getChartIdFromFigureId(this.figureUI?.id)}exitFullScreen(){this.figureUI&&this.fullScreenFigureStore.toggleFullScreenFigure(this.figureUI.id)}onKeyDown(e){"Escape"===e.key&&this.exitFullScreen()}get figureComponent(){if(this.figureUI)return VF.get(this.figureUI.tag).Component}}class Mz extends t.Component{static template="o_spreadsheet.PivotHTMLRenderer";static components={Checkbox:IM};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=t.useState({showMissingValuesOnly:!1});setup(){const 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;const e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){const t=this.pivot.getExpandedTableStructure().rows,s=[...t[e].values];if(s.length<=1)return[e];s.pop();const o=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(s));return[e].concat(this.addRecursiveRow(o))}buildColumnsMissing(e){const t=[];for(const e of this.data.columns){const s=[];for(const t in e)for(let o=0;o<e[t].span;o++)s.push(parseInt(t,10));t.push(s)}for(let s=t[t.length-1].length;s>=0;s--)if(!e.includes(s))for(const e of t)e.splice(s,1);const s=[];for(const e in t){const o=[];let i,n=1;for(let s=0;s<t[e].length;s++)i!==t[e][s]?(void 0!==i&&o.push(Object.assign({},this.data.columns[e][i],{span:n})),i=t[e][s],n=1):n++;void 0!==i&&o.push(Object.assign({},this.data.columns[e][i],{span:n})),s.push(o)}return s}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){const s=e.map(()=>[]);for(const o of t)for(const t in e)s[t].push(this.data.values[e[t]][o]);return s}getColumnsIndexes(){const e=new Set;for(let t=0;t<this.data.columns.length;t++){const s=[];for(let e=0;e<this.data.columns[t].length;e++)for(let o=0;o<this.data.columns[t][e].span;o++)s.push(this.data.columns[t][e]);for(let t=0;t<s.length;t++)s[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(){const e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(const s of this.data.values)s[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){const s=[];for(const o of t.columns){const t=[];for(const s of o){const o=[];for(let e=0;e<s.fields.length;e++)o.push({value:s.fields[e]},{value:s.values[e]});const i=this.pivot.parseArgsToPivotDomain(o),n=this.env.model.getters.getLocale();if("measure"===i.at(-1)?.field){const{value:o,format:r}=this.pivot.getPivotMeasureValue(Eo(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${sp(e,i).join(",")})`,value:pn(o,{format:r,locale:n}),span:s.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{const{value:o,format:r}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${sp(e,i).join(",")})`,value:pn(o,{format:r,locale:n}),span:s.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}s.push(t)}const o=s[s.length-1];return s[s.length-1]=o.map(e=>(e.isMissing||(e.style="color: #756f6f;"),e)),s}_buildRowHeaders(e,t){const s=[];for(const o of t.rows){const t=[];for(let e=0;e<o.fields.length;e++)t.push({value:o.fields[e]},{value:o.values[e]});const i=this.pivot.parseArgsToPivotDomain(t),{value:n,format:r}=this.pivot.getPivotHeaderValueAndFormat(i),a=this.env.model.getters.getLocale(),l={formula:`=PIVOT.HEADER(${sp(e,i).join(",")})`,value:pn(n,{format:r,locale:a}),isMissing:!this.tracker?.isHeaderPresent(i)};o.indent>1&&(l.style=`padding-left: ${o.indent-10}px`),s.push(l)}return s}_buildValues(e,t){const s=[];for(const o of t.columns.at(-1)||[]){const i=[],n=Eo(o.values[o.values.length-1]);for(const s of t.rows){const t=[];for(let e=0;e<s.fields.length;e++)t.push({value:s.fields[e]},{value:s.values[e]});for(let e=0;e<o.fields.length-1;e++)t.push({value:o.fields[e]},{value:o.values[e]});const r=this.pivot.parseArgsToPivotDomain(t),{value:a,format:l}=this.pivot.getPivotCellValueAndFormat(n,r),c=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${sp(e,r,n).join(",")})`,value:pn(a,{format:l,locale:c}),isMissing:!this.tracker?.isValuePresent(n,r)})}s.push(i)}return s}}class Nz{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,s="copyPaste"){}paste(e,t,s){}isPasteAllowed(e,t,s,o){return"Success"}isCutAllowed(e){return"Success"}getPasteTarget(e,t,s,o){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}}class Lz extends Nz{copy(e,t,s="copyPaste"){}pasteFromCopy(e,t,s,o){if(1===t.length)for(const i of I_(t,s))this.pasteZone(e,i.left,i.top,s,o);else for(const i of ft(t))for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++)this.pasteZone(e,t,n,s,o)}pasteZone(e,t,s,o,i){}}class kz extends Lz{isCutAllowed(e){return 1!==e.zones.length?"WrongCutSelection":"Success"}copy(e,t,s="copyPaste"){const o=e.sheetId,{clippedZones:i,rowsIndexes:n,columnsIndexes:r}=e,a=[],l=1===n.length&&1===r.length;for(const t of n){const i=[];for(const a of r){const c={col:a,row:t,sheetId:o};let h=this.getters.getCell(c);const d=this.getters.getEvaluatedCell(c),u=this.getters.getPivotIdFromPosition(c),g=this.getters.getArrayFormulaSpreadingOn(c);if("shiftCells"!==s&&u&&g){const t=this.getters.getSpreadZone(g);if((!Me(g,c)||!l)&&t&&!e.zones.some(e=>Vt(t,e))){const e=this.getters.getPivotCellFromPosition(c),t=ip(this.getters.getPivotFormulaId(u),e);h={id:h?.id||"",style:h?.style,format:h?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if("shiftCells"!==s&&g&&!Me(g,c)){const e=n.includes(g.row)&&r.includes(g.col)?"":pn(d.value,{locale:this.getters.getLocale()});h={id:h?.id||"",style:h?.style,format:d.format,content:e,isFormula:!1,parsedValue:d.value}}i.push({content:h?.content??"",style:h?.style,format:h?.format,tokens:h?.isFormula?h.compiledFormula.tokens.map(({value:e,type:t})=>({value:e,type:t})):[],border:this.getters.getCellBorder(c)||void 0,evaluatedCell:d,position:c})}a.push(i)}return{cells:a,zones:i,sheetId:e.sheetId}}isPasteAllowed(e,t,s,o){if(!s.cells)return"Success";if(o?.isCutOperation&&void 0!==o?.pasteOption)return"WrongPasteOption";if(t.length>1&&(s.cells.length>1||s.cells[0].length>1))return"WrongPasteSelection";const i=s.cells.length,n=s.cells[0].length;for(const o of I_(t,s.cells))if(this.getters.doesIntersectMerge(e,o)&&(t.length>1||!this.getters.isSingleCellOrMerge(e,t[0])||i*n!==1))return"WillRemoveExistingMerge";return"Success"}paste(e,t,s){const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t,s):this.pasteFromCopy(i,o,t.cells,s)}getPasteTarget(e,t,s,o){const i=s.cells[0].length,n=s.cells.length;return o?.isCutOperation?{sheetId:e,zones:[{left:t[0].left,top:t[0].top,right:t[0].left+i-1,bottom:t[0].top+n-1}]}:1===i&&1===n?{zones:[],sheetId:e}:{sheetId:e,zones:I_(t,s.cells)}}pasteFromCut(e,t,s,o){this.clearClippedZones(s);const i=t[0];this.pasteZone(e,i.left,i.top,s.cells,o)}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,s,o,i){for(const[n,r]of o.entries())for(const[o,a]of r.entries()){if(!a)continue;const r={col:t+o,row:s+n,sheetId:e};this.pasteCell(a,r,i)}}pasteCell(e,t,s){const{sheetId:o,col:i,row:n}=t,r=this.getters.getEvaluatedCell(t),a=e?.format||e.evaluatedCell.format;if("asValue"===s?.pasteOption)return void this.dispatch("UPDATE_CELL",{...t,content:e.evaluatedCell.value?.toString()||"",format:a});if("onlyFormat"===s?.pasteOption)return void this.dispatch("UPDATE_CELL",{...t,style:e?.style??null,format:a??r.format});let l=e?.content;e?.tokens&&e.tokens.length>0&&!s?.isCutOperation?l=this.getters.getTranslatedCellFormula(o,i-e.position.col,n-e.position.row,e.tokens):e?.tokens&&e.tokens.length>0&&(l=this.getters.getFormulaMovedInSheet(e.position.sheetId,o,e.tokens)),""!==l||e?.format||e?.style?this.dispatch("UPDATE_CELL",{...t,content:l,style:e?.style||null,format:e?.format}):r&&this.dispatch("CLEAR_CELL",t)}convertTextToClipboardData(e){const t=this.getters.getLocale(),s={cells:[]},o=[];let i=0;for(const[t,s]of e.replace(/\r/g,"").split("\n").entries())o.push(s.split("\t")),o[t].length>i&&(i=o[t].length);for(const e of o){const o=[];for(let s=0;s<i;s++){const i=eh(e[s]||"",t);o.push({content:i,evaluatedCell:{formattedValue:i}})}s.cells.push(o)}return s}}function Vz(e,t){for(let s=0;s<t.length;s++){const o=t[s].proposalValues;if(void 0===o||0===o.length)continue;const i=t=>{const i=t.functionContext;if(!i||i.parent.toUpperCase()!==e.toUpperCase()||i.argPosition!==s)return;const n=[];let r="";for(const{value:e,label:t}of o){switch(typeof e){case"string":r=`"${e}"`;break;case"number":r=e.toString();break;case"boolean":r=e?"TRUE":"FALSE"}n.push({text:r,description:t,htmlContent:[{value:r,color:"string"==typeof e?ie.STRING:ie.NUMBER}],fuzzySearchKey:r,alwaysExpanded:!0})}return n};$P.add(`${e}_function_${t[s].name}_argument_proposals`,{sequence:50,autoSelectFirstProposal:!0,selectProposal:Uz,getProposals:i})}}function Uz(e,t){let s=e.end;const o=e.end;["LEFT_PAREN","ARG_SEPARATOR"].includes(e.type)||(s=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)}F_.add("data_cleanup",class extends Ir{allowDispatch(e){return"REMOVE_DUPLICATES"===e.type?this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique)):"Success"}handle(e){switch(e.type){case"REMOVE_DUPLICATES":this.removeDuplicates(e.columns,e.hasHeader);break;case"TRIM_WHITESPACE":this.trimWhitespace()}}removeDuplicates(e,t){const s=this.getters.getActiveSheetId(),o=this.getters.getSelectedZone();t&&(o.top+=1);const i=this.getUniqueRowsIndexes(s,o.top,o.bottom,e),n=i.length;if(n===Ut(o).numberOfRows)return void this.notifyRowsRemovedAndRemaining(0,n);const r=i.map(e=>({left:o.left,top:e,right:o.right,bottom:e})),a=new kz(this.getters,this.dispatch),l=a.copy(C_(s,r),!1);if(!l)return;this.dispatch("CLEAR_CELLS",{target:[o],sheetId:s});const c={left:o.left,top:o.top,right:o.left,bottom:o.top};a.paste({zones:[c],sheetId:s},l,{isCutOperation:!1});const h={left:o.left,top:o.top-(t?1:0),right:o.right,bottom:o.top+n-1};this.selection.selectZone({cell:{col:h.left,row:h.top},zone:h});const d=o.bottom-o.top+1-n;this.notifyRowsRemovedAndRemaining(d,n)}getUniqueRowsIndexes(e,t,s,o){const i=new Map;for(const n of wC(t,s+1)){const t=o.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).value);!Object.values(i).some(e=>xC(e,t))&&(i[n]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:"info",text:fs("%s duplicate rows found and removed.\n%s unique rows remain.",e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return 1!==this.getters.getSelectedZones().length?"MoreThanOneRangeSelected":"Success"}checkNoMergeInZone(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?"WillRemoveExistingMerge":"Success"}checkRangeContainsValues(e){const t=this.getters.getActiveSheetId(),s=this.getters.getSelectedZone();e.hasHeader&&(s.top+=1);return this.getters.getEvaluatedCellsInZone(t,s).every(e=>"empty"===e.type)?"EmptyTarget":"Success"}checkNoColumnProvided(e){return 0===e.columns.length?"NoColumnsProvided":"Success"}checkColumnsIncludedInZone(e){const 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?"DuplicatesColumnsSelected":"Success"}trimWhitespace(){const e=ft(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId();let s=0;for(const{col:o,row:i}of e.map(Bt).flat()){const e=this.getters.getCell({col:o,row:i,sheetId:t});if(!e)continue;const n=_C(e.content);n!==e.content&&(s+=1,this.dispatch("UPDATE_CELL",{sheetId:t,col:o,row:i,content:n}))}const o=s?fs("Trimmed whitespace from %s cells.",s):fs("No selected cells had whitespace trimmed.");this.ui.notifyUI({type:"info",text:o,sticky:!1})}}),$P.add("dataValidation",{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(ot(t))return[];if(!this.composer.currentEditedCell)return[];const s=this.composer.currentEditedCell,o=this.getters.getValidationRuleForCell(s);if(!o||"isValueInList"!==o.criterion.type&&"isValueInRange"!==o.criterion.type)return[];const i=this.composer.currentEditedCell.sheetId,n="isValueInRange"===o.criterion.type?this.getters.getDataValidationRangeValues(i,o.criterion):o.criterion.values.map(e=>({label:e,value:e}));if(!("chip"===o.criterion.displayStyle))return n.map(e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]}));const r=o.criterion.colors;return n.map(e=>{const t=r?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:t?Pv(t):void 0,backgroundColor:t||C,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()}}),$P.add("functions",{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if("SYMBOL"!==e.type)return[];const t=e.value;if(!ot(this.composer.currentContent))return[];const s=Object.entries(uf.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:s}])=>({text:e,description:s,htmlContent:XH(t,e,g,"o-semi-bold")})).sort((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text));return s},selectProposal(e,t){let s=e.end,o=e.end;["SYMBOL","FUNCTION"].includes(e.type)&&(s=e.start);const i=this.composer.currentTokens;t+="(";const n=i.map(e=>e.start).indexOf(e.start);if(n+1<i.length){const e=i[n+1];"LEFT_PAREN"===e?.type&&o++}this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)}}),uf.getAll().forEach(e=>Vz(e.name,e.args)),$P.add("pivot_ids",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!["PIVOT.VALUE","PIVOT.HEADER","PIVOT"].includes(t.parent.toUpperCase())||0!==t.argPosition)return;const s=this.getters.getPivotIds();return s.includes(e.value)?void 0:s.map(e=>{const t=this.getters.getPivotCoreDefinition(e),s=`${this.getters.getPivotFormulaId(e)}`;return{text:s,description:t.name,htmlContent:[{value:s,color:ie.NUMBER}],fuzzySearchKey:s+t.name,alwaysExpanded:!0}}).filter(Te)},selectProposal:Uz}),$P.add("pivot_measures",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if("PIVOT.VALUE"!==t?.parent.toUpperCase()||1!==t.argPosition)return[];const s=_z(e),o=this.getters.getPivotId(s);if(!o||!this.getters.isExistingPivot(o))return[];const i=this.getters.getPivot(o);return i.init(),i.isValid()?i.definition.measures.map(e=>{if("__count"===e.fieldName){const e='"__count"';return{text:e,description:fs("Count"),htmlContent:[{value:e,color:ie.STRING}],fuzzySearchKey:fs("Count")+e}}return function(e){const t=`"${e.id}"`,s=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:ie.STRING}],fuzzySearchKey:s}}(e)}).filter(Te):[]},selectProposal:Uz}),$P.add("pivot_group_fields",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!function(e){const t=e.functionContext;return"PIVOT.VALUE"===t?.parent.toUpperCase()&&t.argPosition>=2&&t.argPosition%2==0}(e)&&!function(e){const t=e.functionContext;return"PIVOT.HEADER"===t?.parent.toUpperCase()&&t.argPosition>=1&&t.argPosition%2==1}(e))return;const s=_z(e),o=this.getters.getPivotId(s);if(!o||!this.getters.isExistingPivot(o))return;const i=this.getters.getPivot(o);i.init();const n=i.getFields(),{columns:r,rows:a}=i.definition;let l=t.args;"PIVOT.VALUE"===t?.parent.toUpperCase()?(l=l.filter((e,t)=>t%2==0),l=l.slice(1,t.argPosition)):l=l.filter((e,t)=>t%2==1);const c=l.map(e=>e?.value).filter(Te),h=r.map(e=>e.nameWithGranularity),d=a.map(e=>e.nameWithGranularity),u=[];let g=["ARG_SEPARATOR","SPACE"].includes(e.type)?c.at(-1):c.at(-2);const p=Oz.get(i.type);if(p&&g?.startsWith("#")&&(g=g.slice(1)),void 0===g&&(u.push(h[0]),u.push(d[0])),d.includes(g)){const e=d[d.indexOf(g)+1];u.push(e),u.push(h[0])}if(h.includes(g)){const e=h[h.indexOf(g)+1];u.push(e)}const m=u.filter(Te);return m.map(e=>{const[t,s]=e.split(":"),o=n[t];return o?Dz(o,s):void 0}).concat(m.map(e=>{if(!p)return;const t=e.split(":")[0],s=n[t];if(!s)return;const o=`"#${e}"`;return{text:o,description:fs("%s (positional)",s.string)+(s.help?` (${s.help})`:""),htmlContent:[{value:o,color:ie.STRING}],fuzzySearchKey:s.string+o}})).filter(Te)},selectProposal:Uz}),$P.add("pivot_group_values",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!e||!function(e){const t=e.functionContext;return"PIVOT.VALUE"===t?.parent.toUpperCase()&&t.argPosition>=2&&t.argPosition%2==1}(e)&&!function(e){const t=e.functionContext;return"PIVOT.HEADER"===t?.parent.toUpperCase()&&t.argPosition>=1&&t.argPosition%2==0}(e))return;const s=_z(e),o=this.getters.getPivotId(s);if(!o||!this.getters.isExistingPivot(o))return;const i=this.getters.getPivot(o);if(!i.isValid())return;const n=t.argPosition,r=e.functionContext?.args[n-1]?.value;if(!r)return;let a;try{a=i.definition.getDimension(r)}catch(e){return}return"month_number"===a.granularity?Object.values(dn).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:ie.NUMBER}]})):"quarter_number"===a.granularity?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:fs("Quarter %s",e),htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"day_of_month"===a.granularity?ge(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"iso_week_number"===a.granularity?ge(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"day_of_week"===a.granularity?ge(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"hour_number"===a.granularity?ge(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"minute_number"===a.granularity?ge(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"second_number"===a.granularity?ge(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):i.getPossibleFieldValues(a).map(({value:e,label:t})=>{const s="string"==typeof e,o=s?`"${e}"`:e.toString(),i=t===e?"":t;return{text:o,description:i,htmlContent:[{value:o,color:s?ie.STRING:ie.NUMBER}],fuzzySearchKey:o+i}})},selectProposal:Uz}),$P.add("sheet_names",{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return"SYMBOL"===e.type||"UNKNOWN"===e.type&&e.value.startsWith("'")?this.getters.getSheetIds().map(e=>{const t=he(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith("'")?t:"'"+t}}):[]},selectProposal(e,t){const s=e.start,o=e.end;this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t+"!")}});const Hz=new Og;Hz.add("link",{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,s)=>Wf(t.model.getters.getEvaluatedCell(e).link,t,s),title:(e,t)=>{const s=t.getEvaluatedCell(e).link;return s?s.isExternal?fs("Go to url: %(url)s",{url:s.url}):fs("Go to %(label)s",{label:s.label}):""},sequence:5}),Hz.add("dashboard_pivot_sorting",{condition:(e,t)=>{if(!t.isDashboard())return!1;const s=t.getPivotCellFromPosition(e);return gk(t,e)&&"MEASURE_HEADER"===s.type},execute:(e,t)=>{pk(t,e,function(e,t){return zz[e.getPivotCellSortDirection(t)??"none"]}(t.model.getters,e))},component:Fz,componentProps:(e,t)=>({position:e,sortDirection:t.getPivotCellSortDirection(e)}),sequence:2});const zz={none:"asc",asc:"desc",desc:"none"};vD.add("filter_icon",(e,t)=>{if(e.isFilterHeader(t)){const s=e.isFilterActive(t),o=Iv(e.getCellComputedStyle(t).fillColor||"#fff")<.45;return{type:"filter_icon",svg:uR(s,o,!1),hoverSvg:uR(s,o,!0),priority:3,horizontalAlign:"right",size:17,margin:2,position:t,onClick:(e,t)=>{const s=t.getStore(wP),o=s.persistentCellPopover;o.isOpen&&o.col===e.col&&o.row===e.row&&"FilterMenu"===o.type?s.close():s.open(e,"FilterMenu")}}}});const Bz=new Og;Bz.add("format_number_automatic",{..._k,id:"format_number_automatic",sequence:10}).add("format_number_plain_text",{...Ok,id:"format_number_plain_text",sequence:15,separator:!0}).add("format_number_number",{...Fk,id:"format_number_number",sequence:20}).add("format_number_percent",{...Mk,id:"format_number_percent",sequence:30,separator:!0}).add("format_number_currency",{...Nk,id:"format_number_currency",sequence:40}).add("format_number_accounting",{...kk,id:"format_number_accounting",sequence:45}).add("format_number_currency_rounded",{...Lk,id:"format_number_currency_rounded",sequence:50}).add("format_custom_currency",{...Uk,id:"format_custom_currency",sequence:60,separator:!0}).add("format_number_date",{...Hk,id:"format_number_date",sequence:70}).add("format_number_time",{...zk,id:"format_number_time",sequence:80}).add("format_number_date_time",{...Bk,id:"format_number_date_time",sequence:90}).add("format_number_duration",{...Gk,id:"format_number_duration",sequence:100,separator:!0}).add("more_formats",{...qk,id:"more_formats",sequence:120});const Gz=$e(e=>wn(e)?"date":e.includes("[$")?"currency":"number"),Wz={name:fs("More formats"),icon:"o-spreadsheet-Icon.NUMBER_FORMATS",children:[e=>{const t=function(e){const t=new Set(Bz.getAll().map(t=>"function"==typeof t.format?t.format(e):t.format)),s=new Map;for(const o of e.model.getters.getSheetIds()){const i=e.model.getters.getEvaluatedCells(o);for(const e in i){const o=i[e];if(o.format&&!s.has(o.format)&&!t.has(o.format)){const e=Gz(o.format);"date"!==e&&"currency"!==e||s.set(o.format,Dk({descriptionValue:"currency"===e?1e3:Vk,format:o.format,name:o.format}))}}}return[...s.values()]}(e).map(e=>({...e,sequence:110}));return t.length>0&&(t[t.length-1].separator=!0),qf([...Bz.getAll(),...t])}]};const $z=new kM;$z.add("file",{name:fs("File"),sequence:10}).addChild("settings",["file"],{name:fs("Settings"),sequence:200,execute:e=>e.openSidePanel("Settings"),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.COG"}).add("edit",{name:fs("Edit"),sequence:20}).addChild("undo",["edit"],{...KN,sequence:10}).addChild("redo",["edit"],{...JN,sequence:20,separator:!0}).addChild("copy",["edit"],{...QN,sequence:30}).addChild("cut",["edit"],{...eL,sequence:40}).addChild("paste",["edit"],{...tL,sequence:50}).addChild("paste_special",["edit"],{...sL,sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{...oL,sequence:10}).addChild("paste_special_format",["edit","paste_special"],{...iL,sequence:20}).addChild("edit_table",["edit"],{...vL,isVisible:mN,sequence:60}).addChild("find_and_replace",["edit"],{...nL,sequence:65,separator:!0}).addChild("delete",["edit"],{name:fs("Delete"),icon:"o-spreadsheet-Icon.TRASH",sequence:70}).addChild("edit_delete_cell_values",["edit","delete"],{...rL,sequence:10}).addChild("edit_delete_row",["edit","delete"],{...aL,sequence:20}).addChild("edit_delete_column",["edit","delete"],{...hL,sequence:30}).addChild("edit_delete_cell_shift_up",["edit","delete"],{...pL,sequence:40}).addChild("edit_delete_cell_shift_left",["edit","delete"],{...mL,sequence:50}).addChild("edit_unhide_columns",["edit"],{...RN,sequence:80}).addChild("edit_unhide_rows",["edit"],{...AN,sequence:80}).add("view",{name:fs("View"),sequence:30}).addChild("unfreeze_panes",["view"],{...DN,sequence:4}).addChild("freeze_panes",["view"],{..._N,sequence:5}).addChild("unfreeze_rows",["view","freeze_panes"],{...ON,sequence:5}).addChild("freeze_first_row",["view","freeze_panes"],{...FN,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{...PN,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{...MN,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{...NN,sequence:25}).addChild("freeze_first_col",["view","freeze_panes"],{...LN,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{...kN,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{...VN,sequence:40}).addChild("group_headers",["view"],{name:fs("Group"),sequence:15,separator:!0,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",isVisible:vN}).addChild("group_columns",["view","group_headers"],{...BN,sequence:5}).addChild("ungroup_columns",["view","group_headers"],{...WN,isVisible:e=>jN(e,"COL"),sequence:10}).addChild("group_rows",["view","group_headers"],{...GN,sequence:15}).addChild("ungroup_rows",["view","group_headers"],{...$N,isVisible:e=>jN(e,"ROW"),sequence:20}).addChild("show",["view"],{name:fs("Show"),sequence:1,icon:"o-spreadsheet-Icon.SHOW"}).addChild("view_gridlines",["view","show"],{...UN,sequence:5}).addChild("view_formulas",["view","show"],{...zN,sequence:10}).addChild("view_irregularity_map",["view"],{...HN,sequence:40,separator:!0}).add("insert",{name:fs("Insert"),sequence:40}).addChild("insert_row",["insert"],{...yL,sequence:10}).addChild("insert_row_before",["insert","insert_row"],{...wL,sequence:10}).addChild("insert_row_after",["insert","insert_row"],{...xL,sequence:20}).addChild("insert_column",["insert"],{...TL,sequence:20}).addChild("insert_column_before",["insert","insert_column"],{...DL,sequence:10}).addChild("insert_column_after",["insert","insert_column"],{...FL,sequence:20}).addChild("insert_cell",["insert"],{...PL,sequence:30}).addChild("insert_cell_down",["insert","insert_cell"],{...ML,name:fs("Shift down"),sequence:10}).addChild("insert_cell_right",["insert","insert_cell"],{...NL,name:fs("Shift right"),sequence:20}).addChild("insert_sheet",["insert"],{...KL,sequence:40,separator:!0}).addChild("insert_chart",["insert"],{...LL,sequence:50}).addChild("insert_carousel",["insert"],{...kL,sequence:51}).addChild("insert_pivot",["insert"],{...VL,sequence:52}).addChild("insert_image",["insert"],{...UL,sequence:55}).addChild("insert_table",["insert"],{...HL,sequence:57}).addChild("insert_function",["insert"],{...zL,sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{...BL,sequence:0}).addChild("insert_function_average",["insert","insert_function"],{...GL,sequence:10}).addChild("insert_function_count",["insert","insert_function"],{...WL,sequence:20}).addChild("insert_function_max",["insert","insert_function"],{...$L,sequence:30}).addChild("insert_function_min",["insert","insert_function"],{...qL,sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{...ZL,sequence:50}).addChild("categories_function_list",["insert","insert_function"],()=>{const e=uf.content;return[...new Set(uf.getAll().filter(e=>!e.hidden).map(e=>e.category))].filter(Te).sort().map((t,s)=>{const o=Object.keys(e).filter(s=>e[s].category===t&&!e[s].hidden);return{name:t,children:JL(o)}})}).addChild("insert_link",["insert"],{...jL,separator:!0,sequence:70}).addChild("insert_checkbox",["insert"],{...YL,sequence:80}).addChild("insert_dropdown",["insert"],{...XL,separator:!0,sequence:90}).add("format",{name:fs("Format"),sequence:50}).addChild("format_number",["format"],{...Wz,name:fs("Number"),sequence:10,separator:!0}).addChild("format_bold",["format"],{...iV,sequence:20}).addChild("format_italic",["format"],{...nV,sequence:30}).addChild("format_underline",["format"],{...rV,sequence:40}).addChild("format_strikethrough",["format"],{...aV,sequence:50,separator:!0}).addChild("format_font_size",["format"],{...lV,sequence:60,separator:!0}).addChild("format_alignment",["format"],{...cV,sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{...dV,sequence:10}).addChild("format_alignment_center",["format","format_alignment"],{...uV,sequence:20}).addChild("format_alignment_right",["format","format_alignment"],{...gV,sequence:30,separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{...mV,sequence:40}).addChild("format_alignment_middle",["format","format_alignment"],{...fV,sequence:50}).addChild("format_alignment_bottom",["format","format_alignment"],{...vV,sequence:60,separator:!0}).addChild("format_wrapping",["format"],{...bV,sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{...CV,sequence:10}).addChild("format_wrapping_wrap",["format","format_wrapping"],{...yV,sequence:20}).addChild("format_wrapping_clip",["format","format_wrapping"],{...IV,sequence:30}).addChild("format_cf",["format"],{...wV,sequence:90,separator:!0}).addChild("format_clearFormat",["format"],{...EV,sequence:100,separator:!0}).add("data",{name:fs("Data"),sequence:60}).addChild("sort_range",["data"],{...bk,sequence:10,separator:!0}).addChild("sort_ascending",["data","sort_range"],{...Sk,sequence:10}).addChild("sort_descending",["data","sort_range"],{...wk,sequence:20}).addChild("data_cleanup",["data"],{...Ck,sequence:15}).addChild("remove_duplicates",["data","data_cleanup"],{...yk,sequence:10}).addChild("trim_whitespace",["data","data_cleanup"],{...Ik,sequence:20}).addChild("split_to_columns",["data"],{...xk,sequence:20}).addChild("data_validation",["data"],{name:fs("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"],{...Ek,sequence:40,separator:!0}).addChild("pivot_data_sources",["data"],e=>{const t=e.model.getters.getPivotIds().length;return e.model.getters.getPivotIds().map((s,o)=>{const i={get highlights(){return ZH(e.model.getters,s)}};return{id:`item_pivot_${e.model.getters.getPivotFormulaId(s)}`,name:e.model.getters.getPivotDisplayName(s),sequence:50+o/t,isReadonlyAllowed:!0,execute:e=>e.openSidePanel("PivotSidePanel",{pivotId:s}),isEnabled:e=>!e.isSmall,onStartHover:e=>e.getStore(ZP).register(i),onStopHover:e=>e.getStore(ZP).unRegister(i),icon:"o-spreadsheet-Icon.PIVOT",separator:o===e.model.getters.getPivotIds().length-1,secondaryIcon:e=>e.model.getters.isPivotUnused(s)?"o-spreadsheet-Icon.UNUSED_PIVOT_WARNING":void 0}})}).addChild("reinsert_dynamic_pivot",["data"],Tk).addChild("reinsert_static_pivot",["data"],Ak);const qz=[Zz,function(e,t){return"target"in t&&Array.isArray(t.target)?{...ae(t),target:e.getSelectedZones()}:t},Yz,function(e,t){return"ranges"in t?{...ae(t),ranges:e.getSelectedZones().map(t=>e.getRangeDataFromZone(e.getActiveSheetId(),t))}:t}];function Zz(e,t){return"sheetId"in t?{...ae(t),sheetId:e.getActiveSheetId()}:t}function jz(e,t){return"zone"in t?{...ae(t),zone:e.getSelectedZone()}:t}function Yz(e,t){if(!("row"in t)||!("col"in t))return t;const{col:s,row:o}=e.getActivePosition();return{...ae(t),col:s,row:o}}const Xz=new lr;function Kz(e,t){const s=e.getSelectedZone();return{...Zz(e,t),elements:"COL"===t.dimension?ge(s.left,s.right+1):ge(s.top,s.bottom+1)}}function Jz(e,t){const s=e.getSelectedZone();return{...ae(t),zone:s}}function Qz(e,t){const s=ae(t),o=e.getSelectedZone(),{top:i,bottom:n,left:r,right:a}=o;return"cols"in s?s.cols=ge(r,a+1):"rows"in s&&(s.rows=ge(i,n+1)),s}function eB(e,t){const s=e.getSelectedZone();return{...Zz(e,t),start:"COL"===t.dimension?s.left:s.top,end:"COL"===t.dimension?s.right:s.bottom}}function tB(e,t){let s=IC(t);for(const t of qz)s=t(e,s);return s}u_.add("UPDATE_CELL",tB),u_.add("CLEAR_CELL",tB),u_.add("CLEAR_CELLS",tB),u_.add("DELETE_CONTENT",tB),u_.add("ADD_MERGE",tB),u_.add("REMOVE_MERGE",tB),u_.add("SET_FORMATTING",tB),u_.add("CLEAR_FORMATTING",tB),u_.add("SET_BORDER",tB),u_.add("CREATE_TABLE",tB),u_.add("REMOVE_TABLE",tB),u_.add("HIDE_SHEET",tB),u_.add("ADD_COLUMNS_ROWS",function(e,t){const s=e.getActivePosition();return{...Zz(e,t),base:"COL"===t.dimension?s.col:s.row}}),u_.add("REMOVE_COLUMNS_ROWS",Kz),u_.add("HIDE_COLUMNS_ROWS",Kz),u_.add("RESIZE_COLUMNS_ROWS",Kz),u_.add("CREATE_SHEET",function(e,t){const s=ae(t);s.sheetId=Xz.smallUuid();const o=t.name||e.getSheet(e.getActiveSheetId()).name,i=o.match(/(.+?)\d*$/)?.[1]||o;return s.name=e.getNextSheetName(i),s}),u_.add("CREATE_FIGURE",function(e,t){const s=Yz(e,Zz(e,t));return s.figureId=Xz.smallUuid(),s}),u_.add("CREATE_CHART",function(e,t){const s=Xz.smallUuid();return{...Zz(e,t),figureId:s,chartId:s}}),u_.add("CREATE_IMAGE",function(e,t){return{...Zz(e,t),figureId:Xz.smallUuid()}}),u_.add("GROUP_HEADERS",eB),u_.add("UNGROUP_HEADERS",eB),u_.add("UNFOLD_HEADER_GROUPS_IN_ZONE",jz),u_.add("FOLD_HEADER_GROUPS_IN_ZONE",jz),g_.add("PASTE",function(e,t){return{type:"REPEAT_PASTE",pasteOption:ae(t.pasteOption),target:e.getSelectedZones()}}),g_.add("INSERT_CELL",Jz),g_.add("DELETE_CELL",Jz),g_.add("AUTORESIZE_COLUMNS",Qz),g_.add("AUTORESIZE_ROWS",Qz),g_.add("SORT_CELLS",function(e,t){const s=e.getSelectedZone();return{...Zz(e,t),col:s.left,row:s.top,zone:s}}),g_.add("SUM_SELECTION",tB),g_.add("SET_DECIMAL",tB),g_.add("DELETE_UNFILTERED_CONTENT",tB);const sB=new class extends Og{mapping={};uuidGenerator=new lr;replace(e,t){const s={...t,id:this.uuidGenerator.uuidv4()};return super.replace(e,s)}getAllOrdered(){return this.getAll().sort((e,t)=>e.sequence-t.sequence)}};class oB{fileStore;constructor(e){this.fileStore=e}async requestImage(){const e=await this.userImageUpload(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}async uploadFile(e){const t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}userImageUpload(){return new Promise((e,t)=>{const s=document.createElement("input");s.setAttribute("type","file"),s.setAttribute("accept","image/*"),s.addEventListener("change",async()=>{null===s.files||1!==s.files.length?t():e(s.files[0])}),s.click()})}getImageOriginalSize(e){return new Promise((t,s)=>{const o=new Image;o.addEventListener("load",()=>{const e={width:o.width,height:o.height};t(e)}),o.addEventListener("error",s),o.src=e})}}const iB=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];class nB extends t.Component{static template="o-spreadsheet-RippleEffect";static props={x:String,y:String,color:String,opacity:Number,duration:Number,width:Number,height:Number,offsetY:Number,offsetX:Number,allowOverflow:Boolean,onAnimationEnd:Function,style:String};rippleRef=t.useRef("ripple");setup(){let e;t.onMounted(()=>{const t=this.rippleRef.el;t&&t.animate&&(e=t.animate(iB,{duration:this.props.duration,easing:"ease-out"}),e.addEventListener("finish",this.props.onAnimationEnd))}),t.onWillUnmount(()=>{e?.removeEventListener("finish",this.props.onAnimationEnd)})}get rippleStyle(){const{x:e,y:t,width:s,height:o}=this.props;return Ey({transform:"scale(0)",left:e,top:t,"margin-left":`${-s/2+(this.props.offsetX||0)}px`,"margin-top":`${-o/2+(this.props.offsetY||0)}px`,width:`${s}px`,height:`${o}px`,background:this.props.color,"border-radius":"100%",opacity:`${this.props.opacity}`})}}class rB extends t.Component{static template="o-spreadsheet-Ripple";static props={color:{type:String,optional:!0},opacity:{type:Number,optional:!0},duration:{type:Number,optional:!0},ignoreClickPosition:{type:Boolean,optional:!0},width:{type:Number,optional:!0},height:{type:Number,optional:!0},offsetY:{type:Number,optional:!0},offsetX:{type:Number,optional:!0},allowOverflow:{type:Boolean,optional:!0},enabled:{type:Boolean,optional:!0},onAnimationEnd:{type:Function,optional:!0},slots:Object,class:{type:String,optional:!0}};static components={RippleEffect:nB};static defaultProps={color:"#aaaaaa",opacity:.4,duration:800,enabled:!0,onAnimationEnd:()=>{},class:""};childContainer=t.useRef("childContainer");state=t.useState({ripples:[]});currentId=1;onClick(e){if(!this.props.enabled)return;if(!this.childContainer.el)return;const t=this.getRippleChildRectInfo(),{x:s,y:o,width:i,height:n}=t,r=Math.max(i,n),a={x:e.clientX-s,y:e.clientY-o,width:this.props.width||2.85*r,height:this.props.height||2.85*r};this.state.ripples.push({rippleRect:a,id:this.currentId++})}getRippleStyle(){const e=this.childContainer.el;if(!e||1!==e.childElementCount||!e.firstElementChild)return"";const t=this.getRippleChildRectInfo();return Ey({top:t.marginTop+"px",left:t.marginLeft+"px",width:t.width+"px",height:t.height+"px"})}getRippleChildRectInfo(){const e=this.childContainer.el;if(!e)throw new Error("No child container element found");if(1!==e.childElementCount||!e.firstElementChild){return{...Fy(e),marginLeft:0,marginTop:0}}const t=e.firstElementChild,s=function(e){const 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}}(t);return{...Fy(t),marginLeft:s.left,marginTop:s.top}}removeRipple(e){const t=this.state.ripples.findIndex(t=>t.id===e);-1!==t&&this.state.ripples.splice(t,1)}getRippleEffectProps(e){const t=this.state.ripples.find(t=>t.id===e)?.rippleRect;if(!t)throw new Error("Cannot find a ripple with the id "+e);return{color:this.props.color,opacity:this.props.opacity,duration:this.props.duration,x:this.props.ignoreClickPosition?"50%":t.x+"px",y:this.props.ignoreClickPosition?"50%":t.y+"px",width:t.width,height:t.height,offsetX:this.props.offsetX||0,offsetY:this.props.offsetY||0,allowOverflow:this.props.allowOverflow||!1,style:this.getRippleStyle(),onAnimationEnd:()=>this.removeRipple(e)}}}class aB extends t.Component{static template="o-spreadsheet-BottomBarSheet";static props={sheetId:String,openContextMenu:Function,style:{type:String,optional:!0},onMouseDown:{type:Function,optional:!0}};static components={Ripple:rB,ColorPicker:rM};static defaultProps={onMouseDown:()=>{},style:""};state=t.useState({isEditing:!1,pickerOpened:!1});sheetDivRef=t.useRef("sheetDiv");sheetNameRef=t.useRef("sheetNameSpan");editionState="initializing";DOMFocusableElementStore;setup(){t.onPatched(()=>{this.sheetNameRef.el&&this.state.isEditing&&"initializing"===this.editionState&&(this.editionState="editing",this.focusInputAndSelectContent())}),this.DOMFocusableElementStore=ev(OP),t.useExternalListener(window,"click",()=>this.state.pickerOpened=!1),t.useEffect(e=>{this.props.sheetId===e&&this.scrollToSheet()},()=>[this.env.model.getters.getActiveSheetId()])}focusInputAndSelectContent(){if(!this.state.isEditing||!this.sheetNameRef.el)return;this.sheetNameRef.el.focus();const e=window.getSelection();e&&this.sheetNameRef.el.firstChild&&e.setBaseAndExtent(this.sheetNameRef.el.firstChild,0,this.sheetNameRef.el.firstChild,this.sheetNameRef.el.textContent?.length||0)}scrollToSheet(){this.sheetDivRef.el?.scrollIntoView?.({behavior:"smooth",inline:"nearest"})}onFocusOut(){this.state.isEditing&&"initializing"!==this.editionState&&this.stopEdition()}onClick(){this.env.isMobile()&&this.activateSheet()}onMouseDown(e){this.env.isMobile()||(this.activateSheet(),this.props.onMouseDown(e))}activateSheet(){this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:this.props.sheetId}),this.scrollToSheet()}onDblClick(){this.env.model.getters.isReadonly()||this.startEdition()}onKeyDown(e){this.state.isEditing&&("Enter"===e.key&&(e.preventDefault(),this.stopEdition(),this.DOMFocusableElementStore.focus()),"Escape"===e.key&&(this.cancelEdition(),this.DOMFocusableElementStore.focus()))}onMouseEventSheetName(e){this.state.isEditing&&e.stopPropagation()}startEdition(){this.state.isEditing=!0,this.editionState="initializing"}stopEdition(){if(!this.state.isEditing||!this.sheetNameRef.el)return;this.state.isEditing=!1,this.editionState="initializing",this.sheetNameRef.el.blur();const e=this.getInputContent()||"";!function(e,t,s,o){const i=e.model.dispatch("RENAME_SHEET",{sheetId:t,newName:s,oldName:e.model.getters.getSheetName(t)});i.reasons.includes("MissingSheetName")?e.raiseError(fs("The sheet name cannot be empty."),o):i.reasons.includes("DuplicatedSheetName")?e.raiseError(fs("A sheet with the name %s already exists. Please select another name.",s),o):i.reasons.includes("ForbiddenCharactersInSheetName")&&e.raiseError(fs("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",$.join(" ")),o)}(this.env,this.props.sheetId,e,()=>this.startEdition())}cancelEdition(){this.state.isEditing=!1,this.editionState="initializing",this.sheetNameRef.el?.blur(),this.setInputContent(this.sheetName)}onIconClick(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}onContextMenu(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}getInputContent(){return this.sheetNameRef.el?.textContent}setInputContent(e){this.sheetNameRef.el&&(this.sheetNameRef.el.textContent=e)}onColorPicked(e){this.state.pickerOpened=!1,this.env.model.dispatch("COLOR_SHEET",{sheetId:this.props.sheetId,color:e})}get colorPickerAnchorRect(){return Fy(this.sheetDivRef.el)}get contextMenuRegistry(){return function(e){const t=new kM;return t.add("delete",{..._M,sequence:10}).add("hide_sheet",{...LM,sequence:20}).add("duplicate",{...OM,sequence:30,separator:!0}).add("rename",{...FM(e),sequence:40}).add("change_color",{...PM(e),sequence:50,separator:!0}).add("move_right",{...MM,sequence:60}).add("move_left",{...NM,sequence:70}),t}({renameSheetCallback:()=>{this.scrollToSheet(),this.startEdition()},openSheetColorPickerCallback:()=>{this.state.pickerOpened=!0}})}get isSheetActive(){return this.env.model.getters.getActiveSheetId()===this.props.sheetId}get sheetName(){return this.env.model.getters.getSheetName(this.props.sheetId)}get sheetColorStyle(){return Ey({background:this.env.model.getters.getSheet(this.props.sheetId).color||""})}}const lB=[{name:fs("Sum"),types:[_d.number],compute:(e,t)=>Er([[e]],t)},{name:fs("Avg"),types:[_d.number],compute:(e,t)=>Ga([[e]],t)},{name:fs("Min"),types:[_d.number],compute:(e,t)=>Za([[e]],t).value},{name:fs("Max"),types:[_d.number],compute:(e,t)=>qa([[e]],t).value},{name:fs("Count"),types:[_d.number,_d.text,_d.boolean,_d.error],compute:e=>$a([[e]])},{name:fs("Count Numbers"),types:[_d.number,_d.text,_d.boolean,_d.error],compute:(e,t)=>Wa([[e]],t)}];class cB extends hv{statisticFnResults=this._computeStatisticFnResults();isDirty=!1;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.handleEvent.bind(this)})}handle(e){switch((cr.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))&&(this.isDirty=!0),e.type){case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"GROUP_HEADERS":case"UNGROUP_HEADERS":case"ACTIVATE_SHEET":case"ACTIVATE_NEXT_SHEET":case"ACTIVATE_PREVIOUS_SHEET":case"EVALUATE_CELLS":case"UNDO":case"REDO":this.isDirty=!0}}finalize(){this.isDirty&&(this.isDirty=!1,this.statisticFnResults=this._computeStatisticFnResults())}handleEvent(){this.getters.isGridSelectionActive()&&(this.statisticFnResults=this._computeStatisticFnResults())}_computeStatisticFnResults(){const e=this.getters,t=e.getActiveSheetId(),s=[],o=ft(e.getSelectedZones(),[]),i=this.getters.getSheetSize(t).numberOfRows-1,n=this.getters.getSheetSize(t).numberOfCols-1;for(const r of o)for(let o=r.left;o<=(r.right??n);o++)for(let n=r.top;n<=(r.bottom??i);n++){if(e.isRowHidden(t,n)||e.isColHidden(t,o))continue;const i=e.getEvaluatedCell({sheetId:t,col:o,row:n});i.type!==_d.empty&&s.push(i)}const r=e.getLocale(),a={},l=$e(e=>{const t=e.split(",");return s.filter(e=>t.includes(e.type))});for(const e of lB){let t;const s=l(e.types.sort().join(","));s.length&&(t=Oe(()=>e.compute(s,r))),a[e.name]=t}return a}}class hB extends t.Component{static template="o-spreadsheet-BottomBarStatistic";static props={openContextMenu:Function,closeContextMenu:Function};static components={Ripple:rB};selectedStatisticFn="";store;setup(){this.store=ev(cB),t.onWillUpdateProps(()=>{Object.values(this.store.statisticFnResults).every(e=>void 0===e)&&this.props.closeContextMenu()})}getSelectedStatistic(){if(!Object.values(this.store.statisticFnResults).every(e=>void 0===e))return""===this.selectedStatisticFn&&(this.selectedStatisticFn=Object.keys(this.store.statisticFnResults)[0]),this.getComposedFnName(this.selectedStatisticFn)}listSelectionStatistics(e){const t=new kM;let s=0;for(const[e]of Object.entries(this.store.statisticFnResults))t.add(e,{name:()=>this.getComposedFnName(e),sequence:s,isReadonlyAllowed:!0,execute:()=>{this.selectedStatisticFn=e}}),s++;const o=e.currentTarget,{top:i,left:n,width:r}=o.getBoundingClientRect();this.props.openContextMenu(n+r,i,t)}getComposedFnName(e){const t=this.env.model.getters.getLocale(),s=this.store.statisticFnResults[e];return e+": "+(void 0!==s?pn(s(),{locale:t}):"__")}}class dB extends t.Component{static template="o-spreadsheet-BottomBar";static props={onClick:Function};static components={MenuPopover:PF,Ripple:rB,BottomBarSheet:aB,BottomBarStatistic:hB};bottomBarRef=t.useRef("bottomBar");sheetListRef=t.useRef("sheetList");dragAndDrop=cM();targetScroll=void 0;state=t.useState({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1});menuMaxHeight=250;menuState=t.useState({isOpen:!1,menuId:void 0,anchorRect:null,menuItems:[]});sheetList=this.getVisibleSheets();setup(){t.onWillUpdateProps(()=>{this.updateScrollState();const e=this.getVisibleSheets();Me(this.sheetList,e)||this.dragAndDrop.cancel(),this.sheetList=e})}clickAddSheet(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getSheetIds().findIndex(e=>e===t)+1,o=this.env.model.uuidGenerator.smallUuid(),i=this.env.model.getters.getNextSheetName(fs("Sheet"));this.env.model.dispatch("CREATE_SHEET",{sheetId:o,position:s,name:i}),this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map(e=>{const t=this.env.model.getters.getSheet(e);return{id:t.id,name:t.name}})}clickListSheets(e){const t=new kM,s=this.env.model.getters.getActiveSheetId();let o=0;for(const e of this.env.model.getters.getSheetIds()){const i=this.env.model.getters.getSheet(e);t.add(e,{name:i.name,sequence:o,isReadonlyAllowed:!0,textColor:i.isVisible?void 0:"#808080",execute:t=>{this.env.model.getters.isSheetVisible(e)||this.env.model.dispatch("SHOW_SHEET",{sheetId:e}),t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:s,sheetIdTo:e})},isEnabled:e=>!e.model.getters.isReadonly()||i.isVisible,icon:i.color?"o-spreadsheet-Icon.SMALL_DOT_RIGHT_ALIGN":void 0,iconColor:i.color}),o++}const i=e.currentTarget,{left:n}=i.getBoundingClientRect(),r=this.bottomBarRef.el.getBoundingClientRect().top;this.openContextMenu(n,r,"listSheets",t)}openContextMenu(e,t,s,o){this.menuState.isOpen=!0,this.menuState.menuId=s,this.menuState.menuItems=o.getMenuItems(),this.menuState.anchorRect={x:e,y:t,width:0,height:0}}onSheetContextMenu(e,t,s){const o=s.currentTarget,{top:i,left:n}=o.getBoundingClientRect();s.closedMenuId!==e?this.openContextMenu(n,i,e,t):this.closeMenu()}closeMenu(){this.menuState.isOpen=!1,this.menuState.menuId=void 0,this.menuState.menuItems=[],this.menuState.anchorRect=null}closeContextMenuWithId(e){this.menuState.menuId===e&&this.closeMenu()}onWheel(e){this.targetScroll=void 0;e.currentTarget.scrollLeft+=.5*e.deltaY}onScroll(){this.updateScrollState(),this.targetScroll===this.sheetListCurrentScroll&&(this.targetScroll=void 0)}onArrowLeft(e){if(!this.state.isSheetListScrollableLeft)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll-this.sheetListWidth;this.scrollSheetListTo(Math.max(0,t))}onArrowRight(e){if(!this.state.isSheetListScrollableRight)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll+this.sheetListWidth;this.scrollSheetListTo(Math.min(this.sheetListMaxScroll,t))}updateScrollState(){this.state.isSheetListScrollableLeft=this.sheetListCurrentScroll>0,this.state.isSheetListScrollableRight=this.sheetListCurrentScroll<this.sheetListMaxScroll}scrollSheetListTo(e){this.sheetListRef.el&&(this.targetScroll=e,this.sheetListRef.el.scrollTo({top:0,left:e,behavior:"smooth"}))}onSheetMouseDown(e,t){if(0!==t.button||this.env.model.getters.isReadonly())return;if(this.closeMenu(),this.env.isMobile())return;const s=this.getVisibleSheets(),o=this.getSheetItemRects(),i=s.map((e,t)=>({id:e.id,size:o[t].width,position:o[t].x}));this.dragAndDrop.start("horizontal",{draggedItemId:e,initialMousePosition:t.clientX,items:i,scrollableContainerEl:this.sheetListRef.el,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){const s=t-this.getVisibleSheets().findIndex(t=>t.id===e);e&&0!==s&&this.env.model.dispatch("MOVE_SHEET",{sheetId:e,delta:s})}getSheetStyle(e){return this.dragAndDrop.itemsStyle[e]||""}getSheetItemRects(){return Array.from(this.bottomBarRef.el.querySelectorAll(".o-sheet")).map(e=>e.getBoundingClientRect()).map(e=>({x:e.x,width:e.width-1,y:e.y,height:e.height}))}get sheetListCurrentScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollLeft:0}get sheetListWidth(){return this.sheetListRef.el?this.sheetListRef.el.clientWidth:0}get sheetListMaxScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollWidth-this.sheetListRef.el.clientWidth:0}}class uB extends hv{_clickableCells=t.markRaw({});_registryItems=t.markRaw(Hz.getAll().sort((e,t)=>e.sequence-t.sequence));handle(e){(cr.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))&&(this._clickableCells=t.markRaw({}),this._registryItems=t.markRaw(Hz.getAll().sort((e,t)=>e.sequence-t.sequence)))}getClickableItem(e){const{sheetId:t,col:s,row:o}=e,i=this._clickableCells,n=mt(s,o);if(i[t]||(i[t]={}),!(n in i[t])){const s=this.findClickableItem(e);i[t][n]=s}return i[t][n]}findClickableItem(e){const t=this.getters;for(const s of this._registryItems)if(s.condition(e,t))return s}get clickableCells(){const e=[],t=this.getters,s=t.getActiveSheetId();for(const o of this.getters.getVisibleCellPositions()){const i=this.getClickableItem(o);if(!i)continue;const n="function"==typeof i.title?i.title(o,t):i.title,r=t.expandZone(s,Zt(o));e.push({coordinates:t.getVisibleRect(r),position:o,action:i.execute,title:n||"",component:i.component,componentProps:i.componentProps?.(o,t)??{}})}return e}}class gB extends t.Component{static template="o-spreadsheet-SpreadsheetDashboard";static props={getGridSize:Function};static components={GridOverlay:rU,GridPopover:aU,Popover:DF,VerticalScrollBar:EU,HorizontalScrollBar:wU};cellPopovers;onMouseWheel;canvasPosition;hoveredCell;clickableCellsStore;gridRef;setup(){this.gridRef=t.useRef("grid"),this.hoveredCell=ev(HF),this.clickableCellsStore=ev(uB),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),mU("canvas",this.env.model,()=>this.env.model.getters.getSheetViewDimension()),this.onMouseWheel=vU((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=ev(wP),fU(this.gridRef,this.moveCanvas.bind(this),()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0})}get gridContainer(){const e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e),{end:s}=this.env.model.getters.getColDimensions(e,t);return Ey({"max-width":`${s}px`})}get gridOverlayDimensions(){return Ey({height:"100%",width:"100%"})}getCellClickableStyle(e){return Ey({top:`${e.y}px`,left:`${e.x}px`,width:`${e.width}px`,height:`${e.height}px`})}getClickableCells(){return t.toRaw(this.clickableCellsStore.clickableCells)}selectClickableCell(e,t){const{position:s,action:o}=t;o(s,this.env,Hy(e))}onClosePopover(){this.cellPopovers.close()}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t,height:e,gridOffsetX:0,gridOffsetY:0})}moveCanvas(e,t){const{scrollX:s,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:s+e,offsetY:o+t})}getGridRect(){return{...Oy(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}}class pB extends t.Component{static template="o-spreadsheet-HeaderGroup";static props={group:Object,layerOffset:Number,openContextMenu:Function};toggleGroup(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:s}=this.props.group;OV(this.env,e,this.dimension,t,s)}get groupBoxStyle(){const e=this.groupBox;return Ey({top:`${e.groupRect.y}px`,left:`${e.groupRect.x}px`,width:`${e.groupRect.width}px`,height:`${e.groupRect.height}px`})}get groupButtonStyle(){return Ey({"background-color":this.isGroupFolded?"#333":"#fff",color:this.isGroupFolded?"#fff":"#333"})}get groupButtonIcon(){return this.isGroupFolded?"o-spreadsheet-Icon.PLUS":"o-spreadsheet-Icon.MINUS"}get isGroupFolded(){const e=this.env.model.getters.getActiveSheetId(),t=this.props.group;return this.env.model.getters.isGroupFolded(e,this.dimension,t.start,t.end)}onContextMenu(e){const t=this.env.model.getters.getActiveSheetId(),s={x:e.clientX,y:e.clientY},o=this.props.group,i=function(e,t,s,o){const i=qf([{id:"toggle_group",name:e=>{const i=e.model.getters.getActiveSheetId(),n=e.model.getters.isGroupFolded(i,t,s,o);return fs(n?"ROW"===t?"Expand row group":"Expand column group":"ROW"===t?"Collapse row group":"Collapse column group")},execute:e=>{const i=e.model.getters.getActiveSheetId();OV(e,i,t,s,o)},icon:e=>{const i=e.model.getters.getActiveSheetId();return e.model.getters.isGroupFolded(i,t,s,o)?"o-spreadsheet-Icon.EXPAND":"o-spreadsheet-Icon.COLLAPSE"}},{id:"remove_group",name:fs("ROW"===t?"Remove row group":"Remove column group"),execute:e=>{const i=e.model.getters.getActiveSheetId();e.model.dispatch("UNGROUP_HEADERS",{sheetId:i,dimension:t,start:s,end:o})},icon:"o-spreadsheet-Icon.TRASH",separator:!0}]);return[...i,...FV(e,t)]}(t,this.dimension,o.start,o.end);this.props.openContextMenu(s,i)}}class mB extends pB{dimension="ROW";get groupBorderStyle(){const e=this.groupBox;return 0===this.groupBox.groupRect.height?"":Ey({top:e.headerRect.height/2+"px",left:"calc(50% - 1px)",width:"30%",height:`calc(100% - ${e.headerRect.height/2}px)`,"border-left":"1px solid","border-bottom":e.isEndHidden?"":"1px solid"})}get groupHeaderStyle(){return Ey({width:"100%",height:`${this.groupBox.headerRect.height}px`})}get groupBox(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:s}=this.props.group,o=this.env.model.getters.getRowDimensions(e,t).start,i=this.env.model.getters.getRowDimensions(e,s).end;let n=0,r=A;if(0!==t){const s=this.env.model.getters.getRowDimensions(e,t-1);n=A+s.start,r=s.end-s.start}const a={x:this.props.layerOffset,y:n,width:F,height:r};return{headerRect:a,groupRect:{x:this.props.layerOffset,y:a.y,width:F,height:a.height+(i-o)},isEndHidden:this.env.model.getters.isRowHidden(e,s)}}}class fB extends pB{dimension="COL";get groupBorderStyle(){const e=this.groupBox;return 0===e.groupRect.width?"":Ey({top:"calc(50% - 1px)",left:e.headerRect.width/2+"px",width:`calc(100% - ${e.headerRect.width/2}px)`,height:"30%","border-top":"1px solid","border-right":e.isEndHidden?"":"1px solid"})}get groupHeaderStyle(){return Ey({width:`${this.groupBox.headerRect.width}px`,height:"100%"})}get groupBox(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:s}=this.props.group,o=this.env.model.getters.getColDimensions(e,t).start,i=this.env.model.getters.getColDimensions(e,s).end;let n=0,r=D;if(0!==t){const s=this.env.model.getters.getColDimensions(e,t-1);n=D+s.start,r=s.end-s.start}const a={x:n,y:this.props.layerOffset,width:r,height:F};return{headerRect:a,groupRect:{x:a.x,y:this.props.layerOffset,width:a.width+(i-o),height:F},isEndHidden:this.env.model.getters.isColHidden(e,s)}}}class vB extends t.Component{static template="o-spreadsheet-HeaderGroupContainer";static props={dimension:String,layers:Array};static components={RowGroup:mB,ColGroup:fB,MenuPopover:PF};menu=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});getLayerOffset(e){return e*F}onContextMenu(e){const t=this.env.model.getters.getActiveSheetId(),s={x:e.clientX,y:e.clientY},o=FV(t,this.props.dimension);this.openContextMenu(s,o)}openContextMenu(e,t){this.menu.isOpen=!0,this.menu.anchorRect={...e,width:0,height:0},this.menu.menuItems=t}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get groupComponent(){return"ROW"===this.props.dimension?mB:fB}get hasFrozenPane(){const e=this.env.model.getters.getMainViewportCoordinates();return"COL"===this.props.dimension?e.x>0:e.y>0}get scrollContainerStyle(){const{scrollX:e,scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo(),s={};return"COL"===this.props.dimension?s.left=-e-this.frozenPaneContainerSize+"px":s.top=-t-this.frozenPaneContainerSize+"px",Ey(s)}get frozenPaneContainerStyle(){const e={};return"COL"===this.props.dimension?e.width=`${this.frozenPaneContainerSize}px`:e.height=`${this.frozenPaneContainerSize}px`,Ey(e)}get frozenPaneContainerSize(){if(!this.hasFrozenPane)return 0;const e=this.env.model.getters.getMainViewportCoordinates();return"COL"===this.props.dimension?D+e.x:A+e.y}}class bB extends t.Component{static template="o-spreadsheet-SidePanel";static props={panelContent:Object,panelProps:Object,onCloseSidePanel:Function,onStartHandleDrag:Function,onResetPanelSize:Function,isPinned:{type:Boolean,optional:!0},onTogglePinPanel:{type:Function,optional:!0},onToggleCollapsePanel:{type:Function,optional:!0},isCollapsed:{type:Boolean,optional:!0}};spreadsheetRect=AF();getTitle(){const e=this.props.panelContent;return"function"==typeof e.title?e.title(this.env,this.props.panelProps):e.title}get pinInfoMessage(){return fs("Pin this panel to allow to open another side panel beside it.")}}class SB extends t.Component{static template="o-spreadsheet-SidePanels";static props={};static components={SidePanel:bB};sidePanelStore;spreadsheetRect=AF();setup(){this.sidePanelStore=ev(Rz),t.useEffect(()=>{this.sidePanelStore.mainPanel&&!this.sidePanelStore.isMainPanelOpen&&this.sidePanelStore.closeMainPanel(),this.sidePanelStore.secondaryPanel&&!this.sidePanelStore.isSecondaryPanelOpen&&this.sidePanelStore.close()},()=>[this.sidePanelStore.isMainPanelOpen,this.sidePanelStore.isSecondaryPanelOpen])}startHandleDrag(e,t){const s=document.body.style.cursor,o="mainPanel"===e?this.sidePanelStore.mainPanel:this.sidePanelStore.secondaryPanel;if(!o)return;const i=o.size,n=t.clientX;iM(t=>{document.body.style.cursor="col-resize";const s=i+n-t.clientX;this.sidePanelStore.changePanelSize(e,s)},()=>{document.body.style.cursor=s})}get mainPanelProps(){const e=this.sidePanelStore.mainPanelProps;if(this.sidePanelStore.mainPanel&&e)return{panelContent:yz.get(this.sidePanelStore.mainPanel.componentTag),panelProps:e,onCloseSidePanel:()=>this.sidePanelStore.closeMainPanel(),onTogglePinPanel:()=>this.sidePanelStore.togglePinPanel(),onStartHandleDrag:e=>this.startHandleDrag("mainPanel",e),onResetPanelSize:()=>this.sidePanelStore.resetPanelSize("mainPanel"),isPinned:this.sidePanelStore.mainPanel?.isPinned,onToggleCollapsePanel:()=>this.sidePanelStore.toggleCollapsePanel("mainPanel"),isCollapsed:this.sidePanelStore.mainPanel?.isCollapsed}}get secondaryPanelProps(){const e=this.sidePanelStore.secondaryPanelProps;if(this.sidePanelStore.secondaryPanel&&e)return{panelContent:yz.get(this.sidePanelStore.secondaryPanel.componentTag),panelProps:e,onCloseSidePanel:()=>this.sidePanelStore.close(),onStartHandleDrag:e=>this.startHandleDrag("secondaryPanel",e),onResetPanelSize:()=>this.sidePanelStore.resetPanelSize("secondaryPanel"),onToggleCollapsePanel:()=>this.sidePanelStore.toggleCollapsePanel("secondaryPanel"),isCollapsed:this.sidePanelStore.secondaryPanel?.isCollapsed}}get panelList(){return[{key:this.sidePanelStore.secondaryPanelKey,props:this.secondaryPanelProps,style:this.sidePanelStore.secondaryPanel?Ey({width:`${this.sidePanelStore.secondaryPanel.size}px`}):""},{key:this.sidePanelStore.mainPanelKey,props:this.mainPanelProps,style:this.sidePanelStore.mainPanel?Ey({width:`${this.sidePanelStore.mainPanel.size}px`}):""}].filter(e=>e.key&&e.props)}}class CB extends t.Component{static template="o-spreadsheet-RibbonMenu";static props={onClose:Function};static components={Menu:RF};rootItems=$z.getMenuItems();menuRef=t.useRef("menu");containerRef=t.useRef("container");state=t.useState({menuItems:this.rootItems,title:fs("Menu Bar"),parentState:void 0});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0}),t.onMounted(this.updateShadows)}onExternalClick(e){this.menuRef.el?.contains(e.target)||this.props.onClose()}onClickMenu(e){const t=e.children(this.env);t.length?(this.state.parentState={...this.state},this.state.menuItems=t,this.state.title=e.name(this.env),this.containerRef.el?.scrollTo({top:0})):(this.state.menuItems=this.rootItems,this.state.title=void 0,this.state.parentState=void 0,e.execute?.(this.env),this.props.onClose())}get menuProps(){return{menuItems:this.state.menuItems,onClose:this.props.onClose,onClickMenu:this.onClickMenu.bind(this)}}get style(){return Ey({height:`${this.props.height}px`})}updateShadows(){if(!this.containerRef.el)return;this.containerRef.el.classList.remove("scroll-top","scroll-bottom");const e=this.containerRef.el.scrollHeight-this.containerRef.el.clientHeight||0;this.containerRef.el.scrollTop<e-1&&this.containerRef.el.classList.add("scroll-bottom"),this.containerRef.el.scrollTop>0&&this.containerRef.el.classList.add("scroll-top")}onClickBack(){this.state.parentState?(this.state.menuItems=this.state.parentState.menuItems,this.state.title=this.state.parentState.title,this.state.parentState=this.state.parentState.parentState,this.containerRef.el?.scrollTo({top:0})):this.props.onClose()}get backTitle(){return this.state.parentState?fs("Go to previous menu"):fs("Close menu bar")}}class yB extends t.Component{static components={Composer:zP,BottomBar:dB,Ripple:rB,RibbonMenu:CB};static template="o-spreadsheet-SmallBottomBar";static props={onClick:Function};composerFocusStore;composerStore;composerInterface;composerRef=t.useRef("bottombarComposer");menuState=t.useState({isOpen:!1});setup(){this.composerFocusStore=ev(uv);const e=ev(WV);this.composerStore=e,this.composerInterface={id:"bottombarComposer",get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition},t.useEffect(()=>{this.env.isMobile()&&!this.menuState.isOpen&&"inactive"!==this.composerStore.editionMode&&this.composerFocusStore.activeComposer!==this.composerInterface&&this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"})})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get showFxIcon(){return"inactive"===this.focus&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get rect(){return this.composerRef.el?Fy(this.composerRef.el):{x:0,y:0,width:0,height:0}}get composerProps(){const{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,composerStore:this.composerStore,onComposerContentFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus",selection:e}),isDefaultFocus:!1,inputStyle:Ey({height:"inactive"===this.focus?"26px":"fit-content","max-height":"130px"}),showAssistant:!Gy(),placeholder:this.composerStore.placeholder}}get symbols(){return["=","(",")",":","-","/","*",",","+","$","."]}insertSymbol(e){this.composerStore.replaceComposerCursorSelection(e),this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"})}toggleRibbon(){this.composerStore.cancelEdition(),this.menuState.isOpen=!this.menuState.isOpen}}class IB extends t.Component{static template="o-spreadsheet-TopBarComposer";static props={};static components={Composer:zP};composerFocusStore;composerStore;composerInterface;setup(){this.composerFocusStore=ev(uv);const e=ev(WV);this.composerStore=e,this.composerInterface={id:"topbarComposer",get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition}}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get showFxIcon(){return"inactive"===this.focus&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get composerStyle(){const e={padding:"5px 0px 5px 8px","max-height":"300px","line-height":"24px"};return e.height="inactive"===this.focus?"34px":"fit-content",Ey(e)}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}}class wB{mutators=["closeDropdowns","openDropdown"];_currentDropdown=null;closeDropdowns(){this._currentDropdown=null}openDropdown(e){this._currentDropdown=e}get currentDropdown(){return this._currentDropdown}}function EB(){const e=t.useComponent(),s=ev(wB);return t.onWillUnmount(()=>{e===s.currentDropdown&&s.closeDropdowns()}),{closeDropdowns:()=>s.closeDropdowns(),openDropdown:()=>{s.openDropdown(e)},get isActive(){return s.currentDropdown===e}}}const RB=[[["all","o-spreadsheet-Icon.BORDERS"],["hv","o-spreadsheet-Icon.BORDER_HV"],["h","o-spreadsheet-Icon.BORDER_H"],["v","o-spreadsheet-Icon.BORDER_V"],["external","o-spreadsheet-Icon.BORDER_EXTERNAL"]],[["left","o-spreadsheet-Icon.BORDER_LEFT"],["top","o-spreadsheet-Icon.BORDER_TOP"],["right","o-spreadsheet-Icon.BORDER_RIGHT"],["bottom","o-spreadsheet-Icon.BORDER_BOTTOM"],["clear","o-spreadsheet-Icon.BORDER_CLEAR"]]];class xB extends t.Component{static template="o-spreadsheet-BorderEditor";static props={class:{type:String,optional:!0},currentBorderColor:{type:String,optional:!1},currentBorderStyle:{type:String,optional:!1},currentBorderPosition:{type:String,optional:!0},onBorderColorPicked:Function,onBorderStylePicked:Function,onBorderPositionPicked:Function,maxHeight:{type:Number,optional:!0},anchorRect:Object};static components={ColorPickerWidget:DU,Popover:DF};BORDER_POSITIONS=RB;lineStyleButtonRef=t.useRef("lineStyleButton");borderStyles=As;state=t.useState({activeTool:void 0});toggleDropdownTool(e){const t=this.state.activeTool===e;this.state.activeTool=t?void 0:e}closeDropdown(){this.state.activeTool=void 0}setBorderPosition(e){this.props.onBorderPositionPicked(e),this.closeDropdown()}setBorderColor(e){this.props.onBorderColorPicked(e),this.closeDropdown()}setBorderStyle(e){this.props.onBorderStylePicked(e),this.closeDropdown()}get lineStylePickerPopoverProps(){return{anchorRect:this.lineStylePickerAnchorRect,positioning:"bottom-left",verticalOffset:0}}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"bottom-left",verticalOffset:0}}get lineStylePickerAnchorRect(){const e=this.lineStyleButtonRef.el;if(null===e)return{x:0,y:0,width:0,height:0};const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}}class TB extends t.Component{static template="o-spreadsheet-BorderEditorWidget";static props={disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={BorderEditor:xB};topBarToolStore;borderEditorButtonRef=t.useRef("borderEditorButton");state=t.useState({currentColor:U,currentStyle:V,currentPosition:void 0});setup(){this.topBarToolStore=EB(),t.onWillUpdateProps(()=>{this.isActive||(this.state.currentPosition=void 0)})}get dropdownMaxHeight(){return this.env.model.getters.getSheetViewDimension().height}get borderEditorAnchorRect(){const e=this.borderEditorButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}onBorderPositionPicked(e){this.state.currentPosition=e,this.updateBorder()}onBorderColorPicked(e){this.state.currentColor=e,this.updateBorder()}onBorderStylePicked(e){this.state.currentStyle=e,this.updateBorder()}get isActive(){return this.topBarToolStore.isActive}toggleBorderEditor(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}updateBorder(){void 0!==this.state.currentPosition&&this.env.model.dispatch("SET_ZONE_BORDERS",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),border:{position:this.state.currentPosition,color:this.state.currentColor,style:this.state.currentStyle}})}}class AB extends t.Component{static template="o-spreadsheet-PaintFormatButton";static props={class:{type:String,optional:!0}};paintFormatStore;setup(){this.paintFormatStore=ev(sU)}get isActive(){return this.paintFormatStore.isActive}onDblClick(){this.paintFormatStore.activate({persistent:!0})}togglePaintFormat(){this.isActive?this.paintFormatStore.cancel():this.paintFormatStore.activate({persistent:!1})}}class DB extends t.Component{static template="o-spreadsheet-TableDropdownButton";static components={TableStylesPopover:fz,ActionButton:AU};static props={class:{type:String,optional:!0}};topBarToolStore;state=t.useState({popoverProps:void 0});setup(){this.topBarToolStore=EB()}onStylePicked(e){const t=this.env.model.getters.getActiveSheetId(),s={...this.tableConfig,styleId:e};oN(this.env,t,s).isSuccessful&&this.env.openSidePanel("TableSidePanel",{}),this.closePopover()}onClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps)return void this.closePopover();if(this.env.model.getters.getFirstTableInSelection())return this.topBarToolStore.closeDropdowns(),void this.env.toggleSidePanel("TableSidePanel",{});const t=e.currentTarget,{left:s,bottom:o}=t.getBoundingClientRect();this.topBarToolStore.openDropdown(),this.state.popoverProps={anchorRect:{x:s,y:o,width:0,height:0},positioning:"bottom-left",verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}get action(){return{name:e=>e.model.getters.getFirstTableInSelection()?fs("Edit table"):fs("Insert table"),icon:e=>e.model.getters.getFirstTableInSelection()?"o-spreadsheet-Icon.EDIT_TABLE":"o-spreadsheet-Icon.PAINT_TABLE"}}get tableConfig(){return{...hE,numberOfHeaders:1,bandedRows:!0}}}class _B extends t.Component{static components={ColorPickerWidget:DU};static props={class:String,style:String,icon:String,title:String};static template="o-spreadsheet-ColorEditor";topBarToolStore;state=t.useState({isOpen:!1});setup(){this.topBarToolStore=EB()}get currentColor(){return this.env.model.getters.getCurrentStyle()[this.props.style]||("textColor"===this.props.style?"#000000":"#ffffff")}setColor(e){nN(this.env,{[this.props.style]:e}),this.state.isOpen=!1}get isMenuOpen(){return this.topBarToolStore.isActive}onClick(){this.isMenuOpen?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}}class OB extends t.Component{static template="o-spreadsheet-DropdownAction";static components={ActionButton:AU,Popover:DF};static props={parentAction:Object,childActions:Array,class:String,childClass:String};topBarToolStore;actionRef=t.useRef("actionRef");setup(){this.topBarToolStore=EB()}toggleDropdown(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}get popoverProps(){return{anchorRect:this.actionRef.el?this.actionRef.el.getBoundingClientRect():{x:0,y:0,width:0,height:0},positioning:"bottom-left",verticalOffset:0,class:"rounded"}}}class FB extends t.Component{static components={FontSizeEditor:_U};static props={class:String};static template="o-spreadsheet-TopBarFontSizeEditor";topBarToolStore;setup(){this.topBarToolStore=EB()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||L}setFontSize(e){nN(this.env,{fontSize:e})}onToggle(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}}class PB extends t.Component{static template="o-spreadsheet-NumberFormatsTool";static components={MenuPopover:PF,ActionButton:AU};static props={class:String};formatNumberMenuItemSpec=Wz;topBarToolStore;buttonRef=t.useRef("buttonRef");state=t.useState({anchorRect:{x:0,y:0,width:0,height:0},menuItems:[]});setup(){this.topBarToolStore=EB()}toggleMenu(){if(this.isActive)this.topBarToolStore.closeDropdowns();else{const e=jf(this.formatNumberMenuItemSpec);this.state.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.anchorRect=Fy(this.buttonRef.el),this.topBarToolStore.openDropdown()}}get isActive(){return this.topBarToolStore.isActive}}const MB=new class{content={};add(e){if(e in this.content)throw new Error(`${e} is already present in this registry!`);return this.content[e]=[],this}addChild(e,t){return this.content[e].push(t),this}getEntries(e){return this.content[e].sort((e,t)=>e.sequence-t.sequence)}getCategories(){return Object.keys(this.content)}};MB.add("edit").addChild("edit",{component:AU,props:{action:KN,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("edit",{component:AU,props:{action:JN,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("edit",{component:AB,props:{class:"o-hoverable-button o-toolbar-button o-mobile-disabled"},sequence:3}).addChild("edit",{component:AU,props:{action:EV,class:"o-hoverable-button o-toolbar-button"},sequence:4}).add("numberFormat").addChild("numberFormat",{component:AU,props:{action:Pk,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("numberFormat",{component:AU,props:{action:oV,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("numberFormat",{component:AU,props:{action:sV,class:"o-hoverable-button o-toolbar-button"},sequence:3}).addChild("numberFormat",{component:PB,props:{class:"o-menu-item-button o-hoverable-button o-toolbar-button"},sequence:4}).add("fontSize").addChild("fontSize",{component:FB,props:{class:"o-hoverable-button o-toolbar-button"},sequence:3}).add("textStyle").addChild("textStyle",{component:AU,props:{action:iV,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("textStyle",{component:AU,props:{action:nV,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("textStyle",{component:AU,props:{action:aV,class:"o-hoverable-button o-toolbar-button"},sequence:3}).addChild("textStyle",{component:_B,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button",style:"textColor",icon:"o-spreadsheet-Icon.TEXT_COLOR",title:fs("Text Color")},sequence:4}).add("cellStyle").addChild("cellStyle",{component:_B,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button",style:"fillColor",icon:"o-spreadsheet-Icon.FILL_COLOR",title:fs("Fill Color")},sequence:1}).addChild("cellStyle",{component:TB,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:2}).addChild("cellStyle",{component:AU,props:{action:fL,class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:3}).add("alignment").addChild("alignment",{component:OB,props:{parentAction:hV,childActions:[dV,uV,gV],class:"o-hoverable-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:1}).addChild("alignment",{component:OB,props:{parentAction:pV,childActions:[mV,fV,vV],class:"o-hoverable-button o-menu-item-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:2}).addChild("alignment",{component:OB,props:{parentAction:SV,childActions:[CV,yV,IV],class:"o-hoverable-button o-menu-item-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:3}).add("misc").addChild("misc",{component:DB,props:{class:"o-toolbar-button o-hoverable-button o-menu-item-button o-mobile-disabled"},sequence:1}).addChild("misc",{component:AU,props:{action:Rk,class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:2});class NB extends t.Component{static template="o-spreadsheet-TopBar";static props={onClick:Function,dropdownMaxHeight:Number};static components={MenuPopover:PF,TopBarComposer:IB,Popover:DF};toolsCategories=MB.getCategories();state=t.useState({menuState:{isOpen:!1,anchorRect:null,menuItems:[]},invisibleToolsCategories:[],toolsPopoverState:{isOpen:!1}});isSelectingMenu=!1;openedEl=null;menus=[];toolbarMenuRegistry=MB;formatNumberMenuItemSpec=Wz;isntToolbarMenu=!1;composerFocusStore;fingerprints;topBarToolStore;toolBarContainerRef=t.useRef("toolBarContainer");toolbarRef=t.useRef("toolBar");moreToolsContainerRef=t.useRef("moreToolsContainer");moreToolsButtonRef=t.useRef("moreToolsButton");spreadsheetRect=AF();setup(){this.composerFocusStore=ev(uv),this.fingerprints=ev(yN),this.topBarToolStore=ev(wB),t.useExternalListener(window,"click",this.onExternalClick),t.onWillStart(()=>this.updateCellState()),t.onWillUpdateProps(()=>this.updateCellState()),t.useEffect(()=>{this.state.toolsPopoverState.isOpen=!1,this.setVisibilityToolsGroups()},()=>[this.spreadsheetRect.width])}setVisibilityToolsGroups(){if(this.env.model.getters.isReadonly())return;const e=[],{x:t}=this.toolbarRef.el.getBoundingClientRect(),{x:s}=this.toolBarContainerRef.el.getBoundingClientRect();this.moreToolsContainerRef.el?.classList.remove("d-none");const o=this.moreToolsButtonRef.el?.getBoundingClientRect().width||0,i=Math.round(this.spreadsheetRect.width)-o-(t-s)-16,n=document.querySelectorAll(".tool-container");let r=0;for(let t=0;t<n.length;t++){const s=n[t];s.classList.remove("d-none");const{width:o}=s.getBoundingClientRect();r+=o,r>i&&(s.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 sB.getAllOrdered().filter(e=>!e.isVisible||e.isVisible(this.env))}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||L}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=Fy(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=$z.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?Fy(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}}class LB{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({[gI.PlainText]:this.getBlob(e,gI.PlainText),[gI.Html]:this.getBlob(e,gI.Html)})]))}catch(e){}}else await this.writeText(e[gI.PlainText]??"")}async writeText(e){try{this.clipboard?.writeText(e)}catch(e){}}async read(){let e;try{e=await navigator.permissions.query({name:"clipboard-read"})}catch(e){}if(!this.clipboard?.read)return{status:"ok",content:{[gI.PlainText]:await(this.clipboard?.readText())}};try{const e=await this.clipboard.read(),t={};for(const s of e)for(const e of s.types){const o=await s.getType(e);if(S_.includes(e))t[e]=o;else{const s=await o.text();t[e]=s}}return{status:"ok",content:t}}catch(t){return{status:"denied"===e?.state?"permissionDenied":"notImplemented"}}}getClipboardItems(e){const t={};for(const s of Object.keys(e))t[s]=this.getBlob(e,s);return[new ClipboardItem(t)]}getBlob(e,t){const s=e[t];return s instanceof Blob||s instanceof File?s:new Blob([e[t]||""],{type:t})}}class kB 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:NB,Grid:Az,BottomBar:dB,SmallBottomBar:yB,SidePanels:SB,SpreadsheetDashboard:gB,HeaderGroupContainer:vB,FullScreenFigure:Pz};sidePanel;spreadsheetRef=t.useRef("spreadsheet");spreadsheetRect=AF();_focusGrid;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){const e={};this.env.isDashboard()?e["grid-template-rows"]="auto":e["grid-template-rows"]="min-content auto min-content";const t=this.sidePanel.mainPanel?`${this.sidePanel.totalPanelSize||wz}px`:"auto";return e["grid-template-columns"]=`auto ${t}`,Ey(e)}setup(){if(!("isSmall"in this.env)){const e=function(){const e=AF();return{get isSmall(){return e.width<768}}}();t.useSubEnv({get isSmall(){return e.isSmall}})}const e=Qf();e.inject(nv,this.model);const s=this.env;e.get(Iz).setSmallThreshhold(()=>s.isSmall),this.notificationStore=ev(jP),this.composerFocusStore=ev(uv),this.sidePanel=ev(Rz);const o=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:o?new oB(o):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||new LB(navigator.clipboard),startCellEdition:e=>this.composerFocusStore.focusActiveComposer({content:e}),notifyUser:e=>this.notificationStore.notifyUser(e),askConfirmation:(e,t,s)=>this.notificationStore.askConfirmation(e,t,s),raiseError:(e,t)=>this.notificationStore.raiseError(e,t),isMobile:Wy}),this.notificationStore.updateNotificationCallbacks({...this.props}),t.useEffect(()=>{!this.spreadsheetRef.el.contains(document.activeElement)&&document.activeElement?.contains(this.spreadsheetRef.el)&&this.focusGrid()},()=>[this.env.model.getters.getActiveSheetId()]),t.useExternalListener(window,"resize",()=>this.render(!0)),t.useExternalListener(document.body,"wheel",()=>{}),this.bindModelEvents(),t.onWillUpdateProps(e=>{if(e.model!==this.props.model)throw new 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})});const i=function(e){let t=!1;return async(...s)=>{t||(t=!0,await Promise.resolve(),t=!1,e(...s))}}(this.render.bind(this,!0));t.onMounted(()=>{this.checkViewportSize(),e.on("store-updated",this,i),n.observe(this.spreadsheetRef.el)}),t.onWillUnmount(()=>{this.unbindModelEvents(),e.off("store-updated",this),n.disconnect(),function(){if(window.Chart)for(const e of sS.getAll())e.unregister(window.Chart)}()}),t.onPatched(()=>{this.checkViewportSize()});const n=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(){const{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:fs("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(){const e=F*this.rowLayers.length,t=F*this.colLayers.length;return Ey({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`})}get rowLayers(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,"ROW")}get colLayers(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,"COL")}getGridSize(){const e=this.spreadsheetRef.el?.querySelector(".o-spreadsheet-topbar-wrapper")?.getBoundingClientRect().height||0,t=this.spreadsheetRef.el?.querySelector(".o-spreadsheet-bottombar-wrapper")?.getBoundingClientRect().height||0,s=this.spreadsheetRef.el?.querySelector(".o-grid")?.getBoundingClientRect().width||0,o=(this.spreadsheetRef.el?.getBoundingClientRect().height||0)-(this.spreadsheetRef.el?.querySelector(".o-column-groups")?.getBoundingClientRect().height||0)-e-t;return{width:Math.max(s-O,0),height:Math.max(o-O,0)}}}class VB extends ny{dataSets;labelRange;background;legendPosition;aggregated;dataSetsHaveTitle;dataSetDesign;axesDesign;type="combo";showValues;hideDataMarkers;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,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,this.zoomable=e.zoomable}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.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,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId),type:this.dataSetDesign?.[t]?.type??(t?"line":"bar")});return{type:"combo",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,zoomable:this.zoomable,humanize:this.humanize}}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,cC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:uI(this.background||c),fontColor:uI(nC(this.background)),dataSets:e,labelRange:t,verticalAxis:hC(s)}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new VB(i,this.sheetId,this.getters)}static getDefinitionFromContextCreation(e){const 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,zoomable:e.zoomable,humanize:e.humanize}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new VB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new VB(t,e,this.getters)}}class UB extends ny{dataSets;labelRange;background;legendPosition;aggregated;type="funnel";dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;showValues;funnelColors;cumulative;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,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,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}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,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new UB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new UB(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"funnel",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||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,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new UB(i,this.sheetId,this.getters)}}class HB extends ny{dataSets;labelRange;background;legendPosition;type="geo";dataSetsHaveTitle;dataSetDesign;colorScale;missingValueColor;region;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,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,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}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,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new HB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new HB(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"geo",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,colorScale:this.colorScale,missingValueColor:this.missingValueColor,region:this.region,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new HB(i,this.sheetId,this.getters)}}class zB extends ny{dataSets;labelRange;background;legendPosition;aggregated;type="pyramid";dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;stacked=!0;showValues;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,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,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}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,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new zB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new zB(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"pyramid",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,horizontal:!0,stacked:!0,showValues:this.showValues,humanize:this.humanize}}getDefinitionForExcel(e){const{dataSets:t,labelRange:s}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,cC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),o=this.getDefinition(),i=_I(o,this.dataSets,this.labelRange,e),{dataSetsValues:n}=i,r=Math.max(...n.map(e=>Math.max(...e.data.map(Math.abs))));return{...o,horizontal:!0,backgroundColor:uI(this.background||c),fontColor:uI(nC(this.background)),dataSets:t,labelRange:s,verticalAxis:hC(o),maxValue:r}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new zB(i,this.sheetId,this.getters)}}class BB extends ny{dataSets;labelRange;background;legendPosition;stacked;aggregated;type="radar";dataSetsHaveTitle;dataSetDesign;fillArea;showValues;hideDataMarkers;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,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,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}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,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new BB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new BB(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"radar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated,fillArea:this.fillArea,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,humanize:this.humanize}}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,cC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:uI(this.background||c),fontColor:uI(nC(this.background)),dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new BB(i,this.sheetId,this.getters)}}class GB extends ny{dataSets;labelRange;background;legendPosition;type="sunburst";dataSetsHaveTitle;showValues;showLabels;valuesDesign;groupColors;pieHolePercentage;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,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,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static getDefinitionFromContextCreation(e){const 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,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){const 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,s){return{type:"sunburst",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,s||this.sheetId)})),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,showValues:this.showValues,showLabels:this.showLabels,valuesDesign:this.valuesDesign,groupColors:this.groupColors,pieHolePercentage:this.pieHolePercentage,humanize:this.humanize}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new GB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new GB(t,e,this.getters)}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new GB(i,this.sheetId,this.getters)}}class WB extends ny{static defaults={background:c,legendPosition:"top",dataSetsHaveTitle:!1,showHeaders:!0,headersColor:"#000000"};dataSets;labelRange;background;legendPosition;type="treemap";dataSetsHaveTitle;showHeaders;headerDesign;showValues;showLabels;valuesDesign;coloringOptions;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,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,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static getDefinitionFromContextCreation(e){const 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,humanize:e.humanize}}getContextCreation(){const 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(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new WB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new WB(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,s||this.sheetId)}));return{type:"treemap",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||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,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new WB(i,this.sheetId,this.getters)}}$y.add("bar",{match:e=>"bar"===e,createChart:(e,t,s)=>new qw(e,t,s),getChartRuntime:Zw,validateChartDefinition:qw.validateChartDefinition,transformDefinition:qw.transformDefinition,getChartDefinitionFromContextCreation:qw.getDefinitionFromContextCreation,sequence:10}),$y.add("combo",{match:e=>"combo"===e,createChart:(e,t,s)=>new VB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=DI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:VC(s,o)},options:{...nI,layout:QI(0,o),scales:dw(s,o),plugins:{title:Dw(s,t),legend:nw(s),tooltip:Pw(s,o),chartShowValuesPlugin:Rw(s,o)}}},background:e.background||c}},validateChartDefinition:VB.validateChartDefinition,transformDefinition:VB.transformDefinition,getChartDefinitionFromContextCreation:VB.getDefinitionFromContextCreation,sequence:15}),$y.add("line",{match:e=>"line"===e,createChart:(e,t,s)=>new JO(e,t,s),getChartRuntime:QO,validateChartDefinition:JO.validateChartDefinition,transformDefinition:JO.transformDefinition,getChartDefinitionFromContextCreation:JO.getDefinitionFromContextCreation,sequence:20}),$y.add("pie",{match:e=>"pie"===e,createChart:(e,t,s)=>new eF(e,t,s),getChartRuntime:tF,validateChartDefinition:eF.validateChartDefinition,transformDefinition:eF.transformDefinition,getChartDefinitionFromContextCreation:eF.getDefinitionFromContextCreation,sequence:30}),$y.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,s)=>new gy(e,t,s),getChartRuntime:my,validateChartDefinition:gy.validateChartDefinition,transformDefinition:gy.transformDefinition,getChartDefinitionFromContextCreation:gy.getDefinitionFromContextCreation,sequence:40}),$y.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,s)=>new ZO(e,t,s),getChartRuntime:jO,validateChartDefinition:ZO.validateChartDefinition,transformDefinition:ZO.transformDefinition,getChartDefinitionFromContextCreation:ZO.getDefinitionFromContextCreation,sequence:50}),$y.add("scatter",{match:e=>"scatter"===e,createChart:(e,t,s)=>new uH(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=OI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"line",data:{labels:o.labels,datasets:LC(s,o)},options:{...nI,layout:QI(0,o),scales:gw(s,o),plugins:{title:Dw(s,t),legend:iw(s),tooltip:Mw(s,o),chartShowValuesPlugin:Rw(s,o)}}},background:e.background||c}},validateChartDefinition:uH.validateChartDefinition,transformDefinition:uH.transformDefinition,getChartDefinitionFromContextCreation:uH.getDefinitionFromContextCreation,sequence:60}),$y.add("waterfall",{match:e=>"waterfall"===e,createChart:(e,t,s)=>new sF(e,t,s),getChartRuntime:oF,validateChartDefinition:sF.validateChartDefinition,transformDefinition:sF.transformDefinition,getChartDefinitionFromContextCreation:sF.getDefinitionFromContextCreation,sequence:70}),$y.add("pyramid",{match:e=>"pyramid"===e,createChart:(e,t,s)=>new zB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=_I(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:PC(s,o)},options:{...nI,indexAxis:"y",layout:QI(0,o),scales:mw(s,o),plugins:{title:Dw(s,t),legend:tw(s),tooltip:kw(s,o),chartShowValuesPlugin:Tw(s,o)}}},background:e.background||c}},validateChartDefinition:zB.validateChartDefinition,transformDefinition:zB.transformDefinition,getChartDefinitionFromContextCreation:zB.getDefinitionFromContextCreation,sequence:80,dataSeriesLimit:2}),$y.add("radar",{match:e=>"radar"===e,createChart:(e,t,s)=>new BB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=PI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"radar",data:{labels:o.labels,datasets:UC(s,o)},options:{...nI,layout:QI(0,o),scales:fw(s,o),plugins:{title:Dw(s,t),legend:aw(s),tooltip:Vw(s,o),chartShowValuesPlugin:Rw(s,o)}}},background:e.background||c}},validateChartDefinition:BB.validateChartDefinition,transformDefinition:BB.transformDefinition,getChartDefinitionFromContextCreation:BB.getDefinitionFromContextCreation,sequence:80}),$y.add("geo",{match:e=>"geo"===e,createChart:(e,t,s)=>new HB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=MI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"choropleth",data:{datasets:HC(s,o)},options:{...nI,layout:QI(0,o),scales:vw(s,o),plugins:{title:Dw(s,t),tooltip:Uw(s,o),legend:{display:!1}}}},background:e.background||c}},validateChartDefinition:HB.validateChartDefinition,transformDefinition:HB.transformDefinition,getChartDefinitionFromContextCreation:HB.getDefinitionFromContextCreation,sequence:90,dataSeriesLimit:1}),$y.add("funnel",{match:e=>"funnel"===e,createChart:(e,t,s)=>new UB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=NI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"funnel",data:{labels:o.labels,datasets:zC(s,o)},options:{...nI,indexAxis:"y",layout:QI(0,o),scales:bw(0,o),plugins:{title:Dw(s,t),legend:{display:!1},tooltip:Hw(s,o),chartShowValuesPlugin:Rw(s,o)}}},background:e.background||c}},validateChartDefinition:UB.validateChartDefinition,transformDefinition:UB.transformDefinition,getChartDefinitionFromContextCreation:UB.getDefinitionFromContextCreation,sequence:100,dataSeriesLimit:1}),$y.add("sunburst",{match:e=>"sunburst"===e,createChart:(e,t,s)=>new GB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=LI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"doughnut",data:{datasets:GC(s,o)},options:{cutout:void 0===e.pieHolePercentage?"25%":`${e.pieHolePercentage}%`,...nI,layout:QI(0,o),plugins:{title:Dw(s,t),legend:lw(s),tooltip:zw(s,o),sunburstLabelsPlugin:xw(s,o),sunburstHoverPlugin:{enabled:!0}}}},background:e.background||c}},validateChartDefinition:GB.validateChartDefinition,transformDefinition:GB.transformDefinition,getChartDefinitionFromContextCreation:GB.getDefinitionFromContextCreation,sequence:30}),$y.add("treemap",{match:e=>"treemap"===e,createChart:(e,t,s)=>new WB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=LI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"treemap",data:{labels:o.labels,datasets:ZC(s,o)},options:{...nI,layout:QI(0,o),plugins:{title:Dw(s,t),legend:{display:!1},tooltip:Bw(s,o)}}},background:e.background||c}},validateChartDefinition:WB.validateChartDefinition,transformDefinition:WB.transformDefinition,getChartDefinitionFromContextCreation:WB.getDefinitionFromContextCreation,sequence:100}),f_.add("line",{matcher:e=>"line"===e.type&&!e.stacked&&!e.fillArea,displayName:fs("Line"),chartType:"line",chartSubtype:"line",subtypeDefinition:{stacked:!1,fillArea:!1},category:"line",preview:"o-spreadsheet-ChartPreview.LINE_CHART"}).add("stacked_line",{matcher:e=>"line"===e.type&&!e.fillArea&&!!e.stacked,displayName:fs("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=>"line"===e.type&&!e.stacked&&!!e.fillArea,displayName:fs("Area"),chartType:"line",chartSubtype:"area",subtypeDefinition:{stacked:!1,fillArea:!0},category:"area",preview:"o-spreadsheet-ChartPreview.AREA_CHART"}).add("stacked_area",{matcher:e=>"line"===e.type&&e.stacked&&!!e.fillArea,displayName:fs("Stacked Area"),chartType:"line",chartSubtype:"stacked_area",subtypeDefinition:{stacked:!0,fillArea:!0},category:"area",preview:"o-spreadsheet-ChartPreview.STACKED_AREA_CHART"}).add("scatter",{displayName:fs("Scatter"),chartType:"scatter",chartSubtype:"scatter",category:"misc",preview:"o-spreadsheet-ChartPreview.SCATTER_CHART"}).add("column",{matcher:e=>"bar"===e.type&&!e.stacked&&!e.horizontal,displayName:fs("Column"),chartType:"bar",chartSubtype:"column",subtypeDefinition:{stacked:!1,horizontal:!1},category:"column",preview:"o-spreadsheet-ChartPreview.COLUMN_CHART"}).add("stacked_column",{matcher:e=>"bar"===e.type&&e.stacked&&!e.horizontal,displayName:fs("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=>"bar"===e.type&&!e.stacked&&!!e.horizontal,displayName:fs("Bar"),chartType:"bar",chartSubtype:"bar",subtypeDefinition:{horizontal:!0,stacked:!1},category:"bar",preview:"o-spreadsheet-ChartPreview.BAR_CHART"}).add("stacked_bar",{matcher:e=>"bar"===e.type&&e.stacked&&!!e.horizontal,displayName:fs("Stacked Bar"),chartType:"bar",chartSubtype:"stacked_bar",subtypeDefinition:{horizontal:!0,stacked:!0},category:"bar",preview:"o-spreadsheet-ChartPreview.STACKED_BAR_CHART"}).add("combo",{displayName:fs("Combo"),chartSubtype:"combo",chartType:"combo",category:"line",preview:"o-spreadsheet-ChartPreview.COMBO_CHART"}).add("pie",{matcher:e=>"pie"===e.type&&!e.isDoughnut,displayName:fs("Pie"),chartSubtype:"pie",chartType:"pie",subtypeDefinition:{isDoughnut:!1},category:"pie",preview:"o-spreadsheet-ChartPreview.PIE_CHART"}).add("doughnut",{matcher:e=>"pie"===e.type&&!!e.isDoughnut,displayName:fs("Doughnut"),chartSubtype:"doughnut",chartType:"pie",subtypeDefinition:{isDoughnut:!0},category:"pie",preview:"o-spreadsheet-ChartPreview.DOUGHNUT_CHART"}).add("gauge",{displayName:fs("Gauge"),chartSubtype:"gauge",chartType:"gauge",category:"misc",preview:"o-spreadsheet-ChartPreview.GAUGE_CHART"}).add("scorecard",{displayName:fs("Scorecard"),chartSubtype:"scorecard",chartType:"scorecard",category:"misc",preview:"o-spreadsheet-ChartPreview.SCORECARD_CHART"}).add("waterfall",{displayName:fs("Waterfall"),chartSubtype:"waterfall",chartType:"waterfall",category:"misc",preview:"o-spreadsheet-ChartPreview.WATERFALL_CHART"}).add("pyramid",{displayName:fs("Population Pyramid"),chartSubtype:"pyramid",chartType:"pyramid",category:"misc",preview:"o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART"}).add("radar",{matcher:e=>"radar"===e.type&&!e.fillArea,displayName:fs("Radar"),chartSubtype:"radar",chartType:"radar",subtypeDefinition:{fillArea:!1},category:"misc",preview:"o-spreadsheet-ChartPreview.RADAR_CHART"}).add("filled_radar",{matcher:e=>"radar"===e.type&&!!e.fillArea,displayName:fs("Filled Radar"),chartType:"radar",chartSubtype:"filled_radar",subtypeDefinition:{fillArea:!0},category:"misc",preview:"o-spreadsheet-ChartPreview.FILLED_RADAR_CHART"}).add("geo",{displayName:fs("Geo Chart"),chartSubtype:"geo",chartType:"geo",category:"misc",preview:"o-spreadsheet-ChartPreview.GEO_CHART"}).add("funnel",{displayName:fs("Funnel"),chartSubtype:"funnel",chartType:"funnel",category:"misc",preview:"o-spreadsheet-ChartPreview.FUNNEL_CHART"}).add("sunburst",{matcher:e=>"sunburst"===e.type,displayName:fs("Sunburst"),chartSubtype:"sunburst",chartType:"sunburst",category:"hierarchical",preview:"o-spreadsheet-ChartPreview.SUNBURST_CHART"}).add("treemap",{matcher:e=>"treemap"===e.type,displayName:fs("Tree Map"),chartType:"treemap",chartSubtype:"treemap",category:"hierarchical",preview:"o-spreadsheet-ChartPreview.TREE_MAP_CHART"});class $B extends Nz{copy(e){}}T_.figureHandlers.add("chart",class extends $B{copy(e){const t=e.sheetId,s=this.getters.getFigure(t,e.figureId);if(!s)throw new Error(`No figure for the given id: ${e.figureId}`);if("chart"!==s.tag)return;const o={...s},i=this.getters.getChartFromFigureId(e.figureId);if(!i)throw new Error(`No chart for the given id: ${e.figureId}`);const n=i.copyInSheetId(t);return{figureId:e.figureId,copiedFigure:o,copiedChart:n}}getPasteTarget(e,t,s,o){return{zones:[],figureId:(new lr).smallUuid(),sheetId:e}}paste(e,t,s){if(!e.figureId)return;const{zones:o,figureId:i}=e,n=e.sheetId,{width:r,height:a}=t.copiedFigure,l=t.copiedChart.copyInSheetId(n),c=this.getters.getMaxAnchorOffset(n,a,r);let{left:h,top:d}=o[0];const u={x:0,y:0};h>c.col&&(h=c.col,u.x=c.offset.x),d>c.row&&(d=c.row,u.y=c.offset.y),this.dispatch("CREATE_CHART",{figureId:i,chartId:(new lr).smallUuid(),sheetId:n,definition:l.getDefinition(),col:h,row:d,offset:u,size:{height:a,width:r}}),s.isCutOperation&&this.dispatch("DELETE_FIGURE",{sheetId:t.copiedChart.sheetId,figureId:t.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{figureId:i})}isPasteAllowed(e,t,s,o){return 0===t.length?"EmptyTarget":void 0!==o?.pasteOption?"WrongFigurePasteOption":"Success"}}).add("image",class extends $B{copy(e){const t=e.sheetId,s=this.getters.getFigure(t,e.figureId);if(!s)throw new Error(`No figure for the given id: ${e.figureId}`);const o={...s};if("image"!==s.tag)return;const i=ae(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:o,copiedImage:i,sheetId:t}}getPasteTarget(e,t,s,o){return{sheetId:e,zones:[],figureId:(new lr).smallUuid()}}paste(e,t,s){if(!e.figureId)return;const{zones:o,figureId:i}=e,n=this.getters.getActiveSheetId(),{width:r,height:a}=t.copiedFigure,l=ae(t.copiedImage),c=this.getters.getMaxAnchorOffset(n,a,r);let{left:h,top:d}=o[0];const u={x:0,y:0};h>c.col&&(h=c.col,u.x=c.offset.x),d>c.row&&(d=c.row,u.y=c.offset.y),this.dispatch("CREATE_IMAGE",{figureId:i,sheetId:n,col:h,row:d,offset:u,size:{height:a,width:r},definition:l}),s.isCutOperation&&this.dispatch("DELETE_FIGURE",{sheetId:t.sheetId,figureId:t.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{figureId:i})}isPasteAllowed(e,t,s,o){return 0===t.length?"EmptyTarget":void 0!==o?.pasteOption?"WrongFigurePasteOption":"Success"}}).add("carousel",class extends $B{copy(e){const t=e.sheetId,s=this.getters.getFigure(t,e.figureId);if(!s)throw new Error(`No figure for the given id: ${e.figureId}`);if("carousel"!==s.tag)return;const o={...s},i=this.getters.getCarousel(e.figureId),n={};for(const e of i.items)if("chart"===e.type){const s=this.getters.getChart(e.chartId);if(!s)throw new Error(`No chart for the given id: ${e.chartId}`);n[e.chartId]=s.copyInSheetId(t)}return{figureId:e.figureId,copiedFigure:o,copiedCarousel:i,copiedCharts:n,copiedSheetId:t}}getPasteTarget(e){return{zones:[],figureId:(new lr).smallUuid(),sheetId:e}}paste(e,t,s){if(!e.figureId)return;const{zones:o,figureId:i}=e,n=e.sheetId,{width:r,height:a}=t.copiedFigure,l=this.getters.getMaxAnchorOffset(n,a,r);let{left:c,top:h}=o[0];const d={x:0,y:0};c>l.col&&(c=l.col,d.x=l.offset.x),h>l.row&&(h=l.row,d.y=l.offset.y),this.dispatch("CREATE_CAROUSEL",{figureId:i,sheetId:n,definition:{items:[]},col:c,row:h,offset:d,size:{height:a,width:r}});const u=new lr,g=ae(t.copiedCarousel.items);for(const e of g){if("chart"!==e.type)continue;const s=t.copiedCharts[e.chartId],o=u.smallUuid(),r=s.copyInSheetId(n).getDefinition();this.dispatch("CREATE_CHART",{figureId:i,chartId:o,sheetId:n,definition:r}),e.chartId=o}this.dispatch("UPDATE_CAROUSEL",{sheetId:n,figureId:i,definition:{...t.copiedCarousel,items:g}}),s.isCutOperation&&this.dispatch("DELETE_FIGURE",{sheetId:t.copiedSheetId,figureId:t.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{figureId:i})}isPasteAllowed(e,t,s,o){return 0===t.length?"EmptyTarget":void 0!==o?.pasteOption?"WrongFigurePasteOption":"Success"}}),T_.cellHandlers.add("dataValidation",class extends Lz{uuidGenerator=new lr;queuedChanges={};copy(e){const{rowsIndexes:t,columnsIndexes:s}=e,o=e.sheetId,i=[];for(const e of t){const t=[];for(const i of s){const s={sheetId:o,col:i,row:e},n=this.getters.getValidationRuleForCell(s);t.push({position:s,rule:n})}i.push(t)}return{dvRules:i}}paste(e,t,s){if(this.queuedChanges={},s.pasteOption)return;const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t):this.pasteFromCopy(i,o,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,s){const o=t[0];this.pasteZone(e,o.left,o.top,s.dvRules,{isCutOperation:!0})}pasteZone(e,t,s,o,i){for(const[n,r]of o.entries())for(const[o,a]of r.entries()){const r={col:t+o,row:s+n,sheetId:e};this.pasteDataValidation(a,r,i?.isCutOperation)}}pasteDataValidation(e,t,s){if(e){const o=Zt(t),i=Zt(e.position),n=e.rule;if(!n){const e=this.getters.getValidationRuleForCell(t);return void(e&&this.adaptDataValidationRule(t.sheetId,e,[],[o]))}const r=[];if(s&&r.push(i),e.position.sheetId===t.sheetId){const s=this.getDataValidationRuleToCopyTo(t.sheetId,n,!1);this.adaptDataValidationRule(e.position.sheetId,s,[o],r)}else{const s=this.getters.getValidationRuleForCell(e.position);s&&this.adaptDataValidationRule(e.position.sheetId,s,[],r);const i=this.getDataValidationRuleToCopyTo(t.sheetId,n);this.adaptDataValidationRule(t.sheetId,i,[o],[])}}}getDataValidationRuleToCopyTo(e,t,s=!0){let o=this.getters.getDataValidationRules(e).find(e=>Me(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking);const i=this.queuedChanges[e];return!o&&i&&(o=i.find(e=>Me(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),o||{...t,id:s?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,s,o){this.queuedChanges[e]||(this.queuedChanges[e]=[]);const i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...s),i.toRemove.push(...o)):this.queuedChanges[e].push({toAdd:s,toRemove:o,rule:t})}executeQueuedChanges(){for(const e in this.queuedChanges)for(const{toAdd:t,toRemove:s,rule:o}of this.queuedChanges[e]){const i=o.ranges.map(e=>e.zone),n=ft(i,s),r=ft([...n,...t],[]);0!==r.length?this.dispatch("ADD_DATA_VALIDATION_RULE",{rule:{id:o.id,criterion:o.criterion,isBlocking:o.isBlocking},ranges:r.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e}):this.dispatch("REMOVE_DATA_VALIDATION_RULE",{sheetId:e,id:o.id})}}}).add("cell",kz).add("sheet",class extends Lz{isPasteAllowed(e,t,s,o){if(!("cells"in s))return"Success";const{xSplit:i,ySplit:n}=this.getters.getPaneDivisions(e);return Jt(I_(t,s.cells),i,n)?"FrozenPaneOverlap":"Success"}}).add("merge",class extends Lz{copy(e){const t=this.getters.getActiveSheetId(),{rowsIndexes:s,columnsIndexes:o}=e,i=[];for(const e of s){const s=[];for(const i of o){const o={col:i,row:e,sheetId:t};s.push(this.getters.getMerge(o))}i.push(s)}return{merges:i,sheetId:t}}paste(e,t,s){if(s.isCutOperation){const e=t.merges.flat().filter(Te);this.dispatch("REMOVE_MERGE",{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,s)}pasteZone(e,t,s,o){for(const[i,n]of o.entries())for(const[o,r]of n.entries()){const n={col:t+o,row:s+i,sheetId:e};this.pasteMerge(r,n)}}pasteMerge(e,t){if(!e)return;if(this.getters.isInMerge(t))return;const{sheetId:s,col:o,row:i}=t;this.dispatch("ADD_MERGE",{sheetId:s,force:!0,target:[{left:o,top:i,right:o+e.right-e.left,bottom:i+e.bottom-e.top}]})}}).add("table",class extends Lz{copy(e,t,s="copyPaste"){const o=e.sheetId,{rowsIndexes:i,columnsIndexes:n,zones:r}=e,a=new Set,l=[];for(const e of i){const c=[];l.push(c);for(const l of n){const n={col:l,row:e,sheetId:o},h=this.getters.getTable(n);if(!h){c.push({});continue}const d=this.getters.getCoreTable(n),u=d?.range.zone;let g;if(!a.has(h.id)&&d&&u&&r.some(e=>Vt(u,e))){a.add(h.id);let{numberOfRows:e}=Ut(u);for(let s=u.top;s<=u.bottom;s++)t||i.includes(s)||e--;const s=d.range,o=this.getters.extendRange(d.range,"ROW",s.zone.top+e-1-s.zone.bottom);g={range:this.getters.getRangeData(o),config:d.config,type:d.type}}"shiftCells"!==s&&c.push({table:g,style:this.getTableStyleToCopy(n),isWholeTableCopied:a.has(h.id)})}}return{tableCells:l,sheetId:e.sheetId}}getTableStyleToCopy(e){const t=this.getters.getCellTableStyle(e),s=this.getters.getCellStyle(e),o=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Ve(s)},border:{...o,...Ve(i)}}}paste(e,t,s){const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t,s):this.pasteFromCopy(i,o,t.tableCells,s)}pasteFromCut(e,t,s,o){for(const e of s.tableCells)for(const t of e)t.table&&this.dispatch("REMOVE_TABLE",{sheetId:s.sheetId,target:[this.getters.getRangeFromRangeData(t.table.range).zone]});const i=t[0];this.pasteZone(e,i.left,i.top,s.tableCells,o)}pasteZone(e,t,s,o,i){for(let n=0;n<o.length;n++){const r=o[n];for(let o=0;o<r.length;o++){const a=r[o];if(!a)continue;const l={col:t+o,row:s+n,sheetId:e};this.pasteTableCell(e,a,l,i)}}if(1===o.length)for(let i=0;i<o[0].length;i++)this.dispatch("AUTOFILL_TABLE_COLUMN",{col:t+i,row:s,sheetId:e})}pasteTableCell(e,t,s,o){if(t.table&&!o?.pasteOption){const{range:o}=t.table,i=Ut(this.getters.getRangeFromRangeData(o).zone),n={left:s.col,top:s.row,right:s.col+i.numberOfCols-1,bottom:s.row+i.numberOfRows-1};this.dispatch("CREATE_TABLE",{sheetId:s.sheetId,ranges:[this.getters.getRangeDataFromZone(e,n)],config:t.table.config,tableType:t.table.type})}this.getters.getCoreTable(s)||"asValue"===o?.pasteOption||(o?.pasteOption||t.isWholeTableCopied)&&"onlyFormat"!==o?.pasteOption||(t.style?.style&&this.dispatch("UPDATE_CELL",{...s,style:t.style.style}),t.style?.border&&this.dispatch("SET_BORDER",{...s,border:t.style.border}))}}).add("conditionalFormat",class extends Lz{uuidGenerator=new lr;queuedChanges={};copy(e){if(!e.zones.length)return;const{rowsIndexes:t,columnsIndexes:s}=e,o=e.sheetId,i=[];for(const e of t){const t=[];for(const i of s){const s=Array.from(this.getters.getRulesByCell(o,i,e));t.push({position:{col:i,row:e,sheetId:o},rules:s})}i.push(t)}return{cfRules:i}}paste(e,t,s){if(this.queuedChanges={},"asValue"===s.pasteOption)return;const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t):this.pasteFromCopy(i,o,t.cfRules,s),this.executeQueuedChanges()}pasteFromCut(e,t,s){const o=t[0];this.pasteZone(e,o.left,o.top,s.cfRules,{isCutOperation:!0})}pasteZone(e,t,s,o,i){for(const[n,r]of o.entries())for(const[o,a]of r.entries()){const r={col:t+o,row:s+n,sheetId:e};this.pasteCf(a,r,i?.isCutOperation)}}pasteCf(e,t,s){if(e?.rules&&e.rules.length>0){const o=Zt(e.position),i=Zt(t);for(const n of e.rules){const r=[];if(s&&r.push(o),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,n,[i],r);else{this.adaptCFRules(e.position.sheetId,n,[],r);const s=this.getCFToCopyTo(t.sheetId,n);this.adaptCFRules(t.sheetId,s,[i],[])}}}}adaptCFRules(e,t,s,o){this.queuedChanges[e]||(this.queuedChanges[e]=[]);const i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...s),i.toRemove.push(...o)):this.queuedChanges[e].push({toAdd:s,toRemove:o,cf:t})}executeQueuedChanges(){for(const e in this.queuedChanges)for(const{toAdd:t,toRemove:s,cf:o}of this.queuedChanges[e]){const i=this.getters.getAdaptedCfRanges(e,o,t,s);i&&(0!==i.length?this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:o.id,rule:o.rule,stopIfTrue:o.stopIfTrue},ranges:i,sheetId:e}):this.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:o.id,sheetId:e}))}}getCFToCopyTo(e,t){let s=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&Me(e.rule,t.rule));const o=this.queuedChanges[e];return!s&&o&&(s=o.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&Me(e.cf.rule,t.rule))?.cf),s||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}}).add("references",class extends Lz{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,s){if(s.isCutOperation){const s=e.zones[0];this.dispatch("MOVE_RANGES",{target:t.zones,sheetId:t.sheetId,sheetName:this.getters.getSheetName(t.sheetId),targetSheetId:e.sheetId,col:s.left,row:s.top})}}}).add("border",class extends Lz{copy(e){const t=e.sheetId;if(0===e.zones.length)return;const s=[];let o=0;for(const i of EC(e.columnsIndexes)){let n=0;for(const r of EC(e.rowsIndexes)){const e={left:i[0],right:i[i.length-1],top:r[0],bottom:r[r.length-1]};s.push(...this.getters.getBorders(t,e).map(({zone:t,style:s})=>({zone:{left:t.left-e.left+o,right:t.right&&t.right-e.left+o,top:t.top-e.top+n,bottom:t.bottom&&t.bottom-e.top+n},style:s}))),n+=r.length}o+=i.length}return{borders:s,width:e.columnsIndexes.length,height:e.rowsIndexes.length}}paste(e,t,s){const o=e.sheetId;if("asValue"===s.pasteOption)return;const i=e.zones;if(s.isCutOperation){const{left:e,top:s}=i[0];this.pasteBorderZone(o,e,s,t.borders)}else for(const e of i)for(const s of y_(e,t.width,t.height))this.pasteBorderZone(o,s.left,s.top,t.borders)}pasteBorderZone(e,t,s,o){for(const i of o){const o={left:i.zone.left+t,right:i.zone.right&&i.zone.right+t||i.zone.left+t,top:i.zone.top+s,bottom:i.zone.bottom&&i.zone.bottom+s||i.zone.top+s};for(const[t,s]of this.getOptimalBorderCommands(i.style))s&&this.dispatch("SET_ZONE_BORDERS",{sheetId:e,target:[o],border:{position:t,...s}})}}getOptimalBorderCommands(e){const t=xC(e.horizontal,e.vertical),s=xC(e.left,e.right,e.top,e.bottom);return t&&s&&xC(e.horizontal,e.left)?[["all",e.top]]:t&&s?[["hv",e.horizontal],["external",e.top]]:s?[["h",e.horizontal],["v",e.vertical],["external",e.top]]:t?[["hv",e.horizontal],["top",e.top],["bottom",e.bottom],["left",e.left],["right",e.right]]:[["h",e.horizontal],["v",e.vertical],["top",e.top],["bottom",e.bottom],["left",e.left],["right",e.right]]}});const qB={},ZB={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:A,HEADER_WIDTH:D,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:_,SCROLLBAR_WIDTH:O},jB={autoCompleteProviders:$P,autofillModifiersRegistry:e_,autofillRulesRegistry:t_,cellMenuRegistry:vk,colMenuRegistry:DV,errorTypes:Ss,linkMenuRegistry:VM,functionRegistry:uf,featurePluginRegistry:F_,iconsOnCellRegistry:vD,statefulUIPluginRegistry:P_,coreViewsPluginRegistry:M_,corePluginRegistry:O_,rowMenuRegistry:NV,sidePanelRegistry:yz,figureRegistry:VF,chartSidePanelComponentRegistry:IH,chartComponentRegistry:wF,chartRegistry:$y,chartSubtypeRegistry:f_,topbarMenuRegistry:$z,topbarComponentRegistry:sB,clickableCellRegistry:Hz,otRegistry:aE,inverseCommandRegistry:GE,urlRegistry:Uf,cellPopoverRegistry:IP,numberFormatMenuRegistry:Bz,repeatLocalCommandTransformRegistry:g_,repeatCommandTransformRegistry:u_,clipboardHandlersRegistries:T_,pivotRegistry:XD,pivotTimeAdapterRegistry:Fg,pivotSidePanelRegistry:az,pivotNormalizationValueRegistry:cp,supportedPivotPositionalFormulaRegistry:Oz,pivotToFunctionValueRegistry:hp,migrationStepRegistry:LT,chartJsExtensionRegistry:sS},YB={arg:as,isEvaluationError:mo,toBoolean:To,toJsDate:Ao,toNumber:bo,toString:Eo,toNormalizedPivotValue:np,toFunctionPivotValue:ap,toXC:mt,toZone:wt,toUnboundedZone:It,toCartesian:pt,numberToLetters:it,lettersToNumber:nt,UuidGenerator:lr,formatValue:pn,createCurrencyFormat:Dn,ColorGenerator:Gv,computeTextWidth:zb,createEmptyWorkbookData:ZT,createEmptySheet:qT,createEmptyExcelSheet:jT,rgbaToHex:wv,colorToRGBA:Ev,positionToZone:Zt,isDefined:Te,isMatrix:Ds,lazy:Oe,genericRepeat:tB,createAction:jf,createActions:qf,transformRangeData:os,deepEquals:Me,overlap:Lt,union:Ft,isInside:kt,deepCopy:ae,expandZoneOnInsertion:At,reduceZoneOnDeletion:Ot,unquote:ce,getMaxObjectId:Kg,getFunctionsFromTokens:kf,getFirstPivotFunction:MD,getNumberOfPivotFunctions:ND,parseDimension:ep,isDateOrDatetimeField:tp,makeFieldProposal:Dz,insertTokenAfterArgSeparator:function(e,t){let s=e.end;const o=e.end;"ARG_SEPARATOR"!==e.type&&(s=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)},insertTokenAfterLeftParenthesis:function(e,t){let s=e.end;const o=e.end;"LEFT_PAREN"!==e.type&&(s=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)},mergeContiguousZones:es,getPivotHighlights:ZH,pivotTimeAdapter:Pg,UNDO_REDO_PIVOT_COMMANDS:JD,createPivotFormula:ip,areDomainArgsFieldsValid:op,splitReference:tr,sanitizeSheetName:de,getUniqueText:st,isNumber:lo,isDateTime:$s,createCustomFields:fp},XB={isMarkdownLink:Se,parseMarkdownLink:Ie,markdownLink:ye,openLink:Wf,urlRepresentation:Gf},KB={Checkbox:IM,Section:aM,RoundColorPicker:lM,ChartDataSeries:MU,ChartErrorSection:NU,ChartLabelRange:LU,ChartTitle:HU,ChartPanel:xH,ChartFigure:LF,ChartJsComponent:iy,ClickableCellSortIcon:Fz,ZoomableChartJsComponent:mF,Grid:Az,GridOverlay:rU,ScorecardChart:Cy,GaugeChartComponent:yF,LineConfigPanel:aH,BarConfigPanel:VU,PieChartDesignPanel:hH,GenericChartConfigPanel:kU,ChartWithAxisDesignPanel:YU,GenericZoomableChartDesignPanel:KU,LineChartDesignPanel:lH,GaugeChartConfigPanel:eH,GaugeChartDesignPanel:tH,ScorecardChartConfigPanel:gH,ScorecardChartDesignPanel:pH,GeoChartDesignPanel:nH,RadarChartDesignPanel:dH,WaterfallChartDesignPanel:yH,ComboChartDesignPanel:JU,FunnelChartDesignPanel:QU,SunburstChartDesignPanel:mH,TreeMapChartDesignPanel:CH,ChartTypePicker:EH,FigureComponent:UF,MenuPopover:PF,Popover:DF,SelectionInput:fM,ValidationMessages:JV,AddDimensionButton:KH,PivotDimensionGranularity:QH,PivotDimensionOrder:ez,PivotDimension:JH,PivotLayoutConfigurator:oz,PivotHTMLRenderer:Mz,PivotDeferUpdate:jH,PivotTitleSection:iz,CogWheelMenu:FU,TextInput:TU,SidePanelCollapsible:DP,RadioSelection:BU,GeoChartRegionSelectSection:sH,ChartDashboardMenu:MF,FullScreenFigure:Pz},JB={useDragAndDropListItems:cM,useHighlights:DH,useHighlightsOnHover:AH},QB={useStoreProvider:Qf,DependencyContainer:Xf,CellPopoverStore:wP,ComposerFocusStore:uv,CellComposerStore:WV,FindAndReplaceStore:zH,HighlightStore:ZP,DelayedHoveredCellStore:HF,HoveredTableStore:oU,ModelStore:nv,NotificationStore:jP,RendererStore:cv,SelectionInputStore:mM,SpreadsheetStore:hv,useStore:ev,useLocalStore:tv,SidePanelStore:Rz,PivotSidePanelStore:nz,PivotMeasureDisplayPanelStore:$H,ClientFocusStore:kV,GridRenderer:pU};const eG={DEFAULT_LOCALE:Oc,HIGHLIGHT_COLOR:o,PIVOT_TABLE_CONFIG:J,ChartTerms:Ig,FIGURE_ID_SPLITTER:z,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2},tG={...iF,...$w};e.AbstractCellClipboardHandler=Lz,e.AbstractChart=ny,e.AbstractFigureClipboardHandler=$B,e.CellErrorType=bs,e.ClientDisconnectedError=zE,e.CorePlugin=XT,e.CoreViewPlugin=MA,e.DEFAULT_LOCALE=Oc,e.DEFAULT_LOCALES=_c,e.DispatchResult=br,e.EvaluationError=Cs,e.LocalTransportService=nE,e.Model=class extends Yf{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},s=[],o=new lr,i=!1){const n=performance.now();console.debug("##### Model creation #####"),super(),gs===ds&&ps===us&&(ps=()=>!0),s=WT(e,s);const r=zT(e,i);this.state=new V_,this.uuidGenerator=o,this.config=this.setupConfig(t),this.session=this.setupSession(r.revisionId),this.coreGetters={},this.range=new N_(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.adaptFormulaStringDependencies=this.range.adaptFormulaStringDependencies.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.getters={isReadonly:()=>"readonly"===this.config.mode||"dashboard"===this.config.mode,isDashboard:()=>"dashboard"===this.config.mode},this.selection=new k_(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(const e of O_.getAll())this.setupCorePlugin(e,r);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(s);for(const e of M_.getAll()){const t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(const e of P_.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(const e of F_.getAll()){const 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(),t.snapshotRequested||e["[Content_Types].xml"]&&!this.getters.isReadonly()){const e=performance.now();console.debug("Snapshot requested"),this.session.snapshot(this.exportData()),this.garbageCollectExternalResources(),console.debug("Snapshot taken in",performance.now()-e,"ms")}console.debug("Model created in",performance.now()-n,"ms"),console.debug("######")}joinSession(){this.session.join(this.config.client)}async leaveSession(){const e=this.getters.isReadonly()?void 0:Oe(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){const t=new e(this.uiPluginConfig);for(const s of e.getters){if(!(s in t))throw new Error(`Invalid getter name: ${s} for plugin ${t.constructor}`);if(s in this.getters)throw new Error(`Getter "${s}" is already defined.`);this.getters[s]=t[s].bind(t)}for(const s of e.layers)this.renderers[s]||(this.renderers[s]=[]),this.renderers[s].push(t);return t}setupCoreViewPlugin(e){const t=new e(this.coreViewPluginConfig);for(const s of e.getters){if(!(s in t))throw new Error(`Invalid getter name: ${s} for plugin ${t.constructor}`);if(s in this.getters)throw new Error(`Getter "${s}" is already defined.`);this.getters[s]=t[s].bind(t)}return t}setupCorePlugin(e,t){const s=new e(this.corePluginConfig);for(const t of e.getters){if(!(t in s))throw new Error(`Invalid getter name: ${t} for plugin ${s.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=s[t].bind(s)}s.import(t),this.corePlugins.push(s),this.coreHandlers.push(s),this.handlers.push(s)}onRemoteRevisionReceived({commands:e}){for(const t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new BE(JE({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{this.checkDispatchAllowed(e).isSuccessful?(this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1):this.dispatchToHandlers(this.coreHandlers,{type:"UNDO",commands:[e]})}}),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){const t=e.client||{id:this.uuidGenerator.smallUuid(),name:fs("Anonymous").toString()},s=e.transportService||new nE,o="readonly"===e.mode||"dashboard"===e.mode;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:o?new rE(s):s,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){const t=e.loadLocales||(()=>Promise.resolve(_c));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,custom:this.config.custom,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){const t=vr(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>"Success"!==e)?new br(t.flat()):br.Success}checkDispatchAllowedCoreCommand(e){const 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(const e of this.handlers)e.finalize();this.status=0,this.trigger("command-finalized")}canDispatch=(e,t)=>this.checkDispatchAllowed(BO(e,t));dispatch=(e,t)=>{const s=BO(e,t),o=this.status;if(this.getters.isReadonly()&&(i=s,!mr.has(i.type)))return new br("Readonly");var i;if(!this.session.canApplyOptimisticUpdate())return new br("WaitingSessionConfirmation");switch(o){case 0:const t=this.checkDispatchAllowed(s);if(!t.isSuccessful)return this.trigger("update"),t;this.status=1;const{changes:o,commands:i}=this.state.recordChanges(()=>{const t=performance.now();vr(s)&&this.state.addCommand(s),this.dispatchToHandlers(this.handlers,s),this.finalize();const o=performance.now()-t;o>5&&console.debug(e,o,"ms")});this.session.save(s,i,o),this.status=0,this.trigger("update");break;case 1:if(vr(s)){const e=this.checkDispatchAllowed(s);if(!e.isSuccessful)return e;this.state.addCommand(s)}this.dispatchToHandlers(this.handlers,s);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(vr(s))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,s)}return br.Success};dispatchFromCorePlugin=(e,t)=>{const s=BO(e,t),o=this.status;this.status=2;const i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,s),this.status=o,br.Success};dispatchToHandlers(e,t){const s=vr(t);for(const o of e)!s&&o instanceof XT||o.beforeHandle(t);for(const o of e)!s&&o instanceof XT||o.handle(t);this.trigger("command-dispatched",t)}drawLayer(e,t){const s=this.renderers[t];if(s)for(const o of s)e.ctx.save(),o.drawLayer(e,t),e.ctx.restore()}exportData(){let e=ZT();for(const t of this.handlers)t instanceof XT&&t.export(e);return e.revisionId=this.session.getRevisionId()||H,e=ae(e),e}updateMode(e){this.config.mode=e,this.trigger("update")}async exportXLSX(){this.dispatch("EVALUATE_CELLS");let e={...ZT(),sheets:[jT(HT,"Sheet1")]};for(const t of this.handlers)t instanceof yr&&await t.exportForExcel(e);return e=ae(e),UO(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.PivotRuntimeDefinition=VD,e.Registry=Og,e.Revision=HE,e.SPREADSHEET_DIMENSIONS=ZB,e.Spreadsheet=kB,e.SpreadsheetPivotTable=yA,e.UIPlugin=Ir,e.__info__=qB,e.addFunction=function e(t,s){return uf.add(t,s),{addFunction:(t,s)=>e(t,s)}},e.addRenderingLayer=function(e,t){if(av[e])throw new Error(`Layer ${e} already exists`);av[e]=t},e.astToFormula=_D,e.categories=gf,e.chartHelpers=tG,e.compile=sE,e.compileTokens=oE,e.components=KB,e.constants=eG,e.convertAstNodes=Of,e.coreTypes=fr,e.createAutocompleteArgumentsProvider=Vz,e.findCellInNewZone=qt,e.functionCache=tE,e.getCaretDownSvg=oR,e.getCaretUpSvg=iR,e.helpers=YB,e.hooks=JB,e.invalidateCFEvaluationCommands=ur,e.invalidateChartEvaluationCommands=hr,e.invalidateDependenciesCommands=dr,e.invalidateEvaluationCommands=cr,e.iterateAstNodes=Ff,e.links=XB,e.load=zT,e.parse=Df,e.parseTokens=_f,e.readonlyAllowedCommands=mr,e.registries=jB,e.setDefaultSheetViewSize=function(e){j=e},e.setTranslationMethod=function(e,t=()=>!0){gs=e,ps=t},e.stores=QB,e.tokenColors=ie,e.tokenize=Mc,qB.version="19.1.0-alpha.6",qB.date="2025-10-16T14:35:52.911Z",qB.hash="8ab685e"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|