@odoo/o-spreadsheet 19.1.0-alpha.1 → 19.1.0-alpha.11
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 +6675 -0
- package/dist/{o-spreadsheet.cjs.js → o-spreadsheet-engine.esm.js} +40889 -78600
- package/dist/{o-spreadsheet.iife.js → o-spreadsheet-engine.iife.js} +40669 -78268
- package/dist/o-spreadsheet-engine.min.iife.js +817 -0
- package/dist/o-spreadsheet.d.ts +6749 -6498
- package/dist/{o-spreadsheet.esm.js → o_spreadsheet.esm.js} +73992 -73943
- package/dist/o_spreadsheet.iife.js +88580 -0
- package/dist/o_spreadsheet.min.iife.js +843 -0
- package/dist/o_spreadsheet.xml +364 -131
- package/package.json +53 -24
- package/readme.md +1 -0
- package/dist/o-spreadsheet.iife.min.js +0 -3374
|
@@ -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=21,F=[50,75,100,125,150,200],P=10,M="bottom",N="overflow",L=P,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,i=!1;const n=function(){const n=this,r=Array.from(arguments);if(!i&&s)return i=!0,e.apply(n,r);clearTimeout(o),o=setTimeout(function(){o=void 0,i=!1,e.apply(n,r)},t)};return n.isDebouncePending=()=>void 0!==o,n.stopDebounce=()=>{clearTimeout(o)},n}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),yt(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=It(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=It(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=wt(e,i,0,!1);(a%2==0&&!s||a%2!=0&&s)&&n.push(i);const l=a-r-1,c=n.length,h=r+1;h===e.length-1&&1===l&&1===c?e[h]=n[0]??n[1]:e.splice(h,l,...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){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};(void 0===s&&0!==t||void 0===a&&0!==n)&&(i.hasHeader=!0);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}function It(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 wt(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}function Et(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=$t(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 Rt(e){const t=Et(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function xt(e){try{return function(e){return Tt(Et(e))}(e)}catch(e){return!1}}function Tt(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))&&(At(e)&&e.top>=0&&e.left>=0)}function At(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 Dt(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 _t(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?qt(e,n,"RESIZE",i):r<e[t]?qt(e,n,"MOVE",i):{...e}}function Ot(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?qt(e,n,"RESIZE",i):r<e[t]?qt(e,n,"MOVE",i):{...e}}function Ft(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 Pt(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 Mt(...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 Nt(e,t){if(Vt(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 Lt(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom&&e.hasHeader===t.hasHeader}function kt(e,t){if(Nt(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 Vt(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 Ut(e,t,s){const{left:o,right:i,top:n,bottom:r}=s;return e>=o&&(void 0===i||e<=i)&&t>=n&&(void 0===r||t<=r)}function Ht(e,t){return Lt(Mt(t,e),t)}function zt(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function Bt(e){const{numberOfCols:t,numberOfRows:s}=zt(e);return 1===t||1===s}function Gt(e){const t=[],{left:s,right:o,top:i,bottom:n}=$t(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 Wt(e,t){const s=[],{left:o,right:i,top:n,bottom:r}=$t(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 $t(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 qt(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=Kt(e)&&!r?"rows"!==t:!(Xt(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 Zt(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 jt(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function Yt(e){return{...e,right:e.left,bottom:e.top}}function Xt(e){return void 0===e.right}function Kt(e){return void 0===e.bottom}function Jt(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function Qt(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 es(e){return e.length<2||1===ft(e).length}function ts(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))||Vt(t,o));var i,n});if(-1!==i){t[e]=Mt(t[i],o),t.splice(i,1),s=!0;break}}}return t}function ss(e,t){const s=kt(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 os(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?Pt(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?_t(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):e}function is(e,t){const s="DELETE_SHEET"===t.type&&t.sheetId;if("sheetId"in t&&e._sheetId!==t.sheetId)return e;{const o=os(e._zone,t);if(o&&s!==e._sheetId)return{...e,_zone:o}}}let ns=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 rs=/(.*?)\((.*?)\)(.*)/,as=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META","RANGE<META>"];function ls(e,t="",s){return function(e,t,s){const o=e.match(rs),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=as.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 cs={};function hs(e,t){const s=e.name,o=cs[s]?.[t];return o||(cs[s]||(cs[s]={}),cs[s][t]||(cs[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||i.repeating){if(i.repeating){const n=i.optional?0:1;for(let i=0;i<o+n;i++)for(let o=0;o<e.nbrArgRepeating;o++)s[r]={index:t+o,repeatingGroupIndex:i},r++;t+=e.nbrArgRepeating-1;continue}s[r]={index:t},r++}else a<n&&(s[r]={index:t},r++),a++}return e=>s[e]}(e,t)),cs[s][t])}const ds=["META","RANGE<META>"];const us=e=>e,gs=()=>!1;let ps=us,ms=gs;function fs(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 vs=function(e,...t){return ms()?fs(ps(e),...t):new bs(e,t)};let bs=class extends String{values;constructor(e,t){super(e),this.values=t}valueOf(){const e=super.valueOf();return ms()?fs(ps(e),...this.values):fs(e,...this.values)}toString(){return this.valueOf()}};const Ss={NotAvailable:"#N/A",InvalidReference:"#REF",BadExpression:"#BAD_EXPR",CircularDependency:"#CYCLE",UnknownFunction:"#NAME?",DivisionByZero:"#DIV/0!",SpilledBlocked:"#SPILL!",GenericError:"#ERROR",NullError:"#NULL!"},Cs=new Set(Object.values(Ss));class ys{message;value;constructor(e=vs("Error"),t=Ss.GenericError){this.message=e,this.value=t,this.message=e.toString()}}class Is extends ys{constructor(e=vs("Invalid expression")){super(e,Ss.BadExpression)}}class ws extends ys{constructor(e=vs("Circular reference")){super(e,Ss.CircularDependency)}}class Es extends ys{constructor(e=vs("Invalid reference")){super(e,Ss.InvalidReference)}}class Rs extends ys{constructor(e=vs("Data not available")){super(e,Ss.NotAvailable)}}class xs extends ys{constructor(e=vs("Unknown function")){super(e,Ss.UnknownFunction)}}class Ts extends ys{constructor(e=vs("Spill range is not empty")){super(e,Ss.SpilledBlocked)}}class As extends ys{constructor(e=vs("Division by zero")){super(e,Ss.DivisionByZero)}}const Ds=["thin","medium","thick","dashed","dotted"];function _s(e){return Array.isArray(e)&&Array.isArray(e[0])}var Os;!function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(Os||(Os={}));let Fs=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 Ps=new Fs(1899,11,30),Ms=864e5,Ns=2e3,Ls=Fs.now().getFullYear(),ks=Fs.now().getMonth(),Vs=Fs.fromTimestamp(0).getTime()-Ps.getTime(),Us=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,Hs=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,zs=Be.join(""),Bs=new RegExp(`/|-|${Be.join("|")}`),Gs=new RegExp(`^(\\d{1,4})[/${zs}-](\\d{1,4})([/${zs}-](\\d{1,4}))?$`),Ws=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function $s(e,t){switch(typeof e){case"number":return e;case"string":return qs(e,t)?js(e,t)?.value:!e||isNaN(Number(e))?void 0:Number(e);default:return}}function qs(e,t){return null!==js(e,t)}const Zs=new Map;function js(e,t){return Zs.has(t)||Zs.set(t,new Map),Zs.get(t).has(e)||Zs.get(t).set(e,function(e,t){e=e.trim();let s=null;const o=e.match(Ws);if(o){if(s=function(e){if(e=e.trim(),Ws.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 Fs(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(Gs);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(Bs)[0];if(i=function(e,t){const{year:s,month:o,day:i}=e,n=function(e){if(!e)return ks;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 Ls;const t=Number(e);switch(e.length){case 1:return Ns+t;case 2:return Ns+(Ns+t>Ls+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 Fs(a,n,r);if(h.getMonth()!==n||h.getDate()!==r)return null;const d=h.getTime()-Ps.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/Ms),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 Fs(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)),Zs.get(t).get(e)}function Ys(e){const t=Math.trunc(e),s=Fs.fromTimestamp(t*Ms-Vs);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 Xs(e){return Math.round(Ks(e))}function Ks(e){return(e.getTime()-Ps.getTime())/Ms}function Js(e){return new Fs(e.getFullYear(),e.getMonth()+1,0).getDate()}function Qs(e){return Js(e)===e.getDate()}function eo(e,t,s){const o=e.getFullYear(),i=e.getMonth(),n=e.getDate(),r=new Fs(o,i+t,1);return s&&n===Js(e)||n>Js(r)?r.setDate(Js(r)):r.setDate(n),r}function to(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function so(e,t,s){if(e===t)return 0;if(e>t){const s=t;t=e,e=s}const o=Ys(e),i=Ys(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===(to(c)?29:28)&&(n=30,1===l&&r===(to(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+=to(s)?366:365;s=t/e}else o?to(c)&&(s=366):(to(c)&&a<2&&(s=366),to(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 oo(e,t){const s=12*(t.getFullYear()-e.getFullYear())+t.getMonth()-e.getMonth();return e.getDate()>t.getDate()?s-1:s}function io(e,t){const s=e.getTime(),o=t.getTime();return Math.floor((o-s)/Ms)}function no(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 ro(e,t,s){return t>s?ro(e,s,t):(e=Math.trunc(e),t=Math.trunc(t),s=Math.trunc(s),e>=t&&e<=s)}const ao=$e(function(e){return e=re(e),new RegExp(`(?:^-?\\d+(?:${e}?\\d*(?:e(\\+|-)?\\d+)?)?|^-?${e}\\d+)(?!\\w|!)`)}),lo=$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 co(e,t){return!!e&&lo(t).test(e.trim())}const ho=$e(function(e){return new RegExp(`[$€${re(e.thousandsSeparator||"")}]`,"g")});function uo(e,t){e=e.replace(ho(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 go(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 po=["number","string","boolean","undefined"];function mo(e){if(void 0!==e)return _s(e)?e[0][0]?.format:e.format}function fo(e){return"string"==typeof e&&Cs.has(e)}function vo(e){return{value:Ss.NotAvailable,message:vs("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",Ro(e))}}const bo=e=>vs("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function So(e,t){const s=_o(e);switch(typeof s){case"number":return s;case"boolean":return s?1:0;case"string":if(co(s,t)||""===s)return uo(s,t);const e=js(s,t);if(e)return e.value;throw new ys(bo(s));default:return 0}}function Co(e,t){try{return So(e,t)}catch(e){return}}function yo(e,t){return Ko(e).map(e=>e.map(e=>{if("number"!=typeof e.value){let s="";throw"object"==typeof e?s=vs("Function [[FUNCTION_NAME]] expects number values for %s, but got an empty value.",t):"string"==typeof e?s=vs("Function [[FUNCTION_NAME]] expects number values for %s, but got a string.",t):"boolean"==typeof e&&(s=vs("Function [[FUNCTION_NAME]] expects number values for %s, but got a boolean.",t)),new ys(s)}return e.value}))}function Io(e,t){const s=_o(e);if(""===s)throw new ys(bo(s));return So(s,t)}function wo(e,t){return Math.trunc(So(e,t))}function Eo(e,t){return Math.trunc(Io(e,t))}function Ro(e){const t=_o(e);switch(typeof t){case"string":return t;case"number":return t.toString();case"boolean":return t?"TRUE":"FALSE";default:return""}}const xo=$e(function(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"")}),To=e=>vs("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a boolean.",e);function Ao(e){const t=_o(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 ys(To(t))}return!1;case"number":return!!t;default:return!1}}function Do(e,t){return Ys(So(_o(e),t))}function _o(e){if("object"==typeof e&&null!==e&&"value"in e){if(fo(e.value))throw e;return e.value}if(fo(e))throw new ys("",e);return e}function Oo(e,t,s){for(const o of e)if(_s(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 Fo(e,t){Oo(e,e=>{if(fo(e.value))throw e;t(e)},e=>{if(fo(e?.value))throw e;t(e)})}function Po(e,t,s){Oo(e,e=>{if("number"==typeof e?.value&&t(e),fo(e?.value))throw e},e=>{t({value:Io(e,s),format:e?.format})})}function Mo(e,t,s,o,i="rowFirst"){let n=o;for(const o of e)if(_s(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 No(e,t,s,o="rowFirst"){return Mo(e,t,t,s,o)}function Lo(e,t,s,o){return Mo(e,(e,s)=>{const o=s?.value;if("number"==typeof o)return t(e,o);if(fo(o))throw s;return e},(e,s)=>t(e,Io(s,o)),s)}function ko(e,t,s,o){return Mo(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,So(i,o));if(fo(i))throw s;return t(e,0)}return e},(e,s)=>t(e,So(s,o)),s)}function Vo(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 Uo(e,t){return 0===e.length?[]:Vo(e.length,e[0].length,(s,o)=>t(e[s][o]))}function Ho(e){return e.length?Vo(e[0].length,e.length,(t,s)=>e[s][t]):[]}function zo(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(_s(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 Vo(i,n,(s,i)=>{if(s>r-1||i>a-1)return new Rs(vs("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 _s(n)?n[0][0]:n})}function Bo(e,t){return function(e,t,s){for(const o of e)if(_s(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(fo(s))throw e;return!0},e=>void 0===e||null===e.value||t(function(e){const t=_o(e);if(""===t)throw new ys(To(t));return Ao(t)}(e)))}function Go(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)),co(o,t)||qs(o,t)?o=So(o,t):"TRUE"!==o&&"FALSE"!==o||(o=Ao(o)),{operator:s,operand:o}}const Wo=$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 $o(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&&(co(e,s)||qs(e,s))?So(e,s)===i:e===i;if("<>"===o||"="===o){let t;return t=typeof e==typeof i&&("string"==typeof e&&"string"==typeof i?Wo(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 qo(e,t,s,o=!1){const i=e.length;if(i%2==1)throw new ys(vs("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const n=Ko(e[0]),r=n.length,a=n[0].length,l=[];for(let t=0;t<i-1;t+=2){const i=Ko(e[t]);if(i.length!==r||i[0].length!==a)throw new ys(vs("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const n=Go(Ro(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=$o(Ko(e[t])[o][n].value??void 0,l[t/2],s),!r)break}r&&t(o,n)}}function Zo(e,t,s,o,i,n){if(void 0===t||null===t.value)return-1;if(fo(t.value))throw t;const r=Yo(t.value),a=typeof r;let l,c,h,d,u,g,p=0,m=i-1;const f="desc"===o?t=>Yo(n(e,i-t-1)):t=>Yo(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 jo(e,t,s,o,i,n,r=!1){if(void 0===t||null===t.value)return-1;if(fo(t.value))throw t;const a=Yo(t.value),l=r?(e,t)=>Yo(i(e,o-t-1)):(e,t)=>Yo(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=Wo(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&&Xo(t,o)>=0||Xo(t,o)>=0&&Xo(o,r)>0)&&(r=o,a=s),o===t});"nextGreater"===s&&(n=s=>{const o=i(e,s);return(!r&&Xo(t,o)<=0||Xo(t,o)<=0&&Xo(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 Yo(e){return"string"==typeof e?xo(e):e}function Xo(e,t){let s=po.indexOf(typeof e)-po.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 Ko(e){return void 0===e?[[]]:_s(e)?e:[[e]]}function Jo(e,t){return No(e,(e,s)=>(e.push(t(s)),e),[],"rowFirst")}function Qo(e){if(void 0===e)return!1;const{value:t}=e;return null!==t&&""!==t}const ei=vs("[[FUNCTION_NAME]] has no valid input data.");function ti(e){return vs("[[FUNCTION_NAME]] expects the provided values of %(argName)s to be a non-empty matrix.",{argName:e})}function si(e){function t(...t){for(let s=0;s<t.length;s++){const o=t[s],i=hs(e,t.length);if(!e.args[i(s).index??s].acceptErrors&&!_s(o)&&fo(o?.value))return o}try{return s.apply(this,t)}catch(t){return oi(t,e.name)}}function s(...t){this.debug;const s=e.compute.apply(this,t);return _s(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=>ii(t,e.name)),s):Uo(s,e=>({value:e})):"object"==typeof s&&null!==s&&"value"in s?(ii(s,e.name),s):{value:s}}return function(...s){const o=[],i=hs(e,s.length);for(let t=0;t<s.length;t++){const n=i(t).index??-1,r=e.args[n];if(!_s(s[t])&&r.acceptMatrixOnly)throw new Is(vs("Function %s expects the parameter '%s' to be reference to a cell or range.",e.name,(t+1).toString()));o.push(!r.acceptMatrix)}return zo(t.bind(this),s,o)}}function oi(e,t){return s=e,void 0!==s?.value&&"string"==typeof s.value&&fo(e.value)?(ri(e)&&ii(e,t),e):(console.error(e),new ys(ni+(ri(e)?" "+e.message:"")));var s}function ii(e,t){e.message?.includes("[[FUNCTION_NAME]]")&&(e.message=e.message.replace("[[FUNCTION_NAME]]",t))}const ni=vs("An unexpected error occurred. Submit a support ticket at odoo.com/help.");function ri(e){return void 0!==e?.message&&"string"==typeof e.message}function ai(e,t){if(!e)throw new ys(t)}function li(e,t=vs("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")){if(0===e)throw new As(t)}function ci(e){return 1===e.length||1===e[0].length}function hi(...e){if(e.every(_s)){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 di(e){return e.length===e[0].length}const ui=e=>vs("The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.",e);function gi(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 pi(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=gi(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]){mi(i,e,n),mi(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 mi(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 fi(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 vi(e){if(!_s(e))return e;if(!bi(e))throw new Error("The value should be a scalar or a 1x1 matrix");return e[0][0]}function bi(e){return 1===e.length&&1===e[0].length}function Si(e){return _s(e)&&!bi(e)}const Ci={description:vs("Returns a result array constrained to a specific width and height."),args:[ls("input_range (any, range<any>)",vs("The range to constrain.")),ls("rows (number)",vs("The number of rows in the constrained array.")),ls("columns (number)",vs("The number of columns in the constrained array."))],compute:function(e,t,s){const o=Ko(e),i=wo(t?.value,this.locale),n=wo(s?.value,this.locale);if(i<=0)return new ys(vs("The rows argument (%s) must be strictly positive.",i.toString()));if(n<=0)return new ys(vs("The columns argument (%s) must be strictly positive.",n.toString()));const r=Math.min(i,o[0].length);return Vo(Math.min(n,o.length),r,(e,t)=>o[e][t])},isExported:!1},yi={description:vs("Creates a new array from the selected columns in the existing range."),args:[ls("array (any, range<any>)",vs("The array that contains the columns to be returned.")),ls("col_num (number, range<number>, repeating)",vs("The column index of the column to be returned."))],compute:function(e,...t){const s=Ko(e),o=Jo(t,e=>wo(e?.value,this.locale)),i=o.filter(e=>0===e||s.length<Math.abs(e));if(0!==i.length)return new ys(vs("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},Ii={description:vs("Creates a new array from the selected rows in the existing range."),args:[ls("array (any, range<any>)",vs("The array that contains the rows to be returned.")),ls("row_num (number, range<number>, repeating)",vs("The row index of the row to be returned."))],compute:function(e,...t){const s=Ko(e),o=Jo(t,e=>wo(e?.value,this.locale)),i=s.length,n=o.filter(e=>0===e||s[0].length<Math.abs(e));return 0!==n.length?new ys(vs("The rows arguments must be between -%s and %s (got %s), excluding 0.",s[0].length.toString(),s[0].length.toString(),n.join(","))):Vo(i,o.length,(e,t)=>o[t]>0?s[e][o[t]-1]:s[e][s[e].length+o[t]])},isExported:!0},wi={description:vs("Expands or pads an array to specified row and column dimensions."),args:[ls("array (any, range<any>)",vs("The array to expand.")),ls("rows (number)",vs("The number of rows in the expanded array. If missing, rows will not be expanded.")),ls("columns (number, optional)",vs("The number of columns in the expanded array. If missing, columns will not be expanded.")),ls("pad_with (any, default=0)",vs("The value with which to pad."))],compute:function(e,t,s,o={value:0}){const i=Ko(e),n=wo(t?.value,this.locale),r=void 0!==s?wo(s.value,this.locale):i.length;return n<i[0].length?new ys(vs("The rows arguments (%s) must be greater or equal than the number of rows of the array.",n.toString())):r<i.length?new ys(vs("The columns arguments (%s) must be greater or equal than the number of columns of the array.",r.toString())):Vo(r,n,(e,t)=>e>=i.length||t>=i[e].length?o:i[e][t])},isExported:!0},Ei={description:vs("Flattens all the values from one or more ranges into a single column."),args:[ls("range (any, range<any>, repeating)",vs("The range to flatten."))],compute:function(...e){return[Jo(e,e=>void 0===e?{value:""}:e)]},isExported:!1},Ri={description:vs("Calculates the frequency distribution of a range."),args:[ls("data (range<number>)",vs("The array of ranges containing the values to be counted.")),ls("classes (number, range<number>)",vs("The range containing the set of classes."))],compute:function(e,t){const s=Jo([e],e=>e.value).filter(e=>"number"==typeof e),o=Jo([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},xi={description:vs("Appends ranges horizontally and in sequence to return a larger array."),args:[ls("range (any, range<any>, repeating)",vs("The range to be appended."))],compute:function(...e){const t=Math.max(...e.map(e=>e?.[0]?.length??0)),s=[];for(const o of e){const e=Ko(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},Ti={description:vs("Returns the matrix determinant of a square matrix."),args:[ls("square_matrix (number, range<number>)",vs("An range with an equal number of rows and columns representing a matrix whose determinant will be calculated."))],compute:function(e){const t=yo(e,"square_matrix");return di(t)?pi(t).determinant:new ys(vs("The argument square_matrix must have the same number of columns and rows."))},isExported:!0},Ai={description:vs("Returns the multiplicative inverse of a square matrix."),args:[ls("square_matrix (number, range<number>)",vs("An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated."))],compute:function(e){const t=yo(e,"square_matrix");if(!di(t))return new ys(vs("The argument square_matrix must have the same number of columns and rows."));const{inverted:s}=pi(t);return s||new ys(vs("The matrix is not invertible."))},isExported:!0},Di={description:vs("Calculates the matrix product of two matrices."),args:[ls("matrix1 (number, range<number>)",vs("The first matrix in the matrix multiplication operation.")),ls("matrix2 (number, range<number>)",vs("The second matrix in the matrix multiplication operation."))],compute:function(e,t){const s=yo(e,"matrix1"),o=yo(t,"matrix2");return 0===s.length||0===o.length?new ys(vs("The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.")):s.length!==o[0].length?new ys(vs("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())):fi(s,o)},isExported:!0},_i={description:vs("Calculates the sum of the products of corresponding entries in equal-sized ranges."),args:[ls("range (number, range<number>, repeating)",vs("The range whose entries will be multiplied with corresponding entries in the other range."))],compute:function(...e){if(!hi(...e))return new ys(vs("All the ranges must have the same dimensions."));const t=e.map(Ko);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*=So(s[e][o],this.locale);s+=i}return s},isExported:!0};function Oi(e,t,s){if(!hi(e,t))return new ys(vs("The arguments array_x and array_y must have the same dimensions."));const o=Ko(e),i=Ko(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 ys(vs("The arguments array_x and array_y must contain at least one pair of numbers."))}const Fi={description:vs("Calculates the sum of the difference of the squares of the values in two array."),args:[ls("array_x (number, range<number>)",vs("The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.")),ls("array_y (number, range<number>)",vs("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 Oi(e,t,(e,t)=>e**2-t**2)},isExported:!0},Pi={description:vs("Calculates the sum of the sum of the squares of the values in two array."),args:[ls("array_x (number, range<number>)",vs("The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.")),ls("array_y (number, range<number>)",vs("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 Oi(e,t,(e,t)=>e**2+t**2)},isExported:!0},Mi={description:vs("Calculates the sum of squares of the differences of values in two array."),args:[ls("array_x (number, range<number>)",vs("The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.")),ls("array_y (number, range<number>)",vs("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 Oi(e,t,(e,t)=>(e-t)**2)},isExported:!0},Ni=!1,Li=[ls("array (any, range<any>)",vs("The array which will be transformed.")),ls("ignore (number, default=0)",vs("Whether to ignore certain types of values. By default, no values are ignored."),[{value:0,label:vs("Keep all values (default)")},{value:1,label:vs("Ignore blanks")},{value:2,label:vs("Ignore errors")},{value:3,label:vs("Ignore blanks and errors")}]),ls("scan_by_column (number, default=false)",vs("Scan the array by column. By default, the array is scanned by row."),[{value:!1,label:vs("Scan by row (default)")},{value:!0,label:vs("Scan by column")}])];function ki(e){const t=Math.trunc(e);if(0===t)return()=>!0;if(1===t)return e=>null!==e.value;if(2===t)return e=>!fo(e.value);if(3===t)return e=>null!==e.value&&!fo(e.value);throw new ys(vs("Argument ignore must be between 0 and 3"))}const Vi={description:vs("Transforms a range of cells into a single column."),args:Li,compute:function(e,t={value:0},s={value:Ni}){const o=Ko(e),i=So(t.value,this.locale),n=(Ao(s.value)?o:Ho(o)).flat().filter(ki(i));return 0===n.length?new Rs(vs("No results for the given arguments of TOCOL.")):[n]},isExported:!0},Ui={description:vs("Transforms a range of cells into a single row."),args:Li,compute:function(e,t={value:0},s={value:Ni}){const o=Ko(e),i=So(t.value,this.locale),n=(Ao(s.value)?o:Ho(o)).flat().filter(ki(i)).map(e=>[e]);return 0===n.length||0===n[0].length?new Rs(vs("No results for the given arguments of TOROW.")):n},isExported:!0},Hi={description:vs("Transposes the rows and columns of a range."),args:[ls("range (any, range<any>)",vs("The range to be transposed."))],compute:function(e){const t=Ko(e);return Vo(t[0].length,t.length,(e,s)=>t[s][e])},isExported:!0},zi={description:vs("Appends ranges vertically and in sequence to return a larger array."),args:[ls("range (any, range<any>, repeating)",vs("The range to be appended."))],compute:function(...e){const t=Math.max(...e.map(e=>Ko(e).length)),s=e.reduce((e,t)=>e+Ko(t)[0].length,0),o=Array(t).fill([]).map(()=>Array(s).fill({value:0}));let i=0;for(const t of e){const e=Ko(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},Bi={description:vs("Wraps the provided row or column of cells by columns after a specified number of elements to form a new array."),args:[ls("range (any, range<any>)",vs("The range to wrap.")),ls("wrap_count (number)",vs("The maximum number of cells for each column, rounded down to the nearest whole number.")),ls("pad_with (any, default=0)",vs("The value with which to fill the extra cells in the range."))],compute:function(e,t,s={value:0}){const o=Ko(e),i=wo(t?.value,this.locale);if(!ci(o))return new ys(vs("Argument range must be a single row or column."));const n=o.flat();return Vo(Math.ceil(n.length/i),i,(e,t)=>{const o=e*i+t;return o<n.length?n[o]:s})},isExported:!0},Gi={description:vs("Wraps the provided row or column of cells by rows after a specified number of elements to form a new array."),args:[ls("range (any, range<any>)",vs("The range to wrap.")),ls("wrap_count (number)",vs("The maximum number of cells for each row, rounded down to the nearest whole number.")),ls("pad_with (any, default=0)",vs("The value with which to fill the extra cells in the range."))],compute:function(e,t,s={value:0}){const o=Ko(e),i=wo(t?.value,this.locale);if(!ci(o))return new ys(vs("Argument range must be a single row or column."));const n=o.flat(),r=Math.ceil(n.length/i);return Vo(i,r,(e,t)=>{const o=t*i+e;return o<n.length?n[o]:s})},isExported:!0};var Wi=Object.freeze({__proto__:null,ARRAY_CONSTRAIN:Ci,CHOOSECOLS:yi,CHOOSEROWS:Ii,EXPAND:wi,FLATTEN:Ei,FREQUENCY:Ri,HSTACK:xi,MDETERM:Ti,MINVERSE:Ai,MMULT:Di,SUMPRODUCT:_i,SUMX2MY2:Fi,SUMX2PY2:Pi,SUMXMY2:Mi,TOCOL:Vi,TOROW:Ui,TRANSPOSE:Hi,VSTACK:zi,WRAPCOLS:Bi,WRAPROWS:Gi});function $i(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 qi=new Set("$+-/():!^&~{}<>= ");function Zi(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 qi.has(e.current)?{type:"CHAR",value:e.shift()}:null}function ji(e){return","===e.current?(e.shift(),{type:"THOUSANDS_SEPARATOR",value:","}):null}function Yi(e){return"@"===e.current?(e.shift(),{type:"TEXT_PLACEHOLDER",value:"@"}):null}function Xi(e){return"."===e.current?(e.shift(),{type:"DECIMAL_POINT",value:"."}):null}function Ki(e){return"%"===e.current?(e.shift(),{type:"PERCENT",value:"%"}):null}function Ji(e){if("0"===e.current||"#"===e.current){const t=e.current;return e.shift(),{type:"DIGIT",value:t}}return null}const Qi=new Set("dmqyhsa");function en(e){if(!Qi.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 tn(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 sn={};function on(e){let t=sn[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=Ji(t)||$i(t)||Zi(t)||ji(t)||Xi(t)||Ki(t)||en(t)||Yi(t)||tn(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=rn(t[0])||nn(t[0])||an(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=rn(t[1])||nn(t[1]);if(t[1]?.length&&!o)throw new Error("Invalid second format part of: "+e);const i=rn(t[2])||nn(t[2]);if(t[2]?.length&&!i)throw new Error("Invalid third format part of: "+e);const n=an(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),sn[e]=t),t}function nn(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 rn(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 an(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 ln(e){return[cn(e.positive),cn(e.negative),cn(e.zero),cn(e.text)].filter(Te).join(";")}function cn(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+=hn(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 hn(e){return!qi.has(e)}const dn="REPEATED_CHAR_PLACEHOLDER_",un={0:vs("January"),1:vs("February"),2:vs("March"),3:vs("April"),4:vs("May"),5:vs("June"),6:vs("July"),7:vs("August"),8:vs("September"),9:vs("October"),10:vs("November"),11:vs("December")},gn={0:vs("Sunday"),1:vs("Monday"),2:vs("Tuesday"),3:vs("Wednesday"),4:vs("Thursday"),5:vs("Friday"),6:vs("Saturday")};function pn(e,t,s,o=!1){return o?Nn({value:e,format:t},s):mn(e,{format:t,locale:s})}function mn(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=fn(e,on(t)).format;return s&&"text"===s.type?vn(e,s,o):e}case"number":t||(t=Tn(e));const i=on(t),{format:n,isNegativeFormat:r}=fn(e,i);if(!n)return e.toString();if("text"===n.type)return vn(e.toString(),n,o);if(r&&(e=Math.abs(e)),"date"===n.type)return bn(function(e,t){const s=Ys(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+=Rn(s,e.value,o);break;case"REPEATED_CHAR":i+=dn+e.value;break;default:i+=e.value}return i}(e,n),o);const a=e<0,l=bn(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}=Cn(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=dn+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+=dn+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 fn(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 vn(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+=dn+s.value}return bn(o,s)}function bn(e,t){const s=e.indexOf(dn);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 Sn=[];function Cn(e,t=20){const s=e.toString();if(s.includes("e"))return function(e,t=20){let s=Sn[t];s||(s=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),Sn[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(In)?.[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:yn(n||"")}}function yn(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const In=/^0+/;function wn(e,t){const{integerDigits:s,decimalDigits:o}=Cn(e,20);return o?s+t+o:s}const En=$e(function(e){if(!e)return!1;try{return"date"===on(e).positive.type}catch(e){return!1}});function Rn(e,t,s){switch(t){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return gn[e.getDay()].slice(0,3);case"dddd":return gn[e.getDay()].toString();case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return un[e.getMonth()].slice(0,3);case"mmmm":return un[e.getMonth()].toString();case"mmmmm":return un[e.getMonth()].slice(0,1);case"qq":return vs("Q%(quarter)s",{quarter:e.getQuarter()}).toString();case"qqqq":return vs("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()-Ps.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 xn=$e(function(e){return new RegExp(`[0-9]+${re(e.decimalSeparator)}[0-9]`)});function Tn(e){let{integerDigits:t,decimalDigits:s}=Cn(e);if(!s)return"0";const o=t.replace("-","").length;if(o+2>11)return"0";const i=11-o-1;return({decimalDigits:s}=Cn(e,Math.min(i,s.length))),s?"0."+"0".repeat(s.length):"0"}function An(e,t){if(!qs(e,t))return;return js(e,t).format}function Dn(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 _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();return"after"===s&&o&&(r=" "+r),function(e,t,s){const o=`[$${e}]`;return"before"===t?o+s:s+o}(r,s,n)}function On(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[Fn(r,s,` ${n} `),Fn(r,s,`(${n})`),Fn(r,s," - ")].join(";")}function Fn(e,t,s){const o=`[$${e}]`;return"before"===t?o+"* "+s:s+"* "+o}function Pn(e){const t=on(e);return ln({positive:Mn(t.positive),negative:t.negative?Mn(t.negative):void 0,zero:t.zero?Mn(t.zero):void 0,text:t.text})}function Mn(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 Nn({value:e,format:t},s){const o=Co(e,s);if(void 0===o)return"";let i=t;if(Math.abs(o)<1e3){i=!t&&o%1!=0?"0.####":t}else i=Ln({value:e,format:t},void 0,s);return mn(e,{format:i,locale:s})}function Ln(e,t,s){let o=0;try{o=Math.abs(So(e?.value,s))}catch(e){return""}const i=e?.format;if(void 0!==t){const e=t?.value;switch(e){case"k":return kn(i,1,"k");case"m":return kn(i,2,"m");case"b":return kn(i,3,"b");default:throw new ys(vs("The formatting unit should be 'k', 'm' or 'b'."))}}return o<1e5?kn(i,0,""):o<1e8?kn(i,1,"k"):o<1e11?kn(i,2,"m"):kn(i,3,"b")}function kn(e,t,s,o){const i=on(e||"#,##0");return ln({positive:Vn(i.positive,t,s),negative:i.negative?Vn(i.negative,t,s):void 0,zero:i.zero?Vn(i.zero,t,s):void 0,text:i.text})}function Vn(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 Un(e,t){const s=on(e);return ln(on(ln({positive:Hn(s.positive,t),negative:s.negative?Hn(s.negative,t):void 0,zero:s.zero?Hn(s.zero,t):void 0,text:s.text})))}function Hn(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 zn(e){const t=on(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 Bn(e){if(!e)return!1;try{return"text"===on(e).positive.type}catch{return!1}}const Gn={description:vs("Apply a large number format"),args:[ls("value (number)",vs("The number.")),ls("unit (string, optional)",vs("The formatting unit. Use 'k', 'm', or 'b' to force the unit"),[{value:"k",label:vs("Thousand")},{value:"m",label:vs("Million")},{value:"b",label:vs("Billion")}])],compute:function(e,t){return{value:So(e,this.locale),format:Ln(e,t,this.locale)}}};var Wn=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:Gn});const $n=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),qn=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),Zn=new RegExp(/^\$?([A-Z]{1,3})+$/,"i"),jn=new RegExp(/^\$?([0-9]{1,7})+$/,"i"),Yn=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),Xn=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),Kn=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[$n.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 Jn(e){return Xn.test(e)}function Qn(e){return Zn.test(e)}function er(e){return jn.test(e)}function tr(e){return qn.test(e)}function sr(e){if(!e.includes("!"))return{xc:e};const t=e.split("!"),s=t.pop();return{sheetName:le(t.join("!"))||void 0,xc:s}}function or(e,t){return void 0!==e?`${he(e)}!${t}`:t}function ir(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:s}=sr(e.value),[o,i]=t.split(":"),n=nr(o),r=i?`:${nr(i)}`:"";return{...e,value:or(s,n+r)}}function nr(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=rr(e,"colrow");break;case"colrow":e=rr(e,"row");break;case"row":e=rr(e,"col");break;case"col":e=rr(e,"none")}return e}function rr(e,t){let s;({sheetName:s,xc:e}=sr(e)),s=s?s+"!":"";const o=(e=e.replace(/\$/g,"")).indexOf(":");return o>=0?`${s}${ar(e.slice(0,o),t)}:${ar(e.slice(o+1),t)}`:s+ar(e,t)}function ar(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 lr(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class cr{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 hr=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"]),dr=new Set(["EVALUATE_CELLS","EVALUATE_CHARTS","UPDATE_CELL","UNHIDE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","GROUP_HEADERS","SET_FORMATTING","CLEAR_FORMATTING","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"]),ur=new Set(["MOVE_RANGES"]),gr=new Set(["EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","CHANGE_CONDITIONAL_FORMAT_PRIORITY"]),pr=new Set(["AUTOFILL_CELL","SET_BORDER","SET_ZONE_BORDERS","SET_BORDERS_ON_TARGET"]),mr=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"]),fr=new Set(["START","ACTIVATE_SHEET","COPY","RESIZE_SHEETVIEW","SET_VIEWPORT_OFFSET","SET_ZOOM","EVALUATE_CELLS","EVALUATE_CHARTS","SET_FORMULA_VISIBILITY","UPDATE_FILTER","UPDATE_CHART","UPDATE_CAROUSEL_ACTIVE_ITEM","UPDATE_PIVOT"]),vr=new Set(["UPDATE_CELL","UPDATE_CELL_POSITION","CLEAR_CELL","CLEAR_CELLS","DELETE_CONTENT","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","RESIZE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","UNHIDE_COLUMNS_ROWS","SET_GRID_LINES_VISIBILITY","UNFREEZE_COLUMNS","UNFREEZE_ROWS","FREEZE_COLUMNS","FREEZE_ROWS","UNFREEZE_COLUMNS_ROWS","ADD_MERGE","REMOVE_MERGE","CREATE_SHEET","DELETE_SHEET","DUPLICATE_SHEET","MOVE_SHEET","RENAME_SHEET","COLOR_SHEET","HIDE_SHEET","SHOW_SHEET","MOVE_RANGES","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","CHANGE_CONDITIONAL_FORMAT_PRIORITY","CREATE_FIGURE","DELETE_FIGURE","UPDATE_FIGURE","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 br(e){return vr.has(e.type)}class Sr{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter(e=>"Success"!==e)}static get Success(){return Cr}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}const Cr=new Sr;var yr;e.CommandResult=void 0,(yr=e.CommandResult||(e.CommandResult={})).Success="Success",yr.CancelledForUnknownReason="CancelledForUnknownReason",yr.WillRemoveExistingMerge="WillRemoveExistingMerge",yr.CannotMoveTableHeader="CannotMoveTableHeader",yr.MergeIsDestructive="MergeIsDestructive",yr.CellIsMerged="CellIsMerged",yr.InvalidTarget="InvalidTarget",yr.EmptyUndoStack="EmptyUndoStack",yr.EmptyRedoStack="EmptyRedoStack",yr.NotEnoughElements="NotEnoughElements",yr.NotEnoughSheets="NotEnoughSheets",yr.MissingSheetName="MissingSheetName",yr.UnchangedSheetName="UnchangedSheetName",yr.DuplicatedSheetName="DuplicatedSheetName",yr.DuplicatedSheetId="DuplicatedSheetId",yr.ForbiddenCharactersInSheetName="ForbiddenCharactersInSheetName",yr.WrongSheetMove="WrongSheetMove",yr.WrongSheetPosition="WrongSheetPosition",yr.InvalidAnchorZone="InvalidAnchorZone",yr.SelectionOutOfBound="SelectionOutOfBound",yr.TargetOutOfSheet="TargetOutOfSheet",yr.WrongCutSelection="WrongCutSelection",yr.WrongPasteSelection="WrongPasteSelection",yr.WrongPasteOption="WrongPasteOption",yr.WrongFigurePasteOption="WrongFigurePasteOption",yr.EmptyClipboard="EmptyClipboard",yr.EmptyRange="EmptyRange",yr.InvalidRange="InvalidRange",yr.InvalidZones="InvalidZones",yr.InvalidSheetId="InvalidSheetId",yr.InvalidCellId="InvalidCellId",yr.InvalidFigureId="InvalidFigureId",yr.InputAlreadyFocused="InputAlreadyFocused",yr.MaximumRangesReached="MaximumRangesReached",yr.MinimumRangesReached="MinimumRangesReached",yr.InvalidChartDefinition="InvalidChartDefinition",yr.InvalidDataSet="InvalidDataSet",yr.InvalidLabelRange="InvalidLabelRange",yr.InvalidScorecardKeyValue="InvalidScorecardKeyValue",yr.InvalidScorecardBaseline="InvalidScorecardBaseline",yr.InvalidGaugeDataRange="InvalidGaugeDataRange",yr.EmptyGaugeRangeMin="EmptyGaugeRangeMin",yr.GaugeRangeMinNaN="GaugeRangeMinNaN",yr.EmptyGaugeRangeMax="EmptyGaugeRangeMax",yr.GaugeRangeMaxNaN="GaugeRangeMaxNaN",yr.GaugeLowerInflectionPointNaN="GaugeLowerInflectionPointNaN",yr.GaugeUpperInflectionPointNaN="GaugeUpperInflectionPointNaN",yr.InvalidAutofillSelection="InvalidAutofillSelection",yr.MinBiggerThanMax="MinBiggerThanMax",yr.LowerBiggerThanUpper="LowerBiggerThanUpper",yr.MidBiggerThanMax="MidBiggerThanMax",yr.MinBiggerThanMid="MinBiggerThanMid",yr.FirstArgMissing="FirstArgMissing",yr.SecondArgMissing="SecondArgMissing",yr.MinNaN="MinNaN",yr.MidNaN="MidNaN",yr.MaxNaN="MaxNaN",yr.ValueUpperInflectionNaN="ValueUpperInflectionNaN",yr.ValueLowerInflectionNaN="ValueLowerInflectionNaN",yr.MinInvalidFormula="MinInvalidFormula",yr.MidInvalidFormula="MidInvalidFormula",yr.MaxInvalidFormula="MaxInvalidFormula",yr.ValueUpperInvalidFormula="ValueUpperInvalidFormula",yr.ValueLowerInvalidFormula="ValueLowerInvalidFormula",yr.InvalidSortAnchor="InvalidSortAnchor",yr.InvalidSortZone="InvalidSortZone",yr.SortZoneWithArrayFormulas="SortZoneWithArrayFormulas",yr.WaitingSessionConfirmation="WaitingSessionConfirmation",yr.MergeOverlap="MergeOverlap",yr.TooManyHiddenElements="TooManyHiddenElements",yr.Readonly="Readonly",yr.InvalidViewportSize="InvalidViewportSize",yr.InvalidScrollingDirection="InvalidScrollingDirection",yr.ViewportScrollLimitsReached="ViewportScrollLimitsReached",yr.FigureDoesNotExist="FigureDoesNotExist",yr.InvalidConditionalFormatId="InvalidConditionalFormatId",yr.InvalidCellPopover="InvalidCellPopover",yr.EmptyTarget="EmptyTarget",yr.InvalidFreezeQuantity="InvalidFreezeQuantity",yr.FrozenPaneOverlap="FrozenPaneOverlap",yr.ValuesNotChanged="ValuesNotChanged",yr.InvalidFilterZone="InvalidFilterZone",yr.TableNotFound="TableNotFound",yr.TableOverlap="TableOverlap",yr.InvalidTableConfig="InvalidTableConfig",yr.InvalidTableStyle="InvalidTableStyle",yr.FilterNotFound="FilterNotFound",yr.MergeInTable="MergeInTable",yr.NonContinuousTargets="NonContinuousTargets",yr.DuplicatedFigureId="DuplicatedFigureId",yr.InvalidSelectionStep="InvalidSelectionStep",yr.DuplicatedChartId="DuplicatedChartId",yr.ChartDoesNotExist="ChartDoesNotExist",yr.InvalidHeaderIndex="InvalidHeaderIndex",yr.InvalidQuantity="InvalidQuantity",yr.MoreThanOneColumnSelected="MoreThanOneColumnSelected",yr.EmptySplitSeparator="EmptySplitSeparator",yr.SplitWillOverwriteContent="SplitWillOverwriteContent",yr.NoSplitSeparatorInSelection="NoSplitSeparatorInSelection",yr.NoActiveSheet="NoActiveSheet",yr.InvalidLocale="InvalidLocale",yr.MoreThanOneRangeSelected="MoreThanOneRangeSelected",yr.NoColumnsProvided="NoColumnsProvided",yr.ColumnsNotIncludedInZone="ColumnsNotIncludedInZone",yr.DuplicatesColumnsSelected="DuplicatesColumnsSelected",yr.InvalidHeaderGroupStartEnd="InvalidHeaderGroupStartEnd",yr.HeaderGroupAlreadyExists="HeaderGroupAlreadyExists",yr.UnknownHeaderGroup="UnknownHeaderGroup",yr.UnknownDataValidationRule="UnknownDataValidationRule",yr.UnknownDataValidationCriterionType="UnknownDataValidationCriterionType",yr.InvalidDataValidationCriterionValue="InvalidDataValidationCriterionValue",yr.InvalidNumberOfCriterionValues="InvalidNumberOfCriterionValues",yr.InvalidCopyPasteSelection="InvalidCopyPasteSelection",yr.NoChanges="NoChanges",yr.InvalidInputId="InvalidInputId",yr.SheetIsHidden="SheetIsHidden",yr.InvalidTableResize="InvalidTableResize",yr.PivotIdNotFound="PivotIdNotFound",yr.PivotInError="PivotInError",yr.EmptyName="EmptyName",yr.ValueCellIsInvalidFormula="ValueCellIsInvalidFormula",yr.InvalidDefinition="InvalidDefinition",yr.InvalidColor="InvalidColor",yr.InvalidPivotDataSet="InvalidPivotDataSet",yr.InvalidPivotCustomField="InvalidPivotCustomField",yr.MissingFigureArguments="MissingFigureArguments",yr.InvalidCarouselItem="InvalidCarouselItem";class Ir{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 wr extends Ir{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 Er(e){return e.isFormula&&e.compiledFormula.tokens.some(e=>"SYMBOL"===e.type&&"SUBTOTAL"===e.value.toUpperCase())}function Rr(e,t){return Lo(e,(e,t)=>e+t,0,t)}function xr(e){return No(e,(e,t)=>Qo(t)?e.add(t?.value):e,new Set).size}const Tr=/^-?[a-z0-9]+$/i,Ar={description:vs("Absolute value of a number."),args:[ls("value (number)",vs("The number of which to return the absolute value."))],compute:function(e){return Math.abs(So(e,this.locale))},isExported:!0},Dr={description:vs("Inverse cosine of a value, in radians."),args:[ls("value (number)",vs("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive."))],compute:function(e){const t=So(e,this.locale);return Math.abs(t)>1?new ys(vs("The value (%s) must be between -1 and 1 inclusive.",t)):Math.acos(t)},isExported:!0},_r={description:vs("Inverse hyperbolic cosine of a number."),args:[ls("value (number)",vs("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1."))],compute:function(e){const t=So(e,this.locale);return t<1?new ys(vs("The value (%s) must be greater than or equal to 1.",t)):Math.acosh(t)},isExported:!0},Or={description:vs("Inverse cotangent of a value."),args:[ls("value (number)",vs("The value for which to calculate the inverse cotangent."))],compute:function(e){const t=So(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Fr={description:vs("Inverse hyperbolic cotangent of a value."),args:[ls("value (number)",vs("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive."))],compute:function(e){const t=So(e,this.locale);return Math.abs(t)<=1?new ys(vs("The value (%s) cannot be between -1 and 1 inclusive.",t)):Math.log((t+1)/(t-1))/2},isExported:!0},Pr={description:vs("Inverse sine of a value, in radians."),args:[ls("value (number)",vs("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive."))],compute:function(e){const t=So(e,this.locale);return Math.abs(t)>1?new ys(vs("The value (%s) must be between -1 and 1 inclusive.",t)):Math.asin(t)},isExported:!0},Mr={description:vs("Inverse hyperbolic sine of a number."),args:[ls("value (number)",vs("The value for which to calculate the inverse hyperbolic sine."))],compute:function(e){return Math.asinh(So(e,this.locale))},isExported:!0},Nr={description:vs("Inverse tangent of a value, in radians."),args:[ls("value (number)",vs("The value for which to calculate the inverse tangent."))],compute:function(e){return Math.atan(So(e,this.locale))},isExported:!0},Lr={description:vs("Angle from the X axis to a point (x,y), in radians."),args:[ls("x (number)",vs("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")),ls("y (number)",vs("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=So(e,this.locale),o=So(t,this.locale);return 0===s&&0===o?new As(vs("Function [[FUNCTION_NAME]] caused a divide by zero error.")):Math.atan2(o,s)},isExported:!0},kr={description:vs("Inverse hyperbolic tangent of a number."),args:[ls("value (number)",vs("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive."))],compute:function(e){const t=So(e,this.locale);return Math.abs(t)>=1?new ys(vs("The value (%s) must be between -1 and 1 exclusive.",t)):Math.atanh(t)},isExported:!0},Vr={description:vs("Rounds number up to nearest multiple of factor."),args:[ls("value (number)",vs("The value to round up to the nearest integer multiple of factor.")),ls("factor (number, default=1)",vs("The number to whose multiples value will be rounded."))],compute:function(e,t={value:1}){const s=So(e,this.locale),o=So(t,this.locale);return o<0&&s>0?new ys(vs("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 Ur(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 Hr={description:vs("Rounds number up to nearest multiple of factor."),args:[ls("number (number)",vs("The value to round up to the nearest integer multiple of significance.")),ls("significance (number, default=1)",vs("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),ls("mode (number, default=0)",vs("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=So(t,this.locale);return{value:Ur(So(e,this.locale),o,So(s,this.locale)),format:e?.format}},isExported:!0},zr={description:vs("Rounds number up to nearest multiple of factor."),args:[ls("number (number)",vs("The value to round up to the nearest integer multiple of significance.")),ls("significance (number, default=1)",vs("The number to whose multiples number will be rounded."))],compute:function(e,t={value:1}){const s=So(t,this.locale);return{value:Ur(So(e,this.locale),s),format:e?.format}},isExported:!0},Br={description:vs("Cosine of an angle provided in radians."),args:[ls("angle (number)",vs("The angle to find the cosine of, in radians."))],compute:function(e){return Math.cos(So(e,this.locale))},isExported:!0},Gr={description:vs("Hyperbolic cosine of any real number."),args:[ls("value (number)",vs("Any real value to calculate the hyperbolic cosine of."))],compute:function(e){return Math.cosh(So(e,this.locale))},isExported:!0},Wr={description:vs("Cotangent of an angle provided in radians."),args:[ls("angle (number)",vs("The angle to find the cotangent of, in radians."))],compute:function(e){const t=So(e,this.locale);return 0===t?new As(vs("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.tan(t)},isExported:!0},$r={description:vs("Hyperbolic cotangent of any real number."),args:[ls("value (number)",vs("Any real value to calculate the hyperbolic cotangent of."))],compute:function(e){const t=So(e,this.locale);return 0===t?new As(vs("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.tanh(t)},isExported:!0},qr={description:vs("Number of empty values."),args:[ls("value (any, range, repeating)",vs("Value or range in which to count the number of blanks."))],compute:function(...e){return No(e,(e,t)=>void 0===t||null===t.value||""===t.value?e+1:e,0)},isExported:!0},Zr={description:vs("A conditional count across a range."),args:[ls("range (range)",vs("The range that is tested against criterion.")),ls("criterion (string)",vs("The pattern or test to apply to range."))],compute:function(...e){let t=0;return qo(e,(e,s)=>{t+=1},this.locale),t},isExported:!0},jr={description:vs("Count values depending on multiple criteria."),args:[ls("criteria_range (any, range, repeating)",vs("Range over which to evaluate criteria.")),ls("criterion (string, repeating)",vs("Criteria to check."))],compute:function(...e){let t=0;return qo(e,(e,s)=>{t+=1},this.locale),t},isExported:!0},Yr={description:vs("Counts number of unique values in a range."),args:[ls("value (any, range, repeating)",vs("Value or range to consider for uniqueness."))],compute:function(...e){return xr(e)}},Xr={description:vs("Counts number of unique values in a range, filtered by a set of criteria."),args:[ls("range (range)",vs("The range of cells from which the number of unique values will be counted.")),ls("criteria_range (any, range, repeating)",vs("Range over which to evaluate criteria.")),ls("criterion (string, repeating)",vs("Criteria to check."))],compute:function(e,...t){const s=new Set;return qo(t,(t,o)=>{const i=e[t]?.[o];Qo(i)&&s.add(i.value)},this.locale),s.size}},Kr={description:vs("Cosecant of an angle provided in radians."),args:[ls("angle (number)",vs("The angle to find the cosecant of, in radians."))],compute:function(e){const t=So(e,this.locale);return 0===t?new As(vs("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.sin(t)},isExported:!0},Jr={description:vs("Hyperbolic cosecant of any real number."),args:[ls("value (number)",vs("Any real value to calculate the hyperbolic cosecant of."))],compute:function(e){const t=So(e,this.locale);return 0===t?new As(vs("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.sinh(t)},isExported:!0},Qr={description:vs("Converts from another base to decimal."),args:[ls("value (string)",vs("The number to convert.")),ls("base (number)",vs("The base to convert the value from."))],compute:function(e,t){let s=So(t,this.locale);if(s=Math.floor(s),2>s||s>36)return new ys(vs("The base (%s) must be between 2 and 36 inclusive.",s));const o=Ro(e);if(""===o)return 0;if(!Tr.test(o))return new ys(vs("The value (%s) must be a valid base %s representation.",o,s));const i=parseInt(o,s);return isNaN(i)?new ys(vs("The value (%s) must be a valid base %s representation.",o,s)):i},isExported:!0},ea={description:vs("Converts an angle value in radians to degrees."),args:[ls("angle (number)",vs("The angle to convert from radians to degrees."))],compute:function(e){return 180*So(e,this.locale)/Math.PI},isExported:!0},ta={description:vs("Euler's number, e (~2.718) raised to a power."),args:[ls("value (number)",vs("The exponent to raise e."))],compute:function(e){return Math.exp(So(e,this.locale))},isExported:!0},sa={description:vs("Rounds number down to nearest multiple of factor."),args:[ls("value (number)",vs("The value to round down to the nearest integer multiple of factor.")),ls("factor (number, default=1)",vs("The number to whose multiples value will be rounded."))],compute:function(e,t={value:1}){const s=So(e,this.locale),o=So(t,this.locale);return o<0&&s>0?new ys(vs("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 oa(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 ia={description:vs("Rounds number down to nearest multiple of factor."),args:[ls("number (number)",vs("The value to round down to the nearest integer multiple of significance.")),ls("significance (number, default=1)",vs("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),ls("mode (number, default=0)",vs("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=So(t,this.locale);return{value:oa(So(e,this.locale),o,So(s,this.locale)),format:e?.format}},isExported:!0},na={description:vs("Rounds number down to nearest multiple of factor."),args:[ls("number (number)",vs("The value to round down to the nearest integer multiple of significance.")),ls("significance (number, default=1)",vs("The number to whose multiples number will be rounded."))],compute:function(e,t={value:1}){const s=So(t,this.locale);return{value:oa(So(e,this.locale),s),format:e?.format}},isExported:!0},ra={description:vs("Whether the provided value is even."),args:[ls("value (number)",vs("The value to be verified as even."))],compute:function(e){const t=Io(e,this.locale);return!(1&Math.floor(Math.abs(t)))},isExported:!0},aa={description:vs("Rounds number up to nearest multiple of factor."),args:[ls("number (number)",vs("The value to round up to the nearest integer multiple of significance.")),ls("significance (number, default=1)",vs("The number to whose multiples number will be rounded."))],compute:function(e,t={value:1}){return{value:Ur(So(e,this.locale),So(t,this.locale)),format:e?.format}},isExported:!0},la={description:vs("Whether the provided value is even."),args:[ls("value (number)",vs("The value to be verified as even."))],compute:function(e){const t=Io(e,this.locale);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},ca={description:vs("The logarithm of a number, base e (euler's number)."),args:[ls("value (number)",vs("The value for which to calculate the logarithm, base e."))],compute:function(e){const t=So(e,this.locale);return t<=0?new ys(vs("The value (%s) must be strictly positive.",t)):Math.log(t)},isExported:!0},ha={description:vs("The logarithm of a number, for a given base."),args:[ls("value (number)",vs("The value for which to calculate the logarithm.")),ls("base (number, default=10)",vs("The base of the logarithm."))],compute:function(e,t={value:10}){const s=So(e,this.locale),o=So(t,this.locale);return s<=0?new ys(vs("The value (%s) must be strictly positive.",s)):o<=0?new ys(vs("The base (%s) must be strictly positive.",o)):1===o?new ys(vs("The base must be different from 1.")):Math.log10(s)/Math.log10(o)},isExported:!0};function da(e,t){li(t,vs("The divisor must be different from 0."));const s=e%t;return s>0&&t<0||s<0&&t>0?s+t:s}const ua={description:vs("Modulo (remainder) operator."),args:[ls("dividend (number)",vs("The number to be divided to find the remainder.")),ls("divisor (number)",vs("The number to divide by."))],compute:function(e,t){const s=So(t,this.locale);return{value:da(So(e,this.locale),s),format:e?.format}},isExported:!0},ga={description:vs("Returns a n x n unit matrix, where n is the input dimension."),args:[ls("dimension (number)",vs("An integer specifying the dimension size of the unit matrix. It must be positive."))],compute:function(e){const t=wo(e,this.locale);return t<1?new ys(vs("The argument dimension must be positive")):gi(t)},isExported:!0},pa={description:vs("Rounds a number up to the nearest odd integer."),args:[ls("value (number)",vs("The value to round to the next greatest odd number."))],compute:function(e){const t=So(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},ma={description:vs("The number pi."),args:[],compute:function(){return Math.PI},isExported:!0},fa={description:vs("A number raised to a power."),args:[ls("base (number)",vs("The number to raise to the exponent power.")),ls("exponent (number)",vs("The exponent to raise base to."))],compute:function(e,t){const s=So(e,this.locale),o=So(t,this.locale);return s<0&&!Number.isInteger(o)?new ys(vs("The exponent (%s) must be an integer when the base is negative.",o)):{value:Math.pow(s,o),format:e?.format}},isExported:!0},va={description:vs("Result of multiplying a series of numbers together."),args:[ls("factor (number, range<number>, repeating)",vs("Number or range to calculate for the product."))],compute:function(...e){let t=0,s=1;for(const o of e)if(_s(o))for(const e of o)for(const o of e){const e=o.value;if("number"==typeof e&&(s*=e,t+=1),fo(e))return o}else void 0!==o&&null!==o.value&&(s*=Io(o,this.locale),t+=1);return{value:0===t?0:s,format:mo(e[0])}},isExported:!0},ba={description:vs("A random number between 0 inclusive and 1 exclusive."),args:[],compute:function(){return Math.random()},isExported:!0},Sa={description:vs("Returns a grid of random numbers between 0 inclusive and 1 exclusive."),args:[ls("rows (number, default=1)",vs("The number of rows to be returned.")),ls("columns (number, default=1)",vs("The number of columns to be returned.")),ls("min (number, default=0)",vs("The minimum number you would like returned.")),ls("max (number, default=1)",vs("The maximum number you would like returned.")),ls("whole_number (boolean, default=FALSE)",vs("Return a whole number or a decimal value."),[{value:!1,label:vs("Decimal (default)")},{value:!0,label:vs("Integer")}])],compute:function(e={value:1},t={value:1},s={value:0},o={value:1},i={value:!1}){const n=wo(t,this.locale),r=wo(e,this.locale),a=So(s,this.locale),l=So(o,this.locale),c=Ao(i);if(n<1)return new ys(vs("The number of columns (%s) must be positive.",n));if(r<1)return new ys(vs("The number of rows (%s) must be positive.",r));if(a>l)return new ys(vs("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 ys(vs("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},Ca={description:vs("Random integer between two values, inclusive."),args:[ls("low (number)",vs("The low end of the random range.")),ls("high (number)",vs("The high end of the random range."))],compute:function(e,t){let s=So(e,this.locale);Number.isInteger(s)||(s=Math.ceil(s));let o=So(t,this.locale);return Number.isInteger(o)||(o=Math.floor(o)),s>o?new ys(vs("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},ya={description:vs("Rounds a number according to standard rules."),args:[ls("value (number)",vs("The value to round to places number of places.")),ls("places (number, default=0)",vs("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const s=So(e,this.locale);let o=So(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},Ia={description:vs("Rounds down a number."),args:[ls("value (number)",vs("The value to round to places number of places, always rounding down.")),ls("places (number, default=0)",vs("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const s=So(e,this.locale);let o=So(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},wa={description:vs("Rounds up a number."),args:[ls("value (number)",vs("The value to round to places number of places, always rounding up.")),ls("places (number, default=0)",vs("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const s=So(e,this.locale);let o=So(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},Ea={description:vs("Secant of an angle provided in radians."),args:[ls("angle (number)",vs("The angle to find the secant of, in radians."))],compute:function(e){return 1/Math.cos(So(e,this.locale))},isExported:!0},Ra={description:vs("Hyperbolic secant of any real number."),args:[ls("value (number)",vs("Any real value to calculate the hyperbolic secant of."))],compute:function(e){return 1/Math.cosh(So(e,this.locale))},isExported:!0},xa={description:vs("Returns a sequence of numbers."),args:[ls("rows (number)",vs("The number of rows to return")),ls("columns (number, optional, default=1)",vs("The number of columns to return")),ls("start (number, optional, default=1)",vs("The first number in the sequence")),ls("step (number, optional, default=1)",vs("The amount to increment each value in the sequence"))],compute:function(e,t={value:1},s={value:1},o={value:1}){const i=So(s,this.locale),n=So(o,this.locale),r=wo(e,this.locale),a=wo(t,this.locale);return a<1?new ys(vs("The number of columns (%s) must be positive.",a)):r<1?new ys(vs("The number of rows (%s) must be positive.",r)):Vo(a,r,(e,t)=>({value:i+t*a*n+e*n}))},isExported:!0},Ta={description:vs("Sine of an angle provided in radians."),args:[ls("angle (number)",vs("The angle to find the sine of, in radians."))],compute:function(e){return Math.sin(So(e,this.locale))},isExported:!0},Aa={description:vs("Hyperbolic sine of any real number."),args:[ls("value (number)",vs("Any real value to calculate the hyperbolic sine of."))],compute:function(e){return Math.sinh(So(e,this.locale))},isExported:!0},Da={description:vs("Positive square root of a positive number."),args:[ls("value (number)",vs("The number for which to calculate the positive square root."))],compute:function(e){const t=So(e,this.locale);return t<0?new ys(vs("The value (%s) must be positive or null.",t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},_a={1:"AVERAGE",2:"COUNT",3:"COUNTA",4:"MAX",5:"MIN",6:"PRODUCT",7:"STDEV",8:"STDEVP",9:"SUM",10:"VAR",11:"VARP"},Oa=Object.entries(_a).map(([e,t])=>({value:parseInt(e),label:vs("%s (include manually-hidden rows)",t)})),Fa=Object.entries(_a).map(([e,t])=>({value:parseInt(e)+100,label:vs("%s (exclude manually-hidden rows)",t)})),Pa={description:vs("Returns a subtotal for a vertical range of cells using a specified aggregation function."),args:[ls("function_code (number)",vs("The function to use in subtotal aggregation."),[...Oa,...Fa]),ls("ref (meta, range<meta>, repeating)",vs("Range or reference for which you want the subtotal."))],compute:function(e,...t){let s=wo(e,this.locale),o=!0;if(s>100&&(s-=100,o=!1),s<1||s>11)return new ys(vs("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=sr(t.value).sheetName,n=s?this.getters.getSheetIdByName(s):this.__originSheetId;if(!n)continue;const{top:r,left:a}=Rt(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&&Er(s)||i.push(this.getters.getEvaluatedCell({sheetId:n,col:t,row:e}))}}return this[_a[s]].apply(this,[[i]])},isExported:!0},Ma={description:vs("Sum of a series of numbers and/or cells."),args:[ls("value (number, range<number>, repeating)",vs("Number or range to add together."))],compute:function(...e){const t=e[0];return{value:Rr(e,this.locale),format:mo(t)}},isExported:!0},Na={description:vs("A conditional sum across a range."),args:[ls("criteria_range (range)",vs("The range which is tested against criterion.")),ls("criterion (string)",vs("The pattern or test to apply to range.")),ls("sum_range (range, default=criteria_range)",vs("The range to be summed, if different from range."))],compute:function(e,t,s){void 0===s&&(s=e);let o=0;return qo([e,t],(e,t)=>{const i=s[e]?.[t]?.value;"number"==typeof i&&(o+=i)},this.locale),o},isExported:!0},La={description:vs("Sums a range depending on multiple criteria."),args:[ls("sum_range (range)",vs("The range to sum.")),ls("criteria_range (any, range, repeating)",vs("Range to check.")),ls("criterion (string, repeating)",vs("Criteria to check."))],compute:function(e,...t){let s=0;return qo(t,(t,o)=>{const i=e[t]?.[o]?.value;"number"==typeof i&&(s+=i)},this.locale),s},isExported:!0},ka={description:vs("Tangent of an angle provided in radians."),args:[ls("angle (number)",vs("The angle to find the tangent of, in radians."))],compute:function(e){return Math.tan(So(e,this.locale))},isExported:!0},Va={description:vs("Hyperbolic tangent of any real number."),args:[ls("value (number)",vs("Any real value to calculate the hyperbolic tangent of."))],compute:function(e){return Math.tanh(So(e,this.locale))},isExported:!0};function Ua(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 Ha={description:vs("Truncates a number."),args:[ls("value (number)",vs("The value to be truncated.")),ls("places (number, default=0)",vs("The number of significant digits to the right of the decimal point to retain."))],compute:function(e,t={value:0}){return{value:Ua(So(e,this.locale),So(t,this.locale)),format:e?.format}},isExported:!0},za={description:vs("Rounds a number down to the nearest integer that is less than or equal to it."),args:[ls("value (number)",vs("The number to round down to the nearest integer."))],compute:function(e){return Math.floor(So(e,this.locale))},isExported:!0};var Ba=Object.freeze({__proto__:null,ABS:Ar,ACOS:Dr,ACOSH:_r,ACOT:Or,ACOTH:Fr,ASIN:Pr,ASINH:Mr,ATAN:Nr,ATAN2:Lr,ATANH:kr,CEILING:Vr,CEILING_MATH:Hr,CEILING_PRECISE:zr,COS:Br,COSH:Gr,COT:Wr,COTH:$r,COUNTBLANK:qr,COUNTIF:Zr,COUNTIFS:jr,COUNTUNIQUE:Yr,COUNTUNIQUEIFS:Xr,CSC:Kr,CSCH:Jr,DECIMAL:Qr,DEGREES:ea,EXP:ta,FLOOR:sa,FLOOR_MATH:ia,FLOOR_PRECISE:na,INT:za,ISEVEN:ra,ISODD:la,ISO_CEILING:aa,LN:ca,LOG:ha,MOD:ua,MUNIT:ga,ODD:pa,PI:ma,POWER:fa,PRODUCT:va,RAND:ba,RANDARRAY:Sa,RANDBETWEEN:Ca,ROUND:ya,ROUNDDOWN:Ia,ROUNDUP:wa,SEC:Ea,SECH:Ra,SEQUENCE:xa,SIN:Ta,SINH:Aa,SQRT:Da,SUBTOTAL:Pa,SUM:Ma,SUMIF:Na,SUMIFS:La,TAN:ka,TANH:Va,TRUNC:Ha});function Ga(...e){const t=e[0].length;e.forEach((e,s)=>ai(e.length===t,vs("[[FUNCTION_NAME]] has mismatched dimensions for argument %s (%s vs %s).",s.toString(),t.toString(),e.length.toString())))}function Wa(e,t){let s=0;const o=Lo(e,(e,t)=>(s+=1,e+t),0,t);return li(s),o/s}function $a(e,t){let s=0;for(const o of e)if(_s(o))for(const e of o)for(const t of e)"number"==typeof t.value&&(s+=1);else{const e=o?.value;fo(e)||"string"==typeof e&&!co(e,t)&&!js(e,t)||(s+=1)}return s}function qa(e){return No(e,(e,t)=>void 0!==t&&null!==t.value?e+1:e,0)}function Za(e,t){let s={value:-1/0};return Po(e,e=>{e.value>=s.value&&(s=e)},t),s.value===-1/0?{value:0}:s}function ja(e,t){let s={value:1/0};return Po(e,e=>{e.value<=s.value&&(s=e)},t),s.value===1/0?{value:0}:s}function Ya(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?Ho(n):n,{_X:o,_newX:n}}function Xa(e,t,s=!0,o=!1){const i=t.flat(),n=i.length;let{_X:r}=Ya(e,t,[[]]);r=r.length===n?Ho(r):r.slice(),Ga(r[0],i);const a=r.length,l=n-a-(s?1:0),c=[i],h=Ho(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=Ja(h,c);if(s||p.push([0]),!o)return p;const m=fi(g,Ho(g)),{inverted:f}=pi(m);if(void 0===f)throw new ys(vs("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=fi(f,[d]),t=fi(Ho([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 Ka(e,t,s,o){Ga(t,e),ai(s>=1,vs("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=Ja(n,i);return o||r.push([0]),r}function Ja(e,t){const s=fi(e,Ho(e)),{inverted:o}=pi(s);if(void 0===o)throw new ys(vs("Matrix is not invertible"));const i=fi(e,t);return Ho(fi(o,i))}function Qa(e,t,s){return e.reduce((e,o,i)=>e+o*Math.pow(t,s-i),0)}function el(e){return e.map(e=>e.map(e=>Math.exp(e)))}function tl(e){return e.map(e=>e.map(e=>Math.log(e)))}function sl(e,t,s,o){const{_X:i,_newX:n}=Ya(t,e,s),r=Xa(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:Ho(l)}const ol=[{value:!0,label:vs("b is calculated normally")},{value:!1,label:vs("b is forced to 1")}],il=[{value:!1,label:vs("do not return additional regression statistics")},{value:!0,label:vs("return additional regression statistics")}],nl=[{value:1,label:vs("order 1 (Linear)")},{value:2,label:vs("order 2 (Quadratic)")},{value:3,label:vs("order 3 (Cubic)")},{value:4,label:vs("order 4 (Quartic)")},{value:5,label:vs("order 5 (Quintic)")},{value:6,label:vs("order 6 (Sextic)")}],rl=[{value:!0,label:vs("Compute intercept")},{value:!1,label:vs("Force intercept to 0")}],al=[{value:0,label:vs("Minimum value")},{value:1,label:vs("First quartile (25th percentile)")},{value:2,label:vs("Median value (50th percentile)")},{value:3,label:vs("Third quartile (75th percentile)")},{value:4,label:vs("Maximum value")}];function ll(e,t){const s=[],o=[];let i=0,n=0;Fo([e],e=>{s.push(e),i+=1}),Fo([t],e=>{o.push(e),n+=1}),ai(i===n,vs("[[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 cl(e,t,s){const{flatDataX:o,flatDataY:i}=ll(e,t),n=i.length;li(n),s&&li(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 hl(e,t,s,o){let i=0;const n=s?ko:Lo,r=n(e,(e,t)=>(i+=1,e+t),0,o);li(i),t&&li(i-1);const a=r/i;return n(e,(e,t)=>e+Math.pow(t-a,2),0,o)/(i-(t?1:0))}function dl(e,t,s,o){const i=So(t,o);ai(s?0<=i&&i<=1:0<i&&i<1,vs("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));const n=[];let r,a=0;return Fo(e,e=>{const t=e?.value;"number"==typeof t&&(r=Zo(n,e,"nextSmaller","asc",n.length,(e,t)=>e[t]),n.splice(r+1,0,t),a++)}),ai(0!==a,ei),s||ai(1/(a+1)<=i&&i<=a/(a+1),vs("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),go(n,i,s)}const ul={description:vs("Average magnitude of deviations from mean."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to include in the sample."))],compute:function(...e){let t=0;const s=Lo(e,(e,s)=>(t+=1,e+s),0,this.locale);if(0===t)return new As(vs("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const o=s/t;return Lo(e,(e,t)=>e+Math.abs(o-t),0,this.locale)/t},isExported:!0},gl={description:vs("Numerical average value in a dataset, ignoring text."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to consider when calculating the average value."))],compute:function(...e){return{value:Wa(e,this.locale),format:mo(e[0])}},isExported:!0},pl=vs("[[FUNCTION_NAME]] has mismatched range sizes."),ml=vs("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),fl={description:vs("Weighted average."),args:[ls("values (number, range<number>, repeating)",vs("Value to average.")),ls("weights (number, range<number>, repeating)",vs("Weight for each corresponding value."))],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(!hi(i,n))return new ys(pl);if(_s(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=_s(n)?n?.[e][o].value:So(n,this.locale),l="number"==typeof r,c="number"==typeof a;if(l&&c){if(a<0)return new ys(ml);t+=r*a,s+=a}else if(l!==c)return new ys(vs("[[FUNCTION_NAME]] expects number values."))}else{const e=So(i,this.locale),o=_s(n)?n?.[0][0].value:So(n,this.locale);if("number"==typeof o){if(o<0)return new ys(ml);t+=e*o,s+=o}}}return 0===s?new As(vs("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):{value:t/s,format:mo(e[0])}}},vl={description:vs("Numerical average value in a dataset."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to consider when calculating the average value."))],compute:function(...e){let t=0;const s=ko(e,(e,s)=>(t+=1,e+s),0,this.locale);return 0===t?new As(vs("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):{value:s/t,format:mo(e[0])}},isExported:!0},bl={description:vs("Average of values depending on criteria."),args:[ls("criteria_range (number, range<number>)",vs("The range to check against criterion.")),ls("criterion (string)",vs("The pattern or test to apply to criteria_range.")),ls("average_range (number, range<number>, default=criteria_range)",vs("The range to average. If not included, criteria_range is used for the average instead."))],compute:function(e,t,s){const o=Ko(void 0===s?e:s);let i=0,n=0;return qo([e,t],(e,t)=>{const s=o[e]?.[t]?.value;"number"==typeof s&&(i+=1,n+=s)},this.locale),0===i?new As(vs("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):n/i},isExported:!0},Sl={description:vs("Average of values depending on multiple criteria."),args:[ls("average_range (range)",vs("The range to average.")),ls("criteria_range (any, range, repeating)",vs("Range to check.")),ls("criterion (string, repeating)",vs("Criterion to check."))],compute:function(e,...t){const s=Ko(e);let o=0,i=0;return qo(t,(e,t)=>{const n=s[e]?.[t]?.value;"number"==typeof n&&(o+=1,i+=n)},this.locale),0===o?new As(vs("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):i/o},isExported:!0},Cl={description:vs("The number of numeric values in dataset."),args:[ls("value (number, any, range<number>, repeating)",vs("Value or range to consider when counting."))],compute:function(...e){return $a(e,this.locale)},isExported:!0},yl={description:vs("The number of values in a dataset."),args:[ls("value (any, range, repeating)",vs("Value or range to consider when counting."))],compute:function(...e){return qa(e)},isExported:!0},Il={description:vs("The covariance of a dataset."),args:[ls("data_y (any, range)",vs("The range representing the array or matrix of dependent data.")),ls("data_x (any, range)",vs("The range representing the array or matrix of independent data."))],compute:function(e,t){return cl(e,t,!1)},isExported:!0},wl={description:vs("The covariance of a dataset."),args:[ls("data_y (any, range)",vs("The range representing the array or matrix of dependent data.")),ls("data_x (any, range)",vs("The range representing the array or matrix of independent data."))],compute:function(e,t){return cl(e,t,!1)},isExported:!0},El={description:vs("The sample covariance of a dataset."),args:[ls("data_y (any, range)",vs("The range representing the array or matrix of dependent data.")),ls("data_x (any, range)",vs("The range representing the array or matrix of independent data."))],compute:function(e,t){return cl(e,t,!0)},isExported:!0},Rl={description:vs("Calculates the expected y-value for a specified x based on a linear regression of a dataset."),args:[ls("x (number, range<number>)",vs("The value(s) on the x-axis to forecast.")),ls("data_y (range<number>)",vs("The range representing the array or matrix of dependent data.")),ls("data_x (range<number>)",vs("The range representing the array or matrix of independent data."))],compute:function(e,t,s){const{flatDataX:o,flatDataY:i}=ll(t,s);return 0===o.length||0===i.length?new Rs(ei):sl([i],[o],Uo(Ko(e),e=>So(e,this.locale)),!0)},isExported:!0},xl={description:vs("Fits points to exponential growth trend."),args:[ls("known_data_y (range<number>)",vs("The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.")),ls("known_data_x (range<number>, default={1;2;3;...})",vs("The values of the independent variable(s) corresponding with known_data_y.")),ls("new_data_x (any, range, default=known_data_x)",vs("The data points to return the y values for on the ideal curve fit.")),ls("b (boolean, default=TRUE)",vs("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."),ol)],compute:function(e,t=[[]],s=[[]],o={value:!0}){return 0===e.length||0===e[0].length?new ys(ti("known_data_y")):el(sl(tl(yo(e,"known_data_y")),yo(t,"known_data_x"),yo(s,"new_data_y"),Ao(o)))}},Tl={description:vs("Compute the intercept of the linear regression."),args:[ls("data_y (range<number>)",vs("The range representing the array or matrix of dependent data.")),ls("data_x (range<number>)",vs("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:s,flatDataY:o}=ll(e,t);if(0===s.length||0===o.length)return new Rs(ei);const[[],[i]]=Xa([s],[o]);return i},isExported:!0},Al={description:vs("Nth largest element from a data set."),args:[ls("data (any, range)",vs("Array or range containing the dataset to consider.")),ls("n (number)",vs("The rank from largest to smallest of the element to return."))],compute:function(e,t){const s=Math.trunc(So(t?.value,this.locale)),o=[];let i,n=0;Fo([e],e=>{"number"==typeof e?.value&&(i=Zo(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 ys(ei):n<s?new ys(vs("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s)):r},isExported:!0},Dl={description:vs("Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method."),args:[ls("data_y (range<number>)",vs("The range representing the array or matrix of dependent data.")),ls("data_x (range<number>, default={1;2;3;...})",vs("The range representing the array or matrix of independent data.")),ls("calculate_b (boolean, default=TRUE)",vs("A flag specifying whether to compute the slope or not"),ol),ls("verbose (boolean, default=FALSE)",vs("A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept"),il)],compute:function(e,t=[[]],s={value:!0},o={value:!1}){return 0===e.length||0===e[0].length?new ys(ti("data_y")):Xa(yo(t,"data_x"),yo(e,"data_y"),Ao(s),Ao(o))},isExported:!0},_l={description:vs("Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve."),args:[ls("data_y (range<number>)",vs("The range representing the array or matrix of dependent data.")),ls("data_x (range<number>, optional, default={1;2;3;...})",vs("The range representing the array or matrix of independent data.")),ls("calculate_b (boolean, default=TRUE)",vs("A flag specifying whether to compute the slope or not"),ol),ls("verbose (boolean, default=FALSE)",vs("A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept"),il)],compute:function(e,t=[[]],s={value:!0},o={value:!1}){if(0===e.length||0===e[0].length)return new ys(ti("data_y"));const i=Xa(yo(t,"data_x"),tl(yo(e,"data_y")),Ao(s),Ao(o));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},Ol={description:vs("Compute the Matthews correlation coefficient of a dataset."),args:[ls("data_x (range)",vs("The range representing the array or matrix of observed data.")),ls("data_y (range)",vs("The range representing the array or matrix of predicted data."))],compute:function(e,t){const s=e.flat(),o=t.flat();if(Ga(s,o),0===s.length||0===o.length)return new Rs(ei);const i=s.length;let n=0,r=0,a=0,l=0;for(let e=0;e<i;++e){const t=Ao(s[e]);t===Ao(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},Fl={description:vs("Maximum value in a numeric dataset."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to consider when calculating the maximum value."))],compute:function(...e){return Za(e,this.locale)},isExported:!0},Pl={description:vs("Maximum numeric value in a dataset."),args:[ls("value (any, range, repeating)",vs("Value or range to consider when calculating the maximum value."))],compute:function(...e){const t=ko(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:mo(e[0])}},isExported:!0},Ml={description:vs("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:[ls("range (range)",vs("The range of cells from which the maximum will be determined.")),ls("criteria_range (any, range, repeating)",vs("Range to evaluate criteria.")),ls("criterion (string, repeating)",vs("Criteria to check."))],compute:function(e,...t){let s=-1/0;return qo(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},Nl={description:vs("Median value in a numeric dataset."),args:[ls("value (any, range, repeating)",vs("Value or range to consider when calculating the median value."))],compute:function(...e){const t=[];return Po(e,e=>{t.push(e)},this.locale),{value:dl(t,{value:.5},!0,this.locale),format:mo(t[0])}},isExported:!0},Ll={description:vs("Minimum value in a numeric dataset."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to consider when calculating the minimum value."))],compute:function(...e){return ja(e,this.locale)},isExported:!0},kl={description:vs("Minimum numeric value in a dataset."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to consider when calculating the minimum value."))],compute:function(...e){const t=ko(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:mo(e[0])}},isExported:!0},Vl={description:vs("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:[ls("range (range)",vs("The range of cells from which the minimum will be determined.")),ls("criteria_range (any, range, repeating)",vs("Range to evaluate criteria.")),ls("criterion (string, repeating)",vs("Criterion to check."))],compute:function(e,...t){let s=1/0;return qo(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 Ul(e,t){const{flatDataX:s,flatDataY:o}=ll(e,t);if(0===s.length||0===o.length)return new Rs(ei);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 Hl={description:vs("Compute the Pearson product-moment correlation coefficient of a dataset."),args:[ls("data_y (range<number>)",vs("The range representing the array or matrix of dependent data.")),ls("data_x (range<number>)",vs("The range representing the array or matrix of independent data."))],compute:function(e,t){return Ul(e,t)},isExported:!0},zl=Hl,Bl={description:vs("Value at a given percentile of a dataset."),args:[ls("data (any, range)",vs("The array or range containing the dataset to consider.")),ls("percentile (number)",vs("The percentile whose value within data will be calculated and returned."))],compute:function(e,t){return Wl.compute.bind(this)(e,t)},isExported:!0},Gl={description:vs("Value at a given percentile of a dataset exclusive of 0 and 1."),args:[ls("data (any, range)",vs("The array or range containing the dataset to consider.")),ls("percentile (number)",vs("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned."))],compute:function(e,t){return{value:dl([e],t,!1,this.locale),format:mo(e)}},isExported:!0},Wl={description:vs("Value at a given percentile of a dataset."),args:[ls("data (any, range)",vs("The array or range containing the dataset to consider.")),ls("percentile (number)",vs("The percentile whose value within data will be calculated and returned."))],compute:function(e,t){return{value:dl([e],t,!0,this.locale),format:mo(e)}},isExported:!0},$l={description:vs("Compute the coefficients of polynomial regression of the dataset."),args:[ls("data_y (range<number>)",vs("The range representing the array or matrix of dependent data.")),ls("data_x (range<number>)",vs("The range representing the array or matrix of independent data.")),ls("order (number)",vs("The order of the polynomial to fit the data, between 1 and 6."),nl),ls("intercept (boolean, default=TRUE)",vs("A flag specifying whether to compute the intercept or not."),rl)],compute:function(e,t,s,o={value:!0}){const{flatDataX:i,flatDataY:n}=ll(e,t);return 0===i.length||0===n.length?new Rs(ei):Ka(n,i,So(s,this.locale),Ao(o))},isExported:!1},ql={description:vs("Predict value by computing a polynomial regression of the dataset."),args:[ls("x (number, range<number>)",vs("The value(s) on the x-axis to forecast.")),ls("data_y (range<number>)",vs("The range representing the array or matrix of dependent data.")),ls("data_x (range<number>)",vs("The range representing the array or matrix of independent data.")),ls("order (number)",vs("The order of the polynomial to fit the data, between 1 and 6."),nl),ls("intercept (boolean, default=TRUE)",vs("A flag specifying whether to compute the intercept or not."),rl)],compute:function(e,t,s,o,i={value:!0}){const n=So(o,this.locale),{flatDataX:r,flatDataY:a}=ll(t,s);if(0===r.length||0===a.length)return new Rs(ei);const l=Ka(a,r,n,Ao(i)).flat();return Uo(Ko(e),e=>Qa(l,So(e,this.locale),n))},isExported:!1},Zl={description:vs("Value nearest to a specific quartile of a dataset."),args:[ls("data (any, range)",vs("The array or range containing the dataset to consider.")),ls("quartile_number (number)",vs("Which quartile value to return."),al)],compute:function(e,t){return Yl.compute.bind(this)(e,t)},isExported:!0},jl={description:vs("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:[ls("data (any, range)",vs("The array or range containing the dataset to consider.")),ls("quartile_number (number)",vs("Which quartile value, exclusive of 0 and 4, to return."),[{value:1,label:vs("First quartile (25th percentile)")},{value:2,label:vs("Median value (50th percentile)")},{value:3,label:vs("Third quartile (75th percentile)")}])],compute:function(e,t){return{value:dl([e],{value:.25*Math.trunc(So(t,this.locale))},!1,this.locale),format:mo(e)}},isExported:!0},Yl={description:vs("Value nearest to a specific quartile of a dataset."),args:[ls("data (any, range)",vs("The array or range containing the dataset to consider.")),ls("quartile_number (number)",vs("Which quartile value to return."),al)],compute:function(e,t){return{value:dl([e],{value:.25*Math.trunc(So(t,this.locale))},!0,this.locale),format:mo(e)}},isExported:!0},Xl={description:vs("Returns the rank of a specified value in a dataset."),args:[ls("value (number)",vs("The value whose rank will be determined.")),ls("data (range)",vs("The range containing the dataset to consider.")),ls("is_ascending (boolean, default=FALSE)",vs("Whether to consider the values in data in descending or ascending order."),[{value:!1,label:vs("Descending")},{value:!0,label:vs("Ascending")}])],compute:function(e,t,s={value:!1}){const o=Ao(s),i=So(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=So(t,this.locale);e===i?r=!0:e>i!==o&&n++}return r?n:new Rs(vs("Value not found in the given data."))},isExported:!0},Kl={description:vs("Compute the square of r, the Pearson product-moment correlation coefficient of a dataset."),args:[ls("data_y (range<number>)",vs("The range representing the array or matrix of dependent data.")),ls("data_x (range<number>)",vs("The range representing the array or matrix of independent data."))],compute:function(e,t){const s=Ul(e,t);if(s instanceof Error)throw s;return Math.pow(s,2)},isExported:!0},Jl={description:vs("Compute the slope of the linear regression."),args:[ls("data_y (range<number>)",vs("The range representing the array or matrix of dependent data.")),ls("data_x (range<number>)",vs("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:s,flatDataY:o}=ll(e,t);if(0===s.length||0===o.length)return new Rs(ei);const[[i]]=Xa([s],[o]);return i},isExported:!0},Ql={description:vs("Nth smallest element in a data set."),args:[ls("data (any, range)",vs("The array or range containing the dataset to consider.")),ls("n (number)",vs("The rank from smallest to largest of the element to return."))],compute:function(e,t){const s=Math.trunc(So(t?.value,this.locale)),o=[];let i,n=0;Fo([e],e=>{"number"==typeof e?.value&&(i=Zo(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 ys(ei):n<s?new ys(vs("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s)):r},isExported:!0},ec={description:vs("Compute the Spearman rank correlation coefficient of a dataset."),args:[ls("data_y (range<number>)",vs("The range representing the array or matrix of dependent data.")),ls("data_x (range<number>)",vs("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:s,flatDataY:o}=ll(t,e);if(0===s.length||0===o.length)return new Rs(ei);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},tc={description:vs("Standard deviation."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to include in the sample."))],compute:function(...e){return Math.sqrt(cc.compute.bind(this)(...e))},isExported:!0},sc={description:vs("Standard deviation of entire population."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to include in the population."))],compute:function(...e){return Math.sqrt(hc.compute.bind(this)(...e))},isExported:!0},oc={description:vs("Standard deviation."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to include in the sample."))],compute:function(...e){return Math.sqrt(dc.compute.bind(this)(...e))},isExported:!0},ic={description:vs("Standard deviation of sample (text as 0)."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to include in the sample."))],compute:function(...e){return Math.sqrt(uc.compute.bind(this)(...e))},isExported:!0},nc={description:vs("Standard deviation of entire population."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to include in the population."))],compute:function(...e){return Math.sqrt(gc.compute.bind(this)(...e))},isExported:!0},rc={description:vs("Standard deviation of entire population (text as 0)."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to include in the population."))],compute:function(...e){return Math.sqrt(pc.compute.bind(this)(...e))},isExported:!0},ac={description:vs("Calculates the standard error of the predicted y-value for each x in the regression of a dataset."),args:[ls("data_y (range<number>)",vs("The range representing the array or matrix of dependent data.")),ls("data_x (range<number>)",vs("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:s,flatDataY:o}=ll(e,t);if(0===s.length||0===o.length)return new Rs(ei);return Xa([s],[o],!0,!0)[1][2]},isExported:!0},lc={description:vs("Fits points to linear trend derived via least-squares."),args:[ls("known_data_y (number, range<number>)",vs("The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.")),ls("known_data_x (number, range<number>, optional, default={1;2;3;...})",vs("The values of the independent variable(s) corresponding with known_data_y.")),ls("new_data_x (number, range<number>, optional, default=known_data_x)",vs("The data points to return the y values for on the ideal curve fit.")),ls("b (boolean, optional, default=TRUE)",vs("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."),ol)],compute:function(e,t=[[]],s=[[]],o={value:!0}){return 0===e.length||0===e[0].length?new ys(ti("known_data_y")):sl(yo(e,"known_data_y"),yo(t,"known_data_x"),yo(s,"new_data_y"),Ao(o))}},cc={description:vs("Variance."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to include in the sample."))],compute:function(...e){return hl(e,!0,!1,this.locale)},isExported:!0},hc={description:vs("Variance of entire population."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to include in the population."))],compute:function(...e){return hl(e,!1,!1,this.locale)},isExported:!0},dc={description:vs("Variance."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to include in the sample."))],compute:function(...e){return hl(e,!0,!1,this.locale)},isExported:!0},uc={description:vs("Variance of sample (text as 0)."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to include in the sample."))],compute:function(...e){return hl(e,!0,!0,this.locale)},isExported:!0},gc={description:vs("Variance of entire population."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to include in the population."))],compute:function(...e){return hl(e,!1,!1,this.locale)},isExported:!0},pc={description:vs("Variance of entire population (text as 0)."),args:[ls("value (number, range<number>, repeating)",vs("Value or range to include in the population."))],compute:function(...e){return hl(e,!1,!0,this.locale)},isExported:!0};var mc=Object.freeze({__proto__:null,AVEDEV:ul,AVERAGE:gl,AVERAGEA:vl,AVERAGEIF:bl,AVERAGEIFS:Sl,AVERAGE_WEIGHTED:fl,CORREL:zl,COUNT:Cl,COUNTA:yl,COVAR:Il,COVARIANCE_P:wl,COVARIANCE_S:El,FORECAST:Rl,GROWTH:xl,INTERCEPT:Tl,LARGE:Al,LINEST:Dl,LOGEST:_l,MATTHEWS:Ol,MAX:Fl,MAXA:Pl,MAXIFS:Ml,MEDIAN:Nl,MIN:Ll,MINA:kl,MINIFS:Vl,PEARSON:Hl,PERCENTILE:Bl,PERCENTILE_EXC:Gl,PERCENTILE_INC:Wl,POLYFIT_COEFFS:$l,POLYFIT_FORECAST:ql,QUARTILE:Zl,QUARTILE_EXC:jl,QUARTILE_INC:Yl,RANK:Xl,RSQ:Kl,SLOPE:Jl,SMALL:Ql,SPEARMAN:ec,STDEV:tc,STDEVA:ic,STDEVP:nc,STDEVPA:rc,STDEV_P:sc,STDEV_S:oc,STEYX:ac,TREND:lc,VAR:cc,VARA:uc,VARP:gc,VARPA:pc,VAR_P:hc,VAR_S:dc});function fc(e,t,s,o){const i=new Map,n=e.length;for(let t=n-1;t>=0;t--)i.set(Ro(e[t][0]).toUpperCase(),t);const r=t?.value;if("number"!=typeof r&&"string"!=typeof r)throw new ys(vs("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 ys(vs("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=Ro(t).toUpperCase();if(a=i.get(e)??-1,-1===a)throw new ys(vs("The field (%s) must be one of %s.",Ro(t),[...i.keys()].toString()))}const l=s[0].length;if(l<2)throw new ys(vs("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=Ro(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}qo(n,(e,t)=>{c.add(t)},o,!0)}}const d=e[a];return[...c].map(e=>d[e+1])}const vc=[ls("database (range)",vs("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.")),ls("field (number, string)",vs("Indicates which column in database contains the values to be extracted and operated on.")),ls("criteria (range)",vs("An array or range containing zero or more criteria to filter the database values by before operating."))],bc={description:vs("Average of a set of values from a table-like range."),args:vc,compute:function(e,t,s){const o=fc(e,t,s,this.locale);return gl.compute.bind(this)([o])},isExported:!0},Sc={description:vs("Counts values from a table-like range."),args:vc,compute:function(e,t,s){const o=fc(e,t,s,this.locale);return Cl.compute.bind(this)([o])},isExported:!0},Cc={description:vs("Counts values and text from a table-like range."),args:vc,compute:function(e,t,s){const o=fc(e,t,s,this.locale);return yl.compute.bind(this)([o])},isExported:!0},yc={description:vs("Single value from a table-like range."),args:vc,compute:function(e,t,s){const o=fc(e,t,s,this.locale);return 1!==o.length?new ys(vs("More than one match found in DGET evaluation.")):o[0]},isExported:!0},Ic={description:vs("Maximum of values from a table-like range."),args:vc,compute:function(e,t,s){const o=fc(e,t,s,this.locale);return Fl.compute.bind(this)([o])},isExported:!0},wc={description:vs("Minimum of values from a table-like range."),args:vc,compute:function(e,t,s){const o=fc(e,t,s,this.locale);return Ll.compute.bind(this)([o])},isExported:!0},Ec={description:vs("Product of values from a table-like range."),args:vc,compute:function(e,t,s){const o=fc(e,t,s,this.locale);return va.compute.bind(this)([o])},isExported:!0},Rc={description:vs("Standard deviation of population sample from table."),args:vc,compute:function(e,t,s){const o=fc(e,t,s,this.locale);return tc.compute.bind(this)([o])},isExported:!0},xc={description:vs("Standard deviation of entire population from table."),args:vc,compute:function(e,t,s){const o=fc(e,t,s,this.locale);return nc.compute.bind(this)([o])},isExported:!0},Tc={description:vs("Sum of values from a table-like range."),args:vc,compute:function(e,t,s){const o=fc(e,t,s,this.locale);return Ma.compute.bind(this)([o])},isExported:!0},Ac={description:vs("Variance of population sample from table-like range."),args:vc,compute:function(e,t,s){const o=fc(e,t,s,this.locale);return cc.compute.bind(this)([o])},isExported:!0},Dc={description:vs("Variance of a population from a table-like range."),args:vc,compute:function(e,t,s){const o=fc(e,t,s,this.locale);return gc.compute.bind(this)([o])},isExported:!0};var _c=Object.freeze({__proto__:null,DAVERAGE:bc,DCOUNT:Sc,DCOUNTA:Cc,DGET:yc,DMAX:Ic,DMIN:wc,DPRODUCT:Ec,DSTDEV:Rc,DSTDEVP:xc,DSUM:Tc,DVAR:Ac,DVARP:Dc});const Oc=[{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:";"}],Fc=Oc[0],Pc=["%"],Mc="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(Pc);function Nc(e,t=Fc){e=Ge(e);const s=new Qe(e),o=[],i=He.test(e)?Zc:jc;for(;!s.isOver();){let e=Yc(s)||i(s)||Uc(s,t)||Vc(s)||Hc(s)||Gc(s)||Lc(s)||Xc(s)||Bc(s,t)||qc(s);e||(e={type:"UNKNOWN",value:s.shift()}),o.push(e)}return o}function Lc(e){return"?"===e.current?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const kc={"(":{type:"LEFT_PAREN",value:"("},")":{type:"RIGHT_PAREN",value:")"}};function Vc(e){if("("===e.current||")"===e.current){const t=e.shift();return kc[t]}return null}function Uc(e,t){if(e.current===t.formulaArgSeparator){return{type:"ARG_SEPARATOR",value:e.shift()}}return null}function Hc(e){for(const t of Mc)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:"OPERATOR",value:t};return null}const zc=new Set("0123456789");function Bc(e,t){if(!zc.has(e.current)&&e.current!==t.decimalSeparator)return null;const s=e.remaining().match(ao(t.decimalSeparator));return s?(e.advanceBy(s[0].length),{type:"NUMBER",value:s[0]}):null}function Gc(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 Wc=/\p{L}|\p{N}|_|\.|!|\$/u,$c=new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$");function qc(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&&($c.has(e.current)||e.current.match(Wc));)t+=e.shift();if(t.length){const e=t;return Kn.test(e)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}function Zc(e){let t="";for(;" "===e.current||e.current&&e.current.match(He);)t+=e.shift();return t?{type:"SPACE",value:t}:null}function jc(e){let t="";for(;" "===e.current;)t+=e.shift();return t?{type:"SPACE",value:t}:null}function Yc(e){let t=0;for(;e.current===X;)t++,e.shift();return t?{type:"SPACE",value:X.repeat(t)}:null}function Xc(e){return e.currentStartsWith(Ss.InvalidReference)?(e.advanceBy(Ss.InvalidReference.length),{type:"INVALID_REFERENCE",value:Ss.InvalidReference}):null}function Kc(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{mn(1,{locale:e,format:"#,##0.00"}),mn(1,{locale:e,format:e.dateFormat}),mn(1,{locale:e,format:e.timeFormat})}catch{return!1}return!0}function Jc(e,t){return ot(e)?sh(e,t):nh(e,t)}function Qc(e,t){return ot(e)?sh(e,t):function(e,t){if(qs(e,t)){const s=So(e,t);let o=Fc.dateFormat;return Number.isInteger(s)||(o+=" "+Fc.timeFormat),mn(s,{locale:Fc,format:o})}return nh(e,t)}(e,t)}function eh(e,t){return e.startsWith("=")?oh(e,t):function(e,t){if(qs(e,Fc)){const s=So(e,Fc);let o=t.dateFormat;return Number.isInteger(s)||(o+=" "+t.timeFormat),mn(s,{locale:t,format:o})}return function(e,t){if("."===t.decimalSeparator||!co(e,Fc))return e;const s=xn(Fc);return e.replace(s,e=>e.replace(".",t.decimalSeparator))}(e,t)}(e,t)}function th(e,t){return ot(e)?sh(e,t):nh(e,t)}function sh(e,t){return ih(e.startsWith("+")?"="+e.slice(1):e,t,Fc)}function oh(e,t){return ih(e,Fc,t)}function ih(e,t,s){if(t.formulaArgSeparator===s.formulaArgSeparator&&t.decimalSeparator===s.decimalSeparator)return e;const o=Nc(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 nh(e,t){return"."!==t.decimalSeparator&&co(e,t)?(t.thousandsSeparator&&(e=e.replaceAll(t.thousandsSeparator,"")),e.replace(t.decimalSeparator,".")):e}function rh(e,t){return ch(e,e=>Qc(e,t))}function ah(e,t){return ch(e,e=>eh(e,t))}function lh(e,t){const s=ae(e);return s.criterion.values=s.criterion.values.map(e=>eh(e,t)),s}function ch(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=hh(e.minimum,t),e.maximum=hh(e.maximum,t),e.midpoint&&(e.midpoint=hh(e.midpoint,t)),e;case"IconSetRule":return e.lowerInflectionPoint.value=t(e.lowerInflectionPoint.value),e.upperInflectionPoint.value=t(e.upperInflectionPoint.value),e}}function hh(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 dh(e){return e.dateFormat+" "+e.timeFormat}const uh=vs("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."),gh=vs("There must be both positive and negative values in cashflow_amounts."),ph=e=>vs("The cost (%s) must be positive or null.",e),mh=e=>vs("The frequency (%s) must be one of %s",e,[1,2,4].toString()),fh=e=>vs("The day_count_convention (%s) must be between 0 and 4 inclusive.",e),vh=e=>vs("The depreciation factor (%s) must be strictly positive.",e),bh=e=>vs("The discount (%s) must be strictly positive.",e),Sh=e=>vs("The discount (%s) must be smaller than 1.",e),Ch=e=>vs("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e),yh=(e,t)=>vs("The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).",{first:e,last:t}),Ih=e=>vs("The first_period (%s) must be strictly positive.",e),wh=e=>vs("The investment (%s) must be strictly positive.",e),Eh=(e,t)=>vs("The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).",{last:e,nPeriods:t}),Rh=e=>vs("The last_period (%s) must be strictly positive.",e),xh=e=>vs("The life (%s) must be strictly positive.",e),Th=(e,t)=>vs("The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).",{maturity:t,settlement:e}),Ah=e=>vs("The number_of_periods (%s) must be strictly positive.",e),Dh=e=>vs("The periods_by_year (%s) must be strictly positive.",e),_h=(e,t)=>vs("The period (%(period)s) must be less than or equal life (%(life)s).",{period:e,life:t}),Oh=e=>vs("The period (%s) must be strictly positive.",e),Fh=e=>vs("The present_value (%s) must be strictly positive.",e),Ph=e=>vs("The price (%s) must be strictly positive.",e),Mh=e=>vs("The rate_guess (%s) must be strictly greater than -1.",e),Nh=e=>vs("The rate (%s) must be positive or null.",e),Lh=e=>vs("The rate (%s) must be strictly positive.",e),kh=e=>vs("The redemption (%s) must be strictly positive.",e),Vh=e=>vs("The salvage (%s) must be positive or null.",e),Uh=(e,t)=>vs("The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).",{settlement:e,maturity:t}),Hh=e=>vs("The unit (%s) must be strictly positive.",e),zh=e=>vs("The yield (%s) must be positive or null.",e);function Bh(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function Gh(e){return![0,1,2,3,4].includes(e)}function Wh(e){return![1,2,4].includes(e)}function $h(e,t,s){const o=Do(e,s),i=Do(t,s),n=Do(e,s);return n.setFullYear(o.getFullYear()+1),i.getTime()<=n.getTime()}const qh=[{value:0,label:vs("US (NASD) 30/360")},{value:1,label:vs("Actual/Actual")},{value:2,label:vs("Actual/360")},{value:3,label:vs("Actual/365")},{value:4,label:vs("European 30/360")}];var Zh;!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"}(Zh||(Zh={}));const jh={description:vs("Converts year/month/day into a date."),args:[ls("year (number)",vs("The year component of the date.")),ls("month (number)",vs("The month component of the date.")),ls("day (number)",vs("The day component of the date."))],compute:function(e,t,s){let o=Math.trunc(So(e,this.locale));const i=Math.trunc(So(t,this.locale)),n=Math.trunc(So(s,this.locale));if(o<0||o>9999)return new ys(vs("The year (%s) must be between 0 and 9999 inclusive.",o.toString()));o<1900&&(o+=1900);const r=Xs(new Fs(o,i-1,n));return r<0?new ys(vs("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")):{value:r,format:this.locale.dateFormat}},isExported:!0},Yh={description:vs("Calculates the number of days, months, or years between two dates."),args:[ls("start_date (date)",vs("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.")),ls("end_date (date)",vs("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.")),ls("unit (string)",vs("A text abbreviation for unit of time."),[{value:"Y",label:vs("The number of whole years between start_date and end_date")},{value:"M",label:vs("The number of whole months between start_date and end_date")},{value:"D",label:vs("The number of days between start_date and end_date")},{value:"MD",label:vs("The number of days between start_date and end_date after subtracting whole months")},{value:"YM",label:vs("The number of whole months between start_date and end_date after subtracting whole years")},{value:"YD",label:vs("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=Ro(s).toUpperCase();if(!Object.values(Zh).includes(o))return new ys(((e,t)=>{const s=e.map(e=>`'${e}'`).join(", ");return vs("The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.",t,s)})(Object.values(Zh),Ro(s)));const i=Math.trunc(So(e,this.locale)),n=Math.trunc(So(t,this.locale)),r=Ys(i),a=Ys(n);if(n<i)return new ys(vs("start_date (%s) should be on or before end_date (%s).",r.toLocaleDateString(),a.toLocaleDateString()));switch(o){case Zh.WHOLE_YEARS:return no(r,a);case Zh.WHOLE_MONTHS:return oo(r,a);case Zh.WHOLE_DAYS:return io(r,a);case Zh.MONTH_WITHOUT_WHOLE_YEARS:return oo(r,a)-12*no(r,a);case Zh.DAYS_WITHOUT_WHOLE_MONTHS:let e=a.getDate()-r.getDate();if(e<0){e=Js(new Fs(a.getFullYear(),a.getMonth()-1,1))-Math.abs(e)}return e;case Zh.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR:{if(function(e,t){return so(e,t,1)<1}(i,n))return io(r,a);const e=new Fs(r.getFullYear(),a.getMonth(),a.getDate());let t=io(r,e);return t<0&&(e.setFullYear(r.getFullYear()+1),t=io(r,e)),t}}},isExported:!0},Xh={description:vs("Converts a date string to a date value."),args:[ls("date_string (string)",vs("The string representing the date."))],compute:function(e){const t=Ro(e),s=js(t,this.locale);return null===s?new ys(vs("The date_string (%s) cannot be parsed to date/time.",t.toString())):Math.trunc(s.value)},isExported:!0},Kh={description:vs("Day of the month that a specific date falls on."),args:[ls("date (string)",vs("The date from which to extract the day."))],compute:function(e){return Do(e,this.locale).getDate()},isExported:!0},Jh={description:vs("Number of days between two dates."),args:[ls("end_date (date)",vs("The end of the date range.")),ls("start_date (date)",vs("The start of the date range."))],compute:function(e,t){const s=Do(e,this.locale),o=Do(t,this.locale),i=s.getTime()-o.getTime();return Math.round(i/Ms)},isExported:!0},Qh=!1,ed={description:vs("Number of days between two dates on a 360-day year (months of 30 days)."),args:[ls("start_date (date)",vs("The start date to consider in the calculation.")),ls("end_date (date)",vs("The end date to consider in the calculation.")),ls("method (boolean, default=false)",vs("An indicator of what day count method to use."),[{value:!1,label:vs("U.S. NASD method (default)")},{value:!0,label:vs("European method")}])],compute:function(e,t,s={value:Qh}){const o=Math.trunc(So(e,this.locale)),i=Math.trunc(So(t,this.locale)),n=so(o,i,Ao(s)?4:0);return Math.sign(i-o)*Math.round(360*n)},isExported:!0},td={description:vs("Date a number of months before/after another date."),args:[ls("start_date (date)",vs("The date from which to calculate the result.")),ls("months (number)",vs("The number of months before (negative) or after (positive) 'start_date' to calculate."))],compute:function(e,t){return{value:Xs(eo(Do(e,this.locale),Math.trunc(So(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},sd={description:vs("Last day of a month before or after a date."),args:[ls("start_date (date)",vs("The date from which to calculate the result.")),ls("months (number)",vs("The number of months before (negative) or after (positive) 'start_date' to consider."))],compute:function(e,t){const s=Do(e,this.locale),o=Math.trunc(So(t,this.locale)),i=s.getFullYear(),n=s.getMonth();return{value:Xs(new Fs(i,n+o+1,0)),format:this.locale.dateFormat}},isExported:!0},od={description:vs("Hour component of a specific time."),args:[ls("time (date)",vs("The time from which to calculate the hour component."))],compute:function(e){return Do(e,this.locale).getHours()},isExported:!0},id={description:vs("ISO week number of the year."),args:[ls("date (date)",vs("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=Do(e,this.locale),s=t.getFullYear();let o=1;for(;4!==new Fs(s,0,o).getDay();)o+=1;const i=new Fs(s,0,o-3);let n=31;for(;4!==new Fs(s,11,n).getDay();)n-=1;const r=new Fs(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 Fs(s,11,n+3+1);break;case-1:let e=1;for(;4!==new Fs(s-1,0,e).getDay();)e+=1;l=new Fs(s-1,0,e-3)}const c=(t.getTime()-l.getTime())/Ms;return Math.floor(c/7)+1},isExported:!0},nd={description:vs("Minute component of a specific time."),args:[ls("time (date)",vs("The time from which to calculate the minute component."))],compute:function(e){return Do(e,this.locale).getMinutes()},isExported:!0},rd={description:vs("Month of the year a specific date falls in"),args:[ls("date (date)",vs("The date from which to extract the month."))],compute:function(e){return Do(e,this.locale).getMonth()+1},isExported:!0},ad={description:vs("Net working days between two provided days."),args:[ls("start_date (date)",vs("The start date of the period from which to calculate the number of net working days.")),ls("end_date (date)",vs("The end date of the period from which to calculate the number of net working days.")),ls("holidays (date, range<date>, optional)",vs("A range or array constant containing the date serial numbers to consider holidays."))],compute:function(e,t,s){return hd.compute.bind(this)(e,t,{value:1},s)},isExported:!0};function ld(e){const t=e?.value;if("string"==typeof t){ai(7===t.length&&[...t].every(e=>"0"===e||"1"===e),vs('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 ai(1<=t&&t<=7||11<=t&&t<=17,vs("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 ys(vs("The weekend must be a number or a string."))}const cd=[{value:1,label:vs("Saturday/Sunday are weekends")},{value:2,label:vs("Sunday/Monday are weekends")},{value:3,label:vs("Monday/Tuesday are weekends")},{value:4,label:vs("Tuesday/Wednesday are weekends")},{value:5,label:vs("Wednesday/Thursday are weekends")},{value:6,label:vs("Thursday/Friday are weekends")},{value:7,label:vs("Friday/Saturday are weekends")},{value:11,label:vs("Sunday is the only weekend")},{value:12,label:vs("Monday is the only weekend")},{value:13,label:vs("Tuesday is the only weekend")},{value:14,label:vs("Wednesday is the only weekend")},{value:15,label:vs("Thursday is the only weekend")},{value:16,label:vs("Friday is the only weekend")},{value:17,label:vs("Saturday is the only weekend")}],hd={description:vs("Net working days between two dates (specifying weekends)."),args:[ls("start_date (date)",vs("The start date of the period from which to calculate the number of net working days.")),ls("end_date (date)",vs("The end date of the period from which to calculate the number of net working days.")),ls("weekend (any, default=1)",vs("A number or string representing which days of the week are considered weekends."),cd),ls("holidays (date, range<date>, optional)",vs("A range or array constant containing the dates to consider as holidays."))],compute:function(e,t,s={value:1},o){const i=Do(e,this.locale),n=Do(t,this.locale),r=ld(s),a=new Set;void 0!==o&&Fo([o],e=>{const t=Do(e,this.locale);a.add(t.getTime())});const l=i.getTime()>n.getTime(),c=Fs.fromTimestamp((l?i:n).getTime()),h=Fs.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},dd={description:vs("Current date and time as a date value."),args:[],compute:function(){const e=Fs.now(),t=e.getTime()-Ps.getTime(),s=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/Ms)+s,format:dh(this.locale)}},isExported:!0},ud={description:vs("Minute component of a specific time."),args:[ls("time (date)",vs("The time from which to calculate the second component."))],compute:function(e){return Do(e,this.locale).getSeconds()},isExported:!0},gd={description:vs("Converts hour/minute/second into a time."),args:[ls("hour (number)",vs("The hour component of the time.")),ls("minute (number)",vs("The minute component of the time.")),ls("second (number)",vs("The second component of the time."))],compute:function(e,t,s){let o=Math.trunc(So(e,this.locale)),i=Math.trunc(So(t,this.locale)),n=Math.trunc(So(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 ys(vs("The function [[FUNCTION_NAME]] result cannot be negative")):{value:o/24+i/1440+n/86400,format:this.locale.timeFormat}},isExported:!0},pd={description:vs("Converts a time string into its serial number representation."),args:[ls("time_string (string)",vs("The string that holds the time representation."))],compute:function(e){const t=Ro(e),s=js(t,this.locale);if(null===s)return new ys(vs("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},md={description:vs("Current date as a date value."),args:[],compute:function(){const e=Fs.now();return{value:Xs(new Fs(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},fd={description:vs("Day of the week of the date provided (as number)."),args:[ls("date (date)",vs("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.")),ls("type (number, default=1)",vs("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1."),[{value:1,label:vs("Numbers 1 (Sunday) trough 7 (Saturday)")},{value:2,label:vs("Numbers 1 (Monday) trough 7 (Sunday)")},{value:3,label:vs("Numbers 0 (Monday) trough 6 (Sunday)")},{value:11,label:vs("Numbers 1 (Monday) trough 7 (Sunday)")},{value:12,label:vs("Numbers 1 (Tuesday) trough 7 (Monday)")},{value:13,label:vs("Numbers 1 (Wednesday) trough 7 (Tuesday)")},{value:14,label:vs("Numbers 1 (Thursday) trough 7 (Wednesday)")},{value:15,label:vs("Numbers 1 (Friday) trough 7 (Thursday)")},{value:16,label:vs("Numbers 1 (Saturday) trough 7 (Friday)")},{value:17,label:vs("Numbers 1 (Sunday) trough 7 (Saturday)")}])],compute:function(e,t={value:1}){const s=Do(e,this.locale),o=Math.round(So(t,this.locale)),i=s.getDay();if(!(1<=o&&o<=3||11<=o&&o<=17))return new ys(vs("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},vd={description:vs("Week number of the year."),args:[ls("date (date)",vs("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.")),ls("type (number, default=1)",vs("A number representing the day that a week starts on. Sunday = 1."),[{value:1,label:vs("Sunday")},{value:2,label:vs("Monday")},{value:11,label:vs("Monday")},{value:12,label:vs("Tuesday")},{value:13,label:vs("Wednesday")},{value:14,label:vs("Thursday")},{value:15,label:vs("Friday")},{value:16,label:vs("Saturday")},{value:17,label:vs("Sunday")},{value:21,label:vs("ISO week number (Monday as first day of the week)")}])],compute:function(e,t={value:1}){const s=Do(e,this.locale),o=Math.round(So(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(o))return new ys(vs("The type (%s) is out of range.",o.toString()));if(21===o)return id.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 Fs(n,0,r);for(;a.getDay()!==i;)r+=1,a=new Fs(n,0,r);const l=(s.getTime()-a.getTime())/Ms;return l<0?1:Math.floor(l/7)+(1===r?1:2)},isExported:!0},bd={description:vs("Date after a number of workdays."),args:[ls("start_date (date)",vs("The date from which to begin counting.")),ls("num_days (number)",vs("The number of working days to advance from start_date. If negative, counts backwards.")),ls("holidays (date, range<date>, optional)",vs("A range or array constant containing the dates to consider holidays."))],compute:function(e,t,s={value:null}){return Sd.compute.bind(this)(e,t,{value:1},s)},isExported:!0},Sd={description:vs("Date after a number of workdays (specifying weekends)."),args:[ls("start_date (date)",vs("The date from which to begin counting.")),ls("num_days (number)",vs("The number of working days to advance from start_date. If negative, counts backwards.")),ls("weekend (any, default=1)",vs("A number or string representing which days of the week are considered weekends."),cd),ls("holidays (date, range<date>, optional)",vs("A range or array constant containing the dates to consider holidays."))],compute:function(e,t,s={value:1},o){const i=Do(e,this.locale),n=Math.trunc(So(t,this.locale));if("1111111"===s.value)return new ys(vs("The weekend must be different from '1111111'."));const r=ld(s),a=new Set;void 0!==o&&Fo([o],e=>{const t=Do(e,this.locale);a.add(t.getTime())});const l=Fs.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-Ps.getTime();return{value:Math.round(u/Ms),format:this.locale.dateFormat}},isExported:!0},Cd={description:vs("Year specified by a given date."),args:[ls("date (date)",vs("The date from which to extract the year."))],compute:function(e){return Do(e,this.locale).getFullYear()},isExported:!0},yd={description:vs("Exact number of years between two dates."),args:[ls("start_date (date)",vs("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.")),ls("end_date (date)",vs("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.")),ls("day_count_convention (number, default=0)",vs("An indicator of what day count method to use."),qh)],compute:function(e,t,s={value:0}){const o=Math.trunc(So(e,this.locale)),i=Math.trunc(So(t,this.locale)),n=Math.trunc(So(s,this.locale));return o<0?new ys(vs("The start_date (%s) must be positive or null.",o)):i<0?new ys(vs("The end_date (%s) must be positive or null.",i)):0>n||n>4?new ys(vs("The day_count_convention (%s) must be between 0 and 4 inclusive.",n)):so(o,i,n)}},Id={description:vs("First day of the month preceding a date."),args:[ls("date (date)",vs("The date from which to calculate the result."))],compute:function(e){const t=Do(e,this.locale),s=t.getFullYear(),o=t.getMonth();return{value:Xs(new Fs(s,o,1)),format:this.locale.dateFormat}}},wd={description:vs("Last day of the month following a date."),args:[ls("date (date)",vs("The date from which to calculate the result."))],compute:function(e){return sd.compute.bind(this)(e,{value:0})}},Ed={description:vs("Quarter of the year a specific date falls in"),args:[ls("date (date)",vs("The date from which to extract the quarter."))],compute:function(e){return Math.ceil((Do(e,this.locale).getMonth()+1)/3)}},Rd={description:vs("First day of the quarter of the year a specific date falls in."),args:[ls("date (date)",vs("The date from which to calculate the start of quarter."))],compute:function(e){const t=Ed.compute.bind(this)(e),s=Cd.compute.bind(this)(e);return{value:Xs(new Fs(s,3*(t-1),1)),format:this.locale.dateFormat}}},xd={description:vs("Last day of the quarter of the year a specific date falls in."),args:[ls("date (date)",vs("The date from which to calculate the end of quarter."))],compute:function(e){const t=Ed.compute.bind(this)(e),s=Cd.compute.bind(this)(e);return{value:Xs(new Fs(s,3*t,0)),format:this.locale.dateFormat}}},Td={description:vs("First day of the year a specific date falls in."),args:[ls("date (date)",vs("The date from which to calculate the start of the year."))],compute:function(e){const t=Cd.compute.bind(this)(e);return{value:Xs(new Fs(t,0,1)),format:this.locale.dateFormat}}},Ad={description:vs("Last day of the year a specific date falls in."),args:[ls("date (date)",vs("The date from which to calculate the end of the year."))],compute:function(e){const t=Cd.compute.bind(this)(e);return{value:Xs(new Fs(t+1,0,0)),format:this.locale.dateFormat}}};var Dd=Object.freeze({__proto__:null,DATE:jh,DATEDIF:Yh,DATEVALUE:Xh,DAY:Kh,DAYS:Jh,DAYS360:ed,EDATE:td,EOMONTH:sd,HOUR:od,ISOWEEKNUM:id,MINUTE:nd,MONTH:rd,MONTH_END:wd,MONTH_START:Id,NETWORKDAYS:ad,NETWORKDAYS_INTL:hd,NOW:dd,QUARTER:Ed,QUARTER_END:xd,QUARTER_START:Rd,SECOND:ud,TIME:gd,TIMEVALUE:pd,TODAY:md,WEEKDAY:fd,WEEKNUM:vd,WORKDAY:bd,WORKDAY_INTL:Sd,YEAR:Cd,YEARFRAC:yd,YEAR_END:Ad,YEAR_START:Td});const _d={description:vs("Compare two numeric values, returning 1 if they're equal."),args:[ls("number1 (number)",vs("The first number to compare.")),ls("number2 (number, default=0)",vs("The second number to compare."))],compute:function(e,t={value:0}){return So(e,this.locale)===So(t,this.locale)?1:0},isExported:!0};var Od,Fd=Object.freeze({__proto__:null,DELTA:_d});!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(Od||(Od={}));const Pd=[Od.number,Od.error,Od.text,Od.boolean];function Md(e){const t="asc"===e?1:-1;return(e,s)=>{if(e.type===Od.empty)return s.type===Od.empty?0:1;if(s.type===Od.empty)return-1;let o=Pd.indexOf(e.type)-Pd.indexOf(s.type);return 0===o&&(o=e.type===Od.text||e.type===Od.error?e.value.localeCompare(s.value):e.value-s.value),t*o}}function Nd(e,t,...s){for(let e=0;e<s.length;e++){const t=e%2==0?"sort_column":"is_ascending";ai(void 0!==s[e],vs("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(Ao(vi(s[r+1])?.value)?"asc":"desc");const a=s[r];if(_s(a)&&(a.length>1||a[0].length>1))ai(1===a.length&&a[0].length===n,vs("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=So(vi(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:Md("desc"),asc:Md("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?Od.empty:"string"==typeof i?Od.text:typeof i},c={value:a,type:null===a?Od.empty:"string"==typeof a?Od.text:typeof a},h=r[o[s]](l,c);if(0!==h)return h}return 0}),a.map(t=>e[t])}const Ld={description:vs("Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions."),args:[ls("range (any, range<any>)",vs("The data to be filtered.")),ls("condition (boolean, range<boolean>, repeating)",vs("Column or row containing true or false values corresponding to the range."))],compute:function(e,...t){let s=Ko(e);const o=t.map(e=>Uo(Ko(e),e=>e.value));for(const e of o)if(!ci(e))return new ys(vs("The arguments condition must be a single column or row."));if(!hi(...t))return new ys(vs("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?Ho(s):s,i.some(e=>e.length!==s.length))return new ys(vs("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?Ho(r):r:new Rs(vs("No match found in FILTER evaluation"))},isExported:!1},kd={description:vs("Sorts the rows of a given array or range by the values in one or more columns."),args:[ls("range (range)",vs("The data to be sorted.")),ls("sort_column (any, range<number>, repeating, optional)",vs("The index of the column in range or a range outside of range containing the value by which to sort.")),ls("is_ascending (boolean, repeating, optional)",vs("TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order."),[{value:!0,label:vs("Ascending")},{value:!1,label:vs("Descending")}])],compute:function(e,...t){const s=Ho(e);return Ho(Nd(s,this.locale,...t))},isExported:!0},Vd={description:vs("Returns the first n items in a data set after performing a sort."),args:[ls("range (range)",vs("The data to be sorted.")),ls("n (number)",vs("The number of items to return.")),ls("display_ties_mode (number, default=0)",vs("A number representing the way to display ties.")),ls("sort_column (number, range<number>, repeating, optional)",vs("The index of the column in range or a range outside of range containing the value by which to sort.")),ls("is_ascending (boolean, repeating, optional)",vs("TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order."),[{value:!0,label:vs("Ascending")},{value:!1,label:vs("Descending")}])],compute:function(e,t,...s){const o=So(t?.value??1,this.locale),i=s.length%2==0?0:So(s[0]?.value,this.locale),n=s.length%2==0?s:s.slice(1);if(o<0)return new ys(vs("Wrong value of 'n'. Expected a positive number. Got %s.",o));if(i<0||i>3)return new ys(vs("Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.",i));const r=Nd(Ho(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 Ho(r.slice(0,o));case 1:for(let e=o;e<r.length;e++)if(!a(e,o-1))return Ho(r.slice(0,e));return Ho(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 Ho(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 Ho(e)}}},isExported:!1},Ud={description:vs("Unique rows in the provided source range."),args:[ls("range (any, range<any>)",vs("The data to filter by unique entries.")),ls("by_column (boolean, default=FALSE)",vs("Whether to filter the data by columns or by rows."),[{value:!0,label:vs("Return unique columns")},{value:!1,label:vs("Return unique rows")}]),ls("exactly_once (boolean, default=FALSE)",vs("Whether to return only entries with no duplicates."),[{value:!0,label:vs("Return items that appear exactly once")},{value:!1,label:vs("Return every distinct item")}])],compute:function(e={value:""},t,s){if(!_s(e))return[[e]];const o=Ao(t?.value)||!1,i=Ao(s?.value)||!1;o||(e=Ho(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:Ho(r):new ys(vs("No unique values found"))},isExported:!0};var Hd=Object.freeze({__proto__:null,FILTER:Ld,SORT:kd,SORTN:Vd,UNIQUE:Ud});const zd=[{value:1,label:vs("Annual")},{value:2,label:vs("Semi-annual")},{value:4,label:vs("Quarterly")}],Bd=[{value:0,label:vs("End of period (default)")},{value:1,label:vs("Beginning of period")}],Gd=[ls("settlement (date)",vs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ls("maturity (date)",vs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ls("frequency (number)",vs("The number of interest or coupon payments per year (1, 2, or 4)."),zd),ls("day_count_convention (number, default=0 )",vs("An indicator of what day count method to use."),qh)];function Wd(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)?(ai(u<o&&void 0!==n,vs("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,ai(u<o,vs("Function [[FUNCTION_NAME]] didn't find any result.")),u++)}while(!d);return h}const $d={description:vs("Accrued interest of security paying at maturity."),args:[ls("issue (date)",vs("The date the security was initially issued.")),ls("maturity (date)",vs("The maturity date of the security.")),ls("rate (number)",vs("The annualized rate of interest.")),ls("redemption (number)",vs("The redemption amount per 100 face value, or par.")),ls("day_count_convention (number, default=0 )",vs("An indicator of what day count method to use."),qh)],compute:function(e,t,s,o,i={value:0}){const n=Math.trunc(So(e,this.locale)),r=Math.trunc(So(t,this.locale)),a=So(o,this.locale),l=So(s,this.locale),c=Math.trunc(So(i,this.locale));if(n<0)return new ys((e=>vs("The issue (%s) must be positive or null.",e))(n));if(n>=r)return new ys(Th(n,r));if(Gh(c))return new ys(fh(c));if(a<=0)return new ys(kh(a));if(l<=0)return new ys(Lh(l));return a*l*so(n,r,c)},isExported:!0},qd={description:vs("Depreciation for an accounting period."),args:[ls("cost (number)",vs("The initial cost of the asset.")),ls("purchase_date (date)",vs("The date the asset was purchased.")),ls("first_period_end (date)",vs("The date the first period ended.")),ls("salvage (number)",vs("The value of the asset at the end of depreciation.")),ls("period (number)",vs("The single period within life for which to calculate depreciation.")),ls("rate (number)",vs("The deprecation rate.")),ls("day_count_convention (number, optional)",vs("An indicator of what day count method to use."),qh)],compute:function(e,t,s,o,i,n,r={value:0}){r=r||0;const a=So(e,this.locale),l=Math.trunc(So(t,this.locale)),c=Math.trunc(So(s,this.locale)),h=So(o,this.locale),d=So(i,this.locale),u=So(n,this.locale),g=Math.trunc(So(r,this.locale));if(a<=0)return new ys((e=>vs("The cost (%s) must be strictly positive.",e))(a));if(l<0)return new ys((e=>vs("The purchase_date (%s) must be positive or null.",e))(l));if(h<0)return new ys(Vh(h));if(h>a)return new ys(((e,t)=>vs("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 ys((e=>vs("The period (%s) must be positive or null.",e))(d));if(u<=0)return new ys(Lh(u));if(Gh(g))return new ys(fh(g));if(l>c)return new ys(((e,t)=>vs("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=so(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},Zd={description:vs("Days in coupon period containing settlement date."),args:Gd,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(So(e,this.locale)),n=Math.trunc(So(t,this.locale)),r=Math.trunc(So(s,this.locale)),a=Math.trunc(So(o,this.locale));if(i>=n)return new ys(Th(i,n));if(Wh(r))return new ys(mh(r));if(Gh(a))return new ys(fh(a));if(1===a){const i=Jd.compute.bind(this)(e,t,s,o).value;return So(Xd.compute.bind(this)(e,t,s,o).value,this.locale)-So(i,this.locale)}return(3===a?365:360)/r},isExported:!0},jd={description:vs("Days from settlement until next coupon."),args:Gd,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(So(e,this.locale)),n=Math.trunc(So(t,this.locale)),r=Math.trunc(So(s,this.locale)),a=Math.trunc(So(o,this.locale));if(i>=n)return new ys(Th(i,n));if(Wh(r))return new ys(mh(r));if(Gh(a))return new ys(fh(a));const l=So(Jd.compute.bind(this)(e,t,s,o).value,this.locale);if([1,2,3].includes(a))return i-l;if(4===a){const e=so(l,i,a);return Math.round(360*e)}const c=Do(i,this.locale),h=Do(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&&Qs(h)&&Qs(c)&&(f=30),31!==f||30!==m&&31!==m||(f=30),2===g&&Qs(h)&&(m=30),31===m&&(m=30),360*(u-d)+30*(p-g)+(f-m)},isExported:!0},Yd={description:vs("Days from settlement until next coupon."),args:Gd,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(So(e,this.locale)),n=Math.trunc(So(t,this.locale)),r=Math.trunc(So(s,this.locale)),a=Math.trunc(So(o,this.locale));if(i>=n)return new ys(Th(i,n));if(Wh(r))return new ys(mh(r));if(Gh(a))return new ys(fh(a));const l=So(Xd.compute.bind(this)(e,t,s,o).value,this.locale);if([1,2,3].includes(a))return l-i;if(4===a){const e=so(i,l,a);return Math.round(360*e)}const c=jd.compute.bind(this)(e,t,s,o);return So(Zd.compute.bind(this)(e,t,s,o),this.locale)-So(c,this.locale)},isExported:!0},Xd={description:vs("Next coupon date after the settlement date."),args:Gd,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(So(e,this.locale)),n=Math.trunc(So(t,this.locale)),r=Math.trunc(So(s,this.locale)),a=Math.trunc(So(o,this.locale));if(i>=n)return new ys(Th(i,n));if(Wh(r))return new ys(mh(r));if(Gh(a))return new ys(fh(a));const l=12/r,c=Kd.compute.bind(this)(e,t,s,o);return{value:Xs(eo(Do(n,this.locale),-(So(c,this.locale)-1)*l,!0)),format:this.locale.dateFormat}},isExported:!0},Kd={description:vs("Number of coupons between settlement and maturity."),args:Gd,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(So(e,this.locale)),n=Math.trunc(So(t,this.locale)),r=Math.trunc(So(s,this.locale)),a=Math.trunc(So(o,this.locale));if(i>=n)return new ys(Th(i,n));if(Wh(r))return new ys(mh(r));if(Gh(a))return new ys(fh(a));let l=1,c=n;const h=12/r;for(;c>i;)c=Xs(eo(Do(c,this.locale),-h,!1)),l++;return l-1},isExported:!0},Jd={description:vs("Last coupon date prior to or on the settlement date."),args:Gd,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(So(e,this.locale)),n=Math.trunc(So(t,this.locale)),r=Math.trunc(So(s,this.locale)),a=Math.trunc(So(o,this.locale));if(i>=n)return new ys(Th(i,n));if(Wh(r))return new ys(mh(r));if(Gh(a))return new ys(fh(a));const l=12/r,c=Kd.compute.bind(this)(e,t,s,o);return{value:Xs(eo(Do(n,this.locale),-c*l,!0)),format:this.locale.dateFormat}},isExported:!0},Qd={description:vs("Cumulative interest paid over a set of periods."),args:[ls("rate (number)",vs("The interest rate.")),ls("number_of_periods (number)",vs("The number of payments to be made.")),ls("present_value (number)",vs("The current value of the annuity.")),ls("first_period (number)",vs("The number of the payment period to begin the cumulative calculation.")),ls("last_period (number)",vs("The number of the payment period to end the cumulative calculation.")),ls("end_or_beginning (number, default=0)",vs("The timing of the payment payments are due for each period."),Bd)],compute:function(e,t,s,o,i,n={value:0}){const r=So(o,this.locale),a=So(i,this.locale),l=So(e,this.locale),c=So(s,this.locale),h=So(t,this.locale),d=Ao(n)?1:0;if(h<=0)return new ys(Ah(h));if(r<=0)return new ys(Ih(r));if(a<=0)return new ys(Rh(a));if(r>a)return new ys(yh(r,a));if(a>h)return new ys(Eh(a,h));if(l<=0)return new ys(Lh(l));if(c<=0)return new ys(Fh(c));let u=0;for(let e=r;e<=a;e++)u+=gu(l,e,h,c,0,d);return u},isExported:!0},eu={description:vs("Cumulative principal paid over a set of periods."),args:[ls("rate (number)",vs("The interest rate.")),ls("number_of_periods (number)",vs("The number of payments to be made.")),ls("present_value (number)",vs("The current value of the annuity.")),ls("first_period (number)",vs("The number of the payment period to begin the cumulative calculation.")),ls("last_period (number)",vs("The number of the payment period to end the cumulative calculation.")),ls("end_or_beginning (number, default=0)",vs("The timing of the payment payments are due for each period."),Bd)],compute:function(e,t,s,o,i,n={value:0}){const r=So(o,this.locale),a=So(i,this.locale),l=So(e,this.locale),c=So(s,this.locale),h=So(t,this.locale),d=Ao(n)?1:0;if(h<=0)return new ys(Ah(h));if(r<=0)return new ys(Ih(r));if(a<=0)return new ys(Rh(a));if(r>a)return new ys(yh(r,a));if(a>h)return new ys(Eh(a,h));if(l<=0)return new ys(Lh(l));if(c<=0)return new ys(Fh(c));let u=0;for(let e=r;e<=a;e++)u+=xu(l,e,h,c,0,d);return u},isExported:!0},tu={description:vs("Depreciation via declining balance method."),args:[ls("cost (number)",vs("The initial cost of the asset.")),ls("salvage (number)",vs("The value of the asset at the end of depreciation.")),ls("life (number)",vs("The number of periods over which the asset is depreciated.")),ls("period (number)",vs("The single period within life for which to calculate depreciation.")),ls("month (number, optional)",vs("The number of months in the first year of depreciation."))],compute:function(e,t,s,o,...i){const n=So(e,this.locale),r=So(t,this.locale),a=So(s,this.locale),l=Math.trunc(So(o,this.locale)),c=i.length?Math.trunc(So(i[0],this.locale)):12,h=a+(12===c?0:1);if(n<0)return new ys(ph(n));if(r<0)return new ys(Vh(r));if(l<=0)return new ys(Oh(l));if(a<=0)return new ys(xh(a));if(1>c||c>12)return new ys(vs("The month (%s) must be between 1 and 12 inclusive.",c));if(l>h)return new ys(((e,t)=>vs("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},su="#,##0.00",ou={description:vs("Depreciation via double-declining balance method."),args:[ls("cost (number)",vs("The initial cost of the asset.")),ls("salvage (number)",vs("The value of the asset at the end of depreciation.")),ls("life (number)",vs("The number of periods over which the asset is depreciated.")),ls("period (number)",vs("The single period within life for which to calculate depreciation.")),ls("factor (number, default=2)",vs("The factor by which depreciation decreases."))],compute:function(e,t,s,o,i={value:2}){const n=So(e,this.locale),r=So(t,this.locale),a=So(s,this.locale),l=So(o,this.locale),c=So(i,this.locale);if(n<0)return new ys(ph(n));if(r<0)return new ys(Vh(r));if(l<=0)return new ys(Oh(l));if(a<=0)return new ys(xh(a));if(l>a)return new ys(_h(l,a));if(c<=0)return new ys(vh(c));if(0===n||r>=n)return{value:0,format:su};const h=c/a;if(h>1)return{value:1===l?n-r:0,format:su};if(l<=1)return{value:n*h,format:su};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:su}},isExported:!0},iu={description:vs("Discount rate of a security based on price."),args:[ls("settlement (date)",vs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ls("maturity (date)",vs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ls("price (number)",vs("The price at which the security is bought per 100 face value.")),ls("redemption (number)",vs("The redemption amount per 100 face value, or par.")),ls("day_count_convention (number, default=0 )",vs("An indicator of what day count method to use."),qh)],compute:function(e,t,s,o,i={value:0}){i=i||0;const n=Math.trunc(So(e,this.locale)),r=Math.trunc(So(t,this.locale)),a=So(s,this.locale),l=So(o,this.locale),c=Math.trunc(So(i,this.locale));if(n>=r)return new ys(Th(n,r));if(Gh(c))return new ys(fh(c));if(a<=0)return new ys(Ph(a));if(l<=0)return new ys(kh(l));return(l-a)/l/so(n,r,c)},isExported:!0},nu={description:vs("Convert a decimal fraction to decimal value."),args:[ls("fractional_price (number)",vs("The price quotation given using fractional decimal conventions.")),ls("unit (number)",vs("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],compute:function(e,t){const s=So(e,this.locale),o=Math.trunc(So(t,this.locale));if(o<=0)return new ys(Hh(o));const i=Math.trunc(s);return i+(s-i)*(10**Math.ceil(Math.log10(o))/o)},isExported:!0},ru={description:vs("Convert a decimal value to decimal fraction."),args:[ls("decimal_price (number)",vs("The price quotation given as a decimal value.")),ls("unit (number)",vs("The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],compute:function(e,t){const s=So(e,this.locale),o=Math.trunc(So(t,this.locale));if(o<=0)return new ys(Hh(o));const i=Math.trunc(s);return i+(s-i)*(o/10**Math.ceil(Math.log10(o)))},isExported:!0},au={description:vs("Number of periods for an investment to reach a value."),args:[ls("settlement (date)",vs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ls("maturity (date)",vs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ls("rate (number)",vs("The annualized rate of interest.")),ls("yield (number)",vs("The expected annual yield of the security.")),ls("frequency (number)",vs("The number of interest or coupon payments per year (1, 2, or 4)."),zd),ls("day_count_convention (number, default=0 )",vs("An indicator of what day count method to use."),qh)],compute:function(e,t,s,o,i,n={value:0}){const r=Math.trunc(So(e,this.locale)),a=Math.trunc(So(t,this.locale)),l=So(s,this.locale),c=So(o,this.locale),h=Math.trunc(So(i,this.locale)),d=Math.trunc(So(n,this.locale));if(r>=a)return new ys(Th(r,a));if(Wh(h))return new ys(mh(h));if(Gh(d))return new ys(fh(d));if(l<0)return new ys(Nh(l));if(c<0)return new ys(zh(c));const u=so(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},lu={description:vs("Annual effective interest rate."),args:[ls("nominal_rate (number)",vs("The nominal interest rate per year.")),ls("periods_per_year (number)",vs("The number of compounding periods per year."))],compute:function(e,t){const s=So(e,this.locale),o=Math.trunc(So(t,this.locale));return s<=0?new ys(vs("The nominal_rate (%s) must be strictly positive.",s)):o<=0?new ys(Dh(o)):Math.pow(1+s/o,o)-1},isExported:!0};function cu(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 hu={description:vs("Future value of an annuity investment."),args:[ls("rate (number)",vs("The interest rate.")),ls("number_of_periods (number)",vs("The number of payments to be made.")),ls("payment_amount (number)",vs("The amount per period to be paid.")),ls("present_value (number, default=0)",vs("The current value of the annuity.")),ls("end_or_beginning (number, default=0)",vs("The timing of the payment payments are due for each period."),Bd)],compute:function(e,t,s,o={value:0},i={value:0}){o=o||0,i=i||0;return{value:cu(So(e,this.locale),So(t,this.locale),So(s,this.locale),So(o,this.locale),Ao(i)?1:0),format:"#,##0.00"}},isExported:!0},du={description:vs("Future value of principal from series of rates."),args:[ls("principal (number)",vs("The amount of initial capital or value to compound against.")),ls("rate_schedule (number, range<number>)",vs("A series of interest rates to compound against the principal."))],compute:function(e,t){return No([t],(e,t)=>e*(1+So(t,this.locale)),So(e,this.locale))},isExported:!0},uu={description:vs("Calculates effective interest rate."),args:[ls("settlement (date)",vs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ls("maturity (date)",vs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ls("investment (number)",vs("The amount invested in the security.")),ls("redemption (number)",vs("The amount to be received at maturity.")),ls("day_count_convention (number, default=0 )",vs("An indicator of what day count method to use."),qh)],compute:function(e,t,s,o,i={value:0}){const n=Math.trunc(So(e,this.locale)),r=Math.trunc(So(t,this.locale)),a=So(o,this.locale),l=So(s,this.locale),c=Math.trunc(So(i,this.locale));if(n>=r)return new ys(Th(n,r));if(l<=0)return new ys(wh(l));if(a<=0)return new ys(kh(a));if(Gh(c))return new ys(fh(c));return(a-l)/l/so(n,r,c)},isExported:!0};function gu(e,t,s,o,i,n){return Eu(e,s,o,i,n)-xu(e,t,s,o,i,n)}const pu={description:vs("Payment on the principal of an investment."),args:[ls("rate (number)",vs("The annualized rate of interest.")),ls("period (number)",vs("The amortization period, in terms of number of periods.")),ls("number_of_periods (number)",vs("The number of payments to be made.")),ls("present_value (number)",vs("The current value of the annuity.")),ls("future_value (number, default=0)",vs("The future value remaining after the final payment has been made.")),ls("end_or_beginning (number, default=0)",vs("The timing of the payment payments are due for each period."),Bd)],compute:function(e,t,s,o,i={value:0},n={value:0}){return{value:gu(So(e,this.locale),So(t,this.locale),So(s,this.locale),So(o,this.locale),So(i,this.locale),Ao(n)?1:0),format:"#,##0.00"}},isExported:!0},mu={description:vs("Internal rate of return given periodic cashflows."),args:[ls("cashflow_amounts (number, range<number>)",vs("An array or range containing the income or payments associated with the investment.")),ls("rate_guess (number, default=0.1)",vs("An estimate for what the internal rate of return will be."))],compute:function(e,t={value:.1}){const s=So(t,this.locale);if(s<=-1)return new ys(Mh(s));let o=!1,i=!1;const n=[];if(Po([e],({value:e})=>{e>0&&(o=!0),e<0&&(i=!0),n.push(e)},this.locale),!o||!i)return new ys(gh);const r=n.shift();return{value:Wd(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},fu={description:vs("Returns the interest paid at a particular period of an investment."),args:[ls("rate (number)",vs("The interest rate.")),ls("period (number)",vs("The period for which you want to view the interest payment.")),ls("number_of_periods (number)",vs("The number of payments to be made.")),ls("present_value (number)",vs("The current value of the annuity."))],compute:function(e,t,s,o){const i=So(e,this.locale),n=So(t,this.locale),r=So(s,this.locale),a=So(o,this.locale);if(0===r)return new ys(vs("The number_of_periods (%s) must be different from zero.",r));return-1*(a-a*(n/r))*i},isExported:!0},vu={description:vs("Modified Macaulay duration."),args:[ls("settlement (date)",vs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ls("maturity (date)",vs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ls("rate (number)",vs("The annualized rate of interest.")),ls("yield (number)",vs("The expected annual yield of the security.")),ls("frequency (number)",vs("The number of interest or coupon payments per year (1, 2, or 4)."),zd),ls("day_count_convention (number, default=0 )",vs("An indicator of what day count method to use."))],compute:function(e,t,s,o,i,n={value:0}){const r=au.compute.bind(this)(e,t,s,o,i,n),a=So(o,this.locale),l=Math.trunc(So(i,this.locale));return So(r,this.locale)/(1+a/l)},isExported:!0},bu={description:vs("Modified internal rate of return."),args:[ls("cashflow_amounts (range<number>)",vs("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")),ls("financing_rate (number)",vs("The interest rate paid on funds invested.")),ls("reinvestment_return_rate (number)",vs("The return (as a percentage) earned on reinvestment of income received from the investment."))],compute:function(e,t,s){const o=So(t,this.locale),i=So(s,this.locale),n=Ho(e).flat().filter(e=>null!==e.value).map(e=>So(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 ys(gh);return(-a/l)**(1/(r-1))-1},isExported:!0},Su={description:vs("Annual nominal interest rate."),args:[ls("effective_rate (number)",vs("The effective interest rate per year.")),ls("periods_per_year (number)",vs("The number of compounding periods per year."))],compute:function(e,t){const s=So(e,this.locale),o=Math.trunc(So(t,this.locale));return s<=0?new ys(vs("The effective_rate (%s) must be strictly positive.",s)):o<=0?new ys(Dh(o)):(Math.pow(s+1,1/o)-1)*o},isExported:!0},Cu={description:vs("Number of payment periods for an investment."),args:[ls("rate (number)",vs("The interest rate.")),ls("payment_amount (number)",vs("The amount of each payment made.")),ls("present_value (number)",vs("The current value of the annuity.")),ls("future_value (number, default=0)",vs("The future value remaining after the final payment has been made.")),ls("end_or_beginning (number, default=0)",vs("The timing of the payment payments are due for each period."),Bd)],compute:function(e,t,s,o={value:0},i={value:0}){o=o||0,i=i||0;const n=So(e,this.locale),r=So(t,this.locale),a=So(s,this.locale),l=So(o,this.locale),c=Ao(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 yu(e,t,s,o){let i=0;return Lo(s,(t,s)=>(i++,t+s/(1+e)**i),t,o)}const Iu={description:vs("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:[ls("discount (number)",vs("The discount rate of the investment over one period.")),ls("cashflow (number, range<number>, repeating)",vs("The future cash flows."))],compute:function(e,...t){const s=So(e,this.locale);return-1===s?new ys((e=>vs("The discount (%s) must be different from -1.",e))(s)):{value:yu(s,0,t,this.locale),format:"#,##0.00"}},isExported:!0},wu={description:vs("Computes the number of periods needed for an investment to reach a value."),args:[ls("rate (number)",vs("The rate at which the investment grows each period.")),ls("present_value (number)",vs("The investment's current value.")),ls("future_value (number)",vs("The investment's desired future value."))],compute:function(e,t,s){const o=So(e,this.locale),i=So(t,this.locale),n=So(s,this.locale);return o<=0?new ys(Lh(o)):i<=0?new ys(Fh(i)):n<=0?new ys(vs("The future_value (%s) must be strictly positive.",n)):(Math.log(n)-Math.log(i))/Math.log(1+o)},isExported:!0};function Eu(e,t,s,o,i){if(t<=0)throw new ys(Ah(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 Ru={description:vs("Periodic payment for an annuity investment."),args:[ls("rate (number)",vs("The annualized rate of interest.")),ls("number_of_periods (number)",vs("The number of payments to be made.")),ls("present_value (number)",vs("The current value of the annuity.")),ls("future_value (number, default=0)",vs("The future value remaining after the final payment has been made.")),ls("end_or_beginning (number, default=0)",vs("The timing of the payment payments are due for each period."),Bd)],compute:function(e,t,s,o={value:0},i={value:0}){const n=So(t,this.locale),r=So(e,this.locale),a=Ao(i)?1:0,l=So(o,this.locale);return{value:Eu(r,n,So(s,this.locale),l,a),format:"#,##0.00"}},isExported:!0};function xu(e,t,s,o,i,n){if(s<=0)throw new ys(Ah(s));if(t<=0||t>s)throw new ys(vs("The period must be between 1 and number_of_periods (%s)",s));const r=Eu(e,s,o,i,n);if(1===n&&1===t)return r;return r+-cu(e,0===n?t-1:t-2,r,o+r*n,0)*e}const Tu={description:vs("Payment on the principal of an investment."),args:[ls("rate (number)",vs("The annualized rate of interest.")),ls("period (number)",vs("The amortization period, in terms of number of periods.")),ls("number_of_periods (number)",vs("The number of payments to be made.")),ls("present_value (number)",vs("The current value of the annuity.")),ls("future_value (number, default=0)",vs("The future value remaining after the final payment has been made.")),ls("end_or_beginning (number, default=0)",vs("The timing of the payment payments are due for each period."),Bd)],compute:function(e,t,s,o,i={value:0},n={value:0}){const r=So(s,this.locale),a=So(e,this.locale),l=So(t,this.locale),c=Ao(n)?1:0,h=So(i,this.locale);return{value:xu(a,l,r,So(o,this.locale),h,c),format:"#,##0.00"}},isExported:!0},Au={description:vs("Present value of an annuity investment."),args:[ls("rate (number)",vs("The interest rate.")),ls("number_of_periods (number)",vs("The number of payments to be made.")),ls("payment_amount (number)",vs("The amount per period to be paid.")),ls("future_value (number, default=0)",vs("The future value remaining after the final payment has been made.")),ls("end_or_beginning (number, default=0)",vs("The timing of the payment payments are due for each period."),Bd)],compute:function(e,t,s,o={value:0},i={value:0}){o=o||0,i=i||0;const n=So(e,this.locale),r=So(t,this.locale),a=So(s,this.locale),l=So(o,this.locale),c=Ao(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},Du={description:vs("Price of a security paying periodic interest."),args:[ls("settlement (date)",vs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ls("maturity (date)",vs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ls("rate (number)",vs("The annualized rate of interest.")),ls("yield (number)",vs("The expected annual yield of the security.")),ls("redemption (number)",vs("The redemption amount per 100 face value, or par.")),ls("frequency (number)",vs("The number of interest or coupon payments per year (1, 2, or 4)."),zd),ls("day_count_convention (number, default=0 )",vs("An indicator of what day count method to use."),qh)],compute:function(e,t,s,o,i,n,r={value:0}){r=r||0;const a=Math.trunc(So(e,this.locale)),l=Math.trunc(So(t,this.locale)),c=So(s,this.locale),h=So(o,this.locale),d=So(i,this.locale),u=Math.trunc(So(n,this.locale)),g=Math.trunc(So(r,this.locale));if(a>=l)return new ys(Th(a,l));if(Wh(u))return new ys(mh(u));if(Gh(g))return new ys(fh(g));if(c<0)return new ys(Nh(c));if(h<0)return new ys(zh(h));if(d<=0)return new ys(kh(d));const p=so(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},_u={description:vs("Price of a discount security."),args:[ls("settlement (date)",vs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ls("maturity (date)",vs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ls("discount (number)",vs("The discount rate of the security at time of purchase.")),ls("redemption (number)",vs("The redemption amount per 100 face value, or par.")),ls("day_count_convention (number, default=0 )",vs("An indicator of what day count method to use."),qh)],compute:function(e,t,s,o,i={value:0}){i=i||0;const n=Math.trunc(So(e,this.locale)),r=Math.trunc(So(t,this.locale)),a=So(s,this.locale),l=So(o,this.locale),c=Math.trunc(So(i,this.locale));if(n>=r)return new ys(Th(n,r));if(Gh(c))return new ys(fh(c));if(a<=0)return new ys(bh(a));if(l<=0)return new ys(kh(l));return l-a*l*so(n,r,c)},isExported:!0},Ou={description:vs("Calculates the price of a security paying interest at maturity, based on expected yield."),args:[ls("settlement (date)",vs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ls("maturity (date)",vs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ls("issue (date)",vs("The date the security was initially issued.")),ls("rate (number)",vs("The annualized rate of interest.")),ls("yield (number)",vs("The expected annual yield of the security.")),ls("day_count_convention (number, default=0 )",vs("An indicator of what day count method to use."),qh)],compute:function(e,t,s,o,i,n={value:0}){n=n||0;const r=Math.trunc(So(e,this.locale)),a=Math.trunc(So(t,this.locale)),l=Math.trunc(So(s,this.locale)),c=So(o,this.locale),h=So(i,this.locale),d=Math.trunc(So(n,this.locale));if(r<=l)return new ys(((e,t)=>vs("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 ys(Th(r,a));if(Gh(d))return new ys(fh(d));if(c<0)return new ys(Nh(c));if(h<0)return new ys(zh(h));const u=so(r,a,d),g=so(r,l,d);return(100+so(l,a,d)*c*100)/(1+u*h)-g*c*100},isExported:!0},Fu=.1,Pu={description:vs("Interest rate of an annuity investment."),args:[ls("number_of_periods (number)",vs("The number of payments to be made.")),ls("payment_per_period (number)",vs("The amount per period to be paid.")),ls("present_value (number)",vs("The current value of the annuity.")),ls("future_value (number, default=0)",vs("The future value remaining after the final payment has been made.")),ls("end_or_beginning (number, default=0)",vs("The timing of the payment payments are due for each period."),Bd),ls("rate_guess (number, default=0.1)",vs("An estimate for what the interest rate will be."))],compute:function(e,t,s,o={value:0},i={value:0},n={value:Fu}){const r=So(e,this.locale),a=So(t,this.locale),l=Ao(i)?1:0,c=So(n,this.locale)||Fu;let h=So(o,this.locale),d=So(s,this.locale);if(r<=0)return new ys(Ah(r));if(!Bh([a,d,h]))return new ys(vs("There must be both positive and negative values in [payment_amount, present_value, future_value]."));if(c<=-1)return new ys(Mh(c));h-=a*l,d+=a*l;return{value:Wd(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},Mu={description:vs("Amount received at maturity for a security."),args:[ls("settlement (date)",vs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ls("maturity (date)",vs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ls("investment (number)",vs("The amount invested (irrespective of face value of each security).")),ls("discount (number)",vs("The discount rate of the security invested in.")),ls("day_count_convention (number, default=0 )",vs("An indicator of what day count method to use."),qh)],compute:function(e,t,s,o,i={value:0}){i=i||0;const n=Math.trunc(So(e,this.locale)),r=Math.trunc(So(t,this.locale)),a=So(s,this.locale),l=So(o,this.locale),c=Math.trunc(So(i,this.locale));if(n>=r)return new ys(Th(n,r));if(Gh(c))return new ys(fh(c));if(a<=0)return new ys(wh(a));if(l<=0)return new ys(bh(l));return a/(1-l*so(n,r,c))},isExported:!0},Nu={description:vs("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:[ls("number_of_periods (number)",vs("The number of periods.")),ls("present_value (number)",vs("The present value of the investment.")),ls("future_value (number)",vs("The future value of the investment."))],compute:function(e,t,s){const o=So(e,this.locale),i=So(t,this.locale),n=So(s,this.locale);return o<=0?new ys(Ah(o)):(n/i)**(1/o)-1},isExported:!0},Lu={description:vs("Depreciation of an asset using the straight-line method."),args:[ls("cost (number)",vs("The initial cost of the asset.")),ls("salvage (number)",vs("The value of the asset at the end of depreciation.")),ls("life (number)",vs("The number of periods over which the asset is depreciated."))],compute:function(e,t,s){return{value:(So(e,this.locale)-So(t,this.locale))/So(s,this.locale),format:"#,##0.00"}},isExported:!0},ku={description:vs("Depreciation via sum of years digit method."),args:[ls("cost (number)",vs("The initial cost of the asset.")),ls("salvage (number)",vs("The value of the asset at the end of depreciation.")),ls("life (number)",vs("The number of periods over which the asset is depreciated.")),ls("period (number)",vs("The single period within life for which to calculate depreciation."))],compute:function(e,t,s,o){const i=So(e,this.locale),n=So(t,this.locale),r=So(s,this.locale),a=So(o,this.locale);if(a<=0)return new ys(Oh(a));if(r<=0)return new ys(xh(r));if(a>r)return new ys(_h(a,r));return{value:(r-a+1)/(r*(r+1)/2)*(i-n),format:"#,##0.00"}},isExported:!0};function Vu(e,t,s){return 100*(1-s*so(e,t,2))}const Uu={description:vs("Price of a US Treasury bill."),args:[ls("settlement (date)",vs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ls("maturity (date)",vs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ls("discount (number)",vs("The discount rate of the bill at time of purchase."))],compute:function(e,t,s){const o=Math.trunc(So(e,this.locale)),i=Math.trunc(So(t,this.locale)),n=So(s,this.locale);return o>=i?new ys(Th(o,i)):$h(o,i,this.locale)?n<=0?new ys(bh(n)):n>=1?new ys(Sh(n)):Vu(o,i,n):new ys(Uh(o,i))},isExported:!0},Hu={description:vs("Equivalent rate of return for a US Treasury bill."),args:[ls("settlement (date)",vs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ls("maturity (date)",vs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ls("discount (number)",vs("The discount rate of the bill at time of purchase."))],compute:function(e,t,s){const o=Math.trunc(So(e,this.locale)),i=Math.trunc(So(t,this.locale)),n=So(s,this.locale);if(o>=i)return new ys(Th(o,i));if(!$h(o,i,this.locale))return new ys(Uh(o,i));if(n<=0)return new ys(bh(n));if(n>=1)return new ys(Sh(n));const r=Jh.compute.bind(this)({value:i},{value:o});if(r<=182)return 365*n/(360-n*r);const a=Vu(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},zu={description:vs("The yield of a US Treasury bill based on price."),args:[ls("settlement (date)",vs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ls("maturity (date)",vs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ls("price (number)",vs("The price at which the security is bought per 100 face value."))],compute:function(e,t,s){const o=Math.trunc(So(e,this.locale)),i=Math.trunc(So(t,this.locale)),n=So(s,this.locale);if(o>=i)return new ys(Th(o,i));if(!$h(o,i,this.locale))return new ys(Uh(o,i));if(n<=0)return new ys(Ph(n));return(100-n)/n*(1/so(o,i,2))},isExported:!0},Bu=!1,Gu={description:vs("Variable declining balance. WARNING : does not handle decimal periods."),args:[ls("cost (number)",vs("The initial cost of the asset.")),ls("salvage (number)",vs("The value of the asset at the end of depreciation.")),ls("life (number)",vs("The number of periods over which the asset is depreciated.")),ls("start (number)",vs("Starting period to calculate depreciation.")),ls("end (number)",vs("Ending period to calculate depreciation.")),ls("factor (number, default=2)",vs("The number of months in the first year of depreciation.")),ls("no_switch (number, default=false)",vs("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation."),[{value:!1,label:vs("Switch to straight-line depreciation")},{value:!0,label:vs("Do not switch to straight-line depreciation")}])],compute:function(e,t,s,o,i,n={value:2},r={value:Bu}){n=n||0;const a=So(e,this.locale),l=So(t,this.locale),c=So(s,this.locale),h=Math.trunc(So(o,this.locale)),d=Math.trunc(So(i,this.locale)),u=So(n,this.locale),g=Ao(r);if(a<0)return new ys(ph(a));if(l<0)return new ys(Vh(l));if(c<=0)return new ys(xh(c));if(h<0)return new ys((e=>vs("The start_period (%s) must be positive or null.",e))(h));if(d<0)return new ys((e=>vs("The end_period (%s) must be positive or null.",e))(d));if(h>d)return new ys(vs("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 ys(((e,t)=>vs("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 ys(vh(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},Wu={description:vs("Internal rate of return given non-periodic cash flows."),args:[ls("cashflow_amounts (range<number>)",vs("An range containing the income or payments associated with the investment.")),ls("cashflow_dates (range<number>)",vs("An range with dates corresponding to the cash flows in cashflow_amounts.")),ls("rate_guess (number, default=0.1)",vs("An estimate for what the internal rate of return will be."))],compute:function(e,t,s={value:Fu}){const o=So(s,this.locale);if(!hi(e,t))return new ys(uh);const i=e.flat().map(e=>So(e,this.locale)),n=t.flat().map(e=>So(e,this.locale));if(!Bh(i))return new ys(gh);if(n.some(e=>e<n[0]))return new ys(Ch(n[0]));if(o<=-1)return new ys(Mh(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 Wd(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},$u={description:vs("Net present value given to non-periodic cash flows.."),args:[ls("discount (number)",vs("The discount rate of the investment over one period.")),ls("cashflow_amounts (number, range<number>)",vs("An range containing the income or payments associated with the investment.")),ls("cashflow_dates (number, range<number>)",vs("An range with dates corresponding to the cash flows in cashflow_amounts."))],compute:function(e,t,s){const o=So(e,this.locale);if(!hi(t,s))return new ys(uh);const i=Ko(t).flat().map(e=>Io(e,this.locale)),n=Ko(s).flat().map(e=>Io(e,this.locale));if(n.some(e=>e<n[0]))return new ys(Ch(n[0]));if(o<=0)return new ys(Lh(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},qu={description:vs("Annual yield of a security paying periodic interest."),args:[ls("settlement (date)",vs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ls("maturity (date)",vs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ls("rate (number)",vs("The annualized rate of interest.")),ls("price (number)",vs("The price at which the security is bought per 100 face value.")),ls("redemption (number)",vs("The redemption amount per 100 face value, or par.")),ls("frequency (number)",vs("The number of interest or coupon payments per year (1, 2, or 4)."),zd),ls("day_count_convention (number, default=0 )",vs("An indicator of what day count method to use."),qh)],compute:function(e,t,s,o,i,n,r={value:0}){r=r||0;const a=Math.trunc(So(e,this.locale)),l=Math.trunc(So(t,this.locale)),c=So(s,this.locale),h=So(o,this.locale),d=So(i,this.locale),u=Math.trunc(So(n,this.locale)),g=Math.trunc(So(r,this.locale));if(a>=l)return new ys(Th(a,l));if(Wh(u))return new ys(mh(u));if(Gh(g))return new ys(fh(g));if(c<0)return new ys(Nh(c));if(h<=0)return new ys(Ph(h));if(d<=0)return new ys(kh(d));const p=so(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=Wd(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},Zu={description:vs("Annual yield of a discount security."),args:[ls("settlement (date)",vs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ls("maturity (date)",vs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ls("price (number)",vs("The price at which the security is bought per 100 face value.")),ls("redemption (number)",vs("The redemption amount per 100 face value, or par.")),ls("day_count_convention (number, default=0 )",vs("An indicator of what day count method to use."),qh)],compute:function(e,t,s,o,i={value:0}){i=i||0;const n=Math.trunc(So(e,this.locale)),r=Math.trunc(So(t,this.locale)),a=So(s,this.locale),l=So(o,this.locale),c=Math.trunc(So(i,this.locale));if(n>=r)return new ys(Th(n,r));if(Gh(c))return new ys(fh(c));if(a<=0)return new ys(Ph(a));if(l<=0)return new ys(kh(l));return(l/a-1)/so(n,r,c)},isExported:!0},ju={description:vs("Annual yield of a security paying interest at maturity."),args:[ls("settlement (date)",vs("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ls("maturity (date)",vs("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ls("issue (date)",vs("The date the security was initially issued.")),ls("rate (number)",vs("The annualized rate of interest.")),ls("price (number)",vs("The price at which the security is bought.")),ls("day_count_convention (number, default=0 )",vs("An indicator of what day count method to use."),qh)],compute:function(e,t,s,o,i,n={value:0}){n=n||0;const r=Math.trunc(So(e,this.locale)),a=Math.trunc(So(t,this.locale)),l=Math.trunc(So(s,this.locale)),c=So(o,this.locale),h=So(i,this.locale),d=Math.trunc(So(n,this.locale));if(r>=a)return new ys(Th(r,a));if(Gh(d))return new ys(fh(d));if(r<l)return new ys(((e,t)=>vs("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 ys(Nh(c));if(h<=0)return new ys(Ph(h));return(100*(1+c*so(l,a,d))/(h+100*c*so(l,r,d))-1)/so(r,a,d)},isExported:!0};var Yu=Object.freeze({__proto__:null,ACCRINTM:$d,AMORLINC:qd,COUPDAYBS:jd,COUPDAYS:Zd,COUPDAYSNC:Yd,COUPNCD:Xd,COUPNUM:Kd,COUPPCD:Jd,CUMIPMT:Qd,CUMPRINC:eu,DB:tu,DDB:ou,DISC:iu,DOLLARDE:nu,DOLLARFR:ru,DURATION:au,EFFECT:lu,FV:hu,FVSCHEDULE:du,INTRATE:uu,IPMT:pu,IRR:mu,ISPMT:fu,MDURATION:vu,MIRR:bu,NOMINAL:Su,NPER:Cu,NPV:Iu,PDURATION:wu,PMT:Ru,PPMT:Tu,PRICE:Du,PRICEDISC:_u,PRICEMAT:Ou,PV:Au,RATE:Pu,RECEIVED:Mu,RRI:Nu,SLN:Lu,SYD:ku,TBILLEQ:Hu,TBILLPRICE:Uu,TBILLYIELD:zu,VDB:Gu,XIRR:Wu,XNPV:$u,YIELD:qu,YIELDDISC:Zu,YIELDMAT:ju});const Xu=[{value:"address",label:vs("Returns an absolute reference as plain text of the top left cell in reference.")},{value:"col",label:vs("Returns the column number of the cell in reference.")},{value:"contents",label:vs("Returns the value contained in the top left cell in reference.")},{value:"format",label:vs("Returns the format of the top left cell in reference.")},{value:"row",label:vs("Returns the row number of the top left cell in reference.")},{value:"type",label:vs('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.')}],Ku={description:vs("Gets information about a cell."),args:[ls("info_type (string)",vs("The type of information requested."),Xu),ls("reference (meta, range<meta>)",vs("The reference to the cell."))],compute:function(e,t){const s=Ro(e).toLowerCase();if(!Xu.map(e=>e.value).includes(s))return new ys(vs("The info_type should be one of %s.",Xu.join(", ")));const o=this.__originSheetId,i=t[0][0].value;let{sheetName:n,xc:r}=sr(i);n=n===this.getters.getSheetName(o)?void 0:n;const a=or(n,rr(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===Od.empty?"b":t===Od.text?"l":"v"}}return""},isExported:!0},Ju={description:vs("Whether a value is an error other than #N/A."),args:[ls("value (any)",vs("The value to be verified as an error type."))],compute:function(e){const t=e?.value;return fo(t)&&t!==Ss.NotAvailable},isExported:!0},Qu={description:vs("Whether a value is an error."),args:[ls("value (any)",vs("The value to be verified as an error type."))],compute:function(e){const t=e?.value;return fo(t)},isExported:!0},eg={description:vs("Whether a value is `true` or `false`."),args:[ls("value (any)",vs("The value to be verified as a logical TRUE or FALSE."))],compute:function(e){return"boolean"==typeof e?.value},isExported:!0},tg={description:vs("Whether a value is the error #N/A."),args:[ls("value (any)",vs("The value to be verified as an error type."))],compute:function(e){return e?.value===Ss.NotAvailable},isExported:!0},sg={description:vs("Whether a value is non-textual."),args:[ls("value (any)",vs("The value to be checked."))],compute:function(e){return!ig.compute.bind(this)(e)},isExported:!0},og={description:vs("Whether a value is a number."),args:[ls("value (any)",vs("The value to be verified as a number."))],compute:function(e){return"number"==typeof e?.value},isExported:!0},ig={description:vs("Whether a value is text."),args:[ls("value (any)",vs("The value to be verified as text."))],compute:function(e){return"string"==typeof e?.value&&!1===fo(e?.value)},isExported:!0},ng={description:vs("Whether the referenced cell is empty"),args:[ls("value (any)",vs("Reference to the cell that will be checked for emptiness."))],compute:function(e){return null===e?.value},isExported:!0},rg={description:vs("Returns the error value #N/A."),args:[],compute:function(){return{value:Ss.NotAvailable}},isExported:!0};var ag=Object.freeze({__proto__:null,CELL:Ku,ISBLANK:ng,ISERR:Ju,ISERROR:Qu,ISLOGICAL:eg,ISNA:tg,ISNONTEXT:sg,ISNUMBER:og,ISTEXT:ig,NA:rg});function lg(e){let t=!1,s=!0;return Bo(e,e=>(t=!0,s=s&&e,s)),{foundBoolean:t,result:s}}function cg(e){let t=!1,s=!1;return Bo(e,e=>(t=!0,s=s||e,!s)),{foundBoolean:t,result:s}}const hg={description:vs("Logical `and` operator."),args:[ls("logical_expression (boolean, range<boolean>, repeating)",vs("Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value."))],compute:function(...e){const{result:t,foundBoolean:s}=lg(e);return s?t:new ys(ei)},isExported:!0},dg={description:vs("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},ug={description:vs("Returns value depending on logical expression."),args:[ls("logical_expression (boolean, range<boolean>)",vs("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")),ls("value_if_true (any, range)",vs("The value the function returns if logical_expression is TRUE.")),ls("value_if_false (any, range, default=FALSE)",vs("The value the function returns if logical_expression is FALSE."))],compute:function(e,t,s){if(Si(e))return zo(ug.compute,[e,t,s]);return(Ao(vi(e))?t:s)??{value:0}},isExported:!0},gg={description:vs("Value if it is not an error, otherwise 2nd argument."),args:[ls("value (any, range)",vs("The value to return if value itself is not an error.")),ls('value_if_error (any, range, default="empty")',vs("The value the function returns if value is an error."))],compute:function(e,t){if(Si(e))return zo(gg.compute,[e,t]);return(fo(vi(e)?.value)?t:e)??{value:0}},isExported:!0},pg={description:vs("Value if it is not an #N/A error, otherwise 2nd argument."),args:[ls("value (any, range)",vs("The value to return if value itself is not #N/A an error.")),ls('value_if_error (any, range, default="empty")',vs("The value the function returns if value is an #N/A error."))],compute:function(e,t){if(Si(e))return zo(pg.compute,[e,t]);return(vi(e)?.value===Ss.NotAvailable?t:e)??{value:0}},isExported:!0},mg={description:vs("Returns a value depending on multiple logical expressions."),args:[ls("condition (any, range, repeating)",vs("The condition to be evaluated. It can be a boolean, a number, an array, or a reference to any of those.")),ls("value (any, range, repeating)",vs("The value to be returned if its corresponding condition is TRUE."))],compute:function(...e){if(e.length%2!=0)return new ys(vs("Wrong number of arguments. Expected an even number of arguments."));for(;e.length>0;){if(Si(e[0]))return zo(mg.compute,e);const t=Ao(vi(e.shift())),s=e.shift();if(t)return s??{value:0}}return new ys(vs("No match."))},isExported:!0},fg={description:vs("Returns opposite of provided logical value."),args:[ls("logical_expression (boolean)",vs("An expression or reference to a cell holding an expression that represents some logical value."))],compute:function(e){return!Ao(e)},isExported:!0},vg={description:vs("Logical `or` operator."),args:[ls("logical_expression (boolean, range<boolean>, repeating)",vs("Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value."))],compute:function(...e){const{result:t,foundBoolean:s}=cg(e);return s?t:new ys(ei)},isExported:!0},bg={description:vs("Returns a value by comparing cases to an expression."),args:[ls("expression (number, boolean, string)",vs("The value to be checked.")),ls("case (any, repeating)",vs("Case to be checked against expression.")),ls("value (any, repeating)",vs("Value to be returned if its corresponding case matches expression.")),ls('default (any, default="empty")',vs("An optional default value to be returned if none of the cases match expression."))],compute:function(e,...t){const s=t.length%2==0?vo(e):t.pop();for(let s=0;s<t.length;s+=2){const o=t[s];if(o&&fo(o.value))return o;if(e?.value===o?.value)return t[s+1]||{value:0}}return s||{value:0}},isExported:!0},Sg={description:vs("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},Cg={description:vs("Logical `xor` operator."),args:[ls("logical_expression (boolean, range<boolean>, repeating)",vs("Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value."))],compute:function(...e){let t=!1,s=!1;return Bo(e,e=>(t=!0,s=s?!e:e,!0)),t?s:new ys(ei)},isExported:!0};var yg=Object.freeze({__proto__:null,AND:hg,FALSE:dg,IF:ug,IFERROR:gg,IFNA:pg,IFS:mg,NOT:fg,OR:vg,SWITCH:bg,TRUE:Sg,XOR:Cg});const Ig={Errors:{InvalidRange:vs("The range is invalid"),FirstArgMissing:vs("The argument is missing. Please provide a value"),SecondArgMissing:vs("The second argument is missing. Please provide a value"),MinNaN:vs("The minpoint must be a number"),MidNaN:vs("The midpoint must be a number"),MaxNaN:vs("The maxpoint must be a number"),ValueUpperInflectionNaN:vs("The first value must be a number"),ValueLowerInflectionNaN:vs("The second value must be a number"),MinBiggerThanMax:vs("Minimum must be smaller then Maximum"),MinBiggerThanMid:vs("Minimum must be smaller then Midpoint"),MidBiggerThanMax:vs("Midpoint must be smaller then Maximum"),LowerBiggerThanUpper:vs("Lower inflection point must be smaller than upper inflection point"),MinInvalidFormula:vs("Invalid Minpoint formula"),MaxInvalidFormula:vs("Invalid Maxpoint formula"),MidInvalidFormula:vs("Invalid Midpoint formula"),ValueUpperInvalidFormula:vs("Invalid upper inflection point formula"),ValueLowerInvalidFormula:vs("Invalid lower inflection point formula"),EmptyRange:vs("A range needs to be defined"),ValueCellIsInvalidFormula:vs("At least one of the provided values is an invalid formula"),Unexpected:vs("The rule is invalid for an unknown reason")},ColorScale:vs("Color scale"),IconSet:vs("Icon set"),DataBar:vs("Data bar")},wg={Series:vs("Series"),BackgroundColor:vs("Background color"),StackedBarChart:vs("Stacked bar chart"),StackedLineChart:vs("Stacked line chart"),StackedAreaChart:vs("Stacked area chart"),StackedColumnChart:vs("Stacked column chart"),CumulativeData:vs("Cumulative data"),TreatLabelsAsText:vs("Treat labels as text"),AggregatedChart:vs("Aggregate"),Errors:{Unexpected:vs("The chart definition is invalid for an unknown reason"),InvalidDataSet:vs("The dataset is invalid"),InvalidLabelRange:vs("Labels are invalid"),InvalidScorecardKeyValue:vs("The key value is invalid"),InvalidScorecardBaseline:vs("The baseline value is invalid"),InvalidGaugeDataRange:vs("The data range is invalid"),EmptyGaugeRangeMin:vs("A minimum range limit value is needed"),GaugeRangeMinNaN:vs("The minimum range limit value must be a number"),EmptyGaugeRangeMax:vs("A maximum range limit value is needed"),GaugeRangeMaxNaN:vs("The maximum range limit value must be a number"),GaugeLowerInflectionPointNaN:vs("The lower inflection point value must be a number"),GaugeUpperInflectionPointNaN:vs("The upper inflection point value must be a number")},GeoChart:{ColorScales:{blues:vs("Blues"),cividis:vs("Cividis"),greens:vs("Greens"),greys:vs("Greys"),oranges:vs("Oranges"),purples:vs("Purples"),rainbow:vs("Rainbow"),reds:vs("Reds"),viridis:vs("Viridis")}}},Eg={Custom:vs("Custom")},Rg=vs("Merged cells are preventing this operation. Unmerge those cells and try again."),xg=vs("The header row of a table can't be moved."),Tg={Errors:{Unexpected:vs("Cannot split the selection for an unknown reason"),NoSplitSeparatorInSelection:vs("There is no match for the selected separator in the selection"),MoreThanOneColumnSelected:vs("Only a selection from a single column can be split"),SplitWillOverwriteContent:vs("Splitting will overwrite existing content")}},Ag={Errors:{Unexpected:vs("Cannot remove duplicates for an unknown reason"),MoreThanOneRangeSelected:vs("Please select only one range of cells"),EmptyTarget:vs("Please select a range of cells containing values."),NoColumnsProvided:vs("Please select at latest one column to analyze."),WillRemoveExistingMerge:vs("This operation is not possible due to a merge. Please remove the merges first than try again.")}},Dg={DateIs:{today:vs("today"),yesterday:vs("yesterday"),tomorrow:vs("tomorrow"),lastWeek:vs("in the past week"),lastMonth:vs("in the past month"),lastYear:vs("in the past year")},DateIsBefore:{today:vs("today"),yesterday:vs("yesterday"),tomorrow:vs("tomorrow"),lastWeek:vs("one week ago"),lastMonth:vs("one month ago"),lastYear:vs("one year ago")},CriterionError:{notEmptyValue:vs("The value must not be empty"),numberValue:vs("The value must be a number"),dateValue:vs("The value must be a date"),validRange:vs("The value must be a valid range"),validFormula:vs("The formula must be valid")},Errors:{InvalidRange:vs("The range is invalid."),InvalidDataValidationCriterionValue:vs("One or more of the provided criteria values are invalid. Please review and correct them."),InvalidNumberOfCriterionValues:vs("One or more of the provided criteria values are missing."),Unexpected:vs("The rule is invalid for an unknown reason.")}},_g={Errors:{Unexpected:vs("The table zone is invalid for an unknown reason"),TableOverlap:vs("You cannot create overlapping tables."),NonContinuousTargets:vs("A table can only be created on a continuous selection."),InvalidRange:vs("The range is invalid"),TargetOutOfSheet:vs("The range is out of the sheet")},Checkboxes:{hasFilters:vs("Filter button"),headerRow:vs("Header row(s)"),bandedRows:vs("Banded rows"),firstColumn:vs("First column"),lastColumn:vs("Last column"),bandedColumns:vs("Banded columns"),automaticAutofill:vs("Automatically autofill formulas"),totalRow:vs("Total row"),isDynamic:vs("Auto-adjust to formula result")},Tooltips:{filterWithoutHeader:vs("Cannot have filters without a header row"),isDynamic:vs("For tables based on array formulas only")}},Og={labels:{no_calculations:vs("No calculations"),"%_of_grand_total":vs("% of grand total"),"%_of_col_total":vs("% of column total"),"%_of_row_total":vs("% of row total"),"%_of":vs("% of"),"%_of_parent_row_total":vs("% of parent row total"),"%_of_parent_col_total":vs("% of parent column total"),"%_of_parent_total":vs("% of parent total"),difference_from:vs("Difference from"),"%_difference_from":vs("% difference from"),running_total:vs("Running total"),"%_running_total":vs("% Running total"),rank_asc:vs("Rank smallest to largest"),rank_desc:vs("Rank largest to smallest"),index:vs("Index")},descriptions:{"%_of_grand_total":()=>vs("Displayed as % of grand total"),"%_of_col_total":()=>vs("Displayed as % of column total"),"%_of_row_total":()=>vs("Displayed as % of row total"),"%_of":e=>vs('Displayed as % of "%s"',e),"%_of_parent_row_total":e=>vs('Displayed as % of parent row total of "%s"',e),"%_of_parent_col_total":()=>vs("Displayed as % of parent column total"),"%_of_parent_total":e=>vs('Displayed as % of parent "%s" total',e),difference_from:e=>vs('Displayed as difference from "%s"',e),"%_difference_from":e=>vs('Displayed as % difference from "%s"',e),running_total:e=>vs('Displayed as running total based on "%s"',e),"%_running_total":e=>vs('Displayed as % running total based on "%s"',e),rank_asc:e=>vs('Displayed as rank from smallest to largest based on "%s"',e),rank_desc:e=>vs('Displayed as rank largest to smallest based on "%s"',e),index:()=>vs("Displayed as index")},documentation:{no_calculations:vs("Displays the value that is entered in the field."),"%_of_grand_total":vs("Displays values as a percentage of the grand total of all the values or data points in the report."),"%_of_col_total":vs("Displays all the values in each column or series as a percentage of the total for the column or series."),"%_of_row_total":vs("Displays the value in each row or category as a percentage of the total for the row or category."),"%_of":vs("Displays values as a percentage of the value of the Base item in the Base field."),"%_of_parent_row_total":vs("Calculates values as follows:\n(value for the item) / (value for the parent item on rows)"),"%_of_parent_col_total":vs("Calculates values as follows:\n(value for the item) / (value for the parent item on columns)"),"%_of_parent_total":vs("Calculates values as follows:\n(value for the item) / (value for the parent item of the selected Base field)"),difference_from:vs("Displays values as the difference from the value of the Base item in the Base field."),"%_difference_from":vs("Displays values as the percentage difference from the value of the Base item in the Base field."),running_total:vs("Displays the value for successive items in the Base field as a running total."),"%_running_total":vs("Calculates the value as a percentage for successive items in the Base field that are displayed as a running total."),rank_asc:vs("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:vs("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:vs("Calculates values as follows:\n((value in cell) x (Grand Total of Grand Totals)) / ((Grand Row Total) x (Grand Column Total))")}};class Fg{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 Pg=new Fg;function Mg(e){return Pg.get(e)}const Ng={normalizeFunctionValue:e=>So(e,Fc),toValueAndFormat:(e,t)=>({value:So(e,Fc),format:"dd mmm yyyy"}),toFunctionValue(e){const t=Do(e,Fc);return`DATE(${t.getFullYear()},${t.getMonth()+1},${t.getDate()})`}},Lg={normalizeFunctionValue(e){const t=So(e,Fc);if(t<1||t>31)throw new ys(vs("%s is not a valid day of month (it should be a number between 1 and 31)",t));return t},toValueAndFormat:e=>({value:So(e,Fc),format:"0"}),toFunctionValue:e=>`${e}`},kg={normalizeFunctionValue(e){const t=So(e,Fc);if(t<1||t>7)throw new ys(vs("%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||Fc).weekStart)%7;return{value:gn[s].toString(),format:"@"}},toFunctionValue:e=>`${e}`},Vg={normalizeFunctionValue(e){const t=So(e,Fc);if(t<0||t>53)throw new ys(vs("%s is not a valid week (it should be a number between 0 and 53)",t));return t},toValueAndFormat:e=>({value:So(e,Fc),format:"0"}),toFunctionValue:e=>`${e}`},Ug={normalizeFunctionValue(e){const t=So(e,Fc);if(t<1||t>12)throw new ys(vs("%s is not a valid month (it should be a number between 1 and 12)",t));return t},toValueAndFormat:e=>({value:un[So(e,Fc)-1].toString(),format:"@"}),toFunctionValue:e=>`${e}`},Hg={normalizeFunctionValue:e=>mn(So(e,Fc),{locale:Fc,format:"mm/yyyy"}),toValueAndFormat:e=>({value:So(e,Fc),format:"mmmm yyyy"}),toFunctionValue(e){const t=Do(e,Fc);return`DATE(${t.getFullYear()},${t.getMonth()+1},1)`}},zg={normalizeFunctionValue(e){const t=So(e,Fc);if(t<1||t>4)throw new ys(vs("%s is not a valid quarter (it should be a number between 1 and 4)",t));return t},toValueAndFormat:e=>({value:vs("Q%(quarter_number)s",{quarter_number:e}),format:"@"}),toFunctionValue:e=>`${e}`},Bg={normalizeFunctionValue(e){const t=So(e,Fc);return t>3e3?Do(t,Fc).getFullYear():t},toValueAndFormat:e=>({value:So(e,Fc),format:"0"}),toFunctionValue:e=>`${e}`},Gg={normalizeFunctionValue(e){const t=So(e,Fc);if(t<0||t>23)throw new ys(vs("%s is not a valid hour (it should be a number between 0 and 23)",t));return t},toValueAndFormat:e=>({value:vs("%(hour_number)sh",{hour_number:e}),format:"@"}),toFunctionValue:e=>`${e}`},Wg={normalizeFunctionValue(e){const t=So(e,Fc);if(t<0||t>59)throw new ys(vs("%s is not a valid minute (it should be a number between 0 and 59)",t));return t},toValueAndFormat:e=>({value:vs("%(minute_number)s'",{minute_number:e}),format:"@"}),toFunctionValue:e=>`${e}`},$g={normalizeFunctionValue(e){const t=So(e,Fc);if(t<0||t>59)throw new ys(vs("%s is not a valid second (it should be a number between 0 and 59)",t));return t},toValueAndFormat:e=>({value:vs("%(second_number)s''",{second_number:e}),format:"@"}),toFunctionValue:e=>`${e}`};function qg(e){return{normalizeFunctionValue:t=>null===t?null:e.normalizeFunctionValue(t),toValueAndFormat:(t,s)=>null===t?{value:vs("(Undefined)")}:e.toValueAndFormat(t,s),toFunctionValue:t=>null===t?"false":e.toFunctionValue(t)}}Pg.add("day",qg(Ng)).add("year",qg(Bg)).add("day_of_month",qg(Lg)).add("iso_week_number",qg(Vg)).add("month_number",qg(Ug)).add("month",qg(Hg)).add("quarter_number",qg(zg)).add("day_of_week",qg(kg)).add("hour_number",qg(Gg)).add("minute_number",qg(Wg)).add("second_number",qg($g));const Zg={displayTotals:!0,displayColumnHeaders:!0,displayMeasuresRow:!0,numberOfRows:Number.MAX_VALUE,numberOfColumns:Number.MAX_VALUE},jg={count:vs("Count"),count_distinct:vs("Count Distinct"),bool_and:vs("Boolean And"),bool_or:vs("Boolean Or"),max:vs("Maximum"),min:vs("Minimum"),avg:vs("Average"),sum:vs("Sum")},Yg=["max","min","avg","sum","count_distinct","count"],Xg={integer:Yg,char:Yg,datetime:Yg,boolean:["count_distinct","count","bool_and","bool_or"]},Kg={};for(const e in Xg){Kg[e]={};for(const t of Xg[e])Kg[e][t]=jg[t]}const Jg={count:e=>({value:qa([e]),format:"0"}),count_distinct:e=>({value:xr([e]),format:"0"}),bool_and:e=>({value:lg([e]).result}),bool_or:e=>({value:cg([e]).result}),max:(e,t)=>Za([e],t),min:(e,t)=>ja([e],t),avg:(e,t)=>({value:Wa([e],t),format:mo(e)}),sum:(e,t)=>({value:Rr([e],t),format:mo(e)})};function Qg(e){const t=Object.keys(e);if(!t.length)return 0;const s=t.map(e=>parseInt(e,10));return Math.max(...s)}const ep={year:vs("Year"),quarter:vs("Quarter & Year"),month:vs("Month & Year"),week:vs("Week & Year"),day:vs("Day"),quarter_number:vs("Quarter"),month_number:vs("Month"),iso_week_number:vs("Week"),day_of_month:vs("Day of Month"),day_of_week:vs("Day of Week"),hour_number:vs("Hour"),minute_number:vs("Minute"),second_number:vs("Second")},tp=["date","datetime"];function sp(e){const[t,s]=e.split(":");return s?{fieldName:t,granularity:s}:{fieldName:t}}function op(e){return tp.includes(e.type)}function ip(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}=sp(e),n=cp(s,{type:i,granularity:t});o.push(`"${e}"`,n)}return o}function np(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 rp(e,t){switch(t.type){case"HEADER":return`=PIVOT.HEADER(${ip(e,t.domain).join(",")})`;case"VALUE":return`=PIVOT.VALUE(${ip(e,t.domain,t.measure).join(",")})`;case"MEASURE_HEADER":return`=PIVOT.HEADER(${ip(e,[...t.domain,{field:"measure",value:t.measure,type:"char"}]).join(",")})`}return""}function ap(e,t){if(null===t||"null"===t)return null;const s="object"==typeof t?t.value:t;if(fo(s))return s;if("custom"===e.type)return _o(t)??null;const o="boolean"==typeof t?Ro(t).toLocaleLowerCase():Ro(t);if("null"===o)return null;if(!dp.contains(e.type))throw new ys(vs("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 dp.get(e.type)(o,e.granularity)}function lp(e,t){return Mg(t??"month").normalizeFunctionValue(e)}function cp(e,t){return null===e?'"null"':up.contains(t.type)?up.get(t.type)(e,t.granularity):`"${e}"`}function hp(e,t){return Mg(t??"month").toFunctionValue(e)}const dp=new Fg;dp.add("date",lp).add("datetime",lp).add("integer",e=>So(e,Fc)).add("boolean",e=>Ao(e)).add("char",e=>Ro(e)).add("custom",e=>e);const up=new Fg;function gp(e){return e.displayName+(e.granularity?` (${ep[e.granularity]})`:"")}function pp(e,t){return 0===e.length?t:{...t,format:(t.format||"@")+"* "}}function mp(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 fp(e,t){return st(e,t.groups.map(e=>e.name),{compute:(e,t)=>`${e}${t}`,start:2})}function vp(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 bp(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 Sp(e,t){t.groups=t.groups.filter(t=>!t.values.some(t=>e.includes(t)))}function Cp(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 yp(e,t,s){return Object.values(e.customFields||{}).find(e=>e.parentField===t.name)||{parentField:t.name,name:vp(t.string,s),groups:[]}}function Ip(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 wp(e,t,s,o,i,n,r){const a=e.style;return{numberOfRows:void 0!==t?So(t,r):a?.numberOfRows??Zg.numberOfRows,numberOfColumns:void 0!==i?So(i,r):a?.numberOfColumns??Zg.numberOfColumns,displayTotals:void 0!==s?Ao(s):a?.displayTotals??Zg.displayTotals,displayColumnHeaders:void 0!==o?Ao(o):a?.displayColumnHeaders??Zg.displayColumnHeaders,displayMeasuresRow:void 0!==n?Ao(n):a?.displayMeasuresRow??Zg.displayMeasuresRow}}function Ep(e,t){const s=t.getPivotId(e);if(!s)throw new ys(vs('There is no pivot with id "%s"',e));return s}function Rp(e){if(e.length%2!=0)throw new ys(vs("Function PIVOT takes an even number of arguments."))}function xp(e,t,s){const o=[];if("SPREADSHEET"===t.type&&t.dataSet){const{sheetId:s,zone:i}=t.dataSet,n=Dt(i),r=e.getters.getRangeFromSheetXC(s,n);if(void 0===r||r.invalidXc||r.invalidSheetName)throw new Es;if(e.__originCellPosition&&r.sheetId===e.__originSheetId&&Ht(jt(e.__originCellPosition),i))throw new ws;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))}up.add("date",hp).add("datetime",hp).add("integer",e=>`${So(e,Fc)}`).add("boolean",e=>Ao(e)?"TRUE":"FALSE").add("char",e=>`"${Ro(e).replace(/"/g,'\\"')}"`).add("custom",e=>"string"==typeof e?`"${e}"`:String(e));const Tp=!0,Ap=[{value:!0,label:vs("A1 style (default)")},{value:!1,label:vs("R1C1 style")}],Dp=[{value:!0,label:vs("Approximate match (default)")},{value:!1,label:vs("Exact match")}],_p={description:vs("Returns a cell reference as a string. "),args:[ls("row (number)",vs("The row number of the cell reference. ")),ls("column (number)",vs("The column number (not name) of the cell reference. A is column number 1. ")),ls("absolute_relative_mode (number, default=1)",vs("An indicator of whether the reference is row/column absolute."),[{value:1,label:vs("Absolute row and column (e.g. $A$1)")},{value:2,label:vs("Absolute row, relative column (e.g. A$1)")},{value:3,label:vs("Relative row, absolute column (e.g. $A1)")},{value:4,label:vs("Relative row and column (e.g. A1)")}]),ls("use_a1_notation (boolean, default=TRUE)",vs("A boolean indicating whether to use A1 style notation or R1C1 style notation."),Ap),ls("sheet (string, optional)",vs("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=Eo(e,this.locale),r=Eo(t,this.locale);if(n<1)return new ys(ui(n));if(r<1)return new ys(ui(r));const a=Eo(s,this.locale);if(![1,2,3,4].includes(a))return new ys((l=4,c=a,vs("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(Ao(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?or(Ro(i),h):h},isExported:!0},Op={description:vs("Column number of a specified cell."),args:[ls("cell_reference (meta, range<meta>, default='this cell')",vs("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 ys(vs("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 ys(vs("The range is out of bounds."));if(e[0][0].value===Ss.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:Vo(e.length,1,(e,s)=>({value:t+e+1}))},isExported:!0},Fp={description:vs("Number of columns in a specified array or range."),args:[ls("range (any, range<any>)",vs("The range whose column count will be returned."))],compute:function(e){const t=Ko(e);return void 0===t[0][0]?new ys(vs("The range is out of bounds.")):t[0][0].value===Ss.InvalidReference?t[0][0]:t.length},isExported:!0},Pp={description:vs("Horizontal lookup"),args:[ls("search_key (string, number, boolean)",vs("The value to search for. For example, 42, 'Cats', or I24.")),ls("range (any, range)",vs("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")),ls("index (number)",vs("The row index of the value to be returned, where the first row in range is numbered 1.")),ls("is_sorted (boolean, default=true)",vs("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."),Dp)],compute:function(e,t,s,o={value:Tp}){const i=Math.trunc(So(s?.value,this.locale)),n=Ko(t);if(1>i||i>n[0].length)return new ys(vs("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const r=(e,t)=>e[t][0].value,a=n[Ao(o.value)?Zo(n,e,"nextSmaller","asc",n.length,r):jo(n,e,"wildcard",n.length,r,this.lookupCaches)];return void 0===a?vo(e):a[i-1]},isExported:!0},Mp={description:vs("Returns the content of a cell, specified by row and column offset."),args:[ls("reference (any, range)",vs("The range of cells from which the values are returned.")),ls("row (number, default=0)",vs("The index of the row to be returned from within the reference range of cells.")),ls("column (number, default=0)",vs("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=Ko(e),i=So(t.value,this.locale),n=So(s.value,this.locale);return n<0||n-1>=o.length||i<0||i-1>=o[0].length?new ys(vs("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},Np={description:vs("Returns the content of a cell, specified by a string."),args:[ls("reference (string)",vs("The range of cells from which the values are returned.")),ls("use_a1_notation (boolean, default=TRUE)",vs("A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE)."),Ap)],compute:function(e,t={value:!0}){const s=e?.value?.toString();if(!s)return new Es(vs("Reference should be defined."));if(!Ao(t))return new ys(vs("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 Es;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},Lp={description:vs("Look up a value."),args:[ls("search_key (string, number, boolean)",vs("The value to search for. For example, 42, 'Cats', or I24.")),ls("search_array (any, range)",vs("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.")),ls("result_range (any, range, optional)",vs("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=Ko(t),i=Ko(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=Zo(o,e,"nextSmaller","asc",a?r:n,l);return-1===c||a&&void 0===o[0][c]||!a&&void 0===o[c][r-1]?vo(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 ys(vs("The result_range must be a single row or a single column.")):n>1?c>n-1?new ys(vs("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",c+1)):i[c][0]:c>r-1?new ys(vs("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",c+1)):i[0][c])},isExported:!0},kp={description:vs("Position of item in range that matches value."),args:[ls("search_key (string, number, boolean)",vs("The value to search for. For example, 42, 'Cats', or I24.")),ls("range (any, range)",vs("The one-dimensional array to be searched.")),ls("search_type (number, default=1)",vs("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:vs("Ascending order (default)")},{value:0,label:vs("Exact match")},{value:-1,label:vs("Descending order")}])],compute:function(e,t,s={value:1}){let o=So(s,this.locale);const i=Ko(t),n=i.length,r=i[0].length;if(1!==n&&1!==r)return new ys(vs("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=Zo(i,e,"nextSmaller","asc",c,l);break;case 0:a=jo(i,e,"wildcard",c,l,this.lookupCaches);break;case-1:a=Zo(i,e,"nextGreater","desc",c,l)}return 1===n&&void 0===i[0][a]||1!==n&&void 0===i[a]?vo(e):a+1},isExported:!0},Vp={description:vs("Row number of a specified cell."),args:[ls("cell_reference (meta, range<meta>, default='this cell')",vs("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 ys(vs("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 ys(vs("The range is out of bounds."));if(e[0][0].value===Ss.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:Vo(1,e[0].length,(e,s)=>({value:t+s+1}))},isExported:!0},Up={description:vs("Number of rows in a specified array or range."),args:[ls("range (any, range<any>)",vs("The range whose row count will be returned."))],compute:function(e){const t=Ko(e);return void 0===t[0][0]?new ys(vs("The range is out of bounds.")):t[0][0].value===Ss.InvalidReference?t[0][0]:t[0].length},isExported:!0},Hp={description:vs("Vertical lookup."),args:[ls("search_key (string, number, boolean)",vs("The value to search for. For example, 42, 'Cats', or I24.")),ls("range (any, range)",vs("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")),ls("index (number)",vs("The column index of the value to be returned, where the first column in range is numbered 1.")),ls("is_sorted (boolean, default=true)",vs("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."),Dp)],compute:function(e,t,s,o={value:Tp}){const i=Math.trunc(So(s?.value,this.locale)),n=Ko(t);if(1>i||i>n.length)return new ys(vs("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const r=(e,t)=>e[0][t].value,a=Ao(o.value)?Zo(n,e,"nextSmaller","asc",n[0].length,r):jo(n,e,"wildcard",n[0].length,r,this.lookupCaches),l=n[i-1][a];return void 0===l?vo(e):l},isExported:!0},zp={0:"strict",1:"nextGreater","-1":"nextSmaller",2:"wildcard"},Bp={description:vs("Search a range for a match and return the corresponding item from a second range."),args:[ls("search_key (string,number,boolean)",vs("The value to search for.")),ls("lookup_range (any, range)",vs("The range to consider for the search. Should be a single column or a single row.")),ls("return_range (any, range)",vs("The range containing the return value. Should have the same dimensions as lookup_range.")),ls("if_not_found (any, optional)",vs("If a valid match is not found, return this value.")),ls("match_mode (any, default=0)",vs("Specifies how to match search_key with the items in lookup_range. "),[{value:0,label:vs("Exact match (default)")},{value:-1,label:vs("Exact match or next smaller item")},{value:1,label:vs("Exact match or next larger item")},{value:2,label:vs("Wildcard character match")}]),ls("search_mode (any, default=1)",vs("Specifies the search mode to use. By default, a first to last search will be used."),[{value:1,label:vs("Search first to last (default)")},{value:-1,label:vs("Search last to first")},{value:2,label:vs("Binary search (sorted ascending order)")},{value:-2,label:vs("Binary search (sorted descending order)")}])],compute:function(e,t,s,o,i={value:0},n={value:1}){const r=Math.trunc(So(i.value,this.locale)),a=Math.trunc(So(n.value,this.locale)),l=Ko(t),c=Ko(s);if(1!==l.length&&1!==l[0].length)return new ys(vs("lookup_range should be either a single row or single column."));if(![1,-1,2,-2].includes(a))return new ys(vs("search_mode should be a value in [-1, 1, -2, 2]."));if(![-1,0,1,2].includes(r))return new ys(vs("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 ys(vs("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 ys(vs("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=zp[r],p=-1===a,m=2===a||-2===a?Zo(l,e,g,2===a?"asc":"desc",u,d):jo(l,e,g,u,d,this.lookupCaches,p);return-1!==m?"col"===h?c.map(e=>[e[m]]):[c[m]]:void 0===o?vo(e):[[o]]},isExported:!0},Gp={description:vs("Get the value from a pivot."),args:[ls("pivot_id (number,string)",vs("ID of the pivot.")),ls("measure_name (string)",vs("Name of the measure.")),ls("domain_field_name (string,repeating,optional)",vs("Field name.")),ls("domain_value (number,string,boolean,repeating,optional)",vs("Value."))],compute:function(e,t,...s){const o=Ro(e),i=Ro(t),n=Ep(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 ys(vs("The argument %s is not a valid measure. Here are the measures: %s",t,e))}}(n,i,this.getters),Rp(s);const r=this.getters.getPivot(n),a=this.getters.getPivotCoreDefinition(n);xp(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=vs("Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.",`=PIVOT(${o})`);return{value:Ss.GenericError,message:vs("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)}},Wp={description:vs("Get the header of a pivot."),args:[ls("pivot_id (number,string)",vs("ID of the pivot.")),ls("domain_field_name (string,repeating,optional)",vs("Field name.")),ls("domain_value (number,string,value,repeating,optional)",vs("Value."))],compute:function(e,...t){const s=Ro(e),o=Ep(s,this.getters);Rp(t);const i=this.getters.getPivot(o);xp(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=vs("Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.",`=PIVOT(${s})`);return{value:Ss.GenericError,message:vs("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(Ro(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}}},$p={description:vs("Get a pivot table."),args:[ls("pivot_id (string)",vs("ID of the pivot.")),ls("row_count (number, optional)",vs("number of rows")),ls("include_total (boolean, default=TRUE)",vs("Whether to include total/sub-totals or not.")),ls("include_column_titles (boolean, default=TRUE)",vs("Whether to include the column titles or not.")),ls("column_count (number, optional)",vs("number of columns")),ls("include_measure_titles (boolean, default=TRUE)",vs("Whether to include the measure titles row or not."))],compute:function(e,t,s,o,i,n){const r=Ep(Ro(e),this.getters),a=this.getters.getPivot(r),l=this.getters.getPivotCoreDefinition(r),c=wp(l,t,s,o,i,n,this.locale);if(c.numberOfRows<0)return new ys(vs("The number of rows must be positive."));if(c.numberOfColumns<0)return new ys(vs("The number of columns must be positive."));xp(this,l,l.measures),a.init({reload:a.needsReevaluation});const h=a.assertIsValid({throwOnError:!1});if(h)return h;const d=a.getCollapsedTableStructure();if(d.numberOfCells>Q)return new ys(function(e,t){const s=mn(e,{format:"0,00",locale:t});return vs("Oops—this pivot table is quite large (%s cells). Try simplifying it using the side panel.",s)}(d.numberOfCells,this.locale));const u=d.getPivotCells(c);let g=0;c.displayColumnHeaders&&(g=d.columns.length-1),c.displayMeasuresRow&&g++;const p=this.getters.getPivotName(r),m=Math.min(g+c.numberOfRows,u[0].length);if(0===m)return[[{value:p}]];const f=Math.min(1+c.numberOfColumns,u.length),v=[];for(const e of ge(0,f)){v[e]=[];for(const t of ge(0,m)){const s=u[e][t];switch(s.type){case"EMPTY":v[e].push({value:""});break;case"HEADER":const t=a.getPivotHeaderValueAndFormat(s.domain);v[e].push(pp(s.domain,t));break;case"MEASURE_HEADER":v[e].push(a.getPivotMeasureValue(s.measure,s.domain));break;case"VALUE":v[e].push(a.getPivotCellValueAndFormat(s.measure,s.domain))}}}return(c.displayColumnHeaders||c.displayMeasuresRow)&&(v[0][0]={value:p}),v}},qp={description:vs("Returns a range reference shifted by a specified number of rows and columns from a starting cell reference."),args:[ls("cell_reference (meta, range<meta>)",vs("The starting point from which to count the offset rows and columns.")),ls("offset_rows (number)",vs("The number of rows to offset by.")),ls("offset_columns (number)",vs("The number of columns to offset by.")),ls("height (number, default='height of cell_reference')",vs("The number of rows of the range to return starting at the offset target.")),ls("width (number, default='width of cell_reference')",vs("The number of columns of the range to return starting at the offset target."))],compute:function(e,t,s,o,i){if(fo(e[0][0].value))return e[0][0];const n=e[0][0].value;if(!n)return new ys("In this context, the function OFFSET needs to have a cell or range in parameter.");const r=Rt(n);let a=e[0].length,l=e.length;if(o){const e=So(o,this.locale);if(e<1)return new ys(vs("Height value is %(_height)s. It should be greater than or equal to 1.",{_height:e}));a=e}if(i){const e=So(i,this.locale);if(e<1)return new ys(vs("Width value is %(_width)s. It should be greater than or equal to 1.",{_width:e}));l=e}const{sheetName:c}=sr(n),h=c&&this.getters.getSheetIdByName(c)||this.getters.getActiveSheetId(),d=So(t,this.locale),u=So(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 Es(vs("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 Es:(g&&this.addDependencies?.(g,[v]),Vo(l,a,(e,t)=>this.getters.getEvaluatedCell({sheetId:h,col:p+e,row:m+t})))}};var Zp=Object.freeze({__proto__:null,ADDRESS:_p,COLUMN:Op,COLUMNS:Fp,HLOOKUP:Pp,INDEX:Mp,INDIRECT:Np,LOOKUP:Lp,MATCH:kp,OFFSET:qp,PIVOT:$p,PIVOT_HEADER:Wp,PIVOT_VALUE:Gp,ROW:Vp,ROWS:Up,VLOOKUP:Hp,XLOOKUP:Bp});const jp={description:vs("Sum of two numbers."),args:[ls("value1 (number)",vs("The first addend.")),ls("value2 (number)",vs("The second addend."))],compute:function(e,t){return{value:So(e,this.locale)+So(t,this.locale),format:e?.format||t?.format}}},Yp={description:vs("Concatenation of two values."),args:[ls("value1 (string)",vs("The value to which value2 will be appended.")),ls("value2 (string)",vs("The value to append to value1."))],compute:function(e,t){return Ro(e)+Ro(t)},isExported:!0},Xp={description:vs("One number divided by another."),args:[ls("dividend (number)",vs("The number to be divided.")),ls("divisor (number)",vs("The number to divide by."))],compute:function(e,t){const s=So(t,this.locale);return 0===s?new As(vs("The divisor must be different from zero.")):{value:So(e,this.locale)/s,format:e?.format||t?.format}}};function Kp(e){return void 0===e||null===e.value}const Jp={number:0,string:"",boolean:!1};function Qp(e,t,s=2e-16){return Math.abs(e-t)<s}const em={description:vs("Equal."),args:[ls("value1 (string, number, boolean)",vs("The first value.")),ls("value2 (string, number, boolean)",vs("The value to test against value1 for equality."))],compute:function(e,t){if(fo(e?.value))return e;if(fo(t?.value))return t;let s=Kp(e)?Jp[typeof t?.value]:e?.value,o=Kp(t)?Jp[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:Qp(s,o)}:{value:s===o}}};function tm(e,t,s){if(fo(e?.value))return e;if(fo(t?.value))return t;let o=Kp(e)?Jp[typeof t?.value]:e?.value,i=Kp(t)?Jp[typeof e?.value]:t?.value;"number"!=typeof o&&(o=Ro(o).toUpperCase()),"number"!=typeof i&&(i=Ro(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 sm={description:vs("Strictly greater than."),args:[ls("value1 (number, string, boolean)",vs("The value to test as being greater than value2.")),ls("value2 (number, string, boolean)",vs("The second value."))],compute:function(e,t){return tm(e,t,(e,t)=>"number"==typeof e&&"number"==typeof t?!Qp(e,t)&&e>t:e>t)}},om={description:vs("Greater than or equal to."),args:[ls("value1 (number, string, boolean)",vs("The value to test as being greater than or equal to value2.")),ls("value2 (number, string, boolean)",vs("The second value."))],compute:function(e,t){return tm(e,t,(e,t)=>"number"==typeof e&&"number"==typeof t?Qp(e,t)||e>t:e>=t)}},im={description:vs("Less than."),args:[ls("value1 (number, string, boolean)",vs("The value to test as being less than value2.")),ls("value2 (number, string, boolean)",vs("The second value."))],compute:function(e,t){const s=om.compute.bind(this)(e,t);return fo(s.value)?s:{value:!s.value}}},nm={description:vs("Less than or equal to."),args:[ls("value1 (number, string, boolean)",vs("The value to test as being less than or equal to value2.")),ls("value2 (number, string, boolean)",vs("The second value."))],compute:function(e,t){const s=sm.compute.bind(this)(e,t);return fo(s.value)?s:{value:!s.value}}},rm={description:vs("Difference of two numbers."),args:[ls("value1 (number)",vs("The minuend, or number to be subtracted from.")),ls("value2 (number)",vs("The subtrahend, or number to subtract from value1."))],compute:function(e,t){return{value:So(e,this.locale)-So(t,this.locale),format:e?.format||t?.format}}},am={description:vs("Product of two numbers"),args:[ls("factor1 (number)",vs("The first multiplicand.")),ls("factor2 (number)",vs("The second multiplicand."))],compute:function(e,t){return{value:So(e,this.locale)*So(t,this.locale),format:e?.format||t?.format}}},lm={description:vs("Not equal."),args:[ls("value1 (string, number, boolean)",vs("The first value.")),ls("value2 (string, number, boolean)",vs("The value to test against value1 for inequality."))],compute:function(e,t){const s=em.compute.bind(this)(e,t);return fo(s.value)?s:{value:!s.value}}},cm={description:vs("A number raised to a power."),args:[ls("base (number)",vs("The number to raise to the exponent power.")),ls("exponent (number)",vs("The exponent to raise base to."))],compute:function(e,t){return fa.compute.bind(this)(e,t)}},hm={description:vs("A number with the sign reversed."),args:[ls("value (number)",vs("The number to have its sign reversed. Equivalently, the number to multiply by -1."))],compute:function(e){return{value:-So(e,this.locale),format:e?.format}}},dm={description:vs("Value interpreted as a percentage."),args:[ls("percentage (number)",vs("The value to interpret as a percentage."))],compute:function(e){return So(e,this.locale)/100}},um={description:vs("A specified number, unchanged."),args:[ls("value (any)",vs("The number to return."))],compute:function(e={value:null}){return e}};var gm=Object.freeze({__proto__:null,ADD:jp,CONCAT:Yp,DIVIDE:Xp,EQ:em,GT:sm,GTE:om,LT:im,LTE:nm,MINUS:rm,MULTIPLY:am,NE:lm,POW:cm,UMINUS:hm,UNARY_PERCENT:dm,UPLUS:um});const pm=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),mm={transform:e=>e,inverseTransform:e=>e},fm=1e-10,vm=.0254,bm=vm/72,Sm=.3048,Cm=.9144,ym=1609.34,Im=1852,wm=946073047258e4,Em={g:{...mm,category:"weight"},u:{...pm(166053e-29),category:"weight"},grain:{...pm(.0647989),category:"weight"},ozm:{...pm(28.3495),category:"weight"},lbm:{...pm(453.592),category:"weight"},stone:{...pm(6350.29),category:"weight"},sg:{...pm(14593.90294),category:"weight"},cwt:{...pm(45359.237),category:"weight"},uk_cwt:{...pm(50802.3),category:"weight"},ton:{...pm(907184.74),category:"weight"},uk_ton:{...pm(1016046.9),category:"weight"},m:{...mm,category:"distance"},km:{...pm(1e3),category:"distance"},ang:{...pm(fm),category:"distance"},Picapt:{...pm(bm),category:"distance"},pica:{...pm(vm/6),category:"distance"},in:{...pm(vm),category:"distance"},ft:{...pm(Sm),category:"distance"},yd:{...pm(Cm),category:"distance"},ell:{...pm(1.143),category:"distance"},mi:{...pm(ym),category:"distance"},survey_mi:{...pm(1609.34),category:"distance"},Nmi:{...pm(Im),category:"distance"},ly:{...pm(wm),category:"distance"},parsec:{...pm(0x6da012f95c9fd0),category:"distance"},sec:{...mm,category:"time"},min:{...pm(60),category:"time"},hr:{...pm(3600),category:"time"},day:{...pm(86400),category:"time"},yr:{...pm(31556952),category:"time"},Pa:{...mm,category:"pressure"},bar:{...pm(1e5),category:"pressure"},mmHg:{...pm(133.322),category:"pressure"},Torr:{...pm(133.322),category:"pressure"},psi:{...pm(6894.76),category:"pressure"},atm:{...pm(101325),category:"pressure"},N:{...mm,category:"force"},dyn:{...pm(1e-5),category:"force"},pond:{...pm(.00980665),category:"force"},lbf:{...pm(4.44822),category:"force"},J:{...mm,category:"energy"},eV:{...pm(160218e-24),category:"energy"},e:{...pm(1e-7),category:"energy"},flb:{...pm(1.3558179483),category:"energy"},c:{...pm(4.184),category:"energy"},cal:{...pm(4.1868),category:"energy"},BTU:{...pm(1055.06),category:"energy"},Wh:{...pm(3600),category:"energy"},HPh:{...pm(2684520),category:"energy"},W:{...mm,category:"power"},PS:{...pm(735.499),category:"power"},HP:{...pm(745.7),category:"power"},T:{...mm,category:"magnetism"},ga:{...pm(1e-4),category:"magnetism"},K:{...mm,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:{...pm(5/9),category:"temperature"},Reau:{transform:e=>1.25*e+273.15,inverseTransform:e=>(e-273.15)/1.25,category:"temperature"},"m^3":{...mm,category:"volume",order:3},"ang^3":{...pm(Math.pow(fm,3)),category:"volume",order:3},"Picapt^3":{...pm(Math.pow(bm,3)),category:"volume",order:3},tsp:{...pm(492892e-11),category:"volume"},tspm:{...pm(5e-6),category:"volume"},tbs:{...pm(14786764825785619e-21),category:"volume"},"in^3":{...pm(Math.pow(vm,3)),category:"volume",order:3},oz:{...pm(295735295625e-16),category:"volume"},cup:{...pm(237e-6),category:"volume"},pt:{...pm(.0004731765),category:"volume"},uk_pt:{...pm(568261e-9),category:"volume"},qt:{...pm(.0009463529),category:"volume"},l:{...pm(.001),category:"volume"},uk_qt:{...pm(.0011365225),category:"volume"},gal:{...pm(.0037854118),category:"volume"},uk_gal:{...pm(.00454609),category:"volume"},"ft^3":{...pm(Math.pow(Sm,3)),category:"volume",order:3},bushel:{...pm(.0352390704),category:"volume"},barrel:{...pm(.158987295),category:"volume"},"yd^3":{...pm(Math.pow(Cm,3)),category:"volume",order:3},MTON:{...pm(1.13267386368),category:"volume"},GRT:{...pm(2.83168),category:"volume"},"mi^3":{...pm(Math.pow(ym,3)),category:"volume",order:3},"Nmi^3":{...pm(Math.pow(Im,3)),category:"volume",order:3},"ly^3":{...pm(Math.pow(wm,3)),category:"volume",order:3},"m^2":{...mm,category:"area",order:2},"ang^2":{...pm(Math.pow(fm,2)),category:"area",order:2},"Picapt^2":{...pm(Math.pow(bm,2)),category:"area",order:2},"in^2":{...pm(Math.pow(vm,2)),category:"area",order:2},"ft^2":{...pm(Math.pow(Sm,2)),category:"area",order:2},"yd^2":{...pm(Math.pow(Cm,2)),category:"area",order:2},ar:{...pm(100),category:"area"},Morgen:{...pm(2500),category:"area"},uk_acre:{...pm(4046.8564224),category:"area"},us_acre:{...pm(4046.8726098743),category:"area"},ha:{...pm(1e4),category:"area"},"mi^2":{...pm(Math.pow(ym,2)),category:"area",order:2},"Nmi^2":{...pm(Math.pow(Im,2)),category:"area",order:2},"ly^2":{...pm(Math.pow(wm,2)),category:"area",order:2},bit:{...mm,category:"information"},byte:{...pm(8),category:"information"},"m/s":{...mm,category:"speed"},"m/hr":{...pm(1/3600),category:"speed"},"km/hr":{...pm(1/3.6),category:"speed"},mph:{...pm(.44704),category:"speed"},kn:{...pm(.5144444444),category:"speed"},admkn:{...pm(.5147733333),category:"speed"}},Rm={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"},xm={"":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)},Tm={weight:vs("Weight"),distance:vs("Distance"),time:vs("Time"),pressure:vs("Pressure"),force:vs("Force"),energy:vs("Energy"),power:vs("Power"),magnetism:vs("Magnetism"),temperature:vs("Temperature"),volume:vs("Volume"),area:vs("Area"),information:vs("Information"),speed:vs("Speed")},Am=Object.entries(Em).map(([e,t])=>({value:e,label:Dm(t.category)}));function Dm(e){return Tm[e]??""}function _m(e){for(const[t,s]of Object.entries(xm)){if(t&&!e.startsWith(t))continue;const o=e.slice(t.length);let i=Em[o];if(!i&&Rm[o]&&(i=Em[Rm[o]]),i)return{...i,factor:i.order?Math.pow(s,i.order):s}}}const Om={description:vs("Converts a numeric value to a different unit of measure."),args:[ls("value (number)",vs("the numeric value in start_unit to convert to end_unit")),ls("start_unit (string)",vs("The starting unit, the unit currently assigned to value"),Am),ls("end_unit (string)",vs("The unit of measure into which to convert value"),Am)],compute:function(e,t,s){const o=So(e,this.locale),i=Ro(t),n=Ro(s),r=_m(i),a=_m(n);return r?a?r.category!==a.category?{value:Ss.GenericError,message:vs("Incompatible units of measure ('%s' vs '%s')",Dm(r.category),Dm(a.category))}:{value:a.inverseTransform(r.factor*r.transform(o))/a.factor,format:e?.format}:{value:Ss.GenericError,message:vs("Invalid units of measure ('%s')",n)}:{value:Ss.GenericError,message:vs("Invalid units of measure ('%s')",i)}},isExported:!0};var Fm=Object.freeze({__proto__:null,CONVERT:Om});const Pm=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,Mm=[{value:0,label:vs("Case-sensitive (default)")},{value:1,label:vs("Case-insensitive")}],Nm=[{value:0,label:vs("Don't match to end (default)")},{value:1,label:vs("Match to end")}],Lm={description:vs("Gets character associated with number."),args:[ls("table_number (number)",vs("The number of the character to look up from the current Unicode table in decimal format."))],compute:function(e){const t=Math.trunc(So(e,this.locale));return t<1?new ys(vs("The table_number (%s) is out of range.",t)):String.fromCharCode(t)},isExported:!0},km={description:vs("Remove non-printable characters from a piece of text."),args:[ls("text (string)",vs("The text whose non-printable characters are to be removed."))],compute:function(e){const t=Ro(e);let s="";for(const e of t)e&&e.charCodeAt(0)>31&&(s+=e);return s},isExported:!0},Vm={description:vs("Appends strings to one another."),args:[ls("string (string, range<string>, repeating)",vs("String to append in sequence."))],compute:function(...e){return No(e,(e,t)=>e+Ro(t),"")},isExported:!0},Um={description:vs("Tests whether two strings are identical."),args:[ls("string1 (string)",vs("The first string to compare.")),ls("string2 (string)",vs("The second string to compare."))],compute:function(e,t){return Ro(e)===Ro(t)},isExported:!0},Hm={description:vs("First position of string found in text, case-sensitive."),args:[ls("search_for (string)",vs("The string to look for within text_to_search.")),ls("text_to_search (string)",vs("The text to search for the first occurrence of search_for.")),ls("starting_at (number, default=1)",vs("The character within text_to_search at which to start the search."))],compute:function(e,t,s={value:1}){const o=Ro(e),i=Ro(t),n=So(s,this.locale);if(""===i)return new ys(vs("The text_to_search must be non-empty."));if(n<1)return new ys(vs("The starting_at (%s) must be greater than or equal to 1.",n));const r=i.indexOf(o,n-1);return-1===r?new ys(vs("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o,i)):r+1},isExported:!0},zm={description:vs("Concatenates elements of arrays with delimiter."),args:[ls("delimiter (string)",vs("The character or string to place between each concatenated value.")),ls("value_or_array (string, range<string>, repeating)",vs("Value to be appended using delimiter."))],compute:function(e,...t){const s=Ro(e);return No(t,(e,t)=>(e?e+s:"")+Ro(t),"")}},Bm={description:vs("Substring from beginning of specified string."),args:[ls("text (string)",vs("The string from which the left portion will be returned.")),ls("number_of_characters (number, optional)",vs("The number of characters to return from the left side of string."))],compute:function(e,...t){const s=t.length?So(t[0],this.locale):1;return s<0?new ys(vs("The number_of_characters (%s) must be positive or null.",s)):Ro(e).substring(0,s)},isExported:!0},Gm={description:vs("Length of a string."),args:[ls("text (string)",vs("The string whose length will be returned."))],compute:function(e){return Ro(e).length},isExported:!0},Wm={description:vs("Converts a specified string to lowercase."),args:[ls("text (string)",vs("The string to convert to lowercase."))],compute:function(e){return Ro(e).toLowerCase()},isExported:!0},$m={description:vs("A segment of a string."),args:[ls("text (string)",vs("The string to extract a segment from.")),ls("starting_at (number)",vs("The index from the left of string from which to begin extracting. The first character in string has the index 1.")),ls("extract_length (number)",vs("The length of the segment to extract."))],compute:function(e,t,s){const o=Ro(e),i=So(t,this.locale),n=So(s,this.locale);return i<1?new ys(vs("The starting_at argument (%s) must be positive greater than one.",i.toString())):n<0?new ys(vs("The extract_length argument (%s) must be positive or null.",n)):o.slice(i-1,i+n-1)},isExported:!0},qm={description:vs("Capitalizes each word in a specified string."),args:[ls("text_to_capitalize (string)",vs("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 Ro(e).replace(Pm,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},Zm={description:vs("Extract text from a string based on the supplied regular expression."),args:[ls("text (string)",vs("The string on which you want to extract text.")),ls("pattern (string)",vs("The regular expression pattern to match against the text.")),ls("return_mode (number, default=0)",vs("0 = first match, 1 = all matches as an array, 2 = capturing groups from the first match as an array."),[{value:0,label:vs("First match")},{value:1,label:vs("All matches")},{value:2,label:vs("Capture groups of first match")}]),ls("case_sensitivity (number, default=0)",vs("Whether the match is case-sensitive."),[{value:0,label:vs("Case-sensitive")},{value:1,label:vs("Case-insensitive")}])],compute:function(e,t,s={value:0},o={value:0}){const i=Ro(e),n=Ro(t),r=So(s,this.locale),a=So(o,this.locale);if(""===i||""===n)return{value:""};if(r<0||r>2)return new ys(vs("The return_mode (%s) must be 0, 1 or 2.",r));if(0!==a&&1!==a)return new ys(vs("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:Ss.NotAvailable,message:vs("No matches found.")}:0===r?c[0][0]:1===r?c.map(e=>[e[0]]):c[0].length<2?new ys(vs("No capturing groups found.")):c[0].slice(1).map(e=>[e])},isExported:!0},jm={description:vs("Replaces part of a text string with different text."),args:[ls("text (string)",vs("The text, a part of which will be replaced.")),ls("position (number)",vs("The position where the replacement will begin (starting from 1).")),ls("length (number)",vs("The number of characters in the text to be replaced.")),ls("new_text (string)",vs("The text which will be inserted into the original text."))],compute:function(e,t,s,o){const i=So(t,this.locale);if(i<1)return new ys(vs("The position (%s) must be greater than or equal to 1.",i));const n=Ro(e),r=So(s,this.locale),a=Ro(o);return n.substring(0,i-1)+a+n.substring(i-1+r)},isExported:!0},Ym={description:vs("A substring from the end of a specified string."),args:[ls("text (string)",vs("The string from which the right portion will be returned.")),ls("number_of_characters (number, optional)",vs("The number of characters to return from the right side of string."))],compute:function(e,...t){const s=t.length?So(t[0],this.locale):1;if(s<0)return new ys(vs("The number_of_characters (%s) must be positive or null.",s));const o=Ro(e),i=o.length;return o.substring(i-s,i)},isExported:!0},Xm={description:vs("First position of string found in text, ignoring case."),args:[ls("search_for (string)",vs("The string to look for within text_to_search.")),ls("text_to_search (string)",vs("The text to search for the first occurrence of search_for.")),ls("starting_at (number, default=1)",vs("The character within text_to_search at which to start the search."))],compute:function(e,t,s={value:1}){const o=Ro(e).toLowerCase(),i=Ro(t).toLowerCase(),n=So(s,this.locale);if(""===i)return{value:Ss.GenericError,message:vs("The text_to_search must be non-empty.")};if(n<1)return{value:Ss.GenericError,message:vs("The starting_at (%s) must be greater than or equal to 1.",n)};const r=i.indexOf(o,n-1);return-1===r?{value:Ss.GenericError,message:vs("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o,i)}:{value:r+1}},isExported:!0},Km=!0,Jm=!0,Qm={description:vs("Split text by specific character delimiter(s)."),args:[ls("text (string)",vs("The text to divide.")),ls("delimiter (string)",vs("The character or characters to use to split text.")),ls("split_by_each (boolean, default=true})",vs("Whether or not to divide text around each character contained in delimiter.")),ls("remove_empty_text (boolean, default=true)",vs("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:Km},o={value:Jm}){const i=Ro(e),n=re(Ro(t)),r=Ao(s),a=Ao(o);if(n.length<=0)return new ys(vs("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)),Ho([c])},isExported:!1},ef={description:vs("Replaces existing text with new text in a string."),args:[ls("text_to_search (string)",vs("The text within which to search and replace.")),ls("search_for (string)",vs("The string to search for within text_to_search.")),ls("replace_with (string)",vs("The string that will replace search_for.")),ls("occurrence_number (number, optional)",vs("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=So(o,this.locale);if(i<0)return new ys(vs("The occurrenceNumber (%s) must be positive or null.",i));const n=Ro(e),r=Ro(t);if(""===r)return n;const a=Ro(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},tf={description:vs("Combines text from multiple strings and/or arrays."),args:[ls("delimiter (string)",vs("A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")),ls("ignore_empty (boolean)",vs("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result."),[{value:!0,label:vs("Ignore empty cells")},{value:!1,label:vs("Include empty cells (default)")}]),ls("texts (string, range<string>, repeating)",vs("Text item to join."))],compute:function(e,t={value:true},...s){const o=Ro(e),i=Ao(t);let n=0;return No(s,(e,t)=>i&&""===Ro(t)?e:(n++?e+o:"")+Ro(t),"")},isExported:!0},sf=!1,of={description:vs("Splits text into rows or columns using specified column and row delimiters."),args:[ls("text (string)",vs("The text to split.")),ls("col_delimiter (string, range<string>)",vs("Character or string to split columns by.")),ls("row_delimiter (string, range<string>, optional)",vs("Character or string to split rows by.")),ls("ignore_empty (boolean, default=false)",vs("Whether to ignore empty cells."),[{value:!1,label:vs("Include empty cells (default)")},{value:!0,label:vs("Ignore empty cells")}]),ls("match_mode (number, default=0)",vs("Searches the text for a delimiter match. By default, a case-sensitive match is done."),Mm),ls(`pad_with (string, default="${Ss.NotAvailable}")`,vs("The value to use for padding empty cells."))],compute:function(e,t,s,o={value:sf},i={value:0},n=new Rs){const r=Ro(e);if(r.length<=0)return new ys(vs("No text to split."));if(void 0===t&&void 0===s)return new ys(vs("At least one delimiter must be provided."));const a=Ko(t).flat().map(e=>re(Ro(e))),l=Ko(s).flat().map(e=>re(Ro(e)));if(a.some(e=>""===e)||l.some(e=>""===e))return new ys(vs("The delimiters cannot be empty values."));const c=Ao(o),h=So(i,this.locale);if(![0,1].includes(h))return new ys(vs("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 Ho(d)},isExported:!0},nf={description:vs("Removes space characters."),args:[ls("text (string)",vs("The text or reference to a cell containing text to be trimmed."))],compute:function(e){return Ro(e).split("\n").map(e=>e.replace(/\s+/g," ").trim()).join("\n")},isExported:!0},rf={description:vs("Converts a specified string to uppercase."),args:[ls("text (string)",vs("The string to convert to uppercase."))],compute:function(e){return Ro(e).toUpperCase()},isExported:!0},af={description:vs("Converts a number to text according to a specified format."),args:[ls("number (number)",vs("The number, date or time to format.")),ls("format (string)",vs('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 mn(So(e,this.locale),{format:Ro(t),locale:this.locale})},isExported:!0},lf={description:vs("Converts a string to a numeric value."),args:[ls("value (number)",vs("the string to be converted"))],compute:function(e){return So(e,this.locale)},isExported:!0},cf={description:vs("Returns text that occurs after a given substring or delimiter."),args:[ls("text (string)",vs("The source text.")),ls("delimiter (string)",vs("The substring after which text will be returned.")),ls("instance_num (number, default=1)",vs("The desired instance of the delimiter after which we extract the text. A negative number searches from the end.")),ls("match_mode (number, default=0)",vs("Searches the text for a delimiter match. By default, a case-sensitive match is done."),Mm),ls("match_end (number, default=0))",vs("Whether to treat the end of text as a delimiter."),Nm),ls(`if_not_found (string, default="${Ss.NotAvailable}")`,vs("Value to return if the delimiter is not found."))],compute:function(e,t,s={value:1},o={value:0},i={value:0},n=new Rs){const r=Ro(e),a=So(s,this.locale),l=So(o,this.locale),c=So(i,this.locale);if(0===a)return new ys(vs("The instance_num (%s) must not be zero.",a));if(0!==l&&1!==l)return new ys(vs("match_mode should have a value of 0 or 1."));if(0!==c&&1!==c)return new ys(vs("match_end should have a value of 0 or 1."));const h=Ro(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},hf={description:vs("Returns text that occurs before a given substring or delimiter."),args:[ls("text (string)",vs("The source text.")),ls("delimiter (string)",vs("The substring after which text will be returned.")),ls("instance_num (number, default=1)",vs("The desired instance of the delimiter before which we extract the text. A negative number searches from the end.")),ls("match_mode (number, default=0)",vs("Searches the text for a delimiter match. By default, a case-sensitive match is done."),Mm),ls("match_end (number, default=0))",vs("Whether to match a delimiter against the end of the text."),Nm),ls(`if_not_found (string, default="${Ss.NotAvailable}")`,vs("Value to return if the delimiter is not found."))],compute:function(e,t,s={value:1},o={value:0},i={value:0},n=new Rs){const r=Ro(e),a=So(s,this.locale),l=So(o,this.locale),c=So(i,this.locale);if(0===a)return new ys(vs("The instance_num (%s) must not be zero.",a));if(0!==l&&1!==l)return new ys(vs("match_mode should have a value of 0 or 1."));if(0!==c&&1!==c)return new ys(vs("match_end should have a value of 0 or 1."));const h=Ro(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 df=Object.freeze({__proto__:null,CHAR:Lm,CLEAN:km,CONCATENATE:Vm,EXACT:Um,FIND:Hm,JOIN:zm,LEFT:Bm,LEN:Gm,LOWER:Wm,MID:$m,PROPER:qm,REGEXEXTRACT:Zm,REPLACE:jm,RIGHT:Ym,SEARCH:Xm,SPLIT:Qm,SUBSTITUTE:ef,TEXT:af,TEXTAFTER:cf,TEXTBEFORE:hf,TEXTJOIN:tf,TEXTSPLIT:of,TRIM:nf,UPPER:rf,VALUE:lf});const uf={description:vs("Creates a hyperlink in a cell."),args:[ls("url (string)",vs("The full URL of the link enclosed in quotation marks.")),ls("link_label (string, optional)",vs("The text to display in the cell, enclosed in quotation marks."))],compute:function(e,t){const s=Ro(e).trim(),o=Ro(t)||s;return""===s?o:ye(o,s)},isExported:!0};var gf=Object.freeze({__proto__:null,HYPERLINK:uf});const pf=/^[A-Z0-9\_\.]+$/;const mf=new class extends ns{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(),!pf.test(e))throw new Error(vs("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.default||o++,e.repeating&&i++,!e.optional&&!e.default||e.repeating||n++;const r=t;return r.minArgRequired=o,r.maxArgPossible=i?1/0:s,r.nbrArgRepeating=i,r.nbrOptionalNonRepeatingArgs=n,r.hidden=t.hidden||!1,r.name=e,r}(e,t);return function(e){if(e.nbrArgRepeating&&e.nbrOptionalNonRepeatingArgs>=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=>ds.includes(e))&&o.type.some(e=>!ds.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]=si(s),super.replace(e,s),this}},ff=[{name:vs("Array"),functions:Wi},{name:vs("Database"),functions:_c},{name:vs("Date"),functions:Dd},{name:vs("Filter"),functions:Hd},{name:vs("Financial"),functions:Yu},{name:vs("Info"),functions:ag},{name:vs("Lookup"),functions:Zp},{name:vs("Logical"),functions:yg},{name:vs("Math"),functions:Ba},{name:vs("Misc"),functions:Wn},{name:vs("Operator"),functions:gm},{name:vs("Statistical"),functions:mc},{name:vs("Text"),functions:df},{name:vs("Engineering"),functions:Fd},{name:vs("Web"),functions:gf},{name:vs("Parser"),functions:Fm}];for(const e of ff){const t=e.functions;for(let s in t){const o=t[s];o.category=o.category||e.name,s=s.replace(/_/g,"."),mf.add(s,{isExported:!1,...o})}}var vf;!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"}(vf||(vf={}));const bf=(e,t=()=>!0)=>[{goTo:e,guard:t}],Sf=(e,t=()=>!0)=>({goTo:e,guard:t}),Cf={[vf.LeftRef]:{REFERENCE:bf(vf.Separator),NUMBER:bf(vf.FullRowSeparator),SYMBOL:[Sf(vf.FullColumnSeparator,e=>{return t=e.value,Yn.test(t);var t}),Sf(vf.FullRowSeparator,e=>Jn(e.value))]},[vf.FullColumnSeparator]:{SPACE:bf(vf.FullColumnSeparator),OPERATOR:bf(vf.RightColumnRef,e=>":"===e.value)},[vf.FullRowSeparator]:{SPACE:bf(vf.FullRowSeparator),OPERATOR:bf(vf.RightRowRef,e=>":"===e.value)},[vf.Separator]:{SPACE:bf(vf.Separator),OPERATOR:bf(vf.RightRef,e=>":"===e.value)},[vf.RightRef]:{SPACE:bf(vf.RightRef),NUMBER:bf(vf.Found),REFERENCE:bf(vf.Found,e=>tr(e.value)),SYMBOL:bf(vf.Found,e=>Qn(e.value)||er(e.value))},[vf.RightColumnRef]:{SPACE:bf(vf.RightColumnRef),SYMBOL:bf(vf.Found,e=>Qn(e.value)),REFERENCE:bf(vf.Found,e=>tr(e.value))},[vf.RightRowRef]:{SPACE:bf(vf.RightRowRef),NUMBER:bf(vf.Found),REFERENCE:bf(vf.Found,e=>tr(e.value)),SYMBOL:bf(vf.Found,e=>er(e.value))},[vf.Found]:{}};function yf(e){let t=0,s=Cf[vf.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 vf.Found:return o+=i.value,e.splice(0,t),{type:"REFERENCE",value:o};default:s=Cf[r],o+=i.value}}return null}function If(e,t=Fc){const s=Nc(e,t),o=[];for(;s.length;)o.push(yf(s)||s.shift());return o}const wf=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,Ef=["-","+"],Rf=["%"];class xf{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 Tf={"%":40,"^":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function Af(e){const t=e.shift();if(!t)throw new Is;switch(t.type){case"DEBUGGER":const s=Of(e,1e3);return s.debug=!0,s;case"NUMBER":return{type:"NUMBER",value:uo(t.value,Fc),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:Ss.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&&wf.test(t.value)&&o===ce(o,"'")){const{args:s,rightParen:i}=function(e){_f(e,"LEFT_PAREN",vs("Missing opening parenthesis"));const t=e.current;if("RIGHT_PAREN"===t?.type){return{args:[],rightParen:_f(e,"RIGHT_PAREN")}}const s=[];s.push(Df(e));for(;"RIGHT_PAREN"!==e.current?.type;)_f(e,"ARG_SEPARATOR",vs("Wrong function call")),s.push(Df(e));const o=_f(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=Of(e),a=_f(e,"RIGHT_PAREN",vs("Missing closing parenthesis"));return{...r,tokenStartIndex:t.tokenIndex,tokenEndIndex:a.tokenIndex};case"OPERATOR":const l=t.value;if(Ef.includes(l)){const s=Of(e,Tf[l]);return{type:"UNARY_OPERATION",value:l,operand:s,tokenStartIndex:t.tokenIndex,tokenEndIndex:s.tokenEndIndex}}throw new Is(vs("Unexpected token: %s",t.value));default:throw new Is(vs("Unexpected token: %s",t.value))}}function Df(e){const t=e.current;return"ARG_SEPARATOR"===t?.type||"RIGHT_PAREN"===t?.type?{type:"EMPTY",value:"",tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:Of(e)}function _f(e,t,s){const o=e.shift();if(!o||o.type!==t)throw new Is(s);return o}function Of(e,t=0){if(0===e.length)throw new Is;let s=Af(e);for(;"OPERATOR"===e.current?.type&&Tf[e.current.value]>t;){const t=e.shift(),o=t.value;if(Rf.includes(o))s={type:"UNARY_OPERATION",value:o,operand:s,postfix:!0,tokenStartIndex:s.tokenStartIndex,tokenEndIndex:t.tokenIndex};else{const t=Of(e,Tf[o]);s={type:"BIN_OPERATION",value:o,left:s,right:t,tokenStartIndex:s.tokenStartIndex,tokenEndIndex:t.tokenEndIndex}}}return s}function Ff(e){return Pf(If(e))}function Pf(e){const t=e.map((e,t)=>({type:e.type,value:e.value,tokenIndex:t})).filter(e=>"SPACE"!==e.type),s=new xf(t);"="===s.current?.value&&s.shift();const o=Of(s);if(s.current)throw new Is;return o}function Mf(e,t,s){return kf(e,e=>e.type===t?s(e):e)}function Nf(e){return Array.from(Lf(e))}function*Lf(e){switch(yield e,e.type){case"FUNCALL":for(const t of e.args)yield*Lf(t);break;case"UNARY_OPERATION":yield*Lf(e.operand);break;case"BIN_OPERATION":yield*Lf(e.left),yield*Lf(e.right)}}function kf(e,t){switch((e=t(e)).type){case"FUNCALL":return{...e,args:e.args.map(e=>kf(e,t))};case"UNARY_OPERATION":return{...e,operand:kf(e.operand,t)};case"BIN_OPERATION":return{...e,right:kf(e.right,t),left:kf(e.left,t)};default:return e}}const Vf=mf.content;function Uf(e){try{return 0===Nf(Pf(e)).filter(e=>"FUNCALL"===e.type&&!Vf[e.value.toUpperCase()]?.isExported).length}catch(e){return!1}}function Hf(e,t){if(!e.some(e=>"SYMBOL"===e.type&&t.includes(e.value.toUpperCase())))return[];let s;try{s=Pf(e)}catch{return[]}return function(e,t){return Nf(e).filter(e=>"FUNCALL"===e.type&&t.includes(e.value.toUpperCase())).map(e=>({functionName:e.value.toUpperCase(),args:e.args}))}(s,t)}function zf(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const Bf=new Fg;function Gf(e,t){return{url:e=zf(e),label:t||e,isExternal:!0,isUrlEditable:!0}}Bf.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)||vs("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:vs("Cannot open the link because the linked sheet is hidden.")})},sequence:0});const Wf={createLink:Gf,match:e=>Ce(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function $f(e){return Bf.getAll().sort((e,t)=>e.sequence-t.sequence).find(t=>t.match(e))||Wf}function qf(e,t){return $f(e.url).urlRepresentation(e.url,t)}function Zf(e,t,s){$f(e.url).open(e.url,t,s)}function jf(e){if("string"==typeof e){if(Se(e)){const{label:t,url:s}=Ie(e);return $f(s).createLink(s,t)}return Ce(e)?Gf(e):void 0}}function Yf(e){return e.map(Kf).sort((e,t)=>e.sequence-t.sequence)}let Xf=1;function Kf(e){const t=e.name,s=e.children,o=e.description,i=e.icon,n=e.secondaryIcon,r=e.id||Xf++,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(Kf):()=>[],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 Jf{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 Qf extends Jf{dependencies=new Map;factory=new ev(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 ev{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 tv{get;disposeCallbacks=[];constructor(e){this.get=e}onDispose(e){this.disposeCallbacks.push(e)}dispose(){this.disposeCallbacks.forEach(e=>e())}}function sv(){const e=t.useEnv();if(e.__spreadsheet_stores__ instanceof Qf)return e.__spreadsheet_stores__;const s=new Qf;return t.useSubEnv({__spreadsheet_stores__:s,getStore:e=>rv(s.get(e),()=>s.trigger("store-updated"))}),t.onWillUnmount(()=>s.dispose()),s}function ov(e){const s=av(t.useEnv()),o=s.get(e);return nv(s,o)}function iv(e,...s){const o=av(t.useEnv()),i=o.instantiate(e,...s);return t.onWillUnmount(()=>i.dispose()),nv(o,i)}function nv(e,s){const o=t.useComponent();return rv(s,()=>{"mounted"===t.status(o)&&e.trigger("store-updated")})}function rv(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 av(e){const t=e.__spreadsheet_stores__;if(!(t instanceof Qf))throw new Error("No store provider found. Did you forget to call useStoreProvider()?");return t}const lv=(cv="Model",class{constructor(e){throw new Error(`This is a abstract store for ${cv}, it cannot be instantiated.\nDid you forget to inject your store instance?\n\nconst stores = useStoreProvider();\nstores.inject(MyMetaStore, storeInstance);\n`)}});var cv;const hv={Background:0,Highlights:1,Clipboard:2,Chart:4,Autofill:5,Selection:6,Headers:100},dv=$e(()=>Object.keys(hv).sort((e,t)=>hv[e]-hv[t]));class uv{mutators=["register","unRegister","draw","startAnimation","stopAnimation"];renderers={};model;context=void 0;animationFrameId=null;registeredAnimations=new Set;constructor(e){this.model=e(lv)}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 dv())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 gv extends tv{model=this.get(lv);getters=this.model.getters;renderer=this.get(uv);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 pv={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 mv extends gv{mutators=["focusComposer","focusActiveComposer"];activeComposer=pv;_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 fv=/rgba?\(|\s+|\)/gi,vv=/^#([A-F\d]{2}){3,4}$/,bv=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function Sv(e,t=1){const s=1!==t?Math.round(255*t).toString(16).padStart(2,"0"):"";return yv(e.toString(16).padStart(6,"0"))+s}function Cv(e){return"number"==typeof e?e:Number.parseInt(yv(e).slice(1,7),16)}function yv(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(fv,"").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}`),!vv.test(t))throw new Error(`invalid color input: ${e}`);return t}function Iv(e){try{return yv(e),!0}catch(e){return!1}}const wv=e=>e>=0&&e<=255;function Ev(e,t,s,o=1){if(!wv(e)||!wv(t)||!wv(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 Rv(e){let{r:t,g:s,b:o}=Tv(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 xv(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 Tv(e){let t,s,o,i;if(7===(e=yv(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 Av(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 Dv(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 _v(e){return xv(Av(e))}function Ov(e){return Dv(Tv(e))}function Fv(e){return Tv("number"==typeof e?Sv(e):e)}function Pv(e,t){return 1===t?yv(e).slice(0,7):xv({...Tv(e),a:t})}function Mv(e,t){const s=Ov(e);return 1===t?"#fff":(s.l=t*(100-s.l)+s.l,_v(s))}function Nv(e,t){const s=Ov(e);return 1===t?"#000":(s.s=Math.min(100,t*s.s+s.s),s.l=s.l-t*s.l,_v(s))}function Lv(e){return Rv(e)<.6?Mv(e,.9):Nv(e,.75)}const kv=["#4EA7F2","#EA6175","#43C5B1","#F4A261","#8481DD","#FFD86D"],Vv=["#4EA7F2","#3188E6","#43C5B1","#00A78D","#EA6175","#CE4257","#F4A261","#F48935","#8481DD","#5752D1","#FFD86D","#FFBC2C"],Uv=["#4EA7F2","#3188E6","#056BD9","#A76DBC","#7F4295","#6D2387","#EA6175","#CE4257","#982738","#43C5B1","#00A78D","#0E8270","#F4A261","#F48935","#BE5D10","#8481DD","#5752D1","#3A3580","#A4A8B6","#7E8290","#545B70","#FFD86D","#FFBC2C","#C08A16"],Hv=["#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"],zv=["#4EA7F2","#43C5B1","#EA6175","#F4A261","#8481DD","#FFD86D","#3188E6","#00A78D","#CE4257","#F48935","#5752D1","#FFBC2C"],Bv=["#4EA7F2","#A76DBC","#EA6175","#43C5B1","#F4A261","#8481DD","#A4A8B6","#FFD86D","#3188E6","#7F4295","#CE4257","#00A78D","#F48935","#5752D1","#7E8290","#FFBC2C","#056BD9","#6D2387","#982738","#0E8270","#BE5D10","#3A3580","#545B70","#C08A16"],Gv=["#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 Wv(e,t){return t[e%t.length]}function $v(e){return e<=6?kv:e<=12?Vv:e<=24?Uv:Hv}class qv{preferredColors;currentColorIndex=0;palette;constructor(e,t=[]){this.preferredColors=t,this.palette=$v(e).filter(e=>!t.includes(e))}next(){return this.preferredColors?.[this.currentColorIndex]?this.preferredColors[this.currentColorIndex++]:Wv(this.currentColorIndex++,this.palette)}}class Zv extends qv{constructor(e,t=[]){var s;super(e,t),this.palette=(s=e,s<=6?kv:s<=12?zv:s<=24?Bv:Gv).filter(e=>!t.includes(e))}}class jv{availableColors;colors={};constructor(e=12){this.availableColors=new Zv(e)}get(e){return this.colors[e]||(this.colors[e]=this.availableColors.next()),this.colors[e]}}function Yv(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=Fv(t[e-1].color).a,i=Fv(t[e].color).a,n=Cv(t[e-1].color),r=Cv(t[e].color);s.push({min:t[e-1].value,max:t[e].value,minColor:n,maxColor:r,minColorAlpha:o,maxColorAlpha:i,colorDiff:Xv(t[e-1].value,t[e].value,n,r)})}return e=>{if(e<s[0].min)return Sv(s[0].minColor,s[0].minColorAlpha);for(const t of s)if(e>=t.min&&e<=t.max)return Sv(Kv(e,t.min,t.minColor,t.colorDiff),t.maxColorAlpha);return Sv(s[s.length-1].maxColor,s[s.length-1].maxColorAlpha)}}function Xv(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 Kv(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 Jv(e,t,s){return eb({value:Bn(t.format)&&null!==e.parsedValue?e.content:e.parsedValue,format:t.format,origin:s},t.locale)}function Qv(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(co(e,Fc))return uo(e,Fc);const s=js(e,t);return s?s.value:fe(e)?"TRUE"===e.toUpperCase():e}function eb(e,t=Fc,s,o){const i=jf(e.value);if(!i){return ib(tb(e,t,s),e.origin??o)}const n=Qv(i.label,t);return ib({...tb({value:n,format:e.format||("number"==typeof n?An(i.label,t)||Dn(i.label):void 0)},t,s),link:i},e.origin??o)}function tb(e,t,s){let{value:o,format:i,message:n}=e;i=s?.format||i;const r=mn(o,{format:i,locale:t});return fo(o)?function(e,t){return{value:e,formattedValue:e,message:t,type:Od.error,isAutoSummable:!1,defaultAlign:"center"}}(o,n):null===o?ob(i):Bn(i)?sb(Ro(o),i,r):"number"==typeof o?En(i||"")?function(e,t,s){return{value:e,format:t,formattedValue:s,type:Od.number,isAutoSummable:!1,defaultAlign:"right"}}(o,i,r):function(e,t,s){return{value:e||0,format:t,formattedValue:s,type:Od.number,isAutoSummable:!0,defaultAlign:"right"}}(o,i,r):"boolean"==typeof o?function(e,t,s){return{value:e,format:t,formattedValue:s,type:Od.boolean,isAutoSummable:!1,defaultAlign:"center"}}(o,i,r):sb(o,i,r)}function sb(e,t,s){return{value:e,format:t,formattedValue:s,type:Od.text,isAutoSummable:!0,defaultAlign:"left"}}const ob=$e(function(e){return{value:null,format:e,formattedValue:"",type:Od.empty,isAutoSummable:!0,defaultAlign:"left"}});function ib(e,t){return null===e.value||"origin"in e||(e.origin=t),e}function nb(e){const t=Fs.now();switch(e){case"today":return Ks(t);case"yesterday":return Ks(Fs.fromTimestamp(t.setDate(t.getDate()-1)));case"tomorrow":return Ks(Fs.fromTimestamp(t.setDate(t.getDate()+1)));case"lastWeek":return Ks(Fs.fromTimestamp(t.setDate(t.getDate()-7)));case"lastMonth":return Ks(Fs.fromTimestamp(t.setMonth(t.getMonth()-1)));case"lastYear":return Ks(Fs.fromTimestamp(t.setFullYear(t.getFullYear()-1)))}}function rb(e,t){return"dateValue"in e&&"exactDate"!==e.dateValue?[nb(e.dateValue)]:e.values.map(e=>$s(e,t))}function ab(e,t){return e.map(e=>{if(e.startsWith("="))return e;const s=Qv(e,t);return"number"==typeof s?mn(s,{format:t.dateFormat,locale:t}):""})}const lb=new WeakMap,cb=new WeakMap;function hb(e,t){lb.has(t)||(lb.set(t,new Map),cb.set(t,0));const s=lb.get(t),o=gb(e);if(s.has(o)){const i=s.get(o);return t[i]=e,i}const i=cb.get(t)+1;return s.set(o,i),cb.set(t,i),t[i]=e,i}function db(e){const t={};for(const s in e){const o=ft(e[s].map(jt));for(const e of o)t[Dt(e)]=Number(s)}return t}function*ub(e,t){for(const s in t){const o=Rt(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 gb(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+=gb(e[o]);return s+"]"}const t=Object.keys(e).sort();let s="{";for(const o of t)void 0!==e[o]&&(s+=`"${o}":${gb(e[o])},`);return s+="}",s}function pb(e){return 20+120*Math.exp(-.035*(e-1))}function mb(e){const t=[];for(let s=0;s<e;s++){const e={cells:{}};t.push(e)}return t}function fb(e,t,s){return s.map(s=>s>=e?s+t:s)}function vb(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 bb(e,t="Sheet"){let s=1,o=`${t}${s}`;for(;e.includes(o);)o=`${t}${s}`,s++;return o}function Sb(e,t){let s=1;const o=vs("Copy of %s",e);let i=o.toString();for(;t.includes(i);)i=`${o} (${s})`,s++;return i}function Cb(e,t){return void 0!==e&&void 0!==t&&le(e.trim().toUpperCase())===le(t.trim().toUpperCase())}function yb(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&&Jt(o)>1?i=[e.parts[0],e.parts[0]]:2===e.parts.length&&1===Jt(o)&&(i=[e.parts[0]]),{unboundedZone:s,zone:o,parts:i,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function Ib(e,t){const s=e.xc,{xc:o,sheetName:i}=sr(s),n=Et(o),r=function(e,t){const s=e.split(":").map(e=>{const t=Jn(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 yb({zone:n,parts:r,sheetId:e.sheetId,prefixSheet:Boolean(i),invalidSheetName:e.invalidSheetName},t)}function wb(e){const t={left:-1,top:-1,right:-1,bottom:-1};return{sheetId:"",zone:t,unboundedZone:t,parts:[],invalidXc:e,prefixSheet:!1}}function Eb(e){return Kt(e.unboundedZone)}function Rb(e){return Xt(e.unboundedZone)}function xb(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 Ss.InvalidReference;if(e.zone.left<0||e.zone.top<0)return Ss.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 Ss.InvalidReference;let r=Ub(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+=Ub(e,1,o)),`${i?n+"!":""}${r}`}function Tb(e,t,s){const o=s.sheetId===e?t:s.sheetId;return{...s,sheetId:o}}function Ab(e,t,s){if(!s)return;const o=e.getRangeFromSheetXC(t,s);return o.invalidSheetName||o.invalidXc?void 0:o}function Db(e){const t=[];for(const s of e)for(const e of Gt(s.zone))t.push({...e,sheetId:s.sheetId});return t}function _b(e){const t={left:e.col,top:e.row,right:e.col,bottom:e.row};return{sheetId:e.sheetId,zone:t}}function Ob(e){return Fb.get(e.type)?.(e)}const Fb=new class extends Fg{add(e,t){return super.add(e,t),this}get(e){return this.content[e]}};function Pb(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(!Cb(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=Vb(r,o,a,-e)}else if(i.zone[t]>=n&&i.zone[s]<=l)a="REMOVE",r=wb(Ss.InvalidReference);else if(i.zone[t]<=l&&i.zone[s]>=l){const e=l-i.zone[t]+1;a="RESIZE",r=Vb(r,o,a,-e),r=Vb(r,o,"MOVE",-(i.zone[t]-n))}else n<i.zone[t]&&(a="MOVE",r=Vb(r,o,a,-(l-n+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}}function Mb(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:Vb(i,o,"RESIZE",e.quantity)};if(e.base<i.zone[t])return{changeType:"MOVE",range:Vb(i,o,"MOVE",e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[s])return{changeType:"RESIZE",range:Vb(i,o,"RESIZE",e.quantity)};if(e.base<=i.zone[t])return{changeType:"MOVE",range:Vb(i,o,"MOVE",e.quantity)}}return{changeType:"NONE"}}}function Nb(e){return t=>{if(t.sheetId!==e.sheetId&&t.invalidSheetName!==e.sheetName)return{changeType:"NONE"};const s=e.sheetName;return{changeType:"REMOVE",range:t={...wb(Ss.InvalidReference),invalidSheetName:s}}}}function Lb(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 kb(e){const t=e.target[0];return s=>{if(s.sheetId!==e.sheetId||!Ht(s.zone,t))return{changeType:"NONE"};const o=e.targetSheetId,i=Vb(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 Vb(e,t,s,o){return{...e,unboundedZone:qt(e.unboundedZone,t,s,o),zone:qt(e.zone,t,s,o)}}function Ub(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=Kt(e.unboundedZone)&&!s.useBoundedReference?0===t&&e.unboundedZone.hasHeader?o+i+n+r:o+i:Xt(e.unboundedZone)&&!s.useBoundedReference?0===t&&e.unboundedZone.hasHeader?o+i+n+r:n+r:o+i+n+r,a}function Hb(e,t=1){return t*(e+4)-4}function zb(e=100,t=100){return new OffscreenCanvas(e,t).getContext("2d")}function Bb(e,t,s,o){const i=Qb(e,t,s,"wrap"===s?.wrapping?o-8:void 0).length;return Hb(Kb(s),i)+6}function Gb(e,t=!1,s=!1){return`${s?"italic":""} ${t?"bold":""} ${e}px ${k}`}Fb.add("REMOVE_COLUMNS_ROWS",e=>({applyChange:Pb(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("ADD_COLUMNS_ROWS",e=>({applyChange:Mb(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("DELETE_SHEET",e=>({applyChange:Nb(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("RENAME_SHEET",e=>({applyChange:Lb(e),sheetId:e.sheetId,sheetName:{old:e.oldName,current:e.newName}})).add("MOVE_RANGES",e=>({applyChange:kb(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}}));const Wb={};function $b(e,t,s,o="pt"){return qb(e,t,Xb(s,o))}function qb(e,t,s){if(Wb[s]||(Wb[s]={}),void 0===Wb[s][t]){const o=e.font;e.font=s,Wb[s][t]=e.measureText(t).width,e.font=o}return Wb[s][t]}const Zb={};function jb(e,t,s,o="pt"){const i=Xb(s,o);e.save(),e.font=i;const n=function(e,t){const s=e.font;Zb[s]||(Zb[s]={});if(void 0===Zb[s][t]){const o=e.measureText(t),i=o.width,n=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent;Zb[s][t]={width:i,height:n}}return Zb[s][t]}(e,t);return e.restore(),n}function Yb(e){return Math.round(96*e/72)}function Xb(e,t="pt"){return`${e.italic?"italic ":""}${e.bold?"bold":"400"} ${("pt"===t?Kb(e):e.fontSize)??L}px ${k}`}function Kb(e){return Yb(e?.fontSize||L)}function Jb(e,t,s,o){if($b(e,t,o)<=s)return[t];const i=[];let n="";for(const r of t){$b(e,n+r,o)>s?(i.push(n),n=r):n+=r}return i.push(n),i}function Qb(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=$b(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=$b(e,t,s);n<=a?(r+=t,a-=n):(i.push(r),r=l,a=o-c)}}""!==r&&i.push(r)}return i}function eS(e){return e?e.toLowerCase():""}const tS=/([0-9\.]*)px/;function sS(e,t,s){let o=qb(e,t,e.font);if(o<=s)return t;const i=qb(e,"…",e.font);if(o<=i)return t;let n=t.length;for(;o>=s-i&&n-- >0;)o=qb(e,t=t.substring(0,n),e.font);return t+"…"}function oS(e,t,s,o=!1,i=!1,n=function(e){return Number(e.match(tS)?.[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 iS(e,t,s,o,i="pt"){if($b(e,s,o,i)<=t)return s;const n=$b(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=$b(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 nS(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 rS=new Fg;function aS(){if(window.Chart&&!window.Chart.registry.plugins.get("chartShowValuesPlugin"))for(const e of rS.getAll())e.register(window.Chart)}class lS extends gv{mutators=["disableAnimationForChart","enableAnimationForChart"];animationPlayed={};disableAnimationForChart(e,t){return this.animationPlayed[e]=t,"noStateChange"}enableAnimationForChart(e){return this.animationPlayed[e]=void 0,"noStateChange"}}function cS(){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 hS(){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=dS(this),l=(a-(i?dS(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=dS(this),l=n?dS(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 dS(e){const{x:t,base:s}=e.getProps(["x","base"]),o=Math.min(t,s);return Math.max(t,s)-o}const uS=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}},gS="000000",pS={arrows:"3Arrows",smiley:"3Symbols",dots:"3TrafficLights1"},mS="http://schemas.openxmlformats.org/spreadsheetml/2006/main",fS="http://schemas.openxmlformats.org/spreadsheetml/2006/main",vS="http://schemas.openxmlformats.org/package/2006/relationships",bS="http://schemas.openxmlformats.org/package/2006/content-types",SS="http://schemas.openxmlformats.org/spreadsheetml/2006/main",CS="http://schemas.openxmlformats.org/spreadsheetml/2006/main",yS="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing",IS="http://schemas.openxmlformats.org/spreadsheetml/2006/main",wS="http://schemas.microsoft.com/office/spreadsheetml/2014/revision",ES="http://schemas.microsoft.com/office/spreadsheetml/2016/revision3",RS="http://schemas.openxmlformats.org/markup-compatibility/2006",xS="http://schemas.openxmlformats.org/drawingml/2006/main",TS="http://schemas.openxmlformats.org/drawingml/2006/chart",AS={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"},DS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",_S="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",OS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata",FS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",PS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",MS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing",NS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart",LS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/table",kS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",VS="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",US="bdbb8cdc-fa1e-496e-a857-3c3f30c029c3",HS="http://schemas.openxmlformats.org/officeDocument/2006/relationships",zS=.75,BS=.143,GS=8.43,WS=12.75,$S={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}]},qS=["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"],ZS="[Content_Types].xml";function jS(e,t,s){if(!t.startsWith("="))return t;const o=If(t);for(let t=1;t<o.length;t++){if("REFERENCE"!==o[t].type)continue;const i=o[t].value,n=YS(e,i,s);i!==n&&(o[t]={value:n,type:"REFERENCE"})}return _e(o.map(e=>e.value))}function YS(e,t,s){const o=sr(t).sheetName;if(o?!Cb(o,s.sheetName.old):e!==s.sheetId)return t;const i=function(e,t){if(!Kn.test(e))return wb(e);return Ib({xc:e,sheetId:t},XS)}(t,o?s.sheetId:e);if(i.invalidXc)return t;const n=s.applyChange(i);return"NONE"===n.changeType||"REMOVE"===n.changeType?t:xb(n.range,e,function(e){return t=>t===e.sheetId?e.sheetName.current:""}(s))}function XS(e){return{numberOfRows:Number.MAX_SAFE_INTEGER,numberOfCols:Number.MAX_SAFE_INTEGER}}const KS="x1",JS="xMovingAverage",QS={exponential:"exp",logarithmic:"log",polynomial:"poly",trailingMovingAverage:"movingAvg"};function eC(e,t,s,o){let i=!1;const n=[];for(const o in s){let r=s[o];if(r.labelCell){const e=oC(r.labelCell,t);r.labelCell!==e&&(i=!0,r={...r,labelCell:e})}const a=oC(r.dataRange,t);void 0===a||e.getRangeString(a,a.sheetId)===Ss.InvalidReference?(i=!0,r=void 0):a!==r.dataRange&&(i=!0,r={...r,dataRange:a}),n[o]=r}let r=o;const a=oC(r,t);a!==r&&(i=!0,r=a);return{isStale:i,dataSets:n.filter(Te),labelRange:r}}function tC(e,t,s){return s.map(s=>({dataRange:Tb(e,t,s.dataRange),labelCell:s.labelCell?Tb(e,t,s.labelCell):void 0}))}function sC(e,t,s){return s?Tb(e,t,s):void 0}function oC(e,t){if(!e)return;const s=t(e);switch(s.changeType){case"NONE":return e;case"REMOVE":return;default:return s.range}}function iC(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({...nC(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({...nC(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 nC(e,t,s,o){if(s.left!==s.right&&s.top!==s.bottom)throw new Error(`Zone should be a single column or row: ${Dt(s)}`);if(o){const i=Dt(s),n=Dt(o);return{labelCell:e.getRangeFromSheetXC(t,n),dataRange:e.getRangeFromSheetXC(t,i)}}return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,Dt(s))}}function rC(e,t){const s=t.labelCell?.zone;let o=t.dataRange.zone;if(s){const{numberOfRows:e,numberOfCols:t}=zt(o);1===e?o={...o,left:o.left+1}:1===t&&(o={...o,top:o.top+1})}const i=yb({...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":QS[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 aC(e,t,s){if(!t)return;const o={...t.zone};s&&t.zone.bottom>t.zone.top&&(o.top=o.top+1);const i=yb({...t,zone:o},e.getSheetSize);return e.getRangeString(i,"forceSheetReference",{useBoundedReference:!0})}function lC(e,t,s){let o;if(t.labelRange){const i=YS(e,t.labelRange,s);i!==Ss.InvalidReference&&(o=i)}const i=[];for(const o of t.dataSets){const t={...o},n=YS(e,o.dataRange,s);n!==Ss.InvalidReference&&(t.dataRange=n,i.push(t))}return{...t,dataSets:i,labelRange:o}}function cC(e){return e&&Rv(e)<.3?"#FFFFFF":"#000000"}function hC(e){return e&&Rv(e)<.3?"#C8C8C8":"#666666"}function dC(e){if(e.dataSets){const t=void 0!==e.dataSets.find(e=>!Kn.test(e.dataRange));if(t)return"InvalidDataSet";if(e.dataSets.map(e=>Et(e.dataRange)).some(e=>e.top!==e.bottom&&Xt(e)))return"InvalidDataSet"}return"Success"}function uC(e){if(e.labelRange){if(!Kn.test(e.labelRange||""))return"InvalidLabelRange"}return"Success"}function gC(e,t,s){if(!s)return!1;if(!e)return!1;if(!t)return!0;const o=Jt(t.dataRange.zone);return!(Jt(e.zone)<o)}function pC(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 mC(e,t,s=!1){return(o,i)=>{const n=e?.[i];return fC({format:n,locale:t},s)(o)}}function fC(e,t=!1){return s=>{if(s=Number(s),isNaN(s))return s;const{locale:o,format:i}=e;return SC(t?Nn({value:s,format:i},o):mn(s,{locale:o,format:!i&&Math.abs(s)>=1e3?"#,##":i}))}}const vC=[{value:"left",label:vs("Left")},{value:"right",label:vs("Right")}];function bC(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 SC(e,t=20){return e?e.length>t?e.substring(0,t)+"…":e:""}function CC(e){return e===KS||e===JS}const yC={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=$b(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=cC(t.background),s.strokeStyle=t.background||"#ffffff",IC(p,u,g,s))}}(e,s,i);break;case"bar":case"line":case"radar":s.horizontal?wC(e,s,i):function(e,t,s){const o=e.chartArea.bottom,i=e.chartArea.top,n={};for(const r of e._metasets){if(CC(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";IC(t.callback(Number(h),r,l),u,g,s)}}}(e,s,i);break;case"funnel":wC(e,s,i)}i.restore()}};function IC(e,t,s,o){o.lineWidth=3,o.strokeText(e,t,s),o.lineWidth=1,o.fillText(e,t,s)}function wC(e,t,s){const o=e.chartArea.right,i=e.chartArea.left,n={};for(const r of e._metasets){if(CC(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=$b(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",IC(c,p,d,s)}}}const EC={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 RC(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xC(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]=xC(e[s]));else for(const s in e)t[s]=xC(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 TC(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 AC(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 DC(e){return void 0!==e}function _C(...e){if(e.length<=1)return!0;for(let t=1;t<e.length;t++)if(!OC(e[0],e[t]))return!1;return!0}function OC(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(!OC(e[s],t[s]))return!1}else if(e[s]!==t[s])return!1}return!0}function FC(e){if(!e)return e;const t={...e};return Object.keys(t).forEach(e=>!t[e]&&delete t[e]),t}function PC(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 MC(e){return e.split("\n").map(e=>e.replace(/\s+/g," ").trim()).join("\n")}class NC{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 LC="nullValue";function kC(e,t){const{dataSetsValues:s}=t,o=[],i=ty(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",barPercentage:.9,categoryPercentage:s.length>1?.8:1,borderRadius:2};o.push(u);const g=e.dataSets?.[r].trend,p=t.trendDataSetsValues?.[r];g?.display&&!e.horizontal&&p&&n.push(QC(u,g,p))}return o.push(...n),o}function VC(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(vs("Subtotal")),l.push([0,d]),a.push(r))}return{datasets:[c],labels:h}}function UC(e,t){const{dataSetsValues:s,axisType:o,labels:i}=t,n=[],r=!!e.fillArea,a=!!e.stacked,l=[],c=ty(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?Pv(p,.4):p,pointBackgroundColor:p,fill:!!r&&ey(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(QC(m,f,v))}return n.push(...l),n}function HC(e,t){const s=UC(e,t);for(const e of s)CC(e.xAxisID)||(e.showLine=!1);return s}function zC(e,t){const{dataSetsValues:s}=t,o=[],i=Math.max(0,...s.map(e=>e?.data?.length??0)),n=bC(new qv(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 BC(e,t){const{dataSetsValues:s}=t,o=[],i=ty(e,s.length),n=[],r=s.filter((t,s)=>"bar"===(e.dataSets?.[s].type??"line"));for(let a=0;a<s.length;a++){let{label:l,data:c,hidden:h}=s[a];l=e.dataSets?.[a].label||l;const d=e.dataSets?.[a],u=i.next(),g=d?.type??"line",p={label:l,data:c,hidden:h,borderColor:u,backgroundColor:u,yAxisID:e.dataSets?.[a].yAxisId||"y",xAxisID:"x",type:g,order:"bar"===g?s.length+a:a,pointRadius:e.hideDataMarkers?0:3};"bar"===p.type&&(p.barPercentage=.9,p.categoryPercentage=r.length>1?.8:1,p.borderRadius=2),o.push(p);const m=e.dataSets?.[a].trend,f=t.trendDataSetsValues?.[a];m?.display&&f&&n.push(QC(p,m,f))}return o.push(...n),o}function GC(e,t){const{dataSetsValues:s}=t,o=[],i=e.fillArea??!1,n=ty(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=Pv(c,.4),h.fill="start"),o.push(h)}return o}function WC(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 $C(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:qC(o,e.funnelColors),yAxisID:"y",xAxisID:"x",barPercentage:1,categoryPercentage:1,borderColor:e.background||c,borderWidth:3}]}function qC(e,t){const s=new qv(e.length,t);return e.map(()=>s.next())}function ZC(e,t){const{dataSetsValues:s,labels:o}=t,i=XC(jC(s,o)),n=i[0]||[],r=new qv(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!==LC?e.background||c:p},backgroundColor:e=>{const t="data"===e.type?e.raw:void 0;if(!t||t.label===LC)return p;const s=t.groups[0];return a.find(e=>e.label===s)?.color},hoverOffset:10};l.push(s)}return l}function jC(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]?LC:String(e[t].data[i]);s[i][t]=o}s[i].value=Number(t[i])}return s}(e,t);return YC(s,0,e.length,[])}function YC(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:YC(i[e]||[],t+1,s,[...o,e]),groups:r,depth:t}}).sort((e,t)=>t.value-e.value)}function XC(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 KC(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=jC(s,o).sort((e,t)=>t.value-e.value),l=function(e,t){const s="categoryColor"===e.coloringOptions?.type?e.coloringOptions.colors:[],o=new qv(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??EC.showLabels,u=e.showValues??EC.showValues,g=e.coloringOptions||EC.coloringOptions;let p;"colorScale"===g?.type&&(p=function(e,t){const s=XC(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}),Yv(e)}return}(a,g));const m=[{data:[],tree:c,labels:{display:d||u,overflow:"hidden",...JC(e.valuesDesign,EC.valuesDesign),formatter:e=>[d?e.raw.g:void 0,u?mn(e.raw.v,r):void 0].filter(DC)},captions:{display:e.showHeaders??EC.showHeaders,padding:6,...JC(e.headerDesign,EC.headerDesign)},key:"value",groups:TC(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||EC.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=XC(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 Mv(n,u)}(t,a,g,l);throw new Error("Unsupported coloring option type}")}}];return m}function JC(e,t){const s=e=>Rv(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 QC(e,t,s){const o=Tv(e.backgroundColor);o.a=1;const i=t.color||Mv(xv(o),.5);return{type:"line",xAxisID:"trailingMovingAverage"===t.type?JS:KS,yAxisID:e.yAxisID,label:e.label?vs("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 ey(e,t){return t?0===e?"origin":"-1":"origin"}function ty(e,t){return new qv(t,e.dataSets?.map(e=>e.backgroundColor)||[])}const sy={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];oy(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!==LC}),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===LC)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=Mv(a,.5):e.options.backgroundColor=a}}};function oy(e,t){return t.length>e.length&&e.every((e,s)=>e===t[s])}const iy={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===LC)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=Rv(h.options.backgroundColor)>.7?"#666666":"#FFFFFF";s.fillStyle=o.textColor||x,s.textAlign="center",s.textBaseline="middle",s.font=Gb(i,o.bold,o.italic);const T=-(c.length-1)*n/2;for(let e=0;e<c.length;e++){const t=iS(s,C,c[e],o,"px");s.fillText(t,R,T+e*n)}s.restore()}}(e,s,e.ctx)}};const ny={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=ay(o,e);if(!s)break;const n=ry(t),r=ry(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 ry(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 ay(e,t){return e.find((e,s)=>s>t&&0!==e.height)}rS.add("chartShowValuesPlugin",{register:e=>e.register(yC),unregister:e=>e.unregister(yC)}),rS.add("waterfallLinesPlugin",{register:e=>e.register(ny),unregister:e=>e.unregister(ny)}),rS.add("funnelController",{register:e=>e.register(cS()),unregister:e=>e.unregister(cS())}),rS.add("funnelElement",{register:e=>e.register(hS()),unregister:e=>e.unregister(hS())}),rS.add("funnelTooltipPositioner",{register:e=>e.Tooltip.positioners.funnelTooltipPositioner=uS,unregister:e=>e.Tooltip.positioners.funnelTooltipPositioner=void 0}),rS.add("sunburstLabelsPlugin",{register:e=>e.register(iy),unregister:e=>e.unregister(iy)}),rS.add("sunburstHoverPlugin",{register:e=>e.register(sy),unregister:e=>e.unregister(sy)});class ly 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=ov(lS)),t.onMounted(()=>{aS();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 cy{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=>rC(this.getters,e)).filter(e=>""!==e.range&&e.range!==Ss.InvalidReference),labelRange:aC(this.getters,e,s)}}}function hy(e,t,s,o,i){if("text"===t||"progress"===t||e?.type!==Od.number||s?.type!==Od.number)return;const n=s.value-e.value;return n>0?o:n<0?i:void 0}function dy(e,t,s){if("text"===s||e?.type!==Od.number||t?.type!==Od.number)return"neutral";const o=t.value-e.value;return o>0?"up":o<0?"down":"neutral"}function uy(e){return e.keyValue&&!Kn.test(e.keyValue)?"InvalidScorecardKeyValue":"Success"}function gy(e){return e.baseline&&!Kn.test(e.baseline)?"InvalidScorecardBaseline":"Success"}const py=globalThis.Path2D,my=py&&new py("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"),fy=py&&new py("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 vy=class e extends cy{keyValue;keyDescr;baseline;baselineMode;baselineDescr;progressBar=!1;background;baselineColorUp;baselineColorDown;fontColor;humanize;type="scorecard";constructor(e,t,s){super(e,t,s),this.keyValue=Ab(s,t,e.keyValue),this.keyDescr=e.keyDescr,this.baseline=Ab(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,uy,gy)}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=YS(e,t.baseline,s);i!==Ss.InvalidReference&&(o=i)}if(t.keyValue){const o=YS(e,t.keyValue,s);o!==Ss.InvalidReference&&(i=o)}return{...t,baseline:o,keyValue:i}}duplicateInDuplicatedSheet(t){const s=sC(this.sheetId,t,this.baseline),o=sC(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=oC(this.baseline,t),o=oC(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 by(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(sS(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,oS(s,e.baseline.text,e.baseline.position,e.baseline.style.underline,e.baseline.style.strikethrough)),e.baselineArrow&&e.baselineArrow.style.size>0&&py){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(my);break;case"up":s.fill(fy)}s.restore()}if(e.baselineDescr){const t=e.baselineDescr;s.font=t.style.font,s.fillStyle=t.style.color,s.fillText(sS(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,oS(s,sS(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(sS(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 Sy(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?Nn(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!==Od.number||e.type!==Od.number)return o?Nn(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?Nn({value:n,format:r},i):mn(n,{format:r,locale:i})}(n,s,e.baselineMode,e.humanize??!0,i),h="progress"===e.baselineMode&&co(c,i)?So(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:dy(n,s,e.baselineMode),baselineColor:hy(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 Cy=.05;function yy(e,t){const s=e||"";return t&&s?" "+s:s}function Iy({width:e,height:t},s){return new wy({width:e,height:t},s).computeDesign()}class wy{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-Cy*(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 yy(this.runtime.keyDescr,this.keyValue)}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){return yy(this.runtime.baselineDescr,this.baseline)}get baselineArrow(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get secondaryFontColor(){return hC(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:Gb(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:Gb(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:Gb(t,this.runtime.keyValueDescrStyle?.bold,this.runtime.keyValueDescrStyle?.italic),strikethrough:this.runtime.keyValueDescrStyle?.strikethrough,underline:this.runtime.keyValueDescrStyle?.underline},baselineValue:{font:Gb(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:Gb(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}}}}function Ey(e,t,s){const o=e.model.getters.getViewportZoomLevel();if(void 0===s&&(s=function(e){const t=e.target;if(!(t&&"classList"in t&&t instanceof Element))return null;const s=t.classList.contains("o-zoomable")?t:t.closest(".o-zoomable");return s?s.getBoundingClientRect():null}(t)),!s)return function(e){return{ev:e,clientX:e.clientX,clientY:e.clientY,offsetX:e.offsetX,offsetY:e.offsetY}}(t);const i=t.clientX-s.left,n=t.clientY-s.top,r=i/o,a=n/o;return{ev:t,clientX:t.clientX-i+r,clientY:t.clientY-n+a,offsetX:r,offsetY:a}}function Ry(e,t){return{height:t.height*e,width:t.width*e,x:t.x*e,y:t.y*e}}class xy 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;by(Iy(Ry(1/this.env.model.getters.getViewportZoomLevel(),e.getBoundingClientRect()),this.runtime),e)}}function Ty({strikethrough:e,underline:t}){return e||t?`${e?"line-through":""} ${t?"underline":""}`:"none"}function Ay(e){const t=Dy(e);return e?(e.fillColor&&(t.background=e.fillColor),t):t}function Dy(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 _y(e){let t="";for(const s in e)e[s]&&(t+=`${s}:${e[s]}; `);return t}function Oy(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 Fy(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 Py=/Mac/i,My=["Shift","Control","Alt","Meta"];function Ny(e,t){return!!e&&(!!t.target&&e.contains(t.target))}function Ly(){const e=document.querySelector(".o-grid-overlay");if(e)return e.getBoundingClientRect();throw new Error("Can't find spreadsheet position")}function ky(e){return e.el?Vy(e.el):{x:0,y:0,width:0,height:0}}function Vy(e){const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function*Uy(e){if(yield e,e.hasChildNodes())for(const t of e.childNodes)yield*Uy(t)}function Hy(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:zy(e,t,o),end:zy(e,s,i)}}function zy(e,t,s){let o=0;const i=Uy(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 By=/^[a-zA-Z]$/;function Gy(e,t="key"){let s="";My.includes(e.key)||($y(e)&&(s+="Ctrl+"),e.altKey&&(s+="Alt+"),e.shiftKey&&(s+="Shift+"));const o="key"===t?e.key:e.code;return s+=By.test(o)?o.toUpperCase():o,s}function Wy(){return Boolean(Py.test(navigator.userAgent))}function $y(e){return Wy()||Yy()?e.metaKey:e.ctrlKey}function qy(e){return 1===e.button||$y(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 jy(){return/Firefox/i.test(navigator.userAgent)}function Yy(){return/(iPad|iPhone|iPod)/i.test(navigator.userAgent)||"MacIntel"===navigator.platform&&(navigator.maxTouchPoints||1)>1}function Xy(){return/Android/i.test(navigator.userAgent)||Yy()||/(webOS|BlackBerry|Windows Phone)/i.test(navigator.userAgent)}const Ky=new Fg;function Jy(e){const t=Ky.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 Qy(e){const t=Ky.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=>!CC(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 SC(e.options.scales?.x?.ticks?.callback?.call(this,t),5)},padding:0,font:{size:9}}}}}}}(e)}return i}}function eI(e,t){const s=Ky.getAll().find(e=>e.match(t.type));if(!s)throw new Error("Unknown chart type.");return s.validateChartDefinition(e,t)}function tI(e,t,s){const o=Ky.getAll().find(e=>e.match(t.type));if(!o)throw new Error("Unknown chart type.");return o.transformDefinition(e,t,s)}const sI=12,oI="#F3F2F1";function iI(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=hI(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||"-";$b(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=>$b(s,u,{fontSize:e},"px")));const g={x:r.x+a/2,y:r.y+r.height+sI},p={x:r.x+r.width-a/2,y:r.y+r.height+sI},m=hC(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:sI},l=[],c=[];for(const h of e.inflectionValues){const e=(h.value-n.value)/(i.value-n.value),d=$b(o,h.label,a,"px"),u=Math.PI-Math.PI*e,g=cI(u,t.height+6,r.x,r.y,d+2,sI),p=c.some(e=>lI(e,g))?sI:0;c.push(g),l.push({rotation:u,label:h.label,fontSize:sI,color:s,offset:p})}return l}(t,r,m,s);let v=0,b=0,S=0;t.title.text&&({width:b,height:S}=jb(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:nI(t)},inflectionValues:f,gaugeValue:{label:u,textPosition:c,fontSize:h,color:m},minLabel:{label:t.minValue.label,textPosition:g,fontSize:sI,color:m},maxLabel:{label:t.maxValue.label,textPosition:p,fontSize:sI,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=oI,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=hC(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=Gb(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 nI(e){const t=hI(e,"final");if(void 0===t)return oI;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 rI(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 aI(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 lI(e,t){const s=rI(e),o=rI(t);for(const e of s)for(const t of o)if(aI(e,t))return!0;return!1}function cI(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 hI(e,t){return"animated"===t&&void 0!==e.animationValue?e.animationValue:e.gaugeValue?.value}const dI={responsive:!0,maintainAspectRatio:!1,elements:{line:{fill:!1},point:{hitRadius:15}},animation:!1,events:["mousemove","mouseout","click","touchstart","touchmove","mouseup"]};async function uI(e,t,s){const o=mI(t.width,t.height);let i;if("chartJsConfig"in e){const t=ae(e.chartJsConfig);t.plugins=[pI];const s=new globalThis.Chart(o,t);try{i=await vI(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){by(Iy(t,e),o),i=await vI(o)}else"gauge"===s&&(iI(o,e,t),i=await vI(o))}return i}async function gI(e,t,s){const o=mI(t.width,t.height);let i=null;if("chartJsConfig"in e){const t=ae(e.chartJsConfig);t.plugins=[pI];const s=new globalThis.Chart(o,t);try{i=await fI(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){by(Iy(t,e),o),i=await fI(o)}else"gauge"===s&&(iI(o,e,t),i=await fI(o))}return i}const pI={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 mI(e,t){return new OffscreenCanvas(e,t)}async function fI(e){return"convertToBlob"in e?e.convertToBlob({type:"image/png"}):new Promise(t=>e.toBlob(t,"image/png"))}async function vI(e){const t=await fI(e);if(t){if(!URL.createObjectURL)throw new Error("URL.createObjectURL is not supported in this environment");return URL.createObjectURL(t)}}function bI(e){return 8===(e=yv(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}var SI;!function(e){e.PlainText="text/plain",e.Html="text/html",e.Image="image"}(SI||(SI={}));const CI=new Set(["containsText","notContainsText","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","beginsWithText","endsWithText","isNotEmpty","isEmpty","isNotEqual","isEqual","customFormula"]),yI=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"]),II="(previous)",wI="(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 EI=["containsText","notContainsText","isEqualText","isEmpty","isNotEmpty","beginsWithText","endsWithText"],RI=["isEqual","isNotEqual","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","isEmpty","isNotEmpty"],xI=["dateIs","dateIsBefore","dateIsOnOrBefore","dateIsAfter","dateIsOnOrAfter","dateIsBetween","dateIsNotBetween","isEmpty","isNotEmpty"],TI={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},AI=function(e){return Math.floor(e/TI.second)},DI=function(e){return Math.floor(e/TI.minute)},_I=function(e){return Math.floor(e/TI.hour)},OI=function(e){return Math.floor(e/TI.day)},FI=function(e){return Math.floor(e/TI.month)},PI=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function MI(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=>js(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(TI.second>=TI[r]&&AI(n)<180)return"second";if(TI.minute>=TI[r]&&DI(n)<180)return"minute";if(TI.hour>=TI[r]&&_I(n)<96)return"hour";if(TI.day>=TI[r]&&OI(n)<90)return"day";if(TI.month>=TI[r]&&FI(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 NI(e,t,s,o){let i=ew(o,t,s).formattedValues,n=sw(o,t);gC(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=KI(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=JI(i,n));const r=tw(o,t,"left"),a=tw(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=GI(o,s);c.push(i)}return{dataSetsValues:n,trendDataSetsValues:c,axisFormats:l,labels:i,locale:o.getLocale(),topPadding:iw(e,o)}}function LI(e,t,s,o){const i=NI(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 kI(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||YI||(YI=!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&&jI(e,t,s,o)}(e,t,s,o))return"linear";return"category"}(e,t,s,o),n=ew(o,t,s);let r="linear"===i?n.values:n.formattedValues,a=sw(o,t);const l=gC(s,t[0],e.dataSetsHaveTitle||!1);l&&r.shift(),({labels:r,dataSetsValues:a}=KI(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}=JI(r,a)),e.cumulative&&(a=ow(a,"asc"));const c={y:tw(o,t,"left"),y1:tw(o,t,"right"),x:QI(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(WI(s,n,r,i,o.getLocale()))}return{dataSetsValues:a,axisFormats:c,labels:r,locale:o.getLocale(),trendDataSetsValues:h,axisType:i,topPadding:iw(e,o)}}function VI(e,t,s,o){let i=ew(o,t,s).formattedValues,n=sw(o,t);gC(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=KI(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=JI(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:tw(o,t,"left")},labels:i,locale:o.getLocale(),topPadding:iw(e,o)}}function UI(e,t,s,o){let i=ew(o,t,s).formattedValues,n=sw(o,t);gC(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=KI(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=JI(i,n));return{dataSetsValues:n,axisFormats:{r:tw(o,t,"left")||tw(o,t,"right")},labels:i,locale:o.getLocale()}}function HI(e,t,s,o){const i=t.slice(0,1);let n=ew(o,i,s).formattedValues;gC(s,i[0],e.dataSetsHaveTitle||!1)&&n.shift();let r=sw(o,i);({labels:n,dataSetsValues:r}=JI(n,r));return{dataSetsValues:r,axisFormats:{y:tw(o,i,"left")||tw(o,i,"right")},labels:n,locale:o.getLocale(),availableRegions:o.getGeoChartAvailableRegions(),geoFeatureNameToId:o.geoFeatureNameToId,getGeoJsonFeatures:o.getGeoJsonFeatures}}function zI(e,t,s,o){let i=ew(o,t,s).formattedValues,n=sw(o,t);gC(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=KI(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=JI(i,n)),e.cumulative&&(n=ow(n,"desc"));return{dataSetsValues:n,axisFormats:{x:tw(o,t,"left")||tw(o,t,"right")},labels:i,locale:o.getLocale()}}function BI(e,t,s,o){let i=ew(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=>XI(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=gC(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:QI(o,s,r)},labels:i,locale:o.getLocale()}}function GI(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=$I(e,s,o,ge(.5,i.length+.55,.2));return n.length?n:void 0}function WI(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=So({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=$I(e,n,r,ge(c,h+d/2,d));return u.length?u:void 0}function $I(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 sl([t],[i],[n],!0)[0].map((e,t)=>({x:o[t],y:e}));const r=Ka(t,i,s,!0).flat();return n.map((e,t)=>({x:o[t],y:Qa(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?el(sl([e],[s],[n],!0))[0].map((e,t)=>({x:o[t],y:e})):o.map(e=>({x:e,y:NaN}))}case"logarithmic":return sl([t],tl([i]),tl([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 qI(e,t,s,o){return ZI(e,t,s,o)||jI(e,t,s,o)}function ZI(e,t,s,o){if(!s||!jI(e,t,s,o))return!1;const i=QI(o,s,gC(s,t[0],e.dataSetsHaveTitle||!1));return Boolean(i&&PI.test(i))}function jI(e,t,s,o){if(!s)return!1;const i=o.getRangeValues(s);return gC(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),!i.some(e=>isNaN(Number(e))&&e)&&!i.every(e=>!e)}let YI=!1;function XI(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 KI(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 JI(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 QI(e,t,s){if(!t)return;const{sheetId:o,zone:i}=t,n=Gt(i).map(t=>e.getEvaluatedCell({sheetId:o,...t}).format);return s&&n.shift(),n.find(e=>void 0!==e)}function ew(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,XI(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=XI(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,XI(e,t[0]).length).map(e=>e.toString()),values:o.formattedValues}}return o}function tw(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&&!En(e));if(s)return s}}function sw(e,t){const s=[];for(const[o,i]of Object.entries(t)){let t=`${wg.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?XI(e,i):[];r.every(e=>!e||"string"==typeof e&&!fo(e))&&r.filter(e=>"string"==typeof e).length>1?r=r.map(e=>e&&!fo(e)?1:null):r.every(e=>null==e||!co(e.toString(),Fc))&&(n=!0),s.push({data:r,label:t,hidden:n})}return s}function ow(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 iw(e,t){const{title:s,legendPosition:o}=e,i=s&&s.text||"top"===o;return t.isDashboard()&&!i?30:0}function nw(e,t){return{padding:{left:E,right:E,top:Math.max(15,t.topPadding||0),bottom:10}}}function rw(e,t){return{display:"none"!==e.legendPosition,position:"none"!==e.legendPosition?e.legendPosition:void 0}}function aw(e,t){return{...mw,...rw(e),...fw(cC(e.background),{pointStyle:"rect",lineWidth:3})}}function lw(e,t){const s=e.fillArea,o=s?"rect":"line",i=s?2:3;return{...mw,...rw(e),...fw(cC(e.background),{pointStyle:o,lineWidth:i})}}function cw(e,t){const{dataSetsValues:s}=t,o=Math.max(0,...s.map(e=>e?.data?.length??0)),i=bC(new qv(o),s),n=cC(e.background);return{...rw(e),labels:{usePointStyle:!0,generateLabels:e=>(e.data.labels?.map((e,t)=>({text:SC(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 hw(e,t){return{...mw,...rw(e),...fw(cC(e.background),{pointStyle:"circle",strokeStyle:e.background||"#ffffff",lineWidth:8})}}function dw(e,t){return{...mw,...rw(e),...fw(cC(e.background),{lineWidth:3})}}function uw(e,t){const s=cC(e.background),o=e.negativeValuesColor||f,i=e.positiveValuesColor||m,n=e.subTotalValuesColor||v;return{...rw(e),labels:{usePointStyle:!0,generateLabels:()=>{const t=[{text:vs("Positive values"),fontColor:s,fillStyle:i,strokeStyle:i,pointStyle:"rect"},{text:vs("Negative values"),fontColor:s,fillStyle:o,strokeStyle:o,pointStyle:"rect"}];return(e.showSubTotals||e.firstValueAsSubtotal)&&t.push({text:vs("Subtotals"),fontColor:s,fillStyle:n,strokeStyle:n,pointStyle:"rect"}),t},filter:(e,t)=>!("datasetIndex"in e)||!t.datasets[e.datasetIndex].hidden},onClick:()=>{}}}function gw(e,t){const s=e.fillArea??!1,o=s?"rect":"line",i=s?2:3;return{...mw,...rw(e),...fw(cC(e.background),{pointStyle:o,lineWidth:i})}}function pw(e,t){const s=cC(e.background);return{...rw(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:SC(t),fontColor:s,fillStyle:e,strokeStyle:e,pointStyle:"rect"}))}}}}const mw={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 fw(e,t){return{labels:{color:e,usePointStyle:!0,generateLabels:s=>s.data.datasets.map((o,i)=>CC(o.xAxisID)?{text:SC(o.label),fontColor:e,strokeStyle:o.borderColor,hidden:!s.isDatasetVisible(i),pointStyle:"line",datasetIndex:i,lineWidth:3}:{text:SC(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 vw(e,t){let s={};const{trendDataSetsValues:o,locale:i,axisFormats:n}=t,r={stacked:e.stacked,locale:i};if(e.horizontal)s.x=Tw(e,"bottom","values",{...r,format:n?.x}),s.y=Tw(e,"left","labels",r);else{s.x=Tw(e,"bottom","labels",r);const t={...r,format:n?.y};s.y=Tw(e,"left","values",t);const o={...r,format:n?.y1};s.y1=Tw(e,"right","values",o)}if(s=FC(s),o&&o.length&&o.some(DC)){const e=Math.max(...o.map(e=>e?.length||0));s[KS]={...s.x,labels:Array(e).fill(""),offset:!1,display:!1},s[JS]={...s.x,offset:!0,display:!1}}return s}function bw(e,t){const{locale:s,axisType:o,trendDataSetsValues:i,labels:n,axisFormats:r}=t,a=r?.x,l=e.stacked;let c={x:Tw(e,"bottom","labels",{locale:s}),y:Tw(e,"left","values",{locale:s,stacked:l,format:r?.y}),y1:Tw(e,"right","values",{locale:s,stacked:l,format:r?.y1})};if(c=FC(c),"time"===o&&n&&a){const e={type:"time",time:MI(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=>Nn({value:e,format:a},s):e=>mn(e,{format:a,locale:s}));if(i&&i.length&&i.some(DC)&&(c[KS]={...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[KS].type="category",c[KS].labels=TC(0,e).map(e=>e.toString()),c[KS].offset=!1,c[JS].type="category",c[JS].offset=!1}return c}function Sw(e,t){const s=bw(e,t);return{...s,x:{...s.x,grid:{display:!0}}}}function Cw(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;e.dataSets;const n={x:{...Tw(e,"bottom","labels",{locale:s}),grid:{display:!1}},y:{position:e.verticalAxisPosition,ticks:{color:cC(e.background),callback:fC({locale:s,format:i},e.humanize)},grid:{lineWidth:e=>0===e.tick.value?2:1},title:xw(e.axesDesign?.y)}},r=n?.y||n?.y1;return r&&(r.grid={lineWidth:e=>0===e.tick.value?2:1}),n}function yw(e,t){const{dataSetsValues:s}=t,o=vw(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 Iw(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:fC({format:o?.r,locale:s},e.humanize),backdropColor:e.background||"#FFFFFF"},pointLabels:{color:cC(e.background),callback:e=>SC(e)},suggestedMin:n<0?n-1:0}}}function ww(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:Rw(r?.defaultProjection||"mercator"),axis:"x"},color:{axis:"x",display:"none"!==e.legendPosition,border:{color:S},grid:{color:S},ticks:{color:cC(e.background),callback:fC({locale:s,format:a},e.humanize)},legend:{position:n,align:n.includes("right")?"left":"right",margin:Dw(e)},interpolate:Aw(e),missing:e.missingValueColor||"#ffffff"}}}function Ew(e,t){const s=t.dataSetsValues[0];return{x:{display:!1},y:{grid:{offset:!1},ticks:{callback:function(e){return SC(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?mn(n/r,{format:"0%",locale:t.locale}):""}},grid:{display:!1}}}}function Rw(e){return"conicConformal"===e?window.ChartGeo.geoConicConformal().rotate([100,0]):e}function xw(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 Tw(e,t,s,o){const{useLeftAxis:i,useRightAxis:n}=pC(e);if("left"===t&&!i||"right"===t&&!n)return;const r=cC(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:xw(a),grid:{display:s},beginAtZero:!0,stacked:o?.stacked,ticks:{color:r,callback:fC(o,e.humanize)}}}return{ticks:{padding:5,color:r,callback:function(e,t,s){return SC(this.getLabelForValue(e))}},grid:{display:!1},stacked:o?.stacked,title:xw(a)}}function Aw(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}),Yv(t)}function Dw(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 _w={showValues:!1,showLabels:!0,valuesDesign:{align:"center",fontSize:13}};function Ow(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 mC(s,o,e.humanize)(t,n)}}}function Fw(e,t){const{axisFormats:s,locale:o}=t;return{callback:mC(s,o,e.humanize),showLabels:e.showLabels??_w.showLabels,showValues:e.showValues??_w.showValues,style:{fontSize:e.valuesDesign?.fontSize??_w.valuesDesign.fontSize,align:e.valuesDesign?.align??_w.valuesDesign.align,bold:e.valuesDesign?.bold??_w.valuesDesign.bold,italic:e.valuesDesign?.italic??_w.valuesDesign.italic,textColor:e.valuesDesign?.color??_w.valuesDesign.color}}}function Pw(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)))?"":mC(s,o)(e,t.xAxisID||"x")}}function Mw(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}${mC(s,o,e.humanize)(l,i.yAxisID)}`}}}function Nw(e,t){const s=e.title,o=hC(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 Lw='\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 kw;function Vw(e,s={}){return function(e,s={}){kw||(kw=new t.App(t.Component,{templates:Lw,translateFn:vs}));const o=kw.getTemplate(e),i=o(s,{}),n=document.createElement("div");return t.blockDom.mount(i,n),n}(e,s).innerHTML}function Uw(e,t){return{enabled:!1,external:Yw,callbacks:{title:function(e){return e.some(e=>!CC(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 mC(t.axisFormats,t.locale,e.humanize)(i,n)}}}}function Hw(e,t){const{axisType:s,locale:o,axisFormats:i}=t,n=i?.x,r={enabled:!1,external:Yw,callbacks:{}};return r.callbacks.label="linear"===s?t=>{const s=t.parsed.y;let r=CC(t.dataset.xAxisID)?"":t.parsed.x;"string"==typeof r&&co(r,o)&&(r=So(r,o));const a=pn(r,n,o,e.humanize),l=t.dataset.yAxisID||"y",c=pn(s,i?.[l],o,e.humanize);return a?`(${a}, ${c})`:`${c}`}:function(t){const s=t.parsed.y,n=t.dataset.yAxisID;return mC(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=>!CC(e.dataset.xAxisID))?void 0:""},r}function zw(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;return{enabled:!1,external:Yw,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`${pn(n,!i&&n>=1e3?"#,##":i,s,e.humanize)} (${o}%)`}}}}function Bw(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:Yw,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 pn(n,!r&&Math.abs(n)>1e3?"#,##":r,o,e.humanize)}}}}function Gw(e,t){const s=Uw(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 Ww(e,t){const{locale:s,axisFormats:o}=t;return{enabled:!1,external:Yw,callbacks:{beforeLabel:e=>e.dataset?.label||e.label,label:function(t){return pn(t.parsed.r,o?.r,s,e.humanize)}}}}function $w(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;return{enabled:!1,external:Yw,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 pn(o,!i&&Math.abs(o)>=1e3?"#,##":i,s,e.humanize)}}}}function qw(e,t){return{enabled:!1,external:Yw,position:"funnelTooltipPositioner",callbacks:{title:()=>"",beforeLabel:e=>e.label,label:function(s){const o=s.parsed.x,i=s.dataset.xAxisID;return mC(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:Yw,filter:function(e){const t=e.raw;return t?.label!==LC},callbacks:{title:()=>"",beforeLabel:e=>e.raw.groups.join(" / "),label:function(t){const o=t.raw.value;return pn(o,!i&&o>=1e3?"#,##":i,s,e.humanize)}}}}function jw(e,t){const{locale:s,axisFormats:o}=t,i=o?.y;return{enabled:!1,external:Yw,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 pn(o,!i&&o>=1e3?"#,##":i,s,e.humanize)}}}}function Yw({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?Pv(n,1):n}}),o=Vw("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:Xw(e,t,i.clientWidth)+"px",top:Math.floor(t.caretY-i.clientHeight/2)+"px"})}function Xw(e,t,s){const o=t.caretX;return o+s>e.chartArea.right?Math.max(0,o-s):o}var Kw=Object.freeze({__proto__:null,GHOST_SUNBURST_VALUE:LC,INTERACTIVE_LEGEND_CONFIG:mw,canChartParseLabels:qI,getBarChartData:NI,getBarChartDatasets:kC,getBarChartLegend:aw,getBarChartScales:vw,getBarChartTooltip:Uw,getChartColorsGenerator:ty,getChartLabelFormat:QI,getChartLayout:nw,getChartShowValues:Ow,getChartTitle:Nw,getComboChartDatasets:BC,getComboChartLegend:dw,getData:XI,getFunnelChartData:zI,getFunnelChartDatasets:$C,getFunnelChartScales:Ew,getFunnelChartTooltip:qw,getFunnelLabelColors:qC,getGeoChartData:HI,getGeoChartDatasets:WC,getGeoChartScales:ww,getGeoChartTooltip:$w,getHierarchalChartData:BI,getLineChartData:kI,getLineChartDatasets:UC,getLineChartLegend:lw,getLineChartScales:bw,getLineChartTooltip:Hw,getPieChartData:VI,getPieChartDatasets:zC,getPieChartLegend:cw,getPieChartTooltip:zw,getPyramidChartData:LI,getPyramidChartScales:yw,getPyramidChartShowValues:Pw,getPyramidChartTooltip:Gw,getRadarChartData:UI,getRadarChartDatasets:GC,getRadarChartLegend:gw,getRadarChartScales:Iw,getRadarChartTooltip:Ww,getScatterChartDatasets:HC,getScatterChartLegend:hw,getScatterChartScales:Sw,getSunburstChartDatasets:ZC,getSunburstChartLegend:pw,getSunburstChartTooltip:Zw,getSunburstShowValues:Fw,getTopPaddingForDashboard:iw,getTreeMapChartDatasets:KC,getTreeMapChartTooltip:jw,getTrendDatasetForBarChart:GI,getTrendDatasetForLineChart:WI,getWaterfallChartLegend:uw,getWaterfallChartScales:Cw,getWaterfallChartShowValues:Mw,getWaterfallChartTooltip:Bw,getWaterfallDatasetAndLabels:VC,makeDatasetsCumulative:ow});class Jw extends cy{dataSets;labelRange;background;legendPosition;stacked;aggregated;type="bar";dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal;showValues;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=iC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ab(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 lC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,dC,uC)}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=tC(this.sheetId,e,this.dataSets),s=sC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new Jw(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Jw(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,gC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:bI(this.background||c),fontColor:bI(cC(this.background)),dataSets:e,labelRange:t,verticalAxis:pC(s)}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=eC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new Jw(i,this.sheetId,this.getters)}}function Qw(e,t){const s=e.getDefinition(),o=NI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:kC(s,o)},options:{...dI,indexAxis:e.horizontal?"y":"x",layout:nw(0,o),scales:vw(s,o),plugins:{title:Nw(s,t),legend:aw(s),tooltip:Uw(s,o),chartShowValuesPlugin:Ow(s,o)}}},background:e.background||c}}class eE{scope;code="";constructor(e=new sE){this.scope=e}append(...e){this.code+=e.map(e=>e.toString()).join("\n")+"\n"}return(e){return new tE(this.scope,this.code,e)}toString(){return oE(this.code)}}class tE{scope;returnExpression;code;constructor(e,t,s){this.scope=e,this.returnExpression=s,this.code=oE(t)}toString(){return this.code}assignResultToVariable(){if(this.scope.isAlreadyDeclared(this.returnExpression))return this;const e=this.scope.nextVariableName(),t=new eE(this.scope);return t.append(this.code),t.append(`const ${e} = ${this.returnExpression};`),t.return(e)}}class sE{nextId=1;declaredVariables=new Set;nextVariableName(){const e="_"+this.nextId++;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}}function oE(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 iE=mf.content,nE={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},rE={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"},aE={};function lE(e){return cE(If(e))}function cE(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=uo(i.value,Fc);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(!aE[i]){const r=Pf([...e]),a=new sE;let l=0,c=0,h=0;if("BIN_OPERATION"===r.type&&":"===r.value)throw new Is(vs("Invalid formula"));if("EMPTY"===r.type)throw new Is(vs("Invalid formula"));const d=m(r),u=new eE;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=iE[s];if(!o)throw new xs(vs('Unknown function: "%s"',e.value));!function(e){const t=e.args.length,s=e.value.toUpperCase(),o=iE[s],{nbrArgRepeating:i,minArgRequired:n}=o;if(t<n)throw new Is(vs("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 Is(vs("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.nbrOptionalNonRepeatingArgs;if(e>0)throw new Is(vs("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.nbrOptionalNonRepeatingArgs,nbrValueRemaining:e}))}}(e);const i=[],n=hs(o,t.length);for(let e=0;e<t.length;e++){const s=o.args[n(e).index??-1],r=t[e],a=s.type||[],l=a.includes("META")||a.includes("RANGE<META>"),c=a.some(e=>hE(e));i.push(m(r,l,c))}return i}function m(e,t=!1,s=!1){const i=new eE(a);if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&t)throw new Is(vs("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=rE[e.value],s=m(e.operand,!1,!1).assignResultToVariable();return i.append(s),i.return(`ctx['${t}'](${s.returnExpression})`)}case"BIN_OPERATION":{const t=nE[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")}}aE[i]=g}const n={execute:aE[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 hE(e){return e.startsWith("RANGE")}class dE{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 uE{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 gE=new class extends Fg{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 pE=new class extends Fg{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}},mE={light:vs("Light"),medium:vs("Medium"),dark:vs("Dark"),custom:vs("Custom")},fE={hasFilters:!1,totalRow:!1,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,automaticAutofill:!0,styleId:"TableStyleMedium2"};function vE(e,t){return{coloredText:Nv(t,.3),light:Mv(t,.8),medium:Mv(t,.6),dark:Nv(t,.3),mediumBorder:Mv(t,.45),highlight:t,name:e}}const bE={black:{name:vs("Black"),coloredText:"#000000",light:"#D9D9D9",medium:"#A6A6A6",dark:"#404040",mediumBorder:"#000000",highlight:"#000000"},lightBlue:vE(vs("Light blue"),"#346B90"),red:vE(vs("Red"),"#C53628"),lightGreen:vE(vs("Light green"),"#748747"),purple:vE(vs("Purple"),"#6C4E65"),gray:{name:vs("Gray"),coloredText:"#666666",light:"#EEEEEE",medium:"#DDDDDD",dark:"#767676",mediumBorder:"#D0D0D0",highlight:"#A9A9A9"},orange:vE(vs("Orange"),"#C37034")},SE={black:bE.black,orangeBlue:{...bE.lightBlue,highlight:bE.orange.highlight},purpleGreen:{...bE.lightGreen,highlight:bE.purple.highlight},redBlue:{...bE.lightBlue,highlight:bE.red.highlight}},CE=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}}}),yE=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"}}}}),IE=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}}}),wE=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}}}),EE=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}}}),RE=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:bE.black.light}},firstColumnStripe:{style:{fillColor:bE.black.light}}}),xE=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}}}),TE=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}}}),AE=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}}}),DE=TE(bE.black);DE.wholeTable.style.fillColor="#737373";const _E=RE(bE.black);function OE(e,t,s){return{...t(s),displayName:`${s.name}, ${e}`}}_E.wholeTable.border={..._E.wholeTable.border,left:{color:"#000000",style:"thin"},right:{color:"#000000",style:"thin"},horizontal:{color:"#000000",style:"thin"},vertical:{color:"#000000",style:"thin"}};const FE={None:{category:"light",templateName:"none",primaryColor:"",displayName:"none"},TableStyleLight1:OE("TableStyleLight1",CE,bE.black),TableStyleLight2:OE("TableStyleLight2",CE,bE.lightBlue),TableStyleLight3:OE("TableStyleLight3",CE,bE.red),TableStyleLight4:OE("TableStyleLight4",CE,bE.lightGreen),TableStyleLight5:OE("TableStyleLight5",CE,bE.purple),TableStyleLight6:OE("TableStyleLight6",CE,bE.gray),TableStyleLight7:OE("TableStyleLight7",CE,bE.orange),TableStyleLight8:OE("TableStyleLight8",yE,bE.black),TableStyleLight9:OE("TableStyleLight9",yE,bE.lightBlue),TableStyleLight10:OE("TableStyleLight10",yE,bE.red),TableStyleLight11:OE("TableStyleLight11",yE,bE.lightGreen),TableStyleLight12:OE("TableStyleLight12",yE,bE.purple),TableStyleLight13:OE("TableStyleLight13",yE,bE.gray),TableStyleLight14:OE("TableStyleLight14",yE,bE.orange),TableStyleLight15:OE("TableStyleLight15",IE,bE.black),TableStyleLight16:OE("TableStyleLight16",IE,bE.lightBlue),TableStyleLight17:OE("TableStyleLight17",IE,bE.red),TableStyleLight18:OE("TableStyleLight18",IE,bE.lightGreen),TableStyleLight19:OE("TableStyleLight19",IE,bE.purple),TableStyleLight20:OE("TableStyleLight20",IE,bE.gray),TableStyleLight21:OE("TableStyleLight21",IE,bE.orange),TableStyleMedium1:OE("TableStyleMedium1",wE,bE.black),TableStyleMedium2:OE("TableStyleMedium2",wE,bE.lightBlue),TableStyleMedium3:OE("TableStyleMedium3",wE,bE.red),TableStyleMedium4:OE("TableStyleMedium4",wE,bE.lightGreen),TableStyleMedium5:OE("TableStyleMedium5",wE,bE.purple),TableStyleMedium6:OE("TableStyleMedium6",wE,bE.gray),TableStyleMedium7:OE("TableStyleMedium7",wE,bE.orange),TableStyleMedium8:OE("TableStyleMedium8",EE,bE.black),TableStyleMedium9:OE("TableStyleMedium9",EE,bE.lightBlue),TableStyleMedium10:OE("TableStyleMedium10",EE,bE.red),TableStyleMedium11:OE("TableStyleMedium11",EE,bE.lightGreen),TableStyleMedium12:OE("TableStyleMedium12",EE,bE.purple),TableStyleMedium13:OE("TableStyleMedium13",EE,bE.gray),TableStyleMedium14:OE("TableStyleMedium14",EE,bE.orange),TableStyleMedium15:{..._E,displayName:"Black, TableStyleMedium15"},TableStyleMedium16:OE("TableStyleMedium16",RE,bE.lightBlue),TableStyleMedium17:OE("TableStyleMedium17",RE,bE.red),TableStyleMedium18:OE("TableStyleMedium18",RE,bE.lightGreen),TableStyleMedium19:OE("TableStyleMedium19",RE,bE.purple),TableStyleMedium20:OE("TableStyleMedium20",RE,bE.gray),TableStyleMedium21:OE("TableStyleMedium21",RE,bE.orange),TableStyleMedium22:OE("TableStyleMedium22",xE,bE.black),TableStyleMedium23:OE("TableStyleMedium23",xE,bE.lightBlue),TableStyleMedium24:OE("TableStyleMedium24",xE,bE.red),TableStyleMedium25:OE("TableStyleMedium25",xE,bE.lightGreen),TableStyleMedium26:OE("TableStyleMedium26",xE,bE.purple),TableStyleMedium27:OE("TableStyleMedium27",xE,bE.gray),TableStyleMedium28:OE("TableStyleMedium28",xE,bE.orange),TableStyleDark1:{...DE,displayName:"Black, TableStyleDark1"},TableStyleDark2:OE("TableStyleDark2",TE,bE.lightBlue),TableStyleDark3:OE("TableStyleDark3",TE,bE.red),TableStyleDark4:OE("TableStyleDark4",TE,bE.lightGreen),TableStyleDark5:OE("TableStyleDark5",TE,bE.purple),TableStyleDark6:OE("TableStyleDark6",TE,bE.gray),TableStyleDark7:OE("TableStyleDark7",TE,bE.orange),TableStyleDark8:OE("TableStyleDark8",AE,SE.black),TableStyleDark9:OE("TableStyleDark9",AE,SE.redBlue),TableStyleDark10:OE("TableStyleDark10",AE,SE.purpleGreen),TableStyleDark11:OE("TableStyleDark11",AE,SE.orangeBlue)},PE={none:()=>({category:"none",templateName:"none",primaryColor:"",name:"none"}),lightColoredText:CE,lightAllBorders:IE,mediumAllBorders:xE,lightWithHeader:yE,mediumBandedBorders:wE,mediumMinimalBorders:RE,darkNoBorders:AE,mediumWhiteBorders:EE,dark:TE};function ME(e,t,s){const o=vE("",s);return{...PE[t](o),category:"custom",displayName:e}}function NE(e,t){if("SPREADSHEET"!==e.pivot.type)return e;if(e.pivot.dataSet?.sheetId!==t.sheetId)return e;const s=os(e.pivot.dataSet.zone,t),o=s?{...e.pivot.dataSet,zone:s}:void 0;return{...e,pivot:{...e.pivot,dataSet:o}}}function LE(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 kE(e,t){if(e.sheetId!==t.sheetId)return e;const s=os(e.zone,t);if(!s)return;const o=e.newTableRange?is(e.newTableRange,t):void 0;return{...e,newTableRange:o,zone:s}}function VE(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let s;if("REMOVE_COLUMNS_ROWS"===t.type)s=vb(t.elements,[e.base])[0];else if("ADD_COLUMNS_ROWS"===t.type){s=fb(Pe(t.position,t.base),t.quantity,[e.base])[0]}return void 0!==s?{...e,base:s}:void 0}function UE(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=vb(t.elements,s);else if("ADD_COLUMNS_ROWS"===t.type){o=fb(Pe(t.position,t.base),t.quantity,s)}return 0!==o.length?{...e,start:Math.min(...o),end:Math.max(...o)}:void 0}function HE(e,t){return(e=ae(e)).pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=jS(e.computedBy.sheetId,e.computedBy.formula,t))}),e}function zE(e,t){return{...e,definition:tI(e.sheetId,e.definition,t)}}gE.addTransformation("ADD_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],VE),gE.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],VE),gE.addTransformation("DELETE_SHEET",["MOVE_RANGES"],function(e,t){const s=t.sheetId;if(e.targetSheetId===s||e.sheetId===s)return;return e}),gE.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART","UPDATE_CAROUSEL"],function(e,t){if(e.figureId===t.figureId)return;return e}),gE.addTransformation("DELETE_CHART",["UPDATE_CHART"],function(e,t){if(e.chartId===t.chartId)return;return e}),gE.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))}}}),gE.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}),gE.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=>!Vt(o,e))&&s.push(o);if(s.length)return{...e,target:s};return}),gE.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],LE),gE.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],LE),gE.addTransformation("ADD_COLUMNS_ROWS",["UPDATE_TABLE"],kE),gE.addTransformation("REMOVE_COLUMNS_ROWS",["UPDATE_TABLE"],kE),gE.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:fE.styleId}}}),gE.addTransformation("ADD_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],UE),gE.addTransformation("REMOVE_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],UE),gE.addTransformation("REMOVE_PIVOT",["RENAME_PIVOT","DUPLICATE_PIVOT","INSERT_PIVOT","UPDATE_PIVOT"],function(e,t){if(e.pivotId===t.pivotId)return;return e}),gE.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}),gE.addTransformation("ADD_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],NE),gE.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],NE),pE.add("UPDATE_CELL",function(e,t){const s=e.content&&jS(e.sheetId,e.content,t);return{...e,content:s}}),pE.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=>jS(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&&jS(e.sheetId,o.value,t)},maximum:{...i,value:i.value&&jS(e.sheetId,i.value,t)},midpoint:n?{...n,value:jS(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:jS(e.sheetId,o.value,t)},lowerInflectionPoint:{...i,value:jS(e.sheetId,i.value,t)}}}else"DataBarRule"===s.type&&(e.cf.rule={...s,rangeValues:s.rangeValues?YS(e.sheetId,s.rangeValues,t):void 0});return e}),pE.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=>jS(e.sheetId,s,t)),e}),pE.add("ADD_PIVOT",HE),pE.add("UPDATE_PIVOT",HE),pE.add("CREATE_CHART",zE),pE.add("UPDATE_CHART",zE);const BE=[{match:function(e){return"sheetId"in e},fn:$E},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const s=$E(e,t);if("SKIP_TRANSFORMATION"!==s)return"IGNORE_COMMAND"===s?"IGNORE_COMMAND":e;const o=[];for(const s of e.target){const e=os(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=$E(e,t);if("SKIP_TRANSFORMATION"!==s)return"IGNORE_COMMAND"===s?"IGNORE_COMMAND":e;const o=os(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=$E(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)&&Ut(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=$E(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=vb(t.elements,e.elements);else if("ADD_COLUMNS_ROWS"===t.type){o=fb(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=>is(e,t)).filter(Te);if(!s.length)return"IGNORE_COMMAND";return{...e,ranges:s}}}];function GE(e,t){const s=gE.getTransformation(e.type,t.type),o=s?s(e,t):function(e,t){for(const{match:s,fn:o}of BE)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=pE.get(e.type);if(!s)return e;const o=Ob(t);if(o)return s(e,o);return e}(o,t):o}function WE(e,t){let s=[...e];const o=new Set(gE.getKeys());for(const e of t)(o.has(e.type)||Fb.contains(e.type))&&(s=s.reduce((t,s)=>{const o=GE(s,e);return o&&t.push(o),t},[]));return s}function $E(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 qE{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 jE extends Jf{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new cr;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 qE(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 qE(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:WE(s,t)})}break;case"SNAPSHOT_CREATED":{const t=new qE(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 YE=(new Fg).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 vr.values())YE.contains(e)||YE.add(e,XE);function XE(e){return[e]}function KE(e){return YE.get(e.type)(e)}class JE{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 JE(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 QE{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new eR(this.id,Oe(()=>e(this.data)))}}class eR{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new eR(this.id,this.lazyData.map(e))}}class tR{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new tR(function*(e,t){for(const s of e)if(yield s,s.operation.id===t)return}(this.operations,e))}stopBefore(e){return new tR(function*(e,t){for(const s of e){if(s.operation.id===t)return;yield s}}(this.operations,e))}startAfter(e){return new tR(function*(e,t){let s=!0;for(const o of e)s||(yield o),o.operation.id===t&&(s=!1)}(this.operations,e))}}class sR{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 tR(me(this._execution(e),this._execution(e)))}revertedExecution(e){return new tR(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 oR{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 JE(this.buildTransformation),this.tree=new sR(this.buildTransformation,this.HEAD_BRANCH);const t=e.initialOperationId,s=new QE(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 QE(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 QE(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 iR(e){return new oR({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--){nR(t.changes[e])}}([e]),buildEmpty:e=>new qE(e,"empty",[]),buildTransformation:{with:e=>t=>new qE(t.id,t.clientId,WE(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new qE(t.id,t.clientId,WE(t.commands,e.commands.map(KE).flat()),t.rootCommand,void 0,t.timestamp)}})}function nR(e){const t=e.target,s=e.key,o=e.before;void 0===o?delete t[s]:t[s]=o}class rR{xmlString;constructor(e){this.xmlString=e}toString(){return this.xmlString}}const aR=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart","comboChart","radarChart"],lR="M256 9 a247 247 0 1 0.1 0 0";function cR(e){return{name:"CARET_DOWN",width:512,height:512,paths:[{fillColor:e.textColor||I,path:"M120 195 h270 l-135 130"}]}}function hR(e){return{name:"CARET_UP",width:512,height:512,paths:[{fillColor:e.textColor||I,path:"M120 325 h270 l-135 -130"}]}}const dR="M40 185 h270 l-135 128";function uR(e){return{name:"CHIP",width:512,height:512,paths:[{fillColor:e.textColor||I,path:dR}]}}function gR(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:dR}]}}const pR={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"}]},mR={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"}]},fR={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 vR(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 bR(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 SR={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:lR}]}},dotNeutral:{template:"YELLOW_DOT",svg:{name:"YELLOW_DOT",width:512,height:512,paths:[{fillColor:"#F0AD4E",path:lR}]}},dotBad:{template:"RED_DOT",svg:{name:"RED_DOT",width:512,height:512,paths:[{fillColor:"#E06666",path:lR}]}}},CR={arrows:{good:"arrowGood",neutral:"arrowNeutral",bad:"arrowBad"},smiley:{good:"smileyGood",neutral:"smileyNeutral",bad:"smileyBad"},dots:{good:"dotGood",neutral:"dotNeutral",bad:"dotBad"}},yR={};function IR(e){if(yR[e])return yR[e];const t=new Path2D(e);return yR[e]=t,t}function wR(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 ER(e,t=0){const s={};for(let o=0;o<e.length;o++)e[o]&&(s[o+t]=e[o]);return s}function RR(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,(e,t)=>String.fromCharCode(parseInt(t,16)))}function xR(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 TR(e){if("="===e[0])return e;const t=Nc(e);return 1===t.length&&"REFERENCE"!==t[0].type?e:"="+e}var AR;!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"}(AR||(AR={}));class DR{_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 _R=["thin","medium","thick","dashed","dotted"],OR=["general","left","center","right"],FR=["top","center","bottom"],PR=["Arial"],MR=["solid","none"],NR=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWithText","containsBlanks","notContainsBlanks"],LR={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},kR={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"},VR={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"},UR={top:"top",center:"middle",bottom:"bottom",justify:"middle",distributed:"middle"},HR={top:"top",middle:"center",bottom:"bottom"},zR={beginsWith:"beginsWithText",endsWith:"endsWithText",containsText:"containsText",notContains:"notContainsText",between:"isBetween",notBetween:"isNotBetween",equal:"isEqual",notEqual:"isNotEqual",greaterThan:"isGreaterThan",greaterThanOrEqual:"isGreaterOrEqualTo",lessThan:"isLessThan",lessThanOrEqual:"isLessOrEqualTo"},BR={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},GR={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},WR={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"},$R={none:"none",b:"bottom",t:"top",l:"left",r:"right",tr:"right"},qR={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"},jR={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"},YR={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:"@"},XR={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},KR={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"},JR={"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"},QR={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"},ex={between:"isBetween",notBetween:"isNotBetween",equal:"isEqual",notEqual:"isNotEqual",greaterThan:"isGreaterThan",greaterThanOrEqual:"isGreaterOrEqualTo",lessThan:"isLessThan",lessThanOrEqual:"isLessOrEqualTo"},tx={between:"dateIsBetween",notBetween:"dateIsNotBetween",equal:"dateIs",greaterThan:"dateIsAfter",greaterThanOrEqual:"dateIsOnOrAfter",lessThan:"dateIsBefore",lessThanOrEqual:"dateIsOnOrBefore"};function sx(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=gS;else{if(!e.indexed)return;t=KR[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=Tv(e),o=Dv(s);t<0&&(o.l=o.l*(1+t));t>0&&(o.l=o.l*(1-t)+(100-100*(1-t)));return xv(Av(o))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function ox(e){return 9===e.length&&(e=e.slice(0,7)),parseInt(e.replace("#",""),16)}const ix=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function nx(e,t,s){const o=YR[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 ix.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 mn(0,{format:e,locale:Fc}),!0}catch(e){return!1}}(e))return e}catch(e){}s.generateNotSupportedWarning(AR.NumFmtIdNotSupported,o||`nmFmtId ${e}`)}}function rx(e,t){const s=e.borders.map(e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(AR.DiagonalBorderNotSupported)}(e,t);const s={top:ax(e.top,t),bottom:ax(e.bottom,t),left:ax(e.left,t),right:ax(e.right,t)};return Object.keys(s).forEach(e=>void 0===s[e]&&delete s[e]),s});return ER(s,1)}function ax(e,t){if(!e)return;!function(e,t){_R.includes(e.style)||t.generateNotSupportedWarning(AR.BorderStyleNotSupported,e.style,_R)}(e,t);const s=kR[e.style];return s?{style:s,color:sx(e.color)}:void 0}function lx(e,t){return ER(e.styles.map(s=>cx({fontStyle:e.fonts[s.fontId],fillStyle:e.fills[s.fillId],alignment:s.alignment},t)),1)}function cx(e,t){return function(e,t,s){e&&e.name&&!PR.includes(e.name)&&s.generateNotSupportedWarning(AR.FontNotSupported,e.name,PR);t&&t.patternType&&!MR.includes(t.patternType)&&s.generateNotSupportedWarning(AR.FillStyleNotSupported,t.patternType,MR)}(e?.fontStyle,e?.fillStyle,t),function(e,t){e&&!OR.includes(e)&&t.generateNotSupportedWarning(AR.HorizontalAlignmentNotSupported,e,OR)}(e?.alignment?.horizontal,t),function(e,t){e&&!FR.includes(e)&&t.generateNotSupportedWarning(AR.VerticalAlignmentNotSupported,e,FR)}(e?.alignment?.vertical,t),{bold:e.fontStyle?.bold,italic:e.fontStyle?.italic,strikethrough:e.fontStyle?.strike,underline:e.fontStyle?.underline,verticalAlign:e.alignment?.vertical?UR[e.alignment.vertical]:void 0,align:e.alignment?.horizontal?VR[e.alignment.horizontal]:void 0,fillColor:"solid"===e.fillStyle?.patternType?sx(e.fillStyle?.fgColor):sx(e.fillStyle?.bgColor),textColor:sx(e.fontStyle?.color),fontSize:e.fontStyle?.size,wrapping:e.alignment?.wrapText?"wrap":"overflow"}}function hx(e,t){const s=[];for(const o of e.styles){const i=nx(o.numFmtId,e.numFmts,t);i&&(s[o.numFmtId]=i)}return ER(s,1)}function dx(e,t,s){const o=[];let i=1;for(const n of e){if(0===n.cfRules.length)continue;fx(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=ux(i++,n);t&&o.push(t);continue;case"colorScale":const l=gx(i++,n);l&&o.push(l);continue;case"iconSet":const c=px(i++,n,s);c&&o.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;r=BR[e.type],a.push(e.text);break;case"expression":if(!e.formula?.length)continue;r=BR[e.type],a.push(`=${e.formula[0]}`);break;case"containsBlanks":case"notContainsBlanks":r=BR[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;r=zR[e.operator],a.push(TR(e.formula[0])),2===e.formula.length&&a.push(TR(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:cx({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},s)}})}}return o}function ux(e,t){const s=t.cfRules[0].dataBar;if(!s)return;const o=ox(sx(s.color)||"#FFFFFF");return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"DataBarRule",color:o}}}function gx(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:ox(sx(s.colors[e])||"#FFFFFF"),type:GR[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 px(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=GR[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?mx(n[0].iconSet,n[0].iconId):mx(o.iconSet,0),middle:n?mx(n[1].iconSet,n[1].iconId):mx(o.iconSet,1),upper:n?mx(n[2].iconSet,n[2].iconId):mx(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(AR.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=CR.dots.good;break;case"middle":a[e]=CR.dots.neutral;break;case"lower":a[e]=CR.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 mx(e,t){const s=WR[e];return s?0===t?CR[s].bad:1===t?CR[s].neutral:CR[s].good:""}function fx(e,t,s){if(e.cfRules.length>1&&s.generateNotSupportedWarning(AR.MultipleRulesCfNotSupported),NR.includes(e.cfRules[0].type)||s.generateNotSupportedWarning(AR.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const o=t[e.cfRules[0].dxfId];o.border&&s.generateNotSupportedWarning(AR.CfFormatBorderNotSupported),o.alignment&&s.generateNotSupportedWarning(AR.CfFormatAlignmentNotSupported),o.numFmt&&s.generateNotSupportedWarning(AR.CfFormatNumFmtNotSupported)}}function vx(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 bx(e){return Math.round(zS*e*100)/100}function Sx(e){return Math.round(BS*e*100)/100}function Cx(e){return e?Math.round(e/zS*100)/100:e}function yx(e){return e?Math.round(e/BS*100)/100:e}function Ix(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?HR[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 wx(e,t){const s=function(e,t){if(!e)return 0;let s=XR[e.format];s||(s=xx(e,t)+164);return s}(t.numFmt,e.numFmts),o={fontId:xx(t.font,e.fonts),fillId:xx(t.fill,e.fills),borderId:t.border,numFmtId:s,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal,wrapText:t.alignment.wrapText}};return xx(o,e.styles)}function Ex(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 Rx=new WeakMap;function xx(e,t){let s=Rx.get(t);if(!s){s=new Map;for(let e=0;e<t.length;e++){const o=gb(t[e]);s.set(o,e)}Rx.set(t,s)}const o=gb(e);if(s.has(o))return s.get(o);const i=t.length;return t.push(e),s.set(o,i),i}function Tx(e,t){const s=t.chartIds.findIndex(t=>t===e);return-1===s?(t.chartIds.push(e),t.chartIds.length):s+1}const Ax=[];function Dx(e){const t=Ax.findIndex(t=>t===e);return-1===t?(Ax.push(e),Ax.length):t+1}function _x(e){return Math.round(914400*e/96)}function Ox(e,t,s){let o,i,n=e;if(({xc:n,sheetName:o}=sr(e)),o){const e=s.sheets.findIndex(e=>Cb(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=Et(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 Fx(e){return Math.round(96*e/914400)}function Px(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+=GS}return s/BS}function Mx(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+=WS}return s/zS}function Nx(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}=Ux(e.anchors[0])),a=Fx(e.figureSize.cx),r=Fx(e.figureSize.cy);else{({col:o,row:i,offset:n}=Ux(e.anchors[0]));const{x:t,y:l}=Hx(e.anchors[0],s),{x:c,y:h}=Hx(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:Lx(e.data)};if(function(e){return"imageSrc"in e}(e.data))return{...l,width:Fx(e.data.size.cx),height:Fx(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 Lx(e){const t=e.dataSets.some(e=>"reference"in(e.label??{})),s=e.labelRange?kx(e.labelRange,t):void 0,o=e.dataSets.map(e=>{let s;return e.label&&"text"in e.label&&(s=e.label.text),{dataRange:kx(e.range,t),label:s,backgroundColor:e.backgroundColor,trend:Vx(e.trend)}});"pie"===e.type&&o.reverse();const i={range:o,dataSetsHaveTitle:t,auxiliaryRange:s,title:e.title??{text:""},background:sx({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 Ky.get(e.type).getChartDefinitionFromContextCreation(i)}catch(e){return}}function kx(e,t){const{sheetName:s,xc:o}=sr(e);let i=Et(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 or(s,Dt(i))}function Vx(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 Ux(e){const t={x:Fx(e.colOffset)-1,y:Fx(e.rowOffset)-1};return{col:e.col,row:e.row,offset:t}}function Hx(e,t){return{x:Px(e.col,t)+Fx(e.colOffset),y:Mx(e.row,t)+Fx(e.rowOffset)}}function zx(e,t){const s=[];let o=1;for(const i of e)if(i)switch(i.type){case"time":t.generateNotSupportedWarning(AR.TimeDataValidationNotSupported);break;case"textLength":t.generateNotSupportedWarning(AR.TextLengthDataValidationNotSupported);break;case"whole":t.generateNotSupportedWarning(AR.WholeNumberDataValidationNotSupported);break;case"decimal":const e=Bx(o++,i);s.push(e);break;case"list":const n=Gx(o++,i);s.push(n);break;case"date":if("notEqual"===i.operator){t.generateNotSupportedWarning(AR.NotEqualDateDataValidationNotSupported);break}const r=Wx(o++,i);s.push(r);break;case"custom":const a=$x(o++,i);s.push(a)}return s}function Bx(e,t){const s=[TR(t.formula1.toString())];return t.formula2&&s.push(TR(t.formula2.toString())),{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:ex[t.operator],values:s}}}function Gx(e,t){const s=t.formula1.toString(),o=Kn.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 Wx(e,t){let s;const o=[TR(t.formula1.toString())];return t.formula2?(o.push(TR(t.formula2.toString())),s={type:tx[t.operator],values:ab(o,Fc)}):s={type:tx[t.operator],values:ab(o,Fc),dateValue:"exactDate"},{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:s}}function $x(e,t){return{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:"customFormula",values:[TR(t.formula1.toString())]}}}const qx=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),Zx=new RegExp(/SUBTOTAL\(([0-9]*),/g),jx=new RegExp($n.source,"ig");function Yx(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:"="+Kx(o.xc,s[o.formula.sharedIndex]),o.formula.content=Xx(o.formula.content,t))}function Xx(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(Zx,(e,t)=>{const s=jR[t];return s?s+"(":e})).replace(qx,(e,s,o,i)=>{s=Number(s)-1,i=i.replace(/\$/g,"");const n=t.externalBooks[s].sheetNames.findIndex(e=>Cb(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 Kx(e,t){const s=pt(t.refCellXc);let o,i=t.formula.slice();do{if(o=jx.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 Jx(e,t){return e.sheets.map(s=>{Yx(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=oT(s,"ROW",o[1]),r=oT(s,"COL",o[0]);return{id:s.sheetName,areGridLinesVisible:!i||i.showGridLines,name:s.sheetName,colNumber:o[0],rowNumber:o[1],...tT(s,e,o,t),merges:s.merges,cols:Qx(s,o[0],r),rows:eT(s,o[1],n),conditionalFormats:dx(s.cfs,e.dxfs,t),dataValidationRules:zx(s.dataValidations,t),figures:Nx(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:sx(s.sheetProperties?.tabColor)}})}function Qx(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:GS;const r=i-1,a=s.some(e=>e.isFolded&&e.start<=r&&r<=e.end);o[r]={size:yx(n),isHidden:!a&&t?.hidden}}return o}function eT(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:WS;const r=i-1,a=s.some(e=>e.isFolded&&e.start<=r&&r<=e.end);o[r]={size:Cx(n),isHidden:!a&&t?.hidden}}return o}function tT(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]=sT(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 sT(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(AR.BadlyFormattedHyperlink);const i=e.relTarget?e.relTarget:Re(sr(e.location).sheetName);return ye(o,i)}(t[e.xc],i,o)),e.formula&&(i=e.formula.content),i}function oT(e,t,s){const o=e?.sheetProperties?.outlinePr,i=[];let n=0;for(let r=0;r<s;r++){const s=nT(e,t,r),a=s?.outlineLevel||0;if(a>n){const s=iT(e,t,r,("ROW"===t?o?.summaryBelow:o?.summaryRight)??!0);s&&i.push(s)}n=a}return i}function iT(e,t,s,o){const i=nT(e,t,s),n=i?.outlineLevel;if(!n||!n)return;let r=n,a=s,l=i;for(;l&&r>=n;)a++,l=nT(e,t,a),r=l?.outlineLevel||0;const c=s,h=a-1,d=nT(e,t,o?h+1:c-1);return{start:c-1,end:h-1,isFolded:d?.collapsed||!1}}function nT(e,t,s){return"COL"===t?e.cols.find(e=>e.min<=s&&s<=e.max):e.rows.find(e=>e.index===s)}function rT(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:aT(e)});for(const e of s.pivotTables)t.tables.push({range:e.location.ref,config:lT(e)})}}!function(e,t){let s=null;for(const o of e){const i=t.find(e=>Cb(e.sheetName,o.name)).tables;if(i&&0!==i.length){s||(s=cT(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=hT(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 aT(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:FE[t]?t:fE.styleId}}function lT(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:fE.styleId}}function cT(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 hT(e,t,s,o){const i=t.split(",").map(e=>e.trim()),n=Rt(s.ref),r=[],a=[],l=[];for(const e of i)if(dT(e).startsWith("#")){const t=dT(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 Ss.InvalidReference;a.push(n.top);break;case"#Totals":if(!s.totalsRowCount)return Ss.InvalidReference;a.push(n.bottom)}}else{const t=e.split(":").map(e=>e.trim()).map(dT);if(r.length)return Ss.InvalidReference;const o=s.cols.findIndex(e=>e.name===t[0]);if(-1===o)return Ss.InvalidReference;if(r.push(o+n.left),t[1]){const e=s.cols.findIndex(e=>e.name===t[1]);if(-1===e)return Ss.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 Ss.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+Dt({top:Math.min(...a),left:Math.min(...r),bottom:Math.max(...a),right:Math.max(...r)})}function dT(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,e.length-1):e}function uT(e,t,s){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:s}}function gT(e){return String(e).replace(/\&/g,"&").replace(/\</g,"<").replace(/\>/g,">").replace(/\"/g,""").replace(/\'/g,"'").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"")}function pT(e){return new rR(e.map(([e,t])=>`${e}="${gT(t)}"`).join(" "))}function mT(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 fT(e){if(e)return{style:e.style,color:{rgb:e.color}}}function vT(e,t){return ST`
|
|
2
|
+
<Override ContentType="${t}" PartName="${e}" />
|
|
3
|
+
`}function bT(e){return new rR(e.join("\n"))}function ST(e,...t){const s=[e[0]];for(let o=0;o<t.length;o++){const i=t[o]instanceof rR?t[o]:gT(t[o]);s.push(i+e[o+1])}return new rR(_e(s))}function CT(e){return e.replace(/NAMESPACE.*NAMESPACE(.*)/,"$1")}function yT(e){return e.replaceAll(/(<\/?)([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,"$1NAMESPACE$2NAMESPACE$3")}function IT(e){return e.replaceAll(/([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,"NAMESPACE$1NAMESPACE$2")}class wT{value;constructor(e){this.value=e}asString(){return RR(String(this.value))}asBool(){return"true"===this.value||"false"!==this.value&&Boolean(Number(this.value))}asNum(){return Number(this.value)}}class ET{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 wT(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?RR(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 wT(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=IT(t);return e.querySelector(s)}querySelectorAll(e,t){const s=IT(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 RT extends ET{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:gS}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:gS}).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 xT extends ET{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 TT extends ET{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 AT extends ET{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},e=>{const t=this.getChartType(e);if(!qR[t])throw new Error(`Unsupported chart type ${t}`);if("combo"===qR[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:qR[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:$R[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:$R[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&&Iv(n)?`${yv(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&&Iv(o.asString())?`${yv(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&&Iv(o)?`${yv(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=CT(e.tagName);aR.some(e=>e===t)&&(s?s!==t&&(s="comboChart"):s=t)}if(s)return s;throw new Error("Unknown chart type")}}const DT="oneCellAnchor",_T="twoCellAnchor";class OT extends ET{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},e=>{const t=CT(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===DT?this.extractFigureSizeFromSizeTag(e,"xdr:ext"):void 0}})}extractFigureAnchorsByType(e,t){switch(t){case DT:return[this.extractFigureAnchor("xdr:from",e)];case _T: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 AT(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=CT(e.tagName),r=n===_T?this.querySelector(e,"a:xfrm"):e,a=n===_T?"a:ext":"xdr:ext",l=this.extractFigureSizeFromSizeTag(r,a);return{imageSrc:o.imageSrc,mimetype:i?QR[i]:void 0,size:l}}}class FT extends ET{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 PT extends ET{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 MT extends ET{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=wR(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=wR(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 xT(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractDataValidations(){return new TT(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 OT(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 PT(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 FT(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:GS.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:WS.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=Rt(o.ref);for(const{col:o,row:i}of Gt(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:LR[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 NT extends ET{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 LT extends ET{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 kT(e,t){const s=function(e,t){const s=t[ZS],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=VT(o,t);s.push({file:{fileName:o,xml:t[o]},rels:e?{fileName:e,xml:t[e]}:void 0})}return s}(s,t)}function VT(e,t){if(e===ZS)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 UT{warningManager;xmls;images;constructor(e){this.warningManager=new DR,this.xmls={},this.images=[];for(const t of Object.keys(e))if(t.endsWith(".xml")||t.endsWith(".rels")){const s=yT(e[t]);this.xmls[t]=mT(new rR(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 RT(e.theme,e,this.warningManager).getTheme():void 0,s=e.sharedStrings?new RT(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 MT(s,e,this.warningManager,t).getSheet()),i=e.externalLinks.map(t=>new LT(t,e,this.warningManager).getExternalBook()),n=new NT(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:kT(AS.sheet,this.xmls),workbook:kT(AS.workbook,this.xmls)[0]||kT(AS.macroEnabledWorkbook,this.xmls)[0]||kT(AS.templateWorkbook,this.xmls)[0]||kT(AS.macroEnabledTemplateWorkbook,this.xmls)[0]||kT(AS.excelAddInWorkbook,this.xmls)[0],styles:kT(AS.styles,this.xmls)[0],sharedStrings:kT(AS.sharedStrings,this.xmls)[0],theme:kT(AS.themes,this.xmls)[0],charts:kT(AS.chart,this.xmls),figures:kT(AS.drawing,this.xmls),tables:kT(AS.table,this.xmls),pivots:kT(AS.pivot,this.xmls),externalLinks:kT(AS.externalLink,this.xmls),images:this.images};if(!e.workbook.rels)throw Error(vs("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:"18.4.2",sheets:Jx(e,this.warningManager),styles:lx(e,this.warningManager),formats:hx(e,this.warningManager),borders:rx(e,this.warningManager),revisionId:H};return rT(t,e),Object.keys(e.styles).map(t=>{e.styles[t]=Ve(e.styles[t])}),t}}function HT(e){const t=If(e),s=[];return{text:"".concat(...t.map(e=>{if("REFERENCE"===e.type&&$n.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 zT={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},BT=new ns;function GT(e){for(const t of e.sheets||[]){const e=[];for(const s of t.filterTables||[]){const t=Rt(s.range),o=e.findIndex(e=>Vt(e,t));-1!==o?e[o]=t:e.push(t)}t.filterTables=e.map(e=>({range:Dt(e)}))}return e}function WT(){return $T().at(-1)}function $T(){return BT.getKeys().sort(YT)}BT.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=HT(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=Rt(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=hb(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=>GT(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=Fc),e)}).add("16.4.1",{migrate:e=>GT(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=Qg(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=zT[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={...fE,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 qT="Sheet1";function ZT(e,t){if(!e)return QT();console.debug("### Loading data ###");const s=performance.now();if(e["[Content_Types].xml"]){const s=new UT(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=jT[e.version]),e.version!==WT()&&(console.debug("Migrating data from version",e.version),e=function(e){const t=performance.now(),s=$T();for(let t=s.findIndex(t=>t===e.version)+1;t<s.length;t++){const o=s[t];e=BT.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 Set,o=new cr;for(const i of e.sheets||[])for(const e of i.figures||[])t.has(e.id)&&(e.id+=o.smallUuid()),t.add(e.id),"chart"===e.tag&&(s.has(e.data?.chartId)&&(e.data.chartId+=o.smallUuid()),s.add(e.data?.chartId));return e.uniqueFigureIds=!0,e}(e),e=function(e){const t=Object.assign(QT(),e,{version:WT()});t.sheets=t.sheets?t.sheets.map((e,t)=>Object.assign(JT(`Sheet${t+1}`,`Sheet${t+1}`),e)):[],0===t.sheets.length&&t.sheets.push(JT(qT,"Sheet1"));Kc(t.settings.locale)||(t.settings.locale=Fc);return t}(e),e}(e),console.debug("Data loaded in",performance.now()-s,"ms"),console.debug("###"),e}const jT={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.5:"16.4.1",14:"16.4",13:"16.3",12.5:"15.4.1",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 YT(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 XT(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:qT};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=KT(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&&YT(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=KT(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??Sb(s[o.sheetId],Object.values(s));break;case"CREATE_SHEET":s[o.sheetId]=o.name||bb(Object.values(s));break;case"RENAME_SHEET":s[o.sheetId]=o.newName||bb(Object.values(s))}t.push(o)}o.push({...e,commands:t})}else o.push(e);return t}(e,t),t}function KT(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 JT(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 QT(e="Sheet1"){return{version:WT(),sheets:[JT(qT,e)],styles:{},formats:{},borders:{},revisionId:H,uniqueFigureIds:!0,settings:{locale:Fc},pivots:{},pivotNextId:1,customTableStyles:{}}}function eA(e,t){return{...JT(e,t),charts:[],images:[],cellValues:{}}}class tA{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 sA extends Ir{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){}}class oA{id;format;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,s,o,i,n){this.id=e,this.format=s,this.sheetId=i,this.getRangeString=n;let r=0;const a=t.tokens.map(e=>{if("REFERENCE"===e.type){const e=r++;return new iA(o,e,this.sheetId,this.getRangeString)}return e});this.compiledFormula={...t,dependencies:o,tokens:a}}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 iA{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 nA=new Fg;nA.add("containsText",{type:"containsText",isValueValid:(e,t)=>String(e).toLowerCase().includes(String(t.values[0]).toLowerCase()),getErrorString:e=>vs('The value must be a text that contains "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Dg.CriterionError.notEmptyValue,numberOfValues:()=>1,name:vs("Text contains"),getPreview:e=>vs('Text contains "%s"',e.values[0])}),nA.add("notContainsText",{type:"notContainsText",isValueValid:(e,t)=>!String(e).toLowerCase().includes(String(t.values[0]).toLowerCase()),getErrorString:e=>vs('The value must be a text that does not contain "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Dg.CriterionError.notEmptyValue,numberOfValues:()=>1,name:vs("Text does not contain"),getPreview:e=>vs('Text does not contain "%s"',e.values[0])}),nA.add("isEqualText",{type:"isEqualText",isValueValid:(e,t)=>String(e).toLowerCase()===String(t.values[0]).toLowerCase(),getErrorString:e=>vs('The value must be exactly "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Dg.CriterionError.notEmptyValue,numberOfValues:()=>1,name:vs("Text is exactly"),getPreview:e=>vs('Text is exactly "%s"',e.values[0])});const rA=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/;function aA(e,t){return e.values.map(e=>void 0!==e?eh(String(e),t):Ss.InvalidReference)}function lA(e,t){return rb(e,Fc).map(e=>void 0!==e?mn(e,{locale:t,format:t.dateFormat}):Ss.InvalidReference)}function cA(e){return void 0!==$s(e,Fc)}function hA(e){return void 0!==Co(e,Fc)}function dA(e){return""===e?NaN:Number(e)}nA.add("isEmail",{type:"isEmail",isValueValid:(e,t)=>"string"==typeof e&&rA.test(e),getErrorString:()=>vs("The value must be a valid email address"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:vs("Text is valid email"),getPreview:()=>vs("Text is valid email")}),nA.add("isLink",{type:"isLink",isValueValid:(e,t)=>void 0!==jf(e),getErrorString:()=>vs("The value must be a valid link"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:vs("Text is valid link"),getPreview:()=>vs("Text is valid link")}),nA.add("dateIs",{type:"dateIs",isValueValid:(e,t)=>{const s=rb(t,Fc)[0],o=$s(e,Fc);if(void 0===o||void 0===s)return!1;if(["lastWeek","lastMonth","lastYear"].includes(t.dateValue)){return ro(o,Xs(Fs.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?vs("The value must be the date %s",lA(e,s)[0]):vs("The value must be %s",Dg.DateIs[e.dateValue])},isCriterionValueValid:e=>cA(e),criterionValueErrorString:Dg.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:vs("Date is"),getPreview:(e,t)=>"exactDate"===e.dateValue?vs("Date is %s",ab(e.values,t.getLocale())[0]):vs("Date is %s",Dg.DateIs[e.dateValue])}),nA.add("dateIsBefore",{type:"dateIsBefore",isValueValid:(e,t)=>{const s=rb(t,Fc)[0],o=$s(e,Fc);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?vs("The value must be a date before %s",lA(e,s)[0]):vs("The value must be a date before %s",Dg.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>cA(e),criterionValueErrorString:Dg.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:vs("Date is before"),getPreview:(e,t)=>"exactDate"===e.dateValue?vs("Date is before %s",ab(e.values,t.getLocale())[0]):vs("Date is before %s",Dg.DateIsBefore[e.dateValue])}),nA.add("dateIsOnOrBefore",{type:"dateIsOnOrBefore",isValueValid:(e,t)=>{const s=rb(t,Fc)[0],o=$s(e,Fc);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?vs("The value must be a date on or before %s",lA(e,s)[0]):vs("The value must be a date on or before %s",Dg.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>cA(e),criterionValueErrorString:Dg.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:vs("Date is on or before"),getPreview:(e,t)=>"exactDate"===e.dateValue?vs("Date is on or before %s",ab(e.values,t.getLocale())[0]):vs("Date is on or before %s",Dg.DateIsBefore[e.dateValue])}),nA.add("dateIsAfter",{type:"dateIsAfter",isValueValid:(e,t)=>{const s=rb(t,Fc)[0],o=$s(e,Fc);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?vs("The value must be a date after %s",lA(e,s)[0]):vs("The value must be a date after %s",Dg.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>cA(e),criterionValueErrorString:Dg.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:vs("Date is after"),getPreview:(e,t)=>"exactDate"===e.dateValue?vs("Date is after %s",ab(e.values,t.getLocale())[0]):vs("Date is after %s",Dg.DateIsBefore[e.dateValue])}),nA.add("dateIsOnOrAfter",{type:"dateIsOnOrAfter",isValueValid:(e,t)=>{const s=rb(t,Fc)[0],o=$s(e,Fc);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?vs("The value must be a date on or after %s",lA(e,s)[0]):vs("The value must be a date on or after %s",Dg.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>cA(e),criterionValueErrorString:Dg.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:vs("Date is on or after"),getPreview:(e,t)=>"exactDate"===e.dateValue?vs("Date is on or after %s",ab(e.values,t.getLocale())[0]):vs("Date is on or after %s",Dg.DateIsBefore[e.dateValue])}),nA.add("dateIsBetween",{type:"dateIsBetween",isValueValid:(e,t)=>{const s=rb(t,Fc),o=$s(e,Fc);return void 0!==o&&void 0!==s[0]&&void 0!==s[1]&&ro(o,s[0],s[1])},getErrorString:(e,t)=>{const s=lA(e,t.getLocale());return vs("The value must be a date between %s and %s",s[0],s[1])},isCriterionValueValid:e=>cA(e),criterionValueErrorString:Dg.CriterionError.dateValue,numberOfValues:()=>2,name:vs("Date is between"),getPreview:(e,t)=>{const s=ab(e.values,t.getLocale());return vs("Date is between %s and %s",s[0],s[1])}}),nA.add("dateIsNotBetween",{type:"dateIsNotBetween",isValueValid:(e,t)=>{const s=rb(t,Fc),o=$s(e,Fc);return void 0!==o&&void 0!==s[0]&&void 0!==s[1]&&!ro(o,s[0],s[1])},getErrorString:(e,t)=>{const s=lA(e,t.getLocale());return vs("The value must be a date not between %s and %s",s[0],s[1])},isCriterionValueValid:e=>cA(e),criterionValueErrorString:Dg.CriterionError.dateValue,numberOfValues:()=>2,name:vs("Date is not between"),getPreview:(e,t)=>{const s=ab(e.values,t.getLocale());return vs("Date is not between %s and %s",s[0],s[1])}}),nA.add("dateIsValid",{type:"dateIsValid",isValueValid:(e,t)=>void 0!==$s(e,Fc),getErrorString:()=>vs("The value must be a valid date"),isCriterionValueValid:e=>cA(e),criterionValueErrorString:"",numberOfValues:()=>0,name:vs("Is valid date"),getPreview:()=>vs("Date is valid")}),nA.add("isEqual",{type:"isEqual",isValueValid:(e,t)=>e===t.values[0],getErrorString:(e,t)=>{const s=aA(e,t.getLocale());return vs("The value must be equal to %s",s[0])},isCriterionValueValid:e=>hA(e),criterionValueErrorString:Dg.CriterionError.numberValue,numberOfValues:()=>1,name:vs("Is equal to"),getPreview:e=>vs("Value is equal to %s",e.values[0])}),nA.add("isNotEqual",{type:"isNotEqual",isValueValid:(e,t)=>e!==t.values[0],getErrorString:(e,t)=>{const s=aA(e,t.getLocale());return vs("The value must not be equal to %s",s[0])},isCriterionValueValid:e=>hA(e),criterionValueErrorString:Dg.CriterionError.numberValue,numberOfValues:()=>1,name:vs("Is not equal to"),getPreview:e=>vs("Value is not equal to %s",e.values[0])}),nA.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=aA(e,t.getLocale());return vs("The value must be greater than %s",s[0])},isCriterionValueValid:e=>hA(e),criterionValueErrorString:Dg.CriterionError.numberValue,numberOfValues:()=>1,name:vs("Is greater than"),getPreview:e=>vs("Value is greater than %s",e.values[0])}),nA.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=aA(e,t.getLocale());return vs("The value must be greater or equal to %s",s[0])},isCriterionValueValid:e=>hA(e),criterionValueErrorString:Dg.CriterionError.numberValue,numberOfValues:()=>1,name:vs("Is greater or equal to"),getPreview:e=>vs("Value is greater or equal to %s",e.values[0])}),nA.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=aA(e,t.getLocale());return vs("The value must be less than %s",s[0])},isCriterionValueValid:e=>hA(e),criterionValueErrorString:Dg.CriterionError.numberValue,numberOfValues:()=>1,name:vs("Is less than"),getPreview:e=>vs("Value is less than %s",e.values[0])}),nA.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=aA(e,t.getLocale());return vs("The value must be less or equal to %s",s[0])},isCriterionValueValid:e=>hA(e),criterionValueErrorString:Dg.CriterionError.numberValue,numberOfValues:()=>1,name:vs("Is less or equal to"),getPreview:e=>vs("Value is less or equal to %s",e.values[0])}),nA.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=aA(e,t.getLocale());return vs("The value must be between %s and %s",s[0],s[1])},isCriterionValueValid:e=>hA(e),criterionValueErrorString:Dg.CriterionError.numberValue,numberOfValues:()=>2,name:vs("Is between"),getPreview:e=>vs("Value is between %s and %s",e.values[0],e.values[1])}),nA.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=aA(e,t.getLocale());return vs("The value must not be between %s and %s",s[0],s[1])},isCriterionValueValid:e=>hA(e),criterionValueErrorString:Dg.CriterionError.numberValue,numberOfValues:()=>2,name:vs("Is not between"),getPreview:e=>vs("Value is not between %s and %s",e.values[0],e.values[1])}),nA.add("isBoolean",{type:"isBoolean",isValueValid:(e,t)=>""===e||"boolean"==typeof e,getErrorString:()=>vs("The value must be a boolean"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:vs("Checkbox"),getPreview:()=>vs("Checkbox")}),nA.add("isValueInList",{type:"isValueInList",isValueValid:(e,t)=>null!==e&&t.values.map(e=>String(e).toLowerCase()).includes(e.toString().toLowerCase()),getErrorString:e=>vs("The value must be one of: %s",e.values.join(", ")),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>{},allowedValues:"onlyLiterals",name:vs("Value in list"),getPreview:e=>vs("Value one of: %s",e.values.join(", "))}),nA.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=>vs("The value must be a value in the range %s",String(e.values[0])),isCriterionValueValid:e=>Kn.test(e),criterionValueErrorString:Dg.CriterionError.validRange,numberOfValues:()=>1,allowedValues:"onlyLiterals",name:vs("Value in range"),getPreview:e=>vs("Value in range %s",e.values[0])}),nA.add("customFormula",{type:"customFormula",isValueValid:(e,t)=>{const s=t.values[0];return("number"==typeof s||"boolean"==typeof s)&&!!s},getErrorString:()=>vs("The value does not match the custom formula data validation rule"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>1,allowedValues:"onlyFormulas",name:vs("Custom formula"),getPreview:e=>vs("Custom formula %s",e.values[0])}),nA.add("beginsWithText",{type:"beginsWithText",isValueValid:(e,t)=>String(e).toLowerCase().startsWith(String(t.values[0]).toLowerCase()),getErrorString:e=>vs('The value must be a text that begins with "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Dg.CriterionError.notEmptyValue,numberOfValues:()=>1,name:vs("Text begins with"),getPreview:e=>vs('Text begins with "%s"',e.values[0])}),nA.add("endsWithText",{type:"endsWithText",isValueValid:(e,t)=>String(e).toLowerCase().endsWith(String(t.values[0]).toLowerCase()),getErrorString:e=>vs('The value must be a text that ends with "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Dg.CriterionError.notEmptyValue,numberOfValues:()=>1,name:vs("Text ends with"),getPreview:e=>vs('Text ends with "%s"',e.values[0])}),nA.add("isEmpty",{type:"isEmpty",isValueValid:(e,t)=>""===(e??"").toString().trim(),getErrorString:()=>vs("The value must be empty"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:vs("Is empty"),getPreview:()=>vs("Is empty")}),nA.add("isNotEmpty",{type:"isNotEmpty",isValueValid:(e,t)=>""!==(e??"").toString().trim(),getErrorString:()=>vs("The value must not be empty"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:vs("Is not empty"),getPreview:()=>vs("Is not empty")});function uA(e){return Object.entries(e).map(([e,t])=>t?gA(parseInt(e,10),t):void 0).filter(Te).map(e=>mt(e.left,e.top)+":"+mt(e.right,e.bottom))}function gA(e,t){return{...t.zone,id:e}}function pA(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 mA(e,t,s){return"column"===t?pA(e,s).colDomain:pA(e,s).rowDomain}function fA(e,t){return void 0!==vA(e,t)}function vA(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 bA(e,t,s){const o=(e=ae(e)).find(e=>e.field===t);return o?(o.value=s,e):e}function SA(e,t){return t.some(t=>t.field===e)}function CA(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 yA(e){return e?e.map(IA).join(", "):""}function IA(e){return e?`${e.field}=${e.value}`:""}function wA(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 yA(i.field===t?o:[...o,i])}function EA(e,t){const s=e.findIndex(e=>e.field===t);return-1===s?"":yA([...e.slice(0,s),...e.slice(s+1)])}function RA(e,t,s){const o=[...e],i=[...t];o.sort((e,t)=>s([...i,e],[...i,t]));for(const t of e){const e=RA(t.children,[...i,t],s);t.children=e}return o}function xA(e,t){return e.length>t.length&&t.every((t,s)=>Me(t,e[s]))}class TA{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=>xA(this.getDomain(e),i)),a=n.findLastIndex(e=>xA(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=>xA(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=Zg){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 AA;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"}:AA}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 AA;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:ap({displayName:"measure",type:"char"},e.values[s])};{const{fieldName:o,granularity:i}=sp(t),n=this.fieldsType[o]||"char";return{type:n,field:t,value:ap({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}=sp(n),l=ap({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}=sp(o),r=ap({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=RA(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 AA={type:"EMPTY"};function DA(e,t){if(!e)return;const s=t(e);switch(s.changeType){case"NONE":return e;case"REMOVE":return;default:return s.range}}const _A={verticalAlign:"bottom",wrapping:"overflow",bold:!1,italic:!1,strikethrough:!1,underline:!1,fontSize:10,fillColor:"",textColor:""};const OA=["wholeTable","firstColumnStripe","secondColumnStripe","firstRowStripe","secondRowStripe","firstColumn","lastColumn","headerRow","totalRow"];function FA(e){const t=e.range;return{row:t.zone.top,col:t.zone.left,sheetId:t.sheetId}}function PA(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 MA(e){return"static"===e.type||"forceStatic"===e.type}function NA(e,t,s,o){return{borders:LA(e,t,s,o),styles:VA(e,t,s,o)}}function LA(e,t,s,o){const i=Vo(s,o,()=>({}));for(const n of OA){const r=t[n]?.border;if(!r)continue;const a=HA(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?kA(i,"top",r.top,a,l,s,o):l!==t.top&&!c&&r?.horizontal&&kA(i,"top",r.horizontal,a,l,s,o),l===t.bottom&&r?.bottom&&kA(i,"bottom",r.bottom,a,l,s,o),a===t.left&&r?.left&&kA(i,"left",r.left,a,l,s,o),a===t.right&&r?.right?kA(i,"right",r.right,a,l,s,o):a!==t.right&&!c&&r?.vertical&&kA(i,"right",r.vertical,a,l,s,o)}}return i}function kA(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 VA(e,t,s,o){const i=Vo(s,o,()=>({}));for(const n of OA){const r=t[n],a=UA(n);if(!r&&!a)continue;const l=HA(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 UA(e){return"firstColumn"===e||"lastColumn"===e||"headerRow"===e||"totalRow"===e}function HA(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 zA extends Ir{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}}const BA=mf.mapping;function GA(e,t,s){return new WA(e,t,s).getParameters()}class WA{getters;computeCell;evalContext;rangeCache={};constructor(e,t,s){this.getters=t,this.computeCell=s,this.evalContext=Object.assign(Object.create(BA),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:or(this.getters.getSheetName(e.sheetId),Dt(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=Nt(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:or(p,mt(e,i))}:a}}return this.rangeCache[h]=g,g}getRangeError(e){return Tt(e.zone)?e.invalidSheetName?new Es(vs("Invalid sheet name: %s",e.invalidSheetName)):void 0:new Es}}function $A(e,t,s,o,i){qA(e,t,s||0,o||e.length-1,i||jA)}function qA(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);qA(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(ZA(e,s,t),i(e[o],h)>0&&ZA(e,s,o);d<u;){for(ZA(e,d,u),d++,u--;i(e[d],h)<0;)d++;for(;i(e[u],h)>0;)u--}0===i(e[s],h)?ZA(e,s,u):ZA(e,++u,o),u<=t&&(s=u+1),t<=u&&(o=u-1)}}function ZA(e,t,s){var o=e[t];e[t]=e[s],e[s]=o}function jA(e,t){return e<t?-1:e>t?1:0}class YA{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(!aD(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;aD(e,a)&&(t.leaf?s.push(r):rD(e,a)?this._all(r,s):i.push(r))}t=i.pop()}return s}collides(e){let t=this.data;if(!aD(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(aD(e,n)){if(t.leaf||rD(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=lD([]),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=XA(e,s.children,t);if(-1!==o)return s.children.splice(o,1),i.push(s),this._condense(i),this}l||s.leaf||!rD(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=lD(e.slice(t,s+1)),KA(n,this.toBBox),n;o||(o=Math.ceil(Math.log(i)/Math.log(r)),r=Math.ceil(i/Math.pow(r,o-1))),n=lD([]),n.leaf=!1,n.height=o;const a=Math.ceil(i/r),l=a*Math.ceil(Math.sqrt(r));cD(e,t,s,l,this.compareMinX);for(let i=t;i<=s;i+=l){const t=Math.min(i+l-1,s);cD(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 KA(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=sD(r),l=iD(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=lD(s.children.splice(n,s.children.length-n));r.height=s.height,r.leaf=s.leaf,KA(s,this.toBBox),KA(r,this.toBBox),t?e[t-1].children.push(r):this._splitRoot(s,r)}_splitRoot(e,t){this.data=lD([e,t]),this.data.height=e.height+1,this.data.leaf=!1,KA(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=JA(e,0,r,this.toBBox),a=JA(e,r,s,this.toBBox),l=nD(t,a),c=sD(t)+sD(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:eD,i=e.leaf?this.compareMinY:tD;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=JA(e,0,t,i),r=JA(e,s-t,s,i);let a=oD(n)+oD(r);for(let o=t;o<s-t;o++){const t=e.children[o];QA(n,e.leaf?i(t):t),a+=oD(n)}for(let o=s-t-1;o>=t;o--){const t=e.children[o];QA(r,e.leaf?i(t):t),a+=oD(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():KA(e[s],this.toBBox)}}function XA(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 KA(e,t){JA(e,0,e.children.length,t,e)}function JA(e,t,s,o,i){i||(i=lD(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 eD(e,t){return e.minX-t.minX}function tD(e,t){return e.minY-t.minY}function sD(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function oD(e){return e.maxX-e.minX+(e.maxY-e.minY)}function iD(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 nD(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 rD(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function aD(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function lD(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function cD(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;$A(e,r,t,s,i),n.push(t,r,r,s)}}class hD{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 dD,this.rTrees[e].load(t[e])}insert(e){const t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new dD),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 dD extends YA{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 uD{profilesStartingPosition=[0];profiles=new Map([[0,[]]]);constructor(e=[]){for(const t of e)this.add(t)}isEmpty(){return 1===this.profiles.size&&0===this.profiles.get(0)?.length}add(e){vt(this.profilesStartingPosition,this.profiles,[e])}delete(e){vt(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return function(e,t,s){const o=s.left,i=s.right,n=s.top,r=s.bottom+1,a=It(e,o,0),l=It(e,i,a);if(-1===a||-1===l)return!1;for(let s=a;s<=l;s++){const o=t.get(e[s]),i=It(o,n,0,!0),a=wt(o,r,0,!0);if(-1===i||i%2!=0)return!1;if(n<o[i]||r>o[a])return!1}return!0}(this.profilesStartingPosition,this.profiles,e)}difference(e){const t=this.copy();for(const s of e)t.delete(s);return t}copy(){const e=new uD;e.profilesStartingPosition=[...this.profilesStartingPosition],e.profiles=new Map;for(const[t,s]of this.profiles)e.profiles.set(t,[...s]);return e}size(){let e=0;for(const t of this.profiles.values())e+=t.length;return e/2}[Symbol.iterator](){return yt(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}}class gD{setsBySheetId={};constructor(e=[]){for(const t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new uD),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(const t of e)this.add(t)}addPosition(e){this.add(_b(e))}addManyPositions(e){for(const t of e)this.addPosition(t)}has(e){return!!this.setsBySheetId[e.sheetId]&&this.setsBySheetId[e.sheetId].has(e.zone)}hasPosition(e){return this.has(_b(e))}delete(e){this.setsBySheetId[e.sheetId]&&this.setsBySheetId[e.sheetId].delete(e.zone)}deleteMany(e){for(const t of e)this.delete(t)}deleteManyPositions(e){for(const t of e)this.delete(_b(t))}difference(e){const t=new gD;for(const e in this.setsBySheetId)t.setsBySheetId[e]=this.setsBySheetId[e];for(const s in e.setsBySheetId)t.setsBySheetId[s]&&(t.setsBySheetId[s]=t.setsBySheetId[s].difference(e.setsBySheetId[s]));return t}copy(){const e=new gD;for(const t in this.setsBySheetId)e.setsBySheetId[t]=this.setsBySheetId[t].copy();return e}clear(){this.setsBySheetId={}}size(){let e=0;for(const t in this.setsBySheetId)e+=this.setsBySheetId[t].size();return e}isEmpty(){for(const e in this.setsBySheetId)if(!this.setsBySheetId[e].isEmpty())return!1;return!0}[Symbol.iterator](){const e=[];for(const t in this.setsBySheetId)for(const s of this.setsBySheetId[t])e.push({sheetId:t,zone:s});return e[Symbol.iterator]()}}class pD{rTree;constructor(e=[]){const t=function(e){let t=0,s=0;for(let o=0;o<e.length;o++){const i=e[o].boundingBox.zone;i.right>t&&(t=i.right),i.bottom>s&&(s=i.bottom)}t+=1,s+=1;const o=(((s+1)*t+1)*s+1)*t<=Number.MAX_SAFE_INTEGER;o||console.warn("Max col/row size exceeded, using slow zone key");const i={};for(const n of e){const e=n.boundingBox.sheetId;i[e]||(i[e]={});const r=n.boundingBox.zone;let a=0;if(a=o?r.left+r.top*t+r.right*t*s+r.bottom*t*s*t:`${r.left},${r.top},${r.right},${r.bottom}`,i[e][a]){i[e][a].data.add(n.data)}else i[e][a]={boundingBox:n.boundingBox,data:new gD([n.data])}}const n=[];for(const e in i){const t=i[e];for(const e in t)n.push(t[e])}return n}(e);this.rTree=new hD(t)}insert(e){const t=this.rTree.search(e.boundingBox),s=e.boundingBox,o=t.find(({boundingBox:e})=>e.sheetId===s.sheetId&&e.zone.left===s.zone.left&&e.zone.top===s.zone.top&&e.zone.right===s.zone.right&&e.zone.bottom===s.zone.bottom);o?o.data.add(e.data):this.rTree.insert({...e,data:new gD([e.data])})}search({zone:e,sheetId:t}){const s=new gD;for(const{data:o}of this.rTree.search({zone:e,sheetId:t}))s.addMany(o);return s}remove(e){const t=this.rTree.search(e.boundingBox),s=e.boundingBox,o=t.find(({boundingBox:e})=>e.sheetId===s.sheetId&&e.zone.left===s.zone.left&&e.zone.top===s.zone.top&&e.zone.right===s.zone.right&&e.zone.bottom===s.zone.bottom);o?o.data.delete(e.data):this.rTree.remove({...e,data:new gD([e.data])})}}class mD{dependencies=new tA;rTree;constructor(e=[]){this.rTree=new pD(e)}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:{sheetId:e.sheetId,zone:jt(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=new gD){t=t.copy();const s=Array.from(e).reverse();for(;s.length>0;){const e=s.pop();t.add(e);const o=this.rTree.search(e);s.push(...o.difference(t))}for(const s of e)t.delete(s);return t}}class fD 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 vD{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]=fD.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 bD{resultsToArrayFormulas=new hD;arrayFormulasToResults=new tA;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||SD}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:jt(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 SD=[],CD=new Fg;CD.add("pivots",e=>{for(const t of e.getPivotIds()){const s=e.getPivot(t);s.markAsDirtyForEvaluation?.()}});const yD=Object.freeze(eb({...new ws,origin:void 0})),ID=Object.freeze(eb({value:null}));class wD{context;getters;compilationParams;evaluatedCells=new tA;formulaDependencies=Oe(new mD);blockedArrayFormulas=new vD({});spreadingRelations=new bD;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=GA(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||ID}getSpreadZone(e,t={ignoreSpillError:!1}){const s=this.spreadingRelations.getArrayResultZone(e);if(!s)return;const o=this.evaluatedCells.get(e);return o?.type!==Od.error||t.ignoreSpillError&&o?.value===Ss.SpilledBlocked?Mt(jt(e),s):jt(e)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type===Od.empty)return;return this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,jt(e)).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=GA(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 vD(e)}evaluateCells(e){const t=performance.now(),s=new gD;s.addManyPositions(e);const o=this.getArrayFormulasImpactedByChangesOf(e);s.addMany(this.getCellsDependingOn(s)),s.addMany(o),s.addMany(this.getCellsDependingOn(o)),this.evaluate(s),console.debug("evaluate Cells",performance.now()-t,"ms")}getArrayFormulasImpactedByChangesOf(e){const t=new gD;for(const s of e){const e=this.getters.getCell(s)?.content,o=this.getArrayFormulaSpreadingOn(s);void 0!==o&&t.addPosition(o),e||t.addPosition(s)}for(const e of[...t])t.addMany(this.getArrayFormulasBlockedBy(e.sheetId,e.zone));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new bD,this.formulaDependencies=Oe(()=>{const e=[];for(const t of this.getters.getSheetIds()){const s=this.getters.getCells(t);for(const o in s){const i=s[o];if(i.isFormula){const s=i.compiledFormula.dependencies;for(const i of s)i.invalidSheetName||i.invalidXc||e.push({data:{sheetId:t,zone:jt(this.getters.getCellPosition(o))},boundingBox:{sheetId:i.sheetId,zone:i.zone}})}}}return new mD(e)})}evaluateAllCells(){const e=performance.now();this.evaluatedCells=new tA;const t=[];for(const e of this.getters.getSheetIds()){const s=this.getters.getSheetZone(e);t.push({sheetId:e,zone:s})}this.evaluate(t),console.debug("evaluate all cells",performance.now()-e,"ms")}evaluateFormulaResult(e,t){const s=lE(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=xD(t,this.compilationParams,e,this.buildSafeGetSymbolValue(s),this.compilationParams.evalContext.__originCellPosition);return _s(o)?Uo(o,RD):RD(o)}catch(e){return oi(e,"")}}getArrayFormulasBlockedBy(e,t){const s=new gD,o=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);s.addManyPositions(o);const i=[...o].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&s.deleteManyPositions(i),s.addMany(this.getCellsDependingOn(s)),s}nextRangesToUpdate=new gD;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new gD(e);let t=0;for(;!this.nextRangesToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();const e=[...this.nextRangesToUpdate];this.nextRangesToUpdate.clear(),this.clearEvaluatedRanges(e);for(const t of e){const{left:e,bottom:s,right:o,top:i}=t.zone;for(let n=e;n<=o;n++)for(let e=i;e<=s;e++){const s={sheetId:t.sheetId,col:n,row:e};if(this.nextRangesToUpdate.hasPosition(s))continue;const o=this.computeCell(s);o!==ID&&this.evaluatedCells.set(s,o)}}CD.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn("Maximum iteration reached while evaluating cells")}clearEvaluatedRanges(e){for(const t of e){const{left:e,bottom:s,right:o,top:i}=t.zone;for(let n=e;n<=o;n++)for(let e=i;e<=s;e++)this.evaluatedCells.delete({sheetId:t.sheetId,col:n,row:e})}}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 ID;const o=s.id,i={format:s.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(o)?yD:(this.cellsBeingComputed.add(o),s.isFormula?this.computeFormulaCell(e,s):Jv(s,i,e))}catch(t){return t.value=t?.value||Ss.GenericError,t.message=t?.message||ni,t.origin=e,eb(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=xD(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!_s(s)){const o=eb(RD(s),this.getters.getLocale(),t,e);return o.type===Od.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),ED(o,i,this.checkCollision(e)),ED(o,i,this.spreadValues(e,s)),this.invalidatePositionsDependingOnSpread(e.sheetId,n),eb(RD(s[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){const s=this.getCellsDependingOn(function(e){const{top:t,left:s,bottom:o,right:i}=e;if(1===Jt(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})));s.delete({sheetId:e,zone:t}),this.nextRangesToUpdate.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 Ts(vs("Result couldn't be automatically expanded. Please insert more rows."));if(a)throw new Ts(vs("Result couldn't be automatically expanded. Please insert more columns."));throw new Ts(vs("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 Ts(vs("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!==Od.empty)throw this.blockedArrayFormulas.add(e),new Ts(vs("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=eb(RD(o[i][n]),this.getters.getLocale(),a,r);l.type===Od.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.nextRangesToUpdate.addMany(this.getArrayFormulasBlockedBy(s,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return yD;this.symbolsBeingComputed.add(t);try{const s=e?.(t);return s||new Is(vs("Invalid formula"))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){const t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.dependencies:[]}getCellsDependingOn(e){return this.formulaDependencies().getCellsDependingOn(e,this.nextRangesToUpdate)}}function ED(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 RD(e){return null===e.value||void 0===e.value?{...e,value:0}:e}function xD(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 TD=new Fg;TD.add("data_validation_checkbox",(e,t)=>{if(e.isCellValidCheckbox(t)){const s=!!e.getEvaluatedCell(t).value;return{svg:s?fR:pR,hoverSvg:s?fR:mR,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})}}}}),TD.add("data_validation_chip_icon",(e,t)=>{const s=e.getDataValidationChipStyle(t);if(s){const o=e.getCellComputedStyle(t);return{svg:uR(s),hoverSvg:gR(s),priority:10,horizontalAlign:"right",size:Kb(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"}}}),TD.add("data_validation_list_icon",(e,t)=>{if(!e.isReadonly()&&e.cellHasListDataValidationIcon(t)){const o=e.getCellComputedStyle(t);return{svg:cR(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}),TD.add("conditional_formatting",(e,t)=>{const s=e.getConditionalIcon(t);if(s){const o=e.getCellStyle(t);return{type:"conditional_formatting",svg:SR[s].svg,priority:1,horizontalAlign:"left",size:Kb(o),margin:4,position:t}}}),TD.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?vR(l,!1):void 0,hoverSvg:a?vR(l,!0):void 0,position:t,onClick:Ip}}}),TD.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?hR(o):cR(o),position:t,onClick:void 0}});const AD=/"(#[0-9a-fA-F]{6})"/g;const DD={isValid:!0};const _D=["*","+","&"];function OD(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 VD(e,0,s)}(t,e))}(UD(e),t-1)}function FD(){return{type:"insertLine"}}function PD(e,t){return{type:"nest",indentLevel:e,doc:t}}function MD(e){return{type:"concat",docs:e}}function ND(e){return{type:"chooseBetween",doc1:LD(e),doc2:e}}function LD(e){return"string"==typeof e?e:"chooseBetween"===e.type?LD(e.doc1):"concat"===e.type?MD(e.docs.map(LD)):"nest"===e.type?{type:"nest",indentLevel:e.indentLevel,doc:LD(e.doc)}:"insertLine"===e.type?"":e}const kD=$e(function(e){return"\n"+"\t".repeat(e)});function VD(e,t,s){if(null===s)return null;const{indentLevel:o,doc:i,next:n}=s;if("string"==typeof i)return{subString:i,next:VD(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 VD(e,t,s)}if("nest"===i.type)return VD(e,t,{indentLevel:o+i.indentLevel,doc:i.doc,next:n});if("insertLine"===i.type)return{subString:kD(o),next:VD(e,o,n)};if("chooseBetween"===i.type){const s=VD(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 VD(e,t,{indentLevel:o,doc:i.doc2,next:n})}return null}function UD(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":const t=mf.get(e.value.toUpperCase()),s=hs(t,e.args.length),o=[];let i=0;for(;i<e.args.length;){const n=t.args[s(i).index??-1]?.repeating;if(n){const s=e.args.slice(i,i+t.nbrArgRepeating).map(e=>UD(e));o.push(ND(MD(HD(s)))),i+=t.nbrArgRepeating}else o.push(UD(e.args[i])),i++}return zD(MD(HD(o)),e.value);case"UNARY_OPERATION":const n=UD(e.operand),r=(e.postfix?GD(e):WD(e))?zD(n):n;return e.postfix?MD([r,e.value]):MD([e.value,r]);case"BIN_OPERATION":{const t=UD(e.left),s=GD(e)?zD(t):t,o=UD(e.right),i=WD(e)?zD(o):o;return ND(MD([s,`${e.value}`,PD(1,MD([{type:"insertLine"},i]))]))}case"EMPTY":return""}}function HD(e){const t=e.length?[e[0]]:[];for(let s=1;s<e.length;s++)t.push(", ",FD()),t.push(e[s]);return t}function zD(e,t=void 0){const s=["(",PD(1,MD([{type:"insertLine"},e])),{type:"insertLine"},")"];return t&&s.unshift(t),ND(MD(s))}function BD(e){switch(e.type){case"FUNCALL":const t=e.args.map(e=>BD(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(GD(e)?`(${BD(e.operand)})`:BD(e.operand))+e.value}const s=WD(e)?`(${BD(e.operand)})`:BD(e.operand);return e.value+s;case"BIN_OPERATION":const o=GD(e)?`(${BD(e.left)})`:BD(e.left),i=WD(e)?`(${BD(e.right)})`:BD(e.right);return o+e.value+i}}function GD(e){const t=e.value,s="left"in e?e.left:e.operand,o=s.value;return"BIN_OPERATION"===s.type&&Tf[o]<Tf[t]}function WD(e){const t=e.value,s="right"in e?e.right:e.operand,o=Tf[s.value],i=Tf[t];return"BIN_OPERATION"===s.type&&(o<i||o===i&&!_D.includes(t))}const $D=["PIVOT.VALUE","PIVOT.HEADER","PIVOT"];function qD(e){return Hf(e,$D)[0]}function ZD(e){return Hf(e,$D).length}const jD="0.00%";function YD(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=Jg[e.aggregator];if(!o)return{value:0};try{return o([s],this.getters.getLocale())}catch(t){return oi(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}=pA(this,t),o=s.findIndex(t=>t.field===e);return-1===o?new Rs:this.getPivotHeaderValueAndFormat(s.slice(0,o+1))}if(o.find(t=>t.nameWithGranularity===e)){const{rowDomain:s}=pA(this,t),o=s.findIndex(t=>t.field===e);return-1===o?new Rs:this.getPivotHeaderValueAndFormat(s.slice(0,o+1))}return this.getPivotCellValueAndFormat(e,t)});return _s(n)?n[0][0]:n}getValuesToAggregate(e,t){const{rowDomain:s,colDomain:o}=pA(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=ap(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:Ss.NotAvailable,message:vs('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 oi(e,"COMPUTE_MEASURE_DISPLAY_VALUE")}}asPercentOfGrandTotal(e,t){const s=this.getGrandTotal(t.id);return 0===s?{value:Ss.DivisionByZero}:{value:this.measureValueToNumber(e)/s,format:jD}}asPercentOfRowTotal(e,t,s){const o=this.getRowTotal(t.id,s);return 0===o?{value:Ss.DivisionByZero}:{value:this.measureValueToNumber(e)/o,format:jD}}asPercentOfColumnTotal(e,t,s){const o=this.getColumnTotal(t.id,s);return 0===o?{value:Ss.DivisionByZero}:{value:this.measureValueToNumber(e)/o,format:jD}}asPercentOfParentRowTotal(e,t,s){const o=function(e,t){const{colDomain:s,rowDomain:o}=pA(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:jD}}asPercentOfParentColumnTotal(e,t,s){const o=function(e,t){const{colDomain:s,rowDomain:o}=pA(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:jD}}asPercentOfParentTotal(e,t,s,o){const{fieldNameWithGranularity:i}=o;if(!i)return e;if(!SA(i,s))return{value:""};const n=function(e,t,s){let{rowDomain:o,colDomain:i}=pA(e,s);if("row"===CA(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:jD}}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:Ss.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}=pA(this,s),h=yA(c),d=yA(l),u=a[h]?.[d];return{value:u??"",format:"running_total"===i?e.format:jD}}asPercentOf(e,t,s,o){const{fieldNameWithGranularity:i,value:n}=o;if(void 0===n||!i)return e;if(!SA(i,s))return{value:""};const r=this.getComparisonValue(t,s,i,n),a=this.strictMeasureValueToNumber(e);return 0===r||"sameValue"===r&&0===a?{value:Ss.DivisionByZero}:!r||"sameValue"===r&&!a?{value:""}:"sameValue"===r?{value:1,format:jD}:void 0===a?{value:Ss.NullError}:{value:a/r,format:jD}}asDifferenceFrom(e,t,s,o){const{fieldNameWithGranularity:i,value:n}=o;if(void 0===n||!i)return e;if(!SA(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(!SA(i,s))return{value:""};const r=this.getComparisonValue(t,s,i,n),a=this.strictMeasureValueToNumber(e);return 0===r?{value:Ss.DivisionByZero}:r&&"sameValue"!==r?void 0===a?{value:Ss.NullError}:{value:(a-r)/r,format:jD}:{value:""}}asRank(e,t,s,o,i){const{fieldNameWithGranularity:n}=o;if(!n)return e;if(!SA(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}=pA(this,s),h=yA(c),d=yA(l),u=a[h]?.[d];return{value:u??""}}computeRank(e,t,s){const o={},i=CA(this,t),n="row"===i?"column":"row";let r=this.getPivotValueCells(e.id);"column"===i&&(r=Ho(r));for(const a of r){const r=yA(mA(this,n,a[0].domain)),l=a.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:mA(this,i,t.domain)})).filter(e=>SA(t,e.rowDomain)),c=Object.groupBy(l,e=>wA(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=yA(mA(this,i,e.domain)),n=c[wA(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=CA(this,t),n="row"===i?"column":"row";let r=this.getPivotValueCells(e.id);"column"===i&&(r=Ho(r));for(const a of r){const r=yA(mA(this,n,a[0].domain));o[r]={};const l={},c=a.map(t=>({...t,rowDomain:mA(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>SA(t,e.rowDomain));for(const e of c){const s=yA(e.rowDomain),i=EA(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=yA(s),n=EA(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=pA(this,t).rowDomain,o=this._getPivotCellValueAndFormat(e,s);return this.measureValueToNumber(o)}getColumnTotal(e,t){const s=pA(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===II||o===wI?function(e,t,s,o){const i=CA(e,s),n="row"===i?e.getExpandedTableStructure().getRowTree():e.getExpandedTableStructure().getColTree(),r=vA(mA(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 bA(t,s,a[ue(c+(o===II?-1:1),0,a.length-1)])}(this,t,s,o):bA(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}=pA(e,t);return fA(s,e.getExpandedTableStructure().getRowTree())&&fA(o,e.getExpandedTableStructure().getColTree())}(this,i))throw new Rs;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;mp(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}}class XD{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 ys(vs("Dimension %s does not exist",e));return t}getMeasure(e){const t=this.measures.find(t=>t.id===e);if(!t)throw new ys(vs("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:vs("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&&op(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 KD extends XD{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 JD(e,t,s){const o=t.measures.filter(e=>!e.isHidden).map(e=>e.id),i=e_(e,t.columns,0);t_(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=QD(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 TA(n,r,o,a,l)}function QD(e,t,s,o,i){if(t>=s.length)return[];const n=s[t],r=n.nameWithGranularity,a=s_(e,n),l=o_(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(...QD(n,t+1,s,h,o))}return c}function e_(e,t,s){if(s>=t.length)return[];const o=t[s],i=t[s].nameWithGranularity,n=s_(e,o);return o_(n,t[s]).map(e=>({value:n[e]?.[0]?.[o.nameWithGranularity]?.value??null,field:i,children:e_(n[e]||[],t,s+1),type:o.type,width:0}))}function t_(e,t){for(const s in e){const o=e[s];0===o.children.length?o.width=t:(t_(o.children,t),o.width=o.children.reduce((e,t)=>e+t.width,0))}}function s_(e,t){return Object.groupBy(e,function(e){const t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}(t))}function o_(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?So(t,Fc)-So(s,Fc):So(s,Fc)-So(t,Fc);return"asc"===e.order?t.localeCompare(s):s.localeCompare(t)}(t,e,i):0):Object.keys(e)}const i_=Symbol("NULL");function n_(e,t,s){const o=e.granularity||"month";if(!(o in r_))throw new Error(`Unknown date granularity: ${o}`);const i="number"==typeof t||"string"==typeof t?t:i_;if(!r_[o].set.has(t)){r_[o].set.add(t);let n=null;if("number"==typeof t||"string"==typeof t){const e=Do(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(So(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()}}r_[o].values[i]=ap(e,n)}return r_[o].values[i]}const r_={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 a_;!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"}(a_||(a_={}));const l_=new ns,c_=["year","quarter_number","month_number","month","iso_week_number","day_of_month","day","day_of_week"];l_.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(a_.ALL),this.needsReevaluation=!1)}reload(e){e===a_.ALL&&(this.metaData=this.loadMetaData()),e>=a_.DEFINITION&&(this._definition=this.loadRuntimeDefinition()),e>=a_.DATA&&(this.dataEntries=this.loadData()),e>=a_.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),a_.NONE);this.reload(s)}}computeShouldReload(e,t){return Me(e.dataSet,t.dataSet)?a_.DEFINITION:a_.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 ys(vs("At least one measure and/or dimension is not correct."));return{value:Ss.GenericError,message:this.invalidRangeError?.message??vs("At least one measure and/or dimension is not correct.")}}}areDomainArgsFieldsValid(e){let t=e.filter((e,t)=>t%2==0).map(Ro);return t.length&&"measure"===t.at(-1)&&(t=t.slice(0,-1)),np(t,this.definition)}parseArgsToPivotDomain(e){const t=[];for(let s=0;s<e.length-1;s+=2){const o=Ro(e[s]),i=this.getTypeOfDimension(o),n="measure"===o?Ro(e[s+1]):ap(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:vs("Total")};const s=this.getDimension(t.field),o=this.filterDataEntriesFromDomain(this.dataEntries,e),i=o[0]?.[s.nameWithGranularity];if("datetime"===s.type){return Mg(s.granularity||"month").toValueAndFormat(t.value,this.getters.getLocale())}return i?null===i.value?{value:vs("(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!==Od.empty),r=o.aggregator,a=Jg[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 oi(e,r.toUpperCase())}}getPossibleFieldValues(e){const t=[],s=s_(this.dataEntries,e),o=o_(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=JD(this.dataEntries,this.definition,"collapsed")),this.collapsedTable}getExpandedTableStructure(){if(!this.isValid())throw new Error("Pivot is not valid !");return this.expandedTable||(this.expandedTable=JD(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 ys(vs("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=bp(this.coreDefinition,e.fields);return{...e,fields:{...e.fields,...t}}}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}}loadRuntimeDefinition(){return new KD(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}=sp(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===Od.empty||""===e.value));return 0===s.length?"integer":s.every(e=>e.type===Od.number&&e.format&&En(e.format))?"datetime":s.every(e=>e.type===Od.boolean)?"boolean":s.some(e=>e.type===Od.text)?"char":"integer"}assertCellIsValidField(e,t,s){if(s.type===Od.error)throw new ys(vs("The pivot cannot be created because cell %s contains an error",mt(e,t)));if(s.type===Od.empty||""===s.value)throw new ys(vs("The pivot cannot be created because cell %s is empty",mt(e,t)));if("__count"===s.value)throw new ys(vs("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=vp(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:Od.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:Od.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:Od.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=n_(t,o[t.fieldName]?.value||null,this.getters.getLocale()),i=Mg(t.granularity||"month"),{format:n,value:r}=i.toValueAndFormat(s,e);o[t.nameWithGranularity]={value:s,type:o[t.fieldName]?.type||Od.empty,format:o[t.fieldName]?.format,formattedValue:mn(r,{locale:e,format:n})}}}return t}},definition:KD,externalData:!1,dateGranularities:[...c_],datetimeGranularities:[...c_,"hour_number","minute_number","second_number"],isMeasureCandidate:e=>"boolean"!==e.type,isGroupable:()=>!0,canHaveCustomGroup:e=>"char"===e.type&&!e.isCustomField,isPivotUnused:()=>!0});const h_=["ADD_PIVOT","UPDATE_PIVOT","REMOVE_PIVOT"];function d_(e){return h_.includes(e.type)}const u_=new Fg;u_.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.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=mn(e.current,{format:t.cell?.format,locale:i});return{cellData:{border:t.border,style:t.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=Do(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=Ks(o);e.current=i;const n=s.getLocale(),r=mn(i,{format:t.cell?.format,locale:n});return{cellData:{border:t.border,style:t.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.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:t.cell?Jv(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:t.style,format:r.format,content:l},tooltip:l?{props:{content:l}}:void 0}}});const g_=new Fg,p_=/(\d+)$/,m_=/^(.*\D+)/,f_=/^(.*\D+)(\d+)$/,v_=/^0*/;function b_(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:Jv(n,{locale:Fc,format:n.format});if(t&&s(t))o.push(t);else{if(i)return o;o=[]}}return o}function S_(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 C_(e){if(e.length<2)return 1;const t=e.map(e=>Do(e,Fc)),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=Fs.fromTimestamp(e[s-1].getTime()),i=no(o,t),n=oo(o,t)%12;o.setFullYear(o.getFullYear()+i),o.setMonth(o.getMonth()+n);return{years:i,months:n,days:io(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}}g_.add("simple_value_copy",{condition:(e,t)=>!(1!==t.length||e.isFormula||e.format&&En(e.format)),generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&Jv(e,{locale:Fc}).type===Od.text&&f_.test(e.content),generateRule:(e,t,s)=>{const o=parseInt(e.content.match(p_)[0]),i=e.content.match(m_)[0],n=b_(e,t,e=>e.type===Od.text&&f_.test(e.value)).filter(e=>i===(e.value??"").toString().match(m_)[0]).map(e=>(e.value??"").toString().match(p_)[0]),r=n.reduce((e,t)=>{const s=t.match(v_)[0].length;return s>e[1]?[t,s]:e},[n[0],0]),a=r[1]?r[0].length:0;let l=S_(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&&Jv(e,{locale:Fc}).type===Od.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&&Jv(e,{locale:Fc}).type===Od.number&&!!e.format&&En(e.format),generateRule:(e,t)=>{const s=C_(b_(e,t,e=>e.type===Od.number&&!!e.format&&En(e.format)).map(e=>Number(e.value)));if(void 0===s)return{type:"COPY_MODIFIER"};const o=Jv(e,{locale:Fc});return"object"==typeof s?{type:"DATE_INCREMENT_MODIFIER",increment:s,current:o.type===Od.number?o.value:0}:{type:"INCREMENT_MODIFIER",increment:s,current:o.type===Od.number?o.value:0}},sequence:25}).add("increment_number",{condition:e=>!e.isFormula&&Jv(e,{locale:Fc}).type===Od.number,generateRule:(e,t,s)=>{const o=b_(e,t,e=>e.type===Od.number&&!En(e.format||"")).map(e=>Number(e.value));let i=S_(o);["up","left"].includes(s)&&1===o.length&&(i=-i);const n=Jv(e,{locale:Fc});return{type:"INCREMENT_MODIFIER",increment:i,current:n.type===Od.number?n.value:0}},sequence:40});class y_{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}=u_.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 I_=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 w_(e){return I_.has(e.type)}const E_=new Fg,R_=new Fg;function x_(e,t){if(e.rootCommand&&"object"==typeof e.rootCommand)return br(e.rootCommand)?function(e,t){if(!t)return;if(!E_.contains(t.type))return;return E_.get(t.type)(e,t)}(t,e.rootCommand):function(e,t,s){if(!R_.contains(t.type))return;return R_.get(t.type)(e,t,s)}(t,e.rootCommand,e.commands)}class T_{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,Ro(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 A_=new Fg,D_={type:"bar",title:{},stacked:!1,dataSetsHaveTitle:!1,dataSets:[],legendPosition:"top",humanize:!0};function __(e,t){if(t.title)return t.title;if("carouselDataView"===t.type)return vs("Data");const s=e.getChartDefinition(t.chartId);return(A_.getAll().find(e=>e.matcher?.(s))||A_.get(s.type)).displayName}const O_=["image/avif","image/bmp","image/gif","image/vnd.microsoft.icon","image/jpeg","image/png","image/tiff","image/webp"];function F_(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(Vt(e[o],t))return e[o]=Mt(e[o],t),e;return e[s]=t,e},[])}(t):[t[t.length-1]],a=r.map(e=>Gt(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 P_(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 M_(e,t){if(!t.length||!t[0].length)return e;const s=t[0].length,o=t.length;return e.map(e=>P_(e,s,o)).flat()}function N_(e){let t;if(e[SI.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[SI.Html],"text/html"))}const s=e[SI.PlainText]||"";let o;if(!s.trim())for(const t of O_)if(e[t]){o=e[t];break}return{text:s,data:t,imageBlob:o}}const L_=(e,t,s,o)=>{e.forEach(({handlerName:e,handler:i})=>{const n=t[e];n&&i.paste(s,n,o)})};function k_(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?Mt(n,e):e}return{target:a,zone:n,selectedZones:r}}const V_=(e,t,s)=>{const o={col:t[0].left,row:t[0].top};e.getBackToDefault(),e.selectZone({cell:o,zone:Mt(...s)},{scrollIntoView:!1})},U_={figureHandlers:new Fg,cellHandlers:new Fg},H_=5242880;const z_={filterType:"criterion",type:"none",values:[]};class B_{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);Ut(o,this.boundaries.top,this.boundaries)&&this.adjustPositionX(o),Ut(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=Nt(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=Nt(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 G_=(new ns).add("settings",class extends sA{static getters=["getLocale"];locale=Fc;allowDispatch(e){return"UPDATE_LOCALE"===e.type?Kc(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===dh(e)&&(s=dh(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??Fc}export(e){e.settings={locale:this.locale}}}).add("sheet",class extends sA{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||Iv(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"}}beforeHandle(e){if("REMOVE_COLUMNS_ROWS"===e.type)"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements])}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"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:mb(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(Cb(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 bb(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(Tt))return"InvalidRange";if(t.length){const s=this.getSheetZone(e);return t.every(e=>Ht(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:mb(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=>Cb(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{sheetId:e,col:s,row:i}=this.getCellPosition(t.id),n=this.getters.getCellStyle({sheetId:e,col:s,row:i});this.dispatch("UPDATE_CELL",{sheetId:o.id,col:s,row:i,content:t.content,format:t.format,style:n})}const r=Object.assign({},this.sheetIdsMapName);r[o.name]=o.id,this.history.update("sheetIdsMapName",r)}getDuplicateSheetName(e){return Sb(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 sA{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]=fb(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=vb(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=xR(t,e,i);n.outlineLevel=o+1,s.isFolded&&(n.isHidden=!0)}if(s.isFolded){xR(t,e,s.end+1).collapsed=!0}}}}}}).add("header visibility",class extends sA{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 sA{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 es(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(Vt(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||fE,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=>!Nt(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=>Ht(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=>Ut(t,s,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>Vt(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,[jt(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=Yt(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,Yt(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 PA(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 PA(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=PA(e.id,s,t.config,this.getters.getRangeFromZone);n.push(i)}}const r=i.zone;if(n.length<zt(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||fE,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:Dt(e.range.zone),type:e.type};Me(e.config,fE)||(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=Dt(e.range.zone);t.tables.push({range:s,filters:[],config:e.config})}}}).add("dataValidation",class extends sA{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=>Tb(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(Ut(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 Db(e.ranges)){const e=this.getters.getCellStyle(t),s={...e,align:e?.align??"center",verticalAlign:e?.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 nA.contains(e.rule.criterion.type)?"Success":"UnknownDataValidationCriterionType"}checkCriterionHasValidNumberOfValues(e){const t=e.rule.criterion,s=nA.get(t.type).numberOfValues(t);return void 0!==s&&t.values.length!==s?"InvalidNumberOfCriterionValues":"Success"}checkCriterionValuesAreValid(e){const t=e.rule.criterion,s=nA.get(t.type);return t.values.some(e=>"onlyFormulas"===s.allowedValues&&!e.startsWith("=")||(e.startsWith("=")?"onlyLiterals"===s.allowedValues||lE(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 sA{static getters=["zoneToXC","getCells","getTranslatedCellFormula","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":"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.copyColumnFormat.bind(this)):this.handleAddColumnsRows(e,this.copyRowFormat.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:"",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,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:"",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 tA;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 ub(t.id,t.formats)){const t=o.get(e);t?t.format=s:o.set(e,{format:s})}for(const i of o.keysForSheet(s)){const s=o.get(i);if(s?.content||s?.format){const o=this.importCell(t.id,s?.content,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={};for(const s of e.sheets){const e=[],o={},i=Object.keys(this.cells[s.id]||{}).map(e=>this.getters.getCellPosition(e)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(const s of i){const i=this.getters.getCell(s),n=mt(s.col,s.row);if(i.format){const o=hb(i.format,t);e[o]??=[],e[o].push(s)}i.content&&(o[n]=i.content)}s.formats=db(e),s.cells=o}e.formats=t}importCell(e,t,s){const o=this.getNextUid();return this.createCell(o,t||"",s,e)}exportForExcel(e){this.export(e);const t=[];for(const s in e.formats||[])zn(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]}}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(cE(o).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),t,s,e);return this.getFormulaString(e,o,i)}getFormulaMovedInSheet(e,t,s){const o=cE(s).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),i=this.getters.removeRangesSheetPrefix(t,o);return this.getFormulaString(t,s,i)}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}copyColumnFormat(e,t,s){for(let o=0;o<this.getters.getNumberRows(e);o++){const i=this.getFormat(e,t,o);if(i.format)for(const t of s)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,...i})}}copyRowFormat(e,t,s){for(let o=0;o<this.getters.getNumberCols(e);o++){const i=this.getFormat(e,o,t);if(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.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||"",a="format"in o?o.format:i&&i.format;if((n&&!r&&!o.formula||!n&&(!i||""===i.content))&&!a)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 l=i?.id||this.getNextUid(),c=this.createCell(l,r,a,e);this.history.update("cells",e,c.id,c),this.dispatch("UPDATE_CELL_POSITION",{cellId:c.id,col:t,row:s,sheetId:e})}createCell(e,t,s,o){return t.startsWith("=")?this.createFormulaCell(e,t,s,o):this.createLiteralCell(e,t,s)}createLiteralCell(e,t,s){const o=this.getters.getLocale(),i=Qv(t,o);return Bn(s=s||("number"==typeof i?An(t,o)||Dn(t):void 0))||t.startsWith("'")||fo(t)||(t=Ro(i)),{id:e,content:t,format:s,isFormula:!1,parsedValue:i}}createFormulaCell(e,t,s,o){const i=lE(t);return i.dependencies.length?this.createFormulaCellWithDependencies(e,i,s,o):{id:e,content:t,format:s,isFormula:!0,compiledFormula:{...i,dependencies:[]}}}createFormulaCellWithDependencies(e,t,s,o){const i=[];for(const e of t.dependencies)i.push(this.getters.getRangeFromSheetXC(o,e));return new oA(e,t,s,i,o,this.getters.getRangeString)}checkCellOutOfSheet(e){const{sheetId:t,col:s,row:o}=e;if(!this.getters.tryGetSheet(t))return"InvalidSheetId";return Ut(s,o,this.getters.getSheetZone(t))?"Success":"TargetOutOfSheet"}checkUselessClearCell(e){const t=this.getters.getCell(e),s=this.getters.getCellStyle(e);return t&&(t.content||s||t.format)?"Success":"NoChanges"}checkUselessUpdateCell(e){const t=this.getters.getCell(e),s="content"in e||"formula"in e,o="style"in e,i=o&&this.getters.getCellStyle(e),n="format"in e;return s&&t?.content!==e.content||o&&!Me(i,e.style)||n&&t?.format!==e.format?"Success":"NoChanges"}}).add("merge",class extends sA{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=yb({...e,zone:{...s,bottom:Eb(e)?void 0:s.bottom,right:Rb(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}=sr(i);return or(e,t.split(":")[0])}return i}doesIntersectMerge(e,t){for(const s of this.getMerges(e))if(Vt(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&&Vt(s,r)&&(r=Mt(s,r))}return Lt(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)&&Lt(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 Lt(t,s);const{numberOfCols:o,numberOfRows:i}=zt(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?gA(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&&Vt(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 Qt(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||!Lt(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.nextId++;this.history.update("merges",e,r,this.getters.getRangeFromSheetXC(e,Dt({left:s,top:i,right:o,bottom:n})));const a=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,content:""});const o=this.getMerge({sheetId:e,col:n,row:t});o&&a.add(o.id),this.history.update("mergeCellMap",e,n,t,r)}for(const t of a){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===r||(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&&Lt(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}=zt(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 Gt(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,Rt(s))}export(e){for(const t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...uA(e))}}exportForExcel(e){this.export(e)}}).add("style",class extends sA{static getters=["getCellStyle","getCellStyleInZone","getZoneStyles","getStyleColors"];styles={};handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.onMerge(e.sheetId,t);break;case"SET_FORMATTING":"style"in e&&(e.style?this.setStyles(e.sheetId,e.target,e.style):this.clearStyle(e.sheetId,e.target));break;case"CLEAR_FORMATTING":case"CLEAR_CELLS":this.clearStyle(e.sheetId,e.target);break;case"UPDATE_CELL":"style"in e&&(e.style?this.setStyles(e.sheetId,[jt(e)],e.style):this.clearStyle(e.sheetId,[jt(e)]));break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnn(e):this.handleAddRows(e);break;case"CLEAR_CELL":this.clearStyle(e.sheetId,[jt(e)]);break;case"DELETE_SHEET":this.history.update("styles",e.sheetId,void 0)}}adaptRanges(e,t){const s=[];for(const o of this.styles[t]??[]){const i=e(this.getters.getRangeFromZone(t,o.zone));switch(i.changeType){case"RESIZE":case"CHANGE":case"MOVE":s.push({style:o.style,zone:i.range.unboundedZone});break;case"NONE":s.push(o)}}this.history.update("styles",t,s)}handleAddColumnn(e){const t=this.styles[e.sheetId]??[];for(let s=0;s<t.length;s++){const o=t[s];o.zone.left-e.quantity===e.base&&"before"===e.position?this.history.update("styles",e.sheetId,s,"zone","left",o.zone.left-e.quantity):o.zone.right===e.base&&"after"===e.position&&this.history.update("styles",e.sheetId,s,"zone","right",o.zone.right+e.quantity)}}handleAddRows(e){const t=this.styles[e.sheetId]??[];for(let s=0;s<t.length;s++){const o=t[s];o.zone.top-e.quantity===e.base&&"before"===e.position?this.history.update("styles",e.sheetId,s,"zone","top",o.zone.top-e.quantity):o.zone.bottom===e.base&&"after"===e.position&&this.history.update("styles",e.sheetId,s,"zone","bottom",o.zone.bottom+e.quantity)}}styleIsDefault(e){return Me(this.removeDefaultStyleValues(e),{})}removeDefaultStyleValues(e){const t={...e};for(const e in _A)t[e]===_A[e]&&delete t[e];return t}onMerge(e,t){this.setStyle(e,t,this.getCellStyle({sheetId:e,col:t.left,row:t.top}),{force:!0})}setStyles(e,t,s,o={force:!1}){for(const i of t)this.setStyle(e,i,s,o)}setStyle(e,t,s,o={force:!1}){const i=[];let n=[this.getters.expandZone(e,t)];for(const r of this.styles[e]??[]){const e=Nt(r.zone,t);if(!e){i.push(r);continue}let a=o.force?s:{...r.style,...s};if(a=this.removeDefaultStyleValues(a),Me(r.style,a))i.push(r);else{a&&!this.styleIsDefault(a)&&i.push({zone:e,style:a});for(const t of ft([r.zone],[e]))i.push({zone:t,style:r.style})}n=ft(n,[e])}if(s){const e=this.removeDefaultStyleValues(s);i.push(...n.map(t=>({zone:t,style:e})))}this.history.update("styles",e,i.filter(e=>!this.styleIsDefault(e.style)))}clearStyle(e,t){this.setStyles(e,t,void 0,{force:!0})}getCellStyle(e){const t=this.styles[e.sheetId]?.find(t=>Ut(e.col,e.row,t.zone));return t?.style}getCellStyleInZone(e,t){const s=new tA;for(const{zone:o,style:i}of this.styles[e]??[]){const n=Nt(o,t);if(n)for(let t=n.left;t<=n.right;t++)for(let o=n.top;o<=n.bottom;o++)s.set({sheetId:e,col:t,row:o},i)}return s}getZoneStyles(e,t){const s=[];for(const o of this.styles[e]??[]){const e=Nt(o.zone,t);e&&s.push({zone:e,style:o.style})}return s}getStyleColors(e){const t=new Set;for(const s of this.styles[e]??[])s.style.textColor&&t.add(s.style.textColor),s.style.fillColor&&t.add(s.style.fillColor);return[...t]}import(e){if(Object.keys(e.styles||{}).length){for(const t of e.sheets)for(const s in t.styles){const o=t.styles[s];this.setStyle(t.id,Rt(s),e.styles[o])}for(const t of e.sheets)if(t.merges)for(const e of t.merges)this.onMerge(t.id,Rt(e))}}export(e){const t={};for(const s of e.sheets){s.styles={};for(const e of this.styles[s.id]??[])s.styles[Dt(e.zone)]=hb(e.style,t)}e.styles=t}exportForExcel(e){this.export(e)}}).add("headerSize",class extends sA{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 sA{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,[jt(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,jt(e))}getZoneExternalBorders(e,t){const s={};for(const o of this.borders[e]??[])Vt(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 tA;for(const o of this.borders[e]??[]){const{zone:i,style:n}=o,r=Nt(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=Nt(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 ss(e,t)){const e=this.computeBorderFromZone(i,o),n=kt(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=Nt(s.zone,t);if(!e){const e=kt(s.zone,t);if(e&&r[e.position])for(const e of ss(s.zone,t)){const o=this.computeBorderFromZone(e,s),n=kt(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,Rt(s),e.borders[o])}for(const t of e.sheets)if(t.merges)for(const e of t.merges)this.addBordersToMerge(t.id,Rt(e))}export(e){const t={};for(const s of e.sheets){s.borders={};for(const e of this.borders[s.id]??[])s.borders[Dt(e.zone)]=hb(e.style,t)}e.borders=t}exportForExcel(e){this.export(e)}}).add("conditional formatting",class extends sA{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)Ut(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(Et));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=nA.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(lE(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&&dA(t)>=dA(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&&dA(t)>=dA(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&&dA(t)>=dA(s)?"MinBiggerThanMid":"Success"}checkCFValues(e){for(const t of e.values){if(!t.startsWith("="))continue;if(lE(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 sA{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 sA{static getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getFigureIdFromChartId","getContextCreationChart"];charts={};createChart=Jy(this.getters);validateChartDefinition=e=>eI(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 sA{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 sA{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)}}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]}}}).add("pivot_core",class extends sA{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 TA(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:rp(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=lE(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||Qg(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 sA{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=DA(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&&Tt(t)?this.getters.checkZonesExistInSheet(s,[t]):"InvalidDataSet"}return"Success"}}).add("tableStyle",class extends sA{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(!PE[e.templateName])return"InvalidTableStyle";try{yv(e.primaryColor)}catch(e){return"InvalidTableStyle"}}return"Success"}handle(e){switch(e.type){case"CREATE_TABLE_STYLE":const t=ME(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:fE.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(vs("Custom Table Style"),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!FE[e]}import(e){for(const e in FE)this.styles[e]=FE[e];for(const t in e.customTableStyles){const s=e.customTableStyles[t];this.styles[t]=ME(s.displayName,s.templateName,s.primaryColor)}}export(e){const t={};for(const e in this.styles)FE[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}}),W_=(new ns).add("ui_sheet",class extends wr{static getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getContiguousZone","computeTextYCoordinate"];ctx=zb();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=Qb(this.ctx,o,t,void 0);s+=Math.max(...e.map(e=>$b(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 $b(this.ctx,e,t)}getCellText(e,t){const s=this.getters.getCell(e),o=this.getters.getLocale();if(t?.showFormula&&s?.isFormula)return oh(s.content,o);if(t?.showFormula&&!s?.content)return"";{const s=this.getters.getCellStyle(e),i=this.getters.getEvaluatedCell(e),n=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>$b(this.ctx,e,s||{})}:void 0;return mn(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 Qb(this.ctx,o,s,t.wrapText?t.maxWidth:void 0)}computeTextYCoordinate(e,t,s=M,o=1){const i=e.y+1,n=Hb(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);Lt(i,e)||(o=!0,i=e)}while(o);return i}isCellEmpty(e){const t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===Od.empty}getColMaxWidth(e,t){const s=Gt(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,i=0;for(const[s,n]of this.getters.getEvaluatedCellsPositionInZone(e,this.getters.getRowsZone(e,o,o))){if(void 0===n.value)continue;const o=this.getters.getColSize(e,s.col),r=this.getters.getCellStyle(s),a=n.formattedValue,l=Bb(this.ctx,a,r,o);l>i&&l>_&&(i=l,t=s)}const n=t&&this.getters.getCell(t);n&&!n.isFormula&&(i=0),s.push(i||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 wr{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 wr{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(jt({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(jt({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(Rt),[]);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(Ut(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!==Od.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!==Od.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!==Od.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=g_.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),n=this.getters.getCellStyle(e);t.push({data:{...e,border:o,style:n},rule:s})}return new y_(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 wr{allowDispatch(e){return"SORT_CELLS"===e.type?Ut(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 Gt(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=>Vt(e,t)),o=zt(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 Gt(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]===Od.empty&&(s=s.slice(1)),!s.some(e=>e[0]===Od.empty)&&!!s.some(e=>e[1]!==Od.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===Od.empty?{...e,type:Od.number,value:0}:e):o).sort(Md(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 t=0;t<u;t++)for(let s=0;s<g;s++){const o=c[t][d[s]],i=this.getters.getCell(o),a=this.getters.getCellStyle(o),h=l.left+t*n,u=l.top+s*r,g={sheetId:o.sheetId,col:h,row:u,content:""};if(i){let t=i.content;if(i.isFormula){const s=this.getters.getCellPosition(i.id);t=this.getters.getTranslatedCellFormula(e,0,u-s.row,i.compiledFormula.tokens)}g.style=a,g.content=t,g.format=i.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 wr{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}=Ut(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)||Bt(Mt(n,t))?[{position:{col:o,row:i},zone:n}]:this.sumDimensions(e,Mt(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===Od.number&&!(e.format&&En(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 Bt(t)?(s.add(1===zt(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)},Gt(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)},Gt(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 wr{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(jt));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 Gt(i)){const i=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==i){const e=Un(i,s);o[e]=o[e]||[],o[e].push(t)}}for(const t in o){const s=ft(o[t].map(e=>jt(e)));this.setContextualFormat(e,s,t)}}getCellNumberFormat(e){for(const t of[e]){const e=this.getters.getEvaluatedCell(t);if(!(e.type!==Od.number||e.format&&En(e.format)))return e.format||Tn(e.value)}}}).add("insert_pivot",class extends wr{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===Jt(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:vs("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:vs("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:vs("%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(vs("%(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 TA(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:rp(n,t)});const a=this.getters.getCoreTable({sheetId:e,col:t,row:s});if("dynamic"===a?.type){const o=jt({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 wr{static getters=["getPivotPresenceTracker"];trackPresencePivotId;tracker;handle(e){switch(e.type){case"PIVOT_START_PRESENCE_TRACKING":this.tracker=new T_,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 wr{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===Od.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}),l=this.getters.getCellStyle({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:Jc(s,this.getters.getLocale()),format:"",style:{..._A,...l}})}}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 wr{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];Er(s)&&this.subtotalCells.add(s.id)}}break;case"UPDATE_CELL":{if(!("content"in e))return;const t=this.getters.getCell(e);if(!t)return;Er(t)?this.subtotalCells.add(t.id):this.subtotalCells.delete(t.id);break}}mr.has(e.type)&&this.dispatch("EVALUATE_CELLS",{cellIds:Array.from(this.subtotalCells)})}}).add("collaborative",class extends wr{static getters=["getClientsToDisplay","getClient","getCurrentClient","getConnectedClients","isFullySynchronized"];static layers=["Selection"];colors=new jv(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 wr{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=x_(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)&&(br(t.rootCommand)?E_.contains(t.rootCommand.type):R_.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 wr{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&&Ut(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!==Od.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 wr{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 wr{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 Db(t)){const t=this.getters.getCell(e),s=this.getters.getEvaluatedCell(e);if(t?.content)if(t?.content&&s.type===Od.empty){let s;if(t.content.startsWith("=")){const o=this.getters.evaluateFormula(e.sheetId,t.content);s=(_s(o)?o[0][0]:o)?.toString()}else s=t.content;s&&fe(s)||this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}else s.type!==Od.boolean&&this.dispatch("UPDATE_CELL",{...e,content:"FALSE"});else this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}}}}).add("checkbox_toggle",class extends wr{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 wr{static getters=["dynamicTranslate"];dynamicTranslate(e){return e}}).add("geo_features",class extends wr{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")}}),$_=(new ns).add("selection",class extends wr{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=>Lt(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=Ft(s,"left",[...e.elements]);let i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=Ft(i,"left",[...e.elements]);const n={cell:{col:i.left,row:i.top},zone:o},r=this.gridSelection.zones.map(t=>Ft(t,"left",[...e.elements]));this.setSelectionMixin(n,r)}onRowsRemoved(e){const{cell:t,zone:s}=this.gridSelection.anchor,o=Ft(s,"top",[...e.elements]);let i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=Ft(i,"top",[...e.elements]);const n={cell:{col:i.left,row:i.top},zone:o},r=this.gridSelection.zones.map(t=>Ft(t,"top",[...e.elements]));this.setSelectionMixin(n,r)}onAddElements(e){const t="COL"===e.dimension?"left":"top",s=Ot(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),o=this.gridSelection.zones.map(s=>Ot(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=U_.cellHandlers.getKeys().map(e=>[e,new(U_.cellHandlers.get(e))(this.getters,this.dispatch)]),f={};for(const[e,t]of m)f[e]=t.copy(F_(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):jt(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 wr{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 z_;const o=this.filterValues[s][t];return o&&"criterion"===o.filterType?o:z_}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(eS);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=nA.get(t.type),r=t.values.map(t=>t.startsWith("=")?this.getters.evaluateFormula(e,t)??"":Qv(t,Fc));if(r.some(Si))continue;const a={type:t.type,values:r.map(vi),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=Rt(s.range),i=[],n=[];for(const s of ge(0,zt(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?Gt(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 wr{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 wr{static getters=["getCellComputedBorder","getCellComputedStyle"];styles=new tA;borders=new tA;handle(e){if(hr.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 tA,void(this.borders=new tA);w_(e)?"sheetId"in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new tA,this.borders=new tA):gr.has(e.type)?this.styles=new tA:pr.has(e.type)&&(this.borders=new tA)}getCellComputedBorder(e,t){let s=this.borders.get(e);return void 0===s&&(this.precomputeCellBorders(e.sheetId,t??jt(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,t){let s=this.styles.get(e);return void 0===s&&(this.precomputeCellStyle(e.sheetId,t??jt(e)),s=this.styles.get(e)??{}),s}precomputeCellStyle(e,t){const s=this.getters.getCellStyleInZone(e,t),o=this.getters.getCellTableStyleZone(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.styles.get(t))continue;const r={...Ve(o.get(t)),...Ve(this.getters.getDataValidationCellStyle(t)),...Ve(s.get(t)),...Ve(this.getters.getCellConditionalFormatStyle(t))};this.getters.getEvaluatedCell(t).link&&!r.textColor&&(r.textColor=d),this.styles.set(t,r)}}}).add("table_computed_style",class extends wr{static getters=["getCellTableStyle","getCellTableBorder","getCellTableBorderZone","getCellTableStyleZone"];tableStyles={};handle(e){hr.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e)||"EVALUATE_CELLS"===e.type?this.tableStyles={}:w_(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]}getCellTableStyleZone(e,t){const s=new tA;for(const o of this.getters.getTablesOverlappingZones(e,[t])){const t=this.tableStyles[e][o.id]().styles;for(const o of Object.keys(t)){const i=t[o],n=parseInt(o);for(const t of Object.keys(i)){const o=i[t];o&&s.set({sheetId:e,col:n,row:parseInt(t)},o)}}}return s}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 tA;for(const o of this.getters.getTablesOverlappingZones(e,[t])){const t=this.tableStyles[e][o.id]().borders;for(const o of Object.keys(t)){const i=t[o],n=parseInt(o);for(const t of Object.keys(i)){const o=i[t];o&&s.set({sheetId:e,col:n,row:parseInt(t)},o)}}}return s}computeTableStyle(e,t){return Oe(()=>{const{config:s,numberOfCols:o,numberOfRows:i}=this.getTableRuntimeConfig(e,t),n=NA(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 wr{static getters=["getColDimensions","getRowDimensions","getColRowOffset"];headerPositions={};isDirty=!0;handle(e){switch(hr.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"SET_FORMATTING":case"CLEAR_FORMATTING":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 wr{static getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getVisibleRectWithoutHeaders","getVisibleRectWithZoom","getVisibleCellPositions","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio","isPixelPositionVisible","getColDimensionsInViewport","getRowDimensionsInViewport","getAllActiveViewportsZonesAndRect","getRect","getFigureUI","getPositionAnchorOffset","getGridOffset","getViewportZoomLevel","getScrollBarWidth"];viewports={};sheetViewWidth=Y();sheetViewHeight=Y();gridOffsetX=0;gridOffsetY=0;zoomLevel=1;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}=Zt(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(hr.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"SET_ZOOM":this.zoomLevel=e.zoom||1;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":case"SET_FORMATTING":if("content"in e||"format"in e||void 0!==e.style?.fontSize||void 0!==e.style?.wrapping)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*this.zoomLevel}isVisibleInViewport({sheetId:e,col:t,row:s}){return this.getSubViewports(e).some(e=>e.isVisible(t,s))}getScrollBarWidth(){return 15/this.zoomLevel}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=pb(e-a),i=1):e<l&&s>=l&&c>0?(o=!0,n=pb(l-e),i=-1):r&&t<l&&e>l&&(o=!0,n=pb(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=pb(e-a),i=1):e<l&&s>=l&&c>0?(o=!0,n=pb(l-e),i=-1):r&&t<l&&e>l&&(o=!0,n=pb(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}}getVisibleRectWithZoom(e){const t=this.getViewportZoomLevel(),s=this.getVisibleRectWithoutHeaders(e);return s.width=s.width*t,s.height=s.height*t,s.x=s.x*t+this.gridOffsetX*t,s.y=s.y*t+this.gridOffsetY*t,s}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()}}))}getViewportZoomLevel(){return this.zoomLevel}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 B_(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 B_(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 B_(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 B_(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(jt({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 wr{static layers=["Clipboard"];static getters=["getClipboardTextAndImageContent","getClipboardId","getClipboardTextContent","isCutOperation"];status="invisible";originSheetId;copiedData;_isCutOperation=!1;clipboardId=(new cr).uuidv4();fileStore;uuidGenerator;constructor(e){super(e),this.fileStore=e.external.fileStore,this.uuidGenerator=new cr}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=Fy(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(!Tt(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:br(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?U_.figureHandlers:U_.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}=k_(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),L_(i,t,n,s),s?.selectTarget&&V_(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={[SI.PlainText]:this.getPlainTextContent(),[SI.Html]:await this.getHTMLContent()};return t&&e&&(s[t]=e),s}getSheetData(){const e={version:WT(),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="${_y(Ay(this.getters.getCellComputedStyle(t.position)))}">`+gT(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='${gT(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="${gT(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>H_)return void this.ui.notifyUI({text:vs("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=F_(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 wr{static getters=["getSelectedCarouselItem","getChartFromFigureId","getChartIdFromFigureId"];uuidGenerator=new cr;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:D_});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"}}),q_=(new ns).add("evaluation",class extends zA{static getters=["evaluateFormula","evaluateFormulaResult","evaluateCompiledFormula","getCorrespondingFormulaCell","getRangeFormattedValues","getRangeValues","getRangeFormats","getEvaluatedCell","getEvaluatedCells","getEvaluatedCellsInZone","getEvaluatedCellsPositionInZone","getEvaluatedCellsPositions","getSpreadZone","getArrayFormulaSpreadingOn","isEmpty"];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new wD(e.custom,this.getters)}beforeHandle(e){(hr.has(e.type)||ur.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 _s(s)?Uo(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 Wt(e,t).map(this.getters.getEvaluatedCell)}getEvaluatedCellsPositionInZone(e,t){return Wt(e,t).map(e=>[e,this.getters.getEvaluatedCell(e)])}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isEmpty(e,t){return Gt(t).map(({col:t,row:s})=>this.getEvaluatedCell({sheetId:e,col:t,row:s})).every(e=>e.type===Od.empty)}mapVisiblePositions(e,t){const{sheetId:s,zone:o}=e;return Gt(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=Uf(c.compiledFormula.tokens),r=a&&h?.content===c.content,!a&&""!==i){n=(i??"").toString();const t=s.format;if(t){const s=hb(t,e.formats);l.formats[o]=s}}}const h=l.cells[o];let d;d=a&&r&&c instanceof oA?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 zA{static getters=["getChartRuntime","getStyleOfSingleCellChart"];charts={};createRuntimeChart=Qy(this.getters);handle(e){if(hr.has(e.type)||gr.has(e.type)||dr.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:cC(e)};if(!t)return{background:c,fontColor:cC(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||cC(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 uI(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 zA{static getters=["getConditionalIcon","getCellConditionalFormatStyle","getConditionalDataBar"];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(hr.has(e.type)||gr.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("=")?lE(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===Od.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 go(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!==Od.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===Od.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});!Ut(i,c,l)||h.type!==Od.number||h.value<=0||(o[s]||(o[s]=[]),o[s][t]={color:Sv(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=Yv(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===Od.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===Od.error)return!1;const{sheetId:o}=e,i=nA.get(t.operator),n=t.values.map(e=>e.startsWith("=")?this.getters.evaluateFormula(o,e)??"":Qv(e,Fc));if(n.some(Si))return!1;const r={type:t.operator,values:n.map(vi)};return i.isValueValid(s.value??"",r,this.getters,o)}}).add("row_size",class extends zA{static getters=["getRowSize","getHeaderSize","getMaxAnchorOffset"];tallestCellInRow={};ctx=zb();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"SET_FORMATTING":if(e.style&&("fontSize"in e.style||"wrapping"in e.style))for(const t of e.target)this.updateRowSizeForZoneChange(e.sheetId,t);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 Gt(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)}updateRowSizeForZoneChange(e,t){for(let s=t.top;s<=t.bottom;s++){const t=this.getRowTallestCell(e,s);this.history.update("tallestCellInRow",e,s,t)}}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.getCellStyle(e),o=this.getters.getColSize(e.sheetId,e.col);return function(e,t,s,o){return t&&(t.isFormula||t.content)?Bb(e,t.isFormula?"":t.content,s,o):_}(this.ctx,t,s,o)}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 zA{static getters=["getDataValidationInvalidCriterionValueMessage","getInvalidDataValidationMessage","getValidationResultForCellValue","getDataValidationRangeValues","isCellValidCheckbox","getDataValidationCellStyle","getDataValidationChipStyle","isDataValidationInvalid"];validationResults={};handle(e){if(hr.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=nA.get(e);return t.startsWith("=")?"onlyLiterals"===s.allowedValues?vs("The value must not be a formula"):this.isValidFormula(t)?void 0:Dg.CriterionError.validFormula:"onlyFormulas"===s.allowedValues?vs("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 Gt(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 DD;const o=this.getRuleErrorForCellValue(e,t,s);return o?{error:o,rule:s,isValid:!1}:DD}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:Lv(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!lE(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]?.()||DD}computeSheetValidationResults(e){const t={},s=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(const e of Db(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===Od.empty?DD:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,s){const{sheetId:o}=t,i=s.criterion,n=nA.get(i.type),r=this.getCellOffsetInRule(t,s),a=this.getEvaluatedCriterionValues(o,r,i);if(a.some(Si))return;const l={...i,values:a.map(vi)};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=>Ut(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 Qv(s,Fc);const o=lE(s),i=this.getters.getTranslatedCellFormula(e,t.col,t.row,o.tokens);return this.getters.evaluateFormula(e,i)})}}).add("dynamic_tables",class extends zA{static getters=["canCreateDynamicTableOnZones","doesZonesContainFilter","getFilter","getFilters","getTable","getTables","getTablesOverlappingZones","getFilterId","getFilterHeaders","isFilterHeader"];tables={};handle(e){if(hr.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)Vt(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=>Ut(t,s,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>Vt(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(!es(t))return!1;const s=Mt(...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===Ss.SpilledBlocked&&!e.errorOriginPosition}if(Me(i,o)&&1===Jt(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=PA(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=Rt(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=Dt(n.range.zone))}}}).add("custom_colors",class extends zA{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:Ev(255,0,0),colors:[]},{leadColor:Ev(255,128,0),colors:[]},{leadColor:Ev(128,128,0),colors:[]},{leadColor:Ev(128,255,0),colors:[]},{leadColor:Ev(0,255,0),colors:[]},{leadColor:Ev(0,255,128),colors:[]},{leadColor:Ev(0,255,255),colors:[]},{leadColor:Ev(0,127,255),colors:[]},{leadColor:Ev(0,0,255),colors:[]},{leadColor:Ev(127,0,255),colors:[]},{leadColor:Ev(128,0,128),colors:[]},{leadColor:Ev(255,0,128),colors:[]}];for(const s of e.map(Tv)){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)=>Dv(e).s-Dv(t).s)).flat().map(xv)}(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=new Set;for(const s of this.getters.getStyleColors(e))t.add(s);for(const s of this.getters.getBordersColors(e))t.add(s);return[...t]}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(Sv(t.minimum.color)),s.push(t.midpoint?Sv(t.midpoint.color):void 0),s.push(Sv(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(AD)].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(!Iv(t))continue;const e=yv(t);t&&!T.includes(e)&&this.history.update("customColors",e,!0)}}}).add("pivot_ui",class extends zA{static getters=["getPivot","getFirstPivotFunction","getPivotCellSortDirection","getPivotIdFromPosition","getPivotCellFromPosition","generateNewCalculatedMeasureName","isPivotUnused","isSpillPivotFormula"];pivots={};unusedPivotsInFormulas;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(hr.has(e.type))for(const e of this.getters.getPivotIds())l_.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.unusedPivotsInFormulas=void 0;break;case"UNDO":case"REDO":{this.unusedPivotsInFormulas=void 0;const t=e.commands.filter(d_);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 r_)r_[e].set.clear(),r_[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=qD(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=BD(t);return this.getters.evaluateFormula(e,s)})}}getPivotCellFromPosition(e){const t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||0===ZD(t.compiledFormula.tokens))return AA;const s=this.getters.getCellPosition(t.id),o=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!o)return AA;let{functionName:i,args:n}=o;const r=n[0];if(!r)return AA;const a=this.getters.getPivotId(r.toString());if(!a)return AA;const l=this.getPivot(a);if(!l.isValid())return AA;if("PIVOT"===i&&!t.content.replaceAll(" ","").toUpperCase().startsWith("=PIVOT"))return AA;if("PIVOT"===i){const t=wp(this.getters.getPivotCoreDefinition(a),vi(n[1]),vi(n[2]),vi(n[3]),vi(n[4]),vi(n[5]),this.getters.getLocale()),o=l.getCollapsedTableStructure().getPivotCells(t),i=e.col-s.col,r=e.row-s.row;return o[i][r]}try{const t=e.row-s.row,o=e.col-s.col;if(n=n.map(e=>_s(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:pA(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 AA}}generateNewCalculatedMeasureName(e){const t=e.map(e=>e.fieldName);return st(vs("Calculated measure 1"),t,{compute:(e,t)=>vs("Calculated measure %s",t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw new Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){const{type:t}=this.getters.getPivot(e);return this._getUnusedPivotsInFormulas().includes(e)&&l_.get(t).isPivotUnused(this.getters,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=pA(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=YD(l_.get(s.type).ui);this.pivots[e]=new t(this.custom,{definition:s,getters:this.getters})}}_getUnusedPivotsInFormulas(){if(void 0!==this.unusedPivotsInFormulas)return this.unusedPivotsInFormulas;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.unusedPivotsInFormulas=[],[]}return this.unusedPivotsInFormulas=[...e],this.unusedPivotsInFormulas}}).add("cell_icon",class extends zA{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.getCellStyle(s)?.verticalAlign;return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,o),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=TD.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 Z_{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=Ob(e);t?.applyChange&&this.executeOnAllRanges(t.applyChange,t.sheetId,t.sheetName)}finalize(){}verifyRangeRemoved(e){return t=>{const s=e(t);return"NONE"===s.changeType||Tt(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(!Tt(e.zone))return e;const i=e.prefixSheet?e.sheetId:o,n=Rb(e),r=Eb(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(At(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}}(yb({...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:Rb(e)?void 0:o,bottom:Eb(e)?void 0:i};return yb({...e,zone:n},this.getters.getSheetSize)}getRangeFromSheetXC(e,t){if(!Kn.test(t)||!this.getters.tryGetSheet(e))return wb(t);const{sheetName:s}=sr(t);return Ib({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)?xb(e,t,this.getters.getSheetName,s):Ss.InvalidReference:Ss.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 yb({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 wb(Ss.InvalidReference);return yb({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}=sr(e);return null!==t.match(Kn)&&(!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=lE(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=lE(s),n=i.dependencies.map(s=>{const i=this.getters.getRangeFromSheetXC(e,s);return"keepSameReference"===o?i:Tb(e,t,i)});return this.getters.getFormulaString(t,i.tokens,n)}}class j_{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 Y_{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new j_,this.anchor={cell:{col:0,row:0},zone:jt({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=jt({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 Sr("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,jt({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 Sr("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 Sr.Success;let g=o.zone;const p=e=>{e=$t(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?$t(g):g,g&&!Lt(g,o.zone))return this.processEvent({options:{scrollIntoView:!0},mode:"updateAnchor",anchor:{zone:g,cell:{col:i,row:n}}})}g=p(Mt({top:n,bottom:n,left:i,right:i},$t({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=Mt(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=Mt(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(Lt(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:jt(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 Sr(s):(this.anchor=t.anchor,this.stream.send(t),Sr.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:s}=e;if(!Ut(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===Od.empty||s.type===Od.text&&""===s.value}}class X_{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]=lr(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 K_=17781237,J_=17781238,Q_=88853993,eO=88853994;function tO(e,t,s){const o=[["xmlns:r",HS],["xmlns:a",xS],["xmlns:c",TS]],i=sO({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let n=ST``;if(e.data.title?.text){const t=bI(hC(e.data.backgroundColor)),s=e.data.title.fontSize??R;n=ST`
|
|
4
|
+
<c:title>
|
|
5
|
+
${iO(e.data.title.text,t,s,e.data.title)}
|
|
6
|
+
<c:overlay val="0" />
|
|
7
|
+
</c:title>
|
|
8
|
+
`}let r=ST``;switch(e.data.type){case"bar":r=function(e){const t=e.horizontal?"bar":"col",s=e.dataSets.map(e=>e.backgroundColor??""),o=new qv(e.dataSets.length,s),i=[],n=[];for(const[t,s]of Object.entries(e.dataSets)){const r=bI(o.next()),a=sO({backgroundColor:r,line:{color:r}}),l=ST`
|
|
9
|
+
<c:ser>
|
|
10
|
+
<c:idx val="${t}"/>
|
|
11
|
+
<c:order val="${t}"/>
|
|
12
|
+
${rO(s.trend,r)}
|
|
13
|
+
${lO(s.label)}
|
|
14
|
+
${a}
|
|
15
|
+
${e.labelRange?ST`<c:cat>${dO(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
|
|
16
|
+
<c:val> <!-- x-coordinate values -->
|
|
17
|
+
${uO(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 ST`
|
|
21
|
+
${i.length?ST`
|
|
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
|
+
${bT(i)}
|
|
30
|
+
<c:axId val="${K_}" />
|
|
31
|
+
<c:axId val="${Q_}" />
|
|
32
|
+
</c:barChart>
|
|
33
|
+
${"col"===t?hO("b","c:catAx",K_,Q_,e.axesDesign?.x?.title,e.fontColor):hO("b","c:catAx",K_,Q_,e.axesDesign?.y?.title,e.fontColor,void 0,"maxMin")}
|
|
34
|
+
${"col"===t?hO("l","c:valAx",Q_,K_,e.axesDesign?.y?.title,e.fontColor):hO("l","c:valAx",Q_,K_,e.axesDesign?.x?.title,e.fontColor,void 0,void 0,"max")}
|
|
35
|
+
`:""}
|
|
36
|
+
${n.length?ST`
|
|
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
|
+
${bT(n)}
|
|
45
|
+
<c:axId val="${17781238}" />
|
|
46
|
+
<c:axId val="${88853994}" />
|
|
47
|
+
</c:barChart>
|
|
48
|
+
${hO("b","c:catAx",17781238,88853994,e.axesDesign?.x?.title,e.fontColor,i.length?1:0)}
|
|
49
|
+
${hO("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 qv(t.length,s);let i=t[0];const n=bI(o.next()),r=i.rightYAxis??!1,a=ST`
|
|
51
|
+
<c:ser>
|
|
52
|
+
<c:idx val="0"/>
|
|
53
|
+
<c:order val="0"/>
|
|
54
|
+
${rO(i.trend,n)}
|
|
55
|
+
${lO(i.label)}
|
|
56
|
+
${sO({backgroundColor:n,line:{color:n}})}
|
|
57
|
+
${e.labelRange?ST`<c:cat>${dO(e.labelRange)}</c:cat>`:""}
|
|
58
|
+
<!-- x-coordinate values -->
|
|
59
|
+
<c:val>
|
|
60
|
+
${uO(i.range)}
|
|
61
|
+
</c:val>
|
|
62
|
+
</c:ser>
|
|
63
|
+
`,l=[],c=[];for(let s=1;s<t.length;s++){i=t[s];const n=bI(o.next()),r=sO({backgroundColor:n,line:{color:n}}),a=ST`
|
|
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
|
+
${rO(i.trend,n)}
|
|
74
|
+
${lO(i.label)}
|
|
75
|
+
${r}
|
|
76
|
+
${e.labelRange?ST`<c:cat>${dO(e.labelRange)}</c:cat>`:""}
|
|
77
|
+
<!-- x-coordinate values -->
|
|
78
|
+
<c:val>
|
|
79
|
+
${uO(i.range)}
|
|
80
|
+
</c:val>
|
|
81
|
+
</c:ser>
|
|
82
|
+
`;i.rightYAxis?c.push(a):l.push(a)}const h=e.stacked?100:-20;return ST`
|
|
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?J_:K_}" />
|
|
92
|
+
<c:axId val="${r?eO:Q_}" />
|
|
93
|
+
</c:barChart>
|
|
94
|
+
${l.length?ST`
|
|
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
|
+
${bT(l)}
|
|
100
|
+
<c:axId val="${K_}" />
|
|
101
|
+
<c:axId val="${Q_}" />
|
|
102
|
+
</c:lineChart>
|
|
103
|
+
`:""}
|
|
104
|
+
${c.length?ST`
|
|
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
|
+
${bT(c)}
|
|
110
|
+
<c:axId val="${J_}" />
|
|
111
|
+
<c:axId val="${eO}" />
|
|
112
|
+
</c:lineChart>
|
|
113
|
+
`:""}
|
|
114
|
+
${!r||l.length?ST`
|
|
115
|
+
${hO("b","c:catAx",K_,Q_,e.axesDesign?.x?.title,e.fontColor,0)}
|
|
116
|
+
${hO("l","c:valAx",Q_,K_,e.axesDesign?.y?.title,e.fontColor)}
|
|
117
|
+
`:""}
|
|
118
|
+
${r||c.length?ST`
|
|
119
|
+
${hO("b","c:catAx",J_,eO,e.axesDesign?.x?.title,e.fontColor,l.length||!r?1:0)}
|
|
120
|
+
${hO("r","c:valAx",eO,J_,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 qv(t.length,s),i=t[0],n=t[1],r=bI(o.next()),a=bI(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?ST`<c:cat>${dO(e.labelRange)}</c:cat>`:"",d=ST`
|
|
123
|
+
<c:ser>
|
|
124
|
+
<c:idx val="0"/>
|
|
125
|
+
<c:order val="0"/>
|
|
126
|
+
<c:invertIfNegative val="0" />
|
|
127
|
+
${lO(i.label)}
|
|
128
|
+
${sO({backgroundColor:r,line:{color:r}})}
|
|
129
|
+
${h}
|
|
130
|
+
<!-- x-coordinate values -->
|
|
131
|
+
<c:val>
|
|
132
|
+
${uO(i.range)}
|
|
133
|
+
</c:val>
|
|
134
|
+
</c:ser>
|
|
135
|
+
`,u=ST`
|
|
136
|
+
<c:ser>
|
|
137
|
+
<c:idx val="1"/>
|
|
138
|
+
<c:order val="1"/>
|
|
139
|
+
<c:invertIfNegative val="0" />
|
|
140
|
+
${lO(n.label)}
|
|
141
|
+
${sO({backgroundColor:a,line:{color:a}})}
|
|
142
|
+
${e.labelRange?ST`<c:cat>${dO(e.labelRange)}</c:cat>`:""}
|
|
143
|
+
<!-- x-coordinate values -->
|
|
144
|
+
<c:val>
|
|
145
|
+
${uO(n.range)}
|
|
146
|
+
</c:val>
|
|
147
|
+
</c:ser>
|
|
148
|
+
`;return ST`
|
|
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="${K_}" />
|
|
156
|
+
<c:axId val="${Q_}" />
|
|
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="${J_}" />
|
|
165
|
+
<c:axId val="${eO}" />
|
|
166
|
+
</c:barChart>
|
|
167
|
+
${hO("r","c:catAx",K_,Q_,e.axesDesign?.y?.title,e.fontColor,0,"maxMin","autoZero","high")}
|
|
168
|
+
${hO("b","c:valAx",Q_,K_,e.axesDesign?.x?.title,e.fontColor,0,"maxMin","max","nextTo",l,c,"#0;#0")}
|
|
169
|
+
${hO("t","c:valAx",eO,J_,void 0,e.fontColor,1)}
|
|
170
|
+
${hO("l","c:catAx",J_,eO,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 qv(e.dataSets.length,t),o=[],i=[];for(const[t,n]of Object.entries(e.dataSets)){const r=bI(s.next()),a=sO({line:{width:2.5,style:"solid",color:r}}),l=ST`
|
|
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
|
+
${sO({backgroundColor:r,line:{color:r}})}
|
|
180
|
+
</c:marker>
|
|
181
|
+
${rO(n.trend,r)}
|
|
182
|
+
${lO(n.label)}
|
|
183
|
+
${a}
|
|
184
|
+
${e.labelRange?ST`<c:cat>${dO(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
|
|
185
|
+
<c:val> <!-- x-coordinate values -->
|
|
186
|
+
${uO(n.range)}
|
|
187
|
+
</c:val>
|
|
188
|
+
</c:ser>
|
|
189
|
+
`;n.rightYAxis?i.push(l):o.push(l)}const n=e.stacked?"stacked":"standard";return ST`
|
|
190
|
+
${o.length?ST`
|
|
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
|
+
${bT(o)}
|
|
196
|
+
<c:axId val="${K_}" />
|
|
197
|
+
<c:axId val="${Q_}" />
|
|
198
|
+
</c:lineChart>
|
|
199
|
+
${hO("b","c:catAx",K_,Q_,e.axesDesign?.x?.title,e.fontColor)}
|
|
200
|
+
${hO("l","c:valAx",Q_,K_,e.axesDesign?.y?.title,e.fontColor)}
|
|
201
|
+
`:""}
|
|
202
|
+
${i.length?ST`
|
|
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
|
+
${bT(i)}
|
|
208
|
+
<c:axId val="${17781238}" />
|
|
209
|
+
<c:axId val="${88853994}" />
|
|
210
|
+
</c:lineChart>
|
|
211
|
+
${hO("b","c:catAx",17781238,88853994,e.axesDesign?.x?.title,e.fontColor,o.length?1:0)}
|
|
212
|
+
${hO("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 qv(e.dataSets.length,t),o=[],i=[];for(const[t,n]of Object.entries(e.dataSets)){const r=bI(s.next()),a=ST`
|
|
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
|
+
${sO({backgroundColor:r,line:{color:r}})}
|
|
230
|
+
</c:marker>
|
|
231
|
+
${rO(n.trend,r)}
|
|
232
|
+
${lO(n.label)}
|
|
233
|
+
${e.labelRange?ST`<c:xVal> <!-- x-coordinate values -->
|
|
234
|
+
${uO(e.labelRange)}
|
|
235
|
+
</c:xVal>`:""}
|
|
236
|
+
<c:yVal> <!-- y-coordinate values -->
|
|
237
|
+
${uO(n.range)}
|
|
238
|
+
</c:yVal>
|
|
239
|
+
</c:ser>
|
|
240
|
+
`;n.rightYAxis?i.push(a):o.push(a)}return ST`
|
|
241
|
+
${o.length?ST`
|
|
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
|
+
${bT(o)}
|
|
247
|
+
<c:axId val="${K_}" />
|
|
248
|
+
<c:axId val="${Q_}" />
|
|
249
|
+
</c:scatterChart>
|
|
250
|
+
${hO("b","c:valAx",K_,Q_,e.axesDesign?.x?.title,e.fontColor)}
|
|
251
|
+
${hO("l","c:valAx",Q_,K_,e.axesDesign?.y?.title,e.fontColor)}
|
|
252
|
+
`:""}
|
|
253
|
+
${i.length?ST`
|
|
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
|
+
${bT(i)}
|
|
259
|
+
<c:axId val="${17781238}" />
|
|
260
|
+
<c:axId val="${88853994}" />
|
|
261
|
+
</c:scatterChart>
|
|
262
|
+
${hO("b","c:valAx",17781238,88853994,e.axesDesign?.x?.title,e.fontColor,o.length?1:0)}
|
|
263
|
+
${hO("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=>Ox(e.range,t,s))),i=new qv(o),n=ge(0,o).map(()=>bI(i.next())),r=[];for(const[o,i]of Object.entries(e.dataSets).reverse()){const a=Ox(i.range,t,s),l=[];for(const e of ge(0,a)){const t=sO({backgroundColor:n[e],line:{color:"FFFFFF",width:1.5}});l.push(ST`
|
|
265
|
+
<c:dPt>
|
|
266
|
+
<c:idx val="${e}"/>
|
|
267
|
+
${t}
|
|
268
|
+
</c:dPt>
|
|
269
|
+
`)}r.push(ST`
|
|
270
|
+
<c:ser>
|
|
271
|
+
<c:idx val="${o}"/>
|
|
272
|
+
<c:order val="${o}"/>
|
|
273
|
+
${lO(i.label)}
|
|
274
|
+
${bT(l)}
|
|
275
|
+
${cO({showLeaderLines:!0})}
|
|
276
|
+
${e.labelRange?ST`<c:cat>${dO(e.labelRange)}</c:cat>`:""}
|
|
277
|
+
<c:val>
|
|
278
|
+
${uO(i.range)}
|
|
279
|
+
</c:val>
|
|
280
|
+
</c:ser>
|
|
281
|
+
`)}return ST`
|
|
282
|
+
<c:doughnutChart>
|
|
283
|
+
<c:varyColors val="1" />
|
|
284
|
+
<c:holeSize val="${e.pieHolePercentage??(e.isDoughnut?50:0)}" />
|
|
285
|
+
${cO()}
|
|
286
|
+
${bT(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 qv(e.dataSets.length,t),o=[];for(const[t,i]of Object.entries(e.dataSets)){const n=bI(s.next()),r=sO({line:{width:2.5,style:"solid",color:n}}),a=ST`
|
|
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
|
+
${sO({backgroundColor:n,line:{color:n}})}
|
|
297
|
+
</c:marker>
|
|
298
|
+
${lO(i.label)}
|
|
299
|
+
${r}
|
|
300
|
+
${e.labelRange?ST`<c:cat>${dO(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
|
|
301
|
+
<c:val> <!-- x-coordinate values -->
|
|
302
|
+
${uO(i.range)}
|
|
303
|
+
</c:val>
|
|
304
|
+
</c:ser>
|
|
305
|
+
`;o.push(a)}return ST`
|
|
306
|
+
${ST`
|
|
307
|
+
<c:radarChart>
|
|
308
|
+
<c:radarStyle val="marker"/>
|
|
309
|
+
<c:varyColors val="0"/>
|
|
310
|
+
${bT(o)}
|
|
311
|
+
<c:axId val="${K_}" />
|
|
312
|
+
<c:axId val="${Q_}" />
|
|
313
|
+
</c:radarChart>
|
|
314
|
+
${hO("b","c:catAx",K_,Q_,e.axesDesign?.x?.title,e.fontColor)}
|
|
315
|
+
${hO("l","c:valAx",Q_,K_,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=ST`
|
|
318
|
+
<c:chartSpace ${pT(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
|
+
${sO({backgroundColor:e.data.backgroundColor})}
|
|
330
|
+
</c:plotArea>
|
|
331
|
+
${"none"!==a?function(e,t){return ST`
|
|
332
|
+
<c:legend>
|
|
333
|
+
<c:legendPos val="${e}"/>
|
|
334
|
+
<c:overlay val="0"/>
|
|
335
|
+
${nO(10,t)}
|
|
336
|
+
</c:legend>
|
|
337
|
+
`}(a,l):""}
|
|
338
|
+
</c:chart>
|
|
339
|
+
</c:chartSpace>
|
|
340
|
+
`;return mT(c)}function sO(e){return ST`
|
|
341
|
+
<c:spPr>
|
|
342
|
+
${e.backgroundColor?oO(e.backgroundColor):""}
|
|
343
|
+
${e.line?function(e){const t=[["cmpd","sng"]];e.width&&t.push(["w",_x(e.width)]);const s=e.style?ST`<a:prstDash val="${e.style}"/>`:"";return ST`
|
|
344
|
+
<a:ln ${pT(t)}>
|
|
345
|
+
${oO(e.color)}
|
|
346
|
+
${s}
|
|
347
|
+
</a:ln>
|
|
348
|
+
`}(e.line):""}
|
|
349
|
+
</c:spPr>
|
|
350
|
+
`}function oO(e){return ST`
|
|
351
|
+
<a:solidFill>
|
|
352
|
+
<a:srgbClr val="${e}"/>
|
|
353
|
+
</a:solidFill>
|
|
354
|
+
`}function iO(e,t="000000",s=16,o={}){return ST`
|
|
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
|
+
${oO(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 nO(e=12,t="000000",s=!1,o=!1){return ST`
|
|
374
|
+
<c:txPr>
|
|
375
|
+
<a:bodyPr/>
|
|
376
|
+
<a:lstStyle/>
|
|
377
|
+
<a:p>
|
|
378
|
+
<a:pPr lvl="0">
|
|
379
|
+
<a:defRPr ${pT([["b",s?"1":"0"],["i",o?"1":"0"],["sz",100*e]])}>
|
|
380
|
+
${oO(t)}
|
|
381
|
+
<a:latin typeface="+mn-lt"/>
|
|
382
|
+
</a:defRPr>
|
|
383
|
+
</a:pPr>
|
|
384
|
+
</a:p>
|
|
385
|
+
</c:txPr>
|
|
386
|
+
`}function rO(e,t){if(!e)return ST``;const{type:s,order:o,window:i}=e,n=[];switch(s){case"poly":o&&o>1?(n.push(ST`<c:trendlineType val="poly" />`),n.push(ST`<c:order val="${o}" />`)):n.push(ST`<c:trendlineType val="linear" />`);break;case"movingAvg":n.push(ST`<c:trendlineType val="movingAvg" />`),i&&n.push(ST`<c:period val="${i}" />`);break;default:n.push(ST`<c:trendlineType val="${s}" />`)}return ST`
|
|
387
|
+
<c:trendline>
|
|
388
|
+
${function(e,t){if(!e)return ST``;const s=[["val",e.color?bI(e.color).slice(-6):aO(t)]];return ST`
|
|
389
|
+
<c:spPr>
|
|
390
|
+
<a:ln w="19050" cap="rnd">
|
|
391
|
+
<a:solidFill>
|
|
392
|
+
<a:srgbClr ${pT(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
|
+
${bT(n)}
|
|
402
|
+
</c:trendline>
|
|
403
|
+
`}function aO(e){return bI(Mv(e,.5))}function lO(e){return e?"text"in e&&e.text?ST`
|
|
404
|
+
<c:tx><c:v>${e.text}</c:v></c:tx>
|
|
405
|
+
`:"reference"in e&&e.reference?ST`
|
|
406
|
+
<c:tx>
|
|
407
|
+
${dO(e.reference)}
|
|
408
|
+
</c:tx>
|
|
409
|
+
`:ST``:ST``}function cO({showLeaderLines:e}={showLeaderLines:!1}){return ST`
|
|
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 hO(e,t,s,o,i,n,r=0,a="minMax",l,c="nextTo",h,d,u="General"){const g=i?.color?bI(i.color):n,p=i?.fontSize??12;return ST`
|
|
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?ST`<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?ST`<c:max val="${h}" />`:""}
|
|
430
|
+
${h?ST`<c:min val="${-h}" />`:""}
|
|
431
|
+
</c:scaling>
|
|
432
|
+
${d?ST`<c:majorUnit val="${d}" />`:""}
|
|
433
|
+
<c:axPos val="${e}" />
|
|
434
|
+
<c:tickLblPos val="${c}" />
|
|
435
|
+
${function(e="B7B7B7"){return ST`
|
|
436
|
+
<c:majorGridlines>
|
|
437
|
+
${sO({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
|
+
${iO(i?.text??"",g,p,i)}
|
|
445
|
+
</c:title>
|
|
446
|
+
${nO(10,n)}
|
|
447
|
+
</${t}>
|
|
448
|
+
<!-- <tickLblPos/> omitted -->
|
|
449
|
+
`}function dO(e){return ST`
|
|
450
|
+
<c:strRef>
|
|
451
|
+
<c:f>${e}</c:f>
|
|
452
|
+
</c:strRef>
|
|
453
|
+
`}function uO(e){return ST`
|
|
454
|
+
<c:numRef>
|
|
455
|
+
<c:f>${e}</c:f>
|
|
456
|
+
<c:numCache />
|
|
457
|
+
</c:numRef>
|
|
458
|
+
`}function gO(e,t,s){if(!e)return{attrs:[],node:ST``};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:ST``};var i;return{attrs:[["cm","1"],["t",o]],node:ST`<f t="array" ref="${s}">${mO(e)}</f><v>${(i=t)===Ss.InvalidReference?"#REF!":i}</v>`}}function pO(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&&co(o,Fc)||(o=xx(e,t),i.push(["t","s"])),{attrs:i,node:ST`<v>${o}</v>`}}function mO(e){let t;"="===e[0]&&(e=e.slice(1));try{t=Ff(e)}catch(t){return e}return t=Mf(t,"STRING",fO),t=Mf(t,"FUNCALL",e=>e=function(e){const t=e.value.toUpperCase(),s=e.args,o=$S[t];if(o){const i=mf.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:qS.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()}))),t=Mf(t,"REFERENCE",e=>e.value===Ss.InvalidReference?{...e,value:"#REF!"}:e),t?BD(t):e}function fO(e){const t=e.value.replace(new RegExp('"',"g"),""),s=js(t,Fc);if(s){const o=[];return(Us.test(t)||Hs.test(t))&&o.push("yyyy-mm-dd"),Ws.test(t)&&o.push("hh:mm:ss"),{...e,value:mn(s.value,{format:o.join(" "),locale:Fc})}}return{...e,value:e.value.replace(/\\"/g,'""')}}function vO(e,t){const s=[];for(const o of t)switch(o.rule.type){case"CellIsRule":s.push(bO(o,o.rule,e));break;case"ColorScaleRule":s.push(CO(o,o.rule));break;case"IconSetRule":s.push(yO(o,o.rule));break;case"DataBarRule":s.push(SO(o,o.rule));break;default:console.warn(`Conditional formatting ${o.rule.type} not implemented`)}return s}function bO(e,t,s){const o=IO(e),i=vx(t.operator);o.push(...function(e){const t=vx(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=>ST`<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",xx(r,s)]),ST`
|
|
459
|
+
<conditionalFormatting sqref="${e.ranges.join(" ")}">
|
|
460
|
+
<cfRule ${pT(o)}>
|
|
461
|
+
${bT(n)}
|
|
462
|
+
</cfRule>
|
|
463
|
+
</conditionalFormatting>
|
|
464
|
+
`}function SO(e,t){const s=IO(e);return s.push(["type","dataBar"]),ST`
|
|
465
|
+
<conditionalFormatting sqref="${e.ranges.join(" ")}">
|
|
466
|
+
<cfRule ${pT(s)}>
|
|
467
|
+
<dataBar>
|
|
468
|
+
<cfvo type="min" val="0"/>
|
|
469
|
+
<cfvo type="max" val="100"/>
|
|
470
|
+
<color rgb="${bI(Sv(t.color))}"/>
|
|
471
|
+
</dataBar>
|
|
472
|
+
</cfRule>
|
|
473
|
+
</conditionalFormatting>
|
|
474
|
+
`}function CO(e,t){const s=IO(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(xO(o,s)),n.push([["rgb",bI(Sv(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=>ST`<cfvo ${pT(e)}/>`),l=n.map(e=>ST`<color ${pT(e)}/>`);o.push(ST`
|
|
475
|
+
<conditionalFormatting sqref="${i}">
|
|
476
|
+
<cfRule ${pT(s)}>
|
|
477
|
+
<colorScale>
|
|
478
|
+
${bT(a)}
|
|
479
|
+
${bT(l)}
|
|
480
|
+
</colorScale>
|
|
481
|
+
</cfRule>
|
|
482
|
+
</conditionalFormatting>
|
|
483
|
+
`)}return bT(o)}function yO(e,t){const s=IO(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([...xO(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=>ST`<cfvo ${pT(e)} />`),a=[["iconSet",EO(t.icons)]];wO(t.icons)&&a.push(["reverse","1"]),o.push(ST`
|
|
484
|
+
<conditionalFormatting sqref="${i}">
|
|
485
|
+
<cfRule ${pT(s)}>
|
|
486
|
+
<iconSet ${pT(a)}>
|
|
487
|
+
${bT(r)}
|
|
488
|
+
</iconSet>
|
|
489
|
+
</cfRule>
|
|
490
|
+
</conditionalFormatting>
|
|
491
|
+
`)}return bT(o)}function IO(e){return[["priority",1],["stopIfTrue",e.stopIfTrue?1:0]]}function wO(e){const t=CR[RO(e)];return e.upper===t.bad&&e.lower===t.good}function EO(e){return pS[RO(e)]}function RO(e){return Object.keys(CR).find(t=>Object.values(CR[t]).includes(e.upper))||"dots"}function xO(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=mO(e.value)}catch(s){t=e.value}o.push(["val",t])}return o}function TO(e){const t=e.length;if(0===t)return[];const s=[new rR(`<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(AO(t));break;case"isEqual":case"isNotEqual":case"isGreaterThan":case"isGreaterOrEqualTo":case"isLessThan":case"isLessOrEqualTo":case"isBetween":case"isNotBetween":s.push(DO(t));break;case"isValueInRange":case"isValueInList":s.push(_O(t));break;case"customFormula":s.push(OO(t));break;default:console.warn(`Data validation ${t.criterion.type} is not supported in xlsx.`)}return s.push(new rR("</dataValidations>")),s}function AO(e){const t=e.criterion,s=mO(t.values[0]),o=t.values[1]?mO(t.values[1]):void 0,i=function(e){return Object.keys(tx).find(t=>tx[t]===e)}(e.criterion.type),n=FO(e);return n.push(["type","date"],["operator",i]),o?ST`
|
|
492
|
+
<dataValidation ${pT(n)}>
|
|
493
|
+
<formula1>${So(s,Fc)}</formula1>
|
|
494
|
+
<formula2>${So(o,Fc)}</formula2>
|
|
495
|
+
</dataValidation>
|
|
496
|
+
`:ST`
|
|
497
|
+
<dataValidation ${pT(n)}>
|
|
498
|
+
<formula1>${So(s,Fc)}</formula1>
|
|
499
|
+
</dataValidation>
|
|
500
|
+
`}function DO(e){const t=e.criterion,s=mO(t.values[0]),o=t.values[1]?mO(t.values[1]):void 0,i=function(e){return Object.keys(ex).find(t=>ex[t]===e)}(e.criterion.type),n=FO(e);return n.push(["type","decimal"],["operator",i]),o?ST`
|
|
501
|
+
<dataValidation ${pT(n)}>
|
|
502
|
+
<formula1>${s}</formula1>
|
|
503
|
+
<formula2>${o}</formula2>
|
|
504
|
+
</dataValidation>
|
|
505
|
+
`:ST`
|
|
506
|
+
<dataValidation ${pT(n)}>
|
|
507
|
+
<formula1>${s}</formula1>
|
|
508
|
+
</dataValidation>
|
|
509
|
+
`}function _O(e){const t=e.criterion,s="isValueInRange"===e.criterion.type?mO(t.values[0]):`"${t.values.join(",")}"`,o=FO(e);return o.push(["type","list"]),ST`
|
|
510
|
+
<dataValidation ${pT(o)}>
|
|
511
|
+
<formula1>${s}</formula1>
|
|
512
|
+
</dataValidation>
|
|
513
|
+
`}function OO(e){const t=mO(e.criterion.values[0]),s=FO(e);return s.push(["type","custom"]),ST`
|
|
514
|
+
<dataValidation ${pT(s)}>
|
|
515
|
+
<formula1>${t}</formula1>
|
|
516
|
+
</dataValidation>
|
|
517
|
+
`}function FO(e){return[["allowBlank","1"],["showInputMessage","1"],["showErrorMessage","1"],["errorStyle",e.isBlocking?"":"warning"],["sqref",e.ranges.join(" ")]]}function PO(e,t,s,o){const i=[["xmlns:xdr",yS],["xmlns:r",HS],["xmlns:a",xS],["xmlns:c",TS]],n=[];for(const[i,r]of Object.entries(s))switch(r?.tag){case"chart":n.push(LO(r,t,e[i],o));break;case"image":n.push(kO(r,t,e[i]))}return mT(ST`
|
|
518
|
+
<xdr:wsDr ${pT(i)}>
|
|
519
|
+
${bT(n)}
|
|
520
|
+
</xdr:wsDr>
|
|
521
|
+
`)}function MO(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}=NO(c,o,l),{index:u,offset:g}=NO(c,o,l+r),p=Object.values(t.cols),{index:m,offset:f}=NO(p,s,a),{index:v,offset:b}=NO(p,s,a+n);return{from:{col:m,colOff:f,row:h,rowOff:d},to:{col:v,colOff:b,row:u,rowOff:g}}}function NO(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:_x(s-o+1)};i<e.length-1&&(o+=n.size)}return{index:e.length-1,offset:_x(s-o+1)}}function LO(e,t,s,o){const{from:i,to:n}=MO(e,t),r=Tx(e.id,o),a=[["id",r],["name",`Chart ${r}`],["title","Chart"]];return ST`
|
|
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 ${pT(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="${TS}">
|
|
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 kO(e,t,s){const{from:o,to:i}=MO(e,t),n=Dx(e.id),r=[["id",n],["name",`Image ${n}`],["title","Image"]],a=_x(e.width),l=_x(e.height);return ST`
|
|
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 ${pT(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 VO(e){return Ae(e)?ST``:ST`
|
|
590
|
+
<font>
|
|
591
|
+
${e.bold?ST`<b />`:""}
|
|
592
|
+
${e.italic?ST`<i />`:""}
|
|
593
|
+
${e.underline?ST`<u />`:""}
|
|
594
|
+
${e.strike?ST`<strike />`:""}
|
|
595
|
+
${e.size?ST`<sz val="${e.size}" />`:""}
|
|
596
|
+
${e.color&&e.color.rgb?ST`<color rgb="${bI(e.color.rgb)}" />`:""}
|
|
597
|
+
${e.name?ST`<name val="${e.name}" />`:""}
|
|
598
|
+
</font>
|
|
599
|
+
`}function UO(e){return e?pT([["style",e.style]]):ST``}function HO(e){return e?ST`
|
|
600
|
+
<color ${pT([["rgb",bI(e.color.rgb)]])}/>
|
|
601
|
+
`:ST``}function zO(e,t,s){const o=ST`
|
|
602
|
+
<table ${pT([["id",t],["name",`Table${t}`],["displayName",`Table${t}`],["ref",e.range],["headerRowCount",e.config.numberOfHeaders],["totalsRowCount",e.config.totalRow?1:0],["xmlns",IS],["xmlns:xr",wS],["xmlns:xr3",ES],["xmlns:mc",RS]])}>
|
|
603
|
+
${e.config.hasFilters?function(e){const t=[["ref",e.range]];return ST`
|
|
604
|
+
<autoFilter ${pT(t)}>
|
|
605
|
+
${bT(function(e){const t=[];for(const s of e.filters){const e=ST`
|
|
606
|
+
<filterColumn ${pT([["colId",s.colId]])}>
|
|
607
|
+
${BO(s)}
|
|
608
|
+
</filterColumn>
|
|
609
|
+
`;t.push(e)}return t}(e))}
|
|
610
|
+
</autoFilter>
|
|
611
|
+
`}(e):""}
|
|
612
|
+
${function(e,t){const s=Rt(e.range),o=[];for(const i of ge(0,zt(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(ST`<tableColumn ${pT(r)}/>`)}return ST`
|
|
613
|
+
<tableColumns ${pT([["count",o.length]])}>
|
|
614
|
+
${bT(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 ST`<tableStyleInfo ${pT(t)}/>`}(e)}
|
|
618
|
+
</table>
|
|
619
|
+
`;return mT(o)}function BO(e){const t=e.displayedValues.map(e=>ST`<filter ${pT([["val",e]])}/>`);return ST`
|
|
620
|
+
<filters ${pT(e.displayBlanks?[["blank",1]]:[])}>
|
|
621
|
+
${bT(t)}
|
|
622
|
+
</filters>
|
|
623
|
+
`}function GO(e){if(!Object.values(e).length)return ST``;const t=[];for(const[s,o]of Object.entries(e)){const e=[["min",parseInt(s)+1],["max",parseInt(s)+1],["width",Sx(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(ST`
|
|
624
|
+
<col ${pT(e)}/>
|
|
625
|
+
`)}return ST`
|
|
626
|
+
<cols>
|
|
627
|
+
${bT(t)}
|
|
628
|
+
</cols>
|
|
629
|
+
`}function WO(e,t,s){const o=[],i=new tA(ub(s.id,s.styles)),n=new tA(ub(s.id,s.borders)),r=new tA(ub(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",bx(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=wx(e,Ix(t,c,g,p,m));n&&i.push(["s",n]);let r=[],u=ST``;if(c?.startsWith("=")&&void 0!==d){const e=gO(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}=pO(t,e.sharedStrings))}else if(c&&""!==c){const i=$O(o,a,s),n=qO(o,a,s),l=!(!p||!Bn(t.formats[p]));({attrs:r,node:u}=pO(c,e.sharedStrings,i||n||l))}i.push(...r),h.push(ST`<c ${pT(i)}>
|
|
630
|
+
${u}
|
|
631
|
+
</c>`)}}(h.length||c.size!==_||c.isHidden||c.outlineLevel||c.collapsed)&&o.push(ST`
|
|
632
|
+
<row ${pT(l)}>
|
|
633
|
+
${bT(h)}
|
|
634
|
+
</row>
|
|
635
|
+
`)}return ST`
|
|
636
|
+
<sheetData>
|
|
637
|
+
${bT(o)}
|
|
638
|
+
</sheetData>
|
|
639
|
+
`}function $O(e,t,s){return s.tables.some(s=>{const o=Rt(s.range),i={...o,bottom:o.top};return Ut(e,t,i)})}function qO(e,t,s){return s.tables.some(s=>{if(!s.config.totalRow)return!1;const o=Rt(s.range),i={...o,top:o.bottom};return Ut(e,t,i)})}function ZO(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`:Ss.InvalidReference],["ref",n]];i.push(ST`
|
|
640
|
+
<hyperlink ${pT(r)}/>
|
|
641
|
+
`)}else{const t=[["r:id",Ex(e.relsFiles,`xl/worksheets/_rels/sheet${s}.xml.rels`,{target:zf(a),type:kS,targetMode:"External"})],["ref",n]];i.push(ST`
|
|
642
|
+
<hyperlink ${pT(t)}/>
|
|
643
|
+
`)}}}return i.length?ST`
|
|
644
|
+
<hyperlinks>
|
|
645
|
+
${bT(i)}
|
|
646
|
+
</hyperlinks>
|
|
647
|
+
`:ST``}function jO(e){if(e.length){const t=e.map(e=>ST`<mergeCell ref="${e}" />`);return ST`
|
|
648
|
+
<mergeCells count="${e.length}">
|
|
649
|
+
${bT(t)}
|
|
650
|
+
</mergeCells>
|
|
651
|
+
`}return ST``}function YO(e){const t=e.panes;let s=ST``;if(t&&(t.xSplit||t.ySplit)){const e=mt(t.xSplit,t.ySplit),o=t.xSplit?ST`xSplit="${t.xSplit}"`:"",i=t.ySplit?ST`ySplit="${t.ySplit}"`:"",n=t.xSplit?ST`<selection pane="topRight"/>`:"",r=t.ySplit?ST`<selection pane="bottomLeft"/>`:"",a=t.xSplit&&t.ySplit?ST`<selection pane="bottomRight"/>`:"";s=ST`
|
|
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 ST`
|
|
662
|
+
<sheetViews>
|
|
663
|
+
<sheetView ${pT([["showGridLines",e.areGridLinesVisible?1:0],["workbookViewId",0]])}>
|
|
664
|
+
${s}
|
|
665
|
+
</sheetView>
|
|
666
|
+
</sheetViews>
|
|
667
|
+
`}function XO(e){return e.color?ST`
|
|
668
|
+
<sheetPr>
|
|
669
|
+
<tabColor ${pT([["rgb",bI(e.color)]])} />
|
|
670
|
+
</sheetPr>
|
|
671
|
+
`:""}function KO(e){const t=[],s=function(e){const t=[{},...Object.values(e.borders).map(e=>({left:fT(e.left),right:fT(e.right),bottom:fT(e.bottom),top:fT(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=>zt(Rt(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",CS],["xmlns:r",HS]],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(ST`
|
|
672
|
+
<sheet ${pT(e)} />
|
|
673
|
+
`),Ex(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:_S,target:`worksheets/sheet${s}.xml`})}return uT(mT(ST`
|
|
674
|
+
<workbook ${pT(s)}>
|
|
675
|
+
<sheets>
|
|
676
|
+
${bT(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",SS],["xmlns:r",HS]],a=[["defaultRowHeight",bx(_)],["defaultColWidth",Sx(96)]],l=JO(n,i,o,t,s);o+=n.tables.length;let c=ST``;const h=[];for(const o of n.charts){const n=Tx(o.id,t),r=Ex(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../charts/chart${n}.xml`,type:NS});h.push(r),s.push(uT(tO(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=JR[o];if(void 0===n)continue;const r=`image${Dx(e.id)}.${n}`,a=Ex(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../media/${r}`,type:VS});h.push(a),s.push({path:`xl/media/${r}`,imageSrc:e.data.path})}const d=[...n.charts,...n.images];if(d.length){const e=Ex(t.relsFiles,`xl/worksheets/_rels/sheet${i}.xml.rels`,{target:`../drawings/drawing${i}.xml`,type:MS});s.push(uT(PO(h,n,d,t),`xl/drawings/drawing${i}.xml`,"drawing")),c=ST`<drawing r:id="${e}" />`}const u=ST`
|
|
680
|
+
<worksheet ${pT(r)}>
|
|
681
|
+
${XO(n)}
|
|
682
|
+
${YO(n)}
|
|
683
|
+
<sheetFormatPr ${pT(a)} />
|
|
684
|
+
${GO(n.cols)}
|
|
685
|
+
${WO(t,e,n)}
|
|
686
|
+
${jO(n.merges)}
|
|
687
|
+
${bT(vO(t.dxfs,n.conditionalFormats))}
|
|
688
|
+
${bT(TO(n.dataValidationRules))}
|
|
689
|
+
${ZO(t,e,i)}
|
|
690
|
+
${c}
|
|
691
|
+
${l}
|
|
692
|
+
</worksheet>
|
|
693
|
+
`;s.push(uT(mT(u),`xl/worksheets/sheet${i}.xml`,"sheet"))}const i=ST`
|
|
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="{${US}}">
|
|
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(uT(mT(i),"xl/metadata.xml","metadata")),Ex(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:FS,target:"sharedStrings.xml"}),Ex(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:PS,target:"styles.xml"}),Ex(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:OS,target:"metadata.xml"}),s}(e,s)),t.push(function(e){const t=ST`
|
|
716
|
+
<styleSheet ${pT([["xmlns",mS],["xmlns:r",HS]])}>
|
|
717
|
+
${function(e){const t=[];for(const[s,o]of Object.entries(e)){const e=[["numFmtId",parseInt(s)+164],["formatCode",o.format]];t.push(ST`
|
|
718
|
+
<numFmt ${pT(e)}/>
|
|
719
|
+
`)}return ST`
|
|
720
|
+
<numFmts count="${e.length}">
|
|
721
|
+
${bT(t)}
|
|
722
|
+
</numFmts>
|
|
723
|
+
`}(e.numFmts)}
|
|
724
|
+
${s=e.fonts,ST`
|
|
725
|
+
<fonts count="${s.length}">
|
|
726
|
+
${bT(Object.values(s).map(VO))}
|
|
727
|
+
</fonts>
|
|
728
|
+
`}
|
|
729
|
+
${function(e){const t=[];for(const s of Object.values(e))void 0!==s.reservedAttribute?t.push(ST`
|
|
730
|
+
<fill>
|
|
731
|
+
<patternFill patternType="${s.reservedAttribute}" />
|
|
732
|
+
</fill>
|
|
733
|
+
`):t.push(ST`
|
|
734
|
+
<fill>
|
|
735
|
+
<patternFill patternType="solid">
|
|
736
|
+
<fgColor rgb="${bI(s.fgColor.rgb)}" />
|
|
737
|
+
<bgColor indexed="64" />
|
|
738
|
+
</patternFill>
|
|
739
|
+
</fill>
|
|
740
|
+
`);return ST`
|
|
741
|
+
<fills count="${e.length}">
|
|
742
|
+
${bT(t)}
|
|
743
|
+
</fills>
|
|
744
|
+
`}(e.fills)}
|
|
745
|
+
${function(e){const t=[];for(const s of Object.values(e))t.push(ST`
|
|
746
|
+
<border>
|
|
747
|
+
<left ${UO(s.left)}>
|
|
748
|
+
${HO(s.left)}
|
|
749
|
+
</left>
|
|
750
|
+
<right ${UO(s.right)}>
|
|
751
|
+
${HO(s.right)}
|
|
752
|
+
</right>
|
|
753
|
+
<top ${UO(s.top)}>
|
|
754
|
+
${HO(s.top)}
|
|
755
|
+
</top>
|
|
756
|
+
<bottom ${UO(s.bottom)}>
|
|
757
|
+
${HO(s.bottom)}
|
|
758
|
+
</bottom>
|
|
759
|
+
<diagonal ${UO(s.diagonal)}>
|
|
760
|
+
${HO(s.diagonal)}
|
|
761
|
+
</diagonal>
|
|
762
|
+
</border>
|
|
763
|
+
`);return ST`
|
|
764
|
+
<borders count="${e.length}">
|
|
765
|
+
${bT(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(ST`<xf ${pT(e)}><alignment ${pT(o)} /></xf> `)):t.push(ST`<xf ${pT(e)} />`)}return ST`
|
|
769
|
+
<cellXfs count="${e.length}">
|
|
770
|
+
${bT(t)}
|
|
771
|
+
</cellXfs>
|
|
772
|
+
`}(e.styles)}
|
|
773
|
+
${function(e){const t=[];for(const s of e){let e=ST``;s.font&&(e=VO(s.font));let o=ST``;s.fill&&(o=ST`
|
|
774
|
+
<fill>
|
|
775
|
+
<patternFill>
|
|
776
|
+
<bgColor rgb="${bI(s.fill.fgColor.rgb)}" />
|
|
777
|
+
</patternFill>
|
|
778
|
+
</fill>
|
|
779
|
+
`),t.push(ST`
|
|
780
|
+
<dxf>
|
|
781
|
+
${e}
|
|
782
|
+
${o}
|
|
783
|
+
</dxf>
|
|
784
|
+
`)}return ST`
|
|
785
|
+
<dxfs count="${e.length}">
|
|
786
|
+
${bT(t)}
|
|
787
|
+
</dxfs>
|
|
788
|
+
`}(e.dxfs)}
|
|
789
|
+
</styleSheet>
|
|
790
|
+
`;var s;return uT(mT(t),"xl/styles.xml","styles")}(s)),t.push(function(e){const t=[["xmlns",fS],["count",e.length],["uniqueCount",e.length]],s=e.map(e=>e.trim()!==e?ST`<si><t xml:space="preserve">${e}</t></si>`:ST`<si><t>${e}</t></si>`);return uT(mT(ST`
|
|
791
|
+
<sst ${pT(t)}>
|
|
792
|
+
${bT(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(ST`
|
|
795
|
+
<Relationship ${pT(s)} />
|
|
796
|
+
`)}const o=ST`
|
|
797
|
+
<Relationships xmlns="${vS}">
|
|
798
|
+
${bT(e)}
|
|
799
|
+
</Relationships>
|
|
800
|
+
`;t.push(uT(mT(o),s.path))}return t}(s.relsFiles)),t.push(function(e){const t=[],s=Object.entries(JR).map(([e,t])=>function(e,t){return ST`
|
|
801
|
+
<Default Extension="${e}" ContentType="${t}" />
|
|
802
|
+
`}(t,e));for(const s of e)"contentType"in s&&s.contentType&&t.push(vT("/"+s.path,AS[s.contentType]));const o=[["Extension","rels"],["ContentType","application/vnd.openxmlformats-package.relationships+xml"]],i=[["Extension","xml"],["ContentType","application/xml"]];return uT(mT(ST`
|
|
803
|
+
<Types xmlns="${bS}">
|
|
804
|
+
${bT(Object.values(s))}
|
|
805
|
+
<Default ${pT(o)} />
|
|
806
|
+
<Default ${pT(i)} />
|
|
807
|
+
${bT(t)}
|
|
808
|
+
</Types>
|
|
809
|
+
`),"[Content_Types].xml")}(t)),t.push(uT(mT(ST`
|
|
810
|
+
<Relationships xmlns="${vS}">
|
|
811
|
+
<Relationship ${pT([["Id","rId1"],["Type",DS],["Target","xl/workbook.xml"]])} />
|
|
812
|
+
</Relationships>
|
|
813
|
+
`),"_rels/.rels")),{name:"my_spreadsheet.xlsx",files:t}}function JO(e,t,s,o,i){let n=s;if(!e.tables.length)return new rR("");const r=`xl/worksheets/_rels/sheet${t}.xml.rels`,a=[];for(const t of e.tables){const s=Ex(o.relsFiles,r,{target:`../tables/table${n}.xml`,type:LS});i.push(uT(zO(t,n,e),`xl/tables/table${n}.xml`,"table")),a.push(ST`<tablePart r:id="${s}" />`),n++}return ST`
|
|
814
|
+
<tableParts count="${e.tables.length}">
|
|
815
|
+
${bT(a)}
|
|
816
|
+
</tableParts>
|
|
817
|
+
`}var QO;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(QO||(QO={}));function eF(e,t={}){const s=ae(t);return s.type=e,s}function tF(e){return e.dataRange&&!Kn.test(e.dataRange)?"InvalidGaugeDataRange":"Success"}function sF(e,t){return t(t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):"Success",t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):"Success")}function oF(e,t){if(""===e)switch(t){case"rangeMin":return"EmptyGaugeRangeMin";case"rangeMax":return"EmptyGaugeRangeMax"}return"Success"}function iF(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 nF extends cy{dataRange;sectionRule;background;type="gauge";constructor(e,t,s){super(e,t,s),this.dataRange=Ab(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,tF,e.chainValidations(sF(oF,e.batchValidations),sF(iF,e.batchValidations)),e.chainValidations((s=iF,(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=YS(e,t.dataRange,s);i!==Ss.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=sC(this.sheetId,e,this.dataRange),s=cF(this.sectionRule,t=>this.getters.copyFormulaStringForSheet(this.sheetId,e,t,"moveReference")),o=this.getDefinitionWithSpecificRanges(t,s,e);return new nF(o,e,this.getters)}copyInSheetId(e){const t=cF(this.sectionRule,t=>this.getters.copyFormulaStringForSheet(this.sheetId,e,t,"keepSameReference")),s=this.getDefinitionWithSpecificRanges(this.dataRange,t,e);return new nF(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=oC(this.dataRange,e),i=cF(this.sectionRule,o=>jS(this.sheetId,o,{applyChange:e,sheetId:t,sheetName:s})),n=this.getDefinitionWithSpecificRanges(o,i);return new nF(n,this.sheetId,this.getters)}}function rF(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===Od.number&&(i=e.value,n=e.formattedValue,r=e.format)}let l=lF(e.sheetId,e.sectionRule.rangeMin,t),c=lF(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:Ss.GenericError},inflectionValues:[],colors:[]}}(e,t);c<l&&([l,c]=[c,l]);const h=e.sectionRule.lowerInflectionPoint,d=e.sectionRule.upperInflectionPoint,u=aF(e.sheetId,e.sectionRule.lowerInflectionPoint,l,c,t),g=aF(e.sheetId,e.sectionRule.upperInflectionPoint,l,c,t),p=[],m=[];return void 0!==u&&(p.push({value:u,label:pn(u,r,s,e.humanize),operator:h.operator}),m.push(o.lowerColor)),void 0!==g&&g!==u&&(p.push({value:g,label:pn(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:pn(l,r,s,e.humanize)},maxValue:{value:c,label:pn(c,r,s,e.humanize)},gaugeValue:void 0!==i&&n?{value:i,label:e.humanize?Nn({value:i,format:r},s):n}:void 0,inflectionValues:p,colors:m}}function aF(e,t,s,o,i){const n=lF(e,t.value,i);if(void 0===n)return;return ue("number"===t.type?n:s+(o-s)*n/100,s,o)}function lF(e,t,s){const o=s.evaluateFormula(e,t);return Si(o)?void 0:Co(vi(o),s.getLocale())}function cF(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 hF extends cy{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=iC(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ab(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,dC,uC)}static transformDefinition(e,t,s){return lC(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}=eC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new hF(i,this.sheetId,this.getters)}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,gC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:bI(this.background||c),fontColor:bI(cC(this.background)),dataSets:e,labelRange:t,verticalAxis:pC(s)}}duplicateInDuplicatedSheet(e){const t=tC(this.sheetId,e,this.dataSets),s=sC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new hF(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new hF(t,e,this.getters)}}function dF(e,t){const s=e.getDefinition(),o=kI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"line",data:{labels:o.labels,datasets:UC(s,o)},options:{...dI,layout:nw(0,o),scales:bw(s,o),plugins:{title:Nw(s,t),legend:lw(s),tooltip:Hw(s,o),chartShowValuesPlugin:Ow(s,o)}}},background:e.background||c}}class uF extends cy{dataSets;labelRange;background;legendPosition;type="pie";aggregated;dataSetsHaveTitle;isDoughnut;showValues;pieHolePercentage;constructor(e,t,s){super(e,t,s),this.dataSets=iC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ab(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 lC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,dC,uC)}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=tC(this.sheetId,e,this.dataSets),s=sC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new uF(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new uF(t,e,this.getters)}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,gC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:bI(this.background||c),fontColor:bI(cC(this.background)),dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=eC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new uF(i,this.sheetId,this.getters)}}function gF(e,t){const s=e.getDefinition(),o=VI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:e.isDoughnut?"doughnut":"pie",data:{labels:o.labels,datasets:zC(s,o)},options:{...dI,cutout:e.isDoughnut&&void 0!==s.pieHolePercentage?s.pieHolePercentage+"%":void 0,layout:nw(0,o),plugins:{title:Nw(s,t),legend:cw(s,o),tooltip:zw(s,o),chartShowValuesPlugin:Ow(s,o)}}},background:e.background||c}}class pF extends cy{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=iC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ab(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 lC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,dC,uC)}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=tC(this.sheetId,e,this.dataSets),s=sC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new pF(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new pF(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}=eC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new pF(i,this.sheetId,this.getters)}}function mF(e,t){const s=e.getDefinition(),o=NI(s,e.dataSets,e.labelRange,t),{labels:i,datasets:n}=VC(s,o);return{chartJsConfig:{type:"bar",data:{labels:i,datasets:n},options:{...dI,layout:nw(0,o),scales:Cw(s,o),plugins:{title:Nw(s,t),legend:uw(s),tooltip:Bw(s,o),chartShowValuesPlugin:Mw(s,o),waterfallLinesPlugin:{showConnectorLines:s.showConnectorLines}}}},background:e.background||c}}var fF=Object.freeze({__proto__:null,AbstractChart:cy,BarChart:Jw,CHART_AXIS_CHOICES:vC,CHART_COMMON_OPTIONS:dI,GaugeChart:nF,LineChart:hF,MOVING_AVERAGE_TREND_LINE_XAXIS_ID:JS,PieChart:uF,SPREADSHEET_TO_EXCEL_TRENDLINE_TYPE_MAPPING:QS,ScorecardChart:vy,TREND_LINE_XAXIS_ID:KS,WaterfallChart:pF,adaptChartRange:oC,chartFactory:Jy,chartFontColor:cC,chartMutedFontColor:hC,chartRuntimeFactory:Qy,chartToImageFile:gI,chartToImageUrl:uI,checkDataset:dC,checkLabelRange:uC,createBarChartRuntime:Qw,createDataSets:iC,createGaugeChartRuntime:rF,createLineChartRuntime:dF,createPieChartRuntime:gF,createScorecardChartRuntime:Sy,createWaterfallChartRuntime:mF,drawScoreChart:by,duplicateDataSetsInDuplicatedSheet:tC,duplicateLabelRangeInDuplicatedSheet:sC,formatChartDatasetValue:mC,formatTickValue:fC,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:pC,getPieColors:bC,isTrendLineAxis:CC,shouldRemoveFirstLabel:gC,toExcelDataset:rC,toExcelLabelRange:aC,transformChartDefinitionWithDataSetsWithZone:lC,transformDefinition:tI,truncateLabel:SC,updateChartRangesWithDataSets:eC,validateChartDefinition:eI});function vF(e,t,s){if(!s.model.getters.getChartIdFromFigureId(e))return[];return Yf([{id:"edit",name:vs("Edit"),execute:()=>{s.model.dispatch("SELECT_FIGURE",{figureId:e}),s.openSidePanel("ChartPanel")},icon:"o-spreadsheet-Icon.EDIT",isEnabled:e=>!e.isSmall},bF(e,s),SF(e,s),CF(e,s),yF(e,s),IF(e,t,s)]).filter(e=>!s.model.getters.isReadonly()||e.isReadonlyAllowed)}function bF(e,t,s){return{id:"copy",name:vs("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 SF(e,t){return{id:"cut",name:vs("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 CF(e,t){return{id:"copy_as_image",name:vs("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 gI(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:vs("Chart copied to clipboard")})},isReadonlyAllowed:!0}}function yF(e,t){return{id:"download",name:vs("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 uI(r,o,n);a&&Zy(a,"chart")},isReadonlyAllowed:!0}}function IF(e,t,s){return{id:"delete",name:vs("Delete"),execute:()=>{s.model.dispatch("DELETE_FIGURE",{sheetId:s.model.getters.getActiveSheetId(),figureId:e}),t()},icon:"o-spreadsheet-Icon.TRASH"}}const wF=[KS,JS],EF=["x",...wF];class RF extends gv{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 EF)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 wF){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 xF={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()}};rS.add("zoomWindowPlugin",{register:e=>e.register(xF),unregister:e=>e.unregister(xF)});class TF extends ly{static template="o-spreadsheet-ZoomableChartJsComponent";store;masterChartCanvas=t.useRef("masterChartCanvas");masterChart;mode;hasLinearScale;isBarChart;chartId="";datasetBoundaries={xMin:0,xMax:0};removeEventListeners=()=>{};setup(){this.store=ov(RF),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[KS,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=Ey(this.env,e,this.masterChartCanvas.el?.getBoundingClientRect()),s=t.offsetX;if(!this.masterChart?.chartArea||!this.chart?.scales?.x)return;const{left:o,right:i,top:n,bottom:r}=this.masterChart.chartArea,a=this.upperBound??i,l=this.lowerBound??o;if(s<o-5||s>i+5||t.offsetY<n||t.offsetY>r)return;let c,h,d;e.preventDefault(),e.stopPropagation();const u=s;if((l!==o||a!==i)&&s>l+5&&s<a-5){c=t.offsetX-l,this.mode="moveInMaster";const e=this.store.currentAxesLimits[this.chartId]?.x;h=(e?.max??this.chart.scales.x.max)-(e?.min??this.chart.scales.x.min)}else this.mode="selectInMaster",c=Math.abs(s-l)<5?a:Math.abs(s-a)<5?l:ue(s,o,i),d=this.computeCoordinate(c);const g=this.store.originalAxisLimits[this.chartId].x.min,p=this.store.originalAxisLimits[this.chartId].x.max,m=e=>{let t,s;const{left:o,right:i}=this.masterChart.chartArea;if("moveInMaster"===this.mode)t=this.computeCoordinate(e-c),t<g?t=g:t>p-h&&(t=p-h),s=t+h;else if("selectInMaster"===this.mode){const n=ue(e,o,i);if(Math.abs(c-n)>5){const e=this.computeCoordinate(n);if(void 0===d||void 0===e)return{};t=Math.min(d,e),s=Math.max(d,e)}}return{min:t,max:s}},f=e=>{const t=Ey(this.env,e,this.masterChartCanvas.el?.getBoundingClientRect()).offsetX;if(Math.abs(t-u)<5)return;const{min:s,max:o}=m(t);void 0!==s&&void 0!==o&&this.updateAxisLimits(s,o)},v=e=>{this.removeEventListeners();const t=Ey(this.env,e,this.masterChartCanvas.el?.getBoundingClientRect()).offsetX;if(Math.abs(t-u)>5){let{min:e,max:s}=m(t);void 0!==e&&void 0!==s&&(this.hasLinearScale||("moveInMaster"===this.mode&&h&&!this.isBarChart?(e=Math.round(e)-this.axisOffset,s=e+h):(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",f,!0),window.removeEventListener("pointerup",v,!0)},window.addEventListener("pointermove",f,!0),window.addEventListener("pointerup",v,!0)}onPointerMoveInMasterChart(e){const{offsetX:t,offsetY:s}=Ey(this.env,e,e.target?.getBoundingClientRect());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=Ey(this.env,e,this.masterChartCanvas.el?.getBoundingClientRect()),s=t.offsetX;if(!this.masterChart?.chartArea||!this.chart?.scales.x)return;const{left:o,right:i,top:n,bottom:r}=this.masterChart.chartArea;let a=this.upperBound??i,l=this.lowerBound??o;if(a<l&&([a,l]=[l,a]),s<o-5||s>i+5||t.offsetY<n||t.offsetY>r)return;e.preventDefault(),e.stopPropagation();let{min:c,max:h}=this.store.currentAxesLimits[this.chartId]?.x??this.chart.scales.x;const d=this.store.originalAxisLimits[this.chartId].x;if(!d)return;let u=d.min,g=d.max;if(this.hasLinearScale&&(u=Math.ceil(u)-this.axisOffset,g=Math.floor(g)+this.axisOffset),Math.abs(s-l)<5)c=u;else if(Math.abs(s-a)<5)h=g;else{if(!(l<s&&s<a))return;c=u,h=g}this.updateAxisLimits(c,h)}}const AF=new Fg;AF.add("animatedBackgroundColorChange",{id:"animatedBackgroundColorChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>e?.style?.fillColor!==t?.style?.fillColor,updateAnimation:function(e,t,s,o){const i=Yv([{value:0,color:s.style.fillColor||"#ffffff"},{value:1,color:o.style.fillColor||"#ffffff"}]);t.style.fillColor=i(DF[this.easingFn](e))}}),AF.add("animatedTextColorChange",{id:"animatedTextColorChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>e?.style?.textColor!==t?.style?.textColor,updateAnimation:function(e,t,s,o){const i=Yv([{value:0,color:s.style.textColor||"#000000"},{value:1,color:o.style.textColor||"#000000"}]);t.style.textColor=i(DF[this.easingFn](e))}}),AF.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)*DF[this.easingFn](e);t.dataBarFill={color:o.dataBarFill?.color||s.dataBarFill?.color||"#ffffff",percentage:n}}}),AF.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=DF[this.easingFn](e)}}),AF.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-DF[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)}}),AF.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=DF[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)}}),AF.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-DF[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})}}),AF.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||FF(t,e)))},updateAnimation:function(e,t,s,o){const i=DF[this.easingFn](e),n=o.y+(i-1)*o.height,r=o.y+i*o.height,a=FF(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?OF(o.icons,o):_F(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?OF(s.icons,o):_F(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]}}}),AF.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=DF[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)}}),AF.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-DF[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})}}),AF.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=Yv([{value:0,color:n.color||"#000000"},{value:1,color:r.color||"#000000"}]);a.color=t(DF[this.easingFn](e))}};i("top"),i("bottom"),i("left"),i("right")}}),AF.add("iconChange",{id:"iconChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>!FF(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=DF[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]=_F(o.icons)[e],a.push(c,h)};return l("left"),l("right"),l("center"),{newBoxes:a}}});const DF={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 _F(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 OF(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 FF(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 PF 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=ov(lS));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")):iI(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(){iI(this.canvasEl,{...this.runtime,animationValue:0},void 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 MF(o,s,1e3,e=>iI(this.canvasEl,{...this.runtime,animationValue:e},void 0));return i.start(),i}get canvasEl(){return this.canvas.el}get animationChartId(){return this.props.isFullScreen?this.props.chartId+"-fullscreen":this.props.chartId}}class MF{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)*DF.easeOutQuart(s);this.callback(o),s<1?this.animationFrameId=requestAnimationFrame(this.animate.bind(this)):this.stop()}}const NF=new Fg;NF.add("line",TF),NF.add("bar",TF),NF.add("combo",TF),NF.add("pie",ly),NF.add("gauge",PF),NF.add("scatter",TF),NF.add("scorecard",xy),NF.add("waterfall",TF),NF.add("pyramid",ly),NF.add("radar",ly),NF.add("geo",ly),NF.add("funnel",ly),NF.add("sunburst",ly),NF.add("treemap",ly);class LF extends gv{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 kF 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 _y({color:e.textColor})}getIconColor(e){return _y({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?_y({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 VF(e){return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}function UF(e){if(e)return{x:e.left,y:e.top,width:e.right-e.left,height:e.bottom-e.top}}function HF(){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 zF 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=HF();containerRect;setup(){this.containerRect=function(){const e=t.useState({x:0,y:0,width:0,height:0}),s=t.useComponent(),o=HF();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,UF(Nt(VF(o),VF(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 GF(s,this.containerRect,r,l,this.currentPosition):new WF(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 BF{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 GF extends BF{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 WF extends BF{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 $F 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:$F,Menu:kF,Popover:zF};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 _y({color:e.textColor})}getIconColor(e){return _y({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=>Ny(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:ky(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,qy(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?_y({width:this.props.width+"px"}):""}}class qF extends t.Component{static template="o-spreadsheet-ChartDashboardMenu";static components={MenuPopover:$F};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=ov(LF)}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=Vy(e.currentTarget);const t=this.env.model.getters.getFigureIdFromChartId(this.props.chartId);this.menuState.menuItems=vF(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:vs(s?"Exit Full Screen":"Full Screen"),class:"text-muted fa "+(s?"fa-compress":"fa-expand"),onClick:()=>{this.fullScreenFigureStore.toggleFullScreenFigure(t)}}}}class ZF 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:qF,MenuPopover:$F};carouselTabsRef=t.useRef("carouselTabs");carouselTabsDropdownRef=t.useRef("carouselTabsDropdown");menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});hiddenItems=[];animationStore;fullScreenFigureStore;setup(){this.animationStore=ov(lS),this.fullScreenFigureStore=ov(LF),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=NF.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 __(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 _y(e)}get title(){return this.carousel.title?.text??""}get titleStyle(){return _y(Dy(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=Vy(e),o=Array.from(e.children);for(const e of o)e.style.display="block";const i=o.map(e=>Vy(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=ky(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=Yf(s)}toggleFullScreen(){"chart"===this.selectedCarouselItem?.type&&this.fullScreenFigureStore.toggleFullScreenFigure(this.props.figureUI.id)}get fullScreenButtonTitle(){return this.props.isFullScreen?vs("Exit Full Screen"):vs("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?.(Vy(t))}}class jF 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:qF};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=NF.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}class YF 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 XF=new Fg;XF.add("chart",{Component:jF,SidePanelComponent:"ChartPanel",menuBuilder:vF}),XF.add("image",{Component:YF,keepRatio:!0,minFigSize:20,borderWidth:0,menuBuilder:function(e,t,s){return Yf([bF(e,s,vs("Image copied to clipboard")),SF(e,s),{id:"reset_size",name:vs("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}=Fy(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:vs("Download"),execute:async()=>{s.model.dispatch("SELECT_FIGURE",{figureId:e});Zy(s.model.getters.getImagePath(e),"image")},icon:"o-spreadsheet-Icon.DOWNLOAD"},IF(e,t,s)])}}),XF.add("carousel",{Component:ZF,menuBuilder:function(e,t,s){const o=t=>"chart"===t.model.getters.getSelectedCarouselItem(e)?.type;return Yf([{id:"edit_carousel",name:vs("Edit carousel"),execute:()=>{s.model.dispatch("SELECT_FIGURE",{figureId:e}),s.openSidePanel("CarouselPanel",{figureId:e})},icon:"o-spreadsheet-Icon.EDIT",isEnabled:e=>!e.isSmall},{...bF(e,s,vs("Carousel copied to clipboard")),name:vs("Copy carousel")},{...SF(e,s),name:vs("Cut carousel")},{...IF(e,t,s),name:vs("Delete carousel"),separator:!0},{id:"edit_chart",name:vs("Edit chart"),execute:()=>{s.model.dispatch("SELECT_FIGURE",{figureId:e}),s.openSidePanel("ChartPanel",{})},icon:"o-spreadsheet-Icon.EDIT",isEnabled:e=>!e.isSmall,isVisible:o},{...CF(e,s),isVisible:o,name:vs("Copy chart as image")},{...yF(e,s),isVisible:o,name:vs("Download chart")},{id:"popout_chart",name:vs("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 vs("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=>!_C(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 KF 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:$F};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 XF}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 _y({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)",_y(t)}setup(){const e=XF.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=Gy(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){if(this.env.isDashboard())return;const t=Ey(this.env,e);this.openContextMenu({x:t.clientX,y:t.clientY,width:0,height:0})}showMenu(){this.openContextMenu(ky(this.menuButtonRef))}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.anchorRect=e,this.menuState.menuItems=XF.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 JF extends gv{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 QF{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 QF(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds())}static now(){const e=new Date;return new QF(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 eP=new QF(1899,11,30);QF.now().getFullYear(),QF.now().getMonth();const tP=QF.fromTimestamp(0).getTime()-eP.getTime();PC(function(e){return e=RC(e),new RegExp(`(?:^-?\\d+(?:${e}?\\d*(?:e(\\+|-)?\\d+)?)?|^-?${e}\\d+)(?!\\w|!)`)}),PC(function(e){const t=RC(e.decimalSeparator),s="(?:\\s*"+`(?:\\d+(?:${RC(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")}),PC(function(e){return new RegExp(`[$€${RC(e.thousandsSeparator||"")}]`,"g")});const sP=function(e,...t){return new oP(e,t)};class oP 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 iP;function nP(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"}(iP||(iP={})),PC(function(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"")}),PC(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")}),sP("[[FUNCTION_NAME]] has no valid input data.");const rP=new Set("$+-/():!^&~{}<>= ");function aP(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 rP.has(e.current)?{type:"CHAR",value:e.shift()}:null}function lP(e){return","===e.current?(e.shift(),{type:"THOUSANDS_SEPARATOR",value:","}):null}function cP(e){return"@"===e.current?(e.shift(),{type:"TEXT_PLACEHOLDER",value:"@"}):null}function hP(e){return"."===e.current?(e.shift(),{type:"DECIMAL_POINT",value:"."}):null}function dP(e){return"%"===e.current?(e.shift(),{type:"PERCENT",value:"%"}):null}function uP(e){if("0"===e.current||"#"===e.current){const t=e.current;return e.shift(),{type:"DIGIT",value:t}}return null}const gP=new Set("dmqyhsa");function pP(e){if(!gP.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 mP(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 fP={};function vP(e){let t=fP[e];return void 0===t&&(t=function(e){const t=function(e){const t=new NC(e),s=[];let o=[];for(s.push(o);!t.isOver();){if(";"===t.current){o=[],s.push(o),t.shift();continue}const e=uP(t)||nP(t)||aP(t)||lP(t)||hP(t)||dP(t)||pP(t)||cP(t)||mP(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=SP(t[0])||bP(t[0])||CP(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=SP(t[1])||bP(t[1]);if(t[1]?.length&&!o)throw new Error("Invalid second format part of: "+e);const i=SP(t[2])||bP(t[2]);if(t[2]?.length&&!i)throw new Error("Invalid third format part of: "+e);const n=CP(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),fP[e]=t),t}function bP(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 SP(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 CP(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 yP="REPEATED_CHAR_PLACEHOLDER_",IP={0:sP("January"),1:sP("February"),2:sP("March"),3:sP("April"),4:sP("May"),5:sP("June"),6:sP("July"),7:sP("August"),8:sP("September"),9:sP("October"),10:sP("November"),11:sP("December")},wP={0:sP("Sunday"),1:sP("Monday"),2:sP("Tuesday"),3:sP("Wednesday"),4:sP("Thursday"),5:sP("Friday"),6:sP("Saturday")};function EP(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=RP(e,vP(t)).format;return s&&"text"===s.type?xP(e,s,o):e}case"number":t||(t=function(e){let{integerDigits:t,decimalDigits:s}=DP(e);if(!s)return"0";const o=t.replace("-","").length;if(o+2>11)return"0";const i=11-o-1;return({decimalDigits:s}=DP(e,Math.min(i,s.length))),s?"0."+"0".repeat(s.length):"0"}(e));const i=vP(t),{format:n,isNegativeFormat:r}=RP(e,i);if(!n)return e.toString();if("text"===n.type)return xP(e.toString(),n,o);if(r&&(e=Math.abs(e)),"date"===n.type)return TP(function(e,t){const s=function(e){const t=Math.trunc(e),s=QF.fromTimestamp(864e5*t-tP);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+=FP(s,e.value,o);break;case"REPEATED_CHAR":i+=yP+e.value;break;default:i+=e.value}return i}(e,n),o);const a=e<0,l=TP(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}=DP(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=yP+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+=yP+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 RP(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 xP(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+=yP+s.value}return TP(o,s)}function TP(e,t){const s=e.indexOf(yP);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 AP=[];function DP(e,t=20){const s=e.toString();if(s.includes("e"))return function(e,t=20){let s=AP[t];s||(s=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),AP[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(OP)?.[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:_P(n||"")}}function _P(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const OP=/^0+/;function FP(e,t,s){switch(t){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return wP[e.getDay()].slice(0,3);case"dddd":return wP[e.getDay()].toString();case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return IP[e.getMonth()].slice(0,3);case"mmmm":return IP[e.getMonth()].toString();case"mmmmm":return IP[e.getMonth()].slice(0,1);case"qq":return sP("Q%(quarter)s",{quarter:e.getQuarter()}).toString();case"qqqq":return sP("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()-eP.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 PP(e,t){const s=EP(e,{format:"0,00",locale:t});return sP("Oops—this pivot table is quite large (%s cells). Try simplifying it using the side panel.",s)}PC(function(e){if(!e)return!1;try{return"date"===vP(e).positive.type}catch(e){return!1}}),PC(function(e){return new RegExp(`[0-9]+${RC(e.decimalSeparator)}[0-9]`)}),sP("The range is invalid"),sP("The argument is missing. Please provide a value"),sP("The second argument is missing. Please provide a value"),sP("The minpoint must be a number"),sP("The midpoint must be a number"),sP("The maxpoint must be a number"),sP("The first value must be a number"),sP("The second value must be a number"),sP("Minimum must be smaller then Maximum"),sP("Minimum must be smaller then Midpoint"),sP("Midpoint must be smaller then Maximum"),sP("Lower inflection point must be smaller than upper inflection point"),sP("Invalid Minpoint formula"),sP("Invalid Maxpoint formula"),sP("Invalid Midpoint formula"),sP("Invalid upper inflection point formula"),sP("Invalid lower inflection point formula"),sP("A range needs to be defined"),sP("At least one of the provided values is an invalid formula"),sP("The rule is invalid for an unknown reason"),sP("Color scale"),sP("Icon set"),sP("Data bar"),sP("Series"),sP("Background color"),sP("Stacked bar chart"),sP("Stacked line chart"),sP("Stacked area chart"),sP("Stacked column chart"),sP("Cumulative data"),sP("Treat labels as text"),sP("Aggregate"),sP("The chart definition is invalid for an unknown reason"),sP("The dataset is invalid"),sP("Labels are invalid"),sP("The key value is invalid"),sP("The baseline value is invalid"),sP("The data range is invalid"),sP("A minimum range limit value is needed"),sP("The minimum range limit value must be a number"),sP("A maximum range limit value is needed"),sP("The maximum range limit value must be a number"),sP("The lower inflection point value must be a number"),sP("The upper inflection point value must be a number"),sP("Blues"),sP("Cividis"),sP("Greens"),sP("Greys"),sP("Oranges"),sP("Purples"),sP("Rainbow"),sP("Reds"),sP("Viridis"),sP("Custom"),sP("Merged cells are preventing this operation. Unmerge those cells and try again."),sP("The header row of a table can't be moved."),sP("Cannot split the selection for an unknown reason"),sP("There is no match for the selected separator in the selection"),sP("Only a selection from a single column can be split"),sP("Splitting will overwrite existing content"),sP("Cannot remove duplicates for an unknown reason"),sP("Please select only one range of cells"),sP("Please select a range of cells containing values."),sP("Please select at latest one column to analyze."),sP("This operation is not possible due to a merge. Please remove the merges first than try again."),sP("today"),sP("yesterday"),sP("tomorrow"),sP("in the past week"),sP("in the past month"),sP("in the past year"),sP("today"),sP("yesterday"),sP("tomorrow"),sP("one week ago"),sP("one month ago"),sP("one year ago"),sP("The value must not be empty"),sP("The value must be a number"),sP("The value must be a date"),sP("The value must be a valid range"),sP("The formula must be valid"),sP("The range is invalid."),sP("One or more of the provided criteria values are invalid. Please review and correct them."),sP("One or more of the provided criteria values are missing."),sP("The rule is invalid for an unknown reason."),sP("The table zone is invalid for an unknown reason"),sP("You cannot create overlapping tables."),sP("A table can only be created on a continuous selection."),sP("The range is invalid"),sP("The range is out of the sheet"),sP("Filter button"),sP("Header row(s)"),sP("Banded rows"),sP("First column"),sP("Last column"),sP("Banded columns"),sP("Automatically autofill formulas"),sP("Total row"),sP("Auto-adjust to formula result"),sP("Cannot have filters without a header row"),sP("For tables based on array formulas only"),sP("No calculations"),sP("% of grand total"),sP("% of column total"),sP("% of row total"),sP("% of"),sP("% of parent row total"),sP("% of parent column total"),sP("% of parent total"),sP("Difference from"),sP("% difference from"),sP("Running total"),sP("% Running total"),sP("Rank smallest to largest"),sP("Rank largest to smallest"),sP("Index"),sP("Displays the value that is entered in the field."),sP("Displays values as a percentage of the grand total of all the values or data points in the report."),sP("Displays all the values in each column or series as a percentage of the total for the column or series."),sP("Displays the value in each row or category as a percentage of the total for the row or category."),sP("Displays values as a percentage of the value of the Base item in the Base field."),sP("Calculates values as follows:\n(value for the item) / (value for the parent item on rows)"),sP("Calculates values as follows:\n(value for the item) / (value for the parent item on columns)"),sP("Calculates values as follows:\n(value for the item) / (value for the parent item of the selected Base field)"),sP("Displays values as the difference from the value of the Base item in the Base field."),sP("Displays values as the percentage difference from the value of the Base item in the Base field."),sP("Displays the value for successive items in the Base field as a running total."),sP("Calculates the value as a percentage for successive items in the Base field that are displayed as a running total."),sP("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."),sP("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."),sP("Calculates values as follows:\n((value in cell) x (Grand Total of Grand Totals)) / ((Grand Row Total) x (Grand Column Total))");const MP=new Fg;class NP extends gv{mutators=["open","close"];persistentPopover;hoveredCell=this.get(JF);handle(e){if("ACTIVATE_SHEET"===e.type)this.close()}open({col:e,row:t},s){const o=this.getters.getActiveSheetId();MP.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=MP.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=MP.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(jt({col:e,row:t}))}}class LP 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,jt(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 kP={onHover:(e,t)=>{const s=t.getEvaluatedCell(e);return s.type===Od.error&&s.message||t.getInvalidDataValidationMessage(e)?{isOpen:!0,props:{cellPosition:e},Component:LP,cellCorner:"top-right"}:{isOpen:!1}}};function VP(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 UP(e,t,s,o,i);const r=e.model.getters.getContiguousZone(t,o);Lt(r,o)?UP(e,t,s,o,i):e.askConfirmation(vs("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?"),()=>UP(e,t,s,r,i),()=>UP(e,t,s,o,i))}function UP(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(vs("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(vs("Cannot sort a zone with array formulas."))}}class HP 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 zP 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:HP};state=t.useState({isCollapsed:this.props.isInitiallyCollapsed});toggle(){this.state.isCollapsed=!this.state.isCollapsed}}class BP extends t.Component{static props={criterion:Object,onCriterionChanged:Function,disableFormulas:{type:Boolean,optional:!0},autofocus:{type:Boolean,optional:!0}};setup(){const e=ov(mv);"inactive"!==e.activeComposer.editionMode&&e.activeComposer.stopEdition()}updateCriterion(e){const t={...this.props.criterion,...e};this.props.onCriterionChanged(t)}}class GP{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 WP={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function $P(e,t){const s=WP[e.key];e.shiftKey?t.resizeAnchorZone(s,$y(e)?"end":1):t.moveAnchorCell(s,$y(e)?"end":1)}class qP 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 _y({color:e.color||"#000000",background:e.backgroundColor})}}class ZP{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=Uy(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&&jP(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?.(Vy(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 Hy(this.el)}getText(){let e="",t=!0,s=!1;const o=Uy(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=JP(i.value)):i.value.hasChildNodes()||("BR"!==i.value.nodeName||s||(e+=X),e+=i.value.textContent);return e}}function jP(e,t){const s=(e.color?yv(e.color):"")===(t.style?.color?yv(t.style.color):""),o=Me(e.classes,[...t.classList]),i=t.innerText===e.value;return s&&o&&i}const YP=new DOMParser,XP=YP.parseFromString("<br>","text/html").body.firstChild,KP=YP.parseFromString("<span><br></span>","text/html").body.firstChild;function JP(e){if(e.childNodes.length>1)return!1;const t=e.firstChild?.cloneNode(!0);return!t||t instanceof Element&&(t.removeAttribute("class"),t.removeAttribute("style"),t.isEqualNode(XP)||t.isEqualNode(KP)||!1)}class QP extends t.Component{static template="o-spreadsheet-FunctionDescriptionProvider";static props={functionDescription:Object,argsToFocus:Array,repeatingArgGroupIndex:{type:Number,optional:!0}};static components={Collapse:HP};state=t.useState({isCollapsed:!0});toggle(){this.state.isCollapsed=!this.state.isCollapsed}getContext(){return this.props}get formulaHeaderContent(){const{functionDescription:e,repeatingArgGroupIndex:t,argsToFocus:s}=this.props,o=this.env.model.getters.getLocale().formulaArgSeparator+" ",i=[{content:e.name+" ( "}];for(let n=0;n<e.args.length;n++){const r=e.args[n],a=r.repeating;if(n>0&&i.push({content:o}),a){const a=r.optional||(t??0)>0,l=e.args.slice(n,n+e.nbrArgRepeating).map(e=>e.name);t&&i.push({content:"... "+o}),a&&i.push({content:"["});for(let e=0;e<l.length;e++){const r=l[e],a=n+e,c=s.includes(a);i.push({content:r+((t??0)+1),focused:c}),e<l.length-1&&i.push({content:o})}a&&i.push({content:"]"}),i.push({content:o+"["});for(let e=0;e<l.length;e++){const s=l[e];i.push({content:s+((t??0)+2)}),e<l.length-1&&i.push({content:o})}i.push({content:"]"+o+"... "}),n+=e.nbrArgRepeating-1}else{const e=r.optional||r.default,t=s.includes(n);e&&i.push({content:"["}),i.push({content:r.name,focused:t}),e&&i.push({content:"]"})}}return i.push({content:" )"}),i}}class eM extends t.Component{static template="o-spreadsheet-SpeechBubble";static props={content:String,anchorRect:Object};static components={};spreadsheetRect=HF();bubbleRef=t.useRef("bubble");setup(){t.useEffect(()=>{const e=this.bubbleRef.el;if(!e)return;const t=this.props.anchorRect,s=Vy(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 tM=mf.content,sM=300;class oM 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:qP,FunctionDescriptionProvider:QP,SpeechBubble:eM};static defaultProps={inputStyle:"",isDefaultFocus:!1,inputMode:"text",showAssistant:!0};DOMFocusableElementStore;composerRef=t.useRef("o_composer");contentHelper=new ZP(this.composerRef.el);composerState=t.useState({positionStart:0,positionEnd:0,hoveredRect:void 0});functionDescriptionState=t.useState({showDescription:!1,functionDescription:{},argsToFocus:[],repeatingArgGroupIndex:0});assistant=t.useState({forcedClosed:!1});compositionActive=!1;spreadsheetRect=HF();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,sM);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+sM>this.props.delimitation.width&&(t.right="0px")}else t["max-height"]=this.spreadsheetRect.height-e.bottom-1+"px",e.left+sM+15+9>this.spreadsheetRect.width&&(t.right="9px");return t}get assistantStyle(){const e=this.assistantStyleProperties;return _y({"max-height":e["max-height"],width:e.width,"min-width":e["min-width"]})}get assistantContainerStyle(){const e=this.assistantStyleProperties;return _y({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=ov(GP),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 $P(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[Gy(e)]||this.keyCodeMapping[Gy(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()&&!Yy()||(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=Pv(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 tM&&"UNKNOWN"!==t.type){const o=tM[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,this.functionDescriptionState.repeatingArgGroupIndex=this.getRepeatingArgGroupIndex(o,n,i)}}}getRepeatingArgGroupIndex(e,t,s){const{minArgRequired:o,maxArgPossible:i,nbrArgRepeating:n}=e;if(!n)return;const r=(n?Math.ceil((t-o)/n):0)*n+o;return hs(e,Math.max(Math.min(i,r),o))(s).repeatingGroupIndex??0}getArgsToFocus(e,t,s,o){const{nbrArgRepeating:i,minArgRequired:n,nbrOptionalNonRepeatingArgs:r,maxArgPossible:a}=t;if(e){const e=hs(t,Math.max(Math.min(a,s),n))(o)?.index;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=hs(t,e)(o)?.index;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 iM(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(Pf(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})}(If(e,t)))))}class nM{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 rM(e,t,s){const o=(t.startsWith("=")?iM(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(ir).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 aM=new Fg;function lM(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=Pv(yv(l),t.fillAlpha??.12),c.fillRect(i,n,r,a)),c.restore()}class cM extends gv{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}=zt(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){lM(e,t,this.getters.getVisibleRect(t.range.zone))}}}class hM{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 dM extends gv{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 uM extends gv{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 dM(this.get);hoveredTokens=[];hoveredContentEvaluation="";autoCompleteKeepLast=new nM;notificationStore=this.get(hM);highlightStore=this.get(cM);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=rM(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}=sr(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=Jc(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=Pf(e);let o;for(const e of Nf(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 ys)return e;throw t}}evaluationResultToDisplayString(e){const t=this.getters.getLocale();if(_s(e)){const s=","===t.decimalSeparator?"/":",";return`{${Ho(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 mn(t,{locale:this.getters.getLocale(),format:e.format});case"string":return fo(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=jt({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("%")&&co(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=jt({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 Jc(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)?iM(e,t):[];this.currentTokens.filter(e=>"SPACE"!==e.type).length>1e3&&s&&this.notificationStore.raiseError(vs("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 aM.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}=sr(t.value),n=i||this.getters.getSheetName(this.sheetId);if(!Cb(this.getters.getSheetName(s),n))return!1;const r=this.getters.getRangeFromSheetXC(s,o);return Lt(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}=sr(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 mf.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===Jt(o)?this.model.getters.expandZone(s,o):o,Lt(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 bv[t%bv.length]};return this.getReferencedRanges().map(s=>{const o=this.getters.getRangeString(s,e),{numberOfRows:i,numberOfCols:n}=zt(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=nS(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)||Pc.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 gM extends uM{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?rr(t,"colrow"):t}getComposerContent(){let e=this._currentContent;if("inactive"===this.editionMode){const t=this.args().defaultRangeSheetId;e=If(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:eh(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 pM 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},autofocus:{type:Boolean,optional:!0},getContextualColoredSymbolToken:{type:Function,optional:!0}};static components={Composer:oM};static defaultProps={composerContent:"",defaultStatic:!1};composerFocusStore;standaloneComposerStore;composerInterface;spreadsheetRect=HF();setup(){this.composerFocusStore=ov(mv);const e=iv(gM,()=>({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},t.onMounted(()=>{this.props.autofocus&&"inactive"===this.focus&&(this.composerFocusStore.focusComposer(this.composerInterface,{}),this.composerFocusStore.activeComposer.editionMode)})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get composerStyle(){return this.props.invalid?_y({padding:"1px 0px 0px 0px"}):_y({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 mM 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:pM};inputRef=t.useRef("input");setup(){t.useEffect(()=>{this.props.focused&&this.inputRef.el&&this.inputRef.el.focus()},()=>[this.props.focused,this.inputRef.el])}state=t.useState({shouldDisplayError:!!this.props.value});get placeholder(){return"onlyFormulas"===this.allowedValues?vs("Formula"):"onlyLiterals"===this.allowedValues?vs("Value"):vs("Value or formula")}get allowedValues(){const e=nA.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,autofocus:this.props.focused}}get errorMessage(){if(this.state.shouldDisplayError)return this.env.model.getters.getDataValidationInvalidCriterionValueMessage(this.props.criterionType,Qc(this.props.value,this.env.model.getters.getLocale()))}}const fM={today:vs("today"),yesterday:vs("yesterday"),tomorrow:vs("tomorrow"),lastWeek:vs("in the past week"),lastMonth:vs("in the past month"),lastYear:vs("in the past year"),exactDate:vs("exact date")};class vM extends BP{static template="o-spreadsheet-DataValidationDateCriterion";static components={CriterionInput:mM};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(fM).map(e=>({value:e,title:fM[e]}))}}class bM extends BP{static template="o-spreadsheet-DoubleInputCriterionForm";static components={CriterionInput:mM};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 SM extends BP{static template="o-spreadsheet-SingleInputCriterionForm";static components={CriterionInput:mM};onValueChanged(e){const t=ae(this.props.criterion);t.values[0]=e,this.updateCriterion(t)}}function CM(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 yM=216;class IM 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:zF};COLORS=T;state=t.useState({showGradient:!1,currentHslaColor:Iv(this.props.currentColor)?{...Ov(this.props.currentColor),a:1}:{h:0,s:100,l:100,a:1},customHexColor:Iv(this.props.currentColor)?yv(this.props.currentColor):""});get colorPickerStyle(){return void 0!==this.props.maxHeight&&this.props.maxHeight<=0?_y({display:"none"}):""}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"bottom-left",verticalOffset:0}}get gradientHueStyle(){return _y({background:`hsl(${this.state.currentHslaColor?.h||0} 100% 50%)`})}get sliderStyle(){const e=this.state.currentHslaColor?.h||0;return _y({"margin-left":`${ue(Math.round(e/360*yM),1,yM)-9}px`})}get pointerStyle(){const{s:e,l:t}=this.state.currentHslaColor||{s:0,l:0};return _y({left:`${-8+Math.round(yM*ue(e/100,0,1))}px`,top:`${-8+Math.round(186*ue(1-2*t/(200-e),0,1))}px`,background:_v(this.state.currentHslaColor)})}get colorPreviewStyle(){return _y({"background-color":_v(this.state.currentHslaColor)})}get checkmarkColor(){return cC(this.props.currentColor)}get isHexColorInputValid(){return!this.state.customHexColor||Iv(this.state.customHexColor)}setCustomGradient({x:e,y:t}){const s=ue(e,0,yM),o=ue(t,0,186),i=s/yM,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/yM,0,359));this.updateColor({h:t})}updateColor(e){this.state.currentHslaColor={...this.state.currentHslaColor,...e},this.state.customHexColor=_v(this.state.currentHslaColor)}onColorClick(e){e&&this.props.onColorPicked(yv(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;CM(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);CM(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,Iv(t)&&(this.state.currentHslaColor={...Ov(t),a:1})}addCustomColor(e){(function(e){try{return _v(e),!0}catch(e){return!1}})(this.state.currentHslaColor)&&Iv(this.state.customHexColor)&&this.props.onColorPicked(yv(this.state.customHexColor))}isSameColor(e,t){return function(e,t,s=0){if(!Iv(e)||!Iv(t))return!1;const o=Tv(e),i=Tv(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 wM extends t.Component{static template="o_spreadsheet.Section";static props={class:{type:String,optional:!0},title:{type:String,optional:!0},slots:Object}}class EM extends t.Component{static template="o-spreadsheet.RoundColorPicker";static components={Section:wM,ColorPicker:IM};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 Vy(this.colorPickerButtonRef.el)}get buttonStyle(){return _y({background:this.props.currentColor})}}function RM(){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 DM(r.scrollableContainerEl):new AM(r.scrollableContainerEl);e=new xM({...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=CM(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 xM{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"),_y(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 TM{el;constructor(e){this.el=e}get containerRect(){return this.el.getBoundingClientRect()}}class AM extends TM{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 DM extends TM{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 _M{mutators=["focus","unfocus"];focusedElement=null;focus(e){this.focusedElement=e}unfocus(e){this.focusedElement&&this.focusedElement===e&&(this.focusedElement=null)}}class OM extends gv{initialRanges;inputHasSingleRange;colors;disabledRanges;mutators=["resetWithRanges","focusById","unfocus","addEmptyRange","removeRange","changeRange","reset","confirm","updateColors","updateDisabledRanges"];ranges=[];focusedRangeIndex=null;inputSheetId;focusStore=this.get(_M);highlightStore=this.get(cM);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,jt({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}=sr(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 Lt(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 qv(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 qv(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}=sr(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}=sr(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},autofocus:{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=RM();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=iv(OM,this.props.ranges,this.props.hasSingleRange||!1,this.props.colors,this.props.disabledRanges),this.props.autofocus&&this.store.focusById(this.store.selectionInputs[0]?.id),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?_y({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(),$P(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 PM={list:10,text:20,date:30,number:40,misc:50},MM=new Fg;function NM(e,t){const s=MM.getAll().filter(e=>t.has(e.type)).sort((e,t)=>e.category===t.category?e.sequence-t.sequence:PM[e.category]-PM[t.category]);return Yf(s.map((t,o)=>({name:nA.get(t.type).name,id:t.type,separator:t.category!==s[o+1]?.category,execute:()=>e(t.type)})))}MM.add("containsText",{type:"containsText",component:SM,category:"text",sequence:10}),MM.add("notContainsText",{type:"notContainsText",component:SM,category:"text",sequence:20}),MM.add("beginsWithText",{type:"beginsWithText",component:SM,category:"text",sequence:25}),MM.add("endsWithText",{type:"endsWithText",component:SM,category:"text",sequence:26}),MM.add("isEqualText",{type:"isEqualText",component:SM,category:"text",sequence:30}),MM.add("isEmail",{type:"isEmail",component:void 0,category:"text",sequence:40}),MM.add("isLink",{type:"isLink",component:void 0,category:"text",sequence:50}),MM.add("dateIs",{type:"dateIs",component:vM,category:"date",sequence:20}),MM.add("dateIsBefore",{type:"dateIsBefore",component:vM,category:"date",sequence:30}),MM.add("dateIsOnOrBefore",{type:"dateIsOnOrBefore",component:vM,category:"date",sequence:40}),MM.add("dateIsAfter",{type:"dateIsAfter",component:vM,category:"date",sequence:50}),MM.add("dateIsOnOrAfter",{type:"dateIsOnOrAfter",component:vM,category:"date",sequence:60}),MM.add("dateIsBetween",{type:"dateIsBetween",component:bM,category:"date",sequence:70}),MM.add("dateIsNotBetween",{type:"dateIsNotBetween",component:bM,category:"date",sequence:80}),MM.add("dateIsValid",{type:"dateIsValid",component:void 0,category:"date",sequence:10}),MM.add("isEqual",{type:"isEqual",component:SM,category:"number",sequence:10}),MM.add("isNotEqual",{type:"isNotEqual",component:SM,category:"number",sequence:20}),MM.add("isGreaterThan",{type:"isGreaterThan",component:SM,category:"number",sequence:50}),MM.add("isGreaterOrEqualTo",{type:"isGreaterOrEqualTo",component:SM,category:"number",sequence:60}),MM.add("isLessThan",{type:"isLessThan",component:SM,category:"number",sequence:30}),MM.add("isLessOrEqualTo",{type:"isLessOrEqualTo",component:SM,category:"number",sequence:40}),MM.add("isBetween",{type:"isBetween",component:bM,category:"number",sequence:70}),MM.add("isNotBetween",{type:"isNotBetween",component:bM,category:"number",sequence:80}),MM.add("isBoolean",{type:"isBoolean",component:void 0,category:"misc",sequence:10}),MM.add("isValueInList",{type:"isValueInList",component:class extends BP{static template="o-spreadsheet-ListCriterionForm";static components={CriterionInput:mM,RoundColorPicker:EM};state=t.useState({numberOfValues:Math.max(this.props.criterion.values.length,2),focusedValueIndex:this.props.autofocus?0:void 0});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}),MM.add("isValueInRange",{type:"isValueInRange",component:class extends BP{static template="o-spreadsheet-ValueInRangeCriterionForm";static components={RoundColorPicker:EM,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}),MM.add("customFormula",{type:"customFormula",component:SM,category:"misc",sequence:20}),MM.add("isEmpty",{type:"isEmpty",component:void 0,category:"misc",sequence:5}),MM.add("isNotEmpty",{type:"isNotEmpty",component:void 0,category:"misc",sequence:6});class LM extends t.Component{static template="o-spreadsheet-SelectMenu";static props={menuItems:Array,selectedValue:String,class:{type:String,optional:!0}};static components={MenuPopover:$F};menuId=(new cr).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 ky(this.selectRef)}}class kM extends t.Component{static template="o-spreadsheet-FilterMenuCriterion";static props={filterPosition:Object,onCriterionChanged:Function,criterionOperators:Array};static components={SelectMenu:LM};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[Kf({name:vs("None"),id:"none",separator:!0,execute:()=>this.onCriterionTypeChange("none")}),...NM(e=>this.onCriterionTypeChange(e),new Set(this.props.criterionOperators))]}get selectedCriterionName(){return"none"===this.state.criterion.type?vs("None"):nA.get(this.state.criterion.type).name}get criterionComponent(){return"none"===this.state.criterion.type?void 0:MM.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 VM 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 UM extends t.Component{static template="o-spreadsheet-FilterMenuValueItem";static components={Checkbox:VM};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 HM extends t.Component{static template="o-spreadsheet-FilterMenuValueList";static props={filterPosition:Object,onUpdateHiddenValues:Function};static components={FilterMenuValueItem:UM};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?Gt(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(eS)),l=new Set,c=[],h=e=>{const t=eS(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?nS(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 zM extends t.Component{static template="o-spreadsheet-FilterMenu";static props={filterPosition:Object,onClosed:{type:Function,optional:!0}};static components={FilterMenuValueList:HM,SidePanelCollapsible:zP,FilterMenuCriterion:kM};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===Od.text||i.type===Od.boolean?o.text++:i.type===Od.number&&(i.format&&En(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?xI:"number"===this.criterionCategory?RI:EI}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};UP(this.env,i,r,n,e,{emptyCellAsZero:!0,sortHeaders:!0}),this.props.onClosed?.()}}const BM={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:zM,cellCorner:"bottom-left"})};class GM extends t.Component{static template="o-spreadsheet-LinkDisplay";static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};cellPopovers;setup(){this.cellPopovers=ov(NP)}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 qf(e,this.env.model.getters)}openLink(e){Zf(this.link,this.env,qy(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 WM={onHover:(e,t)=>{const s=t.getEvaluatedCell(e);return!t.isDashboard()&&s.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:GM,props:{cellPosition:e},cellCorner:"bottom-left"}:{isOpen:!1}}},$M={name:vs("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))}))]},qM={name:vs("Delete"),isVisible:e=>e.model.getters.getVisibleSheetIds().length>1,execute:e=>e.askConfirmation(vs("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"},ZM={name:vs("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"},jM=e=>({name:vs("Rename"),execute:e.renameSheetCallback,icon:"o-spreadsheet-Icon.RENAME_SHEET"}),YM=e=>({name:vs("Change color"),execute:e.openSheetColorPickerCallback,icon:"o-spreadsheet-Icon.PAINT_FORMAT"}),XM={name:vs("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"},KM={name:vs("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"},JM={name:vs("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 QM extends Fg{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 Yf(this.getAll())}}const eN=new QM;eN.add("sheet",{...$M,sequence:10});class tN extends t.Component{static template="o-spreadsheet-LinkEditor";static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};static components={MenuPopover:$F};menuItems=eN.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 ky(this.linkEditorMenuButtonRef)}onSpecialLink(e){const{detail:t}=e,s=jf(t);s&&(this.link.url=s.url,this.link.label=s.label,this.link.isUrlEditable=s.isUrlEditable)}getUrlRepresentation(e){return qf(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?Jc(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 sN={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:tN,cellCorner:"bottom-left"})};MP.add("ErrorToolTip",kP).add("LinkCell",WM).add("LinkEditor",sN).add("FilterMenu",BM);const oN={type:"bar",title:{},dataSets:[],legendPosition:"none",dataSetsHaveTitle:!1,stacked:!1},iN={type:"line",title:{},dataSets:[],legendPosition:"none",dataSetsHaveTitle:!1,stacked:!1,cumulative:!1,labelsAsText:!1};function nN(e,t){return Dt(e.getUnboundedZone(e.getActiveSheetId(),t))}function rN(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===Od.number?e=i.format&&En(i.format)?"date":i.format?.includes("%")?"percentage":"number":i.type===Od.text&&(e="text"),e){const i=++t[e];i>s&&(s=i,o=e)}}return o}function aN(e,t){const s=[];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=t.getEvaluatedCellsInZone(t.getActiveSheetId(),o);s.push({zone:o,type:rN(e)})}return s}function lN(e,t){const s=e.getEvaluatedCell({sheetId:e.getActiveSheetId(),col:t.zone.left,row:t.zone.top});return![Od.number,Od.empty].includes(s.type)}function cN(e,t){const{type:s,zone:o}=e,i=t.getActiveSheetId(),n=lN(t,e),r=nN(t,o),a=t.getEvaluatedCell({sheetId:i,col:o.left,row:o.top});if(1===Jt(o))return function(e,t){const s=t.getCellStyle({sheetId:t.getActiveSheetId(),col:e.left,row:e.top});return{type:"scorecard",title:{},keyValue:nN(t,e),background:s?.fillColor,baselineMode:B,baselineColorUp:G,baselineColorDown:W}}(o,t);switch(s){case"percentage":return{type:"pie",title:n?{text:String(a.value)}:{},dataSets:[{dataRange:r}],legendPosition:"none",dataSetsHaveTitle:n};case"text":const e=t.getEvaluatedCellsInZone(i,o).reduce((e,t)=>t.value===a.value?e+1:e,0),s=null!==a.value&&1===e;return{type:"pie",title:s?{text:String(a.value)}:{},dataSets:[{dataRange:r}],labelRange:r,dataSetsHaveTitle:s,aggregated:!0,legendPosition:"top"};case"date":return{...iN,type:"line",title:n?{text:String(a.value)}:{},dataSets:[{dataRange:r}],dataSetsHaveTitle:n}}return{...oN,title:n?{text:String(a.value)}:{},dataSets:[{dataRange:r}],dataSetsHaveTitle:n}}function hN(e,t){if(2!==e.length)throw new Error("buildTwoColumnChart expects exactly two columns");if("percentage"===e[1].type)return{type:"pie",title:{},dataSets:[{dataRange:nN(t,e[1].zone)}],labelRange:nN(t,e[0].zone),dataSetsHaveTitle:lN(t,e[1]),aggregated:!0,legendPosition:"none"};if("number"===e[0].type&&"number"===e[1].type)return{type:"scatter",title:{},dataSets:[{dataRange:nN(t,e[1].zone)}],labelRange:nN(t,e[0].zone),dataSetsHaveTitle:lN(t,e[1]),labelsAsText:!1,legendPosition:"none"};if("date"===e[0].type&&"number"===e[1].type)return{...iN,type:"line",dataSets:[{dataRange:nN(t,e[1].zone)}],labelRange:nN(t,e[0].zone),dataSetsHaveTitle:lN(t,e[0])};if("text"===e[0].type&&"number"===e[1].type){const s=e[0],o=e[1],{uniqueCount:i,totalCount:n}=function(e,t){const s=e.getEvaluatedCellsInZone(e.getActiveSheetId(),t).map(e=>e.value?.toString().trim()||"").filter(e=>e);return{uniqueCount:new Set(s).size,totalCount:s.length}}(t,s.zone),r=lN(t,o);if(i!==n)return{type:"treemap",title:{},dataSets:[{dataRange:nN(t,s.zone)}],labelRange:nN(t,o.zone),dataSetsHaveTitle:r,legendPosition:"none"}}return{...oN,dataSets:[{dataRange:nN(t,e[1].zone)}],labelRange:nN(t,e[0].zone),dataSetsHaveTitle:lN(t,e[1])}}function dN(e,t){const s=aN(e,t);if(0===s.length||s.every(e=>"empty"===e.type)){const e=s.map(({zone:e})=>({dataRange:nN(t,e)}));return{...oN,dataSets:e}}const o=s.filter(e=>"empty"!==e.type);switch(o.length){case 1:return cN(o[0],t);case 2:return hN(o,t);default:return function(e,t){if(e.length<3)throw new Error("buildMultiColumnChart expects at least three columns");const s=e.some(e=>"text"!==e.type&&lN(t,e)),o=e[e.length-1],i=e.slice(0,e.length-1);if(("percentage"===o.type||"number"===o.type)&&i.every(e=>"text"===e.type)){const e=i.map(({zone:e})=>({dataRange:nN(t,e)}));return{type:i.length>=3?"sunburst":"treemap",title:{},dataSets:e,labelRange:nN(t,o.zone),dataSetsHaveTitle:s,legendPosition:"none"}}const n=e[0],r=e.slice(1),a=r.map(({zone:e})=>({dataRange:nN(t,e)}));return r.every(e=>"percentage"===e.type)?{type:"pie",title:{},dataSets:a,labelRange:nN(t,n.zone),dataSetsHaveTitle:s,aggregated:!1,legendPosition:"top"}:"date"===n.type&&r.every(e=>"number"===e.type)?{...iN,type:"line",dataSets:a,labelRange:nN(t,n.zone),dataSetsHaveTitle:s,legendPosition:"top"}:{...oN,dataSets:a,labelRange:nN(t,n.zone),dataSetsHaveTitle:s,legendPosition:"top"}}(o,t)}}const uN={wrongPasteSelection:vs("This operation is not allowed with multiple selections."),willRemoveExistingMerge:Ag.Errors.WillRemoveExistingMerge,wrongFigurePasteOption:vs("Cannot do a special paste of a figure."),frozenPaneOverlap:vs("This operation is not allowed due to an overlapping frozen pane.")};function gN(e,t){t.isSuccessful||(t.reasons.includes("WrongPasteSelection")?e.raiseError(uN.wrongPasteSelection):t.reasons.includes("WillRemoveExistingMerge")?e.raiseError(uN.willRemoveExistingMerge):t.reasons.includes("WrongFigurePasteOption")?e.raiseError(uN.wrongFigurePasteOption):t.reasons.includes("FrozenPaneOverlap")&&e.raiseError(uN.frozenPaneOverlap))}function pN(e,t,s){const o=e.model.dispatch("PASTE",{target:t,pasteOption:s});gN(e,o)}async function mN(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=vs("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!==WT()?e.raiseError(vs("An unexpected error occurred while pasting content. This is probably due to a spreadsheet version mismatch.")):(e.raiseError(vs("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})}gN(e,i)}function fN(e,t,s=fE){let o=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,o);1!==o.length||i||1!==Jt(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(_g.Errors.TableOverlap):r.isCancelledBecause("NonContinuousTargets")&&e.raiseError(_g.Errors.NonContinuousTargets),r}function vN(e,t){e.model.dispatch("SET_FORMATTING_WITH_PIVOT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function bN(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const SN=async e=>CN(e,"asValue");async function CN(e,t){const s=await e.clipboard.read();switch(s.status){case"ok":const o=e.model.getters.getClipboardId(),i=N_(s.content),n=i.data?.clipboardId,r=e.model.getters.getSelectedZones();o!==n?await mN(e,r,i,t):pN(e,r,t),e.model.getters.isCutOperation()&&"asValue"!==t&&await e.clipboard.write({[SI.PlainText]:""});break;case"notImplemented":e.raiseError(vs("Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead."));break;case"permissionDenied":e.raiseError(vs("Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings."))}}const yN=(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},IN=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"})},wN=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})},EN=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})},RN=async e=>{if(e.imageProvider){const t=e.model.getters.getActiveSheetId(),s=e.model.uuidGenerator.smallUuid(),o=await e.imageProvider.requestImage(),i=Fy(e.model.getters,o.size),{col:n,row:r,offset:a}=Oy(e.model.getters,i);e.model.dispatch("CREATE_IMAGE",{sheetId:t,figureId:s,col:n,row:r,offset:a,size:i,definition:o})}},xN=e=>{const{col:t,row:s}=e.model.getters.getActivePosition();e.getStore(NP).open({col:t,row:s},"LinkEditor")},TN=e=>{const t=e.model.getters.getFirstTableInSelection();return t?.config.hasFilters||!1},AN=e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSelectedZones();return 1===e.model.getters.getTablesOverlappingZones(t,s).length},DN=e=>es(e.model.getters.getSelectedZones()),_N=e=>1===e.model.getters.getSelectedZones().length,ON=(e,t)=>{if(!_N(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=Lt(e.model.getters.getSelectedZone(),e.model.getters.getSheetZone(i));return We(s)&&(0===o.size||n)},FN={name:e=>TN(e)?vs("Remove selected filters"):vs("Add filters"),isEnabled:e=>DN(e),execute:e=>TN(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}}):fN(e,t,{...fE,hasFilters:!0,bandedRows:!1,styleId:"TableStyleLight11"})})(e),icon:"o-spreadsheet-Icon.FILTER_ICON_ACTIVE"};function PN(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(Rg)}class MN extends gv{mutators=["enable","disable"];isInvalidated=!1;fingerprintColors={[NN]:"#D9D9D9"};isEnabled=!1;colors=new tA;handle(e){switch(br(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 tA}computeFingerprints(){this.colors=new tA;const e=new tA,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 Zv(e.size);Object.keys(this.fingerprintColors).forEach(()=>t.next());for(const s of e)this.fingerprintColors[s]||(this.fingerprintColors[s]=Pv(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=Rb(e)&&!e.unboundedZone.hasHeader,h=Eb(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=$t({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 Od.number:case Od.boolean:return NN;case Od.text:case Od.empty:case Od.error:return}}}const NN="DATA_FINGERPRINT",LN={name:e=>{const t=e.model.getters.getElementsFromSelection("COL"),s=t[0],o=t[t.length-1];return 1===t.length?vs("Hide column %s",it(s).toString()):o-s+1===t.length?vs("Hide columns %s - %s",it(s).toString(),it(o).toString()):vs("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"},kN={name:vs("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"},VN={name:vs("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"},UN={name:e=>{const t=e.model.getters.getElementsFromSelection("ROW"),s=t[0],o=t[t.length-1];return 1===t.length?vs("Hide row %s",(s+1).toString()):o-s+1===t.length?vs("Hide rows %s - %s",(s+1).toString(),(o+1).toString()):vs("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"},HN={name:vs("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"},zN={name:vs("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"},BN={name:vs("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"},GN={name:vs("Freeze"),icon:"o-spreadsheet-Icon.FREEZE"},WN={name:vs("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},$N={name:vs("1 row"),execute:e=>PN(e,"ROW",1),isReadonlyAllowed:!0},qN={name:vs("2 rows"),execute:e=>PN(e,"ROW",2),isReadonlyAllowed:!0},ZN={name:vs("Up to current row"),execute:e=>{const{bottom:t}=e.model.getters.getSelectedZone();PN(e,"ROW",t+1)},isReadonlyAllowed:!0},jN={name:vs("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},YN={name:vs("1 column"),execute:e=>PN(e,"COL",1),isReadonlyAllowed:!0},XN={name:vs("2 columns"),execute:e=>PN(e,"COL",2),isReadonlyAllowed:!0},KN={name:vs("Up to current column"),execute:e=>{const{right:t}=e.model.getters.getSelectedZone();PN(e,"COL",t+1)},isReadonlyAllowed:!0},JN={name:vs("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)}},QN={name:vs("Irregularity map"),execute:e=>{const t=e.getStore(MN);t.isEnabled?t.disable():t.enable()},isReadonlyAllowed:!0,icon:"o-spreadsheet-Icon.IRREGULARITY_MAP"};const eL={name:vs("Formulas"),isActive:e=>e.model.getters.shouldShowFormulas(),execute:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0},tL={name:e=>{const t=e.model.getters.getSelectedZone();return t.left===t.right?vs("Group column %s",it(t.left)):vs("Group columns %s - %s",it(t.left),it(t.right))},execute:e=>nL(e,"COL"),isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSelectedZone(),o=e.model.getters.getHeaderGroupsInZone(t,"COL",s);return _N(e)&&!o.some(e=>e.start===s.left&&e.end===s.right)},icon:"o-spreadsheet-Icon.GROUP_COLUMNS"},sL={name:e=>{const t=e.model.getters.getSelectedZone();return t.top===t.bottom?vs("Group row %s",String(t.top+1)):vs("Group rows %s - %s",String(t.top+1),String(t.bottom+1))},execute:e=>nL(e,"ROW"),isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSelectedZone(),o=e.model.getters.getHeaderGroupsInZone(t,"ROW",s);return _N(e)&&!o.some(e=>e.start===s.top&&e.end===s.bottom)},icon:"o-spreadsheet-Icon.GROUP_ROWS"},oL={name:e=>{const t=e.model.getters.getSelectedZone();return t.left===t.right?vs("Ungroup column %s",it(t.left)):vs("Ungroup columns %s - %s",it(t.left),it(t.right))},execute:e=>rL(e,"COL"),icon:"o-spreadsheet-Icon.UNGROUP_COLUMNS"},iL={name:e=>{const t=e.model.getters.getSelectedZone();return t.top===t.bottom?vs("Ungroup row %s",String(t.top+1)):vs("Ungroup rows %s - %s",String(t.top+1),String(t.bottom+1))},execute:e=>rL(e,"ROW"),icon:"o-spreadsheet-Icon.UNGROUP_ROWS"};function nL(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 rL(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 aL(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 lL(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause("WrongCutSelection")&&e.raiseError(vs("This operation is not allowed with multiple selections."))}const cL={MergeIsDestructive:vs("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),MergeInFilter:vs("You can't merge cells inside of an existing filter.")};const hL={name:vs("Undo"),description:"Ctrl+Z",execute:e=>e.model.dispatch("REQUEST_UNDO"),isEnabled:e=>e.model.getters.canUndo(),icon:"o-spreadsheet-Icon.UNDO"},dL={name:vs("Redo"),description:"Ctrl+Y",execute:e=>e.model.dispatch("REQUEST_REDO"),isEnabled:e=>e.model.getters.canRedo(),icon:"o-spreadsheet-Icon.REDO"},uL={name:vs("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"},gL={name:vs("Cut"),description:"Ctrl+X",execute:async e=>{lL(e),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},icon:"o-spreadsheet-Icon.CUT"},pL={name:vs("Paste"),description:"Ctrl+V",execute:async e=>CN(e),icon:"o-spreadsheet-Icon.PASTE"},mL={name:vs("Paste special"),isVisible:e=>!e.model.getters.isCutOperation(),icon:"o-spreadsheet-Icon.PASTE"},fL={name:vs("Paste as value"),description:"Ctrl+Shift+V",execute:SN},vL={name:vs("Paste format only"),execute:e=>CN(e,"onlyFormat")},bL={name:vs("Find and replace"),description:"Ctrl+H",isReadonlyAllowed:!0,execute:e=>{e.openSidePanel("FindAndReplace",{})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.SEARCH"},SL={name:vs("Delete values"),execute:e=>e.model.dispatch("DELETE_UNFILTERED_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},CL={name:e=>{if(e.model.getters.getSelectedZones().length>1)return vs("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?vs("Delete row %s",(t+1).toString()):vs("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=>yN("ROW",e)},yL={...CL,isVisible:_N},IL={name:e=>{if(e.model.getters.getSelectedZones().length>1)return vs("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?vs("Clear row %s",(t+1).toString()):vs("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()})}},wL={name:e=>{if(e.model.getters.getSelectedZones().length>1)return vs("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?vs("Delete column %s",it(t)):vs("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=>yN("COL",e)},EL={...wL,isVisible:_N},RL={name:e=>{if(e.model.getters.getSelectedZones().length>1)return vs("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?vs("Clear column %s",it(t)):vs("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()})}},xL={name:vs("Delete cells"),isVisible:_N},TL={name:vs("Delete cell and shift up"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});gN(e,s)}},AL={name:vs("Delete cell and shift left"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});gN(e,s)}},DL={name:vs("Merge cells"),isEnabled:e=>!FL(e),isActive:e=>PL(e),execute:e=>function(e){if(FL(e))return;const t=e.model.getters.getSelectedZones(),s=e.model.getters.getActiveSheetId();if(PL(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(cL.MergeInFilter):o.isCancelledBecause("MergeIsDestructive")&&e.askConfirmation(cL.MergeIsDestructive,()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:s,force:!0})})}(e,s,t)}(e),icon:"o-spreadsheet-Icon.MERGE_CELL"},_L={name:()=>vs("Edit table"),execute:e=>e.openSidePanel("TableSidePanel",{}),icon:"o-spreadsheet-Icon.EDIT_TABLE"},OL={name:()=>vs("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 FL(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===Jt(e))||Qt(t,o,i)||function(e){for(let t=0;t<e.length-1;t++)for(let s=t+1;s<e.length;s++)if(Vt(e[t],e[s]))return!0;return!1}(t)}function PL(e){if(FL(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 ML={name:e=>{const t=uk(e);return 1===t?vs("Insert row"):vs("Insert %s rows",t.toString())},isVisible:e=>ON(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW"},NL={name:e=>{const t=uk(e);return 1===t?vs("Insert row above"):vs("Insert %s rows above",t.toString())},execute:IN,isVisible:e=>ON(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},LL={...NL,name:e=>{const t=uk(e);return 1===t?vs("Row above"):vs("%s Rows above",t.toString())}},kL={...NL,name:e=>{const t=uk(e);return 1===t?vs("Insert row"):vs("Insert %s rows",t.toString())},isVisible:_N,icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},VL={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=uk(e);return 1===t?vs("Insert row below"):vs("Insert %s rows below",t.toString())},isVisible:e=>ON(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_AFTER"},UL={...VL,name:e=>{const t=uk(e);return 1===t?vs("Row below"):vs("%s Rows below",t.toString())}},HL={name:e=>{const t=gk(e);return 1===t?vs("Insert column"):vs("Insert %s columns",t.toString())},isVisible:e=>ON(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL"},zL={name:e=>{const t=gk(e);return 1===t?vs("Insert column left"):vs("Insert %s columns left",t.toString())},execute:wN,isVisible:e=>ON(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},BL={...zL,name:e=>{const t=gk(e);return 1===t?vs("Column left"):vs("%s Columns left",t.toString())}},GL={...zL,name:e=>{const t=gk(e);return 1===t?vs("Insert column"):vs("Insert %s columns",t.toString())},isVisible:_N,icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},WL={name:e=>{const t=gk(e);return 1===t?vs("Insert column right"):vs("Insert %s columns right",t.toString())},execute:EN,isVisible:e=>ON(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_AFTER"},$L={...WL,name:e=>{const t=gk(e);return 1===t?vs("Column right"):vs("%s Columns right",t.toString())},execute:EN},qL={name:vs("Insert cells"),isVisible:e=>_N(e)&&0===e.model.getters.getActiveCols().size&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_CELL"},ZL={name:vs("Insert cells and shift down"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});gN(e,s)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_DOWN"},jL={name:vs("Insert cells and shift right"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});gN(e,s)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_RIGHT"},YL={name:vs("Chart"),execute:e=>{const t=e.model.getters,s=e.model.uuidGenerator.smallUuid(),o=t.getActiveSheetId();let i=t.getSelectedZones();1===i.length&&1===Jt(i[0])&&(e.model.selection.selectTableAroundSelection(),i=t.getSelectedZones());const n={width:536,height:335},{col:r,row:a,offset:l}=Oy(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:dN(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"},XL={name:vs("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}=Oy(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"},KL={name:vs("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"},JL={name:vs("Image"),description:"Ctrl+O",execute:RN,isVisible:e=>void 0!==e.imageProvider,isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.INSERT_IMAGE"},QL={name:()=>vs("Table"),execute:e=>{const t=e.model.getters.getActiveSheetId();fN(e,t).isSuccessful&&e.openSidePanel("TableSidePanel",{})},isVisible:e=>DN(e)&&!e.model.getters.getFirstTableInSelection(),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.PAINT_TABLE"},ek={name:vs("Function"),icon:"o-spreadsheet-Icon.FORMULA"},tk={name:vs("SUM"),execute:e=>e.startCellEdition("=SUM(")},sk={name:vs("AVERAGE"),execute:e=>e.startCellEdition("=AVERAGE(")},ok={name:vs("COUNT"),execute:e=>e.startCellEdition("=COUNT(")},ik={name:vs("MAX"),execute:e=>e.startCellEdition("=MAX(")},nk={name:vs("MIN"),execute:e=>e.startCellEdition("=MIN(")},rk={name:vs("All"),children:[function(){return dk(mf.getKeys().filter(e=>!mf.get(e).hidden))}]};const ak={name:vs("Link"),execute:xN,icon:"o-spreadsheet-Icon.INSERT_LINK"},lk={name:vs("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"},ck={name:vs("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:lh(n,e.model.getters.getLocale()),onExit:()=>{e.replaceSidePanel("DataValidation","DataValidationEditor")}})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.INSERT_DROPDOWN"},hk={name:vs("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 dk(e){return e.sort().map((e,t)=>({name:e,sequence:10*t,execute:t=>t.startCellEdition(`=${e}(`)}))}function uk(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 gk(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 pk={name:vs("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"},mk={name:vs("Ascending"),execute:e=>Tk(e,e.model.getters.getActivePosition(),"asc"),isActive:e=>"asc"===e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())},fk={name:vs("Descending"),execute:e=>Tk(e,e.model.getters.getActivePosition(),"desc"),isActive:e=>"desc"===e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())},vk={name:vs("No sorting"),execute:e=>Tk(e,e.model.getters.getActivePosition(),"none"),isActive:e=>"none"===e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())},bk={name:vs("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!==Od.error},icon:"o-spreadsheet-Icon.PIVOT"},Sk={name:vs("Group pivot dimensions"),execute:e=>{const t=Ak(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:fp(vs("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=yp(e,s,o);Sp(t,i);const n={name:fp(vs("Group"),i),values:t};i.groups.push(n),e.customFields||(e.customFields={});e.customFields[i.name]=i,Cp(e,s.name,i.name)}(r,o,i,n.getFields());e.model.dispatch("UPDATE_PIVOT",{pivotId:s,pivot:r})},isVisible:e=>{const t=Ak(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||l_.get(n.type).canHaveCustomGroup(i))}},Ck={name:vs("Group all remaining dimensions"),execute:e=>{const t=Ak(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]:yp(n,o,i.getFields());r&&(r.groups.push({name:fp(vs("Others"),r),values:[],isOtherGroup:!0}),Cp(n,o.name,r.name),e.model.dispatch("UPDATE_PIVOT",{pivotId:s,pivot:n}))},isVisible:e=>{const t=Ak(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||Dk(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)}},yk={name:vs("Ungroup pivot dimensions"),execute:e=>{const t=Ak(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=yp(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)),Sp(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=Ak(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=yp(r,i,n.getFields());if(![...r.rows,...r.columns].some(t=>t.fieldName===e.name))return!1}return Dk(r,o,i,n.getFields())}},Ik={name:e=>{const t=e.model.getters.getActivePosition(),s=Rk(e.model.getters,t);return s.isPivotGroup?s.isCollapsed?vs("Expand"):vs("Collapse"):""},execute(e){Ip(e.model.getters.getActivePosition(),e)},isVisible:e=>{const t=e.model.getters.getActivePosition();return Rk(e.model.getters,t).isPivotGroup}},wk={name:vs("Collapse all"),execute(e){const t=e.model.getters.getActivePosition(),s=Rk(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=Rk(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)))}},Ek={name:vs("Expand all"),execute(e){const t=e.model.getters.getActivePosition(),s=Rk(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=Rk(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 Rk(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 xk(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 Tk(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=pA(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 Ak(e){let t,s;const o=[];for(const i of e.model.getters.getSelectedZones()){const n=e.model.getters.getActiveSheetId();for(const r of Wt(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 Dk(e,t,s,o){if(s.isCustomField){const o=(e.customFields||{})[s.name];return!!o&&o.groups.some(e=>t.includes(e.name))}return yp(e,s,o).groups.some(e=>e.isOtherGroup||t.some(t=>e.values.includes(t)))}const _k=new QM;_k.add("cut",{...gL,sequence:10}).add("copy",{...uL,sequence:20}).add("paste",{...pL,sequence:30}).add("paste_special",{...mL,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...fL,sequence:10}).addChild("paste_format_only",["paste_special"],{...vL,sequence:20}).add("add_row_before",{...kL,sequence:70}).add("add_column_before",{...GL,sequence:90}).add("insert_cell",{...qL,sequence:100,separator:!0}).addChild("insert_cell_down",["insert_cell"],{...ZL,name:vs("Shift down"),sequence:10}).addChild("insert_cell_right",["insert_cell"],{...jL,name:vs("Shift right"),sequence:20}).add("delete_row",{...yL,sequence:110,icon:"o-spreadsheet-Icon.TRASH"}).add("delete_column",{...EL,sequence:120,icon:"o-spreadsheet-Icon.TRASH"}).add("delete_cell",{...xL,sequence:130,separator:!0,icon:"o-spreadsheet-Icon.TRASH"}).addChild("delete_cell_up",["delete_cell"],{...TL,name:vs("Shift up"),sequence:10,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_UP"}).addChild("delete_cell_left",["delete_cell"],{...AL,name:vs("Shift left"),sequence:20,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_LEFT"}).add("edit_table",{..._L,isVisible:AN,isEnabled:e=>!e.isSmall,sequence:140}).add("delete_table",{...OL,isVisible:AN,sequence:145,separator:!0}).add("insert_link",{...ak,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?vs("Edit link"):vs("Insert link")},sequence:150,separator:!0}).add("pivot_headers_group",{sequence:155,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",...Sk}).add("pivot_group_remaining",{sequence:155,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",...Ck}).add("pivot_headers_ungroup",{sequence:155,icon:"o-spreadsheet-Icon.MINUS_IN_BOX",...yk}).add("collapse_pivot",{sequence:156,name:vs("Expand/Collapse"),icon:"o-spreadsheet-Icon.COLLAPSE"}).addChild("toggle_collapse_pivot_cell",["collapse_pivot"],{sequence:10,...Ik}).addChild("collapse_all_pivot",["collapse_pivot"],{sequence:20,...wk}).addChild("expand_all_pivot",["collapse_pivot"],{sequence:30,...Ek}).add("pivot_sorting",{name:vs("Sort pivot"),sequence:155,icon:"o-spreadsheet-Icon.SORT_RANGE",isVisible:e=>{const t=e.model.getters.getActivePosition();return xk(e.model.getters,t)}}).add("pivot_fix_formulas",{...bk,sequence:160}).add("pivot_properties",{...pk,sequence:170,separator:!0}).addChild("pivot_sorting_asc",["pivot_sorting"],{...mk,sequence:10}).addChild("pivot_sorting_desc",["pivot_sorting"],{...fk,sequence:20}).addChild("pivot_sorting_none",["pivot_sorting"],{...vk,sequence:30});const Ok={name:vs("Sort range"),isVisible:_N,icon:"o-spreadsheet-Icon.SORT_RANGE"},Fk={name:vs("Ascending (A ⟶ Z)"),execute:e=>{const{anchor:t,zones:s}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();VP(e,o,t.cell,s[0],"asc")},icon:"o-spreadsheet-Icon.SORT_ASCENDING"},Pk={name:vs("Data cleanup"),icon:"o-spreadsheet-Icon.DATA_CLEANUP"},Mk={name:vs("Remove duplicates"),execute:e=>{1===Jt(e.model.getters.getSelectedZone())&&e.model.selection.selectTableAroundSelection(),e.openSidePanel("RemoveDuplicates",{})},isEnabled:e=>!e.isSmall},Nk={name:vs("Trim whitespace"),execute:e=>{e.model.dispatch("TRIM_WHITESPACE")}},Lk={name:vs("Descending (Z ⟶ A)"),execute:e=>{const{anchor:t,zones:s}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();VP(e,o,t.cell,s[0],"desc")},icon:"o-spreadsheet-Icon.SORT_DESCENDING"},kk={...FN},Vk={...FN,isActive:e=>TN(e)},Uk={name:vs("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"},Hk={id:"reinsert_dynamic_pivot",name:vs("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())},zk={id:"reinsert_static_pivot",name:vs("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:PP(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 Bk({name:e,format:t,descriptionValue:s}){const o="function"==typeof t?t:()=>t;return{name:e,description:e=>mn(s,{format:o(e),locale:e.model.getters.getLocale()}),execute:e=>vN(e,o(e)),isActive:e=>VV(e,o(e)),format:t}}const Gk={name:vs("Automatic"),execute:e=>vN(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)},Wk={name:vs("Plain text"),execute:e=>vN(e,"@"),isActive:e=>VV(e,"@")},$k=Bk({name:vs("Number"),descriptionValue:1000.12,format:"#,##0.00"}),qk={name:vs("Format as percent"),execute:e=>vN(e,"0.00%"),icon:"o-spreadsheet-Icon.PERCENT"},Zk=Bk({name:vs("Percent"),descriptionValue:.1012,format:"0.00%"}),jk=Bk({name:vs("Currency"),descriptionValue:1000.12,format:e=>_n(e.model.config.defaultCurrency||ee)}),Yk={...Bk({name:vs("Currency rounded"),descriptionValue:1e3,format:e=>Pn(_n(e.model.config.defaultCurrency||ee))}),isVisible:e=>{const t=_n(e.model.config.defaultCurrency||ee);return t!==Pn(t)}},Xk=Bk({name:vs("Accounting"),descriptionValue:-1000.12,format:e=>On(e.model.config.defaultCurrency||ee)}),Kk=Qv("2023/09/26 10:43:00 PM",Fc),Jk={name:vs("Custom currency"),isVisible:e=>void 0!==e.loadCurrencies&&!e.isSmall,execute:e=>e.openSidePanel("CustomCurrency",{})},Qk=Bk({name:vs("Date"),descriptionValue:Kk,format:e=>e.model.getters.getLocale().dateFormat}),eV=Bk({name:vs("Time"),descriptionValue:Kk,format:e=>e.model.getters.getLocale().timeFormat}),tV=Bk({name:vs("Date time"),descriptionValue:Kk,format:e=>dh(e.model.getters.getLocale())}),sV=Bk({name:vs("Duration"),descriptionValue:"27:51:38",format:"hhhh:mm:ss"}),oV=Bk({name:vs("Quarter"),descriptionValue:Kk,format:"qq yyyy"}),iV=Bk({name:vs("Full quarter"),descriptionValue:Kk,format:"qqqq yyyy"}),nV={name:vs("More date formats"),execute:e=>e.openSidePanel("MoreFormats",{})},rV=Bk({name:vs("Full date time"),format:"dddd d mmmm yyyy hh:mm:ss a",descriptionValue:Kk}),aV=Bk({name:vs("ISO Date"),format:"yyyy-mm-dd",descriptionValue:Kk}),lV=Bk({name:vs("ISO Date time"),format:"yyyy-mm-dd hh:mm:ss",descriptionValue:Kk}),cV=Bk({name:vs("Full week day and month"),format:"dddd d mmmm yyyy",descriptionValue:Kk}),hV=Bk({name:vs("Day and full month"),format:"d mmmm yyyy",descriptionValue:Kk}),dV=Bk({name:vs("Short week day"),format:"ddd d mmm yyyy",descriptionValue:Kk}),uV=Bk({name:vs("Day and short month"),format:"d mmm yyyy",descriptionValue:Kk}),gV=Bk({name:vs("Full month"),format:"mmmm yyyy",descriptionValue:Kk}),pV=Bk({name:vs("Short month"),format:"mmm yyyy",descriptionValue:Kk}),mV={name:vs("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})},fV={name:vs("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})},vV={name:vs("Bold"),description:"Ctrl+B",execute:e=>bN(e,{bold:!e.model.getters.getCurrentStyle().bold}),icon:"o-spreadsheet-Icon.BOLD",isActive:e=>!!e.model.getters.getCurrentStyle().bold},bV={name:vs("Italic"),description:"Ctrl+I",execute:e=>bN(e,{italic:!e.model.getters.getCurrentStyle().italic}),icon:"o-spreadsheet-Icon.ITALIC",isActive:e=>!!e.model.getters.getCurrentStyle().italic},SV={name:vs("Underline"),description:"Ctrl+U",execute:e=>bN(e,{underline:!e.model.getters.getCurrentStyle().underline}),icon:"o-spreadsheet-Icon.UNDERLINE",isActive:e=>!!e.model.getters.getCurrentStyle().underline},CV={name:vs("Strikethrough"),execute:e=>bN(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),icon:"o-spreadsheet-Icon.STRIKE",isActive:e=>!!e.model.getters.getCurrentStyle().strikethrough},yV={name:vs("Font size"),children:K.map(e=>({name:e.toString(),sequence:e,id:`font_size_${e}`,execute:t=>bN(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"},IV={name:vs("Alignment"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},wV={name:vs("Horizontal align"),icon:e=>function(e){switch(UV(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)},EV={name:vs("Left"),description:"Ctrl+Shift+L",execute:e=>bN(e,{align:"left"}),isActive:e=>"left"===UV(e),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},RV={name:vs("Center"),description:"Ctrl+Shift+E",execute:e=>bN(e,{align:"center"}),isActive:e=>"center"===UV(e),icon:"o-spreadsheet-Icon.ALIGN_CENTER"},xV={name:vs("Right"),description:"Ctrl+Shift+R",execute:e=>bN(e,{align:"right"}),isActive:e=>"right"===UV(e),icon:"o-spreadsheet-Icon.ALIGN_RIGHT"},TV={name:vs("Vertical align"),icon:e=>function(e){switch(HV(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)},AV={name:vs("Top"),execute:e=>bN(e,{verticalAlign:"top"}),isActive:e=>"top"===HV(e),icon:"o-spreadsheet-Icon.ALIGN_TOP"},DV={name:vs("Middle"),execute:e=>bN(e,{verticalAlign:"middle"}),isActive:e=>"middle"===HV(e),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},_V={name:vs("Bottom"),execute:e=>bN(e,{verticalAlign:"bottom"}),isActive:e=>"bottom"===HV(e),icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"},OV={name:vs("Wrapping"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},FV={name:vs("Wrapping"),icon:e=>function(e){switch(zV(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)},PV={name:vs("Overflow"),execute:e=>bN(e,{wrapping:"overflow"}),isActive:e=>"overflow"===zV(e),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},MV={name:vs("Wrap"),execute:e=>bN(e,{wrapping:"wrap"}),isActive:e=>"wrap"===zV(e),icon:"o-spreadsheet-Icon.WRAPPING_WRAP"},NV={name:vs("Clip"),execute:e=>bN(e,{wrapping:"clip"}),isActive:e=>"clip"===zV(e),icon:"o-spreadsheet-Icon.WRAPPING_CLIP"};vs("Text Color"),vs("Fill Color");const LV={name:vs("Conditional formatting"),execute:e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.CONDITIONAL_FORMAT"},kV={name:vs("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 VV(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 UV(e){const t=e.model.getters.getCurrentStyle();if(t.align)return t.align;return e.model.getters.getActiveCell().defaultAlign}function HV(e){const t=e.model.getters.getCurrentStyle();return t.verticalAlign?t.verticalAlign:M}function zV(e){const t=e.model.getters.getCurrentStyle();return t.wrapping?t.wrapping:N}const BV=new QM;BV.add("cut",{...gL,sequence:10}).add("copy",{...uL,sequence:20}).add("paste",{...pL,sequence:30}).add("paste_special",{...mL,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...fL,sequence:10}).addChild("paste_format_only",["paste_special"],{...vL,sequence:20}).add("sort_columns",{...Ok,name:e=>e.model.getters.getActiveCols().size>1?vs("Sort columns"):vs("Sort column"),sequence:50,separator:!0}).addChild("sort_ascending",["sort_columns"],{...Fk,sequence:10}).addChild("sort_descending",["sort_columns"],{...Lk,sequence:20}).add("add_column_before",{...zL,sequence:70}).add("add_column_after",{...WL,sequence:80}).add("delete_column",{...wL,sequence:90,icon:"o-spreadsheet-Icon.TRASH"}).add("clear_column",{...RL,sequence:100,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_columns",{...LN,sequence:105,separator:!0}).add("unhide_columns",{...kN,sequence:106,separator:!0}).add("conditional_formatting",{...LV,sequence:110,separator:!0}).add("edit_table",{..._L,isVisible:AN,sequence:120}).add("delete_table",{...OL,isVisible:AN,sequence:125,separator:!0}).add("group_columns",{sequence:150,...tL}).add("ungroup_columns",{sequence:155,...oL,isVisible:e=>aL(e,"COL")});const GV={CannotHideAllRows:vs("Cannot hide all the rows of a sheet."),CannotHideAllColumns:vs("Cannot hide all the columns of a sheet.")};function WV(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?GV.CannotHideAllRows:GV.CannotHideAllColumns;e.raiseError(t)}}function $V(e,t){return Yf([{id:"unfold_all",name:vs("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:vs("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 qV=new QM;qV.add("group_columns",{sequence:10,...tL,isVisible:()=>!0,isEnabled:tL.isVisible}).add("group_rows",{sequence:20,...sL,isVisible:()=>!0,isEnabled:sL.isVisible});const ZV=new QM;ZV.add("ungroup_columns",{sequence:10,...oL,isEnabled:e=>aL(e,"COL")}).add("ungroup_rows",{sequence:20,...iL,isEnabled:e=>aL(e,"ROW")});const jV=new QM;jV.add("cut",{...gL,sequence:10}).add("copy",{...uL,sequence:20}).add("paste",{...pL,sequence:30}).add("paste_special",{...mL,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...fL,sequence:10}).addChild("paste_format_only",["paste_special"],{...vL,sequence:20}).add("add_row_before",{...NL,sequence:50}).add("add_row_after",{...VL,sequence:60}).add("delete_row",{...CL,sequence:70,icon:"o-spreadsheet-Icon.TRASH"}).add("clear_row",{...IL,sequence:80,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_rows",{...UN,sequence:85,separator:!0}).add("unhide_rows",{...HN,sequence:86,separator:!0}).add("conditional_formatting",{...LV,sequence:90,separator:!0}).add("group_rows",{sequence:100,...sL}).add("ungroup_rows",{sequence:110,...iL,isVisible:e=>aL(e,"ROW")});class YV extends gv{highlightStore=this.get(cM);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===Ss.SpilledBlocked,color:"#17A2B8",noFill:!0,thinLine:!0}]:[]}}class XV extends gv{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 KV(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=Ly(),u=Ey(e,s,h),{x:p,y:m}=l.getMainViewportCoordinates(),{top:f,left:v,bottom:b,right:S}=l.getActiveMainViewport();let{scrollX:C,scrollY:y}=l.getActiveSheetScrollInfo();const{xSplit:I,ySplit:w}=l.getPaneDivisions(c);let E=!1,R=140;const x=u.clientX-h.left;let T=l.getColIndex(x);if("vertical"!==a){const t=o.clientX-h.left,s=l.getEdgeScrollCol(x,t,i);if(s.canEdgeScroll){E=!0,R=Math.min(R,s.delay);let t=T;switch(s.direction){case"reset":T=t=I;break;case 1:T=S,t=v+1;break;case-1:for(T=v-1;e.model.getters.isColHidden(c,T);)T--;t=T}C=l.getColDimensions(c,t).start-p}}const A=u.clientY-h.top;let D=l.getRowIndex(A);if("horizontal"!==a){const t=o.clientY-h.top,s=l.getEdgeScrollRow(A,t,n);if(s.canEdgeScroll){E=!0,R=Math.min(R,s.delay);let t=D;switch(s.direction){case"reset":D=t=w;break;case 1:D=b,t=f+1;break;case-1:for(D=f-1;e.model.getters.isRowHidden(c,D);)D--;t=D}y=e.model.getters.getRowDimensions(c,t).start-m}}E||(T=JV(T,x,l.getNumberCols(c)-1),D=JV(D,A,l.getNumberRows(c)-1)),d?.(T,D,s),E&&(e.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:C,offsetY:y}),r=setTimeout(()=>{r=null,g(s)},Math.round(R))),o={clientX:u.clientX,clientY:u.clientY}},p=()=>{u?.(),h()};return t.onWillUnmount(()=>{h()}),t.useEffect(()=>{h()},()=>[l.getActiveSheetId()]),{start:(e,t,s,r="all")=>{h();const l=Ly();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(CM(g,p))}}}function JV(e,t,s){return-1===e?t<0?0:s:e}class QV extends t.Component{static template="o-spreadsheet-Autofill";static props={position:Object,isVisible:Boolean};state=t.useState({position:{x:0,y:0},handler:!1});dragNDropGrid=KV(this.env);get style(){const{x:e,y:t}=this.props.position;return _y({top:`${t}px`,left:`${e}px`,visibility:this.props.isVisible?"visible":"hidden"})}get handlerStyle(){const{x:e,y:t}=this.state.handler?this.state.position:this.props.position;return _y({top:`${t}px`,left:`${e}px`})}get styleNextValue(){const{x:e,y:t}=this.state.position;return _y({top:`${t+5}px`,left:`${e+15}px`})}getTooltip(){const e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=eU),e}onMouseDown(e){this.state.handler=!0;const t=Ey(this.env,e),s=this.env.model.getters.getViewportZoomLevel();let o,i;const n=e.clientX/s-this.props.position.x,r=e.clientY/s-this.props.position.y;this.dragNDropGrid.start(t,(e,t,a)=>{if(this.state.position={x:a.clientX/s-n,y:a.clientY/s-r},o!==e||i!==t){const s=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getNumberCols(s),r=this.env.model.getters.getNumberRows(s);o=-1===e?o:ue(e,0,n),i=-1===t?i:ue(t,0,r),void 0!==o&&void 0!==i&&this.env.model.dispatch("AUTOFILL_SELECT",{col:o,row:i})}},()=>{this.state.handler=!1,this.state.position={...this.props.position},this.env.model.dispatch("AUTOFILL")})}onDblClick(){this.env.model.dispatch("AUTOFILL_AUTO")}}class eU extends t.Component{static props={content:String};static template=t.xml`
|
|
818
|
+
<div t-esc="props.content"/>
|
|
819
|
+
`}class tU 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 _y({bottom:o-r+15+"px",left:n-1+"px",border:`1px solid ${s}`,"background-color":s,visibility:i?"visible":"hidden"})}}const sU=vs("The cell you are trying to edit has been deleted.");class oU extends uM{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=nA.get(o.criterion.type).getErrorString(o.criterion,this.getters,t.sheetId);this.notificationStore.raiseError(vs("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,jt({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(sU))}}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(sU);const{top:t,left:s}=Ft({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(sU);const{top:t,left:s}=Ft({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}=Ot({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:oh(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 Od.empty:return{text:""};case Od.text:case Od.error:return{text:n};case Od.boolean:return{text:a};case Od.number:if(i&&En(i)){if(null!==js(a,s))return{text:a};return{text:mn(n,{locale:s,format:Number.isInteger(n)?s.dateFormat:dh(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 OD(Pf(e.compiledFormula.tokens),t)}numberComposerContent(e,t,s){return t?.includes("%")?`${wn(100*e,s.decimalSeparator)}%`:wn(e,s.decimalSeparator)}addHeadersForSpreadingFormula(e){if(!ot(e))return;const t=this.getters.evaluateFormula(this.sheetId,e);if(!_s(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):Qv(t,this.getters.getLocale());if(Si(s))return!0;const o=this.getters.getValidationResultForCellValue(vi(s),e);return!(!o.isValid&&o.rule.isBlocking)}}const iU=3*.4*window.devicePixelRatio||1;class nU extends t.Component{static template="o-spreadsheet-GridComposer";static props={gridDims:Object,onInputContextMenu:Function};static components={Composer:oM};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=ov(oU);this.composerStore=e,this.composerFocusStore=ov(mv),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 or(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 _y({left:e-iU+"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*iU;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":Ty(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 _y({left:i-1+"px",top:`${n}px`,border:`${iU}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":`${Yb(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,jt(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=jt(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 rU(e,t,s){return s.map(s=>cU(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 aU(e,t,s,o,i){const n=s.map(s=>cU(e,t,!0,s));let r;for(const t of o){const s=rU(e,t,i);for(const e of n)for(const o of s){if(!lU(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 lU(e,t){return Math.abs(e-t)<=5}function cU(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 hU extends t.Component{static template="o-spreadsheet-FiguresContainer";static props={onFigureDeleted:Function};static components={FigureComponent:KF};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 _y({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),_y({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=this.env.model.getters.getViewportZoomLevel(),i={x:t.clientX/o,y:t.clientY/o},n=this.env.model.getters.getActiveSheetScrollInfo(),r=this.toBottomRightViewport(e),a={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 l=!1;this.dnd.cancelDnd=CM(e=>{const t=this.env.model.getters,s={x:e.clientX/o,y:e.clientY/o},c=Math.abs(s.x-i.x),h=Math.abs(s.y-i.y);if(!l&&c<5&&h<5)return;l=!0;const d=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,i,r,a,n,t.getActiveSheetScrollInfo()),u=this.getOtherFigures(r.id),g=this.getCarouselOverlappingChart(d,u);if(this.dnd.overlappingCarousel=g,g)this.dnd.draggedFigure=d,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0;else{const e=function(e,t,s){const o=aU(e,t,["hCenter","right","left"],s,["hCenter","right","left"]),i=aU(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,d,u);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=this.env.model.getters.getActiveSheetScrollInfo(),n=XF.get(e.tag).keepRatio||!1,r=XF.get(e.tag).minFigSize||80,a=this.env.model.getters.getViewportZoomLevel(),l=this.env.model.getters.getActiveSheetId(),c={x:o.clientX/a,y:o.clientY/a},h={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=CM(o=>{const l={x:o.clientX/a,y:o.clientY/a},d=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,c,n,r,i,this.env.model.getters.getActiveSheetScrollInfo(),h),u=this.getOtherFigures(e.id),g=function(e,t,s,o,i){const n=aU(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=aU(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,d,u);this.dnd.draggedFigure=g.snappedFigure,this.dnd.horizontalSnap=this.getSnap(g.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(g.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?"":_y({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 UF(Mt(...e.map(VF)))}({...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)?_y({top:e.position-t.y-o+"px",left:"0px",width:"100%"}):_y({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 dU 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 uU extends t.Component{static template="o-spreadsheet-GridAddRowsFooter";static props={focusGrid:Function};static components={ValidationMessages:dU};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 _y({top:`${this.env.model.getters.getRowDimensions(e,t-1).end-s}px`})}get errorMessages(){return[vs("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 gU(e,...s){t.useEffect(e=>(e?.addEventListener(...s),()=>e?.removeEventListener(...s)),()=>[e.el])}const pU=["cell","border","style","table","conditionalFormat","merge"];class mU extends gv{mutators=["activate","cancel","pasteFormat"];highlightStore=this.get(cM);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 pU.map(e=>({handlerName:e,handler:new(U_.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(F_(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}=k_(e,t,this.copiedData,this.clipboardHandlers,s);L_(this.clipboardHandlers,this.copiedData,o,s),V_(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 fU extends gv{mutators=["clear","hover"];col;row;overlayColors=new tA;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 tA;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 vU extends gv{mutators=["setHoveredIcon"];hoveredIcon=void 0;setHoveredIcon(e){this.hoveredIcon=e}}function bU(e,s){const o=ov(JF),i=ov(fU),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=Vy(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){Ny(s.el,e.ev)&&(({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 gU(s,"pointermove",t=>!e.isMobile()&&p(Ey(e,t))),gU(s,"mouseleave",function(t){const o=Ey(e,t),{x:i,y:n}=d(o),r=Vy(s.el);return n<0||n>r.height||i<0||i>r.width?p(o):u()}),gU(s,"mouseenter",g),gU(s,"pointerdown",function(){const{col:e,row:t}=h();e===n.col&&t===n.row||m(void 0,void 0)}),gU(s,"pointerdown",t=>e.isMobile()&&p(Ey(e,t))),t.useExternalListener(window,"click",function(e){const t=e.target;s.el.contains(t)||m(void 0,void 0)}),n}class SU 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:hU,GridAddRowsFooter:uU};static defaultProps={onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{},onFigureDeleted:()=>{}};gridOverlay=t.useRef("gridOverlay");cellPopovers;paintFormatStore;hoveredIconStore;setup(){bU(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=ov(NP),this.paintFormatStore=ov(mU),this.hoveredIconStore=ov(vU)}get gridOverlayEl(){if(!this.gridOverlay.el)throw new Error("GridOverlay el is not defined.");return this.gridOverlay.el}get style(){return this.props.gridOverlayDimensions+_y({cursor:this.hoveredIconStore.hoveredIcon?"pointer":"default"})}get isPaintingFormat(){return this.paintFormatStore.isActive}onPointerMove(e){if(this.env.isMobile())return;const t=this.getInteractiveIconAtEvent(Ey(this.env,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(Ey(this.env,e))}onClick(e){e.button>0||!this.env.isMobile()||this.onCellClicked(Ey(this.env,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.ev.shiftKey,addZone:$y(e.ev)},e),i?.onClick&&i.onClick(i.position,this.env),e.ev.target===this.gridOverlay.el&&this.cellPopovers.isOpen&&Me(t,this.cellPopovers.persistentCellPopover)&&this.cellPopovers.close()}onDoubleClick(e){const t=Ey(this.env,e);if(this.getInteractiveIconAtEvent(t))return;const[s,o]=this.getCartesianCoordinates(t);this.props.onCellDoubleClicked(s,o)}onContextMenu(e){const[t,s]=this.getCartesianCoordinates(Ey(this.env,e));this.props.onCellRightClicked(t,s,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){return[this.env.model.getters.getColIndex(e.offsetX),this.env.model.getters.getRowIndex(e.offsetY)]}getInteractiveIconAtEvent(e){const t=ky(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)||jt(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 CU extends t.Component{static template="o-spreadsheet-GridPopover";static props={onClosePopover:Function,onMouseWheel:Function,gridRect:Object};static components={Popover:zF};cellPopovers;setup(){this.cellPopovers=ov(NP)}get cellPopover(){const e=this.cellPopovers.cellPopover;if(!e.isOpen)return{isOpen:!1};const t=Ry(this.env.model.getters.getViewportZoomLevel(),e.anchorRect);return{...e,anchorRect:{...t,x:t.x+this.props.gridRect.x,y:t.y+this.props.gridRect.y}}}}class yU 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(jt({col:0,row:e}));return _y({top:t.y+t.height-A-this.props.offset+"px","margin-right":"1px"})}getUnhideNextButtonStyle(e){return _y({top:this.env.model.getters.getRect(jt({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 IU 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(jt({col:e,row:0}));return _y({left:t.x+t.width-D-this.props.offset+"px"})}getUnhideNextButtonStyle(e){return _y({left:this.env.model.getters.getRect(jt({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 wU 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=KV(this.env);setup(){this.composerFocusStore=ov(mv)}_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){if(this.env.isMobile())return;const t=Ey(this.env,e);this.state.isResizing||this.state.isMoving||this.state.isSelecting||(this._computeHandleDisplay(t),this._computeGrabDisplay(t))}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(e){const t=Ey(this.env,e);this._fitElementSize(this.state.activeElement),this.state.isResizing=!1,this._computeHandleDisplay(t),this._computeGrabDisplay(t)}onMouseDown(e){this.state.isResizing=!0,this.state.delta=0;const t=Ey(this.env,e),s=this._getClientPosition(t),o=this.state.draggerLinePosition,i=this._getElementSize(this.state.activeElement),n=o-i+this.MIN_ELEMENT_SIZE,r=this._getMaxSize();CM(e=>{this.state.delta=this._getClientPosition(Ey(this.env,e))-s,this.state.draggerLinePosition=o+this.state.delta,this.state.draggerLinePosition<n&&(this.state.draggerLinePosition=n,this.state.delta=this.MIN_ELEMENT_SIZE-i),this.state.draggerLinePosition>r&&(this.state.draggerLinePosition=r,this.state.delta=r-o)},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=Ey(this.env,e),s=this._getElementIndex(this._getEvOffset(t));this._selectElement(s,!1)}select(e){if(this.env.isMobile())return;if(e.button>0)return;const t=Ey(this.env,e),s=this._getElementIndex(this._getEvOffset(t));s<0||(this.state.waitingForMove?this.env.model.getters.isGridSelectionActive()?this.startMovement(e):this._selectElement(s,!1):("editing"===this.composerFocusStore.activeComposer.editionMode&&this.env.model.selection.getBackToDefault(),this.startSelection(e,s)))}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;const t=Ey(this.env,e),s=this._getDimensionsInViewport(this._getSelectedZoneStart()),o=this._getDimensionsInViewport(this._getSelectedZoneEnd()),i=s.start;this.state.draggerLinePosition=i,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=i,this.state.draggerShadowThickness=o.end-s.start;this.dragNDropGrid.start(t,(e,t)=>{const o="COL"===this._getType()?e:t;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=s.start,this.state.draggerShadowPosition=s.start,this.state.base=this._getSelectedZoneStart())}},()=>{this.state.isMoving=!1,this.state.base!==this._getSelectedZoneStart()&&this._moveElements();const t=Ey(this.env,e);this._computeGrabDisplay(t)})}startSelection(e,t){if(this.env.isMobile())return;this.state.isSelecting=!0,e.shiftKey?this._increaseSelection(t):this._selectElement(t,$y(e)),this.lastSelectedElementIndex=t;const s=Ey(this.env,e);this.dragNDropGrid.start(s,(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(s)})}onMouseUp(e){this.lastSelectedElementIndex=null}onContextMenu(e){e.preventDefault();const t=this._getElementIndex(this._getEvOffset(Ey(this.env,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 EU extends wU{static props={onOpenContextMenu:Function};static template="o-spreadsheet-ColResizer";static components={UnhideColumnHeaders:IU};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(Rg)}_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 _y({width:this.env.model.getters.getMainViewportCoordinates().x+"px"})}get hasFrozenPane(){return this.env.model.getters.getPaneDivisions(this.sheetId).xSplit>0}}class RU extends wU{static props={onOpenContextMenu:Function};static template="o-spreadsheet-RowResizer";static components={UnhideRowHeaders:yU};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(Rg):o.reasons.includes("CannotMoveTableHeader")&&this.env.raiseError(xg))}_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 _y({height:this.env.model.getters.getMainViewportCoordinates().y+"px"})}get hasFrozenPane(){return this.env.model.getters.getPaneDivisions(this.sheetId).ySplit>0}}class xU extends t.Component{static props={onOpenContextMenu:Function};static template="o-spreadsheet-HeadersOverlay";static components={ColResizer:EU,RowResizer:RU};selectAll(){this.env.model.selection.selectAll()}}class TU extends gv{fingerprints;hoveredTables;hoveredIcon;lastRenderBoxes=new Map;preventNewAnimationsInNextFrame=!1;zonesWithPreventedAnimationsInNextFrame=[];animations=new Map;constructor(e){super(e),this.getters=e(lv).getters,this.fingerprints=e(MN),this.hoveredTables=e(fU),this.hoveredIcon=e(vU)}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=Xb(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)oS(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(IR(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!==Od.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!==Od.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 o=this.getters.getCellComputedStyle(e)?.align,i=this.getters.getEvaluatedCell(e);return function(e,t){if(!t)return!1;try{const s=on(t),{format:o}=fn(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===Od.number?"center"!==o?"left":o:o||i.defaultAlign}createZoneBox(e,t,s){const{left:o,right:i}=s,n=t.left,r=t.top,a={sheetId:e,col:n,row:r},l=this.getters.getEvaluatedCell(a),c=this.getters.shouldShowFormulas(),{x:h,y:d,width:u,height:g}=this.getters.getRect(t),p=this.getters.getDataValidationChipStyle(a),m=this.getters.getCellComputedBorder(a,s);let f=this.getters.getCellComputedStyle(a,s);if(this.fingerprints.isEnabled){const e=this.fingerprints.colors.get(a);f={...f,fillColor:e}}p?.textColor&&(f={...f,textColor:p.textColor});const v=this.fingerprints.isEnabled?void 0:this.getters.getConditionalDataBar(a),b=this.getters.getCellIcons(a),S={left:b.find(e=>"left"===e?.horizontalAlign),right:b.find(e=>"right"===e?.horizontalAlign),center:b.find(e=>"center"===e?.horizontalAlign)},C={id:Dt(t),x:h,y:d,width:u,height:g,border:m||void 0,style:f,dataBarFill:v,overlayColor:this.hoveredTables.overlayColors.get(a),isError:l.type===Od.error&&!!l.message||this.getters.isDataValidationInvalid(a),icons:S,disabledAnimation:this.zonesWithPreventedAnimationsInNextFrame.some(e=>Ht(t,e)||Vt(t,e))},y=Kb(C.style);if(l.type===Od.empty||C.icons.center)return C;const I=f.wrapping||"overflow",w="wrap"===I&&!c,E=u-8,R=this.getters.getCellMultiLineText(a,{maxWidth:E,wrapText:w}),x=Math.max(...R.map(e=>this.getters.getTextWidth(e,f)+4)),T=p?5:0,A=(C.icons.left?C.icons.left.size+C.icons.left.margin:0)+T,D=(C.icons.right?C.icons.right.size+C.icons.right.margin:0)+T,_=A+x+D,O=this.computeCellAlignment(a,_>u),F=R.length,P=Math.round(this.getters.computeTextYCoordinate(C,y,f.verticalAlign,F));let M=C.x;M+="left"===O?4+A:"right"===O?C.width-4-D:C.width/2,M=Math.round(M);const N=Hb(y,F);if(C.content={textLines:R,width:"overflow"===I?x:u,align:O,x:M,y:P,fontSizePx:y},p?.fillColor){const e=A,t=5;C.chip={color:p.fillColor,width:C.width-e-t,height:N+2,x:C.x+e,y:P-2}}const L=_>u||y>g;if(C.icons.left||C.icons.right||C.chip)C.clipRect={x:C.x+A,y:C.y,width:Math.max(0,u-A-D),height:g};else if(L&&"overflow"===I){let e,s;switch(this.getters.isInMerge(a)?(e=this.getters.getMerge(a).right,s=n):(e=C.border?.right?t.right:this.findNextEmptyCol(n,i,r),s=C.border?.left?t.left:this.findPreviousEmptyCol(n,o,r),C.isOverflow=!0),O){case"left":{const s=jt({col:e,row:r}),{x:o,y:i,width:n,height:a}=this.getters.getVisibleRect(Mt(t,s));(n<_||y>a||R.length>1)&&(C.clipRect={x:o,y:i,width:n,height:a});break}case"right":{const e=jt({col:s,row:r}),{x:o,y:i,width:n,height:a}=this.getters.getVisibleRect(Mt(t,e));(n<_||y>a||R.length>1)&&(C.clipRect={x:o,y:i,width:n,height:a});break}case"center":{const o={...t,left:s,right:e},{x:i,y:n,height:r,width:a}=this.getters.getVisibleRect(o),l=_/2,c=C.x+C.width/2;if(i+a<c+l||i>c-l||y>r||R.length>1){const e=i>c-l?i:c-l,t=i+a-e;C.clipRect={x:e,y:n,width:t,height:r}}break}}}else("clip"===I||"wrap"===I||R.length>1)&&(C.clipRect={x:C.x,y:C.y,width:u,height:g});return C}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 e of n)for(const o of s){const s={sheetId:a,col:o,row:e};this.getters.isInMerge(s)||t.push(this.createZoneBox(a,jt(s),r))}for(const s of this.getters.getMerges(a))if(!this.getters.isMergeHidden(a,s)&&Vt(s,r)){const o=this.createZoneBox(a,s,r),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=AF.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 AF.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 AU(e,s,o){const i=t.useRef(e);t.useEffect(function(){const e=i.el,t=window.devicePixelRatio||1,r=e.getContext("2d",{alpha:!1}),a=Math.max(s.getters.getViewportZoomLevel(),1),l={ctx:r,dpr:t,thinLineWidth:.4*t};let{width:c,height:h}=o();if(c*=a,h*=a,e.style.width=`${c}px`,e.style.height=`${h}px`,e.width=c*t,e.height=h*t,e.setAttribute("style",`width:${c}px;height:${h}px;zoom:${1/a}`),0===c||0===h)return;r.translate(-.5,-.5),r.scale(t*a,t*a),n.draw(l)});const n=ov(uv);ov(TU)}function DU(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)}gU(e,"touchstart",function(e){a=!0,({clientX:o,clientY:i}=e.touches[0]),n=0,r=0},{capture:!1}),gU(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}),gU(e,"touchend",function(e){a=!1,o=i=0,c&&clearTimeout(c);n*=1.2,r*=1.2,requestAnimationFrame(h)},{capture:!1})}function _U(e){function t(e,t){return e*(0===t?1:_)}return s=>{const o=t(s.shiftKey&&!Wy()?s.deltaY:s.deltaX,s.deltaMode),i=t(s.shiftKey&&!Wy()?s.deltaX:s.deltaY,s.deltaMode);e(o,i)}}class OU 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 _y({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 FU 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"),_y(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"),_y(e)}onMouseDown(e){this.props.onResizeHighlight(e,this.dirX,this.dirY)}}class PU extends t.Component{static template="o-spreadsheet-Highlight";static props={range:Object,color:String};static components={Corner:FU,Border:OU};highlightState=t.useState({shiftingMode:"none"});dragNDropGrid=KV(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(),i=Ey(this.env,e);this.highlightState.shiftingMode="isResizing";const n=this.props.range.zone,r=1===t?n.left:n.right,a=1===s?n.top:n.bottom;let l=1===t?n.right:n.left,c=1===s?n.bottom:n.top,h=n,d="all";this.env.isMobile()&&(d=0===t?"vertical":0===s?"horizontal":"all"),this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{zone:h});this.dragNDropGrid.start(i,(e,t)=>{if(l!==e||c!==t){let{left:s,right:i,top:n,bottom:u}=h;"horizontal"!==d&&(c=c=ue(-1===t?c:t,0,this.env.model.getters.getNumberRows(o)-1),n=Math.min(a,c),u=Math.max(a,c)),"vertical"!==d&&(l=ue(-1===e?l:e,0,this.env.model.getters.getNumberCols(o)-1),s=Math.min(r,l),i=Math.max(r,l));const g={left:s,right:i,top:n,bottom:u};Lt(g,h)||(this.env.model.selection.selectZone({cell:{col:g.left,row:g.top},zone:g},{unbounded:!0}),h=g)}},()=>{this.highlightState.shiftingMode="none"},d)}onMoveHighlight(e){this.highlightState.shiftingMode="isMoving";const t=this.props.range.zone,s=Ey(this.env,e),o=Ly(),i=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getColIndex(e.clientX-o.left),r=this.env.model.getters.getRowIndex(e.clientY-o.top),a=-t.left,l=this.env.model.getters.getNumberCols(i)-t.right-1,c=-t.top,h=this.env.model.getters.getNumberRows(i)-t.bottom-1;let d=t;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{zone:d});let u=n,g=r;this.dragNDropGrid.start(s,(e,s)=>{if(u!==e||g!==s){u=-1===e?u:e,g=-1===s?g:s;const o=ue(u-n,a,l),i=ue(g-r,c,h),p={left:t.left+o,top:t.top+i,right:t.right+o,bottom:t.bottom+i};Lt(p,d)||(this.env.model.selection.selectZone({cell:{col:p.left,row:p.top},zone:p},{unbounded:!0}),d=p)}},()=>{this.highlightState.shiftingMode="none"})}}let MU=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 NU 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 MU(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 _y({width:`${this.props.width}px`,height:`${this.props.height}px`})}get positionCss(){return _y(this.props.position)}onScroll(e){this.props.offset!==this.scrollbar.scroll&&this.props.onScroll(this.scrollbar.scroll)}}class LU extends t.Component{static props={leftOffset:{type:Number,optional:!0}};static components={ScrollBar:NU};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(),t=this.env.model.getters.getScrollBarWidth();return{left:`${this.props.leftOffset+e}px`,bottom:"0px",height:`${t}px`,right:jy()?`${t}px`:"0"}}onScroll(e){const{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:e,offsetY:t})}}class kU extends t.Component{static props={topOffset:{type:Number,optional:!0}};static components={ScrollBar:NU};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(),t=this.env.model.getters.getScrollBarWidth();return{top:`${this.props.topOffset+e}px`,right:"0px",width:`${t}px`,bottom:jy()?`${t}px`:"0"}}onScroll(e){const{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:t,offsetY:e})}}class VU extends t.Component{static template="o-spreadsheet-Selection";static props={};static components={Highlight:PU};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 UU({refName:e}){const s=t.useRef(e);t.useEffect(e=>{e?.focus()},()=>[s.el])}class HU extends t.Component{static props={value:[Number,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},selectContentOnFocus:{type:Boolean,optional:!0}};refName="input";inputRef;setup(){this.inputRef=t.useRef(this.refName),t.useExternalListener(window,"click",e=>{e.target!==this.inputRef.el&&this.inputRef.el?.value!==this.props.value&&this.save()},{capture:!0}),this.props.autofocus&&UU({refName:this.refName}),t.onWillUpdateProps(e=>{document.activeElement!==this.inputRef.el&&this.inputRef.el&&(this.inputRef.el.value=e.value)}),t.onMounted(()=>{this.inputRef.el&&(this.inputRef.el.value=this.props.value.toString())})}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.toString(),this.inputRef.el.blur()),e.preventDefault(),e.stopPropagation()}}save(e=!1){const t=(this.inputRef.el?.value||"").trim();t!==this.props.value.toString()&&this.props.onChange(t),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(),this.props.selectContentOnFocus&&t.select(),e.preventDefault(),e.stopPropagation())}}class zU extends HU{static template="o-spreadsheet-TextInput";static components={};static props=HU.props;get inputClass(){return[this.props.class,"w-100 os-input",this.props.alwaysShowBorder?"o-input-border":void 0].filter(Te).join(" ")}}class BU 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=Kf(this.props.action);setup(){t.onWillUpdateProps(e=>{e.action!==this.props.action&&(this.actionButton=Kf(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?_y({"border-bottom":`4px solid ${this.props.selectedColor}`,height:"16px","margin-top":"2px"}):""}}class GU 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:IM};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 WU extends t.Component{static template="o-spreadsheet-NumberEditor";static props={currentValue:Number,onValueChange:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String,valueIcon:{type:String,optional:!0},min:Number,max:Number,title:String,valueList:Array};static defaultProps={onFocusInput:()=>{}};static components={Popover:zF};dropdown=t.useState({isOpen:!1});inputRef=t.useRef("inputNumber");rootEditorRef=t.useRef("NumberEditor");valueListRef=t.useRef("numberList");setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0}),t.onWillUpdateProps(e=>{this.inputRef.el&&document.activeElement!==this.inputRef.el&&(this.inputRef.el.value=e.currentValue)}),t.onMounted(()=>{this.inputRef.el&&(this.inputRef.el.value=this.props.currentValue.toString())})}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){Ny(this.valueListRef.el,e)||Ny(this.rootEditorRef.el,e)||this.closeList()}toggleList(){this.dropdown.isOpen?this.closeList():(this.props.onToggle?.(),this.inputRef.el.focus())}closeList(){this.dropdown.isOpen=!1}setValue(e){const t=ue(Math.floor(parseFloat(e)),this.props.min,this.props.max);this.props.onValueChange(t),this.closeList()}setValueFromInput(e){this.setValue(e.target.value)}setValueFromList(e){this.setValue(e)}get currentValue(){return`${this.props.currentValue}`}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if("Enter"===e.key||"Escape"===e.key){this.closeList();const t=e.target;"Escape"===e.key&&(t.value=`${this.props.currentValue}`),this.props.onToggle?.()}}}class $U extends t.Component{static template="o-spreadsheet-FontSizeEditor";static components={NumberEditor:WU};static props={currentFontSize:Number,onFontSizeChanged:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String};static defaultProps={onFocusInput:()=>{}};fontSizes=K}class qU extends t.Component{static template="o-spreadsheet.TextStyler";static components={ColorPickerWidget:GU,ActionButton:BU,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}get boldButtonAction(){return{name:vs("Bold"),execute:()=>this.toggleBold(),isActive:()=>this.bold||!1,icon:"o-spreadsheet-Icon.BOLD"}}get italicButtonAction(){return{name:vs("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:vs("Horizontal alignment"),icon:e}}get horizontalAlignActions(){return[{name:vs("Left"),execute:()=>this.updateAlignment("left"),isActive:()=>"left"===this.align,icon:"o-spreadsheet-Icon.ALIGN_LEFT"},{name:vs("Center"),execute:()=>this.updateAlignment("center"),isActive:()=>"center"===this.align,icon:"o-spreadsheet-Icon.ALIGN_CENTER"},{name:vs("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:vs("Vertical alignment"),icon:e}}get verticalAlignActions(){return[{name:vs("Top"),execute:()=>this.updateVerticalAlignment("top"),isActive:()=>"top"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_TOP"},{name:vs("Middle"),execute:()=>this.updateVerticalAlignment("middle"),isActive:()=>"middle"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},{name:vs("Bottom"),execute:()=>this.updateVerticalAlignment("bottom"),isActive:()=>"bottom"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"}]}}class ZU extends t.Component{static template="o-spreadsheet-CogWheelMenu";static components={MenuPopover:$F};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=Vy(this.buttonRef.el),this.menuState.menuItems=Yf(this.props.items))}}class jU extends t.Component{static template="o-spreadsheet-CarouselPanel";static props={onCloseSidePanel:Function,figureId:String};static components={Section:wM,TextInput:zU,TextStyler:qU,CogWheelMenu:ZU};DEFAULT_CAROUSEL_TITLE_STYLE=te;dragAndDrop=RM();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=>Vy(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 __(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(A_.getAll().find(e=>e.matcher?.(s))||A_.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 vs("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:vs("Edit chart"),execute:()=>this.editCarouselItem(e),icon:"o-spreadsheet-Icon.EDIT"}),t.push({name:vs("Pop out chart"),execute:()=>this.popOutCarouselItem(e),icon:"o-spreadsheet-Icon.EXTERNAL"})),t.push({name:vs("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 vs("The data view makes the carousel transparent, revealing the data underneath.")}}class YU extends t.Component{static template="o-spreadsheet.ChartDataSeries";static components={SelectionInput:FM,Section:wM};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?vs("Data range"):vs("Data series")}}class XU extends t.Component{static template="o-spreadsheet.ChartErrorSection";static components={Section:wM,ValidationMessages:dU};static props={messages:{type:Array,element:String}}}class KU extends t.Component{static template="o-spreadsheet.ChartLabelRange";static components={SelectionInput:FM,Checkbox:VM,Section:wM};static props={title:{type:String,optional:!0},range:String,isInvalid:Boolean,onSelectionChanged:Function,onSelectionConfirmed:Function,options:{type:Array,optional:!0}};static defaultProps={title:vs("Categories / Labels"),options:[]}}class JU extends t.Component{static template="o-spreadsheet-GenericChartConfigPanel";static components={ChartDataSeries:YU,ChartLabelRange:KU,Section:wM,Checkbox:VM,ChartErrorSection:XU};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=wg;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=>wg.Errors[e]||wg.Errors.Unexpected)}get isDatasetInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause("InvalidDataSet")}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.isCancelledBecause("InvalidLabelRange")}get dataSetsHaveTitleLabel(){return"rows"===this.datasetOrientation?vs("Use col %(column_name)s as headers",{column_name:it(this.calculateHeaderPosition()||0)}):vs("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(!xt(i))return!1;const o=sr(i),n=Et(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=ts(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(!xt(s.dataRange))return;const o=Et(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=ty({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=ty({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}=sr(s),i=o?`${o}!`:"",n=Et(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}${Dt({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}${Dt({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}${Dt({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}${Dt({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=Ab(e,t,this.labelRange),o=iC(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 Ky.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(!xt(t))return e.filter(Te).map(e=>({dataRange:e}));let{sheetName:s,xc:i}=sr(t);s=s??a,o[s]||(o[s]=[]),o[s].push(Rt(i))}for(const e in o){const s=ts(o[e]);if("columns"===t)for(const t of s)for(let s=t.left;s<=t.right;s++){const o=`${e===a?"":e+"!"}${Dt({...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+"!"}${Dt({...t,top:s,bottom:s})}`;i.push({dataRange:o})}}return i}}class QU extends JU{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 eH extends t.Component{static template="o-spreadsheet.BadgeSelection";static props={choices:Array,onChange:Function,selectedValue:String}}class tH extends t.Component{static template="o-spreadsheet.ChartTitle";static components={Section:wM,TextStyler:qU,TextInput:zU};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)}}class sH extends t.Component{static template="o-spreadsheet-AxisDesignEditor";static components={Section:wM,ChartTitle:tH,BadgeSelection:eH};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 oH 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 iH extends t.Component{static template="o-spreadsheet-GeneralDesignEditor";static components={RoundColorPicker:EM,ChartTitle:tH,Section:wM,SidePanelCollapsible:zP,RadioSelection:oH};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 nH extends t.Component{static template="o-spreadsheet-ChartHumanizeNumbers";static components={Checkbox:VM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};get title(){const e=this.env.model.getters.getLocale(),t=mn(1234567,{format:Ln({value:1234567},void 0,e),locale:e});return vs("E.g. 1234567 -> %(value)s",{value:t})}}class rH extends t.Component{static template="o-spreadsheet-ChartLegend";static components={Section:wM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e.target.value})}}class aH extends HU{static template="o-spreadsheet-NumberInput";static components={};static props={...HU.props,min:{type:Number,optional:!0},max:{type:Number,optional:!0}};debouncedOnChange=De(this.props.onChange.bind(this),100,!0);save(){const e=(this.inputRef.el?.value||"").trim();e!==this.props.value.toString()&&this.debouncedOnChange(e)}get inputClass(){return[this.props.class,"o-input"].join(" ")}}class lH extends t.Component{static template="o-spreadsheet-SeriesDesignEditor";static components={SidePanelCollapsible:zP,Section:wM,RoundColorPicker:EM};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=>!CC(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?yv(t):Wv(this.state.index,$v(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 cH extends t.Component{static template="o-spreadsheet-SeriesWithAxisDesignEditor";static components={SeriesDesignEditor:lH,Checkbox:VM,RadioSelection:oH,Section:wM,RoundColorPicker:EM,NumberInput:aH};static props={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function,slots:{type:Object,optional:!0}};axisChoices=vC;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){let s=parseInt(t)||2;s<=1&&(s=2),this.updateTrendLineValue(e,{window:s})}getDataSeriesColor(e){const t=this.props.definition.dataSets;if(!t?.[e])return"";const s=t[e].backgroundColor;return s?yv(s):Wv(e,$v(this.props.definition.dataSets.length))}getTrendLineColor(e){return this.getTrendLineConfiguration(e)?.color??Pv(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 hH extends t.Component{static template="o-spreadsheet-ChartShowValues";static components={Checkbox:VM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function,defaultValue:{type:Boolean,optional:!0}}}class dH extends t.Component{static template="o-spreadsheet-ChartWithAxisDesignPanel";static components={GeneralDesignEditor:iH,SidePanelCollapsible:zP,Section:wM,AxisDesignEditor:sH,SeriesWithAxisDesignEditor:cH,ChartLegend:rH,ChartShowValues:hH,ChartHumanizeNumbers:nH};static props={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function};get axesList(){const{useLeftAxis:e,useRightAxis:t}=pC(this.props.definition),s=[{id:"x",name:vs("Horizontal axis")}];return e&&s.push({id:"y",name:vs(t?"Left axis":"Vertical axis")}),t&&s.push({id:"y1",name:vs(e?"Right axis":"Vertical axis")}),s}}class uH extends t.Component{static template="o-spreadsheet-ChartShowDataMarkers";static components={Checkbox:VM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function}}class gH extends dH{static template="o-spreadsheet-GenericZoomableChartDesignPanel";static components={...dH.components,Checkbox:VM};onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}}class pH extends gH{static template="o-spreadsheet-ComboChartDesignPanel";static components={...gH.components,ChartShowDataMarkers:uH,RadioSelection:oH};seriesTypeChoices=[{value:"bar",label:vs("Bar")},{value:"line",label:vs("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 mH extends t.Component{static template="o-spreadsheet-FunnelChartDesignPanel";static components={ChartShowValues:hH,GeneralDesignEditor:iH,SidePanelCollapsible:zP,RoundColorPicker:EM,Section:wM,ChartHumanizeNumbers:nH};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=qC(e,this.props.definition.funnelColors);return e.map((e,s)=>({label:e||vs("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 fH extends t.Component{static template="o-spreadsheet-GaugeChartConfigPanel";static components={ChartErrorSection:XU,ChartDataSeries:YU};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=>wg.Errors[e]||wg.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 vH extends t.Component{static template="o-spreadsheet-GaugeChartDesignPanel";static components={SidePanelCollapsible:zP,Section:wM,RoundColorPicker:EM,GeneralDesignEditor:iH,ChartErrorSection:XU,StandaloneComposer:pM,ChartHumanizeNumbers:nH};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=>wg.Errors[e]||wg.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:vs("Value"),title:vs("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!==Co(e,t);const s=this.env.model.getters.evaluateFormula(this.sheetId,e);return!Si(s)&&void 0!==Co(vi(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 bH extends t.Component{static template="o-spreadsheet-GeoChartRegionSelectSection";static components={Section:wM};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 SH extends JU{static template="o-spreadsheet-GeoChartConfigPanel";static components={...JU.components,GeoChartRegionSelectSection:bH};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 CH={minColor:"#FFF5EB",midColor:"#FD8D3C",maxColor:"#7F2704"};class yH extends dH{static template="o-spreadsheet-GeoChartDesignPanel";static components={...dH.components,RoundColorPicker:EM};colorScalesChoices=wg.GeoChart.ColorScales;updateColorScaleType(e){const t=e.target.value;"custom"===t?this.updateColorScale(CH):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 IH extends JU{static template="o-spreadsheet-HierarchicalChartConfigPanel";static components={...JU.components};getLabelRangeOptions(){return[{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}}class wH extends JU{static template="o-spreadsheet-LineConfigPanel";get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.chartId);return!!(e&&e instanceof hF)&&qI(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 EH extends gH{static template="o-spreadsheet-LineChartDesignPanel";static components={...gH.components,ChartShowDataMarkers:uH}}class RH extends t.Component{static template="o-spreadsheet.PieHoleSize";static components={Section:wM,NumberInput:aH};static props={onValueChange:Function,value:Number};onChange(e){isNaN(Number(e))||this.props.onValueChange(ue(Number(e),0,95))}}class xH extends t.Component{static template="o-spreadsheet-PieChartDesignPanel";static components={GeneralDesignEditor:iH,Section:wM,ChartLegend:rH,ChartShowValues:hH,PieHoleSize:RH,Checkbox:VM,ChartHumanizeNumbers:nH};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 TH extends t.Component{static template="o-spreadsheet-RadarChartDesignPanel";static components={GeneralDesignEditor:iH,SeriesDesignEditor:lH,Section:wM,ChartLegend:rH,ChartShowValues:hH,ChartShowDataMarkers:uH,Checkbox:VM,ChartHumanizeNumbers:nH};static props={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function}}class AH extends cy{dataSets;labelRange;background;legendPosition;labelsAsText;aggregated;type="scatter";dataSetsHaveTitle;dataSetDesign;axesDesign;showValues;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=iC(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ab(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,dC,uC)}static transformDefinition(e,t,s){return lC(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}=eC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new AH(i,this.sheetId,this.getters)}getDefinitionForExcel(){const e=this.dataSets.map(e=>rC(this.getters,e)).filter(e=>""!==e.range),t=aC(this.getters,this.labelRange,gC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:bI(this.background||c),fontColor:bI(cC(this.background)),dataSets:e,labelRange:t,verticalAxis:pC(s)}}duplicateInDuplicatedSheet(e){const t=tC(this.sheetId,e,this.dataSets),s=sC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new AH(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new AH(t,e,this.getters)}}class DH extends t.Component{static template="o-spreadsheet-ScorecardChartConfigPanel";static components={SelectionInput:FM,ChartErrorSection:XU,Section:wM};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=>wg.Errors[e]||wg.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 _H extends t.Component{static template="o-spreadsheet-ScorecardChartDesignPanel";static components={GeneralDesignEditor:iH,RoundColorPicker:EM,SidePanelCollapsible:zP,Section:wM,Checkbox:VM,ChartTitle:tH,ChartHumanizeNumbers:nH};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};get colorsSectionTitle(){return"progress"===this.props.definition.baselineMode?vs("Progress bar colors"):vs("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 OH extends t.Component{static template="o-spreadsheet-SunburstChartDesignPanel";static components={GeneralDesignEditor:iH,Section:wM,SidePanelCollapsible:zP,ChartShowValues:hH,Checkbox:VM,TextStyler:qU,RoundColorPicker:EM,ChartLegend:rH,PieHoleSize:RH,ChartHumanizeNumbers:nH};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};defaults=_w;get showValues(){return this.props.definition.showValues??_w.showValues}get showLabels(){return this.props.definition.showLabels??_w.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:VM,RoundColorPicker:EM};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){const e=this.props.definition.coloringOptions??EC.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 PH extends t.Component{static template="o-spreadsheet-TreeMapColorScale";static components={RoundColorPicker:EM};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){const e=this.props.definition.coloringOptions??EC.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 MH={type:"colorScale",minColor:"#FFF5EB",midColor:"#FD8D3C",maxColor:"#7F2704"},NH={type:"categoryColor",colors:[],useValueBasedGradient:!0};class LH extends t.Component{static template="o-spreadsheet-TreeMapChartDesignPanel";static components={GeneralDesignEditor:iH,Section:wM,SidePanelCollapsible:zP,ChartShowValues:hH,Checkbox:VM,TextStyler:qU,RoundColorPicker:EM,BadgeSelection:eH,TreeMapCategoryColors:FH,TreeMapColorScale:PH,ChartHumanizeNumbers:nH};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};savedColors={categoryColors:NH,colorScale:MH};defaults=EC;get showHeaders(){return this.props.definition.showHeaders??EC.showHeaders}get showValues(){return this.props.definition.showValues??EC.showValues}get showLabels(){return this.props.definition.showLabels??EC.showLabels}get coloringOptions(){return this.props.definition.coloringOptions??EC.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:vs("Category color"),value:"categoryColor"},{label:vs("Color scale"),value:"colorScale"}]}}class kH extends t.Component{static template="o-spreadsheet-WaterfallChartDesignPanel";static components={GeneralDesignEditor:iH,ChartShowValues:hH,Checkbox:VM,SidePanelCollapsible:zP,Section:wM,RoundColorPicker:EM,AxisDesignEditor:sH,RadioSelection:oH,ChartLegend:rH,ChartHumanizeNumbers:nH};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};axisChoices=vC;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:vs("Horizontal axis")},{id:"y",name:vs("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 VH=new Fg;VH.add("line",{configuration:wH,design:EH}).add("scatter",{configuration:class extends JU{static template="o-spreadsheet-ScatterConfigPanel";get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.chartId);return!!(e&&e instanceof AH)&&qI(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:gH}).add("bar",{configuration:QU,design:gH}).add("combo",{configuration:JU,design:pH}).add("pie",{configuration:JU,design:xH}).add("gauge",{configuration:fH,design:vH}).add("scorecard",{configuration:DH,design:_H}).add("waterfall",{configuration:JU,design:kH}).add("pyramid",{configuration:JU,design:dH}).add("radar",{configuration:JU,design:TH}).add("sunburst",{configuration:IH,design:OH}).add("geo",{configuration:SH,design:yH}).add("funnel",{configuration:class extends JU{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:mH}).add("treemap",{configuration:IH,design:LH});const UH={line:vs("Line"),column:vs("Column"),bar:vs("Bar"),area:vs("Area"),pie:vs("Pie"),hierarchical:vs("Hierarchical"),misc:vs("Miscellaneous")};class HH extends t.Component{static template="o-spreadsheet-ChartTypePicker";static components={Section:wM,Popover:zF};static props={chartId:String,chartPanelStore:Object};categories=UH;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 A_.getAll())this.chartTypeByCategories[e.category]?this.chartTypeByCategories[e.category].push(e):this.chartTypeByCategories[e.category]=[e]}onExternalClick(e){Ny(this.popoverRef.el?.parentElement,e)||Ny(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 A_.getAll().find(t=>t.matcher?.(e)||!1)||A_.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=_y({width:`${i}px`})}closePopover(){this.state.popoverProps=void 0}}class zH extends gv{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=A_.get(t);return{...Ky.get(s.chartType).getChartDefinitionFromContextCreation(this.creationContexts[e]),...s.subtypeDefinition}}}class BH extends t.Component{static template="o-spreadsheet-ChartPanel";static components={Section:wM,ChartTypePicker:HH};static props={onCloseSidePanel:Function,chartId:String};panelContentRef;scrollPositions={configuration:0,design:0};store;get chartId(){return this.props.chartId}setup(){this.store=iv(zH),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=VH.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 GH extends t.Component{static template="o-spreadsheet-IconPicker";static props={onIconPicked:Function};icons=SR;iconSets=CR;onIconClick(e){e&&this.props.onIconPicked(e)}}function WH(e,s){const o=function(e){const s=t.useState({hovered:!1});return gU(e,"mouseenter",()=>s.hovered=!0),gU(e,"mouseleave",()=>s.hovered=!1),s}(e);$H({get highlights(){return o.hovered?s.highlights:[]}})}function $H(e){const s=sv(),o=iv(cM);t.onMounted(()=>{o.register(e)});let i=e.highlights;t.useEffect(e=>{Me(e,i)||(i=e,s.trigger("store-updated"))},()=>[e.highlights])}class qH extends t.Component{static template="o-spreadsheet-ConditionalFormatPreview";icons=SR;ref=t.useRef("cfPreview");setup(){WH(this.ref,this)}getPreviewImageStyle(){const e=this.props.conditionalFormat.rule;if("CellIsRule"===e.type)return _y(Ay(e.style));if("ColorScaleRule"===e.type){const t=Sv(e.minimum.color),s=e.midpoint?Sv(e.midpoint.color):null,o=Sv(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, ${Sv(e.color)} 50%, white 50%)`}return""}getDescription(){const e=this.props.conditionalFormat;switch(e.rule.type){case"CellIsRule":return nA.get(e.rule.operator).getPreview({...e.rule,type:e.rule.operator},this.env.model.getters);case"ColorScaleRule":return Ig.ColorScale;case"IconSetRule":return Ig.IconSet;case"DataBarRule":return Ig.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}))}}qH.props={conditionalFormat:Object,onPreviewClick:Function,onMouseDown:Function,class:String};class ZH extends t.Component{static template="o-spreadsheet-ConditionalFormatPreviewList";static props={conditionalFormats:Array,onPreviewClick:Function,onAddConditionalFormat:Function};static components={ConditionalFormatPreview:qH};icons=SR;dragAndDrop=RM();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=>Vy(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 jH extends t.Component{static template="o-spreadsheet-ConditionalFormattingEditor";static props={editedCf:Object,onCancel:Function,onExit:Function,isNewCf:Boolean};static components={SelectionInput:FM,IconPicker:GH,ColorPickerWidget:GU,ConditionalFormatPreviewList:ZH,Section:wM,RoundColorPicker:EM,StandaloneComposer:pM,BadgeSelection:eH,ValidationMessages:dU,SelectMenu:LM};icons=SR;iconSets=CR;getTextDecoration=Ty;colorNumberToHex=Sv;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=>Ig.Errors[e]||Ig.Errors.Unexpected)}get cfTypesValues(){return[{value:"CellIsRule",label:vs("Single color")},{value:"ColorScaleRule",label:vs("Color scale")},{value:"IconSetRule",label:vs("Icon set")},{value:"DataBarRule",label:vs("Data bar")}]}updateConditionalFormat(e){const t=e.ranges||this.state.ranges;if(this.state.ranges.some(e=>!e.match(Kn)))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:rh(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:ox("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=rM({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 NM(e=>this.editOperator(e),CI)}get selectedCriterionName(){return nA.get(this.state.rules.cellIs.operator).name}get criterionComponent(){return MM.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(!Iv(t))return;const s=this.state.rules.colorScale[e];s&&(s.color=Cv(t)),this.updateConditionalFormat({rule:this.state.rules.colorScale}),this.closeMenus()}getPreviewGradient(){const e=this.state.rules.colorScale,t=Sv(e.minimum.color),s=Sv(e.midpoint?.color||h),o=Sv(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 Sv(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:vs("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:vs("Formula"),defaultStatic:!0,invalid:s,class:"o-sidePanel-composer",defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getRangeValues(){return[this.state.rules.dataBar.rangeValues||""]}updateDataBarColor(e){Iv(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 YH extends t.Component{static template="o-spreadsheet-ConditionalFormattingPanel";static props={selection:{type:Object,optional:!0},onCloseSidePanel:Function};static components={ConditionalFormatPreviewList:ZH,ConditionalFormattingEditor:jH,Section:wM};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:ah(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 XH=new Fg;class KH extends t.Component{static template="o-spreadsheet-CustomCurrencyPanel";static components={Section:wM,Checkbox:VM};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=_n(e);if((e.symbol||e.code)&&!a.has(t))return a.add(t),{format:t,accountingFormat:On(e),example:mn(1e3,{format:t,locale:l})}}).filter(Te)}get isSameFormat(){return!!this.selectedFormat&&this.selectedFormat===this.getCommonFormat()}async updateAvailableCurrencies(){if(0===XH.getAll().length){(await(this.env.loadCurrencies?.())||[]).forEach((e,t)=>{XH.add(t.toString(),e)})}const e={name:Eg.Custom,code:"",symbol:"",decimalPlaces:2,position:"after"};this.availableCurrencies=[e,...XH.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:vs("positive")+":",value:mn(1234.56,{format:e,locale:t})},{label:vs("negative")+":",value:mn(-1234.56,{format:e,locale:t})},{label:vs("zero")+":",value:mn(0,{format:e,locale:t})}]}get selectedFormat(){const e=this.formatProposals[this.state.selectedFormatIndex];return this.state.isAccountingFormat?e?.accountingFormat:e?.format}}class JH extends t.Component{static template="o-spreadsheet-DataValidationEditor";static components={SelectionInput:FM,SelectMenu:LM,Section:wM,ValidationMessages:dU};static props={rule:{type:Object,optional:!0},onExit:Function,onCloseSidePanel:{type:Function,optional:!0}};state=t.useState({rule:this.defaultDataValidationRule,errors:[],isTypeUpdated:!1});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,this.state.isTypeUpdated=!0}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=nA.get(s.type),i=s.values.slice(0,o.numberOfValues(s)).map(e=>e?.trim()).filter(e=>""!==e&&void 0!==e).map(e=>Qc(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 NM(e=>this.onCriterionTypeChanged(e),yI)}get selectedCriterionName(){const e=this.state.rule.criterion.type;return nA.get(e).name}get defaultDataValidationRule(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones().map(t=>Dt(this.env.model.getters.getUnboundedZone(e,t)));return{id:this.env.model.uuidGenerator.smallUuid(),criterion:{type:"containsText",values:[""]},ranges:t}}get criterionComponent(){return MM.get(this.state.rule.criterion.type).component}get errorMessages(){return this.state.errors.map(e=>Dg.Errors[e]||Dg.Errors.Unexpected)}}class QH extends t.Component{static template="o-spreadsheet-DataValidationPreview";static props={onClick:Function,rule:Object};ref=t.useRef("dvPreview");setup(){WH(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 nA.get(this.props.rule.criterion.type).getPreview(this.props.rule.criterion,this.env.model.getters)}}class ez extends t.Component{static template="o-spreadsheet-DataValidationPanel";static props={onCloseSidePanel:Function};static components={DataValidationPreview:QH,DataValidationEditor:JH};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 lh(e,this.env.model.getters.getLocale())}get validationRules(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getDataValidationRules(e)}}const tz="#8B008B";var sz;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(sz||(sz={}));class oz extends gv{mutators=["updateSearchOptions","updateSearchContent","searchFormulas","selectPreviousMatch","selectNextMatch","replace"];allSheetsMatches=[];activeSheetMatches=[];specificRangeMatches=[];currentSearchRegex=null;initialShowFormulaState;preserveSelectedMatchIndex=!1;irreplaceableMatchCount=0;isSearchDirty=!1;shouldFinalizeUpdateSelection=!1;notificationStore=this.get(hM);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(cM);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(sz.previous,{jumpToMatchSheet:!0,updateSelection:!0})}selectNextMatch(){this.selectNextCell(sz.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(sz.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&&Ut(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:vs("Match(es) cannot be replaced as they are part of a formula.")}):this.notificationStore.notifyUser({type:"warning",sticky:!1,text:vs("%(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=Jc(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=jt(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:tz,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:tz,noFill:!0,thinLine:!0})}return e}}class iz extends t.Component{static template="o-spreadsheet-FindAndReplacePanel";static components={SelectionInput:FM,Section:wM,Checkbox:VM,ValidationMessages:dU};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 vs("%s matches in all sheets",this.store.allSheetMatchesCount)}get currentSheetMatchesCount(){return vs("%(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 vs("%(matches)s matches in range %(range)s of %(sheetName)s",{matches:this.store.specificRangeMatchesCount,range:Dt(s),sheetName:this.env.model.getters.getSheetName(t)})}get searchInfo(){return this.store.toSearch?[this.specificRangeMatchesCount,this.currentSheetMatchesCount,this.allSheetsMatchesCount]:[]}setup(){this.store=iv(oz),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=Gy(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 nz=Yf([rV,aV,lV,cV,hV,dV,uV,gV,pV,Qk,eV,tV,sV,oV,iV]);class rz extends t.Component{static template="o-spreadsheet-MoreFormatsPanel";static props={onCloseSidePanel:Function};get dateFormatsActions(){return nz}}class az extends gv{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=II),{type:e,fieldNameWithGranularity:t,value:s??II}}}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:gp(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:II,label:vs("(previous)")},{value:wI,label:vs("(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 lz extends t.Component{static template="o-spreadsheet-PivotMeasureDisplayPanel";static props={onCloseSidePanel:Function,pivotId:String,measure:Object};static components={Section:wM,Checkbox:VM,RadioSelection:oH};measureDisplayTypeLabels=Og.labels;measureDisplayDescription=Og.documentation;store;setup(){this.store=iv(az,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 cz(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 ts(i.map(jt)).map(t=>({range:e.getRangeFromZone(s,t),noFill:!0,color:o}))}class hz extends t.Component{static template="o-spreadsheet-PivotDeferUpdate";static props={deferUpdate:Boolean,isDirty:Boolean,toggleDeferUpdate:Function,discard:Function,apply:Function};static components={Section:wM,Checkbox:VM};get deferUpdatesLabel(){return vs("Defer updates")}get deferUpdatesTooltip(){return vs("Changing the pivot definition requires to reload the data. It may take some time.")}}class dz extends t.Component{static template="o-spreadsheet-PivotCustomGroupsCollapsible";static props={pivotId:String,customField:Object,onCustomFieldUpdated:Function};static components={SidePanelCollapsible:zP,TextInput:zU,Checkbox:VM};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:fp(vs("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=fp(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 uz(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 gz extends t.Component{static template="o-spreadsheet-AddDimensionButton";static components={Popover:zF,TextValueProvider:qP};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=iv(dM),this.autoComplete.useProvider(this.getProvider()),t.useExternalListener(window,"click",e=>{e.target!==this.buttonRef.el&&(this.popover.isOpen=!1)}),UU({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?nS(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:uz(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 pz 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:ZU,TextInput:zU};updateName(e){this.props.onNameUpdated?.(this.props.dimension,""===e||e.startsWith("=")?void 0:e)}}class mz extends t.Component{static template="o-spreadsheet-PivotDimensionGranularity";static props={dimension:Object,onUpdated:Function,availableGranularities:Set,allGranularities:Array};periods=ep}class fz extends t.Component{static template="o-spreadsheet-PivotDimensionOrder";static props={dimension:Object,onUpdated:Function}}class vz extends t.Component{static template="o-spreadsheet-PivotMeasureEditor";static components={PivotDimension:pz,StandaloneComposer:pM};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 lE(this.props.measure.computedBy?.formula??"").isBadExpression}}class bz extends t.Component{static template="o-spreadsheet-PivotSortSection";static components={Section:wM};static props={definition:Object,pivotId:String};get hasValidSort(){const e=this.env.model.getters.getPivot(this.props.pivotId);return!!this.props.definition.sortedColumn&&mp(this.props.definition.sortedColumn,e)}get sortDescription(){const e="asc"===this.props.definition.sortedColumn?.order?vs("ascending"):vs("descending");return vs("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=mn(e,{format:r,locale:s}),l=t.definition.getDimension(n.field);i.push({field:gp(l),value:a})}0===e.domain.length&&i.push({value:vs("Total")});const n=t.getMeasure(e.measure).displayName;return i.push({value:n,field:vs("Measure")}),i}}class Sz extends t.Component{static template="o-spreadsheet-PivotLayoutConfigurator";static components={AddDimensionButton:gz,PivotDimension:pz,PivotDimensionOrder:fz,PivotDimensionGranularity:mz,PivotMeasureEditor:vz,PivotSortSection:bz,PivotCustomGroupsCollapsible:dz};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=RM();AGGREGATORS=Kg;composerFocus;isDateOrDatetimeField=op;setup(){this.composerFocus=ov(mv)}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 op(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?gp(o):"";return Og.descriptions[t.type](i)}getHugeDimensionErrorMessage(e){const t=this.env.model.getters.getPivot(this.props.pivotId).getPossibleFieldValues(e);return t.length>100?vs("This dimension contains a lot of values (%s), and might slow down the pivot table.",t.length):void 0}}class Cz extends t.Component{static template="o-spreadsheet-PivotTitleSection";static components={CogWheelMenu:ZU,Section:wM,TextInput:zU};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:vs("Flip axes"),icon:"o-spreadsheet-Icon.EXCHANGE",execute:this.props.flipAxis},{name:vs("Duplicate"),icon:"o-spreadsheet-Icon.COPY",execute:()=>this.duplicatePivot()},{name:vs("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?vs("Pivot duplicated."):s.isCancelledBecause("PivotInError")?vs("Cannot duplicate a pivot in error."):vs("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(vs("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 yz extends gv{pivotId;updateMode;mutators=["reset","deferUpdates","applyUpdate","discardPendingUpdate","update"];_updatesAreDeferred;draft=null;notification=this.get(hM);alreadyNotified=!1;alreadyNotifiedForPivotSize=!1;constructor(e,t,s="canDefer"){super(e),this.pivotId=t,this.updateMode=s,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 updatesAreDeferred(){return"neverDefer"!==this.updateMode&&this._updatesAreDeferred}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){const e=l_.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:vs("Count"),type:"integer",aggregator:"sum"}],t=this.fields;for(const s in t){const o=t[s];o&&(l_.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&&(l_.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=>op(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 l_.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return l_.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:vs("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:PP(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=qD(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 Iz extends t.Component{static template="o-spreadsheet-PivotSpreadsheetSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:Sz,Section:wM,SelectionInput:FM,Checkbox:VM,PivotDeferUpdate:hz,PivotTitleSection:Cz};store;state;pivotSidePanelRef=t.useRef("pivotSidePanel");setup(){this.store=iv(yz,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 wz=new Fg;wz.add("SPREADSHEET",{editor:Iz});class Ez extends t.Component{static template="o-spreadsheet-PivotDesignPanel";static props={pivotId:String};static components={Section:wM,Checkbox:VM};store;setup(){this.store=iv(yz,this.props.pivotId,"neverDefer")}updatePivotStyleProperty(e,t){this.store.update({style:{...this.pivotStyle,[e]:t}})}get pivotStyle(){return this.env.model.getters.getPivotCoreDefinition(this.props.pivotId).style||{}}get defaultStyle(){return Zg}}class Rz extends t.Component{static template="o-spreadsheet-PivotSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:Sz,Section:wM,PivotDesignPanel:Ez};state=t.useState({panel:"configuration"});panelContentRef=t.useRef("panelContent");scrollPositions={configuration:0,design:0};setup(){$H(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 wz.get(e.type).editor}get highlights(){return cz(this.env.model.getters,this.props.pivotId)}switchPanel(e){const t=this.panelContentRef.el;t&&(this.scrollPositions[this.state.panel]=t.scrollTop),this.state.panel=e}}class xz extends t.Component{static template="o-spreadsheet-RemoveDuplicatesPanel";static components={ValidationMessages:dU,Section:wM,Checkbox:VM};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=vs("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(Ag.Errors[s]||Ag.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){const e=zt(this.env.model.getters.getSelectedZone());return vs("%(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 Tz extends t.Component{static template="o-spreadsheet-SettingsPanel";static components={Section:wM,ValidationMessages:dU,BadgeSelection:eH};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=Kc(e);return t||console.warn(`Invalid locale: ${e.code} ${e}`),t}).sort((e,t)=>e.name.localeCompare(t.name))}get numberFormatPreview(){return mn(1234567.89,{format:"#,##0.00",locale:this.env.model.getters.getLocale()})}get dateFormatPreview(){const e=this.env.model.getters.getLocale();return mn(1.6,{format:e.dateFormat,locale:e})}get dateTimeFormatPreview(){const e=this.env.model.getters.getLocale();return mn(1.6,{format:dh(e),locale:e})}get firstDayOfWeek(){const e=this.env.model.getters.getLocale().weekStart;return gn[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 Az={SplitIsDestructive:vs("This will overwrite data in the subsequent columns. Split anyway?")};const Dz=[{name:vs("Detect automatically"),value:"auto"},{name:vs("Custom separator"),value:"custom"},{name:vs("Space"),value:" "},{name:vs("Comma"),value:","},{name:vs("Semicolon"),value:";"},{name:vs("Line Break"),value:X}];class _z extends t.Component{static template="o-spreadsheet-SplitIntoColumnsPanel";static components={ValidationMessages:dU,Section:wM,Checkbox:VM};static props={onCloseSidePanel:Function};state=t.useState({separatorValue:"auto",addNewColumns:!1,customSeparator:""});setup(){const e=ov(mv);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(Az.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(Tg.Errors[s]||Tg.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(Tg.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 Dz}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}}function Oz(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 Fz extends t.Component{static template="o-spreadsheet-TableStylePreview";static components={MenuPopover:$F};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;Oz(t,NA(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)?Yf([{id:"editTableStyle",name:vs("Edit table style"),execute:e=>e.openSidePanel("TableStyleEditorPanel",{styleId:s}),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.EDIT"},{id:"deleteTableStyle",name:vs("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 Pz extends t.Component{static template="o-spreadsheet-TableStylesPopover";static components={Popover:zF,TableStylePreview:Fz};static props={tableConfig:Object,popoverProps:{type:Object,optional:!0},closePopover:Function,onStylePicked:Function,selectedStyleId:{type:String,optional:!0}};categories=mE;tableStyleListRef=t.useRef("tableStyleList");state=t.useState({selectedCategory:this.initialSelectedCategory});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}onExternalClick(e){this.tableStyleListRef.el&&!Ny(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 Mz extends t.Component{static template="o-spreadsheet-TableStylePicker";static components={TableStylesPopover:Pz,TableStylePreview:Fz};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 Nz extends t.Component{static template="o-spreadsheet-TablePanel";static components={TableStylePicker:Mz,SelectionInput:FM,ValidationMessages:dU,Checkbox:VM,Section:wM,NumberInput:aH};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(FA(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(FA(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=parseInt(e);this.updateNumberOfHeaders(t)}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===Jt(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=FA(a);this.env.model.selection.selectZone({zone:jt(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=>_g.Errors[e]||_g.Errors.Unexpected)}getCheckboxLabel(e){return _g.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:_g.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 _g.Tooltips.isDynamic}}const Lz="#3C78D8";class kz extends t.Component{static template="o-spreadsheet-TableStyleEditorPanel";static components={Section:wM,RoundColorPicker:EM,TableStylePreview:Fz};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||Lz,selectedTemplateName:e?.templateName||"lightColoredText",styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=Iv(e)?e:Lz,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 _y({background:this.state.primaryColor})}get tableTemplates(){return Object.keys(PE).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 ME(this.state.styleName,e,this.state.primaryColor)}}const Vz=new Fg;Vz.add("ConditionalFormatting",{title:vs("Conditional formatting"),Body:YH}),Vz.add("ChartPanel",{title:vs("Chart"),Body:BH,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}}}),Vz.add("FindAndReplace",{title:vs("Find and Replace"),Body:iz}),Vz.add("CustomCurrency",{title:vs("Custom currency format"),Body:KH}),Vz.add("SplitToColumns",{title:vs("Split text into columns"),Body:_z}),Vz.add("Settings",{title:vs("Spreadsheet settings"),Body:Tz}),Vz.add("RemoveDuplicates",{title:vs("Remove duplicates"),Body:xz}),Vz.add("DataValidation",{title:vs("Data validation"),Body:ez}),Vz.add("DataValidationEditor",{title:vs("Data validation"),Body:JH}),Vz.add("MoreFormats",{title:vs("More date formats"),Body:rz}),Vz.add("TableSidePanel",{title:vs("Edit table"),Body:Nz,computeState:e=>{const t=e.getFirstTableInSelection();if(!t)return{isOpen:!1};return{isOpen:!0,props:{table:e.getCoreTable(FA(t))},key:t.id}}}),Vz.add("TableStyleEditorPanel",{title:vs("Create custom table style"),Body:kz,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??"new"})}),Vz.add("PivotSidePanel",{title:(e,t)=>vs("Pivot #%s",e.model.getters.getPivotFormulaId(t.pivotId)),Body:Rz,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),Vz.add("PivotMeasureDisplayPanel",{title:(e,t)=>{const s=e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id);return vs('Measure "%s" options',s.displayName)},Body:lz,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}}}}),Vz.add("CarouselPanel",{title:vs("Carousel"),Body:jU,computeState:(e,t)=>{const s=t.figureId||e.getSelectedFigureId();return s&&e.doesCarouselExist(s)?{isOpen:!0,props:{figureId:s}}:{isOpen:!1}}});class Uz{mutators=["setSmallThreshhold"];_isSmallCallback=()=>!1;get isSmall(){return this._isSmallCallback()}setSmallThreshhold(e){this._isSmallCallback=e}}const Hz=350,zz=150;class Bz extends gv{mutators=["open","replace","toggle","close","changePanelSize","resetPanelSize","togglePinPanel","closeMainPanel","changeSpreadsheetWidth","toggleCollapsePanel"];mainPanel=void 0;secondaryPanel;availableWidth=0;screenWidthStore=this.get(Uz);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:Hz},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?Hz:this.mainPanel.size;!this.secondaryPanel&&i+Hz>this.availableWidth?this.get(hM).notifyUser({sticky:!1,type:"warning",text:vs("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:Hz},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||Hz,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,Hz);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,Hz),o=this.secondaryPanel.size),t=Math.max(this.availableWidth-o,Hz)),s.size=t}resetPanelSize(e){this[e]&&(this[e].size=Hz)}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,Hz)):(t.isCollapsed=!0,t.size=45))}computeState({componentTag:e,initialPanelProps:t}){const s=Vz.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-zz,this.secondaryPanel&&e-this.totalPanelSize<zz&&(this.secondaryPanel?.initialPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0),this.mainPanel&&e-this.totalPanelSize<zz&&(this.mainPanel.size=Math.max(e-zz,Hz))}}class Gz extends t.Component{static template="o-spreadsheet-TableResizer";static props={table:Object};state=t.useState({highlightZone:void 0});dragNDropGrid=KV(this.env);setup(){$H(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?_y({display:"none"}):_y({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";const o=Ey(this.env,e);this.dragNDropGrid.start(o,(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 Wz={ROW:jV,COL:BV,CELL:_k,GROUP_HEADERS:qV,UNGROUP_HEADERS:ZV};class $z extends t.Component{static template="o-spreadsheet-Grid";static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:nU,GridOverlay:SU,GridPopover:CU,HeadersOverlay:xU,MenuPopover:$F,Autofill:QV,ClientTag:tU,Highlight:PU,Popover:zF,VerticalScrollBar:kU,HorizontalScrollBar:LU,TableResizer:Gz,Selection:VU};HEADER_HEIGHT=A;HEADER_WIDTH=D;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=KV(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=ov(cM),this.menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.hoveredCell=ov(JF),this.composerFocusStore=ov(mv),this.DOMFocusableElementStore=ov(GP),this.sidePanel=ov(Bz),this.paintFormatStore=ov(mU),this.clientFocusStore=ov(XV),ov(YV),t.useChildSubEnv({getPopoverContainerRect:()=>Ry(this.env.model.getters.getViewportZoomLevel(),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()),AU("canvas",this.env.model,()=>this.env.model.getters.getSheetViewDimensionWithHeaders()),this.onMouseWheel=_U((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=ov(NP),t.useEffect((e,t)=>{e||t||this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),DU(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(){const e=this.env.model.getters.getScrollBarWidth();return _y({top:"26px",left:"48px",height:`calc(100% - ${A+e}px)`,width:`calc(100% - ${D+e}px)`})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>{this.env.model.getters.getActiveCell().type===Od.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===Od.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":()=>RN(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&&Zf(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":()=>SN(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?wN(this.env):i&&!o&&IN(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":()=>xN(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{x:t.x+t.width-4,y: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{...ky(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,s,o){if(o.ev.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===Od.empty?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),$P(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){const t=Gy(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";Ut(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=Wz[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement))return;if("inactive"!==this.composerFocusStore.activeComposer.editionMode)return;e?lL(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=>O_.includes(e.type)),o={content:{[SI.PlainText]:t?.getData(SI.PlainText),[SI.Html]:t?.getData(SI.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=N_(o.content),l=a.data?.clipboardId;r===l?pN(this.env,i):await mN(this.env,i,a),n&&await this.env.clipboard.write({[SI.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(!aL(this.env,"COL")&&!aL(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(MA)}get displaySelectionHandler(){return this.env.isMobile()&&"inactive"===this.composerFocusStore.activeComposer.editionMode}}function qz(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 Zz(e){const t=e.functionContext?.args[0];if(t&&["STRING","NUMBER"].includes(t.type))return t.value}const jz=new Fg;jz.add("SPREADSHEET",!1);class Yz extends t.Component{static template="o-spreadsheet-ClickableCellSortIcon";static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=ov(fU)}get style(){const e=this.env.model.getters.getCellComputedStyle(this.props.position);return _y({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=Tv(t),o=Tv(e),i=s.a+o.a*(1-s.a);return xv({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 Xz extends t.Component{static template="o-spreadsheet-FullScreenFigure";static props={};static components={ChartFigure:jF};fullScreenFigureStore;ref=t.useRef("fullScreenFigure");spreadsheetRect=HF();figureRegistry=XF;setup(){this.fullScreenFigureStore=ov(LF);const e=ov(lS);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 XF.get(this.figureUI.tag).Component}}class Kz extends t.Component{static template="o_spreadsheet.PivotHTMLRenderer";static components={Checkbox:VM};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(Ro(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${ip(e,i).join(",")})`,value:mn(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(${ip(e,i).join(",")})`,value:mn(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(${ip(e,i).join(",")})`,value:mn(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=Ro(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(${ip(e,r,n).join(",")})`,value:mn(a,{format:l,locale:c}),isMissing:!this.tracker?.isValuePresent(n,r)})}s.push(i)}return s}}class Jz{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 Qz extends Jz{copy(e,t,s="copyPaste"){}pasteFromCopy(e,t,s,o){if(1===t.length)for(const i of M_(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 eB extends Qz{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=>Ht(t,e))){const e=this.getters.getPivotCellFromPosition(c),t=rp(this.getters.getPivotFormulaId(u),e);h={id:h?.id||"",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)?"":mn(d.value,{locale:this.getters.getLocale()});h={id:h?.id||"",format:d.format,content:e,isFormula:!1,parsedValue:d.value}}i.push({content:h?.content??"",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 M_(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:M_(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=th(e[s]||"",t);o.push({content:i,evaluatedCell:{formattedValue:i}})}s.cells.push(o)}return s}}function tB(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};aM.add(`${e}_function_${t[s].name}_argument_proposals`,{sequence:50,autoSelectFirstProposal:!0,selectProposal:sB,getProposals:i})}}function sB(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)}W_.add("data_cleanup",class extends wr{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===zt(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 eB(this.getters,this.dispatch),l=a.copy(F_(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 TC(t,s+1)){const t=o.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).value);!Object.values(i).some(e=>_C(e,t))&&(i[n]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:"info",text:vs("%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(Gt).flat()){const e=this.getters.getCell({col:o,row:i,sheetId:t});if(!e)continue;const n=MC(e.content);n!==e.content&&(s+=1,this.dispatch("UPDATE_CELL",{sheetId:t,col:o,row:i,content:n}))}const o=s?vs("Trimmed whitespace from %s cells.",s):vs("No selected cells had whitespace trimmed.");this.ui.notifyUI({type:"info",text:o,sticky:!1})}}),aM.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?Lv(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()}}),aM.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(mf.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:s}])=>({text:e,description:s,htmlContent:uz(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)}}),mf.getAll().forEach(e=>tB(e.name,e.args)),aM.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:sB}),aM.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=Zz(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:vs("Count"),htmlContent:[{value:e,color:ie.STRING}],fuzzySearchKey:vs("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:sB}),aM.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=Zz(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=jz.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?qz(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:vs("%s (positional)",s.string)+(s.help?` (${s.help})`:""),htmlContent:[{value:o,color:ie.STRING}],fuzzySearchKey:s.string+o}})).filter(Te)},selectProposal:sB}),aM.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=Zz(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(un).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:vs("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:sB}),aM.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 oB=new Fg;oB.add("link",{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,s)=>Zf(t.model.getters.getEvaluatedCell(e).link,t,s),title:(e,t)=>{const s=t.getEvaluatedCell(e).link;return s?s.isExternal?vs("Go to url: %(url)s",{url:s.url}):vs("Go to %(label)s",{label:s.label}):""},sequence:5}),oB.add("dashboard_pivot_sorting",{condition:(e,t)=>{if(!t.isDashboard())return!1;const s=t.getPivotCellFromPosition(e);return xk(t,e)&&"MEASURE_HEADER"===s.type},execute:(e,t)=>{Tk(t,e,function(e,t){return iB[e.getPivotCellSortDirection(t)??"none"]}(t.model.getters,e))},component:Yz,componentProps:(e,t)=>({position:e,sortDirection:t.getPivotCellSortDirection(e)}),sequence:2});const iB={none:"asc",asc:"desc",desc:"none"};TD.add("filter_icon",(e,t)=>{if(e.isFilterHeader(t)){const s=e.isFilterActive(t),o=Rv(e.getCellComputedStyle(t).fillColor||"#fff")<.45;return{type:"filter_icon",svg:bR(s,o,!1),hoverSvg:bR(s,o,!0),priority:3,horizontalAlign:"right",size:17,margin:2,position:t,onClick:(e,t)=>{const s=t.getStore(NP),o=s.persistentCellPopover;o.isOpen&&o.col===e.col&&o.row===e.row&&"FilterMenu"===o.type?s.close():s.open(e,"FilterMenu")}}}});const nB=new Fg;nB.add("format_number_automatic",{...Gk,id:"format_number_automatic",sequence:10}).add("format_number_plain_text",{...Wk,id:"format_number_plain_text",sequence:15,separator:!0}).add("format_number_number",{...$k,id:"format_number_number",sequence:20}).add("format_number_percent",{...Zk,id:"format_number_percent",sequence:30,separator:!0}).add("format_number_currency",{...jk,id:"format_number_currency",sequence:40}).add("format_number_accounting",{...Xk,id:"format_number_accounting",sequence:45}).add("format_number_currency_rounded",{...Yk,id:"format_number_currency_rounded",sequence:50}).add("format_custom_currency",{...Jk,id:"format_custom_currency",sequence:60,separator:!0}).add("format_number_date",{...Qk,id:"format_number_date",sequence:70}).add("format_number_time",{...eV,id:"format_number_time",sequence:80}).add("format_number_date_time",{...tV,id:"format_number_date_time",sequence:90}).add("format_number_duration",{...sV,id:"format_number_duration",sequence:100,separator:!0}).add("more_formats",{...nV,id:"more_formats",sequence:120});const rB=$e(e=>En(e)?"date":e.includes("[$")?"currency":"number"),aB={name:vs("More formats"),icon:"o-spreadsheet-Icon.NUMBER_FORMATS",children:[e=>{const t=function(e){const t=new Set(nB.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=rB(o.format);"date"!==e&&"currency"!==e||s.set(o.format,Bk({descriptionValue:"currency"===e?1e3:Kk,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),Yf([...nB.getAll(),...t])}]};const lB=new QM;lB.add("file",{name:vs("File"),sequence:10}).addChild("settings",["file"],{name:vs("Settings"),sequence:200,execute:e=>e.openSidePanel("Settings"),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.COG"}).add("edit",{name:vs("Edit"),sequence:20}).addChild("undo",["edit"],{...hL,sequence:10}).addChild("redo",["edit"],{...dL,sequence:20,separator:!0}).addChild("copy",["edit"],{...uL,sequence:30}).addChild("cut",["edit"],{...gL,sequence:40}).addChild("paste",["edit"],{...pL,sequence:50}).addChild("paste_special",["edit"],{...mL,sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{...fL,sequence:10}).addChild("paste_special_format",["edit","paste_special"],{...vL,sequence:20}).addChild("edit_table",["edit"],{..._L,isVisible:AN,sequence:60}).addChild("find_and_replace",["edit"],{...bL,sequence:65,separator:!0}).addChild("delete",["edit"],{name:vs("Delete"),icon:"o-spreadsheet-Icon.TRASH",sequence:70}).addChild("edit_delete_cell_values",["edit","delete"],{...SL,sequence:10}).addChild("edit_delete_row",["edit","delete"],{...CL,sequence:20}).addChild("edit_delete_column",["edit","delete"],{...wL,sequence:30}).addChild("edit_delete_cell_shift_up",["edit","delete"],{...TL,sequence:40}).addChild("edit_delete_cell_shift_left",["edit","delete"],{...AL,sequence:50}).addChild("edit_unhide_columns",["edit"],{...VN,sequence:80}).addChild("edit_unhide_rows",["edit"],{...zN,sequence:80}).add("view",{name:vs("View"),sequence:30}).addChild("unfreeze_panes",["view"],{...BN,sequence:4}).addChild("freeze_panes",["view"],{...GN,sequence:5}).addChild("unfreeze_rows",["view","freeze_panes"],{...WN,sequence:5}).addChild("freeze_first_row",["view","freeze_panes"],{...$N,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{...qN,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{...ZN,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{...jN,sequence:25}).addChild("freeze_first_col",["view","freeze_panes"],{...YN,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{...XN,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{...KN,sequence:40}).addChild("group_headers",["view"],{name:vs("Group"),sequence:15,separator:!0,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",isVisible:_N}).addChild("group_columns",["view","group_headers"],{...tL,sequence:5}).addChild("ungroup_columns",["view","group_headers"],{...oL,isVisible:e=>aL(e,"COL"),sequence:10}).addChild("group_rows",["view","group_headers"],{...sL,sequence:15}).addChild("ungroup_rows",["view","group_headers"],{...iL,isVisible:e=>aL(e,"ROW"),sequence:20}).addChild("show",["view"],{name:vs("Show"),sequence:1,icon:"o-spreadsheet-Icon.SHOW"}).addChild("view_gridlines",["view","show"],{...JN,sequence:5}).addChild("view_formulas",["view","show"],{...eL,sequence:10}).addChild("zoom",["view"],{name:vs("Zoom"),sequence:1,icon:"o-spreadsheet-Icon.ZOOM"}).addChild("view_irregularity_map",["view"],{...QN,sequence:40,separator:!0}).add("insert",{name:vs("Insert"),sequence:40}).addChild("insert_row",["insert"],{...ML,sequence:10}).addChild("insert_row_before",["insert","insert_row"],{...LL,sequence:10}).addChild("insert_row_after",["insert","insert_row"],{...UL,sequence:20}).addChild("insert_column",["insert"],{...HL,sequence:20}).addChild("insert_column_before",["insert","insert_column"],{...BL,sequence:10}).addChild("insert_column_after",["insert","insert_column"],{...$L,sequence:20}).addChild("insert_cell",["insert"],{...qL,sequence:30}).addChild("insert_cell_down",["insert","insert_cell"],{...ZL,name:vs("Shift down"),sequence:10}).addChild("insert_cell_right",["insert","insert_cell"],{...jL,name:vs("Shift right"),sequence:20}).addChild("insert_sheet",["insert"],{...hk,sequence:40,separator:!0}).addChild("insert_chart",["insert"],{...YL,sequence:50}).addChild("insert_carousel",["insert"],{...XL,sequence:51}).addChild("insert_pivot",["insert"],{...KL,sequence:52}).addChild("insert_image",["insert"],{...JL,sequence:55}).addChild("insert_table",["insert"],{...QL,sequence:57}).addChild("insert_function",["insert"],{...ek,sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{...tk,sequence:0}).addChild("insert_function_average",["insert","insert_function"],{...sk,sequence:10}).addChild("insert_function_count",["insert","insert_function"],{...ok,sequence:20}).addChild("insert_function_max",["insert","insert_function"],{...ik,sequence:30}).addChild("insert_function_min",["insert","insert_function"],{...nk,sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{...rk,sequence:50}).addChild("categories_function_list",["insert","insert_function"],()=>{const e=mf.content;return[...new Set(mf.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:dk(o)}})}).addChild("insert_link",["insert"],{...ak,separator:!0,sequence:70}).addChild("insert_checkbox",["insert"],{...lk,sequence:80}).addChild("insert_dropdown",["insert"],{...ck,separator:!0,sequence:90}).add("format",{name:vs("Format"),sequence:50}).addChild("format_number",["format"],{...aB,name:vs("Number"),sequence:10,separator:!0}).addChild("format_bold",["format"],{...vV,sequence:20}).addChild("format_italic",["format"],{...bV,sequence:30}).addChild("format_underline",["format"],{...SV,sequence:40}).addChild("format_strikethrough",["format"],{...CV,sequence:50,separator:!0}).addChild("format_font_size",["format"],{...yV,sequence:60,separator:!0}).addChild("format_alignment",["format"],{...IV,sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{...EV,sequence:10}).addChild("format_alignment_center",["format","format_alignment"],{...RV,sequence:20}).addChild("format_alignment_right",["format","format_alignment"],{...xV,sequence:30,separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{...AV,sequence:40}).addChild("format_alignment_middle",["format","format_alignment"],{...DV,sequence:50}).addChild("format_alignment_bottom",["format","format_alignment"],{..._V,sequence:60,separator:!0}).addChild("format_wrapping",["format"],{...OV,sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{...PV,sequence:10}).addChild("format_wrapping_wrap",["format","format_wrapping"],{...MV,sequence:20}).addChild("format_wrapping_clip",["format","format_wrapping"],{...NV,sequence:30}).addChild("format_cf",["format"],{...LV,sequence:90,separator:!0}).addChild("format_clearFormat",["format"],{...kV,sequence:100,separator:!0}).add("data",{name:vs("Data"),sequence:60}).addChild("sort_range",["data"],{...Ok,sequence:10,separator:!0}).addChild("sort_ascending",["data","sort_range"],{...Fk,sequence:10}).addChild("sort_descending",["data","sort_range"],{...Lk,sequence:20}).addChild("data_cleanup",["data"],{...Pk,sequence:15}).addChild("remove_duplicates",["data","data_cleanup"],{...Mk,sequence:10}).addChild("trim_whitespace",["data","data_cleanup"],{...Nk,sequence:20}).addChild("split_to_columns",["data"],{...Uk,sequence:20}).addChild("data_validation",["data"],{name:vs("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"],{...kk,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 cz(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(cM).register(i),onStopHover:e=>e.getStore(cM).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"],Hk).addChild("reinsert_static_pivot",["data"],zk),F.forEach(e=>{lB.addChild(`zoom${e}`,["view","zoom"],function(e){return{name:vs("%(zoom_percentage)s%",{zoom_percentage:e}),execute:t=>{t.model.dispatch("SET_ZOOM",{zoom:e/100})},isActive:t=>t.model.getters.getViewportZoomLevel()===e/100,isReadonlyAllowed:!0,sequence:e}}(e))});const cB=[hB,function(e,t){return"target"in t&&Array.isArray(t.target)?{...ae(t),target:e.getSelectedZones()}:t},uB,function(e,t){return"ranges"in t?{...ae(t),ranges:e.getSelectedZones().map(t=>e.getRangeDataFromZone(e.getActiveSheetId(),t))}:t}];function hB(e,t){return"sheetId"in t?{...ae(t),sheetId:e.getActiveSheetId()}:t}function dB(e,t){return"zone"in t?{...ae(t),zone:e.getSelectedZone()}:t}function uB(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 gB=new cr;function pB(e,t){const s=e.getSelectedZone();return{...hB(e,t),elements:"COL"===t.dimension?ge(s.left,s.right+1):ge(s.top,s.bottom+1)}}function mB(e,t){const s=e.getSelectedZone();return{...ae(t),zone:s}}function fB(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 vB(e,t){const s=e.getSelectedZone();return{...hB(e,t),start:"COL"===t.dimension?s.left:s.top,end:"COL"===t.dimension?s.right:s.bottom}}function bB(e,t){let s=xC(t);for(const t of cB)s=t(e,s);return s}E_.add("UPDATE_CELL",bB),E_.add("CLEAR_CELL",bB),E_.add("CLEAR_CELLS",bB),E_.add("DELETE_CONTENT",bB),E_.add("ADD_MERGE",bB),E_.add("REMOVE_MERGE",bB),E_.add("SET_FORMATTING",bB),E_.add("CLEAR_FORMATTING",bB),E_.add("SET_BORDER",bB),E_.add("CREATE_TABLE",bB),E_.add("REMOVE_TABLE",bB),E_.add("HIDE_SHEET",bB),E_.add("ADD_COLUMNS_ROWS",function(e,t){const s=e.getActivePosition();return{...hB(e,t),base:"COL"===t.dimension?s.col:s.row}}),E_.add("REMOVE_COLUMNS_ROWS",pB),E_.add("HIDE_COLUMNS_ROWS",pB),E_.add("RESIZE_COLUMNS_ROWS",pB),E_.add("CREATE_SHEET",function(e,t){const s=ae(t);s.sheetId=gB.smallUuid();const o=t.name||e.getSheet(e.getActiveSheetId()).name,i=o.match(/(.+?)\d*$/)?.[1]||o;return s.name=e.getNextSheetName(i),s}),E_.add("CREATE_FIGURE",function(e,t){const s=uB(e,hB(e,t));return s.figureId=gB.smallUuid(),s}),E_.add("CREATE_CHART",function(e,t){const s=gB.smallUuid();return{...hB(e,t),figureId:s,chartId:s}}),E_.add("CREATE_IMAGE",function(e,t){return{...hB(e,t),figureId:gB.smallUuid()}}),E_.add("GROUP_HEADERS",vB),E_.add("UNGROUP_HEADERS",vB),E_.add("UNFOLD_HEADER_GROUPS_IN_ZONE",dB),E_.add("FOLD_HEADER_GROUPS_IN_ZONE",dB),R_.add("PASTE",function(e,t){return{type:"REPEAT_PASTE",pasteOption:ae(t.pasteOption),target:e.getSelectedZones()}}),R_.add("INSERT_CELL",mB),R_.add("DELETE_CELL",mB),R_.add("AUTORESIZE_COLUMNS",fB),R_.add("AUTORESIZE_ROWS",fB),R_.add("SORT_CELLS",function(e,t){const s=e.getSelectedZone();return{...hB(e,t),col:s.left,row:s.top,zone:s}}),R_.add("SUM_SELECTION",bB),R_.add("SET_DECIMAL",bB),R_.add("DELETE_UNFILTERED_CONTENT",bB);const SB=new class extends Fg{mapping={};uuidGenerator=new cr;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 CB{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 yB=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];class IB 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(yB,{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 _y({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 wB 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:IB};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 _y({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{...Vy(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{...Vy(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 EB 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:wB,ColorPicker:IM};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=ov(GP),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(vs("The sheet name cannot be empty."),o):i.reasons.includes("DuplicatedSheetName")?e.raiseError(vs("A sheet with the name %s already exists. Please select another name.",s),o):i.reasons.includes("ForbiddenCharactersInSheetName")&&e.raiseError(vs("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 Vy(this.sheetDivRef.el)}get contextMenuRegistry(){return function(e){const t=new QM;return t.add("delete",{...qM,sequence:10}).add("hide_sheet",{...JM,sequence:20}).add("duplicate",{...ZM,sequence:30,separator:!0}).add("rename",{...jM(e),sequence:40}).add("change_color",{...YM(e),sequence:50,separator:!0}).add("move_right",{...XM,sequence:60}).add("move_left",{...KM,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 _y({background:this.env.model.getters.getSheet(this.props.sheetId).color||""})}}const RB=[{name:vs("Sum"),types:[Od.number],compute:(e,t)=>Rr([[e]],t)},{name:vs("Avg"),types:[Od.number],compute:(e,t)=>Wa([[e]],t)},{name:vs("Min"),types:[Od.number],compute:(e,t)=>ja([[e]],t).value},{name:vs("Max"),types:[Od.number],compute:(e,t)=>Za([[e]],t).value},{name:vs("Count"),types:[Od.number,Od.text,Od.boolean,Od.error],compute:e=>qa([[e]])},{name:vs("Count Numbers"),types:[Od.number,Od.text,Od.boolean,Od.error],compute:(e,t)=>$a([[e]],t)}];class xB extends gv{statisticFnResults=this._computeStatisticFnResults();isDirty=!1;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.handleEvent.bind(this)})}handle(e){switch((hr.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!==Od.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 RB){let t;const s=l(e.types.sort().join(","));s.length&&(t=Oe(()=>e.compute(s,r))),a[e.name]=t}return a}}class TB extends t.Component{static template="o-spreadsheet-BottomBarStatistic";static props={openContextMenu:Function,closeContextMenu:Function};static components={Ripple:wB};selectedStatisticFn="";store;setup(){this.store=ov(xB),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 QM;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?mn(s(),{locale:t}):"__")}}class AB extends t.Component{static template="o-spreadsheet-BottomBar";static props={onClick:Function};static components={MenuPopover:$F,Ripple:wB,BottomBarSheet:EB,BottomBarStatistic:TB};bottomBarRef=t.useRef("bottomBar");sheetListRef=t.useRef("sheetList");dragAndDrop=RM();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(vs("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 QM,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 DB extends gv{_clickableCells=t.markRaw({});_registryItems=t.markRaw(oB.getAll().sort((e,t)=>e.sequence-t.sequence));handle(e){(hr.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(oB.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,jt(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 _B extends t.Component{static template="o-spreadsheet-SpreadsheetDashboard";static props={getGridSize:Function};static components={GridOverlay:SU,GridPopover:CU,Popover:zF,VerticalScrollBar:kU,HorizontalScrollBar:LU};cellPopovers;onMouseWheel;canvasPosition;hoveredCell;clickableCellsStore;gridRef;setup(){this.gridRef=t.useRef("grid"),this.hoveredCell=ov(JF),this.clickableCellsStore=ov(DB),t.useChildSubEnv({getPopoverContainerRect:()=>Ry(this.env.model.getters.getViewportZoomLevel(),this.getGridRect())}),AU("canvas",this.env.model,()=>this.env.model.getters.getSheetViewDimension()),this.onMouseWheel=_U((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=ov(NP),DU(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 _y({"max-width":`${s}px`})}get gridOverlayDimensions(){return _y({height:"100%",width:"100%"})}getCellClickableStyle(e){return _y({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,qy(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{...ky(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}}class OB 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;WV(this.env,e,this.dimension,t,s)}get groupBoxStyle(){const e=this.groupBox;return _y({top:`${e.groupRect.y}px`,left:`${e.groupRect.x}px`,width:`${e.groupRect.width}px`,height:`${e.groupRect.height}px`})}get groupButtonStyle(){return _y({"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=Yf([{id:"toggle_group",name:e=>{const i=e.model.getters.getActiveSheetId(),n=e.model.getters.isGroupFolded(i,t,s,o);return vs(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();WV(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:vs("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,...$V(e,t)]}(t,this.dimension,o.start,o.end);this.props.openContextMenu(s,i)}}class FB extends OB{dimension="ROW";get groupBorderStyle(){const e=this.groupBox;return 0===this.groupBox.groupRect.height?"":_y({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 _y({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:O,height:r};return{headerRect:a,groupRect:{x:this.props.layerOffset,y:a.y,width:O,height:a.height+(i-o)},isEndHidden:this.env.model.getters.isRowHidden(e,s)}}}class PB extends OB{dimension="COL";get groupBorderStyle(){const e=this.groupBox;return 0===e.groupRect.width?"":_y({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 _y({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:O};return{headerRect:a,groupRect:{x:a.x,y:this.props.layerOffset,width:a.width+(i-o),height:O},isEndHidden:this.env.model.getters.isColHidden(e,s)}}}class MB extends t.Component{static template="o-spreadsheet-HeaderGroupContainer";static props={dimension:String,layers:Array};static components={RowGroup:FB,ColGroup:PB,MenuPopover:$F};menu=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});getLayerOffset(e){return e*O}onContextMenu(e){const t=this.env.model.getters.getActiveSheetId(),s={x:e.clientX,y:e.clientY},o=$V(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?FB:PB}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",_y(s)}get frozenPaneContainerStyle(){const e={};return"COL"===this.props.dimension?e.width=`${this.frozenPaneContainerSize}px`:e.height=`${this.frozenPaneContainerSize}px`,_y(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 NB 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=HF();getTitle(){const e=this.props.panelContent;return"function"==typeof e.title?e.title(this.env,this.props.panelProps):e.title}get pinInfoMessage(){return vs("Pin this panel to allow to open another side panel beside it.")}}class LB extends t.Component{static template="o-spreadsheet-SidePanels";static props={};static components={SidePanel:NB};sidePanelStore;spreadsheetRect=HF();setup(){this.sidePanelStore=ov(Bz),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;CM(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:Vz.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:Vz.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?_y({width:`${this.sidePanelStore.secondaryPanel.size}px`}):""},{key:this.sidePanelStore.mainPanelKey,props:this.mainPanelProps,style:this.sidePanelStore.mainPanel?_y({width:`${this.sidePanelStore.mainPanel.size}px`}):""}].filter(e=>e.key&&e.props)}}class kB extends t.Component{static template="o-spreadsheet-RibbonMenu";static props={onClose:Function};static components={Menu:kF};rootItems=lB.getMenuItems();menuRef=t.useRef("menu");containerRef=t.useRef("container");state=t.useState({menuItems:this.rootItems,title:vs("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 _y({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?vs("Go to previous menu"):vs("Close menu bar")}}class VB extends t.Component{static components={Composer:oM,BottomBar:AB,Ripple:wB,RibbonMenu:kB};static template="o-spreadsheet-SmallBottomBar";static props={onClick:Function};composerFocusStore;composerStore;composerInterface;composerRef=t.useRef("bottombarComposer");menuState=t.useState({isOpen:!1});setup(){this.composerFocusStore=ov(mv);const e=ov(oU);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?Vy(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:_y({height:"inactive"===this.focus?"26px":"fit-content","max-height":"130px"}),showAssistant:!Yy(),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 UB extends t.Component{static template="o-spreadsheet-TopBarComposer";static props={};static components={Composer:oM};composerFocusStore;composerStore;composerInterface;setup(){this.composerFocusStore=ov(mv);const e=ov(oU);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",_y(e)}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}}class HB{mutators=["closeDropdowns","openDropdown"];_currentDropdown=null;closeDropdowns(){this._currentDropdown=null}openDropdown(e){this._currentDropdown=e}get currentDropdown(){return this._currentDropdown}}function zB(){const e=t.useComponent(),s=ov(HB);return t.onWillUnmount(()=>{e===s.currentDropdown&&s.closeDropdowns()}),{closeDropdowns:()=>s.closeDropdowns(),openDropdown:()=>{s.openDropdown(e)},get isActive(){return s.currentDropdown===e}}}const BB=[[["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 GB 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:GU,Popover:zF};BORDER_POSITIONS=BB;lineStyleButtonRef=t.useRef("lineStyleButton");borderStyles=Ds;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 WB 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:GB};topBarToolStore;borderEditorButtonRef=t.useRef("borderEditorButton");state=t.useState({currentColor:U,currentStyle:V,currentPosition:void 0});setup(){this.topBarToolStore=zB(),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 $B extends t.Component{static template="o-spreadsheet-PaintFormatButton";static props={class:{type:String,optional:!0}};paintFormatStore;setup(){this.paintFormatStore=ov(mU)}get isActive(){return this.paintFormatStore.isActive}onDblClick(){this.paintFormatStore.activate({persistent:!0})}togglePaintFormat(){this.isActive?this.paintFormatStore.cancel():this.paintFormatStore.activate({persistent:!1})}}class qB extends t.Component{static template="o-spreadsheet-TableDropdownButton";static components={TableStylesPopover:Pz,ActionButton:BU};static props={class:{type:String,optional:!0}};topBarToolStore;state=t.useState({popoverProps:void 0});setup(){this.topBarToolStore=zB()}onStylePicked(e){const t=this.env.model.getters.getActiveSheetId(),s={...this.tableConfig,styleId:e};fN(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()?vs("Edit table"):vs("Insert table"),icon:e=>e.model.getters.getFirstTableInSelection()?"o-spreadsheet-Icon.EDIT_TABLE":"o-spreadsheet-Icon.PAINT_TABLE"}}get tableConfig(){return{...fE,numberOfHeaders:1,bandedRows:!0}}}class ZB extends t.Component{static components={ColorPickerWidget:GU};static props={class:String,style:String,icon:String,title:String};static template="o-spreadsheet-ColorEditor";topBarToolStore;state=t.useState({isOpen:!1});setup(){this.topBarToolStore=zB()}get currentColor(){return this.env.model.getters.getCurrentStyle()[this.props.style]||("textColor"===this.props.style?"#000000":"#ffffff")}setColor(e){bN(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 jB extends t.Component{static template="o-spreadsheet-DropdownAction";static components={ActionButton:BU,Popover:zF};static props={parentAction:Object,childActions:Array,class:String,childClass:String};topBarToolStore;actionRef=t.useRef("actionRef");setup(){this.topBarToolStore=zB()}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 YB extends t.Component{static components={FontSizeEditor:$U};static props={class:String};static template="o-spreadsheet-TopBarFontSizeEditor";topBarToolStore;setup(){this.topBarToolStore=zB()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||L}setFontSize(e){bN(this.env,{fontSize:e})}onToggle(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}}class XB extends t.Component{static template="o-spreadsheet-NumberFormatsTool";static components={MenuPopover:$F,ActionButton:BU};static props={class:String};formatNumberMenuItemSpec=aB;topBarToolStore;buttonRef=t.useRef("buttonRef");state=t.useState({anchorRect:{x:0,y:0,width:0,height:0},menuItems:[]});setup(){this.topBarToolStore=zB()}toggleMenu(){if(this.isActive)this.topBarToolStore.closeDropdowns();else{const e=Kf(this.formatNumberMenuItemSpec);this.state.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.anchorRect=Vy(this.buttonRef.el),this.topBarToolStore.openDropdown()}}get isActive(){return this.topBarToolStore.isActive}}class KB extends t.Component{static template="o-spreadsheet-TopBarZoom";static components={NumberEditor:WU};static props={class:String};topBarToolStore;valueList=F;setup(){this.topBarToolStore=zB()}get currentFontSize(){return 100*(this.env.model.getters.getViewportZoomLevel()||1)}setZoom(e){this.env.model.dispatch("SET_ZOOM",{zoom:e/100})}toggle(){this.topBarToolStore.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}}const JB=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)}};JB.add("edit").addChild("edit",{component:BU,props:{action:hL,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("edit",{component:BU,props:{action:dL,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("edit",{component:$B,props:{class:"o-hoverable-button o-toolbar-button o-mobile-disabled"},sequence:3}).addChild("edit",{component:BU,props:{action:kV,class:"o-hoverable-button o-toolbar-button"},sequence:4}).addChild("edit",{component:KB,props:{class:"o-menu-item-button o-hoverable-button o-toolbar-button"},sequence:5}).add("numberFormat").addChild("numberFormat",{component:BU,props:{action:qk,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("numberFormat",{component:BU,props:{action:fV,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("numberFormat",{component:BU,props:{action:mV,class:"o-hoverable-button o-toolbar-button"},sequence:3}).addChild("numberFormat",{component:XB,props:{class:"o-menu-item-button o-hoverable-button o-toolbar-button"},sequence:4}).add("fontSize").addChild("fontSize",{component:YB,props:{class:"o-hoverable-button o-toolbar-button"},sequence:3}).add("textStyle").addChild("textStyle",{component:BU,props:{action:vV,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("textStyle",{component:BU,props:{action:bV,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("textStyle",{component:BU,props:{action:CV,class:"o-hoverable-button o-toolbar-button"},sequence:3}).addChild("textStyle",{component:ZB,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button",style:"textColor",icon:"o-spreadsheet-Icon.TEXT_COLOR",title:vs("Text Color")},sequence:4}).add("cellStyle").addChild("cellStyle",{component:ZB,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button",style:"fillColor",icon:"o-spreadsheet-Icon.FILL_COLOR",title:vs("Fill Color")},sequence:1}).addChild("cellStyle",{component:WB,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:2}).addChild("cellStyle",{component:BU,props:{action:DL,class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:3}).add("alignment").addChild("alignment",{component:jB,props:{parentAction:wV,childActions:[EV,RV,xV],class:"o-hoverable-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:1}).addChild("alignment",{component:jB,props:{parentAction:TV,childActions:[AV,DV,_V],class:"o-hoverable-button o-menu-item-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:2}).addChild("alignment",{component:jB,props:{parentAction:FV,childActions:[PV,MV,NV],class:"o-hoverable-button o-menu-item-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:3}).add("misc").addChild("misc",{component:qB,props:{class:"o-toolbar-button o-hoverable-button o-menu-item-button o-mobile-disabled"},sequence:1}).addChild("misc",{component:BU,props:{action:Vk,class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:2});class QB extends t.Component{static template="o-spreadsheet-TopBar";static props={onClick:Function,dropdownMaxHeight:Number};static components={MenuPopover:$F,TopBarComposer:UB,Popover:zF};toolsCategories=JB.getCategories();state=t.useState({menuState:{isOpen:!1,anchorRect:null,menuItems:[]},invisibleToolsCategories:[],toolsPopoverState:{isOpen:!1}});isSelectingMenu=!1;openedEl=null;menus=[];toolbarMenuRegistry=JB;formatNumberMenuItemSpec=aB;isntToolbarMenu=!1;composerFocusStore;fingerprints;topBarToolStore;toolBarContainerRef=t.useRef("toolBarContainer");toolbarRef=t.useRef("toolBar");moreToolsContainerRef=t.useRef("moreToolsContainer");moreToolsButtonRef=t.useRef("moreToolsButton");spreadsheetRect=HF();setup(){this.composerFocusStore=ov(mv),this.fingerprints=ov(MN),this.topBarToolStore=ov(HB),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=Vy(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=lB.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){bN(this.env,{[e]:t}),this.onClick()}setFontSize(e){bN(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?Vy(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 eG{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({[SI.PlainText]:this.getBlob(e,SI.PlainText),[SI.Html]:this.getBlob(e,SI.Html)})]))}catch(e){}}else await this.writeText(e[SI.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:{[SI.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(O_.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 tG 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:QB,Grid:$z,BottomBar:AB,SmallBottomBar:VB,SidePanels:LB,SpreadsheetDashboard:_B,HeaderGroupContainer:MB,FullScreenFigure:Xz};sidePanel;spreadsheetRef=t.useRef("spreadsheet");spreadsheetRect=HF();_focusGrid;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){const e={},t=this.env.model.getters.getScrollBarWidth();this.env.isDashboard()?e["grid-template-rows"]="auto":e["grid-template-rows"]="min-content auto min-content";const s=this.sidePanel.mainPanel?`${this.sidePanel.totalPanelSize||Hz}px`:"auto";return e["grid-template-columns"]=`auto ${s}`,e["--os-scrollbar-width"]=`${t}px`,_y(e)}setup(){if(!("isSmall"in this.env)){const e=function(){const e=HF();return{get isSmall(){return e.width<768}}}();t.useSubEnv({get isSmall(){return e.isSmall}})}const e=sv();e.inject(lv,this.model);const s=this.env;e.get(Uz).setSmallThreshhold(()=>s.isSmall),this.notificationStore=ov(hM),this.composerFocusStore=ov(mv),this.sidePanel=ov(Bz);const o=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:o?new CB(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 eG(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:Xy}),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 rS.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:vs("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=O*this.rowLayers.length,t=O*this.colLayers.length;return _y({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`,zoom:`${this.env.model.getters.getViewportZoomLevel()}`})}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.env.model.getters.getViewportZoomLevel(),t=this.env.model.getters.getScrollBarWidth(),s=this.spreadsheetRef.el?.querySelector(".o-spreadsheet-topbar-wrapper")?.getBoundingClientRect().height||0,o=this.spreadsheetRef.el?.querySelector(".o-spreadsheet-bottombar-wrapper")?.getBoundingClientRect().height||0,i=this.spreadsheetRef.el?.querySelector(".o-grid")?.getBoundingClientRect().width||0,n=(this.spreadsheetRef.el?.getBoundingClientRect().height||0)-(this.spreadsheetRef.el?.querySelector(".o-column-groups")?.getBoundingClientRect().height||0)-s-o;return{width:Math.max(i/e-t,0),height:Math.max(n/e-t,0)}}}class sG extends cy{dataSets;labelRange;background;legendPosition;aggregated;dataSetsHaveTitle;dataSetDesign;axesDesign;type="combo";showValues;hideDataMarkers;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=iC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ab(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 lC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,dC,uC)}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,gC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:bI(this.background||c),fontColor:bI(cC(this.background)),dataSets:e,labelRange:t,verticalAxis:pC(s)}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=eC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new sG(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=tC(this.sheetId,e,this.dataSets),s=sC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new sG(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new sG(t,e,this.getters)}}class oG extends cy{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=iC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ab(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 lC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,dC,uC)}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=tC(this.sheetId,e,this.dataSets),s=sC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new oG(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new oG(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}=eC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new oG(i,this.sheetId,this.getters)}}class iG extends cy{dataSets;labelRange;background;legendPosition;type="geo";dataSetsHaveTitle;dataSetDesign;colorScale;missingValueColor;region;constructor(e,t,s){super(e,t,s),this.dataSets=iC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ab(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 lC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,dC,uC)}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=tC(this.sheetId,e,this.dataSets),s=sC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new iG(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new iG(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}=eC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new iG(i,this.sheetId,this.getters)}}class nG extends cy{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=iC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ab(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 lC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,dC,uC)}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=tC(this.sheetId,e,this.dataSets),s=sC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new nG(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new nG(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,gC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),o=this.getDefinition(),i=LI(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:bI(this.background||c),fontColor:bI(cC(this.background)),dataSets:t,labelRange:s,verticalAxis:pC(o),maxValue:r}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=eC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new nG(i,this.sheetId,this.getters)}}class rG extends cy{dataSets;labelRange;background;legendPosition;stacked;aggregated;type="radar";dataSetsHaveTitle;dataSetDesign;fillArea;showValues;hideDataMarkers;constructor(e,t,s){super(e,t,s),this.dataSets=iC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ab(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 lC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,dC,uC)}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=tC(this.sheetId,e,this.dataSets),s=sC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new rG(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new rG(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,gC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:bI(this.background||c),fontColor:bI(cC(this.background)),dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=eC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new rG(i,this.sheetId,this.getters)}}class aG extends cy{dataSets;labelRange;background;legendPosition;type="sunburst";dataSetsHaveTitle;showValues;showLabels;valuesDesign;groupColors;pieHolePercentage;constructor(e,t,s){super(e,t,s),this.dataSets=iC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ab(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 lC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,dC,uC)}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=tC(this.sheetId,e,this.dataSets),s=sC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new aG(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new aG(t,e,this.getters)}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=eC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new aG(i,this.sheetId,this.getters)}}class lG extends cy{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=iC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ab(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 lC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,dC,uC)}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=tC(this.sheetId,e,this.dataSets),s=sC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new lG(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new lG(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}=eC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new lG(i,this.sheetId,this.getters)}}Ky.add("bar",{match:e=>"bar"===e,createChart:(e,t,s)=>new Jw(e,t,s),getChartRuntime:Qw,validateChartDefinition:Jw.validateChartDefinition,transformDefinition:Jw.transformDefinition,getChartDefinitionFromContextCreation:Jw.getDefinitionFromContextCreation,sequence:10}),Ky.add("combo",{match:e=>"combo"===e,createChart:(e,t,s)=>new sG(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=NI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:BC(s,o)},options:{...dI,layout:nw(0,o),scales:vw(s,o),plugins:{title:Nw(s,t),legend:dw(s),tooltip:Uw(s,o),chartShowValuesPlugin:Ow(s,o)}}},background:e.background||c}},validateChartDefinition:sG.validateChartDefinition,transformDefinition:sG.transformDefinition,getChartDefinitionFromContextCreation:sG.getDefinitionFromContextCreation,sequence:15}),Ky.add("line",{match:e=>"line"===e,createChart:(e,t,s)=>new hF(e,t,s),getChartRuntime:dF,validateChartDefinition:hF.validateChartDefinition,transformDefinition:hF.transformDefinition,getChartDefinitionFromContextCreation:hF.getDefinitionFromContextCreation,sequence:20}),Ky.add("pie",{match:e=>"pie"===e,createChart:(e,t,s)=>new uF(e,t,s),getChartRuntime:gF,validateChartDefinition:uF.validateChartDefinition,transformDefinition:uF.transformDefinition,getChartDefinitionFromContextCreation:uF.getDefinitionFromContextCreation,sequence:30}),Ky.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,s)=>new vy(e,t,s),getChartRuntime:Sy,validateChartDefinition:vy.validateChartDefinition,transformDefinition:vy.transformDefinition,getChartDefinitionFromContextCreation:vy.getDefinitionFromContextCreation,sequence:40}),Ky.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,s)=>new nF(e,t,s),getChartRuntime:rF,validateChartDefinition:nF.validateChartDefinition,transformDefinition:nF.transformDefinition,getChartDefinitionFromContextCreation:nF.getDefinitionFromContextCreation,sequence:50}),Ky.add("scatter",{match:e=>"scatter"===e,createChart:(e,t,s)=>new AH(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=kI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"line",data:{labels:o.labels,datasets:HC(s,o)},options:{...dI,layout:nw(0,o),scales:Sw(s,o),plugins:{title:Nw(s,t),legend:hw(s),tooltip:Hw(s,o),chartShowValuesPlugin:Ow(s,o)}}},background:e.background||c}},validateChartDefinition:AH.validateChartDefinition,transformDefinition:AH.transformDefinition,getChartDefinitionFromContextCreation:AH.getDefinitionFromContextCreation,sequence:60}),Ky.add("waterfall",{match:e=>"waterfall"===e,createChart:(e,t,s)=>new pF(e,t,s),getChartRuntime:mF,validateChartDefinition:pF.validateChartDefinition,transformDefinition:pF.transformDefinition,getChartDefinitionFromContextCreation:pF.getDefinitionFromContextCreation,sequence:70}),Ky.add("pyramid",{match:e=>"pyramid"===e,createChart:(e,t,s)=>new nG(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=LI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:kC(s,o)},options:{...dI,indexAxis:"y",layout:nw(0,o),scales:yw(s,o),plugins:{title:Nw(s,t),legend:aw(s),tooltip:Gw(s,o),chartShowValuesPlugin:Pw(s,o)}}},background:e.background||c}},validateChartDefinition:nG.validateChartDefinition,transformDefinition:nG.transformDefinition,getChartDefinitionFromContextCreation:nG.getDefinitionFromContextCreation,sequence:80,dataSeriesLimit:2}),Ky.add("radar",{match:e=>"radar"===e,createChart:(e,t,s)=>new rG(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=UI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"radar",data:{labels:o.labels,datasets:GC(s,o)},options:{...dI,layout:nw(0,o),scales:Iw(s,o),plugins:{title:Nw(s,t),legend:gw(s),tooltip:Ww(s,o),chartShowValuesPlugin:Ow(s,o)}}},background:e.background||c}},validateChartDefinition:rG.validateChartDefinition,transformDefinition:rG.transformDefinition,getChartDefinitionFromContextCreation:rG.getDefinitionFromContextCreation,sequence:80}),Ky.add("geo",{match:e=>"geo"===e,createChart:(e,t,s)=>new iG(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=HI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"choropleth",data:{datasets:WC(s,o)},options:{...dI,layout:nw(0,o),scales:ww(s,o),plugins:{title:Nw(s,t),tooltip:$w(s,o),legend:{display:!1}}}},background:e.background||c}},validateChartDefinition:iG.validateChartDefinition,transformDefinition:iG.transformDefinition,getChartDefinitionFromContextCreation:iG.getDefinitionFromContextCreation,sequence:90,dataSeriesLimit:1}),Ky.add("funnel",{match:e=>"funnel"===e,createChart:(e,t,s)=>new oG(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=zI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"funnel",data:{labels:o.labels,datasets:$C(s,o)},options:{...dI,indexAxis:"y",layout:nw(0,o),scales:Ew(0,o),plugins:{title:Nw(s,t),legend:{display:!1},tooltip:qw(s,o),chartShowValuesPlugin:Ow(s,o)}}},background:e.background||c}},validateChartDefinition:oG.validateChartDefinition,transformDefinition:oG.transformDefinition,getChartDefinitionFromContextCreation:oG.getDefinitionFromContextCreation,sequence:100,dataSeriesLimit:1}),Ky.add("sunburst",{match:e=>"sunburst"===e,createChart:(e,t,s)=>new aG(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=BI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"doughnut",data:{datasets:ZC(s,o)},options:{cutout:void 0===e.pieHolePercentage?"25%":`${e.pieHolePercentage}%`,...dI,layout:nw(0,o),plugins:{title:Nw(s,t),legend:pw(s),tooltip:Zw(s,o),sunburstLabelsPlugin:Fw(s,o),sunburstHoverPlugin:{enabled:!0}}}},background:e.background||c}},validateChartDefinition:aG.validateChartDefinition,transformDefinition:aG.transformDefinition,getChartDefinitionFromContextCreation:aG.getDefinitionFromContextCreation,sequence:30}),Ky.add("treemap",{match:e=>"treemap"===e,createChart:(e,t,s)=>new lG(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=BI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"treemap",data:{labels:o.labels,datasets:KC(s,o)},options:{...dI,layout:nw(0,o),plugins:{title:Nw(s,t),legend:{display:!1},tooltip:jw(s,o)}}},background:e.background||c}},validateChartDefinition:lG.validateChartDefinition,transformDefinition:lG.transformDefinition,getChartDefinitionFromContextCreation:lG.getDefinitionFromContextCreation,sequence:100}),A_.add("line",{matcher:e=>"line"===e.type&&!e.stacked&&!e.fillArea,displayName:vs("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:vs("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:vs("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:vs("Stacked Area"),chartType:"line",chartSubtype:"stacked_area",subtypeDefinition:{stacked:!0,fillArea:!0},category:"area",preview:"o-spreadsheet-ChartPreview.STACKED_AREA_CHART"}).add("scatter",{displayName:vs("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:vs("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:vs("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:vs("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:vs("Stacked Bar"),chartType:"bar",chartSubtype:"stacked_bar",subtypeDefinition:{horizontal:!0,stacked:!0},category:"bar",preview:"o-spreadsheet-ChartPreview.STACKED_BAR_CHART"}).add("combo",{displayName:vs("Combo"),chartSubtype:"combo",chartType:"combo",category:"line",preview:"o-spreadsheet-ChartPreview.COMBO_CHART"}).add("pie",{matcher:e=>"pie"===e.type&&!e.isDoughnut,displayName:vs("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:vs("Doughnut"),chartSubtype:"doughnut",chartType:"pie",subtypeDefinition:{isDoughnut:!0},category:"pie",preview:"o-spreadsheet-ChartPreview.DOUGHNUT_CHART"}).add("gauge",{displayName:vs("Gauge"),chartSubtype:"gauge",chartType:"gauge",category:"misc",preview:"o-spreadsheet-ChartPreview.GAUGE_CHART"}).add("scorecard",{displayName:vs("Scorecard"),chartSubtype:"scorecard",chartType:"scorecard",category:"misc",preview:"o-spreadsheet-ChartPreview.SCORECARD_CHART"}).add("waterfall",{displayName:vs("Waterfall"),chartSubtype:"waterfall",chartType:"waterfall",category:"misc",preview:"o-spreadsheet-ChartPreview.WATERFALL_CHART"}).add("pyramid",{displayName:vs("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:vs("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:vs("Filled Radar"),chartType:"radar",chartSubtype:"filled_radar",subtypeDefinition:{fillArea:!0},category:"misc",preview:"o-spreadsheet-ChartPreview.FILLED_RADAR_CHART"}).add("geo",{displayName:vs("Geo Chart"),chartSubtype:"geo",chartType:"geo",category:"misc",preview:"o-spreadsheet-ChartPreview.GEO_CHART"}).add("funnel",{displayName:vs("Funnel"),chartSubtype:"funnel",chartType:"funnel",category:"misc",preview:"o-spreadsheet-ChartPreview.FUNNEL_CHART"}).add("sunburst",{matcher:e=>"sunburst"===e.type,displayName:vs("Sunburst"),chartSubtype:"sunburst",chartType:"sunburst",category:"hierarchical",preview:"o-spreadsheet-ChartPreview.SUNBURST_CHART"}).add("treemap",{matcher:e=>"treemap"===e.type,displayName:vs("Tree Map"),chartType:"treemap",chartSubtype:"treemap",category:"hierarchical",preview:"o-spreadsheet-ChartPreview.TREE_MAP_CHART"});class cG extends Jz{copy(e){}}U_.figureHandlers.add("chart",class extends cG{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 cr).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 cr).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 cG{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 cr).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 cG{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 cr).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 cr,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"}}),U_.cellHandlers.add("dataValidation",class extends Qz{uuidGenerator=new cr;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=jt(t),i=jt(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",eB).add("sheet",class extends Qz{isPasteAllowed(e,t,s,o){if(!("cells"in s))return"Success";const{xSplit:i,ySplit:n}=this.getters.getPaneDivisions(e);return Qt(M_(t,s.cells),i,n)?"FrozenPaneOverlap":"Success"}}).add("merge",class extends Qz{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 Qz{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=>Ht(u,e))){a.add(h.id);let{numberOfRows:e}=zt(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=zt(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 Qz{uuidGenerator=new cr;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=jt(e.position),i=jt(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 Qz{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 Qz{copy(e){const t=e.sheetId;if(0===e.zones.length)return;const s=[];let o=0;for(const i of AC(e.columnsIndexes)){let n=0;for(const r of AC(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 P_(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=_C(e.horizontal,e.vertical),s=_C(e.left,e.right,e.top,e.bottom);return t&&s&&_C(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]]}}).add("style",class extends Qz{copy(e){const t=e.sheetId;if(0===e.zones.length)return;const s=[];let o=0;for(const i of pe(e.columnsIndexes)){let n=0;for(const r of pe(e.rowsIndexes)){const e={left:i[0],right:i[i.length-1],top:r[0],bottom:r[r.length-1]};s.push(...this.getters.getZoneStyles(t,e).map(t=>({zone:{left:t.zone.left-e.left+o,right:t.zone.right&&t.zone.right-e.left+o,top:t.zone.top-e.top+n,bottom:t.zone.bottom&&t.zone.bottom-e.top+n},style:t.style}))),n+=r.length}o+=i.length}return{styles: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.pasteStyleZone(o,e,s,t.styles)}else for(const e of i)for(const s of P_(e,t.width,t.height))this.pasteStyleZone(o,s.left,s.top,t.styles)}pasteStyleZone(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};this.dispatch("SET_FORMATTING",{sheetId:e,target:[o],style:i.style})}}});const hG={},dG={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:15},uG={autoCompleteProviders:aM,autofillModifiersRegistry:u_,autofillRulesRegistry:g_,cellMenuRegistry:_k,colMenuRegistry:BV,errorTypes:Cs,linkMenuRegistry:eN,functionRegistry:mf,featurePluginRegistry:W_,iconsOnCellRegistry:TD,statefulUIPluginRegistry:$_,coreViewsPluginRegistry:q_,corePluginRegistry:G_,rowMenuRegistry:jV,sidePanelRegistry:Vz,figureRegistry:XF,chartSidePanelComponentRegistry:VH,chartComponentRegistry:NF,chartRegistry:Ky,chartSubtypeRegistry:A_,topbarMenuRegistry:lB,topbarComponentRegistry:SB,clickableCellRegistry:oB,otRegistry:gE,inverseCommandRegistry:YE,urlRegistry:Bf,cellPopoverRegistry:MP,numberFormatMenuRegistry:nB,repeatLocalCommandTransformRegistry:R_,repeatCommandTransformRegistry:E_,clipboardHandlersRegistries:U_,pivotRegistry:l_,pivotTimeAdapterRegistry:Pg,pivotSidePanelRegistry:wz,pivotNormalizationValueRegistry:dp,supportedPivotPositionalFormulaRegistry:jz,pivotToFunctionValueRegistry:up,migrationStepRegistry:BT,chartJsExtensionRegistry:rS},gG={arg:ls,isEvaluationError:fo,toBoolean:Ao,toJsDate:Do,toNumber:So,toString:Ro,toNormalizedPivotValue:ap,toFunctionPivotValue:cp,toXC:mt,toZone:Rt,toUnboundedZone:Et,toCartesian:pt,numberToLetters:it,lettersToNumber:nt,UuidGenerator:cr,formatValue:mn,createCurrencyFormat:_n,ColorGenerator:qv,computeTextWidth:$b,createEmptyWorkbookData:QT,createEmptySheet:JT,createEmptyExcelSheet:eA,rgbaToHex:xv,colorToRGBA:Tv,positionToZone:jt,isDefined:Te,isMatrix:_s,lazy:Oe,genericRepeat:bB,createAction:Kf,createActions:Yf,transformRangeData:is,deepEquals:Me,overlap:Vt,union:Mt,isInside:Ut,deepCopy:ae,expandZoneOnInsertion:_t,reduceZoneOnDeletion:Pt,unquote:ce,getMaxObjectId:Qg,getFunctionsFromTokens:Hf,getFirstPivotFunction:qD,getNumberOfPivotFunctions:ZD,parseDimension:sp,isDateOrDatetimeField:op,makeFieldProposal:qz,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:ts,getPivotHighlights:cz,pivotTimeAdapter:Mg,UNDO_REDO_PIVOT_COMMANDS:h_,createPivotFormula:rp,areDomainArgsFieldsValid:np,splitReference:sr,sanitizeSheetName:de,getUniqueText:st,isNumber:co,isDateTime:qs,createCustomFields:bp},pG={isMarkdownLink:Se,parseMarkdownLink:Ie,markdownLink:ye,openLink:Zf,urlRepresentation:qf},mG={Checkbox:VM,Section:wM,RoundColorPicker:EM,ChartDataSeries:YU,ChartErrorSection:XU,ChartLabelRange:KU,ChartTitle:tH,ChartPanel:BH,ChartFigure:jF,ChartJsComponent:ly,ClickableCellSortIcon:Yz,ZoomableChartJsComponent:TF,Grid:$z,GridOverlay:SU,ScorecardChart:xy,GaugeChartComponent:PF,LineConfigPanel:wH,BarConfigPanel:QU,PieChartDesignPanel:xH,GenericChartConfigPanel:JU,ChartWithAxisDesignPanel:dH,GenericZoomableChartDesignPanel:gH,LineChartDesignPanel:EH,GaugeChartConfigPanel:fH,GaugeChartDesignPanel:vH,ScorecardChartConfigPanel:DH,ScorecardChartDesignPanel:_H,GeoChartDesignPanel:yH,RadarChartDesignPanel:TH,WaterfallChartDesignPanel:kH,ComboChartDesignPanel:pH,FunnelChartDesignPanel:mH,SunburstChartDesignPanel:OH,TreeMapChartDesignPanel:LH,ChartTypePicker:HH,FigureComponent:KF,MenuPopover:$F,Popover:zF,SelectionInput:FM,ValidationMessages:dU,AddDimensionButton:gz,PivotDimensionGranularity:mz,PivotDimensionOrder:fz,PivotDimension:pz,PivotLayoutConfigurator:Sz,PivotHTMLRenderer:Kz,PivotDeferUpdate:hz,PivotTitleSection:Cz,CogWheelMenu:ZU,TextInput:zU,SidePanelCollapsible:zP,RadioSelection:oH,GeoChartRegionSelectSection:bH,ChartDashboardMenu:qF,FullScreenFigure:Xz,NumberInput:aH},fG={useDragAndDropListItems:RM,useHighlights:$H,useHighlightsOnHover:WH},vG={useStoreProvider:sv,DependencyContainer:Qf,CellPopoverStore:NP,ComposerFocusStore:mv,CellComposerStore:oU,FindAndReplaceStore:oz,HighlightStore:cM,DelayedHoveredCellStore:JF,HoveredTableStore:fU,ModelStore:lv,NotificationStore:hM,RendererStore:uv,SelectionInputStore:OM,SpreadsheetStore:gv,useStore:ov,useLocalStore:iv,SidePanelStore:Bz,PivotSidePanelStore:yz,PivotMeasureDisplayPanelStore:az,ClientFocusStore:XV,GridRenderer:TU};const bG={DEFAULT_LOCALE:Fc,HIGHLIGHT_COLOR:o,PIVOT_TABLE_CONFIG:J,ChartTerms:wg,FIGURE_ID_SPLITTER:z,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2},SG={...fF,...Kw};e.AbstractCellClipboardHandler=Qz,e.AbstractChart=cy,e.AbstractFigureClipboardHandler=cG,e.CellErrorType=Ss,e.ClientDisconnectedError=ZE,e.CorePlugin=sA,e.CoreViewPlugin=zA,e.DEFAULT_LOCALE=Fc,e.DEFAULT_LOCALES=Oc,e.DispatchResult=Sr,e.EvaluationError=ys,e.LocalTransportService=dE,e.Model=class extends Jf{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 cr,i=!1){const n=performance.now();console.debug("##### Model creation #####"),super(),ps===us&&ms===gs&&(ms=()=>!0),s=XT(e,s);const r=ZT(e,i);this.state=new X_,this.uuidGenerator=o,this.config=this.setupConfig(t),this.session=this.setupSession(r.revisionId),this.coreGetters={},this.range=new Z_(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 Y_(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 G_.getAll())this.setupCorePlugin(e,r);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(s);for(const e of q_.getAll()){const t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(const e of $_.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(const e of W_.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()),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 jE(iR({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:vs("Anonymous").toString()},s=e.transportService||new dE,o="readonly"===e.mode||"dashboard"===e.mode;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:o?new uE(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(Oc));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=br(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>"Success"!==e)?new Sr(t.flat()):Sr.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(eF(e,t));dispatch=(e,t)=>{const s=eF(e,t),o=this.status;if(this.getters.isReadonly()&&(i=s,!fr.has(i.type)))return new Sr("Readonly");var i;if(!this.session.canApplyOptimisticUpdate())return new Sr("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();br(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(br(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(br(s))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,s)}return Sr.Success};dispatchFromCorePlugin=(e,t)=>{const s=eF(e,t),o=this.status;this.status=2;const i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,s),this.status=o,Sr.Success};dispatchToHandlers(e,t){const s=br(t);for(const o of e)!s&&o instanceof sA||o.beforeHandle(t);for(const o of e)!s&&o instanceof sA||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=QT();for(const t of this.handlers)t instanceof sA&&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={...QT(),sheets:[eA(qT,"Sheet1")]};for(const t of this.handlers)t instanceof Ir&&await t.exportForExcel(e);return e=ae(e),KO(e)}},e.PivotRuntimeDefinition=XD,e.Registry=Fg,e.Revision=qE,e.SPREADSHEET_DIMENSIONS=dG,e.Spreadsheet=tG,e.SpreadsheetPivotTable=TA,e.UIPlugin=wr,e.__info__=hG,e.addFunction=function e(t,s){return mf.add(t,s),{addFunction:(t,s)=>e(t,s)}},e.addRenderingLayer=function(e,t){if(hv[e])throw new Error(`Layer ${e} already exists`);hv[e]=t},e.astToFormula=BD,e.categories=ff,e.chartHelpers=SG,e.compile=lE,e.compileTokens=cE,e.components=mG,e.constants=bG,e.convertAstNodes=Mf,e.coreTypes=vr,e.createAutocompleteArgumentsProvider=tB,e.findCellInNewZone=Zt,e.functionCache=aE,e.getCaretDownSvg=cR,e.getCaretUpSvg=hR,e.helpers=gG,e.hooks=fG,e.invalidateCFEvaluationCommands=gr,e.invalidateChartEvaluationCommands=dr,e.invalidateDependenciesCommands=ur,e.invalidateEvaluationCommands=hr,e.iterateAstNodes=Nf,e.links=pG,e.load=ZT,e.parse=Ff,e.parseTokens=Pf,e.readonlyAllowedCommands=fr,e.registries=uG,e.setDefaultSheetViewSize=function(e){j=e},e.setTranslationMethod=function(e,t=()=>!0){ps=e,ms=t},e.stores=vG,e.tokenColors=ie,e.tokenize=Nc,hG.version="19.1.0-alpha.11",hG.date="2025-11-03T12:34:28.925Z",hG.hash="d9230f3"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|