@odoo/o-spreadsheet 18.0.70 → 18.0.73

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.
@@ -1,11 +1,11 @@
1
- (function(e,t){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),l=(e,t)=>{let n={};for(var i in e)r(n,i,{get:e[i],enumerable:!0});return t||r(n,Symbol.toStringTag,{value:`Module`}),n},u=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=a(t),l=0,u=c.length,d;l<u;l++)d=c[l],!s.call(e,d)&&d!==n&&r(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(o=i(t,d))||o.enumerable});return e},d=(e,t,i)=>(i=e==null?{}:n(o(e)),u(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e));function f(e){return e.map(m).sort((e,t)=>e.sequence-t.sequence)}let p=1;function m(e){let t=e.name,n=e.children,r=e.description,i=e.icon,a=e.secondaryIcon;return{id:(e.id||p++).toString(),name:typeof t==`function`?t:()=>t,isVisible:e.isVisible?e.isVisible:()=>!0,isEnabled:e.isEnabled?e.isEnabled:()=>!0,isActive:e.isActive,execute:e.execute,children:n?e=>n.map(t=>typeof t==`function`?t(e):t).flat().map(m).sort((e,t)=>e.sequence-t.sequence):()=>[],isReadonlyAllowed:e.isReadonlyAllowed||!1,separator:e.separator||!1,icon:typeof i==`function`?i:()=>i||``,iconColor:e.iconColor,secondaryIcon:typeof a==`function`?a:()=>a||``,description:typeof r==`function`?r:()=>r||``,textColor:e.textColor,sequence:e.sequence||0,onStartHover:e.onStartHover,onStopHover:e.onStopHover}}var h=class{content={};add(e,t){return this.content[e]=t,this}get(e){let t=this.content[e];if(!t&&!(e in this.content))throw Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}};let g=.5,_=`#37A850`,v=`#f5f5f5`,ee=`#F8F9FA`,te=`#E8EAED`,ne=`#595959`,re=`#666666`,ie=`#c9ccd2`,ae=`#3266ca`,oe=`#FFFFFF`,se=`#CACACA`,ce=11982760,le=`#017E84`,ue=`#188038`,de=`#E0E2E4`,fe=`#4A4F59`,pe=`#999`,me=`#E2E3E3`,he=`#BCBCBC`,ge=`#9B359B`,_e=`#111827`,ve=`#D8DADD`,ye=`#E7E9ED`,be=`#F9FAFB`,xe=`#374151`,Se=xe+`C2`,Ce=`#111827`,we=`#714B67`,Te=ve,Ee=`#111827`,De=`#e6f2f3`,Oe=`#111827`,ke=`#017E84`,Ae=`#D44C591A`,je=`#C34A41`,Me=`#E6F2F3`,Ne=`#000000.#434343.#666666.#999999.#B7B7B7.#CCCCCC.#D9D9D9.#EFEFEF.#F3F3F3.#FFFFFF.#980000.#FF0000.#FF9900.#FFFF00.#00FF00.#00FFFF.#4A86E8.#0000FF.#9900FF.#FF00FF.#E6B8AF.#F4CCCC.#FCE5CD.#FFF2CC.#D9EAD3.#D0E0E3.#C9DAF8.#CFE2F3.#D9D2E9.#EAD1DC.#DD7E6B.#EA9999.#F9CB9C.#FFE599.#B6D7A8.#A2C4C9.#A4C2F4.#9FC5E8.#B4A7D6.#D5A6BD.#CC4125.#E06666.#F6B26B.#FFD966.#93C47D.#76A5AF.#6D9EEB.#6FA8DC.#8E7CC3.#C27BA0.#A61C00.#CC0000.#E69138.#F1C232.#6AA84F.#45818E.#3C78D8.#3D85C6.#674EA7.#A64D79.#85200C.#990000.#B45F06.#BF9000.#38761D.#134F5C.#1155CC.#0B5394.#351C75.#741B47.#5B0F00.#660000.#783F04.#7F6000.#274E13.#0C343D.#1C4587.#073763.#20124D.#4C1130`.split(`.`),Pe={align:`left`,verticalAlign:`bottom`,wrapping:`overflow`,bold:!1,italic:!1,strikethrough:!1,underline:!1,fontSize:10,fillColor:``,textColor:``},Fe={...Pe,align:`right`},Ie=Pe.verticalAlign,Le=Pe.wrapping,Re=Pe.fontSize,ze=`'Roboto', arial`,Be={style:`thin`,color:`#000000`},Ve=`START_REVISION`,He=`difference`,Ue=`#43C5B1`,We=`#EA6175`,Ge=[`'`,`*`,`?`,`/`,`\\`,`[`,`]`],Ke=/'|\*|\?|\/|\\|\[|\]/,qe=0;function Je(){return qe}function Ye(e){qe=e}let Xe=[6,7,8,9,10,11,12,14,18,24,36],Ze={hasFilters:!1,totalRow:!1,firstColumn:!0,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,styleId:`TableStyleMedium5`,automaticAutofill:!1},Qe={symbol:`$`,position:`before`,decimalPlaces:2,code:``,name:`Dollar`},$e=new RegExp(Ke,`g`);function et(e){return e[0]===`"`&&(e=e.slice(1)),e[e.length-1]===`"`&&e[e.length-2]!==`\\`?e.slice(0,e.length-1):e}function tt(e){return`clone`in e&&e.clone instanceof Function}function nt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function y(e){switch(typeof e){case`object`:{if(e===null)return e;if(tt(e))return e.clone();if(!(rt(e)||e instanceof Array))throw Error(`Unsupported type: only objects and arrays are supported`);let t=Array.isArray(e)?Array(e.length):{};if(Array.isArray(e))for(let n=0,r=e.length;n<r;n++)n in e&&(t[n]=y(e[n]));else for(let n in e)t[n]=y(e[n]);return t}case`number`:case`string`:case`boolean`:case`function`:case`undefined`:return e;default:throw Error(`Unsupported type: ${typeof e}`)}}function rt(e){return typeof e==`object`&&!!e&&(e?.constructor===Object||e?.constructor===void 0)}function it(e){return at(e,`'`)}function at(e,t=`"`){return e.startsWith(t)&&(e=e.slice(1)),e.endsWith(t)&&(e=e.slice(0,-1)),e}function ot(e){return e.match(/\w/g)?.length!==e.length&&(e=`'${e}'`),e}function st(e,t=` `){return e.replace($e,t)}function b(e,t,n){return e<t?t:e>n?n:e}function x(e,t,n=1){if(t<=e&&n>0)return[];if(n===0)throw Error(`range() step must not be zero`);let r=Math.ceil(Math.abs((t-e)/n)),i=Array(r);for(let t=0;t<r;t++)i[t]=e+t*n;return i}function ct(e){return e.reduce((e,t,n,r)=>(Math.abs(t-r[n-1])===1?e[e.length-1].push(t):e.push([t]),e),[])}function*lt(e,t){t.next();for(let n of e){let e=t.next();yield{...n,next:e.done?void 0:e.value}}}function ut(e){let t=e.toUpperCase();return t===`TRUE`||t===`FALSE`}let dt=/^\[(.+)\]\((.+)\)$/,ft=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function pt(e){return dt.test(e)}function mt(e){return ft.test(e)}function ht(e,t){return`[${e}](${t})`}function gt(e){let t=e.match(dt)||[],n=t[1],r=t[2];if(!n||!r)throw Error(`Could not parse markdown link ${e}.`);return{label:n,url:r}}let _t=`o-spreadsheet://`;function vt(e){return e.startsWith(_t)}function yt(e){return`${_t}${e}`}function bt(e){if(e.startsWith(_t))return e.substr(16);throw Error(`${e} is not a valid sheet link`)}function S(e){return e!==void 0}function xt(e){return e!==null}function St(e){return e===void 0?!0:Object.values(e).every(e=>typeof e==`object`?St(e):!e)}function Ct(e,t,n){let r,i=function(){let i=this,a=Array.from(arguments);function o(){r=void 0,n||e.apply(i,a)}let s=n&&!r;clearTimeout(r),r=setTimeout(o,t),s&&e.apply(i,a)};return i.isDebouncePending=()=>r!==void 0,i.stopDebounce=()=>{clearTimeout(r)},i}function wt(e){let t=!1;return async(...n)=>{t||(t=!0,await Promise.resolve(),t=!1,e(...n))}}function Tt(e){let t=``;for(let n=0,r=e.length;n<r;n++)t+=e[n];return t}function Et(e){let t=!1,n,r=()=>(t||=(n=e instanceof Function?e():e,!0),n);return r.map=e=>Et(()=>e(r())),r}function Dt(e,t){let n=e.slice(t).find(e=>e);return n||=e.slice(0,t).reverse().find(e=>e),n||``}function Ot(e,t){return e===`after`?t+1:t}function C(e,t){if(e===t)return!0;if(e&&!t||t&&!e||typeof e!=typeof t||typeof e!=`object`)return!1;for(let n in t)if(!(n in e)&&t[n]!==void 0)return!1;for(let n in e){if(typeof e[n]!=typeof t[n])return!1;if(typeof e[n]==`object`){if(!C(e[n],t[n]))return!1}else if(e[n]!==t[n])return!1}return!0}function kt(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!C(e[n],t[n]))return!1;return!0}function At(e,t){if(e.length<t.length)return!1;let n=new Set(e);return t.every(e=>n.has(e))}function jt(e){if(!e)return e;let t={...e};return Object.keys(t).forEach(e=>!t[e]&&delete t[e]),t}let Mt=[` `,`\f`,`\v`,`\xA0`,` `,` `,` `,`\u2028`,`\u2029`,` `,` `,` `,``],Nt=new RegExp(Mt.join(`|`),`g`),Pt=/(\r\n|\r)/g,Ft=Mt.concat([` `]);function It(e){return e?e.replace(Pt,`
1
+ (function(e,t){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),l=(e,t)=>{let n={};for(var i in e)r(n,i,{get:e[i],enumerable:!0});return t||r(n,Symbol.toStringTag,{value:`Module`}),n},u=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=a(t),l=0,u=c.length,d;l<u;l++)d=c[l],!s.call(e,d)&&d!==n&&r(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(o=i(t,d))||o.enumerable});return e},d=(e,t,i)=>(i=e==null?{}:n(o(e)),u(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e));function f(e){return e.map(m).sort((e,t)=>e.sequence-t.sequence)}let p=1;function m(e){let t=e.name,n=e.children,r=e.description,i=e.icon,a=e.secondaryIcon;return{id:(e.id||p++).toString(),name:typeof t==`function`?t:()=>t,isVisible:e.isVisible?e.isVisible:()=>!0,isEnabled:e.isEnabled?e.isEnabled:()=>!0,isActive:e.isActive,execute:e.execute,children:n?e=>n.map(t=>typeof t==`function`?t(e):t).flat().map(m).sort((e,t)=>e.sequence-t.sequence):()=>[],isReadonlyAllowed:e.isReadonlyAllowed||!1,separator:e.separator||!1,icon:typeof i==`function`?i:()=>i||``,iconColor:e.iconColor,secondaryIcon:typeof a==`function`?a:()=>a||``,description:typeof r==`function`?r:()=>r||``,textColor:e.textColor,sequence:e.sequence||0,onStartHover:e.onStartHover,onStopHover:e.onStopHover}}var h=class{content={};add(e,t){return this.content[e]=t,this}get(e){let t=this.content[e];if(!t&&!(e in this.content))throw Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}};let g=.5,_=`#37A850`,v=`#f5f5f5`,ee=`#F8F9FA`,te=`#E8EAED`,ne=`#595959`,re=`#666666`,ie=`#c9ccd2`,ae=`#3266ca`,oe=`#FFFFFF`,se=`#CACACA`,ce=11982760,le=`#017E84`,ue=`#188038`,de=`#E0E2E4`,fe=`#4A4F59`,pe=`#999`,me=`#E2E3E3`,he=`#BCBCBC`,ge=`#9B359B`,_e=`#111827`,ve=`#D8DADD`,ye=`#E7E9ED`,be=`#F9FAFB`,xe=`#374151`,Se=`#374151C2`,Ce=`#111827`,we=`#714B67`,Te=ve,Ee=`#111827`,De=`#e6f2f3`,Oe=`#111827`,ke=`#017E84`,Ae=`#D44C591A`,je=`#C34A41`,Me=`#E6F2F3`,Ne=`#000000.#434343.#666666.#999999.#B7B7B7.#CCCCCC.#D9D9D9.#EFEFEF.#F3F3F3.#FFFFFF.#980000.#FF0000.#FF9900.#FFFF00.#00FF00.#00FFFF.#4A86E8.#0000FF.#9900FF.#FF00FF.#E6B8AF.#F4CCCC.#FCE5CD.#FFF2CC.#D9EAD3.#D0E0E3.#C9DAF8.#CFE2F3.#D9D2E9.#EAD1DC.#DD7E6B.#EA9999.#F9CB9C.#FFE599.#B6D7A8.#A2C4C9.#A4C2F4.#9FC5E8.#B4A7D6.#D5A6BD.#CC4125.#E06666.#F6B26B.#FFD966.#93C47D.#76A5AF.#6D9EEB.#6FA8DC.#8E7CC3.#C27BA0.#A61C00.#CC0000.#E69138.#F1C232.#6AA84F.#45818E.#3C78D8.#3D85C6.#674EA7.#A64D79.#85200C.#990000.#B45F06.#BF9000.#38761D.#134F5C.#1155CC.#0B5394.#351C75.#741B47.#5B0F00.#660000.#783F04.#7F6000.#274E13.#0C343D.#1C4587.#073763.#20124D.#4C1130`.split(`.`),Pe={align:`left`,verticalAlign:`bottom`,wrapping:`overflow`,bold:!1,italic:!1,strikethrough:!1,underline:!1,fontSize:10,fillColor:``,textColor:``},Fe={...Pe,align:`right`},Ie=Pe.verticalAlign,Le=Pe.wrapping,Re=Pe.fontSize,ze=`'Roboto', arial, 'Liberation Sans'`,Be={style:`thin`,color:`#000000`},Ve=`START_REVISION`,He=`difference`,Ue=`#43C5B1`,We=`#EA6175`,Ge=[`'`,`*`,`?`,`/`,`\\`,`[`,`]`],Ke=/'|\*|\?|\/|\\|\[|\]/,qe=0;function Je(){return qe}function Ye(e){qe=e}let Xe=[6,7,8,9,10,11,12,14,18,24,36],Ze={hasFilters:!1,totalRow:!1,firstColumn:!0,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,styleId:`TableStyleMedium5`,automaticAutofill:!1},Qe={symbol:`$`,position:`before`,decimalPlaces:2,code:``,name:`Dollar`},$e=new RegExp(Ke,`g`);function et(e){return e[0]===`"`&&(e=e.slice(1)),e[e.length-1]===`"`&&e[e.length-2]!==`\\`?e.slice(0,e.length-1):e}function tt(e){return`clone`in e&&e.clone instanceof Function}function nt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function y(e){switch(typeof e){case`object`:{if(e===null)return e;if(tt(e))return e.clone();if(!(rt(e)||e instanceof Array))throw Error(`Unsupported type: only objects and arrays are supported`);let t=Array.isArray(e)?Array(e.length):{};if(Array.isArray(e))for(let n=0,r=e.length;n<r;n++)n in e&&(t[n]=y(e[n]));else for(let n in e)t[n]=y(e[n]);return t}case`number`:case`string`:case`boolean`:case`function`:case`undefined`:return e;default:throw Error(`Unsupported type: ${typeof e}`)}}function rt(e){return typeof e==`object`&&!!e&&(e?.constructor===Object||e?.constructor===void 0)}function it(e){return at(e,`'`)}function at(e,t=`"`){return e.startsWith(t)&&(e=e.slice(1)),e.endsWith(t)&&(e=e.slice(0,-1)),e}function ot(e){return e.match(/\w/g)?.length!==e.length&&(e=`'${e}'`),e}function st(e,t=` `){return e.replace($e,t)}function b(e,t,n){return e<t?t:e>n?n:e}function x(e,t,n=1){if(t<=e&&n>0)return[];if(n===0)throw Error(`range() step must not be zero`);let r=Math.ceil(Math.abs((t-e)/n)),i=Array(r);for(let t=0;t<r;t++)i[t]=e+t*n;return i}function ct(e){return e.reduce((e,t,n,r)=>(Math.abs(t-r[n-1])===1?e[e.length-1].push(t):e.push([t]),e),[])}function*lt(e,t){t.next();for(let n of e){let e=t.next();yield{...n,next:e.done?void 0:e.value}}}function ut(e){let t=e.toUpperCase();return t===`TRUE`||t===`FALSE`}let dt=/^\[(.+)\]\((.+)\)$/,ft=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function pt(e){return dt.test(e)}function mt(e){return ft.test(e)}function ht(e,t){return`[${e}](${t})`}function gt(e){let t=e.match(dt)||[],n=t[1],r=t[2];if(!n||!r)throw Error(`Could not parse markdown link ${e}.`);return{label:n,url:r}}let _t=`o-spreadsheet://`;function vt(e){return e.startsWith(_t)}function yt(e){return`${_t}${e}`}function bt(e){if(e.startsWith(_t))return e.substr(16);throw Error(`${e} is not a valid sheet link`)}function S(e){return e!==void 0}function xt(e){return e!==null}function St(e){return e===void 0?!0:Object.values(e).every(e=>typeof e==`object`?St(e):!e)}function Ct(e,t,n){let r,i=function(){let i=this,a=Array.from(arguments);function o(){r=void 0,n||e.apply(i,a)}let s=n&&!r;clearTimeout(r),r=setTimeout(o,t),s&&e.apply(i,a)};return i.isDebouncePending=()=>r!==void 0,i.stopDebounce=()=>{clearTimeout(r)},i}function wt(e){let t=!1;return async(...n)=>{t||(t=!0,await Promise.resolve(),t=!1,e(...n))}}function Tt(e){let t=``;for(let n=0,r=e.length;n<r;n++)t+=e[n];return t}function Et(e){let t=!1,n,r=()=>(t||=(n=e instanceof Function?e():e,!0),n);return r.map=e=>Et(()=>e(r())),r}function Dt(e,t){let n=e.slice(t).find(e=>e);return n||=e.slice(0,t).reverse().find(e=>e),n||``}function Ot(e,t){return e===`after`?t+1:t}function C(e,t){if(e===t)return!0;if(e&&!t||t&&!e||typeof e!=typeof t||typeof e!=`object`)return!1;for(let n in t)if(!(n in e)&&t[n]!==void 0)return!1;for(let n in e){if(typeof e[n]!=typeof t[n])return!1;if(typeof e[n]==`object`){if(!C(e[n],t[n]))return!1}else if(e[n]!==t[n])return!1}return!0}function kt(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!C(e[n],t[n]))return!1;return!0}function At(e,t){if(e.length<t.length)return!1;let n=new Set(e);return t.every(e=>n.has(e))}function jt(e){if(!e)return e;let t={...e};return Object.keys(t).forEach(e=>!t[e]&&delete t[e]),t}let Mt=[` `,`\f`,`\v`,`\xA0`,` `,` `,` `,`\u2028`,`\u2029`,` `,` `,` `,``],Nt=new RegExp(Mt.join(`|`),`g`),Pt=/(\r\n|\r)/g,Ft=Mt.concat([` `]);function It(e){return e?e.replace(Pt,`
2
2
  `):``}function Lt(e){let t=Array.from(e).sort((e,t)=>e-t);for(let e=1;e<t.length;e++)if(t[e]-t[e-1]!==1)return!1;return!0}function Rt(e){let t=new Map,n=e.name?e.name+` (memoized)`:`memoized`;return{[n](...n){return t.has(n[0])||t.set(n[0],e(...n)),t.get(n[0])}}[n]}function zt(e,t){let n=new Set(t),r=[];for(let t=0;t<e.length;t++)n.has(t)||r.push(e[t]);return r}function Bt(e,t,n){return e.slice(0,n).concat(t).concat(e.slice(n))}function Vt(e,t,n){let r=[...e];return r.splice(n,1,t),r}function Ht(e){return e.split(`
3
3
  `).map(e=>e.replace(/\s+/g,` `).trim()).join(`
4
- `)}function Ut(e,t,n){return t>n?Ut(e,n,t):e>=t&&e<=n}function Wt(e,t){let n=nt(e),r=t.matchCase?``:`i`;return t.exactMatch&&(n=`^${n}$`),RegExp(n,r)}function Gt(e){let t=e.length;if(t<1e5)return Math.max(...e);let n=-1/0;for(;t--;)n=e[t]>n?e[t]:n;return n}function Kt(e){let t=e.length;if(t<1e5)return Math.min(...e);let n=1/0;for(;t--;)n=e[t]<n?e[t]:n;return n}var qt=class{text;currentIndex=0;current;constructor(e){this.text=e,this.current=e[0]}shift(){let e=this.current,t=this.text[++this.currentIndex];return this.current=t,e}advanceBy(e){this.currentIndex+=e,this.current=this.text[this.currentIndex]}isOver(){return this.currentIndex>=this.text.length}remaining(){return this.text.substring(this.currentIndex)}currentStartsWith(e){if(this.current!==e[0])return!1;for(let t=1;t<e.length;t++)if(this.text[this.currentIndex+t]!==e[t])return!1;return!0}};function Jt(e,t=e=>e){let n=new Set;return e.filter(e=>{let r=t(e);return n.has(r)?!1:(n.add(r),!0)})}function Yt(e){let t={};for(let n in e)for(let r in e[n])t[r]||(t[r]={}),t[r][n]=e[n][r];return t}let Xt=/rgba?\(|\s+|\)/gi,Zt=/^#([A-F\d]{2}){3,4}$/,Qt=[`#eb6d00`,`#0074d9`,`#ad8e00`,`#169ed4`,`#b10dc9`,`#00a82d`,`#00a3a3`,`#f012be`,`#3d9970`,`#111111`,`#62A300`,`#ff4136`,`#949494`,`#85144b`,`#001f3f`];function $t(e){return en(e.toString(16).padStart(6,`0`))}function en(e){let t=e;if(e.startsWith(`rgb`)?t=sn(e):(t=e.replace(`#`,``).toUpperCase(),(t.length===3||t.length===4)&&(t=t.split(``).reduce((e,t)=>e+t+t,``)),t=`#${t}`),!Zt.test(t))throw Error(`invalid color input: ${e}`);return t}function tn(e){try{return en(e),!0}catch{return!1}}function nn(e){try{return fn(e),!0}catch{return!1}}let rn=e=>e>=0&&e<=255;function an(e,t,n,r=1){if(!rn(e)||!rn(t)||!rn(n)||r<0||r>1)throw Error(`Invalid RGBA values ${[e,t,n,r]}`);return{a:r,b:n,g:t,r:e}}function on(e){let{r:t,g:n,b:r}=ln(e);t/=255,n/=255,r/=255;let i=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4,a=i(t),o=i(n),s=i(r);return .2126*a+.7152*o+.0722*s}function sn(e){let t=e.replace(Xt,``).split(`,`),n=255;if(t.length!==3&&t.length!==4)throw Error(`invalid color`);if(t.length===4){let e=parseFloat(t.pop()||`1`);if(isNaN(e))throw Error(`invalid alpha value`);n=Math.round(e*255)}let r=t.map(e=>parseInt(e,10));return n!==255&&r.push(n),`#`+Tt(r.map(e=>e.toString(16).padStart(2,`0`))).toUpperCase()}function cn(e){let t=e.r.toString(16),n=e.g.toString(16),r=e.b.toString(16),i=Math.round(e.a*255).toString(16);return t.length===1&&(t=`0`+t),n.length===1&&(n=`0`+n),r.length===1&&(r=`0`+r),i.length===1&&(i=`0`+i),i===`ff`&&(i=``),(`#`+t+n+r+i).toUpperCase()}function ln(e){e=en(e);let t,n,r,i;if(e.length===7)t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16),i=255;else if(e.length===9)t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16),i=parseInt(e[7]+e[8],16);else throw Error(`Invalid color`);return i=+(i/255).toFixed(3),{a:i,r:t,g:n,b:r}}function un(e){e={...e},e.s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,n=t*(1-Math.abs(e.h/60%2-1)),r=e.l-t/2,i=0,a=0,o=0;return 0<=e.h&&e.h<60?(i=t,a=n,o=0):60<=e.h&&e.h<120?(i=n,a=t,o=0):120<=e.h&&e.h<180?(i=0,a=t,o=n):180<=e.h&&e.h<240?(i=0,a=n,o=t):240<=e.h&&e.h<300?(i=n,a=0,o=t):300<=e.h&&e.h<360&&(i=t,a=0,o=n),i=Math.round((i+r)*255),a=Math.round((a+r)*255),o=Math.round((o+r)*255),{a:e.a,r:i,g:a,b:o}}function dn(e){let t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=a-i,s=0,c=0,l=0;return s=o===0?0:a===t?(n-r)/o%6:a===n?(r-t)/o+2:(t-n)/o+4,s=Math.round(s*60),s<0&&(s+=360),l=(a+i)/2,c=o===0?0:o/(1-Math.abs(2*l-1)),c=+(c*100).toFixed(1),l=+(l*100).toFixed(1),{a:e.a,h:s,s:c,l}}function fn(e){return cn(un(e))}function pn(e){return dn(ln(e))}function mn(e,t,n=0){if(!(tn(e)&&tn(t)))return!1;let r=ln(e),i=ln(t);return r.a===i.a?Math.sqrt(((r.r-i.r)/255)**2+((r.g-i.g)/255)**2+((r.b-i.b)/255)**2)<=n:!1}function hn(e,t){return t===1?en(e).slice(0,7):cn({...ln(e),a:t})}function gn(e,t){let n=pn(e);return t===1?`#fff`:(n.l=t*(100-n.l)+n.l,fn(n))}function _n(e,t){let n=pn(e);return t===1?`#000`:(n.l-=t*n.l,fn(n))}let vn=[`#4EA7F2`,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#FFD86D`],yn=[`#4EA7F2`,`#3188E6`,`#43C5B1`,`#00A78D`,`#EA6175`,`#CE4257`,`#F4A261`,`#F48935`,`#8481DD`,`#5752D1`,`#FFD86D`,`#FFBC2C`],bn=[`#4EA7F2`,`#3188E6`,`#056BD9`,`#A76DBC`,`#7F4295`,`#6D2387`,`#EA6175`,`#CE4257`,`#982738`,`#43C5B1`,`#00A78D`,`#0E8270`,`#F4A261`,`#F48935`,`#BE5D10`,`#8481DD`,`#5752D1`,`#3A3580`,`#A4A8B6`,`#7E8290`,`#545B70`,`#FFD86D`,`#FFBC2C`,`#C08A16`],xn=`#4EA7F2.#3188E6.#056BD9.#155193.#A76DBC.#7F4295.#6D2387.#4F1565.#EA6175.#CE4257.#982738.#791B29.#43C5B1.#00A78D.#0E8270.#105F53.#F4A261.#F48935.#BE5D10.#7D380D.#8481DD.#5752D1.#3A3580.#26235F.#A4A8B6.#7E8290.#545B70.#3F4250.#FFD86D.#FFBC2C.#C08A16.#936A12`.split(`.`);function Sn(e,t){return t[e%t.length]}function Cn(e){return e<=6?vn:e<=12?yn:e<=24?bn:xn}var wn=class{preferredColors;currentColorIndex=0;palette;constructor(e,t=[]){this.preferredColors=t,this.palette=Cn(e).filter(e=>!t.includes(e))}next(){return this.preferredColors?.[this.currentColorIndex]?this.preferredColors[this.currentColorIndex++]:Sn(this.currentColorIndex++,this.palette)}};function Tn(e){if(e<0)throw Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Tn(Math.floor(e/26)-1)+Tn(e%26)}function En(e){let t=0,n=e.length;for(let r=0;r<n;r++){let n=Dn(e[r]);t=t*26+n}return t-1}function Dn(e){let t=e.charCodeAt(0);return t>=65&&t<=90?t-64:t-96}function On(e){return e>=`A`&&e<=`Z`||e>=`a`&&e<=`z`}function kn(e){return e>=`0`&&e<=`9`}let An=En(`ZZZ`);function jn(e){for(;e.current===` `;)e.advanceBy(1)}function Mn(e){if(e.current===`$`&&e.advanceBy(1),!e.current||!On(e.current))return-1;let t=0;for(;e.current&&On(e.current);)t=t*26+Dn(e.shift());return t}function Nn(e){if(e.current===`$`&&e.advanceBy(1),!e.current||!kn(e.current))return-1;let t=0;for(;e.current&&kn(e.current);)t=t*10+Number(e.shift());return t}function Pn(e){let t=new qt(e);jn(t);let n=Mn(t);if(n===-1||!t.current)throw Error(`Invalid cell description: ${e}`);let r=Nn(t);jn(t);let i=n-1,a=r-1;if(!t.isOver()||i>An||a>9999998)throw Error(`Invalid cell description: ${e}`);return{col:i,row:a}}function w(e,t,n={colFixed:!1,rowFixed:!1}){return(n.colFixed?`$`:``)+Tn(e)+(n.rowFixed?`$`:``)+String(t+1)}function T(e,t=[]){if(e.length<=1&&t.length===0)return e;let n=[0],r=new Map([[0,[]]]);return Fn(n,r,e,!1),Fn(n,r,t,!0),zn(n,r)}function Fn(e,t,n,r=!1){for(let i of n){let n=i.left,a=i.right===void 0?void 0:i.right+1,o=In(e,t,n,!0,0),s=In(e,t,a,!1,o);for(let n=o;n<=s;n++)Ln(t.get(e[n]),i,r);Rn(e,t,o,s)}}function In(e,t,n,r,i){if(n===void 0)return e.length-1;let a=Bn(e,n,i);return n===e[a]?r?a:a-1:(e.splice(a+1,0,n),t.set(n,[...t.get(e[a])]),r?a+1:a)}function Ln(e,t,n=!1){let r=t.top,i=t.bottom===void 0?void 0:t.bottom+1,a=[],o=Bn(e,r,0,!1);if((o%2!=0&&!n||o%2==0&&n)&&a.push(r),i===void 0){e.splice(o+1),e.push(...a);return}let s=Vn(e,i,0,!1);(s%2==0&&!n||s%2!=0&&n)&&a.push(i),e.splice(o+1,s-o-1,...a)}function Rn(e,t,n,r){let i=n-1==-1?0:n-1,a=r===e.length-1?r:r+1;for(let n=a;n>i;n--)kt(t.get(e[n]),t.get(e[n-1]))&&(t.delete(e[n]),e.splice(n,1))}function zn(e,t){let n=[],r=[];for(let i=0;i<e.length;i++){let a=e[i],o=t.get(a);if(!o||o.length===0){n.push(...r),r=[];continue}let s=e[i+1];s!==void 0&&s--;let c=[];for(let e=0;e<o.length;e+=2){let t=o[e],n=o[e+1];n!==void 0&&n--;let i={top:t,left:a,bottom:n,right:s,hasHeader:n===void 0&&t!==0||s===void 0&&a!==0},l=!1;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.top===i.top&&t.bottom===i.bottom){t.right=i.right,r.splice(e,1),c.push(t),l=!0;break}}l||c.push(i)}n.push(...r),r=c}return n.push(...r),n}function Bn(e,t,n=0,r=!0){let i=e.length-1,a=-1;for(;n<=i;){let o=Math.floor((n+i)/2);if(e[o]===t&&r)return o;e[o]<t?(a=o,n=o+1):i=o-1}return a}function Vn(e,t,n=0,r=!0){let i=e.length-1,a=e.length;for(;n<=i;){let o=Math.floor((n+i)/2);if(e[o]===t&&r)return o;e[o]>t?(a=o,i=o-1):n=o+1}return a}let Hn=e=>e,Un=()=>!1,Wn=Hn,Gn=Un;function Kn(e,...t){if(t.length===1&&typeof t[0]==`object`&&!(t[0]instanceof String)){let n=t[0];e=e.replace(/\%\(([^\)]+)\)s/g,(e,t)=>n[t])}else t.length>0&&(e=e.replace(/\%s/g,()=>t.shift()));return e}function qn(e,t=()=>!0){Wn=e,Gn=t}function Jn(){Wn===Hn&&Gn===Un&&(Gn=()=>!0)}let E=function(e,...t){return Gn()?Kn(Wn(e),...t):new Yn(e,t)};var Yn=class extends String{values;constructor(e,t){super(e),this.values=t}valueOf(){let e=super.valueOf();return Gn()?Kn(Wn(e),...this.values):Kn(e,...this.values)}toString(){return this.valueOf()}};function Xn(e){let t=new qt(e);jn(t);let n=e.indexOf(`!`);n!==-1&&t.advanceBy(n+1);let r=Mn(t),i=Nn(t),a,o,s,c,l=!1,u=!1,d=!1;if(i===-1?(s=c=r-1,a=o=0,l=!0):r===-1?(a=o=i-1,s=c=0,u=!0):(s=c=r-1,a=o=i-1,d=!0),jn(t),t.current===`:`){t.advanceBy(1),jn(t);let e=Mn(t),n=Nn(t);n===-1?(c=e-1,l=!0):e===-1?(o=n-1,u=!0):(c=e-1,o=n-1,a=l?o:a,s=u?c:s,d=!0)}let f={top:a,left:s,bottom:l?void 0:o,right:u?void 0:c};return d&&=u||l,d&&(f.hasHeader=d),f}function Zn(e){let t=vr(Xn(e)),n=t.bottom,r=t.right;if(n!==void 0&&n>9999998||r!==void 0&&r>An)throw Error(`Range string out of bounds: ${e}`);if(n===void 0&&r===void 0)throw Error(`Wrong zone xc. The zone cannot be at the same time a full column and a full row`);return t}function Qn(e){let t=Zn(e);if(t.bottom===void 0||t.right===void 0)throw Error(`This does not support unbounded ranges`);return t}function $n(e){let{bottom:t,top:n,left:r,right:i}=e;return t!==void 0&&isNaN(t)||isNaN(n)||isNaN(r)||i!==void 0&&isNaN(i)?!1:er(e)&&e.top>=0&&e.left>=0}function er(e){return(e.bottom===void 0||e.bottom>=e.top&&e.bottom>=0)&&(e.right===void 0||e.right>=e.left&&e.right>=0)}function tr(e){let{top:t,bottom:n,left:r,right:i}=e,a=`hasHeader`in e?e.hasHeader:!1,o=t===n&&r===i;if(n===void 0&&i!==void 0)return t===0&&!a?`${Tn(r)}:${Tn(i)}`:`${w(r,t)}:${Tn(i)}`;if(i===void 0&&n!==void 0)return r===0&&!a?`${t+1}:${n+1}`:`${w(r,t)}:${n+1}`;if(n!==void 0&&i!==void 0)return o?w(r,t):`${w(r,t)}:${w(i,n)}`;throw Error(E(`Bad zone format`))}function nr(e,t,n,r,i){let a=t===`left`?`columns`:`rows`,o=r===`before`?n-1:n,s=e[t===`left`?`right`:`bottom`];return e[t]<=o&&s&&s>o?yr(e,a,`RESIZE`,i):o<e[t]?yr(e,a,`MOVE`,i):{...e}}function rr(e,t,n,r,i){let a=t===`left`?`columns`:`rows`,o=r===`before`?n-1:n,s=t===`left`?`right`:`bottom`;return e[t]<=o&&e[s]>o?yr(e,a,`RESIZE`,i):o<e[t]?yr(e,a,`MOVE`,i):{...e}}function ir(e,t,n){let r=t===`left`?`right`:`bottom`,i=e[t],a=e[r];for(let o of n.sort((e,t)=>t-e))e[t]>o&&(i--,a--),e[t]<o&&e[r]>=o&&a--;return{...e,[t]:i,[r]:a}}function ar(e,t,n){let r=t===`left`?`right`:`bottom`,i=e[t],a=e[r],o=e[r];for(let r of n.sort((e,t)=>t-e))e[t]>r&&(i--,a!==void 0&&a--),o!==void 0&&a!==void 0&&e[t]<=r&&o>=r&&a--;if(!(a!==void 0&&i>a))return{...e,[t]:i,[r]:a}}function or(...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 sr(...e){return{top:Math.min(...e.map(e=>e.top)),left:Math.min(...e.map(e=>e.left)),bottom:e.some(e=>e.bottom===void 0)?void 0:Math.max(...e.map(e=>e.bottom)),right:e.some(e=>e.right===void 0)?void 0:Math.max(...e.map(e=>e.right))}}function cr(e,t){if(ur(e,t))return{top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),bottom:Math.min(e.bottom,t.bottom),right:Math.min(e.right,t.right)}}function lr(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function ur(e,t){return!(e.bottom<t.top||t.bottom<e.top||e.right<t.left||t.right<e.left)}function dr(e,t,n){let{left:r,right:i,top:a,bottom:o}=n;return e>=r&&e<=i&&t>=a&&t<=o}function fr(e,t){return lr(or(t,e),t)}function pr(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function mr(e){let{numberOfCols:t,numberOfRows:n}=pr(e);return t===1||n===1}function hr(e){let{top:t,left:n,bottom:r,right:i}=e;if(Er(e)===1)return[];let a={top:t+1,bottom:r,left:n,right:n};if(i===n)return[a];let o={top:t,bottom:r,left:n+1,right:i};return t===r?[o]:[a,o]}function gr(e){let t={};for(let n of e)t[n.sheetId]??=[],t[n.sheetId].push(D(n));for(let e in t)t[e]=T(t[e]);return t}function _r(e){let t=[],{left:n,right:r,top:i,bottom:a}=vr(e);for(let e of x(n,r+1))for(let n of x(i,a+1))t.push({col:e,row:n});return t}function vr(e){return e.right!==void 0&&e.left>e.right&&(e={...e,left:e.right,right:e.left}),e.bottom!==void 0&&e.top>e.bottom&&(e={...e,top:e.bottom,bottom:e.top}),e}function yr(e,t,n,r){let i=t===`both`?r[0]:t===`columns`?r:0,a=t===`both`?r[1]:t===`rows`?r:0,o=`hasHeader`in e?e.hasHeader:!1,s;s=Tr(e)&&!o?t!==`rows`:wr(e)&&!o?t!==`columns`:!0;let c={...e};return s&&n===`MOVE`&&(c.left+=i,c.top+=a),c.right!==void 0&&(c.right+=i),c.bottom!==void 0&&(c.bottom+=a),c}function br(e){return e.reverse().filter((e,t,n)=>t===n.findIndex(t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)).reverse()}function xr(e){return e.reduce((e,t)=>{let n=e.length;for(let r=0;r<n;r++)if(ur(e[r],t))return e[r]=or(e[r],t),e;return e[n]=t,e},[])}function Sr(e,t){let n,r,{left:i,right:a,top:o,bottom:s}=e,{left:c,right:l,top:u,bottom:d}=t;return n=c===i?l===a?c:l:c,r=u===o?d===s?u:d:u,{col:n,row:r}}function D(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function Cr(e){return{...e,right:e.left,bottom:e.top}}function wr(e){return e.right===void 0}function Tr(e){return e.bottom===void 0}function Er(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function Dr(e){return e.length<2?!0:T(e).length===1}function Or(e){let t=new Set;for(let n of T(e))for(let e of x(n.left,n.right+1))t.add(e);return t}function kr(e){let t=new Set;for(let n of T(e))for(let e of x(n.top,n.bottom+1))t.add(e);return t}function Ar(e,t){return e.right+1===t.left||e.left===t.right+1?e.top<=t.bottom&&e.top>=t.top||t.top<=e.bottom&&t.top>=e.top:e.bottom+1===t.top||e.top===t.bottom+1?e.left<=t.right&&e.left>=t.left||t.left<=e.right&&t.left>=e.left:!1}function jr(e){let t=[...e],n=!0;for(;n;){n=!1;for(let e=0;e<t.length;e++){let r=t[e],i=t.findIndex((t,n)=>e!==n&&(Ar(t,r)||ur(t,r)));if(i!==-1){t[e]=or(t[i],r),t.splice(i,1),n=!0;break}}}return t}let Mr=new WeakMap,Nr=new WeakMap;function Pr(e,t){Mr.has(t)||(Mr.set(t,new Map),Nr.set(t,0));let n=Mr.get(t),r=Ir(e);if(n.has(r)){let i=n.get(r);return t[i]=e,i}let i=Nr.get(t)+1;return n.set(r,i),Nr.set(t,i),t[i]=e,i}function Fr(e){let t={};for(let n in e){let r=T(e[n].map(D));for(let e of r)t[tr(e)]=Number(n)}return t}function Ir(e){if(e===null)return`null`;if(e===void 0)return`undefined`;if(typeof e!=`object`)return String(e);if(Array.isArray(e)){let t=e.length,n=`[`;for(let r=0;r<t;r++)r>0&&(n+=`,`),n+=Ir(e[r]);return n+`]`}let t=Object.keys(e).sort(),n=`{`;for(let r of t)e[r]!==void 0&&(n+=`"${r}":${Ir(e[r])},`);return n+=`}`,n}var O=class e{jsDate;constructor(e,t,n,r=0,i=0,a=0){this.jsDate=new Date(Date.UTC(e,t,n,r,i,a,0))}static fromTimestamp(t){let n=new Date(t);return new e(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds())}static now(){let t=new Date;return new e(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds())}toString(){return this.jsDate.toString()}toLocaleDateString(){return this.jsDate.toLocaleDateString()}getTime(){return this.jsDate.getTime()}getFullYear(){return this.jsDate.getUTCFullYear()}getMonth(){return this.jsDate.getUTCMonth()}getQuarter(){return Math.floor(this.getMonth()/3)+1}getDate(){return this.jsDate.getUTCDate()}getDay(){return this.jsDate.getUTCDay()}getHours(){return this.jsDate.getUTCHours()}getMinutes(){return this.jsDate.getUTCMinutes()}getSeconds(){return this.jsDate.getUTCSeconds()}getIsoWeek(){let e=new Date(this.jsDate.getTime()),t=e.getUTCDay()||7;e.setUTCDate(e.getUTCDate()+4-t);let n=new Date(Date.UTC(e.getUTCFullYear(),0,1));return Math.ceil(((e.getTime()-n.getTime())/864e5+1)/7)}setFullYear(e){return this.jsDate.setUTCFullYear(e)}setMonth(e){return this.jsDate.setUTCMonth(e)}setDate(e){return this.jsDate.setUTCDate(e)}setHours(e){return this.jsDate.setUTCHours(e)}setMinutes(e){return this.jsDate.setUTCMinutes(e)}setSeconds(e){return this.jsDate.setUTCSeconds(e)}};let Lr=new O(1899,11,30),Rr=1440*60*1e3,zr=2e3,Br=O.now().getFullYear(),Vr=O.now().getMonth(),Hr=O.fromTimestamp(0).getTime()-Lr.getTime(),Ur=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,Wr=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,Gr=Ft.join(``),Kr=RegExp(`\/|-|${Ft.join(`|`)}`),qr=RegExp(`^(\\d{1,4})[\/${Gr}\-](\\d{1,4})([\/${Gr}\-](\\d{1,4}))?$`),Jr=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function Yr(e,t){switch(typeof e){case`number`:return e;case`string`:return Xr(e,t)?Qr(e,t)?.value:!e||isNaN(Number(e))?void 0:Number(e);default:return}}function Xr(e,t){return Qr(e,t)!==null}let Zr=new Map;function Qr(e,t){return Zr.has(t)||Zr.set(t,new Map),Zr.get(t).has(e)||Zr.get(t).set(e,$r(e,t)),Zr.get(t).get(e)}function $r(e,t){e=e.trim();let n=null,r=e.match(Jr);if(r){if(n=si(r[0]),n===null)return null;e=e.replace(r[0],``).trim()}let i=null,a=ei(e,t);if(a){let t=a.dateString.match(Kr)[0];if(i=ni(a,t),i===null)return null;e=e.replace(a.dateString,``).trim()}return e!==``||!(i||n)?null:i&&i.jsDate&&n&&n.jsDate?{value:i.value+n.value,format:i.format+` `+(n.format===`hhhh:mm:ss`?`hh:mm:ss`:n.format),jsDate:new O(i.jsDate.getFullYear()+n.jsDate.getFullYear()-1899,i.jsDate.getMonth()+n.jsDate.getMonth()-11,i.jsDate.getDate()+n.jsDate.getDate()-30,i.jsDate.getHours()+n.jsDate.getHours(),i.jsDate.getMinutes()+n.jsDate.getMinutes(),i.jsDate.getSeconds()+n.jsDate.getSeconds())}:i||n}function ei(e,t){let n=e.match(qr);if(!n)return null;let[,r,i,,a]=n;if(r.length>2&&a&&a.length>2)return null;if(r.length>2)return{year:r,month:i,day:a,dateString:e,type:`ymd`};let o=ti(t);return a?a.length>2?o===`mdy`?{month:r,day:i,year:a,dateString:e,type:`mdy`}:{day:r,month:i,year:a,dateString:e,type:`dmy`}:o===`mdy`?{month:r,day:i,year:a,dateString:e,type:`mdy`}:o===`ymd`?{year:r,month:i,day:a,dateString:e,type:`ymd`}:o===`dmy`?{day:r,month:i,year:a,dateString:e,type:`dmy`}:null:i.length>2?{month:r,year:i,day:void 0,dateString:e,type:o}:o===`dmy`?{day:r,month:i,year:a,dateString:e,type:`dmy`}:{month:r,day:i,year:a,dateString:e,type:`mdy`}}function ti(e){switch(e.dateFormat[0]){case`d`:return`dmy`;case`m`:return`mdy`;case`y`:return`ymd`}throw Error(`Invalid date format in locale`)}function ni(e,t){let{year:n,month:r,day:i}=e,a=ai(r),o=oi(i),s=ii(n);if(s===null||a===null||o===null)return null;let c=r?.length===2&&a+1<10||i?.length===2&&o<10,l=n?.length!==2,u=new O(s,a,o);if(u.getMonth()!==a||u.getDate()!==o)return null;let d=u.getTime()-Lr.getTime(),f=ri(e,t,c,l);return{value:Math.round(d/Rr),format:f,jsDate:u}}function ri(e,t,n,r){let i=e.year?r?`yyyy`:`yy`:void 0,a=e.month?n?`mm`:`m`:void 0,o=e.day?n?`dd`:`d`:void 0;switch(e.type){case`mdy`:return[a,o,i].filter(S).join(t);case`ymd`:return[i,a,o].filter(S).join(t);case`dmy`:return[o,a,i].filter(S).join(t)}}function ii(e){if(!e)return Br;let t=Number(e);switch(e.length){case 1:return zr+t;case 2:return zr+(zr+t>Br+10?-100:0)+t;case 3:case 4:return t}return null}function ai(e){if(!e)return Vr;let t=Number(e);return t>=1&&t<=12?t-1:null}function oi(e){if(!e)return 1;let t=Number(e);return t>=0&&t<=31?t:null}function si(e){if(e=e.trim(),Jr.test(e)){let t=/AM/i.test(e),n=/PM/i.test(e),r=(t||n?e.substring(0,e.length-2).trim():e).split(/:/),i=r.length>=2,a=r.length===3,o=Number(r[0]),s=i?Number(r[1]):0,c=a?Number(r[2]):0,l=a?`hh:mm:ss`:`hh:mm`;if(t||n)l+=` a`;else if(!i)return null;o>=12&&t?o-=12:o<12&&n&&(o+=12),s+=Math.floor(c/60),c%=60,o+=Math.floor(s/60),s%=60,o>=24&&(l=`hhhh:mm:ss`);let u=new O(1899,11,30,o,s,c);return{value:o/24+s/1440+c/86400,format:l,jsDate:u}}return null}function ci(e){let t=Math.trunc(e),n=O.fromTimestamp(t*Rr-Hr),r=e-t;r=r<0?1+r:r;let i=Math.round(r*24),a=Math.round((r-i/24)*24*60),o=Math.round((r-i/24-a/24/60)*24*60*60);return n.setHours(i),n.setMinutes(a),n.setSeconds(o),n}function li(e){return Math.round(ui(e))}function ui(e){return(e.getTime()-Lr.getTime())/Rr}function di(e){return new O(e.getFullYear(),e.getMonth()+1,0).getDate()}function fi(e){return di(e)===e.getDate()}function pi(e,t,n){let r=e.getFullYear(),i=e.getMonth(),a=e.getDate(),o=new O(r,i+t,1);return n&&a===di(e)||a>di(o)?o.setDate(di(o)):o.setDate(a),o}function mi(e){let t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function hi(e,t,n){if(e===t)return 0;if(e>t){let n=t;t=e,e=n}let r=ci(e),i=ci(t),a=r.getDate(),o=i.getDate(),s=r.getMonth(),c=i.getMonth(),l=r.getFullYear(),u=i.getFullYear(),d=0,f=0;switch(n){case 0:a===31&&(a=30),a===30&&o===31&&(o=30),s===1&&a===(mi(l)?29:28)&&(a=30,c===1&&o===(mi(u)?29:28)&&(o=30)),d=l+(s*30+a)/360,f=u+(c*30+o)/360;break;case 1:let n=365,r=l===u,i=l+1===u;if(!r&&!i||!r&&s<c||!r&&s===c&&a<o){let e=0,t=0;for(let n=l;n<=u;n++)e++,t+=mi(n)?366:365;n=t/e}else r?mi(l)&&(n=366):(mi(l)&&s<2&&(n=366),mi(u)&&(c>1||c===1&&o===29)&&(n=366));d=e/n,f=t/n;break;case 2:d=e/360,f=t/360;break;case 3:d=e/365,f=t/365;break;case 4:a===31&&(a=30),o===31&&(o=30),d=l+(s*30+a)/360,f=u+(c*30+o)/360;break}return f-d}function gi(e,t){let n=(t.getFullYear()-e.getFullYear())*12+t.getMonth()-e.getMonth();return e.getDate()>t.getDate()?n-1:n}function _i(e,t){let n=e.getTime(),r=t.getTime();return Math.floor((r-n)/Rr)}function vi(e,t){let n=t.getFullYear()-e.getFullYear(),r=e.getMonth(),i=t.getMonth(),a=e.getDate(),o=t.getDate();return i>r||i===r&&o>=a?n:n-1}function yi(e,t){return hi(e,t,1)<1}function bi(e,t){return Math.trunc(e)===Math.trunc(t)}function xi(e,t,n){return t>n?xi(e,n,t):(e=Math.trunc(e),t=Math.trunc(t),n=Math.trunc(n),e>=t&&e<=n)}function Si(e,t){return Math.trunc(e)<Math.trunc(t)}function Ci(e,t){return Math.trunc(e)<=Math.trunc(t)}function wi(e,t){return Math.trunc(e)>Math.trunc(t)}function Ti(e,t){return Math.trunc(e)>=Math.trunc(t)}let Ei=Rt(function(e){return e=nt(e),RegExp(`(?:^-?\\d+(?:${e}?\\d*(?:e(\\+|-)?\\d+)?)?|^-?${e}\\d+)(?!\\w|!)`)}),Di=Rt(function(e){let t=nt(e.decimalSeparator),n=`(?:\\d+(?:${nt(e.thousandsSeparator||``)}\\d{3,})*(?:${t}\\d*)?)`,r=`(?:${t}\\d+)`,i=`(?:\\s*`+n+`|`+r+`)(?:e(?:\\+|-)?\\d+)?(?:\\s*%)?`,a=`(?:\\s*-)?`,o=`(?:\\s*[\\$€])?`,s=`^(?:(?:`+[a+o+i,a+i+o,o+a+i].join(`)|(?:`)+`))$`;return new RegExp(s,`i`)});function Oi(e,t){return e?Di(t).test(e.trim()):!1}let ki=Rt(function(e){return RegExp(`[\$€${nt(e.thousandsSeparator||``)}]`,`g`)});function Ai(e,t){e=e.replace(ki(t),``),t.decimalSeparator!==`.`&&(e=e.replace(t.decimalSeparator,`.`));let n=Number(e);return isNaN(n)&&e.includes(`%`)&&(n=Number(e.split(`%`)[0]),!isNaN(n))?n/100:n}function ji(e,t,n){let r=[...e].sort((e,t)=>e-t),i=(r.length+(n?-1:1))*t;if(n||i--,Number.isInteger(i))return r[i];let a=Math.ceil(i),o=Math.floor(i);return r[a]*(i-o)+r[o]*(a-i)}function Mi(e){return`sheetId`in e}function Ni(e){return`dimension`in e&&`sheetId`in e&&`elements`in e}function Pi(e){return`target`in e&&`sheetId`in e}function Fi(e){return`ranges`in e}function Ii(e){return`col`in e&&`row`in e&&`sheetId`in e}function Li(e){return`sheetId`in e&&`zone`in e}let Ri=new Set([`RENAME_SHEET`,`DELETE_SHEET`,`CREATE_SHEET`,`DUPLICATE_SHEET`,`ADD_COLUMNS_ROWS`,`REMOVE_COLUMNS_ROWS`,`UNDO`,`REDO`,`ADD_MERGE`,`REMOVE_MERGE`,`UPDATE_LOCALE`,`ADD_PIVOT`,`UPDATE_PIVOT`,`INSERT_PIVOT`,`RENAME_PIVOT`,`REMOVE_PIVOT`,`DUPLICATE_PIVOT`]),zi=new Set([`EVALUATE_CELLS`,`UPDATE_CELL`,`UNHIDE_COLUMNS_ROWS`,`HIDE_COLUMNS_ROWS`,`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUP`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_ALL_HEADER_GROUPS`,`UNFOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`UPDATE_TABLE`,`UPDATE_FILTER`,`UNDO`,`REDO`]),Bi=new Set([`MOVE_RANGES`]),Vi=new Set([`EVALUATE_CELLS`,`ADD_CONDITIONAL_FORMAT`,`REMOVE_CONDITIONAL_FORMAT`,`CHANGE_CONDITIONAL_FORMAT_PRIORITY`]),Hi=new Set([`AUTOFILL_CELL`,`SET_BORDER`,`SET_ZONE_BORDERS`,`SET_BORDERS_ON_TARGET`]),Ui=new Set([`START`,`ACTIVATE_SHEET`,`COPY`,`RESIZE_SHEETVIEW`,`SET_VIEWPORT_OFFSET`,`EVALUATE_CELLS`,`SET_FORMULA_VISIBILITY`,`UPDATE_FILTER`]),Wi=new Set(`UPDATE_CELL.UPDATE_CELL_POSITION.CLEAR_CELL.CLEAR_CELLS.DELETE_CONTENT.ADD_COLUMNS_ROWS.REMOVE_COLUMNS_ROWS.RESIZE_COLUMNS_ROWS.HIDE_COLUMNS_ROWS.UNHIDE_COLUMNS_ROWS.SET_GRID_LINES_VISIBILITY.UNFREEZE_COLUMNS.UNFREEZE_ROWS.FREEZE_COLUMNS.FREEZE_ROWS.UNFREEZE_COLUMNS_ROWS.ADD_MERGE.REMOVE_MERGE.CREATE_SHEET.DELETE_SHEET.DUPLICATE_SHEET.MOVE_SHEET.RENAME_SHEET.COLOR_SHEET.HIDE_SHEET.SHOW_SHEET.MOVE_RANGES.ADD_CONDITIONAL_FORMAT.REMOVE_CONDITIONAL_FORMAT.CHANGE_CONDITIONAL_FORMAT_PRIORITY.CREATE_FIGURE.DELETE_FIGURE.UPDATE_FIGURE.SET_FORMATTING.CLEAR_FORMATTING.SET_BORDER.SET_ZONE_BORDERS.SET_BORDERS_ON_TARGET.CREATE_CHART.UPDATE_CHART.CREATE_TABLE.REMOVE_TABLE.UPDATE_TABLE.CREATE_TABLE_STYLE.REMOVE_TABLE_STYLE.CREATE_IMAGE.GROUP_HEADERS.UNGROUP_HEADERS.UNFOLD_HEADER_GROUP.FOLD_HEADER_GROUP.FOLD_ALL_HEADER_GROUPS.UNFOLD_ALL_HEADER_GROUPS.UNFOLD_HEADER_GROUPS_IN_ZONE.FOLD_HEADER_GROUPS_IN_ZONE.ADD_DATA_VALIDATION_RULE.REMOVE_DATA_VALIDATION_RULE.UPDATE_LOCALE.ADD_PIVOT.UPDATE_PIVOT.INSERT_PIVOT.RENAME_PIVOT.REMOVE_PIVOT.DUPLICATE_PIVOT`.split(`.`));function Gi(e){return Wi.has(e.type)}function Ki(e){return Ui.has(e.type)}var qi=class{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter(e=>e!==`Success`)}static get Success(){return Ji}get isSuccessful(){return this.reasons.length===0}isCancelledBecause(e){return this.reasons.includes(e)}};let Ji=new qi,Yi=function(e){return e.Success=`Success`,e.CancelledForUnknownReason=`CancelledForUnknownReason`,e.WillRemoveExistingMerge=`WillRemoveExistingMerge`,e.CannotMoveTableHeader=`CannotMoveTableHeader`,e.MergeIsDestructive=`MergeIsDestructive`,e.CellIsMerged=`CellIsMerged`,e.InvalidTarget=`InvalidTarget`,e.EmptyUndoStack=`EmptyUndoStack`,e.EmptyRedoStack=`EmptyRedoStack`,e.NotEnoughElements=`NotEnoughElements`,e.NotEnoughSheets=`NotEnoughSheets`,e.MissingSheetName=`MissingSheetName`,e.UnchangedSheetName=`UnchangedSheetName`,e.DuplicatedSheetName=`DuplicatedSheetName`,e.DuplicatedSheetId=`DuplicatedSheetId`,e.ForbiddenCharactersInSheetName=`ForbiddenCharactersInSheetName`,e.WrongSheetMove=`WrongSheetMove`,e.WrongSheetPosition=`WrongSheetPosition`,e.InvalidAnchorZone=`InvalidAnchorZone`,e.SelectionOutOfBound=`SelectionOutOfBound`,e.TargetOutOfSheet=`TargetOutOfSheet`,e.WrongCutSelection=`WrongCutSelection`,e.WrongPasteSelection=`WrongPasteSelection`,e.WrongPasteOption=`WrongPasteOption`,e.WrongFigurePasteOption=`WrongFigurePasteOption`,e.EmptyClipboard=`EmptyClipboard`,e.EmptyRange=`EmptyRange`,e.InvalidRange=`InvalidRange`,e.InvalidZones=`InvalidZones`,e.InvalidSheetId=`InvalidSheetId`,e.InvalidCellId=`InvalidCellId`,e.InvalidFigureId=`InvalidFigureId`,e.InputAlreadyFocused=`InputAlreadyFocused`,e.MaximumRangesReached=`MaximumRangesReached`,e.MinimumRangesReached=`MinimumRangesReached`,e.InvalidChartDefinition=`InvalidChartDefinition`,e.InvalidDataSet=`InvalidDataSet`,e.InvalidLabelRange=`InvalidLabelRange`,e.InvalidScorecardKeyValue=`InvalidScorecardKeyValue`,e.InvalidScorecardBaseline=`InvalidScorecardBaseline`,e.InvalidGaugeDataRange=`InvalidGaugeDataRange`,e.EmptyGaugeRangeMin=`EmptyGaugeRangeMin`,e.GaugeRangeMinNaN=`GaugeRangeMinNaN`,e.EmptyGaugeRangeMax=`EmptyGaugeRangeMax`,e.GaugeRangeMaxNaN=`GaugeRangeMaxNaN`,e.GaugeRangeMinBiggerThanRangeMax=`GaugeRangeMinBiggerThanRangeMax`,e.GaugeLowerInflectionPointNaN=`GaugeLowerInflectionPointNaN`,e.GaugeUpperInflectionPointNaN=`GaugeUpperInflectionPointNaN`,e.GaugeLowerBiggerThanUpper=`GaugeLowerBiggerThanUpper`,e.InvalidAutofillSelection=`InvalidAutofillSelection`,e.MinBiggerThanMax=`MinBiggerThanMax`,e.LowerBiggerThanUpper=`LowerBiggerThanUpper`,e.MidBiggerThanMax=`MidBiggerThanMax`,e.MinBiggerThanMid=`MinBiggerThanMid`,e.FirstArgMissing=`FirstArgMissing`,e.SecondArgMissing=`SecondArgMissing`,e.MinNaN=`MinNaN`,e.MidNaN=`MidNaN`,e.MaxNaN=`MaxNaN`,e.ValueUpperInflectionNaN=`ValueUpperInflectionNaN`,e.ValueLowerInflectionNaN=`ValueLowerInflectionNaN`,e.MinInvalidFormula=`MinInvalidFormula`,e.MidInvalidFormula=`MidInvalidFormula`,e.MaxInvalidFormula=`MaxInvalidFormula`,e.ValueUpperInvalidFormula=`ValueUpperInvalidFormula`,e.ValueLowerInvalidFormula=`ValueLowerInvalidFormula`,e.InvalidSortZone=`InvalidSortZone`,e.WaitingSessionConfirmation=`WaitingSessionConfirmation`,e.MergeOverlap=`MergeOverlap`,e.TooManyHiddenElements=`TooManyHiddenElements`,e.Readonly=`Readonly`,e.InvalidViewportSize=`InvalidViewportSize`,e.InvalidScrollingDirection=`InvalidScrollingDirection`,e.ViewportScrollLimitsReached=`ViewportScrollLimitsReached`,e.FigureDoesNotExist=`FigureDoesNotExist`,e.InvalidConditionalFormatId=`InvalidConditionalFormatId`,e.InvalidConditionalFormatType=`InvalidConditionalFormatType`,e.InvalidCellPopover=`InvalidCellPopover`,e.EmptyTarget=`EmptyTarget`,e.InvalidFreezeQuantity=`InvalidFreezeQuantity`,e.FrozenPaneOverlap=`FrozenPaneOverlap`,e.ValuesNotChanged=`ValuesNotChanged`,e.InvalidFilterZone=`InvalidFilterZone`,e.TableNotFound=`TableNotFound`,e.TableOverlap=`TableOverlap`,e.InvalidTableConfig=`InvalidTableConfig`,e.InvalidTableStyle=`InvalidTableStyle`,e.FilterNotFound=`FilterNotFound`,e.MergeInTable=`MergeInTable`,e.NonContinuousTargets=`NonContinuousTargets`,e.DuplicatedFigureId=`DuplicatedFigureId`,e.InvalidSelectionStep=`InvalidSelectionStep`,e.DuplicatedChartId=`DuplicatedChartId`,e.ChartDoesNotExist=`ChartDoesNotExist`,e.InvalidHeaderIndex=`InvalidHeaderIndex`,e.InvalidQuantity=`InvalidQuantity`,e.MoreThanOneColumnSelected=`MoreThanOneColumnSelected`,e.EmptySplitSeparator=`EmptySplitSeparator`,e.SplitWillOverwriteContent=`SplitWillOverwriteContent`,e.NoSplitSeparatorInSelection=`NoSplitSeparatorInSelection`,e.NoActiveSheet=`NoActiveSheet`,e.InvalidLocale=`InvalidLocale`,e.MoreThanOneRangeSelected=`MoreThanOneRangeSelected`,e.NoColumnsProvided=`NoColumnsProvided`,e.ColumnsNotIncludedInZone=`ColumnsNotIncludedInZone`,e.DuplicatesColumnsSelected=`DuplicatesColumnsSelected`,e.InvalidHeaderGroupStartEnd=`InvalidHeaderGroupStartEnd`,e.HeaderGroupAlreadyExists=`HeaderGroupAlreadyExists`,e.UnknownHeaderGroup=`UnknownHeaderGroup`,e.UnknownDataValidationRule=`UnknownDataValidationRule`,e.UnknownDataValidationCriterionType=`UnknownDataValidationCriterionType`,e.InvalidDataValidationCriterionValue=`InvalidDataValidationCriterionValue`,e.InvalidNumberOfCriterionValues=`InvalidNumberOfCriterionValues`,e.InvalidCopyPasteSelection=`InvalidCopyPasteSelection`,e.NoChanges=`NoChanges`,e.InvalidInputId=`InvalidInputId`,e.SheetIsHidden=`SheetIsHidden`,e.InvalidTableResize=`InvalidTableResize`,e.PivotIdNotFound=`PivotIdNotFound`,e.PivotInError=`PivotInError`,e.EmptyName=`EmptyName`,e.ValueCellIsInvalidFormula=`ValueCellIsInvalidFormula`,e.InvalidDefinition=`InvalidDefinition`,e.InvalidColor=`InvalidColor`,e.InvalidPivotDataSet=`InvalidPivotDataSet`,e}({}),Xi=[{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:`;`}],k=Xi[0],Zi=[`thin`,`medium`,`thick`,`dashed`,`dotted`];function A(e){return Array.isArray(e)&&Array.isArray(e[0])}let Qi={Background:0,Highlights:1,Clipboard:2,Chart:4,Autofill:5,Selection:6,Headers:100},$i=Rt(()=>Object.keys(Qi).sort((e,t)=>Qi[e]-Qi[t]));function ea(e,t){if(Qi[e])throw Error(`Layer ${e} already exists`);Qi[e]=t}let j={NotAvailable:`#N/A`,InvalidReference:`#REF`,BadExpression:`#BAD_EXPR`,CircularDependency:`#CYCLE`,UnknownFunction:`#NAME?`,DivisionByZero:`#DIV/0!`,SpilledBlocked:`#SPILL!`,GenericError:`#ERROR`,NullError:`#NULL!`},ta=new Set(Object.values(j));var M=class{message;value;constructor(e=E(`Error`),t=j.GenericError){this.message=e,this.value=t,this.message=e.toString()}},na=class extends M{constructor(e=E(`Invalid expression`)){super(e,j.BadExpression)}},ra=class extends M{constructor(e=E(`Circular reference`)){super(e,j.CircularDependency)}},ia=class extends M{constructor(e=E(`Invalid reference`)){super(e,j.InvalidReference)}},aa=class extends M{constructor(e=E(`Data not available`)){super(e,j.NotAvailable)}},oa=class extends M{constructor(e=E(`Unknown function`)){super(e,j.UnknownFunction)}},sa=class extends M{constructor(e=E(`Spill range is not empty`)){super(e,j.SpilledBlocked)}};let ca=[`number`,`string`,`boolean`,`undefined`];function N(e,t,n){if(!e())throw new M(t,n)}function la(e){if(e!==void 0)return A(e)?e[0][0]?.format:e.format}function P(e){return typeof e==`string`&&ta.has(e)}let ua=e=>E(`The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.`,e),da=(e,t,n)=>E(`The function [[FUNCTION_NAME]] expects a number value between %s and %s inclusive, but receives %s.`,e.toString(),t.toString(),n.toString()),fa=(e,t)=>E(`The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.`,t,e.map(e=>`'${e}'`).join(`, `));function F(e,t){let n=Ca(e);switch(typeof n){case`number`:return n;case`boolean`:return+!!n;case`string`:if(Oi(n,t)||n===``)return Ai(n,t);let e=Qr(n,t);if(e)return e.value;throw new M(ua(n));default:return 0}}function pa(e,t){try{return F(e,t)}catch{return}}function ma(e,t){return z(e).map(e=>e.map(e=>{if(typeof e.value!=`number`){let n=``;throw typeof e==`object`?n=E(`Function [[FUNCTION_NAME]] expects number values for %s, but got an empty value.`,t):typeof e==`string`?n=E(`Function [[FUNCTION_NAME]] expects number values for %s, but got a string.`,t):typeof e==`boolean`&&(n=E(`Function [[FUNCTION_NAME]] expects number values for %s, but got a boolean.`,t)),new M(n)}return e.value}))}function ha(e,t){let n=Ca(e);if(n===``)throw new M(ua(n));return F(n,t)}function ga(e,t){return Math.trunc(F(e,t))}function _a(e,t){return Math.trunc(ha(e,t))}function va(e){N(()=>e>=1,E(`The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.`,e.toString()))}function ya(e){N(()=>e!==0,E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`),j.DivisionByZero)}function I(e){let t=Ca(e);switch(typeof t){case`string`:return t;case`number`:return t.toString();case`boolean`:return t?`TRUE`:`FALSE`;default:return``}}let ba=Rt(function(e){return e.toLowerCase().normalize(`NFD`).replace(/[\u0300-\u036f]/g,``)}),xa=e=>E(`The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a boolean.`,e);function L(e){let t=Ca(e);switch(typeof t){case`boolean`:return t;case`string`:if(t){let e=t.toUpperCase();if(e===`TRUE`)return!0;if(e===`FALSE`)return!1;throw new M(xa(t))}else return!1;case`number`:return!!t;default:return!1}}function Sa(e){let t=Ca(e);if(t===``)throw new M(xa(t));return L(t)}function R(e,t){return ci(F(Ca(e),t))}function Ca(e){if(typeof e==`object`&&e&&`value`in e){if(P(e.value))throw e;return e.value}if(P(e))throw new M(``,e);return e}function wa(e,t,n){for(let r of e)if(A(r)){let e=r.length,n=r[0].length;for(let i=0;i<n;i++)for(let n=0;n<e;n++)t(r[n][i])}else n(r)}function Ta(e,t){wa(e,e=>{if(P(e.value))throw e;t(e)},e=>{if(P(e?.value))throw e;t(e)})}function Ea(e,t,n){wa(e,e=>{if(typeof e?.value==`number`&&t(e),P(e?.value))throw e},e=>{t({value:ha(e,n),format:e?.format})})}function Da(e,t,n,r,i=`rowFirst`){let a=r;for(let r of e)if(A(r)){let e=r.length,n=r[0].length;if(i===`rowFirst`)for(let i=0;i<n;i++)for(let n=0;n<e;n++)a=t(a,r[n][i]);else for(let i=0;i<e;i++)for(let e=0;e<n;e++)a=t(a,r[i][e])}else a=n(a,r);return a}function Oa(e,t,n,r=`rowFirst`){return Da(e,t,t,n,r)}function ka(e,t,n,r){return Da(e,(e,n)=>{let r=n?.value;if(typeof r==`number`)return t(e,r);if(P(r))throw n;return e},(e,n)=>t(e,ha(n,r)),n)}function Aa(e,t,n,r){return Da(e,(e,n)=>{let i=n?.value;if(i!=null){if(typeof i==`number`)return t(e,i);if(typeof i==`boolean`)return t(e,F(i,r));if(P(i))throw n;return t(e,0)}return e},(e,n)=>t(e,F(n,r)),n)}function ja(e,t,n){let r=Array(e);for(let i=0;i<e;i++){r[i]=Array(t);for(let e=0;e<t;e++)r[i][e]=n(i,e)}return r}function Ma(e,t){return e.length===0?[]:ja(e.length,e[0].length,(n,r)=>t(e[n][r]))}function Na(e,t){let n=e.length,r=e[0]?.length??0;for(let i=0;i<n;i++)for(let n=0;n<r;n++)t(e[i][n])}function Pa(e){return e.length?ja(e[0].length,e.length,(t,n)=>e[n][t]):[]}function Fa(e,t,n=void 0){let r=1,i=1,a=1/0,o=1/0,s;for(let e=0;e<t.length;e++){let c=t[e];if(A(c)&&(n===void 0||n[e])){let n=c.length,l=c[0].length;n!==1||l!==1?(s??=Array(t.length),n!==1&&l!==1?(s[e]=`matrix`,r=Math.max(r,n),i=Math.max(i,l),a=Math.min(a,n),o=Math.min(o,l)):n===1?l!==1&&(s[e]=`vertical`,i=Math.max(i,l),o=Math.min(o,l)):(s[e]=`horizontal`,r=Math.max(r,n),a=Math.min(a,n))):t[e]=c[0][0]}}if(r===1&&i===1)return e(...t);let c=(e,n)=>t.map((t,r)=>{switch(s?.[r]){case`matrix`:return t[e][n];case`horizontal`:return t[e][0];case`vertical`:return t[0][n];case void 0:return t}});return ja(r,i,(t,n)=>{if(t>a-1||n>o-1)return new aa(E(`Array arguments to [[FUNCTION_NAME]] are of different size.`));let r=e(...c(t,n));return A(r)?r[0][0]:r})}function Ia(e,t,n){for(let r of e)if(A(r)){let e=r.length,n=r[0].length;for(let i=0;i<n;i++)for(let n=0;n<e;n++)if(!t(r[n][i]??void 0))return}else if(!n(r))return}function La(e,t){return Ia(e,e=>{let n=e?.value;if(typeof n==`boolean`)return t(n);if(typeof n==`number`)return t(!!n);if(P(n))throw e;return!0},e=>e!==void 0&&e.value!==null?t(Sa(e)):!0)}function Ra(e,t){let n,r,i=e.substring(0,2);return i===`<=`||i===`>=`||i===`<>`?(n=i,r=e.substring(2)):(i=e.substring(0,1),i===`<`||i===`>`||i===`=`?(n=i,r=e.substring(1)):(n=`=`,r=e)),Oi(r,t)||Xr(r,t)?r=F(r,t):(r===`TRUE`||r===`FALSE`)&&(r=L(r)),{operator:n,operand:r}}let za=Rt(function(e){if(e===`*`)return/.+/;let t=``,n=``;for(let r of e)r===`?`&&n!==`~`?t+=`.`:r===`*`&&n!==`~`?t+=`.*`:((r===`*`||r===`?`)&&(t=t.slice(0,-1)),[`^`,`.`,`[`,`]`,`$`,`(`,`)`,`*`,`+`,`?`,`|`,`{`,`}`,`\\`].includes(r)&&(t+=`\\`),t+=r),n=r;return RegExp(`^`+t+`$`,`i`)});function Ba(e=``,t,n){let{operator:r,operand:i}=t;if(i===void 0||e===null||i===null)return!1;if(typeof i==`number`&&r===`=`)return typeof e==`string`&&(Oi(e,n)||Xr(e,n))?F(e,n)===i:e===i;if(r===`<>`||r===`=`){let t;return t=typeof e==typeof i?typeof e==`string`&&typeof i==`string`?za(i).test(e):e===i:!1,r===`=`?t:!t}if(typeof e==typeof i)switch(r){case`<`:return e<i;case`>`:return e>i;case`<=`:return e<=i;case`>=`:return e>=i}return!1}function Va(e,t,n,r=!1){let i=e.length;if(i%2==1)throw new M(E(`Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs.`));let a=z(e[0]),o=a.length,s=a[0].length,c=[];for(let t=0;t<i-1;t+=2){let i=z(e[t]);if(i.length!==o||i[0].length!==s)throw new M(E(`Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension`));let a=Ra(I(e[t+1]),n);r&&typeof a.operand==`string`&&(a.operand+=`*`),c.push(a)}for(let r=0;r<o;r++)for(let a=0;a<s;a++){let o=!0;for(let t=0;t<i-1;t+=2){let i=z(e[t])[r][a].value,s=c[t/2];if(o=Ba(i??void 0,s,n),!o)break}o&&t(r,a)}}function Ha(e,t,n,r,i,a){if(t===void 0||t.value===null)return-1;if(P(t.value))throw t;let o=Ga(t.value),s=typeof o,c,l,u=0,d=i-1,f,p,m,h,g=r===`desc`?t=>Ga(a(e,i-t-1)):t=>Ga(a(e,t));for(;d-u>=0;){for(f=Math.floor((u+d)/2),p=f,m=g(p),h=typeof m;u<p&&s!==h;)p--,m=g(p),h=typeof m;if(h!==s||m==null){u=f+1;continue}n===`strict`&&m===o?(c=m,l=p):n===`nextSmaller`&&m<=o?(c==null||c<m||c===m&&l<p)&&(c=m,l=p):n===`nextGreater`&&m>=o&&(c===void 0||c>m||c===m&&l<p)&&(c=m,l=p),m>o||n===`strict`&&m===o?d=p-1:u=f+1}return l===void 0?-1:r===`desc`?i-l-1:l}function Ua(e,t,n,r,i,a,o=!1){if(t===void 0||t.value===null)return-1;if(P(t.value))throw t;let s=Ga(t.value),c=o?(e,t)=>Ga(i(e,r-t-1)):(e,t)=>Ga(i(e,t)),l=n!==`wildcard`||typeof s!=`string`||!(s.includes(`*`)||s.includes(`?`));if(a&&l){let t=o?`reverseSearch`:`forwardSearch`,i=a[t].get(e);if(i===void 0){i=new Map;for(let t=0;t<r;t++){let n=c(e,t)??null;i.has(n)||i.set(n,t)}a[t].set(e,i)}if(i.has(s)){let e=i.get(s);return o?r-e-1:e}if(n===`strict`)return-1}let u=Wa(e,s,n,r,c);return o&&u!==-1?r-u-1:u}function Wa(e,t,n,r,i){let a=n=>i(e,n)===t;if(n===`wildcard`&&typeof t==`string`&&(t.includes(`*`)||t.includes(`?`))){let n=za(t);a=t=>{let r=i(e,t);return typeof r==`string`?n.test(r):!1}}let o,s=-1;n===`nextSmaller`&&(a=n=>{let r=i(e,n);return(!o&&Ka(t,r)>=0||Ka(t,r)>=0&&Ka(r,o)>0)&&(o=r,s=n),r===t}),n===`nextGreater`&&(a=n=>{let r=i(e,n);return(!o&&Ka(t,r)<=0||Ka(t,r)<=0&&Ka(r,o)<0)&&(o=r,s=n),r===t});for(let e=0;e<r;e++)if(a(e))return e;return s}function Ga(e){return typeof e==`string`?ba(e):e}function Ka(e,t){let n=ca.indexOf(typeof e)-ca.indexOf(typeof t);return n===0&&(typeof e==`string`&&typeof t==`string`?n=e.localeCompare(t):typeof e==`number`&&typeof t==`number`?n=e-t:typeof e==`boolean`&&typeof t==`boolean`&&(n=Number(e)-Number(t))),n}function z(e){return e===void 0?[[]]:A(e)?e:[[e]]}function qa(e,t){return Oa(e,(e,n)=>(e.push(t(n)),e),[],`rowFirst`)}function Ja(e){if(e===void 0)return!1;let{value:t}=e;return!(t===null||t===``)}function Ya(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}let Xa=new h;function Za(e,t){return e=Ya(e),{url:e,label:t||e,isExternal:!0,isUrlEditable:!0}}Xa.add(`sheet_URL`,{match:e=>vt(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){let n=bt(e);return t.tryGetSheetName(n)||E(`Invalid sheet`)},open(e,t){let n=bt(e);t.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:n}).isCancelledBecause(`SheetIsHidden`)&&t.notifyUser({type:`warning`,sticky:!1,text:E(`Cannot open the link because the linked sheet is hidden.`)})},sequence:0});let Qa={createLink:Za,match:e=>mt(e),open:e=>window.open(e,`_blank`),urlRepresentation:e=>e,sequence:0};function $a(e){return Xa.getAll().sort((e,t)=>e.sequence-t.sequence).find(t=>t.match(e))||Qa}function eo(e,t){return $a(e.url).urlRepresentation(e.url,t)}function to(e,t){$a(e.url).open(e.url,t)}function no(e){if(typeof e==`string`){if(pt(e)){let{label:t,url:n}=gt(e);return $a(n).createLink(n,t)}else if(mt(e))return Za(e)}}function ro(e){e=e.replace(/\s/g,` `);let t=new qt(e),n=[],r=[];for(n.push(r);!t.isOver();){if(t.current===`;`){r=[],n.push(r),t.shift();continue}let e=fo(t)||io(t)||oo(t)||so(t)||lo(t)||uo(t)||mo(t)||co(t)||ho(t);if(!e)throw Error(`Unknown token at `+t.remaining());r.push(e)}return n}function io(e){let t;if(e.current===`"`?(e.shift(),t=`"`):e.currentStartsWith(`[$`)&&(e.advanceBy(2),t=`]`),!t)return null;let n=``;for(;e.current&&e.current!==t;)n+=e.shift();if(e.current===t)e.shift();else throw Error(`Unterminated string in format`);return{type:`STRING`,value:n}}let ao=new Set(`$+-/():!^&~{}<>= `);function oo(e){if(e.current===`\\`){e.shift();let t=e.shift();if(!t)throw Error(`Unexpected end of format string`);return{type:`CHAR`,value:t}}return ao.has(e.current)?{type:`CHAR`,value:e.shift()}:null}function so(e){return e.current===`,`?(e.shift(),{type:`THOUSANDS_SEPARATOR`,value:`,`}):null}function co(e){return e.current===`@`?(e.shift(),{type:`TEXT_PLACEHOLDER`,value:`@`}):null}function lo(e){return e.current===`.`?(e.shift(),{type:`DECIMAL_POINT`,value:`.`}):null}function uo(e){return e.current===`%`?(e.shift(),{type:`PERCENT`,value:`%`}):null}function fo(e){if(e.current===`0`||e.current===`#`){let t=e.current;return e.shift(),{type:`DIGIT`,value:t}}return null}let po=new Set(`dmqyhsa`);function mo(e){if(!po.has(e.current))return null;let t=e.current,n=``;for(;e.current===t;)n+=e.shift();return{type:`DATE_PART`,value:n}}function ho(e){if(e.current!==`*`)return null;e.shift();let t=e.shift();if(!t)throw Error(`Unexpected end of format string`);return{type:`REPEATED_CHAR`,value:t}}let go={};function _o(e){let t=go[e];return t===void 0&&(t=vo(e),go[e]=t),t}function vo(e){let t=ro(e);for(let e of t){let t=e.filter(e=>e.type===`REPEATED_CHAR`);for(let e of t.slice(1))e.type=`CHAR`}let n=Co(t[0])||So(t[0])||wo(t[0]);if(!n)throw Error(`Invalid first format part of: `+e);if(t.length>1&&n.type===`text`)throw Error(`The first format in a multi-part format must be a number format: `+e);let r=Co(t[1])||So(t[1]);if(t[1]?.length&&!r)throw Error(`Invalid second format part of: `+e);let i=Co(t[2])||So(t[2]);if(t[2]?.length&&!i)throw Error(`Invalid third format part of: `+e);let a=wo(t[3]);if(t[3]?.length&&!a)throw Error(`Invalid fourth format part of: `+e);return{positive:n,negative:r,zero:i,text:a}}function yo(e){return e.every(e=>e.type===`DATE_PART`||e.type===`DECIMAL_POINT`||e.type===`THOUSANDS_SEPARATOR`||e.type===`STRING`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function bo(e){return e.every(e=>e.type===`DIGIT`||e.type===`DECIMAL_POINT`||e.type===`THOUSANDS_SEPARATOR`||e.type===`PERCENT`||e.type===`STRING`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function xo(e){return e.every(e=>e.type===`STRING`||e.type===`TEXT_PLACEHOLDER`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function So(e){if(!e||!bo(e))return;let t=[],n,r=t,i=0,a=0,o=e.findLastIndex(e=>e.type===`DIGIT`),s=!1,c=0;for(let l=0;l<e.length;l++){let u=e[l];switch(u.type){case`DIGIT`:r===t?r.push(u):c<20&&(r.push(u),c++);break;case`DECIMAL_POINT`:if(r===t)n=[],r=n;else throw Error(`Multiple decimal points in a number format`);break;case`REPEATED_CHAR`:case`CHAR`:case`STRING`:r.push(u);break;case`PERCENT`:i++,r.push(u);break;case`THOUSANDS_SEPARATOR`:l-1===o?(a+=1,o++,r.push(u)):e[l+1]?.type===`DIGIT`&&e[l-1]?.type===`DIGIT`?(r===t&&(s=!0),r.push(u)):r.push({type:`CHAR`,value:`,`});break}}return{type:`number`,integerPart:t,decimalPart:n,percentSymbols:i,thousandsSeparator:s,magnitude:a}}function Co(e){let t=e&&yo(e)?{type:`date`,tokens:e}:void 0;if(t){if(t.tokens.length&&t.tokens.every(e=>e.type===`DATE_PART`&&e.value===`a`))throw Error(`Invalid date format`);return{type:`date`,tokens:To(t.tokens.map(e=>e.type===`THOUSANDS_SEPARATOR`||e.type===`DECIMAL_POINT`?{type:`CHAR`,value:e.value}:e))}}}function wo(e){return e&&xo(e)?{type:`text`,tokens:e}:void 0}function To(e){let t=e.filter(e=>e.type===`DATE_PART`);for(let e=0;e<t.length;e++)!t[e].value.startsWith(`m`)||t[e].value.length>2||(t[e-1]?.value.startsWith(`h`)||t[e+1]?.value.startsWith(`s`))&&(t[e].value=t[e].value.replaceAll(`m`,`M`));return e}function Eo(e){return[Do(e.positive),Do(e.negative),Do(e.zero),Do(e.text)].filter(S).join(`;`)}function Do(e){if(!e)return;let t=``,n=e.type===`number`?Oo(e):e.tokens;for(let e of n)switch(e.type){case`STRING`:t+=`[$${e.value}]`;break;case`CHAR`:t+=ko(e.value)?`\\${e.value}`:e.value;break;case`REPEATED_CHAR`:t+=`*`+e.value;break;case`DATE_PART`:t+=e.value===`MM`?`mm`:e.value;break;default:t+=e.value}return t}function Oo(e){let t=[...e.integerPart];return e.decimalPart&&(t.push({type:`DECIMAL_POINT`,value:`.`}),t.push(...e.decimalPart)),t}function ko(e){return!ao.has(e)}let Ao=`REPEATED_CHAR_PLACEHOLDER_`,jo={0:E(`January`),1:E(`February`),2:E(`March`),3:E(`April`),4:E(`May`),5:E(`June`),6:E(`July`),7:E(`August`),8:E(`September`),9:E(`October`),10:E(`November`),11:E(`December`)},Mo={0:E(`Sunday`),1:E(`Monday`),2:E(`Tuesday`),3:E(`Wednesday`),4:E(`Thursday`),5:E(`Friday`),6:E(`Saturday`)};function B(e,{format:t,locale:n,formatWidth:r}){switch(typeof e==`boolean`&&(e=e?`TRUE`:`FALSE`),typeof e){case`string`:{if(e.includes(`\\"`)&&(e=e.replaceAll(/\\"/g,`"`)),!t)return e;let n=_o(t),i=n.text||n.positive;return!i||i.type!==`text`?e:No(e,i,r)}case`number`:t||=Yo(e);let i=_o(t);if(i.positive.type===`text`)return No(e.toString(),i.positive,r);let a=i.positive;if(e<0&&i.negative?(a=i.negative,e=-e):e===0&&i.zero&&(a=i.zero),a.type===`date`)return Po(Ko(e,a),r);let o=e<0,s=Po(Fo(Math.abs(e),a,n),r);return o?`-`+s:s;case`object`:return``}}function No(e,t,n){let r=``;for(let n of t.tokens)switch(n.type){case`TEXT_PLACEHOLDER`:r+=e;break;case`CHAR`:case`STRING`:r+=n.value;break;case`REPEATED_CHAR`:r+=Ao+n.value;break}return Po(r,n)}function Po(e,t){let n=e.indexOf(Ao);if(n===-1)return e;let r=e.slice(0,n),i=e.slice(n+26+1),a=e[n+26];function o(){if(!t)return{timesToRepeat:0,padding:``};let e=t.measureText(r+i),n=t.measureText(a),o=t.availableWidth-e;if(o<=0)return{timesToRepeat:0,padding:``};let s=Math.floor(o/n),c=o-s*n,l=t.measureText(` `);return{timesToRepeat:s,padding:` `.repeat(Math.floor(c/l))}}let{timesToRepeat:s,padding:c}=o();return r+a.repeat(s)+c+i}function Fo(e,t,n){if(e===1/0)return`∞`+(t.percentSymbols?`%`:``);let r=t.percentSymbols*2-t.magnitude*3;e*=10**r;let i=0;t.decimalPart!==void 0&&(i=t.decimalPart.filter(e=>e.type===`DIGIT`).length);let{integerDigits:a,decimalDigits:o}=zo(Math.abs(e),i),s=Io(a,t,t.thousandsSeparator?n.thousandsSeparator:void 0);return t.decimalPart!==void 0&&(s+=n.decimalSeparator+Lo(o||``,t)),s}function Io(e,t,n){let r=t.integerPart;r.some(e=>e.type===`DIGIT`)||(r=[...r,{type:`DIGIT`,value:`#`}]),e===`0`&&(e=``);let i=``,a=r.findIndex(e=>e.type===`DIGIT`),o=e.length-1;function s(t,r){if(r===`0`&&(t||=`0`),!t)return;let a=e.length-1-o;i=n&&a>0&&a%3==0?t+n+i:t+i}for(let t=r.length-1;t>=0;t--){let n=r[t];switch(n.type){case`DIGIT`:let r=e[o];if(s(r,n.value),o--,a===t)for(;o>=0;)s(e[o],`0`),o--;break;case`THOUSANDS_SEPARATOR`:break;case`REPEATED_CHAR`:i=Ao+n.value+i;break;default:i=n.value+i;break}}return i}function Lo(e,t){if(!t.decimalPart)return``;let n=``,r=0;for(let i of t.decimalPart)switch(i.type){case`DIGIT`:let t=i.value===`#`?e[r]||``:e[r]||`0`;n+=t,r++;break;case`THOUSANDS_SEPARATOR`:break;case`REPEATED_CHAR`:n+=Ao+i.value;break;default:n+=i.value;break}return n}let Ro=[];function zo(e,t=20){let n=e.toString();if(n.includes(`e`))return Uo(e,t);if(Number.isInteger(e))return{integerDigits:n,decimalDigits:void 0};let r=n.indexOf(`.`),i=n.substring(0,r),a=n.substring(r+1);if(t===0)return Number(a[0])>=5&&(i=(Number(i)+1).toString()),{integerDigits:i,decimalDigits:void 0};if(a.length>t){let{integerDigits:e,decimalDigits:n}=Ho(a,t);a=n,e!==`0`&&(i=(Number(i)+Number(e)).toString())}return{integerDigits:i,decimalDigits:Bo(a||``)}}function Bo(e){let t=e.length-1;for(;t>=0&&e[t]===`0`;)t--;return e.slice(0,t+1)||void 0}let Vo=/^0+/;function Ho(e,t){let n=`0`,r=e,i=e.slice(0,t);if(Number(e[t])<5)return{integerDigits:n,decimalDigits:i};let a=i.match(Vo)?.[0]||``,o=(Number(i)+1).toString(),s=i.slice(a.length),c=o.length>s.length;return c&&!a?(n=`1`,r=void 0):r=c?a.slice(0,-1)+o:a+o,{integerDigits:n,decimalDigits:r}}function Uo(e,t=20){let n=Ro[t];n||(n=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:t,useGrouping:!1}),Ro[t]=n);let[r,i]=n.format(e).split(`.`);return{integerDigits:r,decimalDigits:i}}function Wo(e,t){let{integerDigits:n,decimalDigits:r}=zo(e,20);return r?n+t+r:n}let Go=Rt(function(e){if(!e)return!1;try{return _o(e).positive.type===`date`}catch{return!1}});function Ko(e,t){let n=ci(e);if(isNaN(n.getTime()))return e.toString();let r=t.tokens.some(e=>e.type===`DATE_PART`&&e.value===`a`),i=``;for(let e of t.tokens)switch(e.type){case`DATE_PART`:i+=qo(n,e.value,r);break;case`REPEATED_CHAR`:i+=Ao+e.value;break;default:i+=e.value;break}return i}function qo(e,t,n){switch(t){case`d`:return e.getDate();case`dd`:return e.getDate().toString().padStart(2,`0`);case`ddd`:return Mo[e.getDay()].slice(0,3);case`dddd`:return Mo[e.getDay()].toString();case`m`:return e.getMonth()+1;case`mm`:return String(e.getMonth()+1).padStart(2,`0`);case`mmm`:return jo[e.getMonth()].slice(0,3);case`mmmm`:return jo[e.getMonth()].toString();case`mmmmm`:return jo[e.getMonth()].slice(0,1);case`qq`:return E(`Q%(quarter)s`,{quarter:e.getQuarter()}).toString();case`qqqq`:return E(`Quarter %(quarter)s`,{quarter:e.getQuarter()}).toString();case`yy`:let r=String(e.getFullYear()).replace(`-`,``).padStart(2,`0`);return r.slice(r.length-2);case`yyyy`:return String(e.getFullYear()).replace(`-`,``).padStart(4,`0`);case`hhhh`:return Math.floor((e.getTime()-Lr.getTime())/(3600*1e3)).toString();case`hh`:let i=e.getHours();return n&&(i=i===0?12:i>12?i-12:i),i.toString().padStart(2,`0`);case`MM`:return e.getMinutes().toString().padStart(2,`0`);case`ss`:return e.getSeconds().toString().padStart(2,`0`);case`a`:return e.getHours()>=12?`PM`:`AM`;default:throw Error(`invalid date format token: ${t}`)}}let Jo=Rt(function(e){return RegExp(`[0-9]+${nt(e.decimalSeparator)}[0-9]`)});function Yo(e){let{integerDigits:t,decimalDigits:n}=zo(e);if(!n)return`0`;let r=t.replace(`-`,``).length;if(r+2>11)return`0`;let i=11-r-1;return{decimalDigits:n}=zo(e,Math.min(i,n.length)),n?`0.`+`0`.repeat(n.length):`0`}function Xo(e,t){if(Xr(e,t))return Qr(e,t).format}function Zo(e){let t=e.includes(`.`)?`0.00`:`0`,n=e.match(/[\$€]/);if(n){let r=e.match(/[\d]/),i=`[$`+n.values().next().value+`]`;return r.index<n.index?`#,##`+t+i:i+`#,##`+t}if(e.includes(`%`))return t+`%`}function Qo(e){let t=e.decimalPlaces??2,n=e.position??`before`,r=e.code??``,i=e.symbol??``,a=`#,##0`+(t?`.`+`0`.repeat(t):``),o=`${r} ${i}`.trim();return n===`after`&&r&&(o=` `+o),ts(o,n,a)}function $o(e){let t=e.decimalPlaces??2,n=e.position??`before`,r=e.code??``,i=e.symbol??``,a=`#,##0`+(t?`.`+`0`.repeat(t):``),o=`${r} ${i}`.trim();return n===`after`&&r&&(o=` `+o),[es(o,n,` ${a} `),es(o,n,`(${a})`),es(o,n,` - `)].join(`;`)}function es(e,t,n){let r=`[$${e}]`;return t===`before`?r+`* `+n:n+`* `+r}function ts(e,t,n){let r=`[$${e}]`;return t===`before`?r+n:n+r}function ns(e){let t=_o(e);return Eo({positive:rs(t.positive),negative:t.negative?rs(t.negative):void 0,zero:t.zero?rs(t.zero):void 0,text:t.text})}function rs(e){if(e.type!==`number`||!e.decimalPart)return e;let t=e.decimalPart.filter(e=>e.type!==`DIGIT`);return{...e,decimalPart:void 0,integerPart:[...e.integerPart,...t]}}function is({value:e,format:t},n){return B(e,{format:as({value:e,format:t},void 0,n),locale:n})}function as(e,t,n){let r=0;try{r=Math.abs(F(e?.value,n))}catch{return``}let i=e?.format;if(t!==void 0)switch(t?.value){case`k`:return os(i,1,`k`,n);case`m`:return os(i,2,`m`,n);case`b`:return os(i,3,`b`,n);default:throw new M(E(`The formatting unit should be 'k', 'm' or 'b'.`))}return r<1e5?os(i,0,``,n):r<1e8?os(i,1,`k`,n):r<1e11?os(i,2,`m`,n):os(i,3,`b`,n)}function os(e,t,n,r){let i=_o(e||`#,##0`);return Eo({positive:ss(i.positive,t,n),negative:i.negative?ss(i.negative,t,n):void 0,zero:i.zero?ss(i.zero,t,n):void 0,text:i.text})}function ss(e,t,n){if(e.type!==`number`)return e;let r=rs(e),i={type:`STRING`,value:n},a=[...r.integerPart],o=a.findLastIndex(e=>e.type===`DIGIT`);if(o===-1)throw Error(`Cannot create a large number format from a format with no digit.`);for(;a[o+1]?.type===`THOUSANDS_SEPARATOR`;)a=zt(a,[o+1]);let s=a[o+1];a=s?.type===`STRING`&&[`m`,`k`,`b`].includes(s.value)?Vt(a,i,o+1):Bt(a,[i],o+1),t>0&&(a=Bt(a,Array(t).fill({type:`THOUSANDS_SEPARATOR`,value:`,`}),o+1));let c=r.percentSymbols-a.filter(e=>e.type===`PERCENT`).length;return a.push(...Array(c).fill({type:`PERCENT`,value:`%`})),{...r,integerPart:a,magnitude:t}}function cs(e,t){let n=_o(e);return Eo(_o(Eo({positive:ls(n.positive,t),negative:n.negative?ls(n.negative,t):void 0,zero:n.zero?ls(n.zero,t):void 0,text:n.text})))}function ls(e,t){return e.type===`number`?t>0?ds(e,t):us(e,Math.abs(t)):e}function us(e,t){let n=e.decimalPart;if(!n)return e;let r=[],i=0;for(let e=n.length-1;e>=0&&!(i>=Math.abs(t));e--)n[e].type===`DIGIT`&&(i++,r.push(e));return n=zt(n,r),n.some(e=>e.type===`DIGIT`)?{...e,decimalPart:n}:{...e,decimalPart:void 0,integerPart:[...e.integerPart,...n]}}function ds(e,t){let n=e.integerPart,r=e.decimalPart;if(!r){let e=n.findLastIndex(e=>e.type===`DIGIT`);r=n.slice(e+1),n=n.slice(0,e+1)}let i=x(0,t).map(()=>({type:`DIGIT`,value:`0`})),a=r.findLastIndex(e=>e.type===`DIGIT`);return r=a===-1?[...i,...r]:Bt(r,i,a+1),{...e,decimalPart:r,integerPart:n}}function fs(e){let t=_o(e);for(let e of[t.positive,t.negative,t.zero])if(e&&e.type===`date`&&e.tokens.some(e=>e.type===`DATE_PART`&&e.value.includes(`q`)))return!1;return!0}function ps(e){if(!e)return!1;try{return _o(e).positive.type===`text`}catch{return!1}}function ms(e,t){return gs({value:ps(t.format)&&e.parsedValue!==null?e.content:e.parsedValue,format:t.format},t.locale)}function hs(e,t){if(e.startsWith(`=`))throw Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);if(e===``)return null;if(Oi(e,k))return Ai(e,k);let n=Qr(e,t);return n?n.value:ut(e)?e.toUpperCase()===`TRUE`:e}function gs(e,t=k,n){let r=no(e.value);if(!r)return _s(e,t,n);let i=hs(r.label,t);return{..._s({value:i,format:e.format||(typeof i==`number`?Xo(r.label,t)||Zo(r.label):void 0)},t,n),link:r}}function _s(e,t,n){let{value:r,format:i,message:a}=e;i=n?.format||i;let o=B(r,{format:i,locale:t});return P(r)?Cs(r,a):r===null?bs(i):ps(i)?vs(I(r),i,o):typeof r==`number`?Go(i||``)?xs(r,i,o):ys(r,i,o):typeof r==`boolean`?Ss(r,i,o):vs(r,i,o)}function vs(e,t,n){return{value:e,format:t,formattedValue:n,type:`text`,isAutoSummable:!0,defaultAlign:`left`}}function ys(e,t,n){return{value:e||0,format:t,formattedValue:n,type:`number`,isAutoSummable:!0,defaultAlign:`right`}}let bs=Rt(function(e){return{value:null,format:e,formattedValue:``,type:`empty`,isAutoSummable:!0,defaultAlign:`left`}});function xs(e,t,n){return{value:e,format:t,formattedValue:n,type:`number`,isAutoSummable:!1,defaultAlign:`right`}}function Ss(e,t,n){return{value:e,format:t,formattedValue:n,type:`boolean`,isAutoSummable:!1,defaultAlign:`center`}}function Cs(e,t){return{value:e,formattedValue:e,message:t,type:`error`,isAutoSummable:!1,defaultAlign:`center`}}function ws(e){let t=O.now();switch(e){case`today`:return Math.floor(ui(t));case`yesterday`:return t.setDate(t.getDate()-1),Math.floor(ui(t));case`tomorrow`:return t.setDate(t.getDate()+1),Math.floor(ui(t));case`lastWeek`:return t.setDate(t.getDate()-6),Math.floor(ui(t));case`lastMonth`:{let e=t.getMonth()===0?11:t.getMonth()-1,n=new O(t.getFullYear(),e,1);return t.getDate()>di(n)?t.setDate(1):(t.setDate(t.getDate()+1),t.setMonth(t.getMonth()-1)),Math.floor(ui(t))}case`lastYear`:return t.getMonth()===1&&t.getDate()===29?(t.setDate(28),t.setFullYear(t.getFullYear()-1)):(t.setDate(t.getDate()+1),t.setFullYear(t.getFullYear()-1)),Math.floor(ui(t))}}function Ts(e,t){return`dateValue`in e&&e.dateValue!==`exactDate`?[ws(e.dateValue)]:e.values.map(e=>Yr(e,t))}function Es(e,t){return e.values.map(e=>pa(e,t))}function Ds(e,t){return e.map(e=>{if(e.startsWith(`=`))return e;let n=hs(e,t);return typeof n==`number`?B(n,{format:t.dateFormat,locale:t}):``})}function Os(e){return 20+120*Math.exp(-.035*(e-1))}let ks=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,`i`),As=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,`i`),js=new RegExp(/^\$?([A-Z]{1,3})+$/,`i`),Ms=new RegExp(/^\$?([0-9]{1,7})+$/,`i`),Ns=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,`i`),Ps=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,`i`),Fs=RegExp(`^\\s*('.+'!|[^']+!)?(`+[ks.source,`(\\$?[A-Z]{1,3})?\\$?[0-9]{1,7}\\s*:\\s*(\\$?[A-Z]{1,3})?\\$?[0-9]{1,7}\\s*`,`\\$?[A-Z]{1,3}(\\$?[0-9]{1,7})?\\s*:\\s*\\$?[A-Z]{1,3}(\\$?[0-9]{1,7})?\\s*`].join(`|`)+`)$`,`i`);function Is(e){return Ns.test(e)}function Ls(e){return Ps.test(e)}function Rs(e){return js.test(e)}function zs(e){return Ms.test(e)}function Bs(e){return As.test(e)}function Vs(e){if(!e.includes(`!`))return{xc:e};let t=e.split(`!`),n=t.pop();return{sheetName:it(t.join(`!`))||void 0,xc:n}}function Hs(e,t){return e===void 0?t:`${ot(e)}!${t}`}var Us=class e{getSheetSize;_zone;parts;invalidXc;prefixSheet=!1;sheetId;invalidSheetName;constructor(e,t){this.getSheetSize=t,this._zone=e.zone,this.prefixSheet=e.prefixSheet,this.invalidXc=e.invalidXc,this.sheetId=e.sheetId,this.invalidSheetName=e.invalidSheetName;let n=[...e.parts];e.parts.length===1&&Er(this.zone)>1?n.push({...e.parts[0]}):e.parts.length===2&&Er(this.zone)===1&&n.pop(),this.parts=n}static fromRange(t,n){return t instanceof e?t:new e(t,n.getSheetSize)}get unboundedZone(){return this._zone}get zone(){let{left:e,top:t,bottom:n,right:r}=this._zone;if(r!==void 0&&n!==void 0)return this._zone;if(n===void 0&&r!==void 0)return{right:r,top:t,left:e,bottom:this.getSheetSize(this.sheetId).numberOfRows-1};if(r===void 0&&n!==void 0)return{bottom:n,left:e,top:t,right:this.getSheetSize(this.sheetId).numberOfCols-1};throw Error(E(`Bad zone format`))}static getRangeParts(e,t){let n=e.split(`:`).map(e=>{let t=Ls(e);return{colFixed:t?!1:e.startsWith(`$`),rowFixed:t?e.startsWith(`$`):e.includes(`$`,1)}}),r=t.bottom===void 0,i=t.right===void 0;return r&&(n[0].rowFixed=n[0].rowFixed||n[1].rowFixed,n[1].rowFixed=n[0].rowFixed||n[1].rowFixed),i&&(n[0].colFixed=n[0].colFixed||n[1].colFixed,n[1].colFixed=n[0].colFixed||n[1].colFixed),n}get isFullCol(){return this._zone.bottom===void 0}get isFullRow(){return this._zone.right===void 0}get rangeData(){return{_zone:this._zone,_sheetId:this.sheetId}}orderZone(){if(er(this._zone))return this;let e={...this._zone},t=this.parts;if(e.right!==void 0&&e.right<e.left){let n=e.right;e.right=e.left,e.left=n,t=[{colFixed:t[1]?.colFixed||!1,rowFixed:t[0]?.rowFixed||!1},{colFixed:t[0]?.colFixed||!1,rowFixed:t[1]?.rowFixed||!1}]}if(e.bottom!==void 0&&e.bottom<e.top){let n=e.bottom;e.bottom=e.top,e.top=n,t=[{colFixed:t[0]?.colFixed||!1,rowFixed:t[1]?.rowFixed||!1},{colFixed:t[1]?.colFixed||!1,rowFixed:t[0]?.rowFixed||!1}]}return this.clone({zone:e,parts:t})}clone(t){return new e({zone:t?.zone?t.zone:{...this._zone},sheetId:t?.sheetId?t.sheetId:this.sheetId,invalidSheetName:t&&`invalidSheetName`in t?t.invalidSheetName:this.invalidSheetName,invalidXc:t&&`invalidXc`in t?t.invalidXc:this.invalidXc,parts:t?.parts?t.parts:this.parts.map(e=>({rowFixed:e.rowFixed,colFixed:e.colFixed})),prefixSheet:t?.prefixSheet===void 0?this.prefixSheet:t.prefixSheet},this.getSheetSize)}};function Ws(e,t,n){let r=n.sheetId===e?t:n.sheetId;return n.clone({sheetId:r})}function Gs(e,t,n){if(!n)return;let r=e.getRangeFromSheetXC(t,n);return r.invalidSheetName||r.invalidXc?void 0:r}function Ks(e,t){let n=[];for(let r of t){let t=r.dataRange;if(!e.isRangeValid(t)){n.push(r);continue}let{sheetName:i}=Vs(t),a=i?`${i}!`:``,o=Zn(t);if(o.bottom!==o.top&&o.left!==o.right)if(o.right)for(let e=o.left;e<=o.right;++e){let t=e===o.left?r:{yAxisId:r.yAxisId};n.push({...t,dataRange:`${a}${tr({left:e,right:e,top:o.top,bottom:o.bottom})}`})}else for(let e=o.top;e<=o.bottom;++e){let t=e===o.top?r:{yAxisId:r.yAxisId};n.push({...t,dataRange:`${a}${tr({left:o.left,right:o.right,top:e,bottom:e})}`})}else n.push(r)}return n}function qs(e){let t=[];for(let n of e)for(let e of _r(n.zone))t.push({...e,sheetId:n.sheetId});return t}function Js(e,t){e=e.toLocaleLowerCase(),t=t.toLocaleLowerCase();let n=0,r=0,i=t.length,a=0;for(let o=0;o<i;o++)t[o]===e[a]?(a++,r+=100+r-o/200):r=0,n+=r;return a===e.length?n:0}function Ys(e,t,n){let r=[];return t.forEach(t=>{let i=Js(e,n(t));i>0&&r.push({score:i,elem:t})}),r.sort((e,t)=>t.score-e.score),r.map(e=>e.elem)}function Xs(e){let t=[];for(let n=0;n<e;n++)t.push({cells:{}});return t}function Zs(e,t,n){return n.map(n=>n>=e?n+t:n)}function Qs(e,t){return e=[...e].sort((e,t)=>t-e),t.map(t=>{for(let n of e)if(t>n)t--;else if(t===n)return;return t}).filter(S)}function $s(e,t=`Sheet`){let n=1,r=`${t}${n}`;for(;e.includes(r);)r=`${t}${n}`,n++;return r}function ec(e,t){let n=1,r=E(`Copy of %s`,e),i=r.toString();for(;t.includes(i);)i=`${r} (${n})`,n++;return i}function tc(e,t){return e===void 0||t===void 0?!1:it(e.trim().toUpperCase())===it(t.trim().toUpperCase())}function nc(e,t=1){return t*(e+4)-4}function rc(e,t,n,r){if(!t||!t.isFormula&&!t.content)return 23;let i=``;try{if(!t.isFormula){let e={format:t.format,locale:n};i=B(hs(t.content,n),e)}}catch{i=j.GenericError}return ic(e,i,t.style,r)}function ic(e,t,n,r){let i=gc(e,t,n,n?.wrapping===`wrap`?r-8:void 0).length;return nc(mc(n),i)+6}function ac(e,t=!1,n=!1){return`${n?`italic`:``} ${t?`bold`:``} ${e}px ${ze}`}let oc={};function sc(e,t,n,r=`pt`){let i=pc(n,r);e.save(),e.font=i;let a=cc(e,t);return e.restore(),a}function cc(e,t){let n=e.font;if(oc[n]||(oc[n]={}),oc[n][t]===void 0){let r=e.measureText(t).width;oc[n][t]=r}return oc[n][t]}let lc={};function uc(e,t,n,r=`pt`){let i=pc(n,r);e.save(),e.font=i;let a=dc(e,t);return e.restore(),a}function dc(e,t){let n=e.font;if(lc[n]||(lc[n]={}),lc[n][t]===void 0){let r=e.measureText(t),i=r.width,a=r.fontBoundingBoxAscent+r.fontBoundingBoxDescent;lc[n][t]={width:i,height:a}}return lc[n][t]}function fc(e){return Math.round(e*96/72)}function pc(e,t=`pt`){return`${e.italic?`italic `:``}${e.bold?`bold`:`400`} ${(t===`pt`?mc(e):e.fontSize)??Re}px ${ze}`}function mc(e){return fc(e?.fontSize||Re)}function hc(e,t,n,r){if(sc(e,t,r)<=n)return[t];let i=[],a=``;for(let o of t)sc(e,a+o,r)>n?(i.push(a),a=o):a+=o;return i.push(a),i}function gc(e,t,n,r){n||={},pt(t)&&(t=gt(t).label);let i=[],a=t.includes(`
4
+ `)}function Ut(e,t,n){return t>n?Ut(e,n,t):e>=t&&e<=n}function Wt(e,t){let n=nt(e),r=t.matchCase?``:`i`;return t.exactMatch&&(n=`^${n}$`),RegExp(n,r)}function Gt(e){let t=e.length;if(t<1e5)return Math.max(...e);let n=-1/0;for(;t--;)n=e[t]>n?e[t]:n;return n}function Kt(e){let t=e.length;if(t<1e5)return Math.min(...e);let n=1/0;for(;t--;)n=e[t]<n?e[t]:n;return n}var qt=class{text;currentIndex=0;current;constructor(e){this.text=e,this.current=e[0]}shift(){let e=this.current,t=this.text[++this.currentIndex];return this.current=t,e}advanceBy(e){this.currentIndex+=e,this.current=this.text[this.currentIndex]}isOver(){return this.currentIndex>=this.text.length}remaining(){return this.text.substring(this.currentIndex)}currentStartsWith(e){if(this.current!==e[0])return!1;for(let t=1;t<e.length;t++)if(this.text[this.currentIndex+t]!==e[t])return!1;return!0}};function Jt(e,t=e=>e){let n=new Set;return e.filter(e=>{let r=t(e);return n.has(r)?!1:(n.add(r),!0)})}function Yt(e){let t={};for(let n in e)for(let r in e[n])t[r]||(t[r]={}),t[r][n]=e[n][r];return t}let Xt=/rgba?\(|\s+|\)/gi,Zt=/^#([A-F\d]{2}){3,4}$/,Qt=[`#eb6d00`,`#0074d9`,`#ad8e00`,`#169ed4`,`#b10dc9`,`#00a82d`,`#00a3a3`,`#f012be`,`#3d9970`,`#111111`,`#62A300`,`#ff4136`,`#949494`,`#85144b`,`#001f3f`];function $t(e){return en(e.toString(16).padStart(6,`0`))}function en(e){let t=e;if(e.startsWith(`rgb`)?t=sn(e):(t=e.replace(`#`,``).toUpperCase(),(t.length===3||t.length===4)&&(t=t.split(``).reduce((e,t)=>e+t+t,``)),t=`#${t}`),!Zt.test(t))throw Error(`invalid color input: ${e}`);return t}function tn(e){try{return en(e),!0}catch{return!1}}function nn(e){try{return fn(e),!0}catch{return!1}}let rn=e=>e>=0&&e<=255;function an(e,t,n,r=1){if(!rn(e)||!rn(t)||!rn(n)||r<0||r>1)throw Error(`Invalid RGBA values ${[e,t,n,r]}`);return{a:r,b:n,g:t,r:e}}function on(e){let{r:t,g:n,b:r}=ln(e);t/=255,n/=255,r/=255;let i=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4,a=i(t),o=i(n),s=i(r);return .2126*a+.7152*o+.0722*s}function sn(e){let t=e.replace(Xt,``).split(`,`),n=255;if(t.length!==3&&t.length!==4)throw Error(`invalid color`);if(t.length===4){let e=parseFloat(t.pop()||`1`);if(isNaN(e))throw Error(`invalid alpha value`);n=Math.round(e*255)}let r=t.map(e=>parseInt(e,10));return n!==255&&r.push(n),`#`+Tt(r.map(e=>e.toString(16).padStart(2,`0`))).toUpperCase()}function cn(e){let t=e.r.toString(16),n=e.g.toString(16),r=e.b.toString(16),i=Math.round(e.a*255).toString(16);return t.length===1&&(t=`0`+t),n.length===1&&(n=`0`+n),r.length===1&&(r=`0`+r),i.length===1&&(i=`0`+i),i===`ff`&&(i=``),(`#`+t+n+r+i).toUpperCase()}function ln(e){e=en(e);let t,n,r,i;if(e.length===7)t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16),i=255;else if(e.length===9)t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16),i=parseInt(e[7]+e[8],16);else throw Error(`Invalid color`);return i=+(i/255).toFixed(3),{a:i,r:t,g:n,b:r}}function un(e){e={...e},e.s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,n=t*(1-Math.abs(e.h/60%2-1)),r=e.l-t/2,i=0,a=0,o=0;return 0<=e.h&&e.h<60?(i=t,a=n,o=0):60<=e.h&&e.h<120?(i=n,a=t,o=0):120<=e.h&&e.h<180?(i=0,a=t,o=n):180<=e.h&&e.h<240?(i=0,a=n,o=t):240<=e.h&&e.h<300?(i=n,a=0,o=t):300<=e.h&&e.h<360&&(i=t,a=0,o=n),i=Math.round((i+r)*255),a=Math.round((a+r)*255),o=Math.round((o+r)*255),{a:e.a,r:i,g:a,b:o}}function dn(e){let t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=a-i,s=0,c=0,l=0;return s=o===0?0:a===t?(n-r)/o%6:a===n?(r-t)/o+2:(t-n)/o+4,s=Math.round(s*60),s<0&&(s+=360),l=(a+i)/2,c=o===0?0:o/(1-Math.abs(2*l-1)),c=+(c*100).toFixed(1),l=+(l*100).toFixed(1),{a:e.a,h:s,s:c,l}}function fn(e){return cn(un(e))}function pn(e){return dn(ln(e))}function mn(e,t,n=0){if(!(tn(e)&&tn(t)))return!1;let r=ln(e),i=ln(t);return r.a===i.a?Math.sqrt(((r.r-i.r)/255)**2+((r.g-i.g)/255)**2+((r.b-i.b)/255)**2)<=n:!1}function hn(e,t){return t===1?en(e).slice(0,7):cn({...ln(e),a:t})}function gn(e,t){let n=pn(e);return t===1?`#fff`:(n.l=t*(100-n.l)+n.l,fn(n))}function _n(e,t){let n=pn(e);return t===1?`#000`:(n.l-=t*n.l,fn(n))}let vn=[`#4EA7F2`,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#FFD86D`],yn=[`#4EA7F2`,`#3188E6`,`#43C5B1`,`#00A78D`,`#EA6175`,`#CE4257`,`#F4A261`,`#F48935`,`#8481DD`,`#5752D1`,`#FFD86D`,`#FFBC2C`],bn=[`#4EA7F2`,`#3188E6`,`#056BD9`,`#A76DBC`,`#7F4295`,`#6D2387`,`#EA6175`,`#CE4257`,`#982738`,`#43C5B1`,`#00A78D`,`#0E8270`,`#F4A261`,`#F48935`,`#BE5D10`,`#8481DD`,`#5752D1`,`#3A3580`,`#A4A8B6`,`#7E8290`,`#545B70`,`#FFD86D`,`#FFBC2C`,`#C08A16`],xn=`#4EA7F2.#3188E6.#056BD9.#155193.#A76DBC.#7F4295.#6D2387.#4F1565.#EA6175.#CE4257.#982738.#791B29.#43C5B1.#00A78D.#0E8270.#105F53.#F4A261.#F48935.#BE5D10.#7D380D.#8481DD.#5752D1.#3A3580.#26235F.#A4A8B6.#7E8290.#545B70.#3F4250.#FFD86D.#FFBC2C.#C08A16.#936A12`.split(`.`);function Sn(e,t){return t[e%t.length]}function Cn(e){return e<=6?vn:e<=12?yn:e<=24?bn:xn}var wn=class{preferredColors;currentColorIndex=0;palette;constructor(e,t=[]){this.preferredColors=t,this.palette=Cn(e).filter(e=>!t.includes(e))}next(){return this.preferredColors?.[this.currentColorIndex]?this.preferredColors[this.currentColorIndex++]:Sn(this.currentColorIndex++,this.palette)}};function Tn(e){if(e<0)throw Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Tn(Math.floor(e/26)-1)+Tn(e%26)}function En(e){let t=0,n=e.length;for(let r=0;r<n;r++){let n=Dn(e[r]);t=t*26+n}return t-1}function Dn(e){let t=e.charCodeAt(0);return t>=65&&t<=90?t-64:t-96}function On(e){return e>=`A`&&e<=`Z`||e>=`a`&&e<=`z`}function kn(e){return e>=`0`&&e<=`9`}let An=En(`ZZZ`);function jn(e){for(;e.current===` `;)e.advanceBy(1)}function Mn(e){if(e.current===`$`&&e.advanceBy(1),!e.current||!On(e.current))return-1;let t=0;for(;e.current&&On(e.current);)t=t*26+Dn(e.shift());return t}function Nn(e){if(e.current===`$`&&e.advanceBy(1),!e.current||!kn(e.current))return-1;let t=0;for(;e.current&&kn(e.current);)t=t*10+Number(e.shift());return t}function Pn(e){let t=new qt(e);jn(t);let n=Mn(t);if(n===-1||!t.current)throw Error(`Invalid cell description: ${e}`);let r=Nn(t);jn(t);let i=n-1,a=r-1;if(!t.isOver()||i>An||a>9999998)throw Error(`Invalid cell description: ${e}`);return{col:i,row:a}}function w(e,t,n={colFixed:!1,rowFixed:!1}){return(n.colFixed?`$`:``)+Tn(e)+(n.rowFixed?`$`:``)+String(t+1)}function T(e,t=[]){if(e.length<=1&&t.length===0)return e;let n=[0],r=new Map([[0,[]]]);return Fn(n,r,e,!1),Fn(n,r,t,!0),zn(n,r)}function Fn(e,t,n,r=!1){for(let i of n){let n=i.left,a=i.right===void 0?void 0:i.right+1,o=In(e,t,n,!0,0),s=In(e,t,a,!1,o);for(let n=o;n<=s;n++)Ln(t.get(e[n]),i,r);Rn(e,t,o,s)}}function In(e,t,n,r,i){if(n===void 0)return e.length-1;let a=Bn(e,n,i);return n===e[a]?r?a:a-1:(e.splice(a+1,0,n),t.set(n,[...t.get(e[a])]),r?a+1:a)}function Ln(e,t,n=!1){let r=t.top,i=t.bottom===void 0?void 0:t.bottom+1,a=[],o=Bn(e,r,0,!1);if((o%2!=0&&!n||o%2==0&&n)&&a.push(r),i===void 0){e.splice(o+1),e.push(...a);return}let s=Vn(e,i,0,!1);(s%2==0&&!n||s%2!=0&&n)&&a.push(i),e.splice(o+1,s-o-1,...a)}function Rn(e,t,n,r){let i=n-1==-1?0:n-1,a=r===e.length-1?r:r+1;for(let n=a;n>i;n--)kt(t.get(e[n]),t.get(e[n-1]))&&(t.delete(e[n]),e.splice(n,1))}function zn(e,t){let n=[],r=[];for(let i=0;i<e.length;i++){let a=e[i],o=t.get(a);if(!o||o.length===0){n.push(...r),r=[];continue}let s=e[i+1];s!==void 0&&s--;let c=[];for(let e=0;e<o.length;e+=2){let t=o[e],n=o[e+1];n!==void 0&&n--;let i={top:t,left:a,bottom:n,right:s,hasHeader:n===void 0&&t!==0||s===void 0&&a!==0},l=!1;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.top===i.top&&t.bottom===i.bottom){t.right=i.right,r.splice(e,1),c.push(t),l=!0;break}}l||c.push(i)}n.push(...r),r=c}return n.push(...r),n}function Bn(e,t,n=0,r=!0){let i=e.length-1,a=-1;for(;n<=i;){let o=Math.floor((n+i)/2);if(e[o]===t&&r)return o;e[o]<t?(a=o,n=o+1):i=o-1}return a}function Vn(e,t,n=0,r=!0){let i=e.length-1,a=e.length;for(;n<=i;){let o=Math.floor((n+i)/2);if(e[o]===t&&r)return o;e[o]>t?(a=o,i=o-1):n=o+1}return a}let Hn=e=>e,Un=()=>!1,Wn=Hn,Gn=Un;function Kn(e,...t){if(t.length===1&&typeof t[0]==`object`&&!(t[0]instanceof String)){let n=t[0];e=e.replace(/\%\(([^\)]+)\)s/g,(e,t)=>n[t])}else t.length>0&&(e=e.replace(/\%s/g,()=>t.shift()));return e}function qn(e,t=()=>!0){Wn=e,Gn=t}function Jn(){Wn===Hn&&Gn===Un&&(Gn=()=>!0)}let E=function(e,...t){return Gn()?Kn(Wn(e),...t):new Yn(e,t)};var Yn=class extends String{values;constructor(e,t){super(e),this.values=t}valueOf(){let e=super.valueOf();return Gn()?Kn(Wn(e),...this.values):Kn(e,...this.values)}toString(){return this.valueOf()}};function Xn(e){let t=new qt(e);jn(t);let n=e.indexOf(`!`);n!==-1&&t.advanceBy(n+1);let r=Mn(t),i=Nn(t),a,o,s,c,l=!1,u=!1,d=!1;if(i===-1?(s=c=r-1,a=o=0,l=!0):r===-1?(a=o=i-1,s=c=0,u=!0):(s=c=r-1,a=o=i-1,d=!0),jn(t),t.current===`:`){t.advanceBy(1),jn(t);let e=Mn(t),n=Nn(t);n===-1?(c=e-1,l=!0):e===-1?(o=n-1,u=!0):(c=e-1,o=n-1,a=l?o:a,s=u?c:s,d=!0)}let f={top:a,left:s,bottom:l?void 0:o,right:u?void 0:c};return d&&=u||l,d&&(f.hasHeader=d),f}function Zn(e){let t=vr(Xn(e)),n=t.bottom,r=t.right;if(n!==void 0&&n>9999998||r!==void 0&&r>An)throw Error(`Range string out of bounds: ${e}`);if(n===void 0&&r===void 0)throw Error(`Wrong zone xc. The zone cannot be at the same time a full column and a full row`);return t}function Qn(e){let t=Zn(e);if(t.bottom===void 0||t.right===void 0)throw Error(`This does not support unbounded ranges`);return t}function $n(e){let{bottom:t,top:n,left:r,right:i}=e;return t!==void 0&&isNaN(t)||isNaN(n)||isNaN(r)||i!==void 0&&isNaN(i)?!1:er(e)&&e.top>=0&&e.left>=0}function er(e){return(e.bottom===void 0||e.bottom>=e.top&&e.bottom>=0)&&(e.right===void 0||e.right>=e.left&&e.right>=0)}function tr(e){let{top:t,bottom:n,left:r,right:i}=e,a=`hasHeader`in e?e.hasHeader:!1,o=t===n&&r===i;if(n===void 0&&i!==void 0)return t===0&&!a?`${Tn(r)}:${Tn(i)}`:`${w(r,t)}:${Tn(i)}`;if(i===void 0&&n!==void 0)return r===0&&!a?`${t+1}:${n+1}`:`${w(r,t)}:${n+1}`;if(n!==void 0&&i!==void 0)return o?w(r,t):`${w(r,t)}:${w(i,n)}`;throw Error(E(`Bad zone format`))}function nr(e,t,n,r,i){let a=t===`left`?`columns`:`rows`,o=r===`before`?n-1:n,s=e[t===`left`?`right`:`bottom`];return e[t]<=o&&s&&s>o?yr(e,a,`RESIZE`,i):o<e[t]?yr(e,a,`MOVE`,i):{...e}}function rr(e,t,n,r,i){let a=t===`left`?`columns`:`rows`,o=r===`before`?n-1:n,s=t===`left`?`right`:`bottom`;return e[t]<=o&&e[s]>o?yr(e,a,`RESIZE`,i):o<e[t]?yr(e,a,`MOVE`,i):{...e}}function ir(e,t,n){let r=t===`left`?`right`:`bottom`,i=e[t],a=e[r];for(let o of n.sort((e,t)=>t-e))e[t]>o&&(i--,a--),e[t]<o&&e[r]>=o&&a--;return{...e,[t]:i,[r]:a}}function ar(e,t,n){let r=t===`left`?`right`:`bottom`,i=e[t],a=e[r],o=e[r];for(let r of n.sort((e,t)=>t-e))e[t]>r&&(i--,a!==void 0&&a--),o!==void 0&&a!==void 0&&e[t]<=r&&o>=r&&a--;if(!(a!==void 0&&i>a))return{...e,[t]:i,[r]:a}}function or(...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 sr(...e){return{top:Math.min(...e.map(e=>e.top)),left:Math.min(...e.map(e=>e.left)),bottom:e.some(e=>e.bottom===void 0)?void 0:Math.max(...e.map(e=>e.bottom)),right:e.some(e=>e.right===void 0)?void 0:Math.max(...e.map(e=>e.right))}}function cr(e,t){if(ur(e,t))return{top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),bottom:Math.min(e.bottom,t.bottom),right:Math.min(e.right,t.right)}}function lr(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function ur(e,t){return!(e.bottom<t.top||t.bottom<e.top||e.right<t.left||t.right<e.left)}function dr(e,t,n){let{left:r,right:i,top:a,bottom:o}=n;return e>=r&&e<=i&&t>=a&&t<=o}function fr(e,t){return lr(or(t,e),t)}function pr(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function mr(e){let{numberOfCols:t,numberOfRows:n}=pr(e);return t===1||n===1}function hr(e){let{top:t,left:n,bottom:r,right:i}=e;if(Er(e)===1)return[];let a={top:t+1,bottom:r,left:n,right:n};if(i===n)return[a];let o={top:t,bottom:r,left:n+1,right:i};return t===r?[o]:[a,o]}function gr(e){let t={};for(let n of e)t[n.sheetId]??=[],t[n.sheetId].push(D(n));for(let e in t)t[e]=T(t[e]);return t}function _r(e){let t=[],{left:n,right:r,top:i,bottom:a}=vr(e);for(let e of x(n,r+1))for(let n of x(i,a+1))t.push({col:e,row:n});return t}function vr(e){return e.right!==void 0&&e.left>e.right&&(e={...e,left:e.right,right:e.left}),e.bottom!==void 0&&e.top>e.bottom&&(e={...e,top:e.bottom,bottom:e.top}),e}function yr(e,t,n,r){let i=t===`both`?r[0]:t===`columns`?r:0,a=t===`both`?r[1]:t===`rows`?r:0,o=`hasHeader`in e?e.hasHeader:!1,s;s=Tr(e)&&!o?t!==`rows`:wr(e)&&!o?t!==`columns`:!0;let c={...e};return s&&n===`MOVE`&&(c.left+=i,c.top+=a),c.right!==void 0&&(c.right+=i),c.bottom!==void 0&&(c.bottom+=a),c}function br(e){return e.reverse().filter((e,t,n)=>t===n.findIndex(t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)).reverse()}function xr(e){return e.reduce((e,t)=>{let n=e.length;for(let r=0;r<n;r++)if(ur(e[r],t))return e[r]=or(e[r],t),e;return e[n]=t,e},[])}function Sr(e,t){let n,r,{left:i,right:a,top:o,bottom:s}=e,{left:c,right:l,top:u,bottom:d}=t;return n=c===i?l===a?c:l:c,r=u===o?d===s?u:d:u,{col:n,row:r}}function D(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function Cr(e){return{...e,right:e.left,bottom:e.top}}function wr(e){return e.right===void 0}function Tr(e){return e.bottom===void 0}function Er(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function Dr(e){return e.length<2?!0:T(e).length===1}function Or(e){let t=new Set;for(let n of T(e))for(let e of x(n.left,n.right+1))t.add(e);return t}function kr(e){let t=new Set;for(let n of T(e))for(let e of x(n.top,n.bottom+1))t.add(e);return t}function Ar(e,t){return e.right+1===t.left||e.left===t.right+1?e.top<=t.bottom&&e.top>=t.top||t.top<=e.bottom&&t.top>=e.top:e.bottom+1===t.top||e.top===t.bottom+1?e.left<=t.right&&e.left>=t.left||t.left<=e.right&&t.left>=e.left:!1}function jr(e){let t=[...e],n=!0;for(;n;){n=!1;for(let e=0;e<t.length;e++){let r=t[e],i=t.findIndex((t,n)=>e!==n&&(Ar(t,r)||ur(t,r)));if(i!==-1){t[e]=or(t[i],r),t.splice(i,1),n=!0;break}}}return t}let Mr=new WeakMap,Nr=new WeakMap;function Pr(e,t){Mr.has(t)||(Mr.set(t,new Map),Nr.set(t,0));let n=Mr.get(t),r=Ir(e);if(n.has(r)){let i=n.get(r);return t[i]=e,i}let i=Nr.get(t)+1;return n.set(r,i),Nr.set(t,i),t[i]=e,i}function Fr(e){let t={};for(let n in e){let r=T(e[n].map(D));for(let e of r)t[tr(e)]=Number(n)}return t}function Ir(e){if(e===null)return`null`;if(e===void 0)return`undefined`;if(typeof e!=`object`)return String(e);if(Array.isArray(e)){let t=e.length,n=`[`;for(let r=0;r<t;r++)r>0&&(n+=`,`),n+=Ir(e[r]);return n+`]`}let t=Object.keys(e).sort(),n=`{`;for(let r of t)e[r]!==void 0&&(n+=`"${r}":${Ir(e[r])},`);return n+=`}`,n}var O=class e{jsDate;constructor(e,t,n,r=0,i=0,a=0){this.jsDate=new Date(Date.UTC(e,t,n,r,i,a,0))}static fromTimestamp(t){let n=new Date(t);return new e(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds())}static now(){let t=new Date;return new e(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds())}toString(){return this.jsDate.toString()}toLocaleDateString(){return this.jsDate.toLocaleDateString()}getTime(){return this.jsDate.getTime()}getFullYear(){return this.jsDate.getUTCFullYear()}getMonth(){return this.jsDate.getUTCMonth()}getQuarter(){return Math.floor(this.getMonth()/3)+1}getDate(){return this.jsDate.getUTCDate()}getDay(){return this.jsDate.getUTCDay()}getHours(){return this.jsDate.getUTCHours()}getMinutes(){return this.jsDate.getUTCMinutes()}getSeconds(){return this.jsDate.getUTCSeconds()}getIsoWeek(){let e=new Date(this.jsDate.getTime()),t=e.getUTCDay()||7;e.setUTCDate(e.getUTCDate()+4-t);let n=new Date(Date.UTC(e.getUTCFullYear(),0,1));return Math.ceil(((e.getTime()-n.getTime())/864e5+1)/7)}setFullYear(e){return this.jsDate.setUTCFullYear(e)}setMonth(e){return this.jsDate.setUTCMonth(e)}setDate(e){return this.jsDate.setUTCDate(e)}setHours(e){return this.jsDate.setUTCHours(e)}setMinutes(e){return this.jsDate.setUTCMinutes(e)}setSeconds(e){return this.jsDate.setUTCSeconds(e)}};let Lr=new O(1899,11,30),Rr=1440*60*1e3,zr=2e3,Br=O.now().getFullYear(),Vr=O.now().getMonth(),Hr=O.fromTimestamp(0).getTime()-Lr.getTime(),Ur=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,Wr=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,Gr=Ft.join(``),Kr=RegExp(`\/|-|${Ft.join(`|`)}`),qr=RegExp(`^(\\d{1,4})[\/${Gr}\-](\\d{1,4})([\/${Gr}\-](\\d{1,4}))?$`),Jr=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function Yr(e,t){switch(typeof e){case`number`:return e;case`string`:return Xr(e,t)?Qr(e,t)?.value:!e||isNaN(Number(e))?void 0:Number(e);default:return}}function Xr(e,t){return Qr(e,t)!==null}let Zr=new Map;function Qr(e,t){return Zr.has(t)||Zr.set(t,new Map),Zr.get(t).has(e)||Zr.get(t).set(e,$r(e,t)),Zr.get(t).get(e)}function $r(e,t){e=e.trim();let n=null,r=e.match(Jr);if(r){if(n=si(r[0]),n===null)return null;e=e.replace(r[0],``).trim()}let i=null,a=ei(e,t);if(a){let t=a.dateString.match(Kr)[0];if(i=ni(a,t),i===null)return null;e=e.replace(a.dateString,``).trim()}return e!==``||!(i||n)?null:i&&i.jsDate&&n&&n.jsDate?{value:i.value+n.value,format:i.format+` `+(n.format===`hhhh:mm:ss`?`hh:mm:ss`:n.format),jsDate:new O(i.jsDate.getFullYear()+n.jsDate.getFullYear()-1899,i.jsDate.getMonth()+n.jsDate.getMonth()-11,i.jsDate.getDate()+n.jsDate.getDate()-30,i.jsDate.getHours()+n.jsDate.getHours(),i.jsDate.getMinutes()+n.jsDate.getMinutes(),i.jsDate.getSeconds()+n.jsDate.getSeconds())}:i||n}function ei(e,t){let n=e.match(qr);if(!n)return null;let[,r,i,,a]=n;if(r.length>2&&a&&a.length>2)return null;if(r.length>2)return{year:r,month:i,day:a,dateString:e,type:`ymd`};let o=ti(t);return a?a.length>2?o===`mdy`?{month:r,day:i,year:a,dateString:e,type:`mdy`}:{day:r,month:i,year:a,dateString:e,type:`dmy`}:o===`mdy`?{month:r,day:i,year:a,dateString:e,type:`mdy`}:o===`ymd`?{year:r,month:i,day:a,dateString:e,type:`ymd`}:o===`dmy`?{day:r,month:i,year:a,dateString:e,type:`dmy`}:null:i.length>2?{month:r,year:i,day:void 0,dateString:e,type:o}:o===`dmy`?{day:r,month:i,year:a,dateString:e,type:`dmy`}:{month:r,day:i,year:a,dateString:e,type:`mdy`}}function ti(e){switch(e.dateFormat[0]){case`d`:return`dmy`;case`m`:return`mdy`;case`y`:return`ymd`}throw Error(`Invalid date format in locale`)}function ni(e,t){let{year:n,month:r,day:i}=e,a=ai(r),o=oi(i),s=ii(n);if(s===null||a===null||o===null)return null;let c=r?.length===2&&a+1<10||i?.length===2&&o<10,l=n?.length!==2,u=new O(s,a,o);if(u.getMonth()!==a||u.getDate()!==o)return null;let d=u.getTime()-Lr.getTime(),f=ri(e,t,c,l);return{value:Math.round(d/Rr),format:f,jsDate:u}}function ri(e,t,n,r){let i=e.year?r?`yyyy`:`yy`:void 0,a=e.month?n?`mm`:`m`:void 0,o=e.day?n?`dd`:`d`:void 0;switch(e.type){case`mdy`:return[a,o,i].filter(S).join(t);case`ymd`:return[i,a,o].filter(S).join(t);case`dmy`:return[o,a,i].filter(S).join(t)}}function ii(e){if(!e)return Br;let t=Number(e);switch(e.length){case 1:return zr+t;case 2:return zr+(zr+t>Br+10?-100:0)+t;case 3:case 4:return t}return null}function ai(e){if(!e)return Vr;let t=Number(e);return t>=1&&t<=12?t-1:null}function oi(e){if(!e)return 1;let t=Number(e);return t>=0&&t<=31?t:null}function si(e){if(e=e.trim(),Jr.test(e)){let t=/AM/i.test(e),n=/PM/i.test(e),r=(t||n?e.substring(0,e.length-2).trim():e).split(/:/),i=r.length>=2,a=r.length===3,o=Number(r[0]),s=i?Number(r[1]):0,c=a?Number(r[2]):0,l=a?`hh:mm:ss`:`hh:mm`;if(t||n)l+=` a`;else if(!i)return null;o>=12&&t?o-=12:o<12&&n&&(o+=12),s+=Math.floor(c/60),c%=60,o+=Math.floor(s/60),s%=60,o>=24&&(l=`hhhh:mm:ss`);let u=new O(1899,11,30,o,s,c);return{value:o/24+s/1440+c/86400,format:l,jsDate:u}}return null}function ci(e){let t=Math.trunc(e),n=O.fromTimestamp(t*Rr-Hr),r=e-t;r=r<0?1+r:r;let i=Math.round(r*24),a=Math.round((r-i/24)*24*60),o=Math.round((r-i/24-a/24/60)*24*60*60);return n.setHours(i),n.setMinutes(a),n.setSeconds(o),n}function li(e){return Math.round(ui(e))}function ui(e){return(e.getTime()-Lr.getTime())/Rr}function di(e){return new O(e.getFullYear(),e.getMonth()+1,0).getDate()}function fi(e){return di(e)===e.getDate()}function pi(e,t,n){let r=e.getFullYear(),i=e.getMonth(),a=e.getDate(),o=new O(r,i+t,1);return n&&a===di(e)||a>di(o)?o.setDate(di(o)):o.setDate(a),o}function mi(e){let t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function hi(e,t,n){if(e===t)return 0;if(e>t){let n=t;t=e,e=n}let r=ci(e),i=ci(t),a=r.getDate(),o=i.getDate(),s=r.getMonth(),c=i.getMonth(),l=r.getFullYear(),u=i.getFullYear(),d=0,f=0;switch(n){case 0:a===31&&(a=30),a===30&&o===31&&(o=30),s===1&&a===(mi(l)?29:28)&&(a=30,c===1&&o===(mi(u)?29:28)&&(o=30)),d=l+(s*30+a)/360,f=u+(c*30+o)/360;break;case 1:let n=365,r=l===u,i=l+1===u;if(!r&&!i||!r&&s<c||!r&&s===c&&a<o){let e=0,t=0;for(let n=l;n<=u;n++)e++,t+=mi(n)?366:365;n=t/e}else r?mi(l)&&(n=366):(mi(l)&&s<2&&(n=366),mi(u)&&(c>1||c===1&&o===29)&&(n=366));d=e/n,f=t/n;break;case 2:d=e/360,f=t/360;break;case 3:d=e/365,f=t/365;break;case 4:a===31&&(a=30),o===31&&(o=30),d=l+(s*30+a)/360,f=u+(c*30+o)/360;break}return f-d}function gi(e,t){let n=(t.getFullYear()-e.getFullYear())*12+t.getMonth()-e.getMonth();return e.getDate()>t.getDate()?n-1:n}function _i(e,t){let n=e.getTime(),r=t.getTime();return Math.floor((r-n)/Rr)}function vi(e,t){let n=t.getFullYear()-e.getFullYear(),r=e.getMonth(),i=t.getMonth(),a=e.getDate(),o=t.getDate();return i>r||i===r&&o>=a?n:n-1}function yi(e,t){return hi(e,t,1)<1}function bi(e,t){return Math.trunc(e)===Math.trunc(t)}function xi(e,t,n){return t>n?xi(e,n,t):(e=Math.trunc(e),t=Math.trunc(t),n=Math.trunc(n),e>=t&&e<=n)}function Si(e,t){return Math.trunc(e)<Math.trunc(t)}function Ci(e,t){return Math.trunc(e)<=Math.trunc(t)}function wi(e,t){return Math.trunc(e)>Math.trunc(t)}function Ti(e,t){return Math.trunc(e)>=Math.trunc(t)}let Ei=Rt(function(e){return e=nt(e),RegExp(`(?:^-?\\d+(?:${e}?\\d*(?:e(\\+|-)?\\d+)?)?|^-?${e}\\d+)(?!\\w|!)`)}),Di=Rt(function(e){let t=nt(e.decimalSeparator),n=`(?:\\d+(?:${nt(e.thousandsSeparator||``)}\\d{3,})*(?:${t}\\d*)?)`,r=`(?:${t}\\d+)`,i=`(?:\\s*`+n+`|`+r+`)(?:e(?:\\+|-)?\\d+)?(?:\\s*%)?`,a=`^(?:(?:`+[`(?:\\s*-)?(?:\\s*[\\$€])?`+i,`(?:\\s*-)?`+i+`(?:\\s*[\\$€])?`,`(?:\\s*[\\$€])?(?:\\s*-)?`+i].join(`)|(?:`)+`))$`;return new RegExp(a,`i`)});function Oi(e,t){return e?Di(t).test(e.trim()):!1}let ki=Rt(function(e){return RegExp(`[\$€${nt(e.thousandsSeparator||``)}]`,`g`)});function Ai(e,t){e=e.replace(ki(t),``),t.decimalSeparator!==`.`&&(e=e.replace(t.decimalSeparator,`.`));let n=Number(e);return isNaN(n)&&e.includes(`%`)&&(n=Number(e.split(`%`)[0]),!isNaN(n))?n/100:n}function ji(e,t,n){let r=[...e].sort((e,t)=>e-t),i=(r.length+(n?-1:1))*t;if(n||i--,Number.isInteger(i))return r[i];let a=Math.ceil(i),o=Math.floor(i);return r[a]*(i-o)+r[o]*(a-i)}function Mi(e){return`sheetId`in e}function Ni(e){return`dimension`in e&&`sheetId`in e&&`elements`in e}function Pi(e){return`target`in e&&`sheetId`in e}function Fi(e){return`ranges`in e}function Ii(e){return`col`in e&&`row`in e&&`sheetId`in e}function Li(e){return`sheetId`in e&&`zone`in e}let Ri=new Set([`RENAME_SHEET`,`DELETE_SHEET`,`CREATE_SHEET`,`DUPLICATE_SHEET`,`ADD_COLUMNS_ROWS`,`REMOVE_COLUMNS_ROWS`,`UNDO`,`REDO`,`ADD_MERGE`,`REMOVE_MERGE`,`UPDATE_LOCALE`,`ADD_PIVOT`,`UPDATE_PIVOT`,`INSERT_PIVOT`,`RENAME_PIVOT`,`REMOVE_PIVOT`,`DUPLICATE_PIVOT`]),zi=new Set([`EVALUATE_CELLS`,`UPDATE_CELL`,`UNHIDE_COLUMNS_ROWS`,`HIDE_COLUMNS_ROWS`,`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUP`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_ALL_HEADER_GROUPS`,`UNFOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`UPDATE_TABLE`,`UPDATE_FILTER`,`UNDO`,`REDO`]),Bi=new Set([`MOVE_RANGES`]),Vi=new Set([`EVALUATE_CELLS`,`ADD_CONDITIONAL_FORMAT`,`REMOVE_CONDITIONAL_FORMAT`,`CHANGE_CONDITIONAL_FORMAT_PRIORITY`]),Hi=new Set([`AUTOFILL_CELL`,`SET_BORDER`,`SET_ZONE_BORDERS`,`SET_BORDERS_ON_TARGET`]),Ui=new Set([`START`,`ACTIVATE_SHEET`,`COPY`,`RESIZE_SHEETVIEW`,`SET_VIEWPORT_OFFSET`,`EVALUATE_CELLS`,`SET_FORMULA_VISIBILITY`,`UPDATE_FILTER`]),Wi=new Set(`UPDATE_CELL.UPDATE_CELL_POSITION.CLEAR_CELL.CLEAR_CELLS.DELETE_CONTENT.ADD_COLUMNS_ROWS.REMOVE_COLUMNS_ROWS.RESIZE_COLUMNS_ROWS.HIDE_COLUMNS_ROWS.UNHIDE_COLUMNS_ROWS.SET_GRID_LINES_VISIBILITY.UNFREEZE_COLUMNS.UNFREEZE_ROWS.FREEZE_COLUMNS.FREEZE_ROWS.UNFREEZE_COLUMNS_ROWS.ADD_MERGE.REMOVE_MERGE.CREATE_SHEET.DELETE_SHEET.DUPLICATE_SHEET.MOVE_SHEET.RENAME_SHEET.COLOR_SHEET.HIDE_SHEET.SHOW_SHEET.MOVE_RANGES.ADD_CONDITIONAL_FORMAT.REMOVE_CONDITIONAL_FORMAT.CHANGE_CONDITIONAL_FORMAT_PRIORITY.CREATE_FIGURE.DELETE_FIGURE.UPDATE_FIGURE.SET_FORMATTING.CLEAR_FORMATTING.SET_BORDER.SET_ZONE_BORDERS.SET_BORDERS_ON_TARGET.CREATE_CHART.UPDATE_CHART.CREATE_TABLE.REMOVE_TABLE.UPDATE_TABLE.CREATE_TABLE_STYLE.REMOVE_TABLE_STYLE.CREATE_IMAGE.GROUP_HEADERS.UNGROUP_HEADERS.UNFOLD_HEADER_GROUP.FOLD_HEADER_GROUP.FOLD_ALL_HEADER_GROUPS.UNFOLD_ALL_HEADER_GROUPS.UNFOLD_HEADER_GROUPS_IN_ZONE.FOLD_HEADER_GROUPS_IN_ZONE.ADD_DATA_VALIDATION_RULE.REMOVE_DATA_VALIDATION_RULE.UPDATE_LOCALE.ADD_PIVOT.UPDATE_PIVOT.INSERT_PIVOT.RENAME_PIVOT.REMOVE_PIVOT.DUPLICATE_PIVOT`.split(`.`));function Gi(e){return Wi.has(e.type)}function Ki(e){return Ui.has(e.type)}var qi=class{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter(e=>e!==`Success`)}static get Success(){return Ji}get isSuccessful(){return this.reasons.length===0}isCancelledBecause(e){return this.reasons.includes(e)}};let Ji=new qi,Yi=function(e){return e.Success=`Success`,e.CancelledForUnknownReason=`CancelledForUnknownReason`,e.WillRemoveExistingMerge=`WillRemoveExistingMerge`,e.CannotMoveTableHeader=`CannotMoveTableHeader`,e.MergeIsDestructive=`MergeIsDestructive`,e.CellIsMerged=`CellIsMerged`,e.InvalidTarget=`InvalidTarget`,e.EmptyUndoStack=`EmptyUndoStack`,e.EmptyRedoStack=`EmptyRedoStack`,e.NotEnoughElements=`NotEnoughElements`,e.NotEnoughSheets=`NotEnoughSheets`,e.MissingSheetName=`MissingSheetName`,e.UnchangedSheetName=`UnchangedSheetName`,e.DuplicatedSheetName=`DuplicatedSheetName`,e.DuplicatedSheetId=`DuplicatedSheetId`,e.ForbiddenCharactersInSheetName=`ForbiddenCharactersInSheetName`,e.WrongSheetMove=`WrongSheetMove`,e.WrongSheetPosition=`WrongSheetPosition`,e.InvalidAnchorZone=`InvalidAnchorZone`,e.SelectionOutOfBound=`SelectionOutOfBound`,e.TargetOutOfSheet=`TargetOutOfSheet`,e.WrongCutSelection=`WrongCutSelection`,e.WrongPasteSelection=`WrongPasteSelection`,e.WrongPasteOption=`WrongPasteOption`,e.WrongFigurePasteOption=`WrongFigurePasteOption`,e.EmptyClipboard=`EmptyClipboard`,e.EmptyRange=`EmptyRange`,e.InvalidRange=`InvalidRange`,e.InvalidZones=`InvalidZones`,e.InvalidSheetId=`InvalidSheetId`,e.InvalidCellId=`InvalidCellId`,e.InvalidFigureId=`InvalidFigureId`,e.InputAlreadyFocused=`InputAlreadyFocused`,e.MaximumRangesReached=`MaximumRangesReached`,e.MinimumRangesReached=`MinimumRangesReached`,e.InvalidChartDefinition=`InvalidChartDefinition`,e.InvalidDataSet=`InvalidDataSet`,e.InvalidLabelRange=`InvalidLabelRange`,e.InvalidScorecardKeyValue=`InvalidScorecardKeyValue`,e.InvalidScorecardBaseline=`InvalidScorecardBaseline`,e.InvalidGaugeDataRange=`InvalidGaugeDataRange`,e.EmptyGaugeRangeMin=`EmptyGaugeRangeMin`,e.GaugeRangeMinNaN=`GaugeRangeMinNaN`,e.EmptyGaugeRangeMax=`EmptyGaugeRangeMax`,e.GaugeRangeMaxNaN=`GaugeRangeMaxNaN`,e.GaugeRangeMinBiggerThanRangeMax=`GaugeRangeMinBiggerThanRangeMax`,e.GaugeLowerInflectionPointNaN=`GaugeLowerInflectionPointNaN`,e.GaugeUpperInflectionPointNaN=`GaugeUpperInflectionPointNaN`,e.GaugeLowerBiggerThanUpper=`GaugeLowerBiggerThanUpper`,e.InvalidAutofillSelection=`InvalidAutofillSelection`,e.MinBiggerThanMax=`MinBiggerThanMax`,e.LowerBiggerThanUpper=`LowerBiggerThanUpper`,e.MidBiggerThanMax=`MidBiggerThanMax`,e.MinBiggerThanMid=`MinBiggerThanMid`,e.FirstArgMissing=`FirstArgMissing`,e.SecondArgMissing=`SecondArgMissing`,e.MinNaN=`MinNaN`,e.MidNaN=`MidNaN`,e.MaxNaN=`MaxNaN`,e.ValueUpperInflectionNaN=`ValueUpperInflectionNaN`,e.ValueLowerInflectionNaN=`ValueLowerInflectionNaN`,e.MinInvalidFormula=`MinInvalidFormula`,e.MidInvalidFormula=`MidInvalidFormula`,e.MaxInvalidFormula=`MaxInvalidFormula`,e.ValueUpperInvalidFormula=`ValueUpperInvalidFormula`,e.ValueLowerInvalidFormula=`ValueLowerInvalidFormula`,e.InvalidSortZone=`InvalidSortZone`,e.WaitingSessionConfirmation=`WaitingSessionConfirmation`,e.MergeOverlap=`MergeOverlap`,e.TooManyHiddenElements=`TooManyHiddenElements`,e.Readonly=`Readonly`,e.InvalidViewportSize=`InvalidViewportSize`,e.InvalidScrollingDirection=`InvalidScrollingDirection`,e.ViewportScrollLimitsReached=`ViewportScrollLimitsReached`,e.FigureDoesNotExist=`FigureDoesNotExist`,e.InvalidConditionalFormatId=`InvalidConditionalFormatId`,e.InvalidConditionalFormatType=`InvalidConditionalFormatType`,e.InvalidCellPopover=`InvalidCellPopover`,e.EmptyTarget=`EmptyTarget`,e.InvalidFreezeQuantity=`InvalidFreezeQuantity`,e.FrozenPaneOverlap=`FrozenPaneOverlap`,e.ValuesNotChanged=`ValuesNotChanged`,e.InvalidFilterZone=`InvalidFilterZone`,e.TableNotFound=`TableNotFound`,e.TableOverlap=`TableOverlap`,e.InvalidTableConfig=`InvalidTableConfig`,e.InvalidTableStyle=`InvalidTableStyle`,e.FilterNotFound=`FilterNotFound`,e.MergeInTable=`MergeInTable`,e.NonContinuousTargets=`NonContinuousTargets`,e.DuplicatedFigureId=`DuplicatedFigureId`,e.InvalidSelectionStep=`InvalidSelectionStep`,e.DuplicatedChartId=`DuplicatedChartId`,e.ChartDoesNotExist=`ChartDoesNotExist`,e.InvalidHeaderIndex=`InvalidHeaderIndex`,e.InvalidQuantity=`InvalidQuantity`,e.MoreThanOneColumnSelected=`MoreThanOneColumnSelected`,e.EmptySplitSeparator=`EmptySplitSeparator`,e.SplitWillOverwriteContent=`SplitWillOverwriteContent`,e.NoSplitSeparatorInSelection=`NoSplitSeparatorInSelection`,e.NoActiveSheet=`NoActiveSheet`,e.InvalidLocale=`InvalidLocale`,e.MoreThanOneRangeSelected=`MoreThanOneRangeSelected`,e.NoColumnsProvided=`NoColumnsProvided`,e.ColumnsNotIncludedInZone=`ColumnsNotIncludedInZone`,e.DuplicatesColumnsSelected=`DuplicatesColumnsSelected`,e.InvalidHeaderGroupStartEnd=`InvalidHeaderGroupStartEnd`,e.HeaderGroupAlreadyExists=`HeaderGroupAlreadyExists`,e.UnknownHeaderGroup=`UnknownHeaderGroup`,e.UnknownDataValidationRule=`UnknownDataValidationRule`,e.UnknownDataValidationCriterionType=`UnknownDataValidationCriterionType`,e.InvalidDataValidationCriterionValue=`InvalidDataValidationCriterionValue`,e.InvalidNumberOfCriterionValues=`InvalidNumberOfCriterionValues`,e.InvalidCopyPasteSelection=`InvalidCopyPasteSelection`,e.NoChanges=`NoChanges`,e.InvalidInputId=`InvalidInputId`,e.SheetIsHidden=`SheetIsHidden`,e.InvalidTableResize=`InvalidTableResize`,e.PivotIdNotFound=`PivotIdNotFound`,e.PivotInError=`PivotInError`,e.EmptyName=`EmptyName`,e.ValueCellIsInvalidFormula=`ValueCellIsInvalidFormula`,e.InvalidDefinition=`InvalidDefinition`,e.InvalidColor=`InvalidColor`,e.InvalidPivotDataSet=`InvalidPivotDataSet`,e}({}),Xi=[{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:`;`}],k=Xi[0],Zi=[`thin`,`medium`,`thick`,`dashed`,`dotted`];function A(e){return Array.isArray(e)&&Array.isArray(e[0])}let Qi={Background:0,Highlights:1,Clipboard:2,Chart:4,Autofill:5,Selection:6,Headers:100},$i=Rt(()=>Object.keys(Qi).sort((e,t)=>Qi[e]-Qi[t]));function ea(e,t){if(Qi[e])throw Error(`Layer ${e} already exists`);Qi[e]=t}let j={NotAvailable:`#N/A`,InvalidReference:`#REF`,BadExpression:`#BAD_EXPR`,CircularDependency:`#CYCLE`,UnknownFunction:`#NAME?`,DivisionByZero:`#DIV/0!`,SpilledBlocked:`#SPILL!`,GenericError:`#ERROR`,NullError:`#NULL!`},ta=new Set(Object.values(j));var M=class{message;value;constructor(e=E(`Error`),t=j.GenericError){this.message=e,this.value=t,this.message=e.toString()}},na=class extends M{constructor(e=E(`Invalid expression`)){super(e,j.BadExpression)}},ra=class extends M{constructor(e=E(`Circular reference`)){super(e,j.CircularDependency)}},ia=class extends M{constructor(e=E(`Invalid reference`)){super(e,j.InvalidReference)}},aa=class extends M{constructor(e=E(`Data not available`)){super(e,j.NotAvailable)}},oa=class extends M{constructor(e=E(`Unknown function`)){super(e,j.UnknownFunction)}},sa=class extends M{constructor(e=E(`Spill range is not empty`)){super(e,j.SpilledBlocked)}};let ca=[`number`,`string`,`boolean`,`undefined`];function N(e,t,n){if(!e())throw new M(t,n)}function la(e){if(e!==void 0)return A(e)?e[0][0]?.format:e.format}function P(e){return typeof e==`string`&&ta.has(e)}let ua=e=>E(`The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.`,e),da=(e,t,n)=>E(`The function [[FUNCTION_NAME]] expects a number value between %s and %s inclusive, but receives %s.`,e.toString(),t.toString(),n.toString()),fa=(e,t)=>E(`The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.`,t,e.map(e=>`'${e}'`).join(`, `));function F(e,t){let n=Ca(e);switch(typeof n){case`number`:return n;case`boolean`:return+!!n;case`string`:if(Oi(n,t)||n===``)return Ai(n,t);let e=Qr(n,t);if(e)return e.value;throw new M(ua(n));default:return 0}}function pa(e,t){try{return F(e,t)}catch{return}}function ma(e,t){return z(e).map(e=>e.map(e=>{if(typeof e.value!=`number`){let n=``;throw typeof e==`object`?n=E(`Function [[FUNCTION_NAME]] expects number values for %s, but got an empty value.`,t):typeof e==`string`?n=E(`Function [[FUNCTION_NAME]] expects number values for %s, but got a string.`,t):typeof e==`boolean`&&(n=E(`Function [[FUNCTION_NAME]] expects number values for %s, but got a boolean.`,t)),new M(n)}return e.value}))}function ha(e,t){let n=Ca(e);if(n===``)throw new M(ua(n));return F(n,t)}function ga(e,t){return Math.trunc(F(e,t))}function _a(e,t){return Math.trunc(ha(e,t))}function va(e){N(()=>e>=1,E(`The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.`,e.toString()))}function ya(e){N(()=>e!==0,E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`),j.DivisionByZero)}function I(e){let t=Ca(e);switch(typeof t){case`string`:return t;case`number`:return t.toString();case`boolean`:return t?`TRUE`:`FALSE`;default:return``}}let ba=Rt(function(e){return e.toLowerCase().normalize(`NFD`).replace(/[\u0300-\u036f]/g,``)}),xa=e=>E(`The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a boolean.`,e);function L(e){let t=Ca(e);switch(typeof t){case`boolean`:return t;case`string`:if(t){let e=t.toUpperCase();if(e===`TRUE`)return!0;if(e===`FALSE`)return!1;throw new M(xa(t))}else return!1;case`number`:return!!t;default:return!1}}function Sa(e){let t=Ca(e);if(t===``)throw new M(xa(t));return L(t)}function R(e,t){return ci(F(Ca(e),t))}function Ca(e){if(typeof e==`object`&&e&&`value`in e){if(P(e.value))throw e;return e.value}if(P(e))throw new M(``,e);return e}function wa(e,t,n){for(let r of e)if(A(r)){let e=r.length,n=r[0].length;for(let i=0;i<n;i++)for(let n=0;n<e;n++)t(r[n][i])}else n(r)}function Ta(e,t){wa(e,e=>{if(P(e.value))throw e;t(e)},e=>{if(P(e?.value))throw e;t(e)})}function Ea(e,t,n){wa(e,e=>{if(typeof e?.value==`number`&&t(e),P(e?.value))throw e},e=>{t({value:ha(e,n),format:e?.format})})}function Da(e,t,n,r,i=`rowFirst`){let a=r;for(let r of e)if(A(r)){let e=r.length,n=r[0].length;if(i===`rowFirst`)for(let i=0;i<n;i++)for(let n=0;n<e;n++)a=t(a,r[n][i]);else for(let i=0;i<e;i++)for(let e=0;e<n;e++)a=t(a,r[i][e])}else a=n(a,r);return a}function Oa(e,t,n,r=`rowFirst`){return Da(e,t,t,n,r)}function ka(e,t,n,r){return Da(e,(e,n)=>{let r=n?.value;if(typeof r==`number`)return t(e,r);if(P(r))throw n;return e},(e,n)=>t(e,ha(n,r)),n)}function Aa(e,t,n,r){return Da(e,(e,n)=>{let i=n?.value;if(i!=null){if(typeof i==`number`)return t(e,i);if(typeof i==`boolean`)return t(e,F(i,r));if(P(i))throw n;return t(e,0)}return e},(e,n)=>t(e,F(n,r)),n)}function ja(e,t,n){let r=Array(e);for(let i=0;i<e;i++){r[i]=Array(t);for(let e=0;e<t;e++)r[i][e]=n(i,e)}return r}function Ma(e,t){return e.length===0?[]:ja(e.length,e[0].length,(n,r)=>t(e[n][r]))}function Na(e,t){let n=e.length,r=e[0]?.length??0;for(let i=0;i<n;i++)for(let n=0;n<r;n++)t(e[i][n])}function Pa(e){return e.length?ja(e[0].length,e.length,(t,n)=>e[n][t]):[]}function Fa(e,t,n=void 0){let r=1,i=1,a=1/0,o=1/0,s;for(let e=0;e<t.length;e++){let c=t[e];if(A(c)&&(n===void 0||n[e])){let n=c.length,l=c[0].length;n!==1||l!==1?(s??=Array(t.length),n!==1&&l!==1?(s[e]=`matrix`,r=Math.max(r,n),i=Math.max(i,l),a=Math.min(a,n),o=Math.min(o,l)):n===1?l!==1&&(s[e]=`vertical`,i=Math.max(i,l),o=Math.min(o,l)):(s[e]=`horizontal`,r=Math.max(r,n),a=Math.min(a,n))):t[e]=c[0][0]}}if(r===1&&i===1)return e(...t);let c=(e,n)=>t.map((t,r)=>{switch(s?.[r]){case`matrix`:return t[e][n];case`horizontal`:return t[e][0];case`vertical`:return t[0][n];case void 0:return t}});return ja(r,i,(t,n)=>{if(t>a-1||n>o-1)return new aa(E(`Array arguments to [[FUNCTION_NAME]] are of different size.`));let r=e(...c(t,n));return A(r)?r[0][0]:r})}function Ia(e,t,n){for(let r of e)if(A(r)){let e=r.length,n=r[0].length;for(let i=0;i<n;i++)for(let n=0;n<e;n++)if(!t(r[n][i]??void 0))return}else if(!n(r))return}function La(e,t){return Ia(e,e=>{let n=e?.value;if(typeof n==`boolean`)return t(n);if(typeof n==`number`)return t(!!n);if(P(n))throw e;return!0},e=>e!==void 0&&e.value!==null?t(Sa(e)):!0)}function Ra(e,t){let n,r,i=e.substring(0,2);return i===`<=`||i===`>=`||i===`<>`?(n=i,r=e.substring(2)):(i=e.substring(0,1),i===`<`||i===`>`||i===`=`?(n=i,r=e.substring(1)):(n=`=`,r=e)),Oi(r,t)||Xr(r,t)?r=F(r,t):(r===`TRUE`||r===`FALSE`)&&(r=L(r)),{operator:n,operand:r}}let za=Rt(function(e){if(e===`*`)return/.+/;let t=``,n=``;for(let r of e)r===`?`&&n!==`~`?t+=`.`:r===`*`&&n!==`~`?t+=`.*`:((r===`*`||r===`?`)&&(t=t.slice(0,-1)),[`^`,`.`,`[`,`]`,`$`,`(`,`)`,`*`,`+`,`?`,`|`,`{`,`}`,`\\`].includes(r)&&(t+=`\\`),t+=r),n=r;return RegExp(`^`+t+`$`,`i`)});function Ba(e=``,t,n){let{operator:r,operand:i}=t;if(i===void 0||e===null||i===null)return!1;if(typeof i==`number`&&r===`=`)return typeof e==`string`&&(Oi(e,n)||Xr(e,n))?F(e,n)===i:e===i;if(r===`<>`||r===`=`){let t;return t=typeof e==typeof i?typeof e==`string`&&typeof i==`string`?za(i).test(e):e===i:!1,r===`=`?t:!t}if(typeof e==typeof i)switch(r){case`<`:return e<i;case`>`:return e>i;case`<=`:return e<=i;case`>=`:return e>=i}return!1}function Va(e,t,n,r=!1){let i=e.length;if(i%2==1)throw new M(E(`Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs.`));let a=z(e[0]),o=a.length,s=a[0].length,c=[];for(let t=0;t<i-1;t+=2){let i=z(e[t]);if(i.length!==o||i[0].length!==s)throw new M(E(`Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension`));let a=Ra(I(e[t+1]),n);r&&typeof a.operand==`string`&&(a.operand+=`*`),c.push(a)}for(let r=0;r<o;r++)for(let a=0;a<s;a++){let o=!0;for(let t=0;t<i-1;t+=2){let i=z(e[t])[r][a].value,s=c[t/2];if(o=Ba(i??void 0,s,n),!o)break}o&&t(r,a)}}function Ha(e,t,n,r,i,a){if(t===void 0||t.value===null)return-1;if(P(t.value))throw t;let o=Ga(t.value),s=typeof o,c,l,u=0,d=i-1,f,p,m,h,g=r===`desc`?t=>Ga(a(e,i-t-1)):t=>Ga(a(e,t));for(;d-u>=0;){for(f=Math.floor((u+d)/2),p=f,m=g(p),h=typeof m;u<p&&s!==h;)p--,m=g(p),h=typeof m;if(h!==s||m==null){u=f+1;continue}n===`strict`&&m===o?(c=m,l=p):n===`nextSmaller`&&m<=o?(c==null||c<m||c===m&&l<p)&&(c=m,l=p):n===`nextGreater`&&m>=o&&(c===void 0||c>m||c===m&&l<p)&&(c=m,l=p),m>o||n===`strict`&&m===o?d=p-1:u=f+1}return l===void 0?-1:r===`desc`?i-l-1:l}function Ua(e,t,n,r,i,a,o=!1){if(t===void 0||t.value===null)return-1;if(P(t.value))throw t;let s=Ga(t.value),c=o?(e,t)=>Ga(i(e,r-t-1)):(e,t)=>Ga(i(e,t)),l=n!==`wildcard`||typeof s!=`string`||!(s.includes(`*`)||s.includes(`?`));if(a&&l){let t=o?`reverseSearch`:`forwardSearch`,i=a[t].get(e);if(i===void 0){i=new Map;for(let t=0;t<r;t++){let n=c(e,t)??null;i.has(n)||i.set(n,t)}a[t].set(e,i)}if(i.has(s)){let e=i.get(s);return o?r-e-1:e}if(n===`strict`)return-1}let u=Wa(e,s,n,r,c);return o&&u!==-1?r-u-1:u}function Wa(e,t,n,r,i){let a=n=>i(e,n)===t;if(n===`wildcard`&&typeof t==`string`&&(t.includes(`*`)||t.includes(`?`))){let n=za(t);a=t=>{let r=i(e,t);return typeof r==`string`?n.test(r):!1}}let o,s=-1;n===`nextSmaller`&&(a=n=>{let r=i(e,n);return(!o&&Ka(t,r)>=0||Ka(t,r)>=0&&Ka(r,o)>0)&&(o=r,s=n),r===t}),n===`nextGreater`&&(a=n=>{let r=i(e,n);return(!o&&Ka(t,r)<=0||Ka(t,r)<=0&&Ka(r,o)<0)&&(o=r,s=n),r===t});for(let e=0;e<r;e++)if(a(e))return e;return s}function Ga(e){return typeof e==`string`?ba(e):e}function Ka(e,t){let n=ca.indexOf(typeof e)-ca.indexOf(typeof t);return n===0&&(typeof e==`string`&&typeof t==`string`?n=e.localeCompare(t):typeof e==`number`&&typeof t==`number`?n=e-t:typeof e==`boolean`&&typeof t==`boolean`&&(n=Number(e)-Number(t))),n}function z(e){return e===void 0?[[]]:A(e)?e:[[e]]}function qa(e,t){return Oa(e,(e,n)=>(e.push(t(n)),e),[],`rowFirst`)}function Ja(e){if(e===void 0)return!1;let{value:t}=e;return!(t===null||t===``)}function Ya(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}let Xa=new h;function Za(e,t){return e=Ya(e),{url:e,label:t||e,isExternal:!0,isUrlEditable:!0}}Xa.add(`sheet_URL`,{match:e=>vt(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){let n=bt(e);return t.tryGetSheetName(n)||E(`Invalid sheet`)},open(e,t){let n=bt(e);t.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:n}).isCancelledBecause(`SheetIsHidden`)&&t.notifyUser({type:`warning`,sticky:!1,text:E(`Cannot open the link because the linked sheet is hidden.`)})},sequence:0});let Qa={createLink:Za,match:e=>mt(e),open:e=>window.open(e,`_blank`),urlRepresentation:e=>e,sequence:0};function $a(e){return Xa.getAll().sort((e,t)=>e.sequence-t.sequence).find(t=>t.match(e))||Qa}function eo(e,t){return $a(e.url).urlRepresentation(e.url,t)}function to(e,t){$a(e.url).open(e.url,t)}function no(e){if(typeof e==`string`){if(pt(e)){let{label:t,url:n}=gt(e);return $a(n).createLink(n,t)}else if(mt(e))return Za(e)}}function ro(e){e=e.replace(/\s/g,` `);let t=new qt(e),n=[],r=[];for(n.push(r);!t.isOver();){if(t.current===`;`){r=[],n.push(r),t.shift();continue}let e=fo(t)||io(t)||oo(t)||so(t)||lo(t)||uo(t)||mo(t)||co(t)||ho(t);if(!e)throw Error(`Unknown token at `+t.remaining());r.push(e)}return n}function io(e){let t;if(e.current===`"`?(e.shift(),t=`"`):e.currentStartsWith(`[$`)&&(e.advanceBy(2),t=`]`),!t)return null;let n=``;for(;e.current&&e.current!==t;)n+=e.shift();if(e.current===t)e.shift();else throw Error(`Unterminated string in format`);return{type:`STRING`,value:n}}let ao=new Set(`$+-/():!^&~{}<>= `);function oo(e){if(e.current===`\\`){e.shift();let t=e.shift();if(!t)throw Error(`Unexpected end of format string`);return{type:`CHAR`,value:t}}return ao.has(e.current)?{type:`CHAR`,value:e.shift()}:null}function so(e){return e.current===`,`?(e.shift(),{type:`THOUSANDS_SEPARATOR`,value:`,`}):null}function co(e){return e.current===`@`?(e.shift(),{type:`TEXT_PLACEHOLDER`,value:`@`}):null}function lo(e){return e.current===`.`?(e.shift(),{type:`DECIMAL_POINT`,value:`.`}):null}function uo(e){return e.current===`%`?(e.shift(),{type:`PERCENT`,value:`%`}):null}function fo(e){if(e.current===`0`||e.current===`#`){let t=e.current;return e.shift(),{type:`DIGIT`,value:t}}return null}let po=new Set(`dmqyhsa`);function mo(e){if(!po.has(e.current))return null;let t=e.current,n=``;for(;e.current===t;)n+=e.shift();return{type:`DATE_PART`,value:n}}function ho(e){if(e.current!==`*`)return null;e.shift();let t=e.shift();if(!t)throw Error(`Unexpected end of format string`);return{type:`REPEATED_CHAR`,value:t}}let go={};function _o(e){let t=go[e];return t===void 0&&(t=vo(e),go[e]=t),t}function vo(e){let t=ro(e);for(let e of t){let t=e.filter(e=>e.type===`REPEATED_CHAR`);for(let e of t.slice(1))e.type=`CHAR`}let n=Co(t[0])||So(t[0])||wo(t[0]);if(!n)throw Error(`Invalid first format part of: `+e);if(t.length>1&&n.type===`text`)throw Error(`The first format in a multi-part format must be a number format: `+e);let r=Co(t[1])||So(t[1]);if(t[1]?.length&&!r)throw Error(`Invalid second format part of: `+e);let i=Co(t[2])||So(t[2]);if(t[2]?.length&&!i)throw Error(`Invalid third format part of: `+e);let a=wo(t[3]);if(t[3]?.length&&!a)throw Error(`Invalid fourth format part of: `+e);return{positive:n,negative:r,zero:i,text:a}}function yo(e){return e.every(e=>e.type===`DATE_PART`||e.type===`DECIMAL_POINT`||e.type===`THOUSANDS_SEPARATOR`||e.type===`STRING`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function bo(e){return e.every(e=>e.type===`DIGIT`||e.type===`DECIMAL_POINT`||e.type===`THOUSANDS_SEPARATOR`||e.type===`PERCENT`||e.type===`STRING`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function xo(e){return e.every(e=>e.type===`STRING`||e.type===`TEXT_PLACEHOLDER`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function So(e){if(!e||!bo(e))return;let t=[],n,r=t,i=0,a=0,o=e.findLastIndex(e=>e.type===`DIGIT`),s=!1,c=0;for(let l=0;l<e.length;l++){let u=e[l];switch(u.type){case`DIGIT`:r===t?r.push(u):c<20&&(r.push(u),c++);break;case`DECIMAL_POINT`:if(r===t)n=[],r=n;else throw Error(`Multiple decimal points in a number format`);break;case`REPEATED_CHAR`:case`CHAR`:case`STRING`:r.push(u);break;case`PERCENT`:i++,r.push(u);break;case`THOUSANDS_SEPARATOR`:l-1===o?(a+=1,o++,r.push(u)):e[l+1]?.type===`DIGIT`&&e[l-1]?.type===`DIGIT`?(r===t&&(s=!0),r.push(u)):r.push({type:`CHAR`,value:`,`});break}}return{type:`number`,integerPart:t,decimalPart:n,percentSymbols:i,thousandsSeparator:s,magnitude:a}}function Co(e){let t=e&&yo(e)?{type:`date`,tokens:e}:void 0;if(t){if(t.tokens.length&&t.tokens.every(e=>e.type===`DATE_PART`&&e.value===`a`))throw Error(`Invalid date format`);return{type:`date`,tokens:To(t.tokens.map(e=>e.type===`THOUSANDS_SEPARATOR`||e.type===`DECIMAL_POINT`?{type:`CHAR`,value:e.value}:e))}}}function wo(e){return e&&xo(e)?{type:`text`,tokens:e}:void 0}function To(e){let t=e.filter(e=>e.type===`DATE_PART`);for(let e=0;e<t.length;e++)!t[e].value.startsWith(`m`)||t[e].value.length>2||(t[e-1]?.value.startsWith(`h`)||t[e+1]?.value.startsWith(`s`))&&(t[e].value=t[e].value.replaceAll(`m`,`M`));return e}function Eo(e){return[Do(e.positive),Do(e.negative),Do(e.zero),Do(e.text)].filter(S).join(`;`)}function Do(e){if(!e)return;let t=``,n=e.type===`number`?Oo(e):e.tokens;for(let e of n)switch(e.type){case`STRING`:t+=`[$${e.value}]`;break;case`CHAR`:t+=ko(e.value)?`\\${e.value}`:e.value;break;case`REPEATED_CHAR`:t+=`*`+e.value;break;case`DATE_PART`:t+=e.value===`MM`?`mm`:e.value;break;default:t+=e.value}return t}function Oo(e){let t=[...e.integerPart];return e.decimalPart&&(t.push({type:`DECIMAL_POINT`,value:`.`}),t.push(...e.decimalPart)),t}function ko(e){return!ao.has(e)}let Ao=`REPEATED_CHAR_PLACEHOLDER_`,jo={0:E(`January`),1:E(`February`),2:E(`March`),3:E(`April`),4:E(`May`),5:E(`June`),6:E(`July`),7:E(`August`),8:E(`September`),9:E(`October`),10:E(`November`),11:E(`December`)},Mo={0:E(`Sunday`),1:E(`Monday`),2:E(`Tuesday`),3:E(`Wednesday`),4:E(`Thursday`),5:E(`Friday`),6:E(`Saturday`)};function B(e,{format:t,locale:n,formatWidth:r}){switch(typeof e==`boolean`&&(e=e?`TRUE`:`FALSE`),typeof e){case`string`:{if(e.includes(`\\"`)&&(e=e.replaceAll(/\\"/g,`"`)),!t)return e;let n=_o(t),i=n.text||n.positive;return!i||i.type!==`text`?e:No(e,i,r)}case`number`:t||=Yo(e);let i=_o(t);if(i.positive.type===`text`)return No(e.toString(),i.positive,r);let a=i.positive;if(e<0&&i.negative?(a=i.negative,e=-e):e===0&&i.zero&&(a=i.zero),a.type===`date`)return Po(Ko(e,a),r);let o=e<0,s=Po(Fo(Math.abs(e),a,n),r);return o?`-`+s:s;case`object`:return``}}function No(e,t,n){let r=``;for(let n of t.tokens)switch(n.type){case`TEXT_PLACEHOLDER`:r+=e;break;case`CHAR`:case`STRING`:r+=n.value;break;case`REPEATED_CHAR`:r+=Ao+n.value;break}return Po(r,n)}function Po(e,t){let n=e.indexOf(Ao);if(n===-1)return e;let r=e.slice(0,n),i=e.slice(n+26+1),a=e[n+26];function o(){if(!t)return{timesToRepeat:0,padding:``};let e=t.measureText(r+i),n=t.measureText(a),o=t.availableWidth-e;if(o<=0)return{timesToRepeat:0,padding:``};let s=Math.floor(o/n),c=o-s*n,l=t.measureText(` `);return{timesToRepeat:s,padding:` `.repeat(Math.floor(c/l))}}let{timesToRepeat:s,padding:c}=o();return r+a.repeat(s)+c+i}function Fo(e,t,n){if(e===1/0)return`∞`+(t.percentSymbols?`%`:``);let r=t.percentSymbols*2-t.magnitude*3;e*=10**r;let i=0;t.decimalPart!==void 0&&(i=t.decimalPart.filter(e=>e.type===`DIGIT`).length);let{integerDigits:a,decimalDigits:o}=zo(Math.abs(e),i),s=Io(a,t,t.thousandsSeparator?n.thousandsSeparator:void 0);return t.decimalPart!==void 0&&(s+=n.decimalSeparator+Lo(o||``,t)),s}function Io(e,t,n){let r=t.integerPart;r.some(e=>e.type===`DIGIT`)||(r=[...r,{type:`DIGIT`,value:`#`}]),e===`0`&&(e=``);let i=``,a=r.findIndex(e=>e.type===`DIGIT`),o=e.length-1;function s(t,r){if(r===`0`&&(t||=`0`),!t)return;let a=e.length-1-o;i=n&&a>0&&a%3==0?t+n+i:t+i}for(let t=r.length-1;t>=0;t--){let n=r[t];switch(n.type){case`DIGIT`:let r=e[o];if(s(r,n.value),o--,a===t)for(;o>=0;)s(e[o],`0`),o--;break;case`THOUSANDS_SEPARATOR`:break;case`REPEATED_CHAR`:i=Ao+n.value+i;break;default:i=n.value+i;break}}return i}function Lo(e,t){if(!t.decimalPart)return``;let n=``,r=0;for(let i of t.decimalPart)switch(i.type){case`DIGIT`:let t=i.value===`#`?e[r]||``:e[r]||`0`;n+=t,r++;break;case`THOUSANDS_SEPARATOR`:break;case`REPEATED_CHAR`:n+=Ao+i.value;break;default:n+=i.value;break}return n}let Ro=[];function zo(e,t=20){let n=e.toString();if(n.includes(`e`))return Uo(e,t);if(Number.isInteger(e))return{integerDigits:n,decimalDigits:void 0};let r=n.indexOf(`.`),i=n.substring(0,r),a=n.substring(r+1);if(t===0)return Number(a[0])>=5&&(i=(Number(i)+1).toString()),{integerDigits:i,decimalDigits:void 0};if(a.length>t){let{integerDigits:e,decimalDigits:n}=Ho(a,t);a=n,e!==`0`&&(i=(Number(i)+Number(e)).toString())}return{integerDigits:i,decimalDigits:Bo(a||``)}}function Bo(e){let t=e.length-1;for(;t>=0&&e[t]===`0`;)t--;return e.slice(0,t+1)||void 0}let Vo=/^0+/;function Ho(e,t){let n=`0`,r=e,i=e.slice(0,t);if(Number(e[t])<5)return{integerDigits:n,decimalDigits:i};let a=i.match(Vo)?.[0]||``,o=(Number(i)+1).toString(),s=i.slice(a.length),c=o.length>s.length;return c&&!a?(n=`1`,r=void 0):r=c?a.slice(0,-1)+o:a+o,{integerDigits:n,decimalDigits:r}}function Uo(e,t=20){let n=Ro[t];n||(n=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:t,useGrouping:!1}),Ro[t]=n);let[r,i]=n.format(e).split(`.`);return{integerDigits:r,decimalDigits:i}}function Wo(e,t){let{integerDigits:n,decimalDigits:r}=zo(e,20);return r?n+t+r:n}let Go=Rt(function(e){if(!e)return!1;try{return _o(e).positive.type===`date`}catch{return!1}});function Ko(e,t){let n=ci(e);if(isNaN(n.getTime()))return e.toString();let r=t.tokens.some(e=>e.type===`DATE_PART`&&e.value===`a`),i=``;for(let e of t.tokens)switch(e.type){case`DATE_PART`:i+=qo(n,e.value,r);break;case`REPEATED_CHAR`:i+=Ao+e.value;break;default:i+=e.value;break}return i}function qo(e,t,n){switch(t){case`d`:return e.getDate();case`dd`:return e.getDate().toString().padStart(2,`0`);case`ddd`:return Mo[e.getDay()].slice(0,3);case`dddd`:return Mo[e.getDay()].toString();case`m`:return e.getMonth()+1;case`mm`:return String(e.getMonth()+1).padStart(2,`0`);case`mmm`:return jo[e.getMonth()].slice(0,3);case`mmmm`:return jo[e.getMonth()].toString();case`mmmmm`:return jo[e.getMonth()].slice(0,1);case`qq`:return E(`Q%(quarter)s`,{quarter:e.getQuarter()}).toString();case`qqqq`:return E(`Quarter %(quarter)s`,{quarter:e.getQuarter()}).toString();case`yy`:let r=String(e.getFullYear()).replace(`-`,``).padStart(2,`0`);return r.slice(r.length-2);case`yyyy`:return String(e.getFullYear()).replace(`-`,``).padStart(4,`0`);case`hhhh`:return Math.floor((e.getTime()-Lr.getTime())/(3600*1e3)).toString();case`hh`:let i=e.getHours();return n&&(i=i===0?12:i>12?i-12:i),i.toString().padStart(2,`0`);case`MM`:return e.getMinutes().toString().padStart(2,`0`);case`ss`:return e.getSeconds().toString().padStart(2,`0`);case`a`:return e.getHours()>=12?`PM`:`AM`;default:throw Error(`invalid date format token: ${t}`)}}let Jo=Rt(function(e){return RegExp(`[0-9]+${nt(e.decimalSeparator)}[0-9]`)});function Yo(e){let{integerDigits:t,decimalDigits:n}=zo(e);if(!n)return`0`;let r=t.replace(`-`,``).length;if(r+2>11)return`0`;let i=11-r-1;return{decimalDigits:n}=zo(e,Math.min(i,n.length)),n?`0.`+`0`.repeat(n.length):`0`}function Xo(e,t){if(Xr(e,t))return Qr(e,t).format}function Zo(e){let t=e.includes(`.`)?`0.00`:`0`,n=e.match(/[\$€]/);if(n){let r=e.match(/[\d]/),i=`[$`+n.values().next().value+`]`;return r.index<n.index?`#,##`+t+i:i+`#,##`+t}if(e.includes(`%`))return t+`%`}function Qo(e){let t=e.decimalPlaces??2,n=e.position??`before`,r=e.code??``,i=e.symbol??``,a=`#,##0`+(t?`.`+`0`.repeat(t):``),o=`${r} ${i}`.trim();return n===`after`&&r&&(o=` `+o),ts(o,n,a)}function $o(e){let t=e.decimalPlaces??2,n=e.position??`before`,r=e.code??``,i=e.symbol??``,a=`#,##0`+(t?`.`+`0`.repeat(t):``),o=`${r} ${i}`.trim();return n===`after`&&r&&(o=` `+o),[es(o,n,` ${a} `),es(o,n,`(${a})`),es(o,n,` - `)].join(`;`)}function es(e,t,n){let r=`[$${e}]`;return t===`before`?r+`* `+n:n+`* `+r}function ts(e,t,n){let r=`[$${e}]`;return t===`before`?r+n:n+r}function ns(e){let t=_o(e);return Eo({positive:rs(t.positive),negative:t.negative?rs(t.negative):void 0,zero:t.zero?rs(t.zero):void 0,text:t.text})}function rs(e){if(e.type!==`number`||!e.decimalPart)return e;let t=e.decimalPart.filter(e=>e.type!==`DIGIT`);return{...e,decimalPart:void 0,integerPart:[...e.integerPart,...t]}}function is({value:e,format:t},n){return B(e,{format:as({value:e,format:t},void 0,n),locale:n})}function as(e,t,n){let r=0;try{r=Math.abs(F(e?.value,n))}catch{return``}let i=e?.format;if(t!==void 0)switch(t?.value){case`k`:return os(i,1,`k`,n);case`m`:return os(i,2,`m`,n);case`b`:return os(i,3,`b`,n);default:throw new M(E(`The formatting unit should be 'k', 'm' or 'b'.`))}return r<1e5?os(i,0,``,n):r<1e8?os(i,1,`k`,n):r<1e11?os(i,2,`m`,n):os(i,3,`b`,n)}function os(e,t,n,r){let i=_o(e||`#,##0`);return Eo({positive:ss(i.positive,t,n),negative:i.negative?ss(i.negative,t,n):void 0,zero:i.zero?ss(i.zero,t,n):void 0,text:i.text})}function ss(e,t,n){if(e.type!==`number`)return e;let r=rs(e),i={type:`STRING`,value:n},a=[...r.integerPart],o=a.findLastIndex(e=>e.type===`DIGIT`);if(o===-1)throw Error(`Cannot create a large number format from a format with no digit.`);for(;a[o+1]?.type===`THOUSANDS_SEPARATOR`;)a=zt(a,[o+1]);let s=a[o+1];a=s?.type===`STRING`&&[`m`,`k`,`b`].includes(s.value)?Vt(a,i,o+1):Bt(a,[i],o+1),t>0&&(a=Bt(a,Array(t).fill({type:`THOUSANDS_SEPARATOR`,value:`,`}),o+1));let c=r.percentSymbols-a.filter(e=>e.type===`PERCENT`).length;return a.push(...Array(c).fill({type:`PERCENT`,value:`%`})),{...r,integerPart:a,magnitude:t}}function cs(e,t){let n=_o(e);return Eo(_o(Eo({positive:ls(n.positive,t),negative:n.negative?ls(n.negative,t):void 0,zero:n.zero?ls(n.zero,t):void 0,text:n.text})))}function ls(e,t){return e.type===`number`?t>0?ds(e,t):us(e,Math.abs(t)):e}function us(e,t){let n=e.decimalPart;if(!n)return e;let r=[],i=0;for(let e=n.length-1;e>=0&&!(i>=Math.abs(t));e--)n[e].type===`DIGIT`&&(i++,r.push(e));return n=zt(n,r),n.some(e=>e.type===`DIGIT`)?{...e,decimalPart:n}:{...e,decimalPart:void 0,integerPart:[...e.integerPart,...n]}}function ds(e,t){let n=e.integerPart,r=e.decimalPart;if(!r){let e=n.findLastIndex(e=>e.type===`DIGIT`);r=n.slice(e+1),n=n.slice(0,e+1)}let i=x(0,t).map(()=>({type:`DIGIT`,value:`0`})),a=r.findLastIndex(e=>e.type===`DIGIT`);return r=a===-1?[...i,...r]:Bt(r,i,a+1),{...e,decimalPart:r,integerPart:n}}function fs(e){let t=_o(e);for(let e of[t.positive,t.negative,t.zero])if(e&&e.type===`date`&&e.tokens.some(e=>e.type===`DATE_PART`&&e.value.includes(`q`)))return!1;return!0}function ps(e){if(!e)return!1;try{return _o(e).positive.type===`text`}catch{return!1}}function ms(e,t){return gs({value:ps(t.format)&&e.parsedValue!==null?e.content:e.parsedValue,format:t.format},t.locale)}function hs(e,t){if(e.startsWith(`=`))throw Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);if(e===``)return null;if(Oi(e,k))return Ai(e,k);let n=Qr(e,t);return n?n.value:ut(e)?e.toUpperCase()===`TRUE`:e}function gs(e,t=k,n){let r=no(e.value);if(!r)return _s(e,t,n);let i=hs(r.label,t);return{..._s({value:i,format:e.format||(typeof i==`number`?Xo(r.label,t)||Zo(r.label):void 0)},t,n),link:r}}function _s(e,t,n){let{value:r,format:i,message:a}=e;i=n?.format||i;let o=B(r,{format:i,locale:t});return P(r)?Cs(r,a):r===null?bs(i):ps(i)?vs(I(r),i,o):typeof r==`number`?Go(i||``)?xs(r,i,o):ys(r,i,o):typeof r==`boolean`?Ss(r,i,o):vs(r,i,o)}function vs(e,t,n){return{value:e,format:t,formattedValue:n,type:`text`,isAutoSummable:!0,defaultAlign:`left`}}function ys(e,t,n){return{value:e||0,format:t,formattedValue:n,type:`number`,isAutoSummable:!0,defaultAlign:`right`}}let bs=Rt(function(e){return{value:null,format:e,formattedValue:``,type:`empty`,isAutoSummable:!0,defaultAlign:`left`}});function xs(e,t,n){return{value:e,format:t,formattedValue:n,type:`number`,isAutoSummable:!1,defaultAlign:`right`}}function Ss(e,t,n){return{value:e,format:t,formattedValue:n,type:`boolean`,isAutoSummable:!1,defaultAlign:`center`}}function Cs(e,t){return{value:e,formattedValue:e,message:t,type:`error`,isAutoSummable:!1,defaultAlign:`center`}}function ws(e){let t=O.now();switch(e){case`today`:return Math.floor(ui(t));case`yesterday`:return t.setDate(t.getDate()-1),Math.floor(ui(t));case`tomorrow`:return t.setDate(t.getDate()+1),Math.floor(ui(t));case`lastWeek`:return t.setDate(t.getDate()-6),Math.floor(ui(t));case`lastMonth`:{let e=t.getMonth()===0?11:t.getMonth()-1,n=new O(t.getFullYear(),e,1);return t.getDate()>di(n)?t.setDate(1):(t.setDate(t.getDate()+1),t.setMonth(t.getMonth()-1)),Math.floor(ui(t))}case`lastYear`:return t.getMonth()===1&&t.getDate()===29?(t.setDate(28),t.setFullYear(t.getFullYear()-1)):(t.setDate(t.getDate()+1),t.setFullYear(t.getFullYear()-1)),Math.floor(ui(t))}}function Ts(e,t){return`dateValue`in e&&e.dateValue!==`exactDate`?[ws(e.dateValue)]:e.values.map(e=>Yr(e,t))}function Es(e,t){return e.values.map(e=>pa(e,t))}function Ds(e,t){return e.map(e=>{if(e.startsWith(`=`))return e;let n=hs(e,t);return typeof n==`number`?B(n,{format:t.dateFormat,locale:t}):``})}function Os(e){return 20+120*Math.exp(-.035*(e-1))}let ks=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,`i`),As=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,`i`),js=new RegExp(/^\$?([A-Z]{1,3})+$/,`i`),Ms=new RegExp(/^\$?([0-9]{1,7})+$/,`i`),Ns=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,`i`),Ps=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,`i`),Fs=RegExp(`^\\s*('.+'!|[^']+!)?(`+[ks.source,`(\\$?[A-Z]{1,3})?\\$?[0-9]{1,7}\\s*:\\s*(\\$?[A-Z]{1,3})?\\$?[0-9]{1,7}\\s*`,`\\$?[A-Z]{1,3}(\\$?[0-9]{1,7})?\\s*:\\s*\\$?[A-Z]{1,3}(\\$?[0-9]{1,7})?\\s*`].join(`|`)+`)$`,`i`);function Is(e){return Ns.test(e)}function Ls(e){return Ps.test(e)}function Rs(e){return js.test(e)}function zs(e){return Ms.test(e)}function Bs(e){return As.test(e)}function Vs(e){if(!e.includes(`!`))return{xc:e};let t=e.split(`!`),n=t.pop();return{sheetName:it(t.join(`!`))||void 0,xc:n}}function Hs(e,t){return e===void 0?t:`${ot(e)}!${t}`}var Us=class e{getSheetSize;_zone;parts;invalidXc;prefixSheet=!1;sheetId;invalidSheetName;constructor(e,t){this.getSheetSize=t,this._zone=e.zone,this.prefixSheet=e.prefixSheet,this.invalidXc=e.invalidXc,this.sheetId=e.sheetId,this.invalidSheetName=e.invalidSheetName;let n=[...e.parts];e.parts.length===1&&Er(this.zone)>1?n.push({...e.parts[0]}):e.parts.length===2&&Er(this.zone)===1&&n.pop(),this.parts=n}static fromRange(t,n){return t instanceof e?t:new e(t,n.getSheetSize)}get unboundedZone(){return this._zone}get zone(){let{left:e,top:t,bottom:n,right:r}=this._zone;if(r!==void 0&&n!==void 0)return this._zone;if(n===void 0&&r!==void 0)return{right:r,top:t,left:e,bottom:this.getSheetSize(this.sheetId).numberOfRows-1};if(r===void 0&&n!==void 0)return{bottom:n,left:e,top:t,right:this.getSheetSize(this.sheetId).numberOfCols-1};throw Error(E(`Bad zone format`))}static getRangeParts(e,t){let n=e.split(`:`).map(e=>{let t=Ls(e);return{colFixed:t?!1:e.startsWith(`$`),rowFixed:t?e.startsWith(`$`):e.includes(`$`,1)}}),r=t.bottom===void 0,i=t.right===void 0;return r&&(n[0].rowFixed=n[0].rowFixed||n[1].rowFixed,n[1].rowFixed=n[0].rowFixed||n[1].rowFixed),i&&(n[0].colFixed=n[0].colFixed||n[1].colFixed,n[1].colFixed=n[0].colFixed||n[1].colFixed),n}get isFullCol(){return this._zone.bottom===void 0}get isFullRow(){return this._zone.right===void 0}get rangeData(){return{_zone:this._zone,_sheetId:this.sheetId}}orderZone(){if(er(this._zone))return this;let e={...this._zone},t=this.parts;if(e.right!==void 0&&e.right<e.left){let n=e.right;e.right=e.left,e.left=n,t=[{colFixed:t[1]?.colFixed||!1,rowFixed:t[0]?.rowFixed||!1},{colFixed:t[0]?.colFixed||!1,rowFixed:t[1]?.rowFixed||!1}]}if(e.bottom!==void 0&&e.bottom<e.top){let n=e.bottom;e.bottom=e.top,e.top=n,t=[{colFixed:t[0]?.colFixed||!1,rowFixed:t[1]?.rowFixed||!1},{colFixed:t[1]?.colFixed||!1,rowFixed:t[0]?.rowFixed||!1}]}return this.clone({zone:e,parts:t})}clone(t){return new e({zone:t?.zone?t.zone:{...this._zone},sheetId:t?.sheetId?t.sheetId:this.sheetId,invalidSheetName:t&&`invalidSheetName`in t?t.invalidSheetName:this.invalidSheetName,invalidXc:t&&`invalidXc`in t?t.invalidXc:this.invalidXc,parts:t?.parts?t.parts:this.parts.map(e=>({rowFixed:e.rowFixed,colFixed:e.colFixed})),prefixSheet:t?.prefixSheet===void 0?this.prefixSheet:t.prefixSheet},this.getSheetSize)}};function Ws(e,t,n){let r=n.sheetId===e?t:n.sheetId;return n.clone({sheetId:r})}function Gs(e,t,n){if(!n)return;let r=e.getRangeFromSheetXC(t,n);return r.invalidSheetName||r.invalidXc?void 0:r}function Ks(e,t){let n=[];for(let r of t){let t=r.dataRange;if(!e.isRangeValid(t)){n.push(r);continue}let{sheetName:i}=Vs(t),a=i?`${i}!`:``,o=Zn(t);if(o.bottom!==o.top&&o.left!==o.right)if(o.right)for(let e=o.left;e<=o.right;++e){let t=e===o.left?r:{yAxisId:r.yAxisId};n.push({...t,dataRange:`${a}${tr({left:e,right:e,top:o.top,bottom:o.bottom})}`})}else for(let e=o.top;e<=o.bottom;++e){let t=e===o.top?r:{yAxisId:r.yAxisId};n.push({...t,dataRange:`${a}${tr({left:o.left,right:o.right,top:e,bottom:e})}`})}else n.push(r)}return n}function qs(e){let t=[];for(let n of e)for(let e of _r(n.zone))t.push({...e,sheetId:n.sheetId});return t}function Js(e,t){e=e.toLocaleLowerCase(),t=t.toLocaleLowerCase();let n=0,r=0,i=t.length,a=0;for(let o=0;o<i;o++)t[o]===e[a]?(a++,r+=100+r-o/200):r=0,n+=r;return a===e.length?n:0}function Ys(e,t,n){let r=[];return t.forEach(t=>{let i=Js(e,n(t));i>0&&r.push({score:i,elem:t})}),r.sort((e,t)=>t.score-e.score),r.map(e=>e.elem)}function Xs(e){let t=[];for(let n=0;n<e;n++)t.push({cells:{}});return t}function Zs(e,t,n){return n.map(n=>n>=e?n+t:n)}function Qs(e,t){return e=[...e].sort((e,t)=>t-e),t.map(t=>{for(let n of e)if(t>n)t--;else if(t===n)return;return t}).filter(S)}function $s(e,t=`Sheet`){let n=1,r=`${t}${n}`;for(;e.includes(r);)r=`${t}${n}`,n++;return r}function ec(e,t){let n=1,r=E(`Copy of %s`,e),i=r.toString();for(;t.includes(i);)i=`${r} (${n})`,n++;return i}function tc(e,t){return e===void 0||t===void 0?!1:it(e.trim().toUpperCase())===it(t.trim().toUpperCase())}function nc(e,t=1){return t*(e+4)-4}function rc(e,t,n,r){if(!t||!t.isFormula&&!t.content)return 23;let i=``;try{if(!t.isFormula){let e={format:t.format,locale:n};i=B(hs(t.content,n),e)}}catch{i=j.GenericError}return ic(e,i,t.style,r)}function ic(e,t,n,r){let i=gc(e,t,n,n?.wrapping===`wrap`?r-8:void 0).length;return nc(mc(n),i)+6}function ac(e,t=!1,n=!1){return`${n?`italic`:``} ${t?`bold`:``} ${e}px ${ze}`}let oc={};function sc(e,t,n,r=`pt`){let i=pc(n,r);e.save(),e.font=i;let a=cc(e,t);return e.restore(),a}function cc(e,t){let n=e.font;if(oc[n]||(oc[n]={}),oc[n][t]===void 0){let r=e.measureText(t).width;oc[n][t]=r}return oc[n][t]}let lc={};function uc(e,t,n,r=`pt`){let i=pc(n,r);e.save(),e.font=i;let a=dc(e,t);return e.restore(),a}function dc(e,t){let n=e.font;if(lc[n]||(lc[n]={}),lc[n][t]===void 0){let r=e.measureText(t),i=r.width,a=r.fontBoundingBoxAscent+r.fontBoundingBoxDescent;lc[n][t]={width:i,height:a}}return lc[n][t]}function fc(e){return Math.round(e*96/72)}function pc(e,t=`pt`){return`${e.italic?`italic `:``}${e.bold?`bold`:`400`} ${(t===`pt`?mc(e):e.fontSize)??Re}px ${ze}`}function mc(e){return fc(e?.fontSize||Re)}function hc(e,t,n,r){if(sc(e,t,r)<=n)return[t];let i=[],a=``;for(let o of t)sc(e,a+o,r)>n?(i.push(a),a=o):a+=o;return i.push(a),i}function gc(e,t,n,r){n||={},pt(t)&&(t=gt(t).label);let i=[],a=t.includes(`
5
5
  `)?t.split(`
6
- `):[t];for(let t of a){let a=t.includes(` `)?t.split(` `):[t];if(!r){i.push(t);continue}let o=``,s=r;for(let t of a){let a=hc(e,t,r,n),c=a.pop(),l=sc(e,c,n);if(a.length)o!==``&&(i.push(o),o=``,s=r),a.forEach(e=>{i.push(e)}),o=c,s=r-l;else{let t=o===``?c:` `+c,a=sc(e,t,n);a<=s?(o+=t,s-=a):(i.push(o),o=c,s=r-l)}}o!==``&&i.push(o)}return i}function _c(e,t,n,r=.25){let i=1;if(n(i)>e)return i;if(n(t)<e)return t;let a=(i+t)/2,o=n(a),s=0;for(;Math.abs(o-e)>r&&s<20;)o>=e?t=(i+t)/2:i=(i+t)/2,a=(i+t)/2,o=n(a),s++;return a}function vc(e){return mc(e)+8}function yc(e){return e?e.toLowerCase():``}let bc=/([0-9\.]*)px/;function xc(e){return Number(e.match(bc)?.[1])}function Sc(e,t,n){let r=cc(e,t);if(r<=n)return t;let i=cc(e,`…`);if(r<=i)return t;let a=t.length;for(;r>=n-i&&a-- >0;)t=t.substring(0,a),r=cc(e,t);return t+`…`}function Cc(e,t,n,r=!1,i=!1,a=xc(e.font)/10){if(e.fillText(t,n.x,n.y),!r&&!i)return;let o=e.measureText(t),s=o.width,c=o.actualBoundingBoxAscent+o.actualBoundingBoxDescent,l=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent,{x:u,y:d}=n,f=d,p=d;switch(e.textAlign){case`center`:u-=s/2;break;case`right`:u-=s;break}switch(e.textBaseline){case`top`:p+=l-2*a,f+=l/2-a;break;case`middle`:p+=l/2-a;break;case`alphabetic`:p+=2*a,f-=3*a;break;case`bottom`:p=d,f-=c/2-a/2;break}r&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,p),e.lineTo(u+s,p),e.stroke()),i&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,f),e.lineTo(u+s,f),e.stroke())}var wc=class{isFastIdStrategy=!1;fastIdStart=0;setIsFastStrategy(e){this.isFastIdStrategy=e}smallUuid(){return this.isFastIdStrategy?(this.fastIdStart++,String(this.fastIdStart)):window.crypto?`10000000-1000`.replace(/[01]/g,e=>{let t=Number(e);return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)}):`xxxxxxxx-xxxx`.replace(/[xy]/g,function(e){var t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}uuidv4(){return this.isFastIdStrategy?(this.fastIdStart++,String(this.fastIdStart)):window.crypto?`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>{let t=Number(e);return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)}):`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(e){var t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}};function Tc(e,t){let n=new Set(t.map(e=>e.left)),r=new Set(t.map(e=>e.right)),i=new Set(t.map(e=>e.top)),a=new Set(t.map(e=>e.bottom)),o=i.size===1&&a.size===1||n.size===1&&r.size===1?xr(t):[t[t.length-1]],s=o.map(e=>_r(e)).flat();return{sheetId:e,zones:t,clippedZones:o,columnsIndexes:[...new Set(s.map(e=>e.col))].sort((e,t)=>e-t),rowsIndexes:[...new Set(s.map(e=>e.row))].sort((e,t)=>e-t)}}function Ec(e,t,n){let r=Math.max(e.right-t+1,e.left),i=Math.max(e.bottom-n+1,e.top),a=[];for(let o=e.left;o<=r;o+=t)for(let r=e.top;r<=i;r+=n)a.push({left:o,top:r,bottom:r+n-1,right:o+t-1});return a}function Dc(e,t){if(!t.length||!t[0].length)return e;let n=t[0].length,r=t.length;return e.map(e=>Ec(e,n,r)).flat()}function Oc(e){if(!e[`text/html`])return{text:e[`text/plain`]};let t=new DOMParser().parseFromString(e[`text/html`],`text/html`);return{text:e[`text/plain`],data:kc(t)}}function kc(e){if([...e.documentElement.attributes].some(e=>e.value.includes(`microsoft`)))return;let t=e.querySelector(`div`)?.getAttribute(`data-osheet-clipboard`);return t&&JSON.parse(t)}let Ac=(e,t,n,r)=>{e.forEach(({handlerName:e,handler:i})=>{let a=t[e];a&&i.paste(n,a,r)})};function jc(e,t,n,r,i){let a,o=[],s={sheetId:e,zones:t};for(let{handlerName:c,handler:l}of r){let r=n[c];if(!r)continue;let u=l.getPasteTarget(e,t,r,i);u.figureId&&(s.figureId=u.figureId);for(let e of u.zones){if(o.push(e),a===void 0){a=e;continue}a=or(a,e)}}return{target:s,zone:a,selectedZones:o}}let Mc=(e,t,n)=>{let r={col:t[0].left,row:t[0].top};e.getBackToDefault(),e.selectZone({cell:r,zone:or(...n)},{scrollIntoView:!1})};var Nc=class{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t=`copyPaste`){}paste(e,t,n){}isPasteAllowed(e,t,n,r){return`Success`}isCutAllowed(e){return`Success`}getPasteTarget(e,t,n,r){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}},Pc=class extends Nc{copy(e,t=`copyPaste`){}pasteFromCopy(e,t,n,r){if(t.length===1)for(let i of Dc(t,n))this.pasteZone(e,i.left,i.top,n,r);else for(let i of T(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++)this.pasteZone(e,t,a,n,r)}pasteZone(e,t,n,r,i){}},Fc=class extends Pc{queuedBordersToAdd={};copy(e){let t=e.sheetId;if(e.zones.length===0)return;let{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getCellBorder(r))}i.push(n)}return{borders:i}}paste(e,t,n){let r=e.sheetId;if(n.pasteOption===`asValue`)return;let i=e.zones;if(!n.isCutOperation)this.pasteFromCopy(r,i,t.borders);else{let{left:e,top:n}=i[0];this.pasteZone(r,e,n,t.borders)}this.executeQueuedChanges(r)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteBorder(o,a)}}pasteBorder(e,t){let n={...this.getters.getCellBorder(t),...e},r=JSON.stringify(n);this.queuedBordersToAdd[r]||(this.queuedBordersToAdd[r]=[]),this.queuedBordersToAdd[r].push(D(t))}executeQueuedChanges(e){for(let t in this.queuedBordersToAdd){let n=this.queuedBordersToAdd[t],r=JSON.parse(t),i=T(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}};let Ic=[`%`],Lc=`+,-,*,/,:,=,<>,>=,>,<=,<,^,&`.split(`,`).concat(Ic);function Rc(e,t=k){e=It(e);let n=new qt(e),r=[],i=Nt.test(e)?Xc:Zc;for(;!n.isOver();){let e=Qc(n)||i(n)||Hc(n,t)||Vc(n)||Uc(n)||Kc(n)||zc(n)||$c(n)||Gc(n,t)||Yc(n);e||={type:`UNKNOWN`,value:n.shift()},r.push(e)}return r}function zc(e){return e.current===`?`?(e.shift(),{type:`DEBUGGER`,value:`?`}):null}let Bc={"(":{type:`LEFT_PAREN`,value:`(`},")":{type:`RIGHT_PAREN`,value:`)`}};function Vc(e){return e.current===`(`||e.current===`)`?Bc[e.shift()]:null}function Hc(e,t){return e.current===t.formulaArgSeparator?{type:`ARG_SEPARATOR`,value:e.shift()}:null}function Uc(e){for(let t of Lc)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:`OPERATOR`,value:t};return null}let Wc=new Set(`0123456789`);function Gc(e,t){if(!Wc.has(e.current)&&e.current!==t.decimalSeparator)return null;let n=e.remaining().match(Ei(t.decimalSeparator));return n?(e.advanceBy(n[0].length),{type:`NUMBER`,value:n[0]}):null}function Kc(e){if(e.current===`"`){let t=e.shift(),n=t;for(;e.current&&(e.current!==t||n[n.length-1]===`\\`);)n+=e.shift();return e.current===`"`&&(n+=e.shift()),{type:`STRING`,value:n}}return null}let qc=/\p{L}|\p{N}|_|\.|!|\$/u,Jc=new Set(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$`);function Yc(e){let t=``;if(e.current===`'`){let n=e.shift();for(t+=n;e.current;)if(n=e.shift(),t+=n,n===`'`)if(e.current&&e.current===`'`)n=e.shift(),t+=n;else break;if(n!==`'`)return{type:`UNKNOWN`,value:t}}for(;e.current&&(Jc.has(e.current)||e.current.match(qc));)t+=e.shift();if(t.length){let e=t;return Fs.test(e)?{type:`REFERENCE`,value:e}:{type:`SYMBOL`,value:e}}return null}function Xc(e){let t=``;for(;e.current===` `||e.current&&e.current.match(Nt);)t+=e.shift();return t?{type:`SPACE`,value:t}:null}function Zc(e){let t=``;for(;e.current===` `;)t+=e.shift();return t?{type:`SPACE`,value:t}:null}function Qc(e){let t=0;for(;e.current===`
6
+ `):[t];for(let t of a){let a=t.includes(` `)?t.split(` `):[t];if(!r){i.push(t);continue}let o=``,s=r;for(let t of a){let a=hc(e,t,r,n),c=a.pop(),l=sc(e,c,n);if(a.length)o!==``&&(i.push(o),o=``,s=r),a.forEach(e=>{i.push(e)}),o=c,s=r-l;else{let t=o===``?c:` `+c,a=sc(e,t,n);a<=s?(o+=t,s-=a):(i.push(o),o=c,s=r-l)}}o!==``&&i.push(o)}return i}function _c(e,t,n,r=.25){let i=1;if(n(i)>e)return i;if(n(t)<e)return t;let a=(i+t)/2,o=n(a),s=0;for(;Math.abs(o-e)>r&&s<20;)o>=e?t=(i+t)/2:i=(i+t)/2,a=(i+t)/2,o=n(a),s++;return a}function vc(e){return mc(e)+8}function yc(e){return e?e.toLowerCase():``}let bc=/([0-9\.]*)px/;function xc(e){return Number(e.match(bc)?.[1])}function Sc(e,t,n){let r=cc(e,t);if(r<=n)return t;let i=cc(e,`…`);if(r<=i)return t;let a=t.length;for(;r>=n-i&&a-->0;)t=t.substring(0,a),r=cc(e,t);return t+`…`}function Cc(e,t,n,r=!1,i=!1,a=xc(e.font)/10){if(e.fillText(t,n.x,n.y),!r&&!i)return;let o=e.measureText(t),s=o.width,c=o.actualBoundingBoxAscent+o.actualBoundingBoxDescent,l=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent,{x:u,y:d}=n,f=d,p=d;switch(e.textAlign){case`center`:u-=s/2;break;case`right`:u-=s;break}switch(e.textBaseline){case`top`:p+=l-2*a,f+=l/2-a;break;case`middle`:p+=l/2-a;break;case`alphabetic`:p+=2*a,f-=3*a;break;case`bottom`:p=d,f-=c/2-a/2;break}r&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,p),e.lineTo(u+s,p),e.stroke()),i&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,f),e.lineTo(u+s,f),e.stroke())}var wc=class{isFastIdStrategy=!1;fastIdStart=0;setIsFastStrategy(e){this.isFastIdStrategy=e}smallUuid(){return this.isFastIdStrategy?(this.fastIdStart++,String(this.fastIdStart)):window.crypto?`10000000-1000`.replace(/[01]/g,e=>{let t=Number(e);return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)}):`xxxxxxxx-xxxx`.replace(/[xy]/g,function(e){var t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}uuidv4(){return this.isFastIdStrategy?(this.fastIdStart++,String(this.fastIdStart)):window.crypto?`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>{let t=Number(e);return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)}):`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(e){var t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}};function Tc(e,t){let n=new Set(t.map(e=>e.left)),r=new Set(t.map(e=>e.right)),i=new Set(t.map(e=>e.top)),a=new Set(t.map(e=>e.bottom)),o=i.size===1&&a.size===1||n.size===1&&r.size===1?xr(t):[t[t.length-1]],s=o.map(e=>_r(e)).flat();return{sheetId:e,zones:t,clippedZones:o,columnsIndexes:[...new Set(s.map(e=>e.col))].sort((e,t)=>e-t),rowsIndexes:[...new Set(s.map(e=>e.row))].sort((e,t)=>e-t)}}function Ec(e,t,n){let r=Math.max(e.right-t+1,e.left),i=Math.max(e.bottom-n+1,e.top),a=[];for(let o=e.left;o<=r;o+=t)for(let r=e.top;r<=i;r+=n)a.push({left:o,top:r,bottom:r+n-1,right:o+t-1});return a}function Dc(e,t){if(!t.length||!t[0].length)return e;let n=t[0].length,r=t.length;return e.map(e=>Ec(e,n,r)).flat()}function Oc(e){if(!e[`text/html`])return{text:e[`text/plain`]};let t=new DOMParser().parseFromString(e[`text/html`],`text/html`);return{text:e[`text/plain`],data:kc(t)}}function kc(e){if([...e.documentElement.attributes].some(e=>e.value.includes(`microsoft`)))return;let t=e.querySelector(`div`)?.getAttribute(`data-osheet-clipboard`);return t&&JSON.parse(t)}let Ac=(e,t,n,r)=>{e.forEach(({handlerName:e,handler:i})=>{let a=t[e];a&&i.paste(n,a,r)})};function jc(e,t,n,r,i){let a,o=[],s={sheetId:e,zones:t};for(let{handlerName:c,handler:l}of r){let r=n[c];if(!r)continue;let u=l.getPasteTarget(e,t,r,i);u.figureId&&(s.figureId=u.figureId);for(let e of u.zones){if(o.push(e),a===void 0){a=e;continue}a=or(a,e)}}return{target:s,zone:a,selectedZones:o}}let Mc=(e,t,n)=>{let r={col:t[0].left,row:t[0].top};e.getBackToDefault(),e.selectZone({cell:r,zone:or(...n)},{scrollIntoView:!1})};var Nc=class{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t=`copyPaste`){}paste(e,t,n){}isPasteAllowed(e,t,n,r){return`Success`}isCutAllowed(e){return`Success`}getPasteTarget(e,t,n,r){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}},Pc=class extends Nc{copy(e,t=`copyPaste`){}pasteFromCopy(e,t,n,r){if(t.length===1)for(let i of Dc(t,n))this.pasteZone(e,i.left,i.top,n,r);else for(let i of T(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++)this.pasteZone(e,t,a,n,r)}pasteZone(e,t,n,r,i){}},Fc=class extends Pc{queuedBordersToAdd={};copy(e){let t=e.sheetId;if(e.zones.length===0)return;let{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getCellBorder(r))}i.push(n)}return{borders:i}}paste(e,t,n){let r=e.sheetId;if(n.pasteOption===`asValue`)return;let i=e.zones;if(!n.isCutOperation)this.pasteFromCopy(r,i,t.borders);else{let{left:e,top:n}=i[0];this.pasteZone(r,e,n,t.borders)}this.executeQueuedChanges(r)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteBorder(o,a)}}pasteBorder(e,t){let n={...this.getters.getCellBorder(t),...e},r=JSON.stringify(n);this.queuedBordersToAdd[r]||(this.queuedBordersToAdd[r]=[]),this.queuedBordersToAdd[r].push(D(t))}executeQueuedChanges(e){for(let t in this.queuedBordersToAdd){let n=this.queuedBordersToAdd[t],r=JSON.parse(t),i=T(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}};let Ic=[`%`],Lc=`+,-,*,/,:,=,<>,>=,>,<=,<,^,&`.split(`,`).concat(Ic);function Rc(e,t=k){e=It(e);let n=new qt(e),r=[],i=Nt.test(e)?Xc:Zc;for(;!n.isOver();){let e=Qc(n)||i(n)||Hc(n,t)||Vc(n)||Uc(n)||Kc(n)||zc(n)||$c(n)||Gc(n,t)||Yc(n);e||={type:`UNKNOWN`,value:n.shift()},r.push(e)}return r}function zc(e){return e.current===`?`?(e.shift(),{type:`DEBUGGER`,value:`?`}):null}let Bc={"(":{type:`LEFT_PAREN`,value:`(`},")":{type:`RIGHT_PAREN`,value:`)`}};function Vc(e){return e.current===`(`||e.current===`)`?Bc[e.shift()]:null}function Hc(e,t){return e.current===t.formulaArgSeparator?{type:`ARG_SEPARATOR`,value:e.shift()}:null}function Uc(e){for(let t of Lc)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:`OPERATOR`,value:t};return null}let Wc=new Set(`0123456789`);function Gc(e,t){if(!Wc.has(e.current)&&e.current!==t.decimalSeparator)return null;let n=e.remaining().match(Ei(t.decimalSeparator));return n?(e.advanceBy(n[0].length),{type:`NUMBER`,value:n[0]}):null}function Kc(e){if(e.current===`"`){let t=e.shift(),n=t;for(;e.current&&(e.current!==t||n[n.length-1]===`\\`);)n+=e.shift();return e.current===`"`&&(n+=e.shift()),{type:`STRING`,value:n}}return null}let qc=/\p{L}|\p{N}|_|\.|!|\$/u,Jc=new Set(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$`);function Yc(e){let t=``;if(e.current===`'`){let n=e.shift();for(t+=n;e.current;)if(n=e.shift(),t+=n,n===`'`)if(e.current&&e.current===`'`)n=e.shift(),t+=n;else break;if(n!==`'`)return{type:`UNKNOWN`,value:t}}for(;e.current&&(Jc.has(e.current)||e.current.match(qc));)t+=e.shift();if(t.length){let e=t;return Fs.test(e)?{type:`REFERENCE`,value:e}:{type:`SYMBOL`,value:e}}return null}function Xc(e){let t=``;for(;e.current===` `||e.current&&e.current.match(Nt);)t+=e.shift();return t?{type:`SPACE`,value:t}:null}function Zc(e){let t=``;for(;e.current===` `;)t+=e.shift();return t?{type:`SPACE`,value:t}:null}function Qc(e){let t=0;for(;e.current===`
7
7
  `;)t++,e.shift();return t?{type:`SPACE`,value:`
8
- `.repeat(t)}:null}function $c(e){return e.currentStartsWith(j.InvalidReference)?(e.advanceBy(j.InvalidReference.length),{type:`INVALID_REFERENCE`,value:j.InvalidReference}):null}function el(e){if(!e||typeof e!=`object`||!(!e.thousandsSeparator||typeof e.thousandsSeparator==`string`))return!1;for(let t of[`code`,`name`,`decimalSeparator`,`dateFormat`,`timeFormat`,`formulaArgSeparator`])if(!e[t]||typeof e[t]!=`string`)return!1;if(e.formulaArgSeparator===e.decimalSeparator||e.thousandsSeparator===e.decimalSeparator)return!1;try{B(1,{locale:e,format:`#,##0.00`}),B(1,{locale:e,format:e.dateFormat}),B(1,{locale:e,format:e.timeFormat})}catch{return!1}return!0}function tl(e,t){return e.startsWith(`=`)?al(e,t):cl(e,t)}function nl(e,t){return e.startsWith(`=`)?al(e,t):ll(e,t)}function rl(e,t){return e.startsWith(`=`)?ol(e,t):dl(e,t)}function il(e,t){return e.startsWith(`=`)?al(e,t):cl(e,t)}function al(e,t){return sl(e,t,k)}function ol(e,t){return sl(e,k,t)}function sl(e,t,n){if(t.formulaArgSeparator===n.formulaArgSeparator&&t.decimalSeparator===n.decimalSeparator)return e;let r=Rc(e,t),i=``;for(let e of r)e.type===`NUMBER`?i+=e.value.replace(t.decimalSeparator,n.decimalSeparator):e.type===`ARG_SEPARATOR`?i+=n.formulaArgSeparator:i+=e.value;return i}function cl(e,t){return t.decimalSeparator===`.`||!Oi(e,t)?e:(t.thousandsSeparator&&(e=e.replaceAll(t.thousandsSeparator,``)),e.replace(t.decimalSeparator,`.`))}function ll(e,t){if(Xr(e,t)){let n=F(e,t),r=k.dateFormat;return Number.isInteger(n)||(r+=` `+k.timeFormat),B(n,{locale:k,format:r})}return cl(e,t)}function ul(e,t){if(t.decimalSeparator===`.`||!Oi(e,k))return e;let n=Jo(k);return e.replace(n,e=>e.replace(`.`,t.decimalSeparator))}function dl(e,t){if(Xr(e,k)){let n=F(e,k),r=t.dateFormat;return Number.isInteger(n)||(r+=` `+t.timeFormat),B(n,{locale:t,format:r})}return ul(e,t)}function fl(e,t){return hl(e,e=>nl(e,t))}function pl(e,t){return hl(e,e=>rl(e,t))}function ml(e,t){let n=y(e);return n.criterion.values=n.criterion.values.map(e=>rl(e,t)),n}function hl(e,t){switch(e=y(e),e.type){case`CellIsRule`:switch(e.operator){case`Between`:case`NotBetween`:case`Equal`:case`NotEqual`:case`GreaterThan`:case`GreaterThanOrEqual`:case`LessThan`:case`LessThanOrEqual`:return e.values=e.values.map(e=>t(e)),e;case`BeginsWith`:case`ContainsText`:case`EndsWith`:case`NotContains`:case`IsEmpty`:case`IsNotEmpty`:return e}case`DataBarRule`:return e;case`ColorScaleRule`:return e.minimum=gl(e.minimum,t),e.maximum=gl(e.maximum,t),e.midpoint&&=gl(e.midpoint,t),e;case`IconSetRule`:return e.lowerInflectionPoint.value=t(e.lowerInflectionPoint.value),e.upperInflectionPoint.value=t(e.upperInflectionPoint.value),e}}function gl(e,t){if(!e?.value)return e;let n=t(e.type===`formula`?`=`+e.value:e.value),r=e.type===`formula`?n.slice(1):n;return{...e,value:r}}function _l(e){return e.dateFormat+` `+e.timeFormat}function vl(e){let t=!1,n=!0;return La(e,e=>(t=!0,n&&=e,n)),{foundBoolean:t,result:n}}function yl(e){let t=!1,n=!1;return La(e,e=>(t=!0,n||=e,!n)),{foundBoolean:t,result:n}}function bl(e,t){return ka(e,(e,t)=>e+t,0,t)}function xl(e){return Oa(e,(e,t)=>Ja(t)?e.add(t?.value):e,new Set).size}function Sl(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=Array(e).fill(0),t[n][n]=1;return t}function Cl(e){if(e.length<1||e[0].length<1)throw Error(`invertMatrix: an empty matrix cannot be inverted.`);if(e.length!==e[0].length)throw Error(`invertMatrix: only square matrices are invertible`);let t=1,n=e.length,r=Sl(n),i=e.map(e=>e.slice());for(let e=0;e<n;e++){let a=i[e][e];if(a===0){for(let a=e+1;a<n;a++)if(i[e][a]!==0){wl(i,e,a),wl(r,e,a),t*=-1;break}if(a=i[e][e],a===0)return{determinant:0}}for(let t=0;t<n;t++)i[t][e]=i[t][e]/a,r[t][e]=r[t][e]/a;t*=a;for(let t=0;t<n;t++){if(t===e)continue;let a=i[e][t];for(let o=0;o<n;o++)i[o][t]-=a*i[o][e],r[o][t]-=a*r[o][e]}}return{inverted:r,determinant:t}}function wl(e,t,n){for(let r=0;r<e.length;r++){let i=e[r][t];e[r][t]=e[r][n],e[r][n]=i}}function Tl(e,t){if(e.length<1||t.length<1)throw Error(`multiplyMatrices: empty matrices cannot be multiplied.`);if(e.length!==t[0].length)throw Error(`multiplyMatrices: incompatible matrices size.`);let n=e[0].length,r=t.length,i=e.length,a=Array(r);for(let o=0;o<r;o++){a[o]=Array(n);for(let r=0;r<n;r++){let n=0;for(let a=0;a<i;a++)n+=e[a][r]*t[o][a];a[o][r]=n}}return a}function El(e){if(!A(e))return e;if(!Dl(e))throw Error(`The value should be a scalar or a 1x1 matrix`);return e[0][0]}function Dl(e){return e.length===1&&e[0].length===1}function Ol(e){return A(e)&&!Dl(e)}function kl(...e){let t=e[0].length;e.forEach((e,n)=>N(()=>e.length===t,E(`[[FUNCTION_NAME]] has mismatched dimensions for argument %s (%s vs %s).`,n.toString(),t.toString(),e.length.toString())))}function Al(e,t){let n=0,r=ka(e,(e,t)=>(n+=1,e+t),0,t);return ya(n),r/n}function jl(e,t){let n=0;for(let r of e)if(A(r))for(let e of r)for(let t of e)typeof t.value==`number`&&(n+=1);else{let e=r?.value;!P(e)&&(typeof e!=`string`||Oi(e,t)||Qr(e,t))&&(n+=1)}return n}function Ml(e){return Oa(e,(e,t)=>t!==void 0&&t.value!==null?e+1:e,0)}function Nl(e,t){let n={value:-1/0};return Ea(e,e=>{e.value>=n.value&&(n=e)},t),n.value===-1/0?{value:0}:n}function Pl(e,t){let n={value:1/0};return Ea(e,e=>{e.value<=n.value&&(n=e)},t),n.value===1/0?{value:0}:n}function Fl(e,t,n){let r=e[0].length?e:[x(1,t.flat().length+1)],i=r.length,a=n[0].length?n:r;return a=a.length===i?Pa(a):a,{_X:r,_newX:a}}function Il(e,t,n=!0,r=!1){let i=t.flat(),a=i.length,{_X:o}=Fl(e,t,[[]]);o=o.length===a?Pa(o):o.slice(),kl(o[0],i);let s=o.length,c=a-s-+!!n,l=[i],u=Pa(o.reverse()),d=[];for(let e=0;e<s;e++)if(d.push(0),n){for(let t of o[e])d[e]+=t;d[e]/=a}let f=0;if(n){for(let e of i)f+=e;f/=a}let p=u.map(e=>e.map((e,t)=>e-d[t]));n&&u.forEach(e=>e.push(1));let m=Rl(u,l);if(n||m.push([0]),!r)return m;let{inverted:h}=Cl(Tl(p,Pa(p)));if(h===void 0)throw new M(E(`Matrix is not invertible`));let g=0,_=0;for(let e=0;e<a;e++){let t=i[e]-f,n=0;for(let t=0;t<s;t++){let r=p[e][t];n+=r*m[t][0]}let r=t-n;g+=r*r,_+=n*n}let v=Math.sqrt(g/c),ee=_/(_+g),te=_/s/(g/c),ne=[];for(let e=0;e<s;e++)ne.push(v*Math.sqrt(h[e][e]));if(n){let e=Tl(h,[d]),t=Tl(Pa([d]),e);ne.push(v*Math.sqrt(t[0][0]+1/i.length))}let re=[[m[0][0],ne[0],ee,te,_],[m[1][0],ne[1],v,c,g]];for(let e=2;e<s;e++)re.push([m[e][0],ne[e],``,``,``]);return n?re.push([m[s][0],ne[s],``,``,``]):re.push([0,``,``,``,``]),re}function Ll(e,t,n,r){kl(t,e),N(()=>n>=1,E(`Function [[FUNCTION_NAME]] A regression of order less than 1 cannot be possible.`));let i=[e],a=t.map(e=>x(0,n).map(t=>e**+(n-t)));r&&a.forEach(e=>e.push(1));let o=Rl(a,i);return r||o.push([0]),o}function Rl(e,t){let{inverted:n}=Cl(Tl(e,Pa(e)));if(n===void 0)throw new M(E(`Matrix is not invertible`));return Pa(Tl(n,Tl(e,t)))}function zl(e,t,n){return e.reduce((e,r,i)=>e+r*t**+(n-i),0)}function Bl(e){return e.map(e=>e.map(e=>Math.exp(e)))}function Vl(e){return e.map(e=>e.map(e=>Math.log(e)))}function Hl(e,t,n,r){let{_X:i,_newX:a}=Fl(t,e,n),o=Il(i,e,r,!1),s=o.length-1,c=a.map(e=>{let t=0;for(let n=0;n<s;n++)t+=o[n][0]*e[s-n-1];return t+=o[s][0],[t]});return c.length===n.length?c:Pa(c)}function Ul(e,t){N(()=>e.length>0&&e[0].length>0,E(`[[FUNCTION_NAME]] expects the provided values of %(argName)s to be a non-empty matrix.`,{argName:t}))}function Wl(...e){if(e.length===0||e.some(e=>e.length===0))throw new aa(E(`[[FUNCTION_NAME]] has no valid input data.`))}let Gl=`(previous)`;function Kl(e,t){let{colDomain:n,rowDomain:r}=Jl(e,t);return[...n,...r.slice(0,r.length-1)]}function ql(e,t){let{colDomain:n,rowDomain:r}=Jl(e,t);return[...n.slice(0,n.length-1),...r]}function Jl(e,t){let n=e.definition.rows.map(e=>e.nameWithGranularity),r=t.filter(e=>n.includes(e.field)),i=e.definition.columns.map(e=>e.nameWithGranularity);return{colDomain:t.filter(e=>i.includes(e.field)),rowDomain:r}}function Yl(e,t,n){return t===`column`?Jl(e,n).colDomain:Jl(e,n).rowDomain}function Xl(e,t){return t.find(t=>t.field===e)?.value}function Zl(e,t){let{rowDomain:n,colDomain:r}=Jl(e,t);return Ql(n,e.getTableStructure().getRowTree())&&Ql(r,e.getTableStructure().getColTree())}function Ql(e,t){return $l(e,t)!==void 0}function $l(e,t,n){let r=t;for(let t of e){let e=r.find(e=>e.value===t.value);if(!e)return;if(e.field===n)return r;r=e.children}return r}function eu(e,t,n){let{rowDomain:r,colDomain:i}=Jl(e,n);if(ru(e,t)===`row`){let e=r.findIndex(e=>e.field===t);if(e===-1)return n;r=r.slice(0,e+1)}else{let e=i.findIndex(e=>e.field===t);if(e===-1)return n;i=i.slice(0,e+1)}return[...r,...i]}function tu(e,t,n){e=y(e);let r=e.find(e=>e.field===t);return r&&(r.value=n),e}function nu(e,t){return t.some(t=>t.field===e)}function ru(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 Error(`Field ${t} not found in pivot`)}function iu(e,t,n,r){let i=ru(e,n),a=i===`row`?e.getTableStructure().getRowTree():e.getTableStructure().getColTree(),o=$l(Yl(e,i,t),a,n)?.map(e=>e.value)??[],s=Xl(n,t);if(s===void 0)return;let c=o.indexOf(s);if(!(s===void 0||c===-1))return tu(t,n,o[b(c+(r===`(previous)`?-1:1),0,o.length-1)])}function au(e){return e?e.map(ou).join(`, `):``}function ou(e){return e?`${e.field}=${e.value}`:``}function su(e,t){let n=e.findIndex(e=>e.field===t);if(n===-1)return``;let r=e.slice(0,n),i=e.at(-1);return au(i.field===t?r:[...r,i])}function cu(e,t){let n=e.findIndex(e=>e.field===t);return n===-1?``:au([...e.slice(0,n),...e.slice(n+1)])}let lu=new h;function uu(e){return lu.get(e)}let du={normalizeFunctionValue(e){return F(e,k)},toValueAndFormat(e,t){return{value:F(e,k),format:`dd mmm yyyy`}},toFunctionValue(e){return`"${B(F(e,k),{locale:k,format:`mm/dd/yyyy`})}"`}},fu={normalizeFunctionValue(e){let t=F(e,k);if(t<1||t>31)throw new M(E(`%s is not a valid day of month (it should be a number between 1 and 31)`,t));return t},toValueAndFormat(e){return{value:F(e,k),format:`0`}},toFunctionValue(e){return`${e}`}},pu={normalizeFunctionValue(e){let t=F(e,k);if(t<1||t>7)throw new M(E(`%s is not a valid day of week (it should be a number between 1 and 7)`,t));return t},toValueAndFormat(e,t){return{value:Mo[(e-1+(t||k).weekStart)%7].toString(),format:`@`}},toFunctionValue(e){return`${e}`}},mu={normalizeFunctionValue(e){let t=F(e,k);if(t<0||t>53)throw new M(E(`%s is not a valid week (it should be a number between 0 and 53)`,t));return t},toValueAndFormat(e){return{value:F(e,k),format:`0`}},toFunctionValue(e){return`${e}`}},hu={normalizeFunctionValue(e){let t=F(e,k);if(t<1||t>12)throw new M(E(`%s is not a valid month (it should be a number between 1 and 12)`,t));return t},toValueAndFormat(e){return{value:jo[F(e,k)-1].toString(),format:`@`}},toFunctionValue(e){return`${e}`}},gu={normalizeFunctionValue(e){return B(F(e,k),{locale:k,format:`mm/yyyy`})},toValueAndFormat(e){return{value:F(e,k),format:`mmmm yyyy`}},toFunctionValue(e){return`"${e}"`}},_u={normalizeFunctionValue(e){let t=F(e,k);if(t<1||t>4)throw new M(E(`%s is not a valid quarter (it should be a number between 1 and 4)`,t));return t},toValueAndFormat(e){return{value:E(`Q%(quarter_number)s`,{quarter_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},vu={normalizeFunctionValue(e){return F(e,k)},toValueAndFormat(e){return{value:F(e,k),format:`0`}},toFunctionValue(e){return`${e}`}},yu={normalizeFunctionValue(e){let t=F(e,k);if(t<0||t>23)throw new M(E(`%s is not a valid hour (it should be a number between 0 and 23)`,t));return t},toValueAndFormat(e){return{value:E(`%(hour_number)sh`,{hour_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},bu={normalizeFunctionValue(e){let t=F(e,k);if(t<0||t>59)throw new M(E(`%s is not a valid minute (it should be a number between 0 and 59)`,t));return t},toValueAndFormat(e){return{value:E(`%(minute_number)s'`,{minute_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},xu={normalizeFunctionValue(e){let t=F(e,k);if(t<0||t>59)throw new M(E(`%s is not a valid second (it should be a number between 0 and 59)`,t));return t},toValueAndFormat(e){return{value:E(`%(second_number)s''`,{second_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}};function Su(e){return{normalizeFunctionValue(t){return t===null?null:e.normalizeFunctionValue(t)},toValueAndFormat(t,n){return t===null?{value:E(`(Undefined)`)}:e.toValueAndFormat(t,n)},toFunctionValue(t){return t===null?`false`:e.toFunctionValue(t)}}}lu.add(`day`,Su(du)).add(`year`,Su(vu)).add(`day_of_month`,Su(fu)).add(`iso_week_number`,Su(mu)).add(`month_number`,Su(hu)).add(`month`,Su(gu)).add(`quarter_number`,Su(_u)).add(`day_of_week`,Su(pu)).add(`hour_number`,Su(yu)).add(`minute_number`,Su(bu)).add(`second_number`,Su(xu));let Cu={count:E(`Count`),count_distinct:E(`Count Distinct`),bool_and:E(`Boolean And`),bool_or:E(`Boolean Or`),max:E(`Maximum`),min:E(`Minimum`),avg:E(`Average`),sum:E(`Sum`)},wu=[`max`,`min`,`avg`,`sum`,`count_distinct`,`count`],Tu={integer:wu,char:wu,boolean:[`count_distinct`,`count`,`bool_and`,`bool_or`]},Eu={};for(let e in Tu){Eu[e]={};for(let t of Tu[e])Eu[e][t]=Cu[t]}let Du={count:e=>({value:Ml([e]),format:`0`}),count_distinct:e=>({value:xl([e]),format:`0`}),bool_and:e=>({value:vl([e]).result}),bool_or:e=>({value:yl([e]).result}),max:(e,t)=>Nl([e],t),min:(e,t)=>Pl([e],t),avg:(e,t)=>({value:Al([e],t),format:la(e)}),sum:(e,t)=>({value:bl([e],t),format:la(e)})};function Ou(e){let t=Object.keys(e);if(!t.length)return 0;let n=t.map(e=>parseInt(e,10));return Math.max(...n)}let ku={year:E(`Year`),quarter:E(`Quarter & Year`),month:E(`Month & Year`),week:E(`Week & Year`),day:E(`Day`),quarter_number:E(`Quarter`),month_number:E(`Month`),iso_week_number:E(`Week`),day_of_month:E(`Day of Month`),day_of_week:E(`Day of Week`),hour_number:E(`Hour`),minute_number:E(`Minute`),second_number:E(`Second`)},Au=[`date`,`datetime`];function ju(e){let[t,n]=e.split(`:`);return n?{fieldName:t,granularity:n}:{fieldName:t}}function Mu(e){return Au.includes(e.type)}function Nu(e,t,n){let r=[e];n&&r.push(`"${n}"`);for(let{field:e,value:n,type:i}of t){if(e===`measure`){r.push(`"measure"`,`"${n}"`);continue}let{granularity:t}=ju(e),a=Ru(n,{type:i,granularity:t});r.push(`"${e}"`,a)}return r}function Pu(e,t){let n=0,r=0,i=t.columns.map(e=>e.nameWithGranularity),a=t.rows.map(e=>e.nameWithGranularity);for(;e[n]!==void 0&&e[n]===a[r];)n++,r++;for(r=0;e[n]!==void 0&&e[n]===i[r];)n++,r++;return e.length===n}function Fu(e,t){switch(t.type){case`HEADER`:return`=PIVOT.HEADER(${Nu(e,t.domain).join(`,`)})`;case`VALUE`:return`=PIVOT.VALUE(${Nu(e,t.domain,t.measure).join(`,`)})`;case`MEASURE_HEADER`:return`=PIVOT.HEADER(${Nu(e,[...t.domain,{field:`measure`,value:t.measure,type:`char`}]).join(`,`)})`}return``}function Iu(e,t){if(t===null||t===`null`)return null;let n=typeof t==`object`?t.value:t;if(P(n))return n;let r=typeof t==`boolean`?I(t).toLocaleLowerCase():I(t);if(r===`null`)return null;if(!Bu.contains(e.type))throw new M(E(`Field %(field)s is not supported because of its type (%(type)s)`,{field:e.displayName,type:e.type}));return r.toLowerCase()===`false`?!1:Bu.get(e.type)(r,e.granularity)}function Lu(e,t){return uu(t??`month`).normalizeFunctionValue(e)}function Ru(e,t){return e===null?`"null"`:Vu.contains(t.type)?Vu.get(t.type)(e,t.granularity):`"${e}"`}function zu(e,t){return uu(t??`month`).toFunctionValue(e)}let Bu=new h;Bu.add(`date`,Lu).add(`datetime`,Lu).add(`integer`,e=>F(e,k)).add(`boolean`,e=>L(e)).add(`char`,e=>I(e));let Vu=new h;Vu.add(`date`,zu).add(`datetime`,zu).add(`integer`,e=>`${F(e,k)}`).add(`boolean`,e=>L(e)?`TRUE`:`FALSE`).add(`char`,e=>`"${I(e).replace(/"/g,`\\"`)}"`);function Hu(e){return e.displayName+(e.granularity?` (${ku[e.granularity]})`:``)}function Uu(e,t,n){let{rowDomain:r,colDomain:i}=Jl(e,t);if(r.length===0&&i.length===0)return n;if(r.length===0&&i.length>0)return{...n,format:(n.format||`@`)+`* `};let a=r.length-1,o=n.format||`@`;return{...n,format:`${` `.repeat(a)}${o}* `}}var Wu=class extends Pc{isCutAllowed(e){return e.zones.length===1?`Success`:`WrongCutSelection`}copy(e,t=`copyPaste`){let n=e.sheetId,{clippedZones:r,rowsIndexes:i,columnsIndexes:a}=e,o=[],s=i.length===1&&a.length===1;for(let r of i){let c=[];for(let o of a){let l={col:o,row:r,sheetId:n},u=this.getters.getCell(l),d=this.getters.getEvaluatedCell(l),f=this.getters.getPivotIdFromPosition(l),p=this.getters.getArrayFormulaSpreadingOn(l);if(t!==`shiftCells`&&f&&p){let t=this.getters.getSpreadZone(p);if((!C(p,l)||!s)&&t&&!e.zones.some(e=>fr(t,e))){let e=this.getters.getPivotCellFromPosition(l),t=Fu(this.getters.getPivotFormulaId(f),e);u={id:u?.id||``,style:u?.style,format:u?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if(t!==`shiftCells`&&p&&!C(p,l)){let e=i.includes(p.row)&&a.includes(p.col)?``:B(d.value,{locale:this.getters.getLocale()});u={id:u?.id||``,style:u?.style,format:d.format,content:e,isFormula:!1,parsedValue:d.value}}c.push({content:u?.content??``,style:u?.style,format:u?.format,tokens:u?.isFormula?u.compiledFormula.tokens.map(({value:e,type:t})=>({value:e,type:t})):[],border:this.getters.getCellBorder(l)||void 0,evaluatedCell:d,position:l})}o.push(c)}return{cells:o,zones:r,sheetId:e.sheetId}}isPasteAllowed(e,t,n,r){if(!n.cells)return`Success`;if(r?.isCutOperation&&r?.pasteOption!==void 0)return`WrongPasteOption`;if(t.length>1&&(n.cells.length>1||n.cells[0].length>1))return`WrongPasteSelection`;let i=n.cells.length,a=n.cells[0].length;for(let r of Dc(t,n.cells))if(this.getters.doesIntersectMerge(e,r)&&(t.length>1||!this.getters.isSingleCellOrMerge(e,t[0])||i*a!==1))return`WillRemoveExistingMerge`;return`Success`}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.cells,n)}getPasteTarget(e,t,n,r){let i=n.cells[0].length,a=n.cells.length;return r?.isCutOperation?{sheetId:e,zones:[{left:t[0].left,top:t[0].top,right:t[0].left+i-1,bottom:t[0].top+a-1}]}:i===1&&a===1?{zones:[],sheetId:e}:{sheetId:e,zones:Dc(t,n.cells)}}pasteFromCut(e,t,n,r){this.clearClippedZones(n);let i=t[0];this.pasteZone(e,i.left,i.top,n.cells,r)}clearClippedZones(e){this.dispatch(`CLEAR_CELLS`,{sheetId:e.sheetId,target:e.zones}),this.dispatch(`CLEAR_FORMATTING`,{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){if(!s)continue;let o={col:t+r,row:n+a,sheetId:e};this.pasteCell(s,o,i)}}pasteCell(e,t,n){let{sheetId:r,col:i,row:a}=t,o=this.getters.getEvaluatedCell(t),s=e?.format||e.evaluatedCell.format;if(n?.pasteOption===`asValue`){this.dispatch(`UPDATE_CELL`,{...t,content:e.evaluatedCell.value?.toString()||``});return}if(n?.pasteOption===`onlyFormat`){this.dispatch(`UPDATE_CELL`,{...t,style:e?.style??null,format:s??o.format});return}let c=e?.content;e?.tokens&&e.tokens.length>0&&!n?.isCutOperation?c=this.getters.getTranslatedCellFormula(r,i-e.position.col,a-e.position.row,e.tokens):e?.tokens&&e.tokens.length>0&&(c=this.getters.getFormulaMovedInSheet(e.position.sheetId,r,e.tokens)),c!==``||e?.format||e?.style?this.dispatch(`UPDATE_CELL`,{...t,content:c,style:e?.style||null,format:e?.format}):o&&this.dispatch(`CLEAR_CELL`,t)}convertTextToClipboardData(e){let t=this.getters.getLocale(),n={cells:[]},r=[],i=0;for(let[t,n]of e.replace(/\r/g,``).split(`
8
+ `.repeat(t)}:null}function $c(e){return e.currentStartsWith(j.InvalidReference)?(e.advanceBy(j.InvalidReference.length),{type:`INVALID_REFERENCE`,value:j.InvalidReference}):null}function el(e){if(!e||typeof e!=`object`||!(!e.thousandsSeparator||typeof e.thousandsSeparator==`string`))return!1;for(let t of[`code`,`name`,`decimalSeparator`,`dateFormat`,`timeFormat`,`formulaArgSeparator`])if(!e[t]||typeof e[t]!=`string`)return!1;if(e.formulaArgSeparator===e.decimalSeparator||e.thousandsSeparator===e.decimalSeparator)return!1;try{B(1,{locale:e,format:`#,##0.00`}),B(1,{locale:e,format:e.dateFormat}),B(1,{locale:e,format:e.timeFormat})}catch{return!1}return!0}function tl(e,t){return e.startsWith(`=`)?al(e,t):cl(e,t)}function nl(e,t){return e.startsWith(`=`)?al(e,t):ll(e,t)}function rl(e,t){return e.startsWith(`=`)?ol(e,t):dl(e,t)}function il(e,t){return e.startsWith(`=`)?al(e,t):cl(e,t)}function al(e,t){return sl(e,t,k)}function ol(e,t){return sl(e,k,t)}function sl(e,t,n){if(t.formulaArgSeparator===n.formulaArgSeparator&&t.decimalSeparator===n.decimalSeparator)return e;let r=Rc(e,t),i=``;for(let e of r)e.type===`NUMBER`?i+=e.value.replace(t.decimalSeparator,n.decimalSeparator):e.type===`ARG_SEPARATOR`?i+=n.formulaArgSeparator:i+=e.value;return i}function cl(e,t){return t.decimalSeparator===`.`||!Oi(e,t)?e:(t.thousandsSeparator&&(e=e.replaceAll(t.thousandsSeparator,``)),e.replace(t.decimalSeparator,`.`))}function ll(e,t){if(Xr(e,t)){let n=F(e,t),r=k.dateFormat;return Number.isInteger(n)||(r+=` `+k.timeFormat),B(n,{locale:k,format:r})}return cl(e,t)}function ul(e,t){if(t.decimalSeparator===`.`||!Oi(e,k))return e;let n=Jo(k);return e.replace(n,e=>e.replace(`.`,t.decimalSeparator))}function dl(e,t){if(Xr(e,k)){let n=F(e,k),r=t.dateFormat;return Number.isInteger(n)||(r+=` `+t.timeFormat),B(n,{locale:t,format:r})}return ul(e,t)}function fl(e,t){return hl(e,e=>nl(e,t))}function pl(e,t){return hl(e,e=>rl(e,t))}function ml(e,t){let n=y(e);return n.criterion.values=n.criterion.values.map(e=>rl(e,t)),n}function hl(e,t){switch(e=y(e),e.type){case`CellIsRule`:switch(e.operator){case`Between`:case`NotBetween`:case`Equal`:case`NotEqual`:case`GreaterThan`:case`GreaterThanOrEqual`:case`LessThan`:case`LessThanOrEqual`:return e.values=e.values.map(e=>t(e)),e;case`BeginsWith`:case`ContainsText`:case`EndsWith`:case`NotContains`:case`IsEmpty`:case`IsNotEmpty`:return e}case`DataBarRule`:return e;case`ColorScaleRule`:return e.minimum=gl(e.minimum,t),e.maximum=gl(e.maximum,t),e.midpoint&&=gl(e.midpoint,t),e;case`IconSetRule`:return e.lowerInflectionPoint.value=t(e.lowerInflectionPoint.value),e.upperInflectionPoint.value=t(e.upperInflectionPoint.value),e}}function gl(e,t){if(!e?.value)return e;let n=t(e.type===`formula`?`=`+e.value:e.value),r=e.type===`formula`?n.slice(1):n;return{...e,value:r}}function _l(e){return e.dateFormat+` `+e.timeFormat}function vl(e){let t=!1,n=!0;return La(e,e=>(t=!0,n&&=e,n)),{foundBoolean:t,result:n}}function yl(e){let t=!1,n=!1;return La(e,e=>(t=!0,n||=e,!n)),{foundBoolean:t,result:n}}function bl(e,t){return ka(e,(e,t)=>e+t,0,t)}function xl(e){return Oa(e,(e,t)=>Ja(t)?e.add(t?.value):e,new Set).size}function Sl(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=Array(e).fill(0),t[n][n]=1;return t}function Cl(e){if(e.length<1||e[0].length<1)throw Error(`invertMatrix: an empty matrix cannot be inverted.`);if(e.length!==e[0].length)throw Error(`invertMatrix: only square matrices are invertible`);let t=1,n=e.length,r=Sl(n),i=e.map(e=>e.slice());for(let e=0;e<n;e++){let a=i[e][e];if(a===0){for(let a=e+1;a<n;a++)if(i[e][a]!==0){wl(i,e,a),wl(r,e,a),t*=-1;break}if(a=i[e][e],a===0)return{determinant:0}}for(let t=0;t<n;t++)i[t][e]=i[t][e]/a,r[t][e]=r[t][e]/a;t*=a;for(let t=0;t<n;t++){if(t===e)continue;let a=i[e][t];for(let o=0;o<n;o++)i[o][t]-=a*i[o][e],r[o][t]-=a*r[o][e]}}return{inverted:r,determinant:t}}function wl(e,t,n){for(let r=0;r<e.length;r++){let i=e[r][t];e[r][t]=e[r][n],e[r][n]=i}}function Tl(e,t){if(e.length<1||t.length<1)throw Error(`multiplyMatrices: empty matrices cannot be multiplied.`);if(e.length!==t[0].length)throw Error(`multiplyMatrices: incompatible matrices size.`);let n=e[0].length,r=t.length,i=e.length,a=Array(r);for(let o=0;o<r;o++){a[o]=Array(n);for(let r=0;r<n;r++){let n=0;for(let a=0;a<i;a++)n+=e[a][r]*t[o][a];a[o][r]=n}}return a}function El(e){if(!A(e))return e;if(!Dl(e))throw Error(`The value should be a scalar or a 1x1 matrix`);return e[0][0]}function Dl(e){return e.length===1&&e[0].length===1}function Ol(e){return A(e)&&!Dl(e)}function kl(...e){let t=e[0].length;e.forEach((e,n)=>N(()=>e.length===t,E(`[[FUNCTION_NAME]] has mismatched dimensions for argument %s (%s vs %s).`,n.toString(),t.toString(),e.length.toString())))}function Al(e,t){let n=0,r=ka(e,(e,t)=>(n+=1,e+t),0,t);return ya(n),r/n}function jl(e,t){let n=0;for(let r of e)if(A(r))for(let e of r)for(let t of e)typeof t.value==`number`&&(n+=1);else{let e=r?.value;!P(e)&&(typeof e!=`string`||Oi(e,t)||Qr(e,t))&&(n+=1)}return n}function Ml(e){return Oa(e,(e,t)=>t!==void 0&&t.value!==null?e+1:e,0)}function Nl(e,t){let n={value:-1/0};return Ea(e,e=>{e.value>=n.value&&(n=e)},t),n.value===-1/0?{value:0}:n}function Pl(e,t){let n={value:1/0};return Ea(e,e=>{e.value<=n.value&&(n=e)},t),n.value===1/0?{value:0}:n}function Fl(e,t,n){let r=e[0].length?e:[x(1,t.flat().length+1)],i=r.length,a=n[0].length?n:r;return a=a.length===i?Pa(a):a,{_X:r,_newX:a}}function Il(e,t,n=!0,r=!1){let i=t.flat(),a=i.length,{_X:o}=Fl(e,t,[[]]);o=o.length===a?Pa(o):o.slice(),kl(o[0],i);let s=o.length,c=a-s-+!!n,l=[i],u=Pa(o.reverse()),d=[];for(let e=0;e<s;e++)if(d.push(0),n){for(let t of o[e])d[e]+=t;d[e]/=a}let f=0;if(n){for(let e of i)f+=e;f/=a}let p=u.map(e=>e.map((e,t)=>e-d[t]));n&&u.forEach(e=>e.push(1));let m=Rl(u,l);if(n||m.push([0]),!r)return m;let{inverted:h}=Cl(Tl(p,Pa(p)));if(h===void 0)throw new M(E(`Matrix is not invertible`));let g=0,_=0;for(let e=0;e<a;e++){let t=i[e]-f,n=0;for(let t=0;t<s;t++){let r=p[e][t];n+=r*m[t][0]}let r=t-n;g+=r*r,_+=n*n}let v=Math.sqrt(g/c),ee=_/(_+g),te=_/s/(g/c),ne=[];for(let e=0;e<s;e++)ne.push(v*Math.sqrt(h[e][e]));if(n){let e=Tl(h,[d]),t=Tl(Pa([d]),e);ne.push(v*Math.sqrt(t[0][0]+1/i.length))}let re=[[m[0][0],ne[0],ee,te,_],[m[1][0],ne[1],v,c,g]];for(let e=2;e<s;e++)re.push([m[e][0],ne[e],``,``,``]);return n?re.push([m[s][0],ne[s],``,``,``]):re.push([0,``,``,``,``]),re}function Ll(e,t,n,r){kl(t,e),N(()=>n>=1,E(`Function [[FUNCTION_NAME]] A regression of order less than 1 cannot be possible.`));let i=[e],a=t.map(e=>x(0,n).map(t=>e**+(n-t)));r&&a.forEach(e=>e.push(1));let o=Rl(a,i);return r||o.push([0]),o}function Rl(e,t){let{inverted:n}=Cl(Tl(e,Pa(e)));if(n===void 0)throw new M(E(`Matrix is not invertible`));return Pa(Tl(n,Tl(e,t)))}function zl(e,t,n){return e.reduce((e,r,i)=>e+r*t**+(n-i),0)}function Bl(e){return e.map(e=>e.map(e=>Math.exp(e)))}function Vl(e){return e.map(e=>e.map(e=>Math.log(e)))}function Hl(e,t,n,r){let{_X:i,_newX:a}=Fl(t,e,n),o=Il(i,e,r,!1),s=o.length-1,c=a.map(e=>{let t=0;for(let n=0;n<s;n++)t+=o[n][0]*e[s-n-1];return t+=o[s][0],[t]});return c.length===n.length?c:Pa(c)}function Ul(e,t){N(()=>e.length>0&&e[0].length>0,E(`[[FUNCTION_NAME]] expects the provided values of %(argName)s to be a non-empty matrix.`,{argName:t}))}function Wl(...e){if(e.length===0||e.some(e=>e.length===0))throw new aa(E(`[[FUNCTION_NAME]] has no valid input data.`))}let Gl=`(previous)`;function Kl(e,t){let{colDomain:n,rowDomain:r}=Jl(e,t);return[...n,...r.slice(0,r.length-1)]}function ql(e,t){let{colDomain:n,rowDomain:r}=Jl(e,t);return[...n.slice(0,n.length-1),...r]}function Jl(e,t){let n=e.definition.rows.map(e=>e.nameWithGranularity),r=t.filter(e=>n.includes(e.field)),i=e.definition.columns.map(e=>e.nameWithGranularity);return{colDomain:t.filter(e=>i.includes(e.field)),rowDomain:r}}function Yl(e,t,n){return t===`column`?Jl(e,n).colDomain:Jl(e,n).rowDomain}function Xl(e,t){return t.find(t=>t.field===e)?.value}function Zl(e,t){let{rowDomain:n,colDomain:r}=Jl(e,t);return Ql(n,e.getTableStructure().getRowTree())&&Ql(r,e.getTableStructure().getColTree())}function Ql(e,t){return $l(e,t)!==void 0}function $l(e,t,n){let r=t;for(let t of e){let e=r.find(e=>e.value===t.value);if(!e)return;if(e.field===n)return r;r=e.children}return r}function eu(e,t,n){let{rowDomain:r,colDomain:i}=Jl(e,n);if(ru(e,t)===`row`){let e=r.findIndex(e=>e.field===t);if(e===-1)return n;r=r.slice(0,e+1)}else{let e=i.findIndex(e=>e.field===t);if(e===-1)return n;i=i.slice(0,e+1)}return[...r,...i]}function tu(e,t,n){e=y(e);let r=e.find(e=>e.field===t);return r&&(r.value=n),e}function nu(e,t){return t.some(t=>t.field===e)}function ru(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 Error(`Field ${t} not found in pivot`)}function iu(e,t,n,r){let i=ru(e,n),a=i===`row`?e.getTableStructure().getRowTree():e.getTableStructure().getColTree(),o=$l(Yl(e,i,t),a,n)?.map(e=>e.value)??[],s=Xl(n,t);if(s===void 0)return;let c=o.indexOf(s);if(!(s===void 0||c===-1))return tu(t,n,o[b(c+(r===`(previous)`?-1:1),0,o.length-1)])}function au(e){return e?e.map(ou).join(`, `):``}function ou(e){return e?`${e.field}=${e.value}`:``}function su(e,t){let n=e.findIndex(e=>e.field===t);if(n===-1)return``;let r=e.slice(0,n),i=e.at(-1);return au(i.field===t?r:[...r,i])}function cu(e,t){let n=e.findIndex(e=>e.field===t);return n===-1?``:au([...e.slice(0,n),...e.slice(n+1)])}let lu=new h;function uu(e){return lu.get(e)}let du={normalizeFunctionValue(e){return F(e,k)},toValueAndFormat(e,t){return{value:F(e,k),format:`dd mmm yyyy`}},toFunctionValue(e){return`"${B(F(e,k),{locale:k,format:`mm/dd/yyyy`})}"`}},fu={normalizeFunctionValue(e){let t=F(e,k);if(t<1||t>31)throw new M(E(`%s is not a valid day of month (it should be a number between 1 and 31)`,t));return t},toValueAndFormat(e){return{value:F(e,k),format:`0`}},toFunctionValue(e){return`${e}`}},pu={normalizeFunctionValue(e){let t=F(e,k);if(t<1||t>7)throw new M(E(`%s is not a valid day of week (it should be a number between 1 and 7)`,t));return t},toValueAndFormat(e,t){return{value:Mo[(e-1+(t||k).weekStart)%7].toString(),format:`@`}},toFunctionValue(e){return`${e}`}},mu={normalizeFunctionValue(e){let t=F(e,k);if(t<0||t>53)throw new M(E(`%s is not a valid week (it should be a number between 0 and 53)`,t));return t},toValueAndFormat(e){return{value:F(e,k),format:`0`}},toFunctionValue(e){return`${e}`}},hu={normalizeFunctionValue(e){let t=F(e,k);if(t<1||t>12)throw new M(E(`%s is not a valid month (it should be a number between 1 and 12)`,t));return t},toValueAndFormat(e){return{value:jo[F(e,k)-1].toString(),format:`@`}},toFunctionValue(e){return`${e}`}},gu={normalizeFunctionValue(e){return B(F(e,k),{locale:k,format:`mm/yyyy`})},toValueAndFormat(e){return{value:F(e,k),format:`mmmm yyyy`}},toFunctionValue(e){return`"${e}"`}},_u={normalizeFunctionValue(e){let t=F(e,k);if(t<1||t>4)throw new M(E(`%s is not a valid quarter (it should be a number between 1 and 4)`,t));return t},toValueAndFormat(e){return{value:E(`Q%(quarter_number)s`,{quarter_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},vu={normalizeFunctionValue(e){return F(e,k)},toValueAndFormat(e){return{value:F(e,k),format:`0`}},toFunctionValue(e){return`${e}`}},yu={normalizeFunctionValue(e){let t=F(e,k);if(t<0||t>23)throw new M(E(`%s is not a valid hour (it should be a number between 0 and 23)`,t));return t},toValueAndFormat(e){return{value:E(`%(hour_number)sh`,{hour_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},bu={normalizeFunctionValue(e){let t=F(e,k);if(t<0||t>59)throw new M(E(`%s is not a valid minute (it should be a number between 0 and 59)`,t));return t},toValueAndFormat(e){return{value:E(`%(minute_number)s'`,{minute_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},xu={normalizeFunctionValue(e){let t=F(e,k);if(t<0||t>59)throw new M(E(`%s is not a valid second (it should be a number between 0 and 59)`,t));return t},toValueAndFormat(e){return{value:E(`%(second_number)s''`,{second_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}};function Su(e){return{normalizeFunctionValue(t){return t===null?null:e.normalizeFunctionValue(t)},toValueAndFormat(t,n){return t===null?{value:E(`(Undefined)`)}:e.toValueAndFormat(t,n)},toFunctionValue(t){return t===null?`false`:e.toFunctionValue(t)}}}lu.add(`day`,Su(du)).add(`year`,Su(vu)).add(`day_of_month`,Su(fu)).add(`iso_week_number`,Su(mu)).add(`month_number`,Su(hu)).add(`month`,Su(gu)).add(`quarter_number`,Su(_u)).add(`day_of_week`,Su(pu)).add(`hour_number`,Su(yu)).add(`minute_number`,Su(bu)).add(`second_number`,Su(xu));let Cu={count:E(`Count`),count_distinct:E(`Count Distinct`),bool_and:E(`Boolean And`),bool_or:E(`Boolean Or`),max:E(`Maximum`),min:E(`Minimum`),avg:E(`Average`),sum:E(`Sum`)},wu=[`max`,`min`,`avg`,`sum`,`count_distinct`,`count`],Tu={integer:wu,char:wu,boolean:[`count_distinct`,`count`,`bool_and`,`bool_or`]},Eu={};for(let e in Tu){Eu[e]={};for(let t of Tu[e])Eu[e][t]=Cu[t]}let Du={count:e=>({value:Ml([e]),format:`0`}),count_distinct:e=>({value:xl([e]),format:`0`}),bool_and:e=>({value:vl([e]).result}),bool_or:e=>({value:yl([e]).result}),max:(e,t)=>Nl([e],t),min:(e,t)=>Pl([e],t),avg:(e,t)=>({value:Al([e],t),format:la(e)}),sum:(e,t)=>({value:bl([e],t),format:la(e)})};function Ou(e){let t=Object.keys(e);if(!t.length)return 0;let n=t.map(e=>parseInt(e,10));return Math.max(...n)}let ku={year:E(`Year`),quarter:E(`Quarter & Year`),month:E(`Month & Year`),week:E(`Week & Year`),day:E(`Day`),quarter_number:E(`Quarter`),month_number:E(`Month`),iso_week_number:E(`Week`),day_of_month:E(`Day of Month`),day_of_week:E(`Day of Week`),hour_number:E(`Hour`),minute_number:E(`Minute`),second_number:E(`Second`)},Au=[`date`,`datetime`];function ju(e){let[t,n]=e.split(`:`);return n?{fieldName:t,granularity:n}:{fieldName:t}}function Mu(e){return Au.includes(e.type)}function Nu(e,t,n){let r=[e];n&&r.push(`"${n}"`);for(let{field:e,value:n,type:i}of t){if(e===`measure`){r.push(`"measure"`,`"${n}"`);continue}let{granularity:t}=ju(e),a=Ru(n,{type:i,granularity:t});r.push(`"${e}"`,a)}return r}function Pu(e,t){let n=0,r=0,i=t.columns.map(e=>e.nameWithGranularity),a=t.rows.map(e=>e.nameWithGranularity);for(;e[n]!==void 0&&e[n]===a[r];)n++,r++;for(r=0;e[n]!==void 0&&e[n]===i[r];)n++,r++;return e.length===n}function Fu(e,t){switch(t.type){case`HEADER`:return`=PIVOT.HEADER(${Nu(e,t.domain).join(`,`)})`;case`VALUE`:return`=PIVOT.VALUE(${Nu(e,t.domain,t.measure).join(`,`)})`;case`MEASURE_HEADER`:return`=PIVOT.HEADER(${Nu(e,[...t.domain,{field:`measure`,value:t.measure,type:`char`}]).join(`,`)})`}return``}function Iu(e,t){if(t===null||t===`null`)return null;let n=typeof t==`object`?t.value:t;if(P(n))return n;let r=typeof t==`boolean`?I(t).toLocaleLowerCase():I(t);if(r===`null`)return null;if(!Bu.contains(e.type))throw new M(E(`Field %(field)s is not supported because of its type (%(type)s)`,{field:e.displayName,type:e.type}));return r.toLowerCase()===`false`?!1:Bu.get(e.type)(r,e)}function Lu(e,t){return uu(t.granularity??`month`).normalizeFunctionValue(e)}function Ru(e,t){return e===null?`"null"`:Vu.contains(t.type)?Vu.get(t.type)(e,t.granularity):`"${e}"`}function zu(e,t){return uu(t??`month`).toFunctionValue(e)}let Bu=new h;Bu.add(`date`,Lu).add(`datetime`,Lu).add(`integer`,e=>F(e,k)).add(`boolean`,e=>L(e)).add(`char`,e=>I(e));let Vu=new h;Vu.add(`date`,zu).add(`datetime`,zu).add(`integer`,e=>`${F(e,k)}`).add(`boolean`,e=>L(e)?`TRUE`:`FALSE`).add(`char`,e=>`"${I(e).replace(/"/g,`\\"`)}"`);function Hu(e){return e.displayName+(e.granularity?` (${ku[e.granularity]})`:``)}function Uu(e,t,n){let{rowDomain:r,colDomain:i}=Jl(e,t);if(r.length===0&&i.length===0)return n;if(r.length===0&&i.length>0)return{...n,format:(n.format||`@`)+`* `};let a=r.length-1,o=n.format||`@`;return{...n,format:`${` `.repeat(a)}${o}* `}}var Wu=class extends Pc{isCutAllowed(e){return e.zones.length===1?`Success`:`WrongCutSelection`}copy(e,t=`copyPaste`){let n=e.sheetId,{clippedZones:r,rowsIndexes:i,columnsIndexes:a}=e,o=[],s=i.length===1&&a.length===1;for(let r of i){let c=[];for(let o of a){let l={col:o,row:r,sheetId:n},u=this.getters.getCell(l),d=this.getters.getEvaluatedCell(l),f=this.getters.getPivotIdFromPosition(l),p=this.getters.getArrayFormulaSpreadingOn(l);if(t!==`shiftCells`&&f&&p){let t=this.getters.getSpreadZone(p);if((!C(p,l)||!s)&&t&&!e.zones.some(e=>fr(t,e))){let e=this.getters.getPivotCellFromPosition(l),t=Fu(this.getters.getPivotFormulaId(f),e);u={id:u?.id||``,style:u?.style,format:u?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if(t!==`shiftCells`&&p&&!C(p,l)){let e=i.includes(p.row)&&a.includes(p.col)?``:B(d.value,{locale:this.getters.getLocale()});u={id:u?.id||``,style:u?.style,format:d.format,content:e,isFormula:!1,parsedValue:d.value}}c.push({content:u?.content??``,style:u?.style,format:u?.format,tokens:u?.isFormula?u.compiledFormula.tokens.map(({value:e,type:t})=>({value:e,type:t})):[],border:this.getters.getCellBorder(l)||void 0,evaluatedCell:d,position:l})}o.push(c)}return{cells:o,zones:r,sheetId:e.sheetId}}isPasteAllowed(e,t,n,r){if(!n.cells)return`Success`;if(r?.isCutOperation&&r?.pasteOption!==void 0)return`WrongPasteOption`;if(t.length>1&&(n.cells.length>1||n.cells[0].length>1))return`WrongPasteSelection`;let i=n.cells.length,a=n.cells[0].length;for(let r of Dc(t,n.cells))if(this.getters.doesIntersectMerge(e,r)&&(t.length>1||!this.getters.isSingleCellOrMerge(e,t[0])||i*a!==1))return`WillRemoveExistingMerge`;return`Success`}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.cells,n)}getPasteTarget(e,t,n,r){let i=n.cells[0].length,a=n.cells.length;return r?.isCutOperation?{sheetId:e,zones:[{left:t[0].left,top:t[0].top,right:t[0].left+i-1,bottom:t[0].top+a-1}]}:i===1&&a===1?{zones:[],sheetId:e}:{sheetId:e,zones:Dc(t,n.cells)}}pasteFromCut(e,t,n,r){this.clearClippedZones(n);let i=t[0];this.pasteZone(e,i.left,i.top,n.cells,r)}clearClippedZones(e){this.dispatch(`CLEAR_CELLS`,{sheetId:e.sheetId,target:e.zones}),this.dispatch(`CLEAR_FORMATTING`,{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){if(!s)continue;let o={col:t+r,row:n+a,sheetId:e};this.pasteCell(s,o,i)}}pasteCell(e,t,n){let{sheetId:r,col:i,row:a}=t,o=this.getters.getEvaluatedCell(t),s=e?.format||e.evaluatedCell.format;if(n?.pasteOption===`asValue`){this.dispatch(`UPDATE_CELL`,{...t,content:e.evaluatedCell.value?.toString()||``});return}if(n?.pasteOption===`onlyFormat`){this.dispatch(`UPDATE_CELL`,{...t,style:e?.style??null,format:s??o.format});return}let c=e?.content;e?.tokens&&e.tokens.length>0&&!n?.isCutOperation?c=this.getters.getTranslatedCellFormula(r,i-e.position.col,a-e.position.row,e.tokens):e?.tokens&&e.tokens.length>0&&(c=this.getters.getFormulaMovedInSheet(e.position.sheetId,r,e.tokens)),c!==``||e?.format||e?.style?this.dispatch(`UPDATE_CELL`,{...t,content:c,style:e?.style||null,format:e?.format}):o&&this.dispatch(`CLEAR_CELL`,t)}convertTextToClipboardData(e){let t=this.getters.getLocale(),n={cells:[]},r=[],i=0;for(let[t,n]of e.replace(/\r/g,``).split(`
9
9
  `).entries())r.push(n.split(` `)),r[t].length>i&&(i=r[t].length);for(let e of r){let r=[];for(let n=0;n<i;n++){let i=il(e[n]||``,t);r.push({content:i,evaluatedCell:{formattedValue:i}})}n.cells.push(r)}return n}},Gu=class extends Nc{copy(e){}},Ku=class extends Gu{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`chart`)return;let r={...n},i=this.getters.getChart(e.figureId);if(!i)throw Error(`No chart for the given id: ${e.figureId}`);let a=i.copyInSheetId(t);return{figureId:e.figureId,copiedFigure:r,copiedChart:a}}getPasteTarget(e,t,n,r){return{zones:[],figureId:new wc().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,o=this.getters.getNumberCols(a),s=this.getters.getNumberRows(a),c=this.getters.getColDimensions(a,r[0].left).start,l=this.getters.getRowDimensions(a,r[0].top).start,u=this.getters.getColDimensions(a,o-1).end,d=this.getters.getRowDimensions(a,s-1).end,{width:f,height:p}=t.copiedFigure,m={x:u<f?0:Math.min(c,u-f),y:d<p?0:Math.min(l,d-p)},h=t.copiedChart.copyInSheetId(a);this.dispatch(`CREATE_CHART`,{id:i,sheetId:a,position:m,size:{height:p,width:f},definition:h.getDefinition()}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedChart.sheetId,id:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{id:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},qu=class extends Pc{uuidGenerator=new wc;queuedChanges={};copy(e){if(!e.zones.length)return;let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n=Array.from(this.getters.getRulesByCell(r,i,e));t.push({position:{col:i,row:e,sheetId:r},rules:n})}i.push(t)}return{cfRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption===`asValue`)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.cfRules,n),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.cfRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteCf(s,o,i?.isCutOperation)}}pasteCf(e,t,n){if(e?.rules&&e.rules.length>0){let r=D(e.position),i=D(t);for(let a of e.rules){let o=[];if(n&&o.push(r),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,a,[i],o);else{this.adaptCFRules(e.position.sheetId,a,[],o);let n=this.getCFToCopyTo(t.sheetId,a);this.adaptCFRules(t.sheetId,n,[i],[])}}}}adaptCFRules(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,cf:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,cf:r}of this.queuedChanges[e]){let i=this.getters.getAdaptedCfRanges(e,r,t,n);if(i){if(i.length===0){this.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{id:r.id,sheetId:e});continue}this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:r.id,rule:r.rule,stopIfTrue:r.stopIfTrue},ranges:i,sheetId:e})}}}getCFToCopyTo(e,t){let n=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&C(e.rule,t.rule)),r=this.queuedChanges[e];return!n&&r&&(n=r.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&C(e.cf.rule,t.rule))?.cf),n||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}},Ju=class extends Pc{uuidGenerator=new wc;queuedChanges={};copy(e){let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n={sheetId:r,col:i,row:e},a=this.getters.getValidationRuleForCell(n);t.push({position:n,rule:a})}i.push(t)}return{dvRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.dvRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteDataValidation(s,o,i?.isCutOperation)}}pasteDataValidation(e,t,n){if(e){let r=D(t),i=D(e.position),a=e.rule;if(!a){let e=this.getters.getValidationRuleForCell(t);e&&this.adaptDataValidationRule(t.sheetId,e,[],[r]);return}let o=[];if(n&&o.push(i),e.position.sheetId===t.sheetId){let n=this.getDataValidationRuleToCopyTo(t.sheetId,a,!1);this.adaptDataValidationRule(e.position.sheetId,n,[r],o)}else{let n=this.getters.getValidationRuleForCell(e.position);n&&this.adaptDataValidationRule(e.position.sheetId,n,[],o);let i=this.getDataValidationRuleToCopyTo(t.sheetId,a);this.adaptDataValidationRule(t.sheetId,i,[r],[])}}}getDataValidationRuleToCopyTo(e,t,n=!0){let r=this.getters.getDataValidationRules(e).find(e=>C(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking),i=this.queuedChanges[e];return!r&&i&&(r=i.find(e=>C(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),r||{...t,id:n?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,rule:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,rule:r}of this.queuedChanges[e]){let i=T([...T(r.ranges.map(e=>e.zone),n),...t],[]);if(i.length===0){this.dispatch(`REMOVE_DATA_VALIDATION_RULE`,{sheetId:e,id:r.id});continue}this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:{id:r.id,criterion:r.criterion,isBlocking:r.isBlocking},ranges:i.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}},Yu=class extends Gu{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);let r={...n};if(n.tag!==`image`)return;let i=y(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:r,copiedImage:i,sheetId:t}}getPasteTarget(e,t,n,r){return{sheetId:e,zones:[],figureId:new wc().smallUuid()}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=this.getters.getActiveSheetId(),o=this.getters.getNumberCols(a),s=this.getters.getNumberRows(a),c=this.getters.getColDimensions(a,r[0].left).start,l=this.getters.getRowDimensions(a,r[0].top).start,u=this.getters.getColDimensions(a,o-1).end,d=this.getters.getRowDimensions(a,s-1).end,{width:f,height:p}=t.copiedFigure,m={x:u<f?0:Math.min(c,u-f),y:d<p?0:Math.min(l,d-p)},h=y(t.copiedImage);this.dispatch(`CREATE_IMAGE`,{figureId:i,sheetId:a,position:m,size:{height:p,width:f},definition:h}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.sheetId,id:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{id:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},Xu=class extends Pc{copy(e){let t=this.getters.getActiveSheetId(),{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getMerge(r))}i.push(n)}return{merges:i,sheetId:t}}paste(e,t,n){if(n.isCutOperation){let e=t.merges.flat().filter(S);this.dispatch(`REMOVE_MERGE`,{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,n)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteMerge(o,a)}}pasteMerge(e,t){if(!e||this.getters.isInMerge(t))return;let{sheetId:n,col:r,row:i}=t;this.dispatch(`ADD_MERGE`,{sheetId:n,force:!0,target:[{left:r,top:i,right:r+e.right-e.left,bottom:i+e.bottom-e.top}]})}},Zu=class extends Pc{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,n){if(n.isCutOperation){let n=e.zones[0];this.dispatch(`MOVE_RANGES`,{target:t.zones,sheetId:t.sheetId,targetSheetId:e.sheetId,col:n.left,row:n.top})}}},Qu=class extends Pc{isPasteAllowed(e,t,n,r){if(!(`cells`in n))return`Success`;let{xSplit:i,ySplit:a}=this.getters.getPaneDivisions(e);for(let e of Dc(t,n.cells))if(e.left<i&&e.right>=i||e.top<a&&e.bottom>=a)return`FrozenPaneOverlap`;return`Success`}},$u=class extends Pc{copy(e,t=`copyPaste`){let n=e.sheetId,{rowsIndexes:r,columnsIndexes:i,zones:a}=e,o=new Set,s=[];for(let e of r){let r=[];s.push(r);for(let s of i){let i={col:s,row:e,sheetId:n},c=this.getters.getTable(i);if(!c){r.push({});continue}let l=this.getters.getCoreTable(i),u=l?.range.zone,d;if(!o.has(c.id)&&l&&u&&a.some(e=>fr(u,e))){o.add(c.id);let e=[];for(let t of x(u.left,u.right+1))e.push(this.getters.getFilterHiddenValues({sheetId:n,col:t,row:u.top}));d={range:l.range.rangeData,config:l.config,type:l.type}}t!==`shiftCells`&&r.push({table:d,style:this.getTableStyleToCopy(i),isWholeTableCopied:o.has(c.id)})}}return{tableCells:s,sheetId:e.sheetId}}getTableStyleToCopy(e){let t=this.getters.getCellTableStyle(e),n=this.getters.getCellStyle(e),r=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...jt(n)},border:{...r,...jt(i)}}}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.tableCells,n)}pasteFromCut(e,t,n,r){for(let e of n.tableCells)for(let t of e)t.table&&this.dispatch(`REMOVE_TABLE`,{sheetId:n.sheetId,target:[this.getters.getRangeFromRangeData(t.table.range).zone]});let i=t[0];this.pasteZone(e,i.left,i.top,n.tableCells,r)}pasteZone(e,t,n,r,i){for(let a=0;a<r.length;a++){let o=r[a];for(let r=0;r<o.length;r++){let s=o[r];if(!s)continue;let c={col:t+r,row:n+a,sheetId:e};this.pasteTableCell(e,s,c,i)}}if(r.length===1)for(let i=0;i<r[0].length;i++)this.dispatch(`AUTOFILL_TABLE_COLUMN`,{col:t+i,row:n,sheetId:e})}pasteTableCell(e,t,n,r){if(t.table&&!r?.pasteOption){let{range:r}=t.table,i=pr(this.getters.getRangeFromRangeData(r).zone),a={left:n.col,top:n.row,right:n.col+i.numberOfCols-1,bottom:n.row+i.numberOfRows-1};this.dispatch(`CREATE_TABLE`,{sheetId:n.sheetId,ranges:[this.getters.getRangeDataFromZone(e,a)],config:t.table.config,tableType:t.table.type})}this.getters.getCoreTable(n)||r?.pasteOption===`asValue`||(!r?.pasteOption&&!t.isWholeTableCopied||r?.pasteOption===`onlyFormat`)&&(t.style?.style&&this.dispatch(`UPDATE_CELL`,{...n,style:t.style.style}),t.style?.border&&this.dispatch(`SET_BORDER`,{...n,border:t.style.border}))}};let ed={figureHandlers:new h,cellHandlers:new h};ed.figureHandlers.add(`chart`,Ku).add(`image`,Yu),ed.cellHandlers.add(`dataValidation`,Ju).add(`cell`,Wu).add(`sheet`,Qu).add(`merge`,Xu).add(`border`,Fc).add(`table`,$u).add(`conditionalFormat`,qu).add(`references`,Zu);function td(e,t){return t.type===`REMOVE_COLUMNS_ROWS`?ar(e,t.dimension===`COL`?`left`:`top`,t.elements):t.type===`ADD_COLUMNS_ROWS`?nr(e,t.dimension===`COL`?`left`:`top`,t.base,t.position,t.quantity):e}function nd(e,t){let n=t.type===`DELETE_SHEET`&&t.sheetId;if(`sheetId`in t&&e._sheetId!==t.sheetId)return e;{let r=td(e._zone,t);if(r&&n!==e._sheetId)return{...e,_zone:r}}}var rd=class{subscriptions={};on(e,t,n){if(!n)throw Error(`Missing callback`);this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:n})}trigger(e,t){let n=this.subscriptions[e]||[];for(let e=0,r=n.length;e<r;e++){let r=n[e];r.callback.call(r.owner,t)}}off(e,t){let n=this.subscriptions[e];n&&(this.subscriptions[e]=n.filter(e=>e.owner!==t))}clear(){this.subscriptions={}}},id=class extends rd{dependencies=new Map;factory=new ad(this.get.bind(this));inject(e,t){if(this.dependencies.has(e)&&this.dependencies.get(e)!==t)throw Error(`Store ${e.name} already has an instance`);this.dependencies.set(e,t)}get(e){return this.dependencies.has(e)||this.dependencies.set(e,this.instantiate(e)),this.dependencies.get(e)}instantiate(e,...t){return this.factory.build(e,...t)}resetStores(){this.dependencies.clear()}},ad=class{get;pendingBuilds=new Set;constructor(e){this.get=e}build(e,...t){if(this.pendingBuilds.has(e))throw Error(`Circular dependency detected: ${[...this.pendingBuilds,e].map(e=>e.name).join(` -> `)}`);this.pendingBuilds.add(e);let n=new e(this.get,...t);return this.pendingBuilds.delete(e),n}};function od(e){class t{constructor(t){throw Error(`This is a abstract store for ${e}, it cannot be instantiated.
10
10
  Did you forget to inject your store instance?
11
11
 
@@ -1170,7 +1170,7 @@ stores.inject(MyMetaStore, storeInstance);
1170
1170
  }
1171
1171
  }
1172
1172
  }
1173
- `;var WP=class extends t.Component{static template=`o-spreadsheet-DataValidationPreview`;static props={onClick:Function,rule:Object};ref=(0,t.useRef)(`dvPreview`);setup(){yP(this.ref,this)}deleteDataValidation(){let 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=>({sheetId:this.env.model.getters.getActiveSheetId(),zone:e.zone,color:_,fillAlpha:.06}))}get rangesString(){let e=this.env.model.getters.getActiveSheetId();return this.props.rule.ranges.map(t=>this.env.model.getters.getRangeString(t,e)).join(`, `)}get descriptionString(){return Q.get(this.props.rule.criterion.type).getPreview(this.props.rule.criterion,this.env.model.getters)}},GP=class extends t.Component{static template=`o-spreadsheet-DataValidationPanel`;static props={onCloseSidePanel:Function};static components={DataValidationPreview:WP,DataValidationEditor:UP};state=(0,t.useState)({mode:`list`,activeRule:void 0});onPreviewClick(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getDataValidationRule(t,e);n&&(this.state.mode=`edit`,this.state.activeRule=n)}addDataValidationRule(){this.state.mode=`edit`,this.state.activeRule=void 0}onExitEditMode(){this.state.mode=`list`,this.state.activeRule=void 0}localizeDVRule(e){return e&&ml(e,this.env.model.getters.getLocale())}get validationRules(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getDataValidationRules(e)}};let KP=`#8B008B`;var qP=class extends hd{mutators=[`updateSearchOptions`,`updateSearchContent`,`searchFormulas`,`selectPreviousMatch`,`selectNextMatch`,`replace`];allSheetsMatches=[];activeSheetMatches=[];specificRangeMatches=[];currentSearchRegex=null;isSearchDirty=!1;initialShowFormulaState;preserveSelectedMatchIndex=!1;irreplaceableMatchCount=0;notificationStore=this.get(sP);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;let t=e(xN);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(-1)}selectNextMatch(){this.selectNextCell(1)}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`:case`ACTIVATE_SHEET`:this.isSearchDirty=!0,this.searchOptions.specificRange&&(this.searchOptions.specificRange=this.searchOptions.specificRange.clone({sheetId:this.getters.getActiveSheetId()}));break;case`DELETE_SHEET`:this.searchOptions.searchScope===`specificRange`&&this.searchOptions.specificRange?.sheetId===e.sheetId&&(this.searchOptions={...this.searchOptions,specificRange:void 0}),this.isSearchDirty=!0;break;case`REPLACE_SEARCH`:for(let 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;break}}finalize(){this.isSearchDirty&&=(this.refreshSearch(!1),!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=Wt(this.toSearch,this.searchOptions),this.refreshSearch()}refreshSearch(e=!0){this.preserveSelectedMatchIndex||(this.selectedMatchIndex=null),this.findMatches(),this.selectNextCell(0,e)}getSheetsInSearchOrder(){switch(this.searchOptions.searchScope){case`allSheets`:let 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`:let n=this.searchOptions.specificRange;return n&&n?[n.sheetId]:[]}}findMatches(){let e=[];if(this.toSearch)for(let 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){let{sheetId:t,zone:n}=this.searchOptions.specificRange;this.specificRangeMatches=e.filter(e=>e.sheetId===t&&dr(e.col,e.row,n))}else this.specificRangeMatches=[]}findMatchesInSheet(e){let t=[],{left:n,right:r,top:i,bottom:a}=this.getters.getSheetZone(e);for(let o=i;o<=a;o++)for(let i=n;i<=r;i++){let n=this.getters.isColHidden(e,i),r=this.getters.isRowHidden(e,o);if(n||r)continue;let a={sheetId:e,col:i,row:o};if(this.currentSearchRegex?.test(this.getSearchableString(a))){let n={sheetId:e,col:i,row:o};t.push(n)}}return t}selectNextCell(e,t=!0){let n=this.searchMatches;if(!n.length){this.selectedMatchIndex=null;return}let r;if(this.selectedMatchIndex===null){let e=-1;for(let t of this.getSheetsInSearchOrder())if(e=n.findIndex(e=>e.sheetId===t),e!==-1)break;r=e}else r=this.selectedMatchIndex+e;r=(r+n.length)%n.length,this.selectedMatchIndex=r;let i=n[r];t&&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(),this.model.selection.selectCell(i.col,i.row)}replace(){this.selectedMatchIndex!==null&&(this.preserveSelectedMatchIndex=!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){let n=e-t;n===0?this.notificationStore.notifyUser({type:`warning`,sticky:!1,text:E(`Match(es) cannot be replaced as they are part of a formula.`)}):this.notificationStore.notifyUser({type:`warning`,sticky:!1,text:E(`%(replaceable_count)s match(es) replaced. %(irreplaceable_count)s match(es) cannot be replaced as they are part of a formula.`,{replaceable_count:n,irreplaceable_count:t})})}replaceMatch(e,t,n,r){let i=this.getters.getCell(e);if(!i?.content)return;if(i?.isFormula&&!r.searchFormulas){this.irreplaceableMatchCount++;return}let a=Wt(t,r),o=new RegExp(a.source,a.flags+`g`),s=tl(this.getters.getCellText(e,{showFormula:r.searchFormulas}).replace(o,n),this.getters.getLocale());this.model.dispatch(`UPDATE_CELL`,{...e,content:s})}getSearchableString(e){return this.getters.getCellText(e,{showFormula:this.searchOptions.searchFormulas})}get highlights(){let e=[],t=this.getters.getActiveSheetId();for(let[n,r]of this.searchMatches.entries()){if(r.sheetId!==t)continue;let i=D(r),a=this.getters.expandZone(t,i),{width:o,height:s}=this.getters.getVisibleRect(a);o>0&&s>0&&e.push({sheetId:t,zone:a,color:KP,noBorder:n!==this.selectedMatchIndex,thinLine:!0,fillAlpha:.2})}if(this.searchOptions.searchScope===`specificRange`){let n=this.searchOptions.specificRange;n&&n.sheetId===t&&e.push({sheetId:t,zone:n.zone,color:KP,noFill:!0,thinLine:!0})}return e}};H`
1173
+ `;var WP=class extends t.Component{static template=`o-spreadsheet-DataValidationPreview`;static props={onClick:Function,rule:Object};ref=(0,t.useRef)(`dvPreview`);setup(){yP(this.ref,this)}deleteDataValidation(){let 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=>({sheetId:this.env.model.getters.getActiveSheetId(),zone:e.zone,color:_,fillAlpha:.06}))}get rangesString(){let e=this.env.model.getters.getActiveSheetId();return this.props.rule.ranges.map(t=>this.env.model.getters.getRangeString(t,e)).join(`, `)}get descriptionString(){return Q.get(this.props.rule.criterion.type).getPreview(this.props.rule.criterion,this.env.model.getters)}},GP=class extends t.Component{static template=`o-spreadsheet-DataValidationPanel`;static props={onCloseSidePanel:Function};static components={DataValidationPreview:WP,DataValidationEditor:UP};state=(0,t.useState)({mode:`list`,activeRule:void 0});onPreviewClick(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getDataValidationRule(t,e);n&&(this.state.mode=`edit`,this.state.activeRule=n)}addDataValidationRule(){this.state.mode=`edit`,this.state.activeRule=void 0}onExitEditMode(){this.state.mode=`list`,this.state.activeRule=void 0}localizeDVRule(e){return e&&ml(e,this.env.model.getters.getLocale())}get validationRules(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getDataValidationRules(e)}};let KP=`#8B008B`;var qP=class extends hd{mutators=[`updateSearchOptions`,`updateSearchContent`,`searchFormulas`,`selectPreviousMatch`,`selectNextMatch`,`replace`];allSheetsMatches=[];activeSheetMatches=[];specificRangeMatches=[];selectedMatchPosition=null;currentSearchRegex=null;isSearchDirty=!1;initialShowFormulaState;irreplaceableMatchCount=0;notificationStore=this.get(sP);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;let t=e(xN);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(-1)}selectNextMatch(){this.selectNextCell(1)}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`:case`ACTIVATE_SHEET`:this.isSearchDirty=!0,this.searchOptions.specificRange&&(this.searchOptions.specificRange=this.searchOptions.specificRange.clone({sheetId:this.getters.getActiveSheetId()}));break;case`DELETE_SHEET`:this.searchOptions.searchScope===`specificRange`&&this.searchOptions.specificRange?.sheetId===e.sheetId&&(this.searchOptions={...this.searchOptions,specificRange:void 0}),this.isSearchDirty=!0;break;case`REPLACE_SEARCH`:for(let 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;break}}finalize(){this.isSearchDirty&&=(this.refreshSearch(!1),!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.selectedMatchPosition=null),this.toSearch=e,this.currentSearchRegex=Wt(this.toSearch,this.searchOptions),this.refreshSearch()}refreshSearch(e=!0){if(this.findMatches(),this.selectedMatchPosition)if(this.selectedMatchPosition.sheetId!==this.getters.getActiveSheetId())this.selectedMatchIndex=null,this.selectedMatchPosition=null;else{let e=this.searchMatches.findIndex(e=>e.sheetId===this.selectedMatchPosition?.sheetId&&e.col===this.selectedMatchPosition?.col&&e.row===this.selectedMatchPosition?.row);e!==-1&&(this.selectedMatchIndex=e)}this.selectNextCell(0,e)}getSheetsInSearchOrder(){switch(this.searchOptions.searchScope){case`allSheets`:let 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`:let n=this.searchOptions.specificRange;return n&&n?[n.sheetId]:[]}}findMatches(){let e=[];if(this.toSearch)for(let 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){let{sheetId:t,zone:n}=this.searchOptions.specificRange;this.specificRangeMatches=e.filter(e=>e.sheetId===t&&dr(e.col,e.row,n))}else this.specificRangeMatches=[]}findMatchesInSheet(e){let t=[],{left:n,right:r,top:i,bottom:a}=this.getters.getSheetZone(e);for(let o=i;o<=a;o++)for(let i=n;i<=r;i++){let n=this.getters.isColHidden(e,i),r=this.getters.isRowHidden(e,o);if(n||r)continue;let a={sheetId:e,col:i,row:o};if(this.currentSearchRegex?.test(this.getSearchableString(a))){let n={sheetId:e,col:i,row:o};t.push(n)}}return t}selectNextCell(e,t=!0){let n=this.searchMatches;if(!n.length){this.selectedMatchIndex=null,this.selectedMatchPosition=null;return}let r;if(this.selectedMatchIndex===null){let e=-1;for(let t of this.getSheetsInSearchOrder())if(e=n.findIndex(e=>e.sheetId===t),e!==-1)break;r=e}else r=this.selectedMatchIndex+e;r=(r+n.length)%n.length,this.selectedMatchIndex=r,this.selectedMatchPosition=n[this.selectedMatchIndex];let i=n[r];t&&this.getters.getActiveSheetId()!==i.sheetId&&(this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:i.sheetId}),this.isSearchDirty=!1),this.model.selection.getBackToDefault(),this.model.selection.selectCell(i.col,i.row)}replace(){this.selectedMatchIndex!==null&&this.model.dispatch(`REPLACE_SEARCH`,{searchString:this.toSearch,replaceWith:this.toReplace,matches:[this.searchMatches[this.selectedMatchIndex]],searchOptions:this.searchOptions})}replaceAll(){this.model.dispatch(`REPLACE_SEARCH`,{searchString:this.toSearch,replaceWith:this.toReplace,matches:this.searchMatches,searchOptions:this.searchOptions})}showReplaceWarningMessage(e,t){let n=e-t;n===0?this.notificationStore.notifyUser({type:`warning`,sticky:!1,text:E(`Match(es) cannot be replaced as they are part of a formula.`)}):this.notificationStore.notifyUser({type:`warning`,sticky:!1,text:E(`%(replaceable_count)s match(es) replaced. %(irreplaceable_count)s match(es) cannot be replaced as they are part of a formula.`,{replaceable_count:n,irreplaceable_count:t})})}replaceMatch(e,t,n,r){let i=this.getters.getCell(e);if(!i?.content)return;if(i?.isFormula&&!r.searchFormulas){this.irreplaceableMatchCount++;return}let a=Wt(t,r),o=new RegExp(a.source,a.flags+`g`),s=tl(this.getters.getCellText(e,{showFormula:r.searchFormulas}).replace(o,n),this.getters.getLocale());this.model.dispatch(`UPDATE_CELL`,{...e,content:s})}getSearchableString(e){return this.getters.getCellText(e,{showFormula:this.searchOptions.searchFormulas})}get highlights(){let e=[],t=this.getters.getActiveSheetId();for(let[n,r]of this.searchMatches.entries()){if(r.sheetId!==t)continue;let i=D(r),a=this.getters.expandZone(t,i),{width:o,height:s}=this.getters.getVisibleRect(a);o>0&&s>0&&e.push({sheetId:t,zone:a,color:KP,noBorder:n!==this.selectedMatchIndex,thinLine:!0,fillAlpha:.2})}if(this.searchOptions.searchScope===`specificRange`){let n=this.searchOptions.specificRange;n&&n.sheetId===t&&e.push({sheetId:t,zone:n.zone,color:KP,noFill:!0,thinLine:!0})}return e}};H`
1174
1174
  .o-find-and-replace {
1175
1175
  outline: none;
1176
1176
  height: 100%;
@@ -1299,17 +1299,17 @@ stores.inject(MyMetaStore, storeInstance);
1299
1299
  .add-calculated-measure {
1300
1300
  cursor: pointer;
1301
1301
  }
1302
- `;var lF=class extends t.Component{static template=`o-spreadsheet-PivotLayoutConfigurator`;static components={AddDimensionButton:tF,PivotDimension:iF,PivotDimensionOrder:oF,PivotDimensionGranularity:aF,PivotMeasureEditor:cF};static props={definition:Object,onDimensionsUpdated:Function,unusedGroupableFields:Array,measureFields:Array,unusedGranularities:Object,dateGranularities:Array,datetimeGranularities:Array,getScrollableContainerEl:{type:Function,optional:!0},pivotId:String};dimensionsRef=(0,t.useRef)(`pivot-dimensions`);dragAndDrop=fP();AGGREGATORS=Eu;composerFocus;isDateOrDatetimeField=Mu;setup(){this.composerFocus=V(_d)}startDragAndDrop(e,t){if(t.button!==0||t.target.tagName===`SELECT`)return;let n=this.getDimensionElementsRects(),{columns:r,rows:i}=this.props.definition,a=[...r.map(e=>e.nameWithGranularity),`__rows_title__`,...i.map(e=>e.nameWithGranularity)],o=r.concat(i),s=a.map((e,t)=>({id:e,size:n[t+1].height,position:n[t+1].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:s,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=a.findIndex(t=>t===e);if(n===t)return;let r=[...a];r.splice(n,1),r.splice(t,0,e);let i=r.slice(0,r.indexOf(`__rows_title__`)),s=r.slice(r.indexOf(`__rows_title__`)+1);this.props.onDimensionsUpdated({columns:i.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(S),rows:s.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(S)})}})}getGranularitiesFor(e){return Mu(e)?e.type===`date`?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(t.button!==0||t.target.tagName===`SELECT`||t.target.tagName===`INPUT`||this.composerFocus.focusMode!==`inactive`)return;let n=this.getDimensionElementsRects(),{measures:r,columns:i,rows:a}=this.props.definition,o=r.map(e=>e.id),s=3+i.length+a.length,c=o.map((e,t)=>({id:e,size:n[t+s].height,position:n[t+s].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=o.findIndex(t=>t===e);if(n===t)return;let i=[...o];i.splice(n,1),i.splice(t,0,e),this.props.onDimensionsUpdated({measures:i.map(e=>r.find(t=>t.id===e)).filter(S)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{let t=getComputedStyle(e),n=e.getBoundingClientRect();return{x:n.x,y:n.y,width:n.width+parseInt(t.marginLeft||`0`)+parseInt(t.marginRight||`0`),height:n.height+parseInt(t.marginTop||`0`)+parseInt(t.marginBottom||`0`)}})}removeDimension(e){let{columns:t,rows:n}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:n.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){let{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){let{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:`asc`}])})}addRowDimension(e){let{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:`asc`}])})}addMeasureDimension(e){let{measures:t}=this.props.definition,n=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,n),fieldName:e,aggregator:n}])})}updateMeasure(e,t){let{measures:n}=this.props.definition;this.props.onDimensionsUpdated({measures:n.map(n=>n.id===e.id?t:n)})}getMeasureId(e,t){let n=e.replaceAll(`'`,``)+(t?`:${t}`:``),r=n,i=2;for(;this.props.definition.measures.some(e=>e.id===r);)r=`${n}:${i}`,i++;return r}getDefaultMeasureAggregator(e){let t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:`count`}addCalculatedMeasure(){let{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t,`sum`),fieldName:t,aggregator:`sum`,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:`=0`}}])})}updateOrder(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n)})}updateGranularity(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n)})}getMeasureDescription(e){let t=e.display;if(!t||t.type===`no_calculations`)return``;let n=this.env.model.getters.getPivot(this.props.pivotId),r=[...n.definition.columns,...n.definition.rows].find(e=>e.nameWithGranularity===t.fieldNameWithGranularity),i=r?Hu(r):``;return pg.descriptions[t.type](i)}},uF=class extends t.Component{static template=`o-spreadsheet-PivotTitleSection`;static components={CogWheelMenu:rF,Section:Z,TextInput:nF};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:E(`Flip axes`),icon:`o-spreadsheet-Icon.EXCHANGE`,execute:this.props.flipAxis},{name:E(`Duplicate`),icon:`o-spreadsheet-Icon.COPY`,execute:()=>this.duplicatePivot()},{name:E(`Delete`),icon:`o-spreadsheet-Icon.TRASH`,execute:()=>this.delete()}]}get name(){return this.env.model.getters.getPivotName(this.props.pivotId)}get displayName(){return this.env.model.getters.getPivotDisplayName(this.props.pivotId)}duplicatePivot(){let e=this.env.model.uuidGenerator.smallUuid(),t=this.env.model.uuidGenerator.smallUuid(),n=this.env.model.dispatch(`DUPLICATE_PIVOT_IN_NEW_SHEET`,{pivotId:this.props.pivotId,newPivotId:e,newSheetId:t}),r;r=n.isSuccessful?E(`Pivot duplicated.`):n.isCancelledBecause(`PivotInError`)?E(`Cannot duplicate a pivot in error.`):E(`Pivot duplication failed.`);let i=n.isSuccessful?`success`:`danger`;this.env.notifyUser({text:r,sticky:!1,type:i}),n.isSuccessful&&this.env.openSidePanel(`PivotSidePanel`,{pivotId:e})}delete(){this.env.askConfirmation(E(`Are you sure you want to delete this pivot?`),()=>{this.env.model.dispatch(`REMOVE_PIVOT`,{pivotId:this.props.pivotId})})}onNameChanged(e){let t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.props.pivotId,pivot:{...t,name:e}})}},dF=class{measures;columns;rows;constructor(e,t){this.measures=e.measures.map(e=>fF(t,e)),this.columns=e.columns.map(e=>pF(t,e)),this.rows=e.rows.map(e=>pF(t,e))}getDimension(e){let t=this.columns.find(t=>t.nameWithGranularity===e)||this.rows.find(t=>t.nameWithGranularity===e);if(!t)throw new M(E(`Dimension %s does not exist`,e));return t}getMeasure(e){let t=this.measures.find(t=>t.id===e);if(!t)throw new M(E(`Field %s is not a measure`,e));return t}};function fF(e,t){let n=t.fieldName,r=n===`__count`?{name:`__count`,string:E(`Count`),type:`integer`,aggregator:`sum`}:e[n],i=t.aggregator;return{id:t.id,get displayName(){return t.userDefinedName??r?.string??t.fieldName},userDefinedName:t.userDefinedName,fieldName:n,aggregator:i,type:n===`__count`?`integer`:r?.type??`integer`,isValid:!!(r||t.computedBy),isHidden:t.isHidden,format:t.format,computedBy:t.computedBy,display:t.display}}function pF(e,t){let n=e[t.fieldName],r=n?.type??`integer`,i=n&&Mu(n)?t.granularity:void 0;return{displayName:n?.string??t.fieldName,nameWithGranularity:t.fieldName+(i?`:${i}`:``),fieldName:t.fieldName,granularity:i,type:r,order:t.order,isValid:!!n}}var mF=class extends dF{range;constructor(e,t,n){if(super(e,t),e.dataSet){let{sheetId:t,zone:r}=e.dataSet;this.range=n.getRangeFromZone(t,r)}}},hF=class{columns;rows;measures;fieldsType;maxIndent;pivotCells={};rowTree;colTree;constructor(e,t,n,r){this.columns=e.map(e=>{let t=1;return e.map(e=>(e={...e,offset:t},t+=e.width,e))}),this.rows=t,this.measures=n,this.fieldsType=r,this.maxIndent=Math.max(...this.rows.map(e=>e.indent)),this.rowTree=Et(()=>this.buildRowsTree()),this.colTree=Et(()=>this.buildColumnsTree())}getNumberOfDataColumns(){return this.columns.at(-1)?.length||0}getPivotCells(e=!0,t=!0){let n=JSON.stringify({includeTotal:e,includeColumnHeaders:t});if(!this.pivotCells[n]){let r=this.rows.length,i=this.getNumberOfDataColumns(),a=this.columns.length+r,o=1+i;!e&&r!==1&&--a,!e&&i!==this.measures.length&&(o-=this.measures.length);let s=[],c=t?0:this.columns.length;for(let t=0;t<o;t++){s.push([]);for(let n=c;n<a;n++)!e&&n===a||s[t].push(this.getPivotCell(t,n,e))}this.pivotCells[n]=s}return this.pivotCells[n]}getRowTree(){return this.rowTree()}getColTree(){return this.colTree()}isTotalRow(e){return this.rows[e].indent!==this.maxIndent}getPivotCell(e,t,n=!0){let r=this.columns.length;if(e>0&&t===r-1){let n=this.getColHeaderDomain(e,t);if(!n)return gF;let r=n.at(-1)?.value?.toString()||``;return{type:`MEASURE_HEADER`,domain:n.slice(0,-1),measure:r}}else if(t<=r-1){let n=this.getColHeaderDomain(e,t);return n?{type:`HEADER`,domain:n}:gF}else if(e===0){let e=t-r;return{type:`HEADER`,domain:this.getRowDomain(e)}}else{let i=t-r;return!n&&this.isTotalRow(i)?gF:{type:`VALUE`,domain:[...this.getRowDomain(i),...this.getColDomain(e)],measure:this.getColMeasure(e)}}}getColHeaderDomain(e,t){if(e===0)return;let n=[],r=this.columns[t].find(t=>t.offset===e);if(r){for(let e=0;e<r.fields.length;e++){let t=r.fields[e];if(t===`measure`)n.push({type:`char`,field:t,value:Iu({displayName:`measure`,type:`char`},r.values[e])});else{let{fieldName:i,granularity:a}=ju(t),o=this.fieldsType[i]||`char`;n.push({type:o,field:t,value:Iu({displayName:i,type:o,granularity:a},r.values[e])})}}return n}}getColDomain(e){let t=this.getColHeaderDomain(e,this.columns.length-1);return t?t.slice(0,-1):[]}getColMeasure(e){let t=this.getColHeaderDomain(e,this.columns.length-1)?.at(-1)?.value;if(t==null)throw Error(`Measure is missing`);return t.toString()}getRowDomain(e){let t=[];for(let n=0;n<this.rows[e].fields.length;n++){let r=this.rows[e].fields[n],{fieldName:i,granularity:a}=ju(r),o=this.fieldsType[i]||`char`;t.push({type:o,field:r,value:Iu({displayName:i,type:o,granularity:a},this.rows[e].values[n])})}return t}buildRowsTree(){let e=[],t=0,n={};n[0]=e;for(let r of this.rows){if(r.fields.length===0||r.values.length===0)return e;let i=r.fields.length-1,a=r.fields[i],{fieldName:o,granularity:s}=ju(a),c=Iu({displayName:o,type:this.fieldsType[o]??`char`,granularity:s},r.values[i]);if(i>t){t=i,n[t]=[];let e=n[t-1].at(-1);e&&(e.children=n[t])}t=i;let l={value:c,field:r.fields[i],children:[],width:0};n[t].push(l)}return e}buildColumnsTree(){let e=[],t=this.columns.at(-2)||[],n={};n[0]=e;for(let e of t)for(let t=0;t<e.fields.length;t++){let r=e.fields[t],{fieldName:i,granularity:a}=ju(r),o=Iu({displayName:i,type:this.fieldsType[i]??`char`,granularity:a},e.values[t]),s={value:o,field:e.fields[t],children:[],width:e.width};n[t]?.at(-1)?.value!==o&&(n[t+1]=[],s.children=n[t+1],n[t].push(s))}return e}export(){return{cols:this.columns,rows:this.rows,measures:this.measures,fieldsType:this.fieldsType}}};let gF={type:`EMPTY`};function _F(e,t){let n=t.measures.filter(e=>!e.isHidden).map(e=>e.id),r=yF(e,t.columns,0);bF(r,n.length);let i=xF(r,t),a=vF(e,0,t.rows,[],[]);a.push({fields:[],values:[],indent:0});let o={};for(let e of t.columns)o[e.fieldName]=e.type;for(let e of t.rows)o[e.fieldName]=e.type;return new hF(i,a,n,o)}function vF(e,t,n,r,i){if(t>=n.length)return[];let a=n[t],o=a.nameWithGranularity,s=SF(e,a),c=wF(s,a),l=[],u=r.concat(o);for(let e of c){let r=i.concat(e);l.push({fields:u,values:r,indent:t});let a=s[e];a&&l.push(...vF(a,t+1,n,u,r))}return l}function yF(e,t,n){if(n>=t.length)return[];let r=t[n],i=t[n].nameWithGranularity,a=SF(e,r);return wF(a,t[n]).map(e=>({value:a[e]?.[0]?.[r.nameWithGranularity]?.value??null,field:i,children:yF(a[e]||[],t,n+1),width:0}))}function bF(e,t){for(let n in e){let r=e[n];r.children.length===0?r.width=t:(bF(r.children,t),r.width=r.children.reduce((e,t)=>e+t.width,0))}}function xF(e,t){let n=t.columns.map(e=>e.nameWithGranularity),r=n.length,i=t.measures.filter(e=>!e.isHidden),a=i.length,o=Array(r).fill(0).map(()=>[]);function s(e,t,i){let a=o[t];for(let o of e){let e=i.concat([o.value]),c={fields:n.slice(0,t+1),values:e,width:o.width,offset:0};a.push(c),t<=r-1&&s(o.children,t+1,e)}}s(e,0,[]);let c=n.length>0,l=[];return c&&o[o.length-1].forEach(e=>{i.forEach(t=>{let n={fields:[...e.fields,`measure`],values:[...e.values,t.id],width:1,offset:0};l.push(n)})}),i.forEach(e=>{let t={fields:[`measure`],values:[e.id],width:1,offset:0};l.push(t)}),o.push(l),o.length===1&&o.unshift([]),o[o.length-2].push({fields:[],values:[],width:a,offset:0}),o}function SF(e,t){return Object.groupBy(e,CF(t))}function CF(e){let t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}function wF(e,t){return t.order?Object.keys(e).sort((e,n)=>TF(t,e,n)):Object.keys(e)}function TF(e,t,n){return t===`null`?e.order===`asc`?1:-1:n===`null`?e.order===`asc`?-1:1:e.type===`integer`||e.type===`datetime`?e.order===`asc`?F(t,k)-F(n,k):F(n,k)-F(t,k):e.order===`asc`?t.localeCompare(n):n.localeCompare(t)}let EF=Symbol(`NULL`);function DF(e,t,n){let r=e.granularity||`month`;if(!(r in OF))throw Error(`Unknown date granularity: ${r}`);let i=typeof t==`number`||typeof t==`string`?t:EF;if(!OF[r].set.has(t)){OF[r].set.add(t);let a=null;if(typeof t==`number`||typeof t==`string`){let e=R(t,n);switch(r){case`year`:a=e.getFullYear();break;case`quarter_number`:a=Math.floor(e.getMonth()/3)+1;break;case`month_number`:a=e.getMonth()+1;break;case`month`:a=Math.floor(F(t,n));break;case`iso_week_number`:a=e.getIsoWeek();break;case`day_of_month`:a=e.getDate();break;case`day`:a=Math.floor(F(t,n));break;case`day_of_week`:a=(e.getDay()+7-n.weekStart)%7+1;break;case`hour_number`:a=e.getHours();break;case`minute_number`:a=e.getMinutes();break;case`second_number`:a=e.getSeconds();break}}OF[r].values[i]=Iu(e,a)}return OF[r].values[i]}let OF={year:{set:new Set,values:{}},quarter_number:{set:new Set,values:{}},month_number:{set:new Set,values:{}},month:{set:new Set,values:{}},iso_week_number:{set:new Set,values:{}},day_of_month:{set:new Set,values:{}},day:{set:new Set,values:{}},day_of_week:{set:new Set,values:{}},hour_number:{set:new Set,values:{}},minute_number:{set:new Set,values:{}},second_number:{set:new Set,values:{}}};function kF(){for(let e in OF)OF[e].set.clear(),OF[e].values={}}var AF=class{type=`SPREADSHEET`;getters;_definition;coreDefinition;metaData={fields:{},fieldKeys:[]};dataEntries=[];table;invalidRangeError;needsReevaluation=!0;constructor(e,t){this.getters=t.getters,this.coreDefinition=t.definition}init(e={}){(!this._definition||e.reload)&&(this.reload(4),this.needsReevaluation=!1)}reload(e){e===4&&(this.metaData=this.loadMetaData()),e>=3&&(this._definition=this.loadRuntimeDefinition()),e>=2&&(this.dataEntries=this.loadData()),e>=1&&(this.table=void 0)}onDefinitionChange(e){let t=this.coreDefinition;if(this.coreDefinition=e,this._definition){let n=Math.max(this.computeShouldReload(t,e),0);this.reload(n)}}computeShouldReload(e,t){return C(e.dataSet,t.dataSet)?3:4}get isInvalidRange(){return!!this.invalidRangeError}get invalidRangeMessage(){return this.invalidRangeError?.message}get definition(){if(this._definition||this.init(),!this._definition)throw Error(`Pivot definition should be defined at this point.`);return this._definition}isValid(){if(this.invalidRangeError||!this.definition)return!1;for(let e of this.definition.measures)if(!e.isValid)return!1;for(let e of this.definition.columns)if(!e.isValid)return!1;for(let e of this.definition.rows)if(!e.isValid)return!1;return!0}assertIsValid({throwOnError:e}){if(!this.isValid()){if(e)throw this.invalidRangeError?this.invalidRangeError:new M(E(`At least one measure and/or dimension is not correct.`));return{value:j.GenericError,message:this.invalidRangeError?.message??E(`At least one measure and/or dimension is not correct.`)}}}areDomainArgsFieldsValid(e){let t=e.filter((e,t)=>t%2==0).map(I);return t.length&&t.at(-1)===`measure`&&(t=t.slice(0,-1)),Pu(t,this.definition)}parseArgsToPivotDomain(e){let t=[];for(let n=0;n<e.length-1;n+=2){let r=I(e[n]),i=this.getTypeOfDimension(r),a=r===`measure`?I(e[n+1]):Iu(this.getDimension(r),e[n+1]);t.push({field:r,value:a,type:i})}return t}markAsDirtyForEvaluation(){this.needsReevaluation=!0}getMeasure(e){return this.definition.getMeasure(e)}getPivotMeasureValue(e){return{value:this.getMeasure(e).displayName}}getPivotHeaderValueAndFormat(e){let t=e.at(-1);if(!t)return{value:E(`Total`)};let n=this.getDimension(t.field),r=this.filterDataEntriesFromDomain(this.dataEntries,e)[0]?.[n.nameWithGranularity];return n.type===`datetime`?uu(n.granularity||`month`).toValueAndFormat(t.value,this.getters.getLocale()):r?r.value===null?{value:E(`(Undefined)`)}:r:{value:``}}getPivotCellValueAndFormat(e,t){let n=this.filterDataEntriesFromDomain(this.dataEntries,t);if(n.length===0)return{value:``};let r=this.getMeasure(e),i=n.map(e=>e[r.fieldName]).filter(S),a=i.filter(e=>e.type!==`empty`),o=r.aggregator,s=Du[o];if(!s)throw Error(`Aggregator ${o} does not exist`);try{let e=s([i],this.getters.getLocale());return a.length===0?{...e,value:``}:e}catch(e){return BT(e,o.toUpperCase())}}getPossibleFieldValues(e){let t=[],n=SF(this.dataEntries,e),r=wF(n,e);for(let i of r)t.push({value:n[i]?.[0]?.[e.nameWithGranularity]?.value??``,label:n[i]?.[0]?.[e.nameWithGranularity]?.formattedValue||``});return t}getTableStructure(){if(!this.isValid())throw Error(`Pivot is not valid !`);return this.table||=_F(this.dataEntries,this.definition),this.table}getFields(){return this.metaData.fields}get fields(){return this.getFields()}loadMetaData(){if(this.invalidRangeError=void 0,this.coreDefinition.dataSet){let{zone:e,sheetId:t}=this.coreDefinition.dataSet,n=this.getters.getRangeFromZone(t,e);try{return this.extractFieldsFromRange(n)}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}else return this.invalidRangeError=new M(E(`The pivot cannot be created because the dataset is missing.`)),{fields:{},fieldKeys:[]}}loadRuntimeDefinition(){return new mF(this.coreDefinition,this.fields,this.getters)}loadData(){let e=this._definition?.range;return this.isValid()&&e?this.extractDataEntriesFromRange(e):[]}getTypeOfDimension(e){if(e===`measure`)return`char`;let{fieldName:t}=ju(e),n=this.fields[t]?.type;if(!n)throw Error(`Field ${t} does not exist`);return n}filterDataEntriesFromDomain(e,t){return t.reduce((e,t)=>this.filterDataEntriesFromDomainNode(e,t),e)}filterDataEntriesFromDomainNode(e,t){let{field:n,value:r,type:i}=t,{nameWithGranularity:a}=this.getDimension(n);return e.filter(e=>{let t=e[a]?.value;return i===`char`?String(t)===String(r):t===r})}getDimension(e){return this.definition.getDimension(e)}getTypeFromZone(e,t){let n=this.getters.getEvaluatedCellsInZone(e,t).filter(e=>!(e.type===`empty`||e.value===``));return n.length===0?`integer`:n.every(e=>e.type===`number`&&e.format&&Go(e.format))?`datetime`:n.every(e=>e.type===`boolean`)?`boolean`:n.every(e=>e.type===`number`)?`integer`:`char`}assertCellIsValidField(e,t,n){if(n.type===`error`)throw new M(E(`The pivot cannot be created because cell %s contains an error`,w(e,t)));if(n.type===`empty`||n.value===``)throw new M(E(`The pivot cannot be created because cell %s is empty`,w(e,t)));if(n.value===`__count`)throw new M(E(`The pivot cannot be created because cell %s contains a reserved value`,w(e,t)))}extractFieldsFromRange(e){let t={},n=[],r=e.sheetId,i=e.zone.top;for(let a=e.zone.left;a<=e.zone.right;a++){let o=this.getters.getEvaluatedCell({sheetId:r,col:a,row:i});this.assertCellIsValidField(a,i,o);let s=o.value?.toString();if(s){let i=this.getTypeFromZone(r,{top:e.zone.top+1,left:a,bottom:e.zone.bottom,right:a}),o=this.findName(s,t);t[o]={name:o,type:i,string:o,aggregator:i===`integer`?`sum`:`count`},n.push(o)}}return{fields:t,fieldKeys:n}}findName(e,t){let n=1,r=e;for(;e in t;)e=`${r}${++n}`;return e}extractDataEntriesFromRange(e){let t=[];for(let n=e.zone.top+1;n<=e.zone.bottom;n++){let r={top:n,bottom:n,left:e.zone.left,right:e.zone.right},i=this.getters.getEvaluatedCellsInZone(e.sheetId,r),a={};for(let e in i){let t=i[e],n=this.fields[this.metaData.fieldKeys[e]];if(!n)throw Error(`Field ${this.metaData.fieldKeys[e]} does not exist`);t.value===``?a[n.name]={value:null,type:`empty`,formattedValue:``}:a[n.name]=t}a.__count={value:1,type:`number`,formattedValue:`1`},t.push(a)}let n=this.definition.columns.concat(this.definition.rows).filter(e=>e.type===`datetime`);if(n.length){let e=this.getters.getLocale();for(let r of t)for(let t of n){let n=DF(t,r[t.fieldName]?.value||null,this.getters.getLocale()),{format:i,value:a}=uu(t.granularity||`month`).toValueAndFormat(n,e);r[t.nameWithGranularity]={value:n,type:r[t.fieldName]?.type||`empty`,format:r[t.fieldName]?.format,formattedValue:B(a,{locale:e,format:i})}}}return t}};let jF=new h,MF=[`year`,`quarter_number`,`month_number`,`month`,`iso_week_number`,`day_of_month`,`day`,`day_of_week`],NF=[...MF,`hour_number`,`minute_number`,`second_number`];jF.add(`SPREADSHEET`,{ui:AF,definition:mF,dateGranularities:[...MF],datetimeGranularities:[...NF],isMeasureCandidate:e=>![`datetime`,`boolean`].includes(e.type),isGroupable:()=>!0,adaptRanges:(e,t,n)=>{if(t.type!==`SPREADSHEET`||!t.dataSet)return t;let{sheetId:r,zone:i}=t.dataSet,a=e.getRangeFromZone(r,i),o=PF(a,n);if(o===a)return t;let s=o&&{sheetId:o.sheetId,zone:o.zone};return{...t,dataSet:s}}});function PF(e,t){if(!e)return;let n=t(e);switch(n.changeType){case`NONE`:return e;case`REMOVE`:return;default:return n.range}}var FF=class extends hd{pivotId;mutators=[`reset`,`deferUpdates`,`applyUpdate`,`discardPendingUpdate`,`update`];updatesAreDeferred=!1;draft=null;notification=this.get(sP);alreadyNotified=!1;constructor(e,t){super(e),this.pivotId=t}handle(e){switch(e.type){case`UPDATE_PIVOT`:e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){let e=jF.get(this.pivot.type).definition;return this.draft?new e(this.draft,this.fields,this.getters):this.pivot.definition}get isDirty(){return!!this.draft}get measureFields(){let e=[{name:`__count`,string:E(`Count`),type:`integer`,aggregator:`sum`}],t=this.fields;for(let n in t){let r=t[n];r&&jF.get(this.pivot.type).isMeasureCandidate(r)&&e.push(r)}return e.sort((e,t)=>e.string.localeCompare(t.string))}get unusedGroupableFields(){let e=[],t=this.fields;for(let n in t){let r=t[n];r&&jF.get(this.pivot.type).isGroupable(r)&&e.push(r)}let{columns:n,rows:r,measures:i}=this.definition,a=i.concat(r).concat(n).map(e=>e.fieldName),o=this.unusedGranularities;return e.filter(e=>Mu(e)?!a.includes(e.name)||o[e.name].size>0:!a.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get datetimeGranularities(){return jF.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return jF.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){this.updatesAreDeferred=e,e===!1&&this.draft&&this.applyUpdate()}applyUpdate(){if(this.draft&&(this.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&this.isUpdatedPivotVisibleInViewportOnlyAsStaticPivot())){let e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:`info`,text:E(`Pivot updates only work with dynamic pivot tables. Use %s or re-insert the static pivot from the Data menu.`,e),sticky:!0})}}discardPendingUpdate(){this.draft=null}update(e){let t=this.getters.getPivotCoreDefinition(this.pivotId),n={...t,...this.draft,...e},r={...n,columns:n.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:n.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:n.measures.map(e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display}))};if(!this.draft&&C(t,r))return;let i=this.addDefaultDateTimeGranularity(this.fields,r);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0,t=this.getters.getPivotFormulaId(this.pivotId);for(let n of this.getters.getVisibleCellPositions()){let r=this.getters.getCell(n);if(r?.isFormula){let n=GE(r.compiledFormula.tokens),i=n?.args[0]?.value;if(n&&t===i.toString()){if(n.functionName===`PIVOT`)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){let{columns:n,rows:r}=t,i=y(n),a=y(r),o=this.getUnusedGranularities(e,t);for(let t of i.concat(a)){let n=e[t.fieldName]?.type;if((n===`date`||n===`datetime`)&&!t.granularity){let e=o[t.fieldName]?.values().next().value;o[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:a}}getUnusedGranularities(e,t){let{columns:n,rows:r}=t,i=n.concat(r).filter(t=>{let n=e[t.fieldName]?.type;return n===`date`||n===`datetime`}),a={};for(let t of i)a[t.fieldName]=new Set(e[t.fieldName]?.type===`date`?this.dateGranularities:this.datetimeGranularities);for(let e of i)a[e.fieldName].delete(e.granularity);return a}},IF=class extends t.Component{static template=`o-spreadsheet-PivotSpreadsheetSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:lF,Section:Z,SelectionInput:ON,Checkbox:TN,PivotDeferUpdate:$P,PivotTitleSection:uF};store;state;pivotSidePanelRef=(0,t.useRef)(`pivotSidePanel`);setup(){this.store=ld(FF,this.props.pivotId),this.state=(0,t.useState)({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return this.store.isDirty&&this.state.rangeHasChanged?!1:this.pivot.isInvalidRange}get ranges(){return this.state.range?[this.state.range]:this.definition.range?[this.env.model.getters.getRangeString(this.definition.range,`forceSheetReference`)]:[]}get pivot(){return this.store.pivot}get definition(){return this.store.definition}getScrollableContainerEl(){return this.pivotSidePanelRef.el}onSelectionChanged(e){this.state.rangeHasChanged=!0,this.state.range=e[0]}onSelectionConfirmed(){if(this.state.range){let e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;let t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){let{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}};let LF=new h;LF.add(`SPREADSHEET`,{editor:IF});var RF=class extends t.Component{static template=`o-spreadsheet-PivotSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:lF,Section:Z};get sidePanelEditor(){let e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw Error(`pivotId does not correspond to a pivot.`);return LF.get(e.type).editor}};H`
1302
+ `;var lF=class extends t.Component{static template=`o-spreadsheet-PivotLayoutConfigurator`;static components={AddDimensionButton:tF,PivotDimension:iF,PivotDimensionOrder:oF,PivotDimensionGranularity:aF,PivotMeasureEditor:cF};static props={definition:Object,onDimensionsUpdated:Function,unusedGroupableFields:Array,measureFields:Array,unusedGranularities:Object,dateGranularities:Array,datetimeGranularities:Array,getScrollableContainerEl:{type:Function,optional:!0},pivotId:String};dimensionsRef=(0,t.useRef)(`pivot-dimensions`);dragAndDrop=fP();AGGREGATORS=Eu;composerFocus;isDateOrDatetimeField=Mu;setup(){this.composerFocus=V(_d)}startDragAndDrop(e,t){if(t.button!==0||t.target.tagName===`SELECT`)return;let n=this.getDimensionElementsRects(),{columns:r,rows:i}=this.props.definition,a=[...r.map(e=>e.nameWithGranularity),`__rows_title__`,...i.map(e=>e.nameWithGranularity)],o=r.concat(i),s=a.map((e,t)=>({id:e,size:n[t+1].height,position:n[t+1].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:s,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=a.findIndex(t=>t===e);if(n===t)return;let r=[...a];r.splice(n,1),r.splice(t,0,e);let i=r.slice(0,r.indexOf(`__rows_title__`)),s=r.slice(r.indexOf(`__rows_title__`)+1);this.props.onDimensionsUpdated({columns:i.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(S),rows:s.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(S)})}})}getGranularitiesFor(e){return Mu(e)?e.type===`date`?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(t.button!==0||t.target.tagName===`SELECT`||t.target.tagName===`INPUT`||this.composerFocus.focusMode!==`inactive`)return;let n=this.getDimensionElementsRects(),{measures:r,columns:i,rows:a}=this.props.definition,o=r.map(e=>e.id),s=3+i.length+a.length,c=o.map((e,t)=>({id:e,size:n[t+s].height,position:n[t+s].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=o.findIndex(t=>t===e);if(n===t)return;let i=[...o];i.splice(n,1),i.splice(t,0,e),this.props.onDimensionsUpdated({measures:i.map(e=>r.find(t=>t.id===e)).filter(S)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{let t=getComputedStyle(e),n=e.getBoundingClientRect();return{x:n.x,y:n.y,width:n.width+parseInt(t.marginLeft||`0`)+parseInt(t.marginRight||`0`),height:n.height+parseInt(t.marginTop||`0`)+parseInt(t.marginBottom||`0`)}})}removeDimension(e){let{columns:t,rows:n}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:n.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){let{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){let{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:`asc`}])})}addRowDimension(e){let{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:`asc`}])})}addMeasureDimension(e){let{measures:t}=this.props.definition,n=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,n),fieldName:e,aggregator:n}])})}updateMeasure(e,t){let{measures:n}=this.props.definition;this.props.onDimensionsUpdated({measures:n.map(n=>n.id===e.id?t:n)})}getMeasureId(e,t){let n=e.replaceAll(`'`,``)+(t?`:${t}`:``),r=n,i=2;for(;this.props.definition.measures.some(e=>e.id===r);)r=`${n}:${i}`,i++;return r}getDefaultMeasureAggregator(e){let t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:`count`}addCalculatedMeasure(){let{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t,`sum`),fieldName:t,aggregator:`sum`,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:`=0`}}])})}updateOrder(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n)})}updateGranularity(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n)})}getMeasureDescription(e){let t=e.display;if(!t||t.type===`no_calculations`)return``;let n=this.env.model.getters.getPivot(this.props.pivotId),r=[...n.definition.columns,...n.definition.rows].find(e=>e.nameWithGranularity===t.fieldNameWithGranularity),i=r?Hu(r):``;return pg.descriptions[t.type](i)}},uF=class extends t.Component{static template=`o-spreadsheet-PivotTitleSection`;static components={CogWheelMenu:rF,Section:Z,TextInput:nF};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:E(`Flip axes`),icon:`o-spreadsheet-Icon.EXCHANGE`,execute:this.props.flipAxis},{name:E(`Duplicate`),icon:`o-spreadsheet-Icon.COPY`,execute:()=>this.duplicatePivot()},{name:E(`Delete`),icon:`o-spreadsheet-Icon.TRASH`,execute:()=>this.delete()}]}get name(){return this.env.model.getters.getPivotName(this.props.pivotId)}get displayName(){return this.env.model.getters.getPivotDisplayName(this.props.pivotId)}duplicatePivot(){let e=this.env.model.uuidGenerator.smallUuid(),t=this.env.model.uuidGenerator.smallUuid(),n=this.env.model.dispatch(`DUPLICATE_PIVOT_IN_NEW_SHEET`,{pivotId:this.props.pivotId,newPivotId:e,newSheetId:t}),r;r=n.isSuccessful?E(`Pivot duplicated.`):n.isCancelledBecause(`PivotInError`)?E(`Cannot duplicate a pivot in error.`):E(`Pivot duplication failed.`);let i=n.isSuccessful?`success`:`danger`;this.env.notifyUser({text:r,sticky:!1,type:i}),n.isSuccessful&&this.env.openSidePanel(`PivotSidePanel`,{pivotId:e})}delete(){this.env.askConfirmation(E(`Are you sure you want to delete this pivot?`),()=>{this.env.model.dispatch(`REMOVE_PIVOT`,{pivotId:this.props.pivotId})})}onNameChanged(e){let t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.props.pivotId,pivot:{...t,name:e}})}},dF=class{measures;columns;rows;constructor(e,t){this.measures=e.measures.map(e=>fF(t,e)),this.columns=e.columns.map(e=>this.createPivotDimension(t,e)),this.rows=e.rows.map(e=>this.createPivotDimension(t,e))}getDimension(e){let t=this.columns.find(t=>t.nameWithGranularity===e)||this.rows.find(t=>t.nameWithGranularity===e);if(!t)throw new M(E(`Dimension %s does not exist`,e));return t}getMeasure(e){let t=this.measures.find(t=>t.id===e);if(!t)throw new M(E(`Field %s is not a measure`,e));return t}createPivotDimension(e,t){let n=e[t.fieldName],r=n?.type??`integer`,i=n&&Mu(n)?t.granularity:void 0;return{displayName:n?.string??t.fieldName,nameWithGranularity:t.fieldName+(i?`:${i}`:``),fieldName:t.fieldName,granularity:i,type:r,order:t.order,isValid:!!n}}};function fF(e,t){let n=t.fieldName,r=n===`__count`?{name:`__count`,string:E(`Count`),type:`integer`,aggregator:`sum`}:e[n],i=t.aggregator;return{id:t.id,get displayName(){return t.userDefinedName??r?.string??t.fieldName},userDefinedName:t.userDefinedName,fieldName:n,aggregator:i,type:n===`__count`?`integer`:r?.type??`integer`,isValid:!!(r||t.computedBy),isHidden:t.isHidden,format:t.format,computedBy:t.computedBy,display:t.display}}var pF=class extends dF{range;constructor(e,t,n){if(super(e,t),e.dataSet){let{sheetId:t,zone:r}=e.dataSet;this.range=n.getRangeFromZone(t,r)}}},mF=class{columns;rows;measures;fieldsType;maxIndent;pivotCells={};rowTree;colTree;constructor(e,t,n,r){this.columns=e.map(e=>{let t=1;return e.map(e=>(e={...e,offset:t},t+=e.width,e))}),this.rows=t,this.measures=n,this.fieldsType=r,this.maxIndent=Math.max(...this.rows.map(e=>e.indent)),this.rowTree=Et(()=>this.buildRowsTree()),this.colTree=Et(()=>this.buildColumnsTree())}getNumberOfDataColumns(){return this.columns.at(-1)?.length||0}getPivotCells(e=!0,t=!0){let n=JSON.stringify({includeTotal:e,includeColumnHeaders:t});if(!this.pivotCells[n]){let r=this.rows.length,i=this.getNumberOfDataColumns(),a=this.columns.length+r,o=1+i;!e&&r!==1&&--a,!e&&i!==this.measures.length&&(o-=this.measures.length);let s=[],c=t?0:this.columns.length;for(let t=0;t<o;t++){s.push([]);for(let n=c;n<a;n++)!e&&n===a||s[t].push(this.getPivotCell(t,n,e))}this.pivotCells[n]=s}return this.pivotCells[n]}getRowTree(){return this.rowTree()}getColTree(){return this.colTree()}isTotalRow(e){return this.rows[e].indent!==this.maxIndent}getPivotCell(e,t,n=!0){let r=this.columns.length;if(e>0&&t===r-1){let n=this.getColHeaderDomain(e,t);if(!n)return hF;let r=n.at(-1)?.value?.toString()||``;return{type:`MEASURE_HEADER`,domain:n.slice(0,-1),measure:r}}else if(t<=r-1){let n=this.getColHeaderDomain(e,t);return n?{type:`HEADER`,domain:n}:hF}else if(e===0){let e=t-r;return{type:`HEADER`,domain:this.getRowDomain(e)}}else{let i=t-r;return!n&&this.isTotalRow(i)?hF:{type:`VALUE`,domain:[...this.getRowDomain(i),...this.getColDomain(e)],measure:this.getColMeasure(e)}}}getColHeaderDomain(e,t){if(e===0)return;let n=[],r=this.columns[t].find(t=>t.offset===e);if(r){for(let e=0;e<r.fields.length;e++){let t=r.fields[e];if(t===`measure`)n.push({type:`char`,field:t,value:Iu({displayName:`measure`,type:`char`},r.values[e])});else{let{fieldName:i,granularity:a}=ju(t),o=this.fieldsType[i]||`char`;n.push({type:o,field:t,value:Iu({displayName:i,type:o,granularity:a},r.values[e])})}}return n}}getColDomain(e){let t=this.getColHeaderDomain(e,this.columns.length-1);return t?t.slice(0,-1):[]}getColMeasure(e){let t=this.getColHeaderDomain(e,this.columns.length-1)?.at(-1)?.value;if(t==null)throw Error(`Measure is missing`);return t.toString()}getRowDomain(e){let t=[];for(let n=0;n<this.rows[e].fields.length;n++){let r=this.rows[e].fields[n],{fieldName:i,granularity:a}=ju(r),o=this.fieldsType[i]||`char`;t.push({type:o,field:r,value:Iu({displayName:i,type:o,granularity:a},this.rows[e].values[n])})}return t}buildRowsTree(){let e=[],t=0,n={};n[0]=e;for(let r of this.rows){if(r.fields.length===0||r.values.length===0)return e;let i=r.fields.length-1,a=r.fields[i],{fieldName:o,granularity:s}=ju(a),c=Iu({displayName:o,type:this.fieldsType[o]??`char`,granularity:s},r.values[i]);if(i>t){t=i,n[t]=[];let e=n[t-1].at(-1);e&&(e.children=n[t])}t=i;let l={value:c,field:r.fields[i],children:[],width:0};n[t].push(l)}return e}buildColumnsTree(){let e=[],t=this.columns.at(-2)||[],n={};n[0]=e;for(let e of t)for(let t=0;t<e.fields.length;t++){let r=e.fields[t],{fieldName:i,granularity:a}=ju(r),o=Iu({displayName:i,type:this.fieldsType[i]??`char`,granularity:a},e.values[t]),s={value:o,field:e.fields[t],children:[],width:e.width};n[t]?.at(-1)?.value!==o&&(n[t+1]=[],s.children=n[t+1],n[t].push(s))}return e}export(){return{cols:this.columns,rows:this.rows,measures:this.measures,fieldsType:this.fieldsType}}};let hF={type:`EMPTY`};function gF(e,t){let n=t.measures.filter(e=>!e.isHidden).map(e=>e.id),r=vF(e,t.columns,0);yF(r,n.length);let i=bF(r,t),a=_F(e,0,t.rows,[],[]);a.push({fields:[],values:[],indent:0});let o={};for(let e of t.columns)o[e.fieldName]=e.type;for(let e of t.rows)o[e.fieldName]=e.type;return new mF(i,a,n,o)}function _F(e,t,n,r,i){if(t>=n.length)return[];let a=n[t],o=a.nameWithGranularity,s=xF(e,a),c=CF(s,a),l=[],u=r.concat(o);for(let e of c){let r=i.concat(e);l.push({fields:u,values:r,indent:t});let a=s[e];a&&l.push(..._F(a,t+1,n,u,r))}return l}function vF(e,t,n){if(n>=t.length)return[];let r=t[n],i=t[n].nameWithGranularity,a=xF(e,r);return CF(a,t[n]).map(e=>({value:a[e]?.[0]?.[r.nameWithGranularity]?.value??null,field:i,children:vF(a[e]||[],t,n+1),width:0}))}function yF(e,t){for(let n in e){let r=e[n];r.children.length===0?r.width=t:(yF(r.children,t),r.width=r.children.reduce((e,t)=>e+t.width,0))}}function bF(e,t){let n=t.columns.map(e=>e.nameWithGranularity),r=n.length,i=t.measures.filter(e=>!e.isHidden),a=i.length,o=Array(r).fill(0).map(()=>[]);function s(e,t,i){let a=o[t];for(let o of e){let e=i.concat([o.value]),c={fields:n.slice(0,t+1),values:e,width:o.width,offset:0};a.push(c),t<=r-1&&s(o.children,t+1,e)}}s(e,0,[]);let c=n.length>0,l=[];return c&&o[o.length-1].forEach(e=>{i.forEach(t=>{let n={fields:[...e.fields,`measure`],values:[...e.values,t.id],width:1,offset:0};l.push(n)})}),i.forEach(e=>{let t={fields:[`measure`],values:[e.id],width:1,offset:0};l.push(t)}),o.push(l),o.length===1&&o.unshift([]),o[o.length-2].push({fields:[],values:[],width:a,offset:0}),o}function xF(e,t){return Object.groupBy(e,SF(t))}function SF(e){let t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}function CF(e,t){return t.order?Object.keys(e).sort((e,n)=>wF(t,e,n)):Object.keys(e)}function wF(e,t,n){return t===`null`?e.order===`asc`?1:-1:n===`null`?e.order===`asc`?-1:1:e.type===`integer`||e.type===`datetime`?e.order===`asc`?F(t,k)-F(n,k):F(n,k)-F(t,k):e.order===`asc`?t.localeCompare(n):n.localeCompare(t)}let TF=Symbol(`NULL`);function EF(e,t,n){let r=e.granularity||`month`;if(!(r in DF))throw Error(`Unknown date granularity: ${r}`);let i=typeof t==`number`||typeof t==`string`?t:TF;if(!DF[r].set.has(t)){DF[r].set.add(t);let a=null;if(typeof t==`number`||typeof t==`string`){let e=R(t,n);switch(r){case`year`:a=e.getFullYear();break;case`quarter_number`:a=Math.floor(e.getMonth()/3)+1;break;case`month_number`:a=e.getMonth()+1;break;case`month`:a=Math.floor(F(t,n));break;case`iso_week_number`:a=e.getIsoWeek();break;case`day_of_month`:a=e.getDate();break;case`day`:a=Math.floor(F(t,n));break;case`day_of_week`:a=(e.getDay()+7-n.weekStart)%7+1;break;case`hour_number`:a=e.getHours();break;case`minute_number`:a=e.getMinutes();break;case`second_number`:a=e.getSeconds();break}}DF[r].values[i]=Iu(e,a)}return DF[r].values[i]}let DF={year:{set:new Set,values:{}},quarter_number:{set:new Set,values:{}},month_number:{set:new Set,values:{}},month:{set:new Set,values:{}},iso_week_number:{set:new Set,values:{}},day_of_month:{set:new Set,values:{}},day:{set:new Set,values:{}},day_of_week:{set:new Set,values:{}},hour_number:{set:new Set,values:{}},minute_number:{set:new Set,values:{}},second_number:{set:new Set,values:{}}};function OF(){for(let e in DF)DF[e].set.clear(),DF[e].values={}}var kF=class{type=`SPREADSHEET`;getters;_definition;coreDefinition;metaData={fields:{},fieldKeys:[]};dataEntries=[];table;invalidRangeError;needsReevaluation=!0;constructor(e,t){this.getters=t.getters,this.coreDefinition=t.definition}init(e={}){(!this._definition||e.reload)&&(this.reload(4),this.needsReevaluation=!1)}reload(e){e===4&&(this.metaData=this.loadMetaData()),e>=3&&(this._definition=this.loadRuntimeDefinition()),e>=2&&(this.dataEntries=this.loadData()),e>=1&&(this.table=void 0)}onDefinitionChange(e){let t=this.coreDefinition;if(this.coreDefinition=e,this._definition){let n=Math.max(this.computeShouldReload(t,e),0);this.reload(n)}}computeShouldReload(e,t){return C(e.dataSet,t.dataSet)?3:4}get isInvalidRange(){return!!this.invalidRangeError}get invalidRangeMessage(){return this.invalidRangeError?.message}get definition(){if(this._definition||this.init(),!this._definition)throw Error(`Pivot definition should be defined at this point.`);return this._definition}isValid(){if(this.invalidRangeError||!this.definition)return!1;for(let e of this.definition.measures)if(!e.isValid)return!1;for(let e of this.definition.columns)if(!e.isValid)return!1;for(let e of this.definition.rows)if(!e.isValid)return!1;return!0}assertIsValid({throwOnError:e}){if(!this.isValid()){if(e)throw this.invalidRangeError?this.invalidRangeError:new M(E(`At least one measure and/or dimension is not correct.`));return{value:j.GenericError,message:this.invalidRangeError?.message??E(`At least one measure and/or dimension is not correct.`)}}}areDomainArgsFieldsValid(e){let t=e.filter((e,t)=>t%2==0).map(I);return t.length&&t.at(-1)===`measure`&&(t=t.slice(0,-1)),Pu(t,this.definition)}parseArgsToPivotDomain(e){let t=[];for(let n=0;n<e.length-1;n+=2){let r=I(e[n]),i=this.getTypeOfDimension(r),a=r===`measure`?I(e[n+1]):Iu(this.getDimension(r),e[n+1]);t.push({field:r,value:a,type:i})}return t}markAsDirtyForEvaluation(){this.needsReevaluation=!0}getMeasure(e){return this.definition.getMeasure(e)}getPivotMeasureValue(e){return{value:this.getMeasure(e).displayName}}getPivotHeaderValueAndFormat(e){let t=e.at(-1);if(!t)return{value:E(`Total`)};let n=this.getDimension(t.field),r=this.filterDataEntriesFromDomain(this.dataEntries,e)[0]?.[n.nameWithGranularity];return n.type===`datetime`?uu(n.granularity||`month`).toValueAndFormat(t.value,this.getters.getLocale()):r?r.value===null?{value:E(`(Undefined)`)}:r:{value:``}}getPivotCellValueAndFormat(e,t){let n=this.filterDataEntriesFromDomain(this.dataEntries,t);if(n.length===0)return{value:``};let r=this.getMeasure(e),i=n.map(e=>e[r.fieldName]).filter(S),a=i.filter(e=>e.type!==`empty`),o=r.aggregator,s=Du[o];if(!s)throw Error(`Aggregator ${o} does not exist`);try{let e=s([i],this.getters.getLocale());return a.length===0?{...e,value:``}:e}catch(e){return BT(e,o.toUpperCase())}}getPossibleFieldValues(e){let t=[],n=xF(this.dataEntries,e),r=CF(n,e);for(let i of r)t.push({value:n[i]?.[0]?.[e.nameWithGranularity]?.value??``,label:n[i]?.[0]?.[e.nameWithGranularity]?.formattedValue||``});return t}getTableStructure(){if(!this.isValid())throw Error(`Pivot is not valid !`);return this.table||=gF(this.dataEntries,this.definition),this.table}getFields(){return this.metaData.fields}get fields(){return this.getFields()}loadMetaData(){if(this.invalidRangeError=void 0,this.coreDefinition.dataSet){let{zone:e,sheetId:t}=this.coreDefinition.dataSet,n=this.getters.getRangeFromZone(t,e);try{return this.extractFieldsFromRange(n)}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}else return this.invalidRangeError=new M(E(`The pivot cannot be created because the dataset is missing.`)),{fields:{},fieldKeys:[]}}loadRuntimeDefinition(){return new pF(this.coreDefinition,this.fields,this.getters)}loadData(){let e=this._definition?.range;return this.isValid()&&e?this.extractDataEntriesFromRange(e):[]}getTypeOfDimension(e){if(e===`measure`)return`char`;let{fieldName:t}=ju(e),n=this.fields[t]?.type;if(!n)throw Error(`Field ${t} does not exist`);return n}filterDataEntriesFromDomain(e,t){return t.reduce((e,t)=>this.filterDataEntriesFromDomainNode(e,t),e)}filterDataEntriesFromDomainNode(e,t){let{field:n,value:r,type:i}=t,{nameWithGranularity:a}=this.getDimension(n);return e.filter(e=>{let t=e[a]?.value;return i===`char`?String(t)===String(r):t===r})}getDimension(e){return this.definition.getDimension(e)}getTypeFromZone(e,t){let n=this.getters.getEvaluatedCellsInZone(e,t).filter(e=>!(e.type===`empty`||e.value===``));return n.length===0?`integer`:n.every(e=>e.type===`number`&&e.format&&Go(e.format))?`datetime`:n.every(e=>e.type===`boolean`)?`boolean`:n.every(e=>e.type===`number`)?`integer`:`char`}assertCellIsValidField(e,t,n){if(n.type===`error`)throw new M(E(`The pivot cannot be created because cell %s contains an error`,w(e,t)));if(n.type===`empty`||n.value===``)throw new M(E(`The pivot cannot be created because cell %s is empty`,w(e,t)));if(n.value===`__count`)throw new M(E(`The pivot cannot be created because cell %s contains a reserved value`,w(e,t)))}extractFieldsFromRange(e){let t={},n=[],r=e.sheetId,i=e.zone.top;for(let a=e.zone.left;a<=e.zone.right;a++){let o=this.getters.getEvaluatedCell({sheetId:r,col:a,row:i});this.assertCellIsValidField(a,i,o);let s=o.value?.toString();if(s){let i=this.getTypeFromZone(r,{top:e.zone.top+1,left:a,bottom:e.zone.bottom,right:a}),o=this.findName(s,t);t[o]={name:o,type:i,string:o,aggregator:i===`integer`?`sum`:`count`},n.push(o)}}return{fields:t,fieldKeys:n}}findName(e,t){let n=1,r=e;for(;e in t;)e=`${r}${++n}`;return e}extractDataEntriesFromRange(e){let t=[];for(let n=e.zone.top+1;n<=e.zone.bottom;n++){let r={top:n,bottom:n,left:e.zone.left,right:e.zone.right},i=this.getters.getEvaluatedCellsInZone(e.sheetId,r),a={};for(let e in i){let t=i[e],n=this.fields[this.metaData.fieldKeys[e]];if(!n)throw Error(`Field ${this.metaData.fieldKeys[e]} does not exist`);t.value===``?a[n.name]={value:null,type:`empty`,formattedValue:``}:a[n.name]=t}a.__count={value:1,type:`number`,formattedValue:`1`},t.push(a)}let n=this.definition.columns.concat(this.definition.rows).filter(e=>e.type===`datetime`);if(n.length){let e=this.getters.getLocale();for(let r of t)for(let t of n){let n=EF(t,r[t.fieldName]?.value||null,this.getters.getLocale()),{format:i,value:a}=uu(t.granularity||`month`).toValueAndFormat(n,e);r[t.nameWithGranularity]={value:n,type:r[t.fieldName]?.type||`empty`,format:r[t.fieldName]?.format,formattedValue:B(a,{locale:e,format:i})}}}return t}};let AF=new h,jF=[`year`,`quarter_number`,`month_number`,`month`,`iso_week_number`,`day_of_month`,`day`,`day_of_week`],MF=[...jF,`hour_number`,`minute_number`,`second_number`];AF.add(`SPREADSHEET`,{ui:kF,definition:pF,dateGranularities:[...jF],datetimeGranularities:[...MF],isMeasureCandidate:e=>![`datetime`,`boolean`].includes(e.type),isGroupable:()=>!0,adaptRanges:(e,t,n)=>{if(t.type!==`SPREADSHEET`||!t.dataSet)return t;let{sheetId:r,zone:i}=t.dataSet,a=e.getRangeFromZone(r,i),o=NF(a,n);if(o===a)return t;let s=o&&{sheetId:o.sheetId,zone:o.zone};return{...t,dataSet:s}}});function NF(e,t){if(!e)return;let n=t(e);switch(n.changeType){case`NONE`:return e;case`REMOVE`:return;default:return n.range}}var PF=class extends hd{pivotId;mutators=[`reset`,`deferUpdates`,`applyUpdate`,`discardPendingUpdate`,`update`];updatesAreDeferred=!1;draft=null;notification=this.get(sP);alreadyNotified=!1;constructor(e,t){super(e),this.pivotId=t}handle(e){switch(e.type){case`UPDATE_PIVOT`:e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){let e=AF.get(this.pivot.type).definition;return this.draft?new e(this.draft,this.fields,this.getters):this.pivot.definition}get isDirty(){return!!this.draft}get measureFields(){let e=[{name:`__count`,string:E(`Count`),type:`integer`,aggregator:`sum`}],t=this.fields;for(let n in t){let r=t[n];r&&AF.get(this.pivot.type).isMeasureCandidate(r)&&e.push(r)}return e.sort((e,t)=>e.string.localeCompare(t.string))}get unusedGroupableFields(){let e=[],t=this.fields;for(let n in t){let r=t[n];r&&AF.get(this.pivot.type).isGroupable(r)&&e.push(r)}let{columns:n,rows:r,measures:i}=this.definition,a=i.concat(r).concat(n).map(e=>e.fieldName),o=this.unusedGranularities;return e.filter(e=>Mu(e)?!a.includes(e.name)||o[e.name].size>0:!a.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get datetimeGranularities(){return AF.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return AF.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){this.updatesAreDeferred=e,e===!1&&this.draft&&this.applyUpdate()}applyUpdate(){if(this.draft&&(this.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&this.isUpdatedPivotVisibleInViewportOnlyAsStaticPivot())){let e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:`info`,text:E(`Pivot updates only work with dynamic pivot tables. Use %s or re-insert the static pivot from the Data menu.`,e),sticky:!0})}}discardPendingUpdate(){this.draft=null}update(e){let t=this.getters.getPivotCoreDefinition(this.pivotId),n={...t,...this.draft,...e},r={...n,columns:n.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:n.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:n.measures.map(e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display}))};if(!this.draft&&C(t,r))return;let i=this.addDefaultDateTimeGranularity(this.fields,r);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0,t=this.getters.getPivotFormulaId(this.pivotId);for(let n of this.getters.getVisibleCellPositions()){let r=this.getters.getCell(n);if(r?.isFormula){let n=GE(r.compiledFormula.tokens),i=n?.args[0]?.value;if(n&&t===i.toString()){if(n.functionName===`PIVOT`)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){let{columns:n,rows:r}=t,i=y(n),a=y(r),o=this.getUnusedGranularities(e,t);for(let t of i.concat(a)){let n=e[t.fieldName]?.type;if((n===`date`||n===`datetime`)&&!t.granularity){let e=o[t.fieldName]?.values().next().value;o[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:a}}getUnusedGranularities(e,t){let{columns:n,rows:r}=t,i=n.concat(r).filter(t=>{let n=e[t.fieldName]?.type;return n===`date`||n===`datetime`}),a={};for(let t of i)a[t.fieldName]=new Set(e[t.fieldName]?.type===`date`?this.dateGranularities:this.datetimeGranularities);for(let e of i)a[e.fieldName].delete(e.granularity);return a}},FF=class extends t.Component{static template=`o-spreadsheet-PivotSpreadsheetSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:lF,Section:Z,SelectionInput:ON,Checkbox:TN,PivotDeferUpdate:$P,PivotTitleSection:uF};store;state;pivotSidePanelRef=(0,t.useRef)(`pivotSidePanel`);setup(){this.store=ld(PF,this.props.pivotId),this.state=(0,t.useState)({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return this.store.isDirty&&this.state.rangeHasChanged?!1:this.pivot.isInvalidRange}get ranges(){return this.state.range?[this.state.range]:this.definition.range?[this.env.model.getters.getRangeString(this.definition.range,`forceSheetReference`)]:[]}get pivot(){return this.store.pivot}get definition(){return this.store.definition}getScrollableContainerEl(){return this.pivotSidePanelRef.el}onSelectionChanged(e){this.state.rangeHasChanged=!0,this.state.range=e[0]}onSelectionConfirmed(){if(this.state.range){let e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;let t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){let{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}};let IF=new h;IF.add(`SPREADSHEET`,{editor:FF});var LF=class extends t.Component{static template=`o-spreadsheet-PivotSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:lF,Section:Z};get sidePanelEditor(){let e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw Error(`pivotId does not correspond to a pivot.`);return IF.get(e.type).editor}};H`
1303
1303
  .o-checkbox-selection {
1304
1304
  max-height: 300px;
1305
1305
  }
1306
- `;var zF=class extends t.Component{static template=`o-spreadsheet-RemoveDuplicatesPanel`;static components={ValidationMessages:AN,Section:Z,Checkbox:TN};static props={onCloseSidePanel:Function};state=(0,t.useState)({hasHeader:!1,columns:{}});setup(){this.updateColumns(),(0,t.onWillUpdateProps)(()=>this.updateColumns())}toggleHasHeader(){this.state.hasHeader=!this.state.hasHeader}toggleAllColumns(){let e=!this.isEveryColumnSelected;for(let 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){let t=parseInt(e),n=E(`Column %s`,Tn(t));if(this.state.hasHeader){let e=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone().top,i=this.env.model.getters.getEvaluatedCell({sheetId:e,col:t,row:r});i.type!==`empty`&&(n+=` - ${i.value}`)}return n}get isEveryColumnSelected(){return Object.values(this.state.columns).every(e=>e===!0)}get errorMessages(){let e=this.env.model.canDispatch(`REMOVE_DUPLICATES`,{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()}).reasons,t=new Set;for(let n of e)t.add(ug.Errors[n]||ug.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){let e=pr(this.env.model.getters.getSelectedZone());return E(`%(row_count)s rows and %(column_count)s columns selected`,{row_count:e.numberOfRows,column_count:e.numberOfCols})}get canConfirm(){return this.errorMessages.length===0}updateColumns(){let e=this.env.model.getters.getSelectedZone(),t=this.state.columns,n={};for(let r=e.left;r<=e.right;r++)n[r]=r in t?t[r]:!0;this.state.columns=n}getColsToAnalyze(){return Object.keys(this.state.columns).filter(e=>this.state.columns[e]).map(e=>parseInt(e))}};H`
1306
+ `;var RF=class extends t.Component{static template=`o-spreadsheet-RemoveDuplicatesPanel`;static components={ValidationMessages:AN,Section:Z,Checkbox:TN};static props={onCloseSidePanel:Function};state=(0,t.useState)({hasHeader:!1,columns:{}});setup(){this.updateColumns(),(0,t.onWillUpdateProps)(()=>this.updateColumns())}toggleHasHeader(){this.state.hasHeader=!this.state.hasHeader}toggleAllColumns(){let e=!this.isEveryColumnSelected;for(let 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){let t=parseInt(e),n=E(`Column %s`,Tn(t));if(this.state.hasHeader){let e=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone().top,i=this.env.model.getters.getEvaluatedCell({sheetId:e,col:t,row:r});i.type!==`empty`&&(n+=` - ${i.value}`)}return n}get isEveryColumnSelected(){return Object.values(this.state.columns).every(e=>e===!0)}get errorMessages(){let e=this.env.model.canDispatch(`REMOVE_DUPLICATES`,{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()}).reasons,t=new Set;for(let n of e)t.add(ug.Errors[n]||ug.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){let e=pr(this.env.model.getters.getSelectedZone());return E(`%(row_count)s rows and %(column_count)s columns selected`,{row_count:e.numberOfRows,column_count:e.numberOfCols})}get canConfirm(){return this.errorMessages.length===0}updateColumns(){let e=this.env.model.getters.getSelectedZone(),t=this.state.columns,n={};for(let r=e.left;r<=e.right;r++)n[r]=r in t?t[r]:!0;this.state.columns=n}getColsToAnalyze(){return Object.keys(this.state.columns).filter(e=>this.state.columns[e]).map(e=>parseInt(e))}};H`
1307
1307
  .o-locale-preview {
1308
1308
  border: 1px solid ${ve};
1309
1309
  background-color: ${be};
1310
1310
  }
1311
- `;var BF=class extends t.Component{static template=`o-spreadsheet-SettingsPanel`;static components={Section:Z,ValidationMessages:AN};static props={onCloseSidePanel:Function};loadedLocales=[];setup(){(0,t.onWillStart)(()=>this.loadLocales())}onLocaleChange(e){let 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=>{let t=el(e);return t||console.warn(`Invalid locale: ${e.code} ${e}`),t}).sort((e,t)=>e.name.localeCompare(t.name))}get numberFormatPreview(){return B(1234567.89,{format:`#,##0.00`,locale:this.env.model.getters.getLocale()})}get dateFormatPreview(){let e=this.env.model.getters.getLocale();return B(1.6,{format:e.dateFormat,locale:e})}get dateTimeFormatPreview(){let e=this.env.model.getters.getLocale();return B(1.6,{format:_l(e),locale:e})}get firstDayOfWeek(){return Mo[this.env.model.getters.getLocale().weekStart%7]}get currentLocale(){return this.env.model.getters.getLocale()}get supportedLocales(){let 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(!C(e,t)){let n=this.loadedLocales.indexOf(t),r=[...this.loadedLocales];return r[n]=e,r.sort((e,t)=>e.name.localeCompare(t.name)),r}return this.loadedLocales}};let VF={SplitIsDestructive:E(`This will overwrite data in the subsequent columns. Split anyway?`)};function HF(e,t,n){let r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n});return r.isCancelledBecause(`SplitWillOverwriteContent`)&&e.askConfirmation(VF.SplitIsDestructive,()=>{r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n,force:!0})}),r}let UF=[{name:E(`Detect automatically`),value:`auto`},{name:E(`Custom separator`),value:`custom`},{name:E(`Space`),value:` `},{name:E(`Comma`),value:`,`},{name:E(`Semicolon`),value:`;`},{name:E(`Line Break`),value:`
1312
- `}];var WF=class extends t.Component{static template=`o-spreadsheet-SplitIntoColumnsPanel`;static components={ValidationMessages:AN,Section:Z,Checkbox:TN};static props={onCloseSidePanel:Function};state=(0,t.useState)({separatorValue:`auto`,addNewColumns:!1,customSeparator:``});setup(){let e=V(_d);(0,t.useEffect)(e=>{e!==`inactive`&&this.props.onCloseSidePanel()},()=>[e.focusMode]),(0,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(){HF(this.env,this.separatorValue,this.state.addNewColumns).isSuccessful&&this.props.onCloseSidePanel()}get errorMessages(){let e=this.env.model.canDispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!0}).reasons,t=new Set;for(let n of e)switch(n){case`SplitWillOverwriteContent`:case`EmptySplitSeparator`:break;default:t.add(lg.Errors[n]||lg.Errors.Unexpected)}return Array.from(t)}get warningMessages(){let e=[];return this.env.model.canDispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!1}).reasons.includes(`SplitWillOverwriteContent`)&&e.push(lg.Errors.SplitWillOverwriteContent),e}get separatorValue(){return this.state.separatorValue===`custom`?this.state.customSeparator:this.state.separatorValue===`auto`?this.env.model.getters.getAutomaticSeparator():this.state.separatorValue}get separators(){return UF}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}};let GF=[`wholeTable`,`firstColumnStripe`,`secondColumnStripe`,`firstRowStripe`,`secondRowStripe`,`firstColumn`,`lastColumn`,`headerRow`,`totalRow`];function KF(e,t){let n=t.numberOfHeaders,r={...e,top:e.top+n};return r.top<=r.bottom?r:void 0}function qF(e){let t=e.range;return{row:t.zone.top,col:t.zone.left,sheetId:t.sheetId}}function JF(e,t,n,r){let i=t.zone;if(i.left!==i.right)throw Error(`Can only define a filter on a single column`);let a={...i,top:i.top+n.numberOfHeaders},o=r(t.sheetId,a);return{id:e,rangeWithHeaders:t,col:i.left,filteredRange:a.top>a.bottom?void 0:o}}function YF(e){return e.type===`static`||e.type===`forceStatic`}function XF(e,t,n,r){return{borders:ZF(e,t,n,r),styles:$F(e,t,n,r)}}function ZF(e,t,n,r){let i=ja(n,r,()=>({}));for(let a of GF){let o=t[a]?.border;if(!o)continue;let s=tI(a,e,n,r);for(let t of s)for(let s=t.left;s<=t.right;s++)for(let c=t.top;c<=t.bottom;c++){let l=a===`wholeTable`&&c<=e.numberOfHeaders-1;c===t.top&&o?.top?QF(i,`top`,o.top,s,c,n,r):c!==t.top&&!l&&o?.horizontal&&QF(i,`top`,o.horizontal,s,c,n,r),c===t.bottom&&o?.bottom&&QF(i,`bottom`,o.bottom,s,c,n,r),s===t.left&&o?.left&&QF(i,`left`,o.left,s,c,n,r),s===t.right&&o?.right?QF(i,`right`,o.right,s,c,n,r):s!==t.right&&!l&&o?.vertical&&QF(i,`right`,o.vertical,s,c,n,r)}}return i}function QF(e,t,n,r,i,a,o){switch(t){case`top`:e[r][i].top=n,i!==0&&(e[r][i-1].bottom=n);return;case`bottom`:e[r][i].bottom=n,i!==o-1&&(e[r][i+1].top=n);return;case`left`:e[r][i].left=n,r!==0&&(e[r-1][i].right=n);return;case`right`:e[r][i].right=n,r!==a-1&&(e[r+1][i].left=n);return}}function $F(e,t,n,r){let i=ja(n,r,()=>({}));for(let a of GF){let o=t[a],s=eI(a);if(!o&&!s)continue;let c=tI(a,e,n,r);for(let e of c)for(let t=e.left;t<=e.right;t++)for(let n=e.top;n<=e.bottom;n++)i[t][n]||(i[t][n]={}),i[t][n]={...i[t][n],...o?.style},s&&(i[t][n].bold=!0)}return i}function eI(e){return e===`firstColumn`||e===`lastColumn`||e===`headerRow`||e===`totalRow`}function tI(e,t,n,r){let i=[],a=Math.min(t.numberOfHeaders,r),o=+!!t.totalRow,s=n-1,c=r-1;switch(e){case`wholeTable`:i.push({top:0,left:0,bottom:c,right:s});break;case`firstColumn`:if(!t.firstColumn)break;i.push({top:0,left:0,bottom:c,right:0});break;case`lastColumn`:if(!t.lastColumn)break;i.push({top:0,left:s,bottom:c,right:s});break;case`headerRow`:if(!t.numberOfHeaders)break;i.push({top:0,left:0,bottom:a-1,right:s});break;case`totalRow`:if(!t.totalRow)break;i.push({top:c,left:0,bottom:c,right:s});break;case`firstRowStripe`:if(!t.bandedRows)break;for(let e=a;e<r-o;e+=2)i.push({top:e,left:0,bottom:e,right:s});break;case`secondRowStripe`:if(!t.bandedRows)break;for(let e=a+1;e<r-o;e+=2)i.push({top:e,left:0,bottom:e,right:s});break;case`firstColumnStripe`:if(!t.bandedColumns)break;for(let e=0;e<n;e+=2)i.push({top:a,left:e,bottom:c-o,right:e});break;case`secondColumnStripe`:if(!t.bandedColumns)break;for(let e=1;e<n;e+=2)i.push({top:a,left:e,bottom:c-o,right:e});break}return i}function nI(e,t){return e.model.getters.isTableStyleEditable(t)?f([{id:`editTableStyle`,name:E(`Edit table style`),execute:e=>e.openSidePanel(`TableStyleEditorPanel`,{styleId:t}),icon:`o-spreadsheet-Icon.EDIT`},{id:`deleteTableStyle`,name:E(`Delete table style`),execute:e=>e.model.dispatch(`REMOVE_TABLE_STYLE`,{tableStyleId:t}),icon:`o-spreadsheet-Icon.TRASH`}]):[]}function rI(e,t,n,r){e.resetTransform(),iI(e,t,n,r),aI(e,t,n,r),oI(e,t,n,r)}function iI(e,t,n,r){e.save();for(let i=0;i<5;i++)for(let a=0;a<5;a++)e.fillStyle=t.styles[i][a].fillColor||`#fff`,e.fillRect(i*n,a*r,n,r);e.restore()}function aI(e,t,n,r){e.save(),e.translate(0,.5),e.lineWidth=1;for(let i=0;i<5;i++)for(let a=0;a<5;a++){let o=t.borders[i][a];o.top&&(e.strokeStyle=o.top.color,e.beginPath(),e.moveTo(i*n,a*r),e.lineTo(i*n+n,a*r),e.stroke()),o.bottom&&(e.strokeStyle=o.bottom.color,e.beginPath(),e.moveTo(i*n,a*r+r),e.lineTo(i*n+n,a*r+r),e.stroke())}e.resetTransform(),e.translate(.5,0);for(let i=0;i<5;i++)for(let a=0;a<5;a++){let o=t.borders[i][a];o.left&&(e.strokeStyle=o.left.color,e.beginPath(),e.moveTo(i*n,a*r),e.lineTo(i*n,a*r+r),e.stroke()),o.right&&(e.strokeStyle=o.right.color,e.beginPath(),e.moveTo(i*n+n,a*r),e.lineTo(i*n+n,a*r+r+1),e.stroke())}e.restore()}function oI(e,t,n,r){e.save(),e.translate(0,.5),e.lineWidth=1;let i=Math.floor(n/4),a=Math.floor(r/2);for(let o=0;o<5;o++)for(let s=0;s<5;s++)e.strokeStyle=t.styles[o][s].textColor||`#000`,e.beginPath(),e.moveTo(o*n+i+1,s*r+a),e.lineTo(o*n+n-i,s*r+a),e.stroke();e.restore()}H`
1311
+ `;var zF=class extends t.Component{static template=`o-spreadsheet-SettingsPanel`;static components={Section:Z,ValidationMessages:AN};static props={onCloseSidePanel:Function};loadedLocales=[];setup(){(0,t.onWillStart)(()=>this.loadLocales())}onLocaleChange(e){let 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=>{let t=el(e);return t||console.warn(`Invalid locale: ${e.code} ${e}`),t}).sort((e,t)=>e.name.localeCompare(t.name))}get numberFormatPreview(){return B(1234567.89,{format:`#,##0.00`,locale:this.env.model.getters.getLocale()})}get dateFormatPreview(){let e=this.env.model.getters.getLocale();return B(1.6,{format:e.dateFormat,locale:e})}get dateTimeFormatPreview(){let e=this.env.model.getters.getLocale();return B(1.6,{format:_l(e),locale:e})}get firstDayOfWeek(){return Mo[this.env.model.getters.getLocale().weekStart%7]}get currentLocale(){return this.env.model.getters.getLocale()}get supportedLocales(){let 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(!C(e,t)){let n=this.loadedLocales.indexOf(t),r=[...this.loadedLocales];return r[n]=e,r.sort((e,t)=>e.name.localeCompare(t.name)),r}return this.loadedLocales}};let BF={SplitIsDestructive:E(`This will overwrite data in the subsequent columns. Split anyway?`)};function VF(e,t,n){let r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n});return r.isCancelledBecause(`SplitWillOverwriteContent`)&&e.askConfirmation(BF.SplitIsDestructive,()=>{r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n,force:!0})}),r}let HF=[{name:E(`Detect automatically`),value:`auto`},{name:E(`Custom separator`),value:`custom`},{name:E(`Space`),value:` `},{name:E(`Comma`),value:`,`},{name:E(`Semicolon`),value:`;`},{name:E(`Line Break`),value:`
1312
+ `}];var UF=class extends t.Component{static template=`o-spreadsheet-SplitIntoColumnsPanel`;static components={ValidationMessages:AN,Section:Z,Checkbox:TN};static props={onCloseSidePanel:Function};state=(0,t.useState)({separatorValue:`auto`,addNewColumns:!1,customSeparator:``});setup(){let e=V(_d);(0,t.useEffect)(e=>{e!==`inactive`&&this.props.onCloseSidePanel()},()=>[e.focusMode]),(0,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(){VF(this.env,this.separatorValue,this.state.addNewColumns).isSuccessful&&this.props.onCloseSidePanel()}get errorMessages(){let e=this.env.model.canDispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!0}).reasons,t=new Set;for(let n of e)switch(n){case`SplitWillOverwriteContent`:case`EmptySplitSeparator`:break;default:t.add(lg.Errors[n]||lg.Errors.Unexpected)}return Array.from(t)}get warningMessages(){let e=[];return this.env.model.canDispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!1}).reasons.includes(`SplitWillOverwriteContent`)&&e.push(lg.Errors.SplitWillOverwriteContent),e}get separatorValue(){return this.state.separatorValue===`custom`?this.state.customSeparator:this.state.separatorValue===`auto`?this.env.model.getters.getAutomaticSeparator():this.state.separatorValue}get separators(){return HF}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}};let WF=[`wholeTable`,`firstColumnStripe`,`secondColumnStripe`,`firstRowStripe`,`secondRowStripe`,`firstColumn`,`lastColumn`,`headerRow`,`totalRow`];function GF(e,t){let n=t.numberOfHeaders,r={...e,top:e.top+n};return r.top<=r.bottom?r:void 0}function KF(e){let t=e.range;return{row:t.zone.top,col:t.zone.left,sheetId:t.sheetId}}function qF(e,t,n,r){let i=t.zone;if(i.left!==i.right)throw Error(`Can only define a filter on a single column`);let a={...i,top:i.top+n.numberOfHeaders},o=r(t.sheetId,a);return{id:e,rangeWithHeaders:t,col:i.left,filteredRange:a.top>a.bottom?void 0:o}}function JF(e){return e.type===`static`||e.type===`forceStatic`}function YF(e,t,n,r){return{borders:XF(e,t,n,r),styles:QF(e,t,n,r)}}function XF(e,t,n,r){let i=ja(n,r,()=>({}));for(let a of WF){let o=t[a]?.border;if(!o)continue;let s=eI(a,e,n,r);for(let t of s)for(let s=t.left;s<=t.right;s++)for(let c=t.top;c<=t.bottom;c++){let l=a===`wholeTable`&&c<=e.numberOfHeaders-1;c===t.top&&o?.top?ZF(i,`top`,o.top,s,c,n,r):c!==t.top&&!l&&o?.horizontal&&ZF(i,`top`,o.horizontal,s,c,n,r),c===t.bottom&&o?.bottom&&ZF(i,`bottom`,o.bottom,s,c,n,r),s===t.left&&o?.left&&ZF(i,`left`,o.left,s,c,n,r),s===t.right&&o?.right?ZF(i,`right`,o.right,s,c,n,r):s!==t.right&&!l&&o?.vertical&&ZF(i,`right`,o.vertical,s,c,n,r)}}return i}function ZF(e,t,n,r,i,a,o){switch(t){case`top`:e[r][i].top=n,i!==0&&(e[r][i-1].bottom=n);return;case`bottom`:e[r][i].bottom=n,i!==o-1&&(e[r][i+1].top=n);return;case`left`:e[r][i].left=n,r!==0&&(e[r-1][i].right=n);return;case`right`:e[r][i].right=n,r!==a-1&&(e[r+1][i].left=n);return}}function QF(e,t,n,r){let i=ja(n,r,()=>({}));for(let a of WF){let o=t[a],s=$F(a);if(!o&&!s)continue;let c=eI(a,e,n,r);for(let e of c)for(let t=e.left;t<=e.right;t++)for(let n=e.top;n<=e.bottom;n++)i[t][n]||(i[t][n]={}),i[t][n]={...i[t][n],...o?.style},s&&(i[t][n].bold=!0)}return i}function $F(e){return e===`firstColumn`||e===`lastColumn`||e===`headerRow`||e===`totalRow`}function eI(e,t,n,r){let i=[],a=Math.min(t.numberOfHeaders,r),o=+!!t.totalRow,s=n-1,c=r-1;switch(e){case`wholeTable`:i.push({top:0,left:0,bottom:c,right:s});break;case`firstColumn`:if(!t.firstColumn)break;i.push({top:0,left:0,bottom:c,right:0});break;case`lastColumn`:if(!t.lastColumn)break;i.push({top:0,left:s,bottom:c,right:s});break;case`headerRow`:if(!t.numberOfHeaders)break;i.push({top:0,left:0,bottom:a-1,right:s});break;case`totalRow`:if(!t.totalRow)break;i.push({top:c,left:0,bottom:c,right:s});break;case`firstRowStripe`:if(!t.bandedRows)break;for(let e=a;e<r-o;e+=2)i.push({top:e,left:0,bottom:e,right:s});break;case`secondRowStripe`:if(!t.bandedRows)break;for(let e=a+1;e<r-o;e+=2)i.push({top:e,left:0,bottom:e,right:s});break;case`firstColumnStripe`:if(!t.bandedColumns)break;for(let e=0;e<n;e+=2)i.push({top:a,left:e,bottom:c-o,right:e});break;case`secondColumnStripe`:if(!t.bandedColumns)break;for(let e=1;e<n;e+=2)i.push({top:a,left:e,bottom:c-o,right:e});break}return i}function tI(e,t){return e.model.getters.isTableStyleEditable(t)?f([{id:`editTableStyle`,name:E(`Edit table style`),execute:e=>e.openSidePanel(`TableStyleEditorPanel`,{styleId:t}),icon:`o-spreadsheet-Icon.EDIT`},{id:`deleteTableStyle`,name:E(`Delete table style`),execute:e=>e.model.dispatch(`REMOVE_TABLE_STYLE`,{tableStyleId:t}),icon:`o-spreadsheet-Icon.TRASH`}]):[]}function nI(e,t,n,r){e.resetTransform(),rI(e,t,n,r),iI(e,t,n,r),aI(e,t,n,r)}function rI(e,t,n,r){e.save();for(let i=0;i<5;i++)for(let a=0;a<5;a++)e.fillStyle=t.styles[i][a].fillColor||`#fff`,e.fillRect(i*n,a*r,n,r);e.restore()}function iI(e,t,n,r){e.save(),e.translate(0,.5),e.lineWidth=1;for(let i=0;i<5;i++)for(let a=0;a<5;a++){let o=t.borders[i][a];o.top&&(e.strokeStyle=o.top.color,e.beginPath(),e.moveTo(i*n,a*r),e.lineTo(i*n+n,a*r),e.stroke()),o.bottom&&(e.strokeStyle=o.bottom.color,e.beginPath(),e.moveTo(i*n,a*r+r),e.lineTo(i*n+n,a*r+r),e.stroke())}e.resetTransform(),e.translate(.5,0);for(let i=0;i<5;i++)for(let a=0;a<5;a++){let o=t.borders[i][a];o.left&&(e.strokeStyle=o.left.color,e.beginPath(),e.moveTo(i*n,a*r),e.lineTo(i*n,a*r+r),e.stroke()),o.right&&(e.strokeStyle=o.right.color,e.beginPath(),e.moveTo(i*n+n,a*r),e.lineTo(i*n+n,a*r+r+1),e.stroke())}e.restore()}function aI(e,t,n,r){e.save(),e.translate(0,.5),e.lineWidth=1;let i=Math.floor(n/4),a=Math.floor(r/2);for(let o=0;o<5;o++)for(let s=0;s<5;s++)e.strokeStyle=t.styles[o][s].textColor||`#000`,e.beginPath(),e.moveTo(o*n+i+1,s*r+a),e.lineTo(o*n+n-i,s*r+a),e.stroke();e.restore()}H`
1313
1313
  .o-table-style-list-item {
1314
1314
  border: 1px solid transparent;
1315
1315
  border-radius: 4px;
@@ -1336,7 +1336,7 @@ stores.inject(MyMetaStore, storeInstance);
1336
1336
  }
1337
1337
  }
1338
1338
  }
1339
- `;var sI=class extends t.Component{static template=`o-spreadsheet-TableStylePreview`;static components={Menu:pk};static props={tableConfig:Object,tableStyle:Object,class:String,styleId:{type:String,optional:!0},selected:{type:Boolean,optional:!0},onClick:{type:Function,optional:!0}};canvasRef=(0,t.useRef)(`canvas`);menu=(0,t.useState)({isOpen:!1,position:null,menuItems:[]});setup(){(0,t.onWillUpdateProps)(e=>{(!C(this.props.tableConfig,e.tableConfig)||!C(this.props.tableStyle,e.tableStyle))&&this.drawTable(e)}),(0,t.onMounted)(()=>this.drawTable(this.props))}drawTable(e){let t=this.canvasRef.el.getContext(`2d`),{width:n,height:r}=this.canvasRef.el.getBoundingClientRect();this.canvasRef.el.width=n,this.canvasRef.el.height=r,rI(t,XF(e.tableConfig,e.tableStyle,5,5),(n-1)/5,(r-1)/5)}onContextMenu(e){this.props.styleId&&(this.menu.menuItems=nI(this.env,this.props.styleId),this.menu.isOpen=!0,this.menu.position={x:e.clientX,y:e.clientY})}closeMenu(){this.menu.isOpen=!1,this.menu.position=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):!1}editTableStyle(){this.env.openSidePanel(`TableStyleEditorPanel`,{styleId:this.props.styleId})}};H`
1339
+ `;var oI=class extends t.Component{static template=`o-spreadsheet-TableStylePreview`;static components={Menu:pk};static props={tableConfig:Object,tableStyle:Object,class:String,styleId:{type:String,optional:!0},selected:{type:Boolean,optional:!0},onClick:{type:Function,optional:!0}};canvasRef=(0,t.useRef)(`canvas`);menu=(0,t.useState)({isOpen:!1,position:null,menuItems:[]});setup(){(0,t.onWillUpdateProps)(e=>{(!C(this.props.tableConfig,e.tableConfig)||!C(this.props.tableStyle,e.tableStyle))&&this.drawTable(e)}),(0,t.onMounted)(()=>this.drawTable(this.props))}drawTable(e){let t=this.canvasRef.el.getContext(`2d`),{width:n,height:r}=this.canvasRef.el.getBoundingClientRect();this.canvasRef.el.width=n,this.canvasRef.el.height=r,nI(t,YF(e.tableConfig,e.tableStyle,5,5),(n-1)/5,(r-1)/5)}onContextMenu(e){this.props.styleId&&(this.menu.menuItems=tI(this.env,this.props.styleId),this.menu.isOpen=!0,this.menu.position={x:e.clientX,y:e.clientY})}closeMenu(){this.menu.isOpen=!1,this.menu.position=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):!1}editTableStyle(){this.env.openSidePanel(`TableStyleEditorPanel`,{styleId:this.props.styleId})}};H`
1340
1340
  .o-table-style-popover {
1341
1341
  /** 7 tables preview + padding by line */
1342
1342
  width: calc((66px + 4px * 2) * 7 + 1.5rem * 2);
@@ -1381,7 +1381,7 @@ stores.inject(MyMetaStore, storeInstance);
1381
1381
  }
1382
1382
  }
1383
1383
  }
1384
- `;var cI=class extends t.Component{static template=`o-spreadsheet-TableStylesPopover`;static components={Popover:lk,TableStylePreview:sI};static props={tableConfig:Object,popoverProps:{type:Object,optional:!0},closePopover:Function,onStylePicked:Function,selectedStyleId:{type:String,optional:!0}};categories=Dm;tableStyleListRef=(0,t.useRef)(`tableStyleList`);state=(0,t.useState)({selectedCategory:this.initialSelectedCategory});menu=(0,t.useState)({isOpen:!1,position:null,menuItems:[]});setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0})}onExternalClick(e){this.tableStyleListRef.el&&!JT(this.tableStyleListRef.el,e)&&(this.props.closePopover(),e.hasClosedTableStylesPopover=!0)}get displayedStyles(){let 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})}};H`
1384
+ `;var sI=class extends t.Component{static template=`o-spreadsheet-TableStylesPopover`;static components={Popover:lk,TableStylePreview:oI};static props={tableConfig:Object,popoverProps:{type:Object,optional:!0},closePopover:Function,onStylePicked:Function,selectedStyleId:{type:String,optional:!0}};categories=Dm;tableStyleListRef=(0,t.useRef)(`tableStyleList`);state=(0,t.useState)({selectedCategory:this.initialSelectedCategory});menu=(0,t.useState)({isOpen:!1,position:null,menuItems:[]});setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0})}onExternalClick(e){this.tableStyleListRef.el&&!JT(this.tableStyleListRef.el,e)&&(this.props.closePopover(),e.hasClosedTableStylesPopover=!0)}get displayedStyles(){let 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})}};H`
1385
1385
  .o-table-style-picker {
1386
1386
  box-sizing: border-box;
1387
1387
  border: 1px solid ${ve};
@@ -1406,7 +1406,7 @@ stores.inject(MyMetaStore, storeInstance);
1406
1406
  }
1407
1407
  }
1408
1408
  }
1409
- `;var lI=class extends t.Component{static template=`o-spreadsheet-TableStylePicker`;static components={TableStylesPopover:cI,TableStylePreview:sI};static props={table:Object};state=(0,t.useState)({popoverProps:void 0});getDisplayedTableStyles(){let e=this.env.model.getters.getTableStyles(),t=e[this.props.table.config.styleId].category,n=Object.keys(e).filter(n=>e[n].category===t),r=n.indexOf(this.props.table.config.styleId);if(r===-1)return r;let i=Math.floor(r/4)*4;return n.slice(i)}onStylePicked(e){let 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){this.closePopover();return}let{bottom:t,right:n}=e.currentTarget.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:n,y:t,width:0,height:0},positioning:`TopRight`,verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}};H`
1409
+ `;var cI=class extends t.Component{static template=`o-spreadsheet-TableStylePicker`;static components={TableStylesPopover:sI,TableStylePreview:oI};static props={table:Object};state=(0,t.useState)({popoverProps:void 0});getDisplayedTableStyles(){let e=this.env.model.getters.getTableStyles(),t=e[this.props.table.config.styleId].category,n=Object.keys(e).filter(n=>e[n].category===t),r=n.indexOf(this.props.table.config.styleId);if(r===-1)return r;let i=Math.floor(r/4)*4;return n.slice(i)}onStylePicked(e){let 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){this.closePopover();return}let{bottom:t,right:n}=e.currentTarget.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:n,y:t,width:0,height:0},positioning:`TopRight`,verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}};H`
1410
1410
  .o-table-panel {
1411
1411
  input.o-table-n-of-headers {
1412
1412
  width: 14px;
@@ -1418,7 +1418,7 @@ stores.inject(MyMetaStore, storeInstance);
1418
1418
  height: 14px;
1419
1419
  }
1420
1420
  }
1421
- `;var uI=class extends t.Component{static template=`o-spreadsheet-TablePanel`;static components={TableStylePicker:lI,SelectionInput:ON,ValidationMessages:AN,Checkbox:TN,Section:Z};static props={onCloseSidePanel:Function,table:Object};state;setup(){let e=this.env.model.getters.getActiveSheetId();this.state=(0,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){let n=this.env.model.getters.getActiveSheetId();return this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:n,zone:this.props.table.range.zone,config:{[e]:t}})}updateHasHeaders(e){let t=+!!e;this.updateNumberOfHeaders(t)}updateTableIsDynamic(e){let t=e?`dynamic`:`forceStatic`;if(t===this.props.table.type)return;let n=this.env.model.getters.getTable(qF(this.props.table));if(!n)return;let r=this.env.model.getters.getActiveSheetId(),i=this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:r,zone:this.props.table.range.zone,newTableRange:n.range.rangeData,tableType:t}),a=this.env.model.getters.getCoreTable(qF(this.props.table));if(i.isSuccessful&&a){let e=a.range;this.state.tableXc=this.env.model.getters.getRangeString(e,r),this.state.tableZoneErrors=[]}}onChangeNumberOfHeaders(e){let t=e.target,n=parseInt(t.value);this.updateNumberOfHeaders(n).isSuccessful||(t.value=this.props.table.config.numberOfHeaders.toString())}updateNumberOfHeaders(e){let 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){let t=this.env.model.getters.getActiveSheetId();this.state.tableXc=e[0];let n=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(n.zone)}).reasons}onRangeConfirmed(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getRangeFromSheetXC(e,this.state.tableXc);if(Er(t.zone)===1){let n=this.env.model.getters.getContiguousZone(e,t.zone);t=this.env.model.getters.getRangeFromZone(e,n)}let n=t.zone,r=this.props.table.range.zone,i=n.top===r.top&&n.left===r.left?`RESIZE_TABLE`:`UPDATE_TABLE`,a=this.env.model.dispatch(i,{sheetId:e,zone:this.props.table.range.zone,newTableRange:t.rangeData,tableType:this.getNewTableType(t.zone)}),o={sheetId:e,col:t.zone.left,row:t.zone.top},s=this.env.model.getters.getCoreTable(o);if(a.isSuccessful&&s){let t=qF(s);this.env.model.selection.selectZone({zone:D(t),cell:t});let n=s.range;this.state.tableXc=this.env.model.getters.getRangeString(n,e)}}deleteTable(){let e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch(`REMOVE_TABLE`,{sheetId:e,target:[this.props.table.range.zone]})}getNewTableType(e){if(this.props.table.type===`forceStatic`)return`forceStatic`;let 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=>fg.Errors[e]||fg.Errors.Unexpected)}getCheckboxLabel(e){return fg.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:fg.Tooltips.filterWithoutHeader}get canBeDynamic(){let e=this.env.model.getters.getActiveSheetId();return this.props.table.type===`dynamic`||this.env.model.getters.canCreateDynamicTableOnZones(e,[this.props.table.range.zone])}get dynamicTableTooltip(){return fg.Tooltips.isDynamic}};H`
1421
+ `;var lI=class extends t.Component{static template=`o-spreadsheet-TablePanel`;static components={TableStylePicker:cI,SelectionInput:ON,ValidationMessages:AN,Checkbox:TN,Section:Z};static props={onCloseSidePanel:Function,table:Object};state;setup(){let e=this.env.model.getters.getActiveSheetId();this.state=(0,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){let n=this.env.model.getters.getActiveSheetId();return this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:n,zone:this.props.table.range.zone,config:{[e]:t}})}updateHasHeaders(e){let t=+!!e;this.updateNumberOfHeaders(t)}updateTableIsDynamic(e){let t=e?`dynamic`:`forceStatic`;if(t===this.props.table.type)return;let n=this.env.model.getters.getTable(KF(this.props.table));if(!n)return;let r=this.env.model.getters.getActiveSheetId(),i=this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:r,zone:this.props.table.range.zone,newTableRange:n.range.rangeData,tableType:t}),a=this.env.model.getters.getCoreTable(KF(this.props.table));if(i.isSuccessful&&a){let e=a.range;this.state.tableXc=this.env.model.getters.getRangeString(e,r),this.state.tableZoneErrors=[]}}onChangeNumberOfHeaders(e){let t=e.target,n=parseInt(t.value);this.updateNumberOfHeaders(n).isSuccessful||(t.value=this.props.table.config.numberOfHeaders.toString())}updateNumberOfHeaders(e){let 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){let t=this.env.model.getters.getActiveSheetId();this.state.tableXc=e[0];let n=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(n.zone)}).reasons}onRangeConfirmed(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getRangeFromSheetXC(e,this.state.tableXc);if(Er(t.zone)===1){let n=this.env.model.getters.getContiguousZone(e,t.zone);t=this.env.model.getters.getRangeFromZone(e,n)}let n=t.zone,r=this.props.table.range.zone,i=n.top===r.top&&n.left===r.left?`RESIZE_TABLE`:`UPDATE_TABLE`,a=this.env.model.dispatch(i,{sheetId:e,zone:this.props.table.range.zone,newTableRange:t.rangeData,tableType:this.getNewTableType(t.zone)}),o={sheetId:e,col:t.zone.left,row:t.zone.top},s=this.env.model.getters.getCoreTable(o);if(a.isSuccessful&&s){let t=KF(s);this.env.model.selection.selectZone({zone:D(t),cell:t});let n=s.range;this.state.tableXc=this.env.model.getters.getRangeString(n,e)}}deleteTable(){let e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch(`REMOVE_TABLE`,{sheetId:e,target:[this.props.table.range.zone]})}getNewTableType(e){if(this.props.table.type===`forceStatic`)return`forceStatic`;let 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=>fg.Errors[e]||fg.Errors.Unexpected)}getCheckboxLabel(e){return fg.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:fg.Tooltips.filterWithoutHeader}get canBeDynamic(){let e=this.env.model.getters.getActiveSheetId();return this.props.table.type===`dynamic`||this.env.model.getters.canCreateDynamicTableOnZones(e,[this.props.table.range.zone])}get dynamicTableTooltip(){return fg.Tooltips.isDynamic}};H`
1422
1422
  .o-table-style-editor-panel {
1423
1423
  .o-table-style-list-item {
1424
1424
  margin: 2px 7px;
@@ -1430,7 +1430,7 @@ stores.inject(MyMetaStore, storeInstance);
1430
1430
  }
1431
1431
  }
1432
1432
  }
1433
- `;let dI=`#3C78D8`;var fI=class extends t.Component{static template=`o-spreadsheet-TableStyleEditorPanel`;static components={Section:Z,RoundColorPicker:HN,TableStylePreview:sI};static props={onCloseSidePanel:Function,onStylePicked:{type:Function,optional:!0},styleId:{type:String,optional:!0}};state=(0,t.useState)(this.getInitialState());setup(){(0,t.useExternalListener)(window,`click`,()=>this.state.pickerOpened=!1)}getInitialState(){let e=this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId):null;return{pickerOpened:!1,primaryColor:e?.primaryColor||dI,selectedTemplateName:e?.templateName||`lightColoredText`,styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=tn(e)?e:dI,this.state.pickerOpened=!1}onTemplatePicked(e){this.state.selectedTemplateName=e}onConfirm(){let 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 U({background:this.state.primaryColor})}get tableTemplates(){return Object.keys(Um).filter(e=>e!==`none`)}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 Wm(this.state.styleName,e,this.state.primaryColor)}};let pI=new h;pI.add(`ConditionalFormatting`,{title:E(`Conditional formatting`),Body:wP}),pI.add(`ChartPanel`,{title:E(`Chart`),Body:oP,computeState:(e,t)=>{let n=e.getSelectedFigureId()??t.figureId;return e.isChartDefined(n)?{isOpen:!0,props:{figureId:n}}:{isOpen:!1}}}),pI.add(`FindAndReplace`,{title:E(`Find and Replace`),Body:JP}),pI.add(`CustomCurrency`,{title:E(`Custom currency format`),Body:TP}),pI.add(`SplitToColumns`,{title:E(`Split text into columns`),Body:WF}),pI.add(`Settings`,{title:E(`Spreadsheet settings`),Body:BF}),pI.add(`RemoveDuplicates`,{title:E(`Remove duplicates`),Body:zF}),pI.add(`DataValidation`,{title:E(`Data validation`),Body:GP}),pI.add(`DataValidationEditor`,{title:E(`Data validation`),Body:UP}),pI.add(`MoreFormats`,{title:E(`More date formats`),Body:XP}),pI.add(`TableSidePanel`,{title:E(`Edit table`),Body:uI,computeState:e=>{let t=e.getFirstTableInSelection();return t?{isOpen:!0,props:{table:e.getCoreTable(qF(t))},key:t.id}:{isOpen:!1}}}),pI.add(`TableStyleEditorPanel`,{title:E(`Create custom table style`),Body:fI,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??`new`})}),pI.add(`PivotSidePanel`,{title:(e,t)=>E(`Pivot #%s`,e.model.getters.getPivotFormulaId(t.pivotId)),Body:RF,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),pI.add(`PivotMeasureDisplayPanel`,{title:(e,t)=>E(`Measure "%s" options`,e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id).displayName),Body:QP,computeState:(e,t)=>{try{return e.getPivot(t.pivotId).getMeasure(t.measure.id),{isOpen:!0,props:t,key:`pivot_measure_display`}}catch{return{isOpen:!1}}}}),H`
1433
+ `;let uI=`#3C78D8`;var dI=class extends t.Component{static template=`o-spreadsheet-TableStyleEditorPanel`;static components={Section:Z,RoundColorPicker:HN,TableStylePreview:oI};static props={onCloseSidePanel:Function,onStylePicked:{type:Function,optional:!0},styleId:{type:String,optional:!0}};state=(0,t.useState)(this.getInitialState());setup(){(0,t.useExternalListener)(window,`click`,()=>this.state.pickerOpened=!1)}getInitialState(){let e=this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId):null;return{pickerOpened:!1,primaryColor:e?.primaryColor||uI,selectedTemplateName:e?.templateName||`lightColoredText`,styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=tn(e)?e:uI,this.state.pickerOpened=!1}onTemplatePicked(e){this.state.selectedTemplateName=e}onConfirm(){let 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 U({background:this.state.primaryColor})}get tableTemplates(){return Object.keys(Um).filter(e=>e!==`none`)}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 Wm(this.state.styleName,e,this.state.primaryColor)}};let fI=new h;fI.add(`ConditionalFormatting`,{title:E(`Conditional formatting`),Body:wP}),fI.add(`ChartPanel`,{title:E(`Chart`),Body:oP,computeState:(e,t)=>{let n=e.getSelectedFigureId()??t.figureId;return e.isChartDefined(n)?{isOpen:!0,props:{figureId:n}}:{isOpen:!1}}}),fI.add(`FindAndReplace`,{title:E(`Find and Replace`),Body:JP}),fI.add(`CustomCurrency`,{title:E(`Custom currency format`),Body:TP}),fI.add(`SplitToColumns`,{title:E(`Split text into columns`),Body:UF}),fI.add(`Settings`,{title:E(`Spreadsheet settings`),Body:zF}),fI.add(`RemoveDuplicates`,{title:E(`Remove duplicates`),Body:RF}),fI.add(`DataValidation`,{title:E(`Data validation`),Body:GP}),fI.add(`DataValidationEditor`,{title:E(`Data validation`),Body:UP}),fI.add(`MoreFormats`,{title:E(`More date formats`),Body:XP}),fI.add(`TableSidePanel`,{title:E(`Edit table`),Body:lI,computeState:e=>{let t=e.getFirstTableInSelection();return t?{isOpen:!0,props:{table:e.getCoreTable(KF(t))},key:t.id}:{isOpen:!1}}}),fI.add(`TableStyleEditorPanel`,{title:E(`Create custom table style`),Body:dI,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??`new`})}),fI.add(`PivotSidePanel`,{title:(e,t)=>E(`Pivot #%s`,e.model.getters.getPivotFormulaId(t.pivotId)),Body:LF,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),fI.add(`PivotMeasureDisplayPanel`,{title:(e,t)=>E(`Measure "%s" options`,e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id).displayName),Body:QP,computeState:(e,t)=>{try{return e.getPivot(t.pivotId).getMeasure(t.measure.id),{isOpen:!0,props:t,key:`pivot_measure_display`}}catch{return{isOpen:!1}}}}),H`
1434
1434
  div.o-figure {
1435
1435
  box-sizing: border-box;
1436
1436
  position: absolute;
@@ -1503,7 +1503,7 @@ stores.inject(MyMetaStore, storeInstance);
1503
1503
  }
1504
1504
  }
1505
1505
  }
1506
- `;var mI=class extends t.Component{static template=`o-spreadsheet-FigureComponent`;static props={figure:Object,style:{type:String,optional:!0},onMouseDown:{type:Function,optional:!0},onClickAnchor:{type:Function,optional:!0}};static components={Menu:pk};static defaultProps={onMouseDown:()=>{},onClickAnchor:()=>{}};menuState=(0,t.useState)({isOpen:!1,position:null,menuItems:[]});figureRef=(0,t.useRef)(`figure`);menuButtonRef=(0,t.useRef)(`menuButton`);menuButtonRect=iE(this.menuButtonRef);borderWidth;get isSelected(){return this.env.model.getters.getSelectedFigureId()===this.props.figure.id}get figureRegistry(){return pO}getBorderWidth(){return this.env.isDashboard()?0:this.isSelected?2:this.borderWidth}get borderStyle(){return`border: ${this.getBorderWidth()}px solid ${this.isSelected?ae:ie};`}get wrapperStyle(){let{x:e,y:t,width:n,height:r}=this.props.figure;return U({left:`${e}px`,top:`${t}px`,width:`${n}px`,height:`${r}px`,"z-index":String(10+ +!!this.isSelected)})}getResizerPosition(e){let 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)`,U(t)}setup(){let e=pO.get(this.props.figure.tag).borderWidth;this.borderWidth=e===void 0?1:e,(0,t.useEffect)((e,t,n)=>{e===t&&n?.focus({preventScroll:!0})},()=>[this.env.model.getters.getSelectedFigureId(),this.props.figure.id,this.figureRef.el])}clickAnchor(e,t,n){this.props.onClickAnchor(e,t,n)}onMouseDown(e){this.props.onMouseDown(e)}onKeyDown(e){let t=this.props.figure,n=eE(e);switch(n){case`Delete`:case`Backspace`:this.env.model.dispatch(`DELETE_FIGURE`,{sheetId:this.env.model.getters.getActiveSheetId(),id:t.id}),e.preventDefault(),e.stopPropagation();break;case`ArrowDown`:case`ArrowLeft`:case`ArrowRight`:case`ArrowUp`:let r={ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1]}[e.key];this.env.model.dispatch(`UPDATE_FIGURE`,{sheetId:this.env.model.getters.getActiveSheetId(),id:t.id,x:t.x+r[0],y:t.y+r[1]}),e.preventDefault(),e.stopPropagation();break;case`Ctrl+A`:e.preventDefault(),e.stopPropagation();break;case`Ctrl+Y`:case`Ctrl+Z`:n===`Ctrl+Y`?this.env.model.dispatch(`REQUEST_REDO`):n===`Ctrl+Z`&&this.env.model.dispatch(`REQUEST_UNDO`),e.preventDefault(),e.stopPropagation();break}}onContextMenu(e){if(this.env.isDashboard())return;let t={x:e.clientX,y:e.clientY};this.openContextMenu(t)}showMenu(){let{x:e,y:t,width:n}=this.menuButtonRect,r={x:e>=250?e-250:e+n,y:t};this.openContextMenu(r)}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.position=e,this.menuState.menuItems=pO.get(this.props.figure.tag).menuBuilder(this.props.figure.id,this.env)}};let hI={CannotHideAllRows:E(`Cannot hide all the rows of a sheet.`),CannotHideAllColumns:E(`Cannot hide all the columns of a sheet.`)};function gI(e,t,n,r,i){let a=e.model.getters.getHeaderGroup(t,n,r,i);if(!a)return;let o=a.isFolded?`UNFOLD_HEADER_GROUP`:`FOLD_HEADER_GROUP`,s=e.model.dispatch(o,{sheetId:t,dimension:n,start:a.start,end:a.end});if(!s.isSuccessful&&s.isCancelledBecause(`NotEnoughElements`)){let t=n===`ROW`?hI.CannotHideAllRows:hI.CannotHideAllColumns;e.raiseError(t)}}function _I(e,t){return f([{id:`unfold_all`,name:E(t===`ROW`?`Expand all row groups`:`Expand all column groups`),execute:n=>{n.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:e,dimension:t})}},{id:`fold_all`,name:E(t===`ROW`?`Collapse all row groups`:`Collapse all column groups`),execute:n=>{n.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:e,dimension:t})}}])}function vI(e,t,n,r){return[...f([{id:`toggle_group`,name:e=>{let i=e.model.getters.getActiveSheetId();return e.model.getters.isGroupFolded(i,t,n,r)?E(t===`ROW`?`Expand row group`:`Expand column group`):E(t===`ROW`?`Collapse row group`:`Collapse column group`)},execute:e=>{gI(e,e.model.getters.getActiveSheetId(),t,n,r)}},{id:`remove_group`,name:E(t===`ROW`?`Remove row group`:`Remove column group`),execute:e=>{let i=e.model.getters.getActiveSheetId();e.model.dispatch(`UNGROUP_HEADERS`,{sheetId:i,dimension:t,start:n,end:r})},separator:!0}]),..._I(e,t)]}let yI=new PO;yI.add(`group_columns`,{sequence:10,...iN,isVisible:()=>!0,isEnabled:iN.isVisible}).add(`group_rows`,{sequence:20,...aN,isVisible:()=>!0,isEnabled:aN.isVisible});let bI=new PO;bI.add(`ungroup_columns`,{sequence:10,...oN,isEnabled:e=>uN(e,`COL`)}).add(`ungroup_rows`,{sequence:20,...sN,isEnabled:e=>uN(e,`ROW`)});var xI=class extends hd{highlightStore=this.get(xN);constructor(e){super(e),this.highlightStore.register(this)}get highlights(){let e=this.model.getters.getActivePosition(),t=this.model.getters.getArrayFormulaSpreadingOn(e),n=t?this.model.getters.getSpreadZone(t,{ignoreSpillError:!0}):this.model.getters.getSpreadZone(e,{ignoreSpillError:!0});if(!n)return[];let r=this.model.getters.isArrayFormulaSpillBlocked(t??e);return[{sheetId:e.sheetId,zone:n,dashed:r,color:`#17A2B8`,noFill:!0,thinLine:!0}]}};H`
1506
+ `;var pI=class extends t.Component{static template=`o-spreadsheet-FigureComponent`;static props={figure:Object,style:{type:String,optional:!0},onMouseDown:{type:Function,optional:!0},onClickAnchor:{type:Function,optional:!0}};static components={Menu:pk};static defaultProps={onMouseDown:()=>{},onClickAnchor:()=>{}};menuState=(0,t.useState)({isOpen:!1,position:null,menuItems:[]});figureRef=(0,t.useRef)(`figure`);menuButtonRef=(0,t.useRef)(`menuButton`);menuButtonRect=iE(this.menuButtonRef);borderWidth;get isSelected(){return this.env.model.getters.getSelectedFigureId()===this.props.figure.id}get figureRegistry(){return pO}getBorderWidth(){return this.env.isDashboard()?0:this.isSelected?2:this.borderWidth}get borderStyle(){return`border: ${this.getBorderWidth()}px solid ${this.isSelected?ae:ie};`}get wrapperStyle(){let{x:e,y:t,width:n,height:r}=this.props.figure;return U({left:`${e}px`,top:`${t}px`,width:`${n}px`,height:`${r}px`,"z-index":String(10+ +!!this.isSelected)})}getResizerPosition(e){let 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)`,U(t)}setup(){let e=pO.get(this.props.figure.tag).borderWidth;this.borderWidth=e===void 0?1:e,(0,t.useEffect)((e,t,n)=>{e===t&&n?.focus({preventScroll:!0})},()=>[this.env.model.getters.getSelectedFigureId(),this.props.figure.id,this.figureRef.el])}clickAnchor(e,t,n){this.props.onClickAnchor(e,t,n)}onMouseDown(e){this.props.onMouseDown(e)}onKeyDown(e){let t=this.props.figure,n=eE(e);switch(n){case`Delete`:case`Backspace`:this.env.model.dispatch(`DELETE_FIGURE`,{sheetId:this.env.model.getters.getActiveSheetId(),id:t.id}),e.preventDefault(),e.stopPropagation();break;case`ArrowDown`:case`ArrowLeft`:case`ArrowRight`:case`ArrowUp`:let r={ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1]}[e.key];this.env.model.dispatch(`UPDATE_FIGURE`,{sheetId:this.env.model.getters.getActiveSheetId(),id:t.id,x:t.x+r[0],y:t.y+r[1]}),e.preventDefault(),e.stopPropagation();break;case`Ctrl+A`:e.preventDefault(),e.stopPropagation();break;case`Ctrl+Y`:case`Ctrl+Z`:n===`Ctrl+Y`?this.env.model.dispatch(`REQUEST_REDO`):n===`Ctrl+Z`&&this.env.model.dispatch(`REQUEST_UNDO`),e.preventDefault(),e.stopPropagation();break}}onContextMenu(e){if(this.env.isDashboard())return;let t={x:e.clientX,y:e.clientY};this.openContextMenu(t)}showMenu(){let{x:e,y:t,width:n}=this.menuButtonRect,r={x:e>=250?e-250:e+n,y:t};this.openContextMenu(r)}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.position=e,this.menuState.menuItems=pO.get(this.props.figure.tag).menuBuilder(this.props.figure.id,this.env)}};let mI={CannotHideAllRows:E(`Cannot hide all the rows of a sheet.`),CannotHideAllColumns:E(`Cannot hide all the columns of a sheet.`)};function hI(e,t,n,r,i){let a=e.model.getters.getHeaderGroup(t,n,r,i);if(!a)return;let o=a.isFolded?`UNFOLD_HEADER_GROUP`:`FOLD_HEADER_GROUP`,s=e.model.dispatch(o,{sheetId:t,dimension:n,start:a.start,end:a.end});if(!s.isSuccessful&&s.isCancelledBecause(`NotEnoughElements`)){let t=n===`ROW`?mI.CannotHideAllRows:mI.CannotHideAllColumns;e.raiseError(t)}}function gI(e,t){return f([{id:`unfold_all`,name:E(t===`ROW`?`Expand all row groups`:`Expand all column groups`),execute:n=>{n.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:e,dimension:t})}},{id:`fold_all`,name:E(t===`ROW`?`Collapse all row groups`:`Collapse all column groups`),execute:n=>{n.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:e,dimension:t})}}])}function _I(e,t,n,r){return[...f([{id:`toggle_group`,name:e=>{let i=e.model.getters.getActiveSheetId();return e.model.getters.isGroupFolded(i,t,n,r)?E(t===`ROW`?`Expand row group`:`Expand column group`):E(t===`ROW`?`Collapse row group`:`Collapse column group`)},execute:e=>{hI(e,e.model.getters.getActiveSheetId(),t,n,r)}},{id:`remove_group`,name:E(t===`ROW`?`Remove row group`:`Remove column group`),execute:e=>{let i=e.model.getters.getActiveSheetId();e.model.dispatch(`UNGROUP_HEADERS`,{sheetId:i,dimension:t,start:n,end:r})},separator:!0}]),...gI(e,t)]}let vI=new PO;vI.add(`group_columns`,{sequence:10,...iN,isVisible:()=>!0,isEnabled:iN.isVisible}).add(`group_rows`,{sequence:20,...aN,isVisible:()=>!0,isEnabled:aN.isVisible});let yI=new PO;yI.add(`ungroup_columns`,{sequence:10,...oN,isEnabled:e=>uN(e,`COL`)}).add(`ungroup_rows`,{sequence:20,...sN,isEnabled:e=>uN(e,`ROW`)});var bI=class extends hd{highlightStore=this.get(xN);constructor(e){super(e),this.highlightStore.register(this)}get highlights(){let e=this.model.getters.getActivePosition(),t=this.model.getters.getArrayFormulaSpreadingOn(e),n=t?this.model.getters.getSpreadZone(t,{ignoreSpillError:!0}):this.model.getters.getSpreadZone(e,{ignoreSpillError:!0});if(!n)return[];let r=this.model.getters.isArrayFormulaSpillBlocked(t??e);return[{sheetId:e.sheetId,zone:n,dashed:r,color:`#17A2B8`,noFill:!0,thinLine:!0}]}};H`
1507
1507
  .o-autofill {
1508
1508
  position: absolute;
1509
1509
  height: ${8}px;
@@ -1531,7 +1531,7 @@ stores.inject(MyMetaStore, storeInstance);
1531
1531
  pointer-events: none;
1532
1532
  white-space: nowrap;
1533
1533
  }
1534
- `;var SI=class extends t.Component{static template=`o-spreadsheet-Autofill`;static props={position:Object,isVisible:Boolean};state=(0,t.useState)({position:{left:0,top:0},handler:!1});get style(){let{left:e,top:t}=this.props.position;return U({top:`${t}px`,left:`${e}px`,visibility:this.props.isVisible?`visible`:`hidden`})}get handlerStyle(){let{left:e,top:t}=this.state.handler?this.state.position:this.props.position;return U({top:`${t}px`,left:`${e}px`})}get styleNextValue(){let{left:e,top:t}=this.state.position;return U({top:`${t+5}px`,left:`${e+15}px`})}getTooltip(){let e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=CI),e}onMouseDown(e){this.state.handler=!0;let t,n,r={left:e.clientX-this.props.position.left,top:e.clientY-this.props.position.top};zN(this.env,(e,i,a)=>{if(this.state.position={left:a.clientX-r.left,top:a.clientY-r.top},t!==e||n!==i){let r=this.env.model.getters.getActiveSheetId(),a=this.env.model.getters.getNumberCols(r),o=this.env.model.getters.getNumberRows(r);t=e===-1?t:b(e,0,a),n=i===-1?n:b(i,0,o),t!==void 0&&n!==void 0&&this.env.model.dispatch(`AUTOFILL_SELECT`,{col:t,row:n})}},()=>{this.state.handler=!1,this.state.position={...this.props.position},this.env.model.dispatch(`AUTOFILL`)})}onDblClick(){this.env.model.dispatch(`AUTOFILL_AUTO`)}},CI=class extends t.Component{static props={content:String};static template=t.xml`
1534
+ `;var xI=class extends t.Component{static template=`o-spreadsheet-Autofill`;static props={position:Object,isVisible:Boolean};state=(0,t.useState)({position:{left:0,top:0},handler:!1});get style(){let{left:e,top:t}=this.props.position;return U({top:`${t}px`,left:`${e}px`,visibility:this.props.isVisible?`visible`:`hidden`})}get handlerStyle(){let{left:e,top:t}=this.state.handler?this.state.position:this.props.position;return U({top:`${t}px`,left:`${e}px`})}get styleNextValue(){let{left:e,top:t}=this.state.position;return U({top:`${t+5}px`,left:`${e+15}px`})}getTooltip(){let e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=SI),e}onMouseDown(e){this.state.handler=!0;let t,n,r={left:e.clientX-this.props.position.left,top:e.clientY-this.props.position.top};zN(this.env,(e,i,a)=>{if(this.state.position={left:a.clientX-r.left,top:a.clientY-r.top},t!==e||n!==i){let r=this.env.model.getters.getActiveSheetId(),a=this.env.model.getters.getNumberCols(r),o=this.env.model.getters.getNumberRows(r);t=e===-1?t:b(e,0,a),n=i===-1?n:b(i,0,o),t!==void 0&&n!==void 0&&this.env.model.dispatch(`AUTOFILL_SELECT`,{col:t,row:n})}},()=>{this.state.handler=!1,this.state.position={...this.props.position},this.env.model.dispatch(`AUTOFILL`)})}onDblClick(){this.env.model.dispatch(`AUTOFILL_AUTO`)}},SI=class extends t.Component{static props={content:String};static template=t.xml`
1535
1535
  <div t-esc="props.content"/>
1536
1536
  `};H`
1537
1537
  .o-client-tag {
@@ -1542,13 +1542,13 @@ stores.inject(MyMetaStore, storeInstance);
1542
1542
  color: white;
1543
1543
  pointer-events: none;
1544
1544
  }
1545
- `;var wI=class extends t.Component{static template=`o-spreadsheet-ClientTag`;static props={active:Boolean,name:String,color:String,col:Number,row:Number};get tagStyle(){let{col:e,row:t,color:n}=this.props,{height:r}=this.env.model.getters.getSheetViewDimensionWithHeaders(),{x:i,y:a}=this.env.model.getters.getVisibleRect({left:e,top:t,right:e,bottom:t});return U({bottom:`${r-a+15}px`,left:`${i-1}px`,border:`1px solid ${n}`,"background-color":n})}};let TI=E(`The cell you are trying to edit has been deleted.`);var EI=class extends cP{canStopEdition(){return this.editionMode===`inactive`?!0:this.checkDataValidation()}stopEdition(e){if(this.canStopEdition()){this._stopEdition(),e&&this.model.selection.moveAnchorCell(e,1);return}let t=this.currentEditedCell,n=w(t.col,t.row),r=this.getters.getValidationRuleForCell(t);if(!r)return;let i=Q.get(r.criterion.type).getErrorString(r.criterion,this.getters,t.sheetId);this.notificationStore.raiseError(E(`The data you entered in %s violates the data validation rule set on the cell:
1546
- %s`,n,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`:e.dimension===`COL`?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case`ACTIVATE_SHEET`:if(this._currentContent.startsWith(`=`)||(this._cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){let t=this.getters.getActivePosition(),{col:n,row:r}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),i=this.getters.expandZone(e.sheetIdTo,D({col:n,row:r}));this.model.selection.resetAnchor(this,{cell:{col:n,row:r},zone:i})}break;case`DELETE_SHEET`:case`UNDO`:case`REDO`:!this.getters.tryGetSheet(this.sheetId)&&this.editionMode!==`inactive`&&(this.sheetId=this.getters.getActiveSheetId(),this.resetContent(),this.cancelEditionAndActivateSheet(),this.notificationStore.raiseError(TI));break}}get placeholder(){let 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)&&this.editionMode!==`inactive`){this.cancelEdition(),this.notificationStore.raiseError(TI);return}let{top:t,left:n}=ir({left:this.col,right:this.col,top:this.row,bottom:this.row},`left`,[...e.elements]);this.col=n,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&this.editionMode!==`inactive`){this.cancelEdition(),this.notificationStore.raiseError(TI);return}let{top:t,left:n}=ir({left:this.col,right:this.col,top:this.row,bottom:this.row},`top`,[...e.elements]);this.col=n,this.row=t}onAddElements(e){let{top:t,left:n}=rr({left:this.col,right:this.col,top:this.row,bottom:this.row},e.dimension===`COL`?`left`:`top`,e.base,e.position,e.quantity);this.col=n,this.row=t}confirmEdition(e){if(e){let t=this.getters.getActiveSheetId(),n=this.getters.getEvaluatedCell({sheetId:t,col:this.col,row:this.row});n.link&&!e.startsWith(`=`)&&(e=ht(e,n.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){let t=this.getters.getLocale(),n=this.getters.getCell(e);if(n?.isFormula)return ol(n.content,t);if(this.model.getters.getArrayFormulaSpreadingOn(e))return``;let{format:r,value:i,type:a,formattedValue:o}=this.getters.getEvaluatedCell(e);switch(a){case`empty`:return``;case`text`:case`error`:return i;case`boolean`:return o;case`number`:return r&&Go(r)?Qr(o,t)===null?B(i,{locale:t,format:Number.isInteger(i)?t.dateFormat:_l(t)}):o:this.numberComposerContent(i,r,t)}}numberComposerContent(e,t,n){return t?.includes(`%`)?`${Wo(e*100,n.decimalSeparator)}%`:Wo(e,n.decimalSeparator)}addHeadersForSpreadingFormula(e){if(!e.startsWith(`=`))return;let t=this.getters.evaluateFormula(this.sheetId,e,{sheetId:this.sheetId,col:this.col,row:this.row});if(!A(t))return;let n=this.getters.getNumberRows(this.sheetId),r=this.getters.getNumberCols(this.sheetId),i=this.row+t[0].length-n,a=this.col+t.length-r;a>0&&this.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:this.sheetId,dimension:`COL`,base:r-1,position:`after`,quantity:a+20}),i>0&&this.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:this.sheetId,dimension:`ROW`,base:n-1,position:`after`,quantity:i+50})}checkDataValidation(){let e={sheetId:this.sheetId,col:this.col,row:this.row},t=this.getCurrentCanonicalContent(),n=t.startsWith(`=`)?this.getters.evaluateFormula(this.sheetId,t):hs(t,this.getters.getLocale());if(A(n))return!0;let r=this.getters.getValidationResultForCellValue(n,e);return!(!r.isValid&&r.rule.isBlocking)}};let DI=3*.4*window.devicePixelRatio||1;H`
1545
+ `;var CI=class extends t.Component{static template=`o-spreadsheet-ClientTag`;static props={active:Boolean,name:String,color:String,col:Number,row:Number};get tagStyle(){let{col:e,row:t,color:n}=this.props,{height:r}=this.env.model.getters.getSheetViewDimensionWithHeaders(),{x:i,y:a}=this.env.model.getters.getVisibleRect({left:e,top:t,right:e,bottom:t});return U({bottom:`${r-a+15}px`,left:`${i-1}px`,border:`1px solid ${n}`,"background-color":n})}};let wI=E(`The cell you are trying to edit has been deleted.`);var TI=class extends cP{canStopEdition(){return this.editionMode===`inactive`?!0:this.checkDataValidation()}stopEdition(e){if(this.canStopEdition()){let{col:t,row:n}=this.currentEditedCell;this._stopEdition(),e&&(this.model.selection.selectCell(t,n),this.model.selection.moveAnchorCell(e,1));return}let t=this.currentEditedCell,n=w(t.col,t.row),r=this.getters.getValidationRuleForCell(t);if(!r)return;let i=Q.get(r.criterion.type).getErrorString(r.criterion,this.getters,t.sheetId);this.notificationStore.raiseError(E(`The data you entered in %s violates the data validation rule set on the cell:
1546
+ %s`,n,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`:e.dimension===`COL`?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case`ACTIVATE_SHEET`:if(this._currentContent.startsWith(`=`)||(this._cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){let t=this.getters.getActivePosition(),{col:n,row:r}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),i=this.getters.expandZone(e.sheetIdTo,D({col:n,row:r}));this.model.selection.resetAnchor(this,{cell:{col:n,row:r},zone:i})}break;case`DELETE_SHEET`:case`UNDO`:case`REDO`:!this.getters.tryGetSheet(this.sheetId)&&this.editionMode!==`inactive`&&(this.sheetId=this.getters.getActiveSheetId(),this.resetContent(),this.cancelEditionAndActivateSheet(),this.notificationStore.raiseError(wI));break}}get placeholder(){let 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)&&this.editionMode!==`inactive`){this.cancelEdition(),this.notificationStore.raiseError(wI);return}let{top:t,left:n}=ir({left:this.col,right:this.col,top:this.row,bottom:this.row},`left`,[...e.elements]);this.col=n,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&this.editionMode!==`inactive`){this.cancelEdition(),this.notificationStore.raiseError(wI);return}let{top:t,left:n}=ir({left:this.col,right:this.col,top:this.row,bottom:this.row},`top`,[...e.elements]);this.col=n,this.row=t}onAddElements(e){let{top:t,left:n}=rr({left:this.col,right:this.col,top:this.row,bottom:this.row},e.dimension===`COL`?`left`:`top`,e.base,e.position,e.quantity);this.col=n,this.row=t}confirmEdition(e){if(e){let t=this.getters.getActiveSheetId(),n=this.getters.getEvaluatedCell({sheetId:t,col:this.col,row:this.row});n.link&&!e.startsWith(`=`)&&(e=ht(e,n.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){let t=this.getters.getLocale(),n=this.getters.getCell(e);if(n?.isFormula)return ol(n.content,t);if(this.model.getters.getArrayFormulaSpreadingOn(e))return``;let{format:r,value:i,type:a,formattedValue:o}=this.getters.getEvaluatedCell(e);switch(a){case`empty`:return``;case`text`:case`error`:return i;case`boolean`:return o;case`number`:return r&&Go(r)?Qr(o,t)===null?B(i,{locale:t,format:Number.isInteger(i)?t.dateFormat:_l(t)}):o:this.numberComposerContent(i,r,t)}}numberComposerContent(e,t,n){return t?.includes(`%`)?`${Wo(e*100,n.decimalSeparator)}%`:Wo(e,n.decimalSeparator)}addHeadersForSpreadingFormula(e){if(!e.startsWith(`=`))return;let t=this.getters.evaluateFormula(this.sheetId,e,{sheetId:this.sheetId,col:this.col,row:this.row});if(!A(t))return;let n=this.getters.getNumberRows(this.sheetId),r=this.getters.getNumberCols(this.sheetId),i=this.row+t[0].length-n,a=this.col+t.length-r;a>0&&this.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:this.sheetId,dimension:`COL`,base:r-1,position:`after`,quantity:a+20}),i>0&&this.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:this.sheetId,dimension:`ROW`,base:n-1,position:`after`,quantity:i+50})}checkDataValidation(){let e={sheetId:this.sheetId,col:this.col,row:this.row},t=this.getCurrentCanonicalContent(),n=t.startsWith(`=`)?this.getters.evaluateFormula(this.sheetId,t):hs(t,this.getters.getLocale());if(A(n))return!0;let r=this.getters.getValidationResultForCellValue(n,e);return!(!r.isValid&&r.rule.isBlocking)}};let EI=3*.4*window.devicePixelRatio||1;H`
1547
1547
  div.o-grid-composer {
1548
1548
  z-index: ${20};
1549
1549
  box-sizing: border-box;
1550
1550
  position: absolute;
1551
- border: ${DI}px solid ${ae};
1551
+ border: ${EI}px solid ${ae};
1552
1552
  font-family: ${ze};
1553
1553
 
1554
1554
  display: flex;
@@ -1565,12 +1565,12 @@ stores.inject(MyMetaStore, storeInstance);
1565
1565
  padding: 6px 7px;
1566
1566
  border-radius: 4px;
1567
1567
  }
1568
- `;var OI=class extends t.Component{static template=`o-spreadsheet-GridComposer`;static props={gridDims:Object,onInputContextMenu:Function};static components={Composer:vE};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(){let e=V(EI);this.composerStore=e,this.composerFocusStore=V(_d),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`}),(0,t.onWillUpdateProps)(()=>{this.updateComponentPosition(),this.updateCellReferenceVisibility()})}get shouldDisplayCellReference(){return this.isCellReferenceVisible}get cellReference(){let{col:e,row:t,sheetId:n}=this.currentEditedCell;return Hs(n===this.env.model.getters.getActiveSheetId()?void 0:this.env.model.getters.getSheetName(n),w(e,t))}get cellReferenceStyle(){let{x:e,y:t}=this.rect;return U({left:`${e-DI}px`,top:`${t-28}px`})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:`inactive`}get composerProps(){let{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders(),n=this.props.gridDims.height-this.rect.y-2*DI;return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,isDefaultFocus:!0,onComposerContentFocused:()=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`}),onComposerCellFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`cellFocus`,content:e}),onInputContextMenu:this.props.onInputContextMenu,composerStore:this.composerStore,inputStyle:`max-height: ${n}px;`}}get containerStyle(){if(this.composerStore.editionMode===`inactive`)return`z-index: -1000;`;let e=this.composerStore.currentContent.startsWith(`=`),t=this.env.model.getters.getActiveCell(),n=this.env.model.getters.getActivePosition(),r=this.env.model.getters.getCellComputedStyle(n),{x:i,y:a,width:o,height:s}=this.rect,c=!e&&r.fillColor||`#ffffff`,l=!e&&r.textColor||`#000000`,u=!e&&r.fontSize||10,d=!e&&r.bold?`bold`:void 0,f=!e&&r.italic?`italic`:`normal`,p=e?`none`:yf(r),m=`left`;e||(m=r.align||t.defaultAlign);let h=this.props.gridDims.height-this.rect.y,g=this.props.gridDims.width-this.rect.x;return U({left:`${i-1}px`,top:`${a}px`,"min-width":`${o+1}px`,"min-height":`${s+1}px`,"max-width":`${g}px`,"max-height":`${h}px`,background:c,color:l,"font-size":`${fc(u)}px`,"font-weight":d,"font-style":f,"text-decoration":p,"text-align":m})}updateComponentPosition(){let e=this.composerFocusStore.activeComposer.editionMode!==`inactive`;!e&&this.composerFocusStore.activeComposer!==this.composerInterface&&this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`inactive`});let t=e&&!C(this.currentEditedCell,this.composerStore.currentEditedCell);if(this.isEditing!==e){if(this.isEditing=e,!e){this.rect=this.defaultRect;return}this.currentEditedCell=this.composerStore.currentEditedCell,t=!0}if(t){let e=this.env.model.getters.getActivePosition(),t=this.env.model.getters.expandZone(e.sheetId,D(e));this.rect=this.env.model.getters.getVisibleRect(t)}}updateCellReferenceVisibility(){if(this.composerStore.editionMode===`inactive`){this.isCellReferenceVisible=!1;return}if(this.isCellReferenceVisible)return;let e=this.env.model.getters.getActiveSheetId(),t=D(this.env.model.getters.getSelection().anchor.cell);(!C(this.env.model.getters.getVisibleRect(t),this.rect)||e!==this.composerStore.currentEditedCell.sheetId)&&(this.isCellReferenceVisible=!0)}onFocus(){this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`})}};H`
1568
+ `;var DI=class extends t.Component{static template=`o-spreadsheet-GridComposer`;static props={gridDims:Object,onInputContextMenu:Function};static components={Composer:vE};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(){let e=V(TI);this.composerStore=e,this.composerFocusStore=V(_d),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`}),(0,t.onWillUpdateProps)(()=>{this.updateComponentPosition(),this.updateCellReferenceVisibility()})}get shouldDisplayCellReference(){return this.isCellReferenceVisible}get cellReference(){let{col:e,row:t,sheetId:n}=this.currentEditedCell;return Hs(n===this.env.model.getters.getActiveSheetId()?void 0:this.env.model.getters.getSheetName(n),w(e,t))}get cellReferenceStyle(){let{x:e,y:t}=this.rect;return U({left:`${e-EI}px`,top:`${t-28}px`})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:`inactive`}get composerProps(){let{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders(),n=this.props.gridDims.height-this.rect.y-2*EI;return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,isDefaultFocus:!0,onComposerContentFocused:()=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`}),onComposerCellFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`cellFocus`,content:e}),onInputContextMenu:this.props.onInputContextMenu,composerStore:this.composerStore,inputStyle:`max-height: ${n}px;`}}get containerStyle(){if(this.composerStore.editionMode===`inactive`)return`z-index: -1000;`;let e=this.composerStore.currentContent.startsWith(`=`),t=this.env.model.getters.getActiveCell(),n=this.env.model.getters.getActivePosition(),r=this.env.model.getters.getCellComputedStyle(n),{x:i,y:a,width:o,height:s}=this.rect,c=!e&&r.fillColor||`#ffffff`,l=!e&&r.textColor||`#000000`,u=!e&&r.fontSize||10,d=!e&&r.bold?`bold`:void 0,f=!e&&r.italic?`italic`:`normal`,p=e?`none`:yf(r),m=`left`;e||(m=r.align||t.defaultAlign);let h=this.props.gridDims.height-this.rect.y,g=this.props.gridDims.width-this.rect.x;return U({left:`${i-1}px`,top:`${a}px`,"min-width":`${o+1}px`,"min-height":`${s+1}px`,"max-width":`${g}px`,"max-height":`${h}px`,background:c,color:l,"font-size":`${fc(u)}px`,"font-weight":d,"font-style":f,"text-decoration":p,"text-align":m})}updateComponentPosition(){let e=this.composerFocusStore.activeComposer.editionMode!==`inactive`;!e&&this.composerFocusStore.activeComposer!==this.composerInterface&&this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`inactive`});let t=e&&!C(this.currentEditedCell,this.composerStore.currentEditedCell);if(this.isEditing!==e){if(this.isEditing=e,!e){this.rect=this.defaultRect;return}this.currentEditedCell=this.composerStore.currentEditedCell,t=!0}if(t){let e=this.env.model.getters.getActivePosition(),t=this.env.model.getters.expandZone(e.sheetId,D(e));this.rect=this.env.model.getters.getVisibleRect(t)}}updateCellReferenceVisibility(){if(this.composerStore.editionMode===`inactive`){this.isCellReferenceVisible=!1;return}if(this.isCellReferenceVisible)return;let e=this.env.model.getters.getActiveSheetId(),t=D(this.env.model.getters.getSelection().anchor.cell);(!C(this.env.model.getters.getVisibleRect(t),this.rect)||e!==this.composerStore.currentEditedCell.sheetId)&&(this.isCellReferenceVisible=!0)}onFocus(){this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`})}};H`
1569
1569
  .o-grid-cell-icon {
1570
1570
  width: ${17}px;
1571
1571
  height: ${17}px;
1572
1572
  }
1573
- `;var kI=class extends t.Component{static template=`o-spreadsheet-GridCellIcon`;static props={cellPosition:Object,horizontalAlign:{type:String,optional:!0},verticalAlign:{type:String,optional:!0},slots:Object};get iconStyle(){let e=this.props.cellPosition,t=this.env.model.getters.getMerge(e)||D(e),n=this.env.model.getters.getVisibleRectWithoutHeaders(t),r=this.getIconHorizontalPosition(n,e);return U({top:`${this.getIconVerticalPosition(n,e)}px`,left:`${r}px`})}getIconVerticalPosition(e,t){let n=e.y,r=e.y+e.height,i=this.env.model.getters.getCell(t);switch(this.props.verticalAlign||i?.style?.verticalAlign||Ie){case`bottom`:return r-2-17;case`top`:return n+2;default:let e=Math.floor((r-n-17)/2);return r-17-e}}getIconHorizontalPosition(e,t){let n=e.x,r=e.x+e.width,i=this.env.model.getters.getCell(t),a=this.env.model.getters.getEvaluatedCell(t);switch(this.props.horizontalAlign||i?.style?.align||a.defaultAlign){case`right`:return r-2-17;case`left`:return n+2;default:let e=Math.floor((r-n-17)/2);return r-17-e}}isPositionVisible(e){let t=this.env.model.getters.getVisibleRect(D(e));return!(t.width===0||t.height===0)}};H`
1573
+ `;var OI=class extends t.Component{static template=`o-spreadsheet-GridCellIcon`;static props={cellPosition:Object,horizontalAlign:{type:String,optional:!0},verticalAlign:{type:String,optional:!0},slots:Object};get iconStyle(){let e=this.props.cellPosition,t=this.env.model.getters.getMerge(e)||D(e),n=this.env.model.getters.getVisibleRectWithoutHeaders(t),r=this.getIconHorizontalPosition(n,e);return U({top:`${this.getIconVerticalPosition(n,e)}px`,left:`${r}px`})}getIconVerticalPosition(e,t){let n=e.y,r=e.y+e.height,i=this.env.model.getters.getCell(t);switch(this.props.verticalAlign||i?.style?.verticalAlign||Ie){case`bottom`:return r-2-17;case`top`:return n+2;default:let e=Math.floor((r-n-17)/2);return r-17-e}}getIconHorizontalPosition(e,t){let n=e.x,r=e.x+e.width,i=this.env.model.getters.getCell(t),a=this.env.model.getters.getEvaluatedCell(t);switch(this.props.horizontalAlign||i?.style?.align||a.defaultAlign){case`right`:return r-2-17;case`left`:return n+2;default:let e=Math.floor((r-n-17)/2);return r-17-e}}isPositionVisible(e){let t=this.env.model.getters.getVisibleRect(D(e));return!(t.width===0||t.height===0)}};H`
1574
1574
  .o-dv-checkbox {
1575
1575
  box-sizing: border-box !important;
1576
1576
  accent-color: #808080;
@@ -1578,7 +1578,7 @@ stores.inject(MyMetaStore, storeInstance);
1578
1578
  /** required to prevent the checkbox position to be sensible to the font-size (affects Firefox) */
1579
1579
  position: absolute;
1580
1580
  }
1581
- `;var AI=class extends t.Component{static template=`o-spreadsheet-DataValidationCheckbox`;static components={Checkbox:TN};static props={cellPosition:Object};onCheckboxChange(e){let{sheetId:t,col:n,row:r}=this.props.cellPosition,i=e?`TRUE`:`FALSE`;this.env.model.dispatch(`UPDATE_CELL`,{sheetId:t,col:n,row:r,content:i})}get checkBoxValue(){return!!this.env.model.getters.getEvaluatedCell(this.props.cellPosition).value}get isDisabled(){let e=this.env.model.getters.getCell(this.props.cellPosition);return this.env.model.getters.isReadonly()||!!e?.isFormula}};H`
1581
+ `;var kI=class extends t.Component{static template=`o-spreadsheet-DataValidationCheckbox`;static components={Checkbox:TN};static props={cellPosition:Object};onCheckboxChange(e){let{sheetId:t,col:n,row:r}=this.props.cellPosition,i=e?`TRUE`:`FALSE`;this.env.model.dispatch(`UPDATE_CELL`,{sheetId:t,col:n,row:r,content:i})}get checkBoxValue(){return!!this.env.model.getters.getEvaluatedCell(this.props.cellPosition).value}get isDisabled(){let e=this.env.model.getters.getCell(this.props.cellPosition);return this.env.model.getters.isReadonly()||!!e?.isFormula}};H`
1582
1582
  .o-dv-list-icon {
1583
1583
  color: ${Se};
1584
1584
  border-radius: 1px;
@@ -1595,7 +1595,7 @@ stores.inject(MyMetaStore, storeInstance);
1595
1595
  height: ${13}px;
1596
1596
  }
1597
1597
  }
1598
- `;var jI=class extends t.Component{static template=`o-spreadsheet-DataValidationListIcon`;static props={cellPosition:Object};onClick(){let{col:e,row:t}=this.props.cellPosition;this.env.model.selection.selectCell(e,t),this.env.startCellEdition()}},MI=class extends t.Component{static template=`o-spreadsheet-DataValidationOverlay`;static props={};static components={GridCellIcon:kI,DataValidationCheckbox:AI,DataValidationListIcon:jI};get checkBoxCellPositions(){return this.env.model.getters.getVisibleCellPositions().filter(e=>this.env.model.getters.isCellValidCheckbox(e)&&!this.env.model.getters.isFilterHeader(e))}get listIconsCellPositions(){return this.env.model.getters.isReadonly()?[]:this.env.model.getters.getVisibleCellPositions().filter(e=>this.env.model.getters.cellHasListDataValidationIcon(e)&&!this.env.model.getters.isFilterHeader(e))}};function NI(e,t){return{...t,...FI(e,{x:t.x,y:t.y})}}function PI(e,t){return{...t,...II(e,{x:t.x,y:t.y})}}function FI(e,{x:t,y:n}){let{x:r,y:i}=e.getMainViewportCoordinates(),{scrollX:a,scrollY:o}=e.getActiveSheetScrollInfo();return t=t<r?t:t-a,n=n<i?n:n-o,{x:t,y:n}}function II(e,{x:t,y:n}){let{x:r,y:i}=e.getMainViewportCoordinates(),{scrollX:a,scrollY:o}=e.getActiveSheetScrollInfo();return t=r&&t<r?t:t+a,n=i&&n<i?n:n+o,{x:t,y:n}}function LI({x:e,y:t},{x:n,y:r},i,{x:a,y:o},{maxX:s,maxY:c},{scrollX:l,scrollY:u}){let d=a?0:-l,f=o?0:-u,p=e-n,m=b(i.x+p,d,s-i.width-l),h=t-r,g=b(i.y+h,f,c-i.height-u);return{...i,x:m,y:g}}function RI(e,t,n,{x:r,y:i},{x:a,y:o},s,c,{scrollX:l,scrollY:u}){let{x:d,y:f,width:p,height:m}=e;if(s&&t!==0&&n!==0){let s=Math.min(t*(a-r),e.width-c),l=Math.min(n*(o-i),e.height-c),u=Math.min(s/e.width,l/e.height);p=e.width*(1-u),m=e.height*(1-u),t<0&&(d=e.x+e.width*u),n<0&&(f=e.y+e.height*u)}else{let s=Math.max(t*(r-a),c-e.width),l=Math.max(n*(i-o),c-e.height);p=e.width+s,m=e.height+l,t<0&&(d=e.x-s),n<0&&(f=e.y-l)}return d+l<=0&&(p=p+d+l,d=-l),f+u<=0&&(m=m+f+u,f=-u),{...e,x:d,y:f,width:p,height:m}}function zI(e,t,n){let r={...t},i=WI(e,r,[`hCenter`,`right`,`left`],n,[`hCenter`,`right`,`left`]),a=WI(e,r,[`vCenter`,`bottom`,`top`],n,[`vCenter`,`bottom`,`top`]),{y:o,x:s}=e.getMainViewportCoordinates(),{scrollY:c,scrollX:l}=e.getActiveSheetScrollInfo();if(a){r.y-=a.snapOffset;let e=t.y<o,n=r.y<o;e&&!n?r.y+=c:!e&&n&&(r.y-=c)}if(i){r.x-=i.snapOffset;let e=t.x<s,n=r.x<s;e&&!n?r.x+=l:!e&&n&&(r.x-=l)}return{snappedFigure:r,verticalSnapLine:i,horizontalSnapLine:a}}function BI(e,t,n,r,i){let a={...r},o=WI(e,a,[t===-1?`left`:`right`],i,[`right`,`left`]);o&&(t===1?a.width-=o.snapOffset:t===-1&&(a.x-=o.snapOffset,a.width+=o.snapOffset));let s=WI(e,a,[n===-1?`top`:`bottom`],i,[`bottom`,`top`]);return s&&(n===1?a.height-=s.snapOffset:n===-1&&(a.y-=s.snapOffset,a.height+=s.snapOffset)),a.x=Math.round(a.x),a.y=Math.round(a.y),a.height=Math.round(a.height),a.width=Math.round(a.width),{snappedFigure:a,verticalSnapLine:o,horizontalSnapLine:s}}function VI(e,t,n){return n.map(e=>KI(t,e)).filter(n=>UI(e,t,n)).map(n=>HI(e,t,n))}function HI(e,t,n){return KI(NI(e,t),n.axisType)}function UI(e,t,n){let{x:r,y:i}=e.getMainViewportCoordinates(),a=[];switch(n.axisType){case`top`:case`bottom`:case`vCenter`:if(t.y<i)return!0;a.push({x:t.x,y:n.position}),a.push({x:t.x+t.width,y:n.position});break;case`left`:case`right`:case`hCenter`:if(t.x<r)return!0;a.push({x:n.position,y:t.y}),a.push({x:n.position,y:t.y+t.height});break}return a.some(e.isPositionVisible)}function WI(e,t,n,r,i){let a=VI(e,t,n),o;for(let t of r){let n=VI(e,t,i);for(let e of a)for(let r of n){if(!GI(e.position,r.position))continue;let n=e.position-r.position;o&&n===o.snapOffset?o.matchedFigIds.push(t.id):(!o||Math.abs(n)<=Math.abs(o.snapOffset))&&(o={matchedFigIds:[t.id],snapOffset:n,snappedAxisType:e.axisType,position:r.position})}}return o}function GI(e,t){return Math.abs(e-t)<=5}function KI(e,t){let n=0;switch(t){case`top`:n=e.y;break;case`bottom`:n=e.y+e.height-1;break;case`vCenter`:n=e.y+Math.floor(e.height/2)-1;break;case`left`:n=e.x;break;case`right`:n=e.x+e.width-1;break;case`hCenter`:n=e.x+Math.floor(e.width/2)-1;break}return{position:n,axisType:t}}H`
1598
+ `;var AI=class extends t.Component{static template=`o-spreadsheet-DataValidationListIcon`;static props={cellPosition:Object};onClick(){let{col:e,row:t}=this.props.cellPosition;this.env.model.selection.selectCell(e,t),this.env.startCellEdition()}},jI=class extends t.Component{static template=`o-spreadsheet-DataValidationOverlay`;static props={};static components={GridCellIcon:OI,DataValidationCheckbox:kI,DataValidationListIcon:AI};get checkBoxCellPositions(){return this.env.model.getters.getVisibleCellPositions().filter(e=>this.env.model.getters.isCellValidCheckbox(e)&&!this.env.model.getters.isFilterHeader(e))}get listIconsCellPositions(){return this.env.model.getters.isReadonly()?[]:this.env.model.getters.getVisibleCellPositions().filter(e=>this.env.model.getters.cellHasListDataValidationIcon(e)&&!this.env.model.getters.isFilterHeader(e))}};function MI(e,t){return{...t,...PI(e,{x:t.x,y:t.y})}}function NI(e,t){return{...t,...FI(e,{x:t.x,y:t.y})}}function PI(e,{x:t,y:n}){let{x:r,y:i}=e.getMainViewportCoordinates(),{scrollX:a,scrollY:o}=e.getActiveSheetScrollInfo();return t=t<r?t:t-a,n=n<i?n:n-o,{x:t,y:n}}function FI(e,{x:t,y:n}){let{x:r,y:i}=e.getMainViewportCoordinates(),{scrollX:a,scrollY:o}=e.getActiveSheetScrollInfo();return t=r&&t<r?t:t+a,n=i&&n<i?n:n+o,{x:t,y:n}}function II({x:e,y:t},{x:n,y:r},i,{x:a,y:o},{maxX:s,maxY:c},{scrollX:l,scrollY:u}){let d=a?0:-l,f=o?0:-u,p=e-n,m=b(i.x+p,d,s-i.width-l),h=t-r,g=b(i.y+h,f,c-i.height-u);return{...i,x:m,y:g}}function LI(e,t,n,{x:r,y:i},{x:a,y:o},s,c,{scrollX:l,scrollY:u}){let{x:d,y:f,width:p,height:m}=e;if(s&&t!==0&&n!==0){let s=Math.min(t*(a-r),e.width-c),l=Math.min(n*(o-i),e.height-c),u=Math.min(s/e.width,l/e.height);p=e.width*(1-u),m=e.height*(1-u),t<0&&(d=e.x+e.width*u),n<0&&(f=e.y+e.height*u)}else{let s=Math.max(t*(r-a),c-e.width),l=Math.max(n*(i-o),c-e.height);p=e.width+s,m=e.height+l,t<0&&(d=e.x-s),n<0&&(f=e.y-l)}return d+l<=0&&(p=p+d+l,d=-l),f+u<=0&&(m=m+f+u,f=-u),{...e,x:d,y:f,width:p,height:m}}function RI(e,t,n){let r={...t},i=UI(e,r,[`hCenter`,`right`,`left`],n,[`hCenter`,`right`,`left`]),a=UI(e,r,[`vCenter`,`bottom`,`top`],n,[`vCenter`,`bottom`,`top`]),{y:o,x:s}=e.getMainViewportCoordinates(),{scrollY:c,scrollX:l}=e.getActiveSheetScrollInfo();if(a){r.y-=a.snapOffset;let e=t.y<o,n=r.y<o;e&&!n?r.y+=c:!e&&n&&(r.y-=c)}if(i){r.x-=i.snapOffset;let e=t.x<s,n=r.x<s;e&&!n?r.x+=l:!e&&n&&(r.x-=l)}return{snappedFigure:r,verticalSnapLine:i,horizontalSnapLine:a}}function zI(e,t,n,r,i){let a={...r},o=UI(e,a,[t===-1?`left`:`right`],i,[`right`,`left`]);o&&(t===1?a.width-=o.snapOffset:t===-1&&(a.x-=o.snapOffset,a.width+=o.snapOffset));let s=UI(e,a,[n===-1?`top`:`bottom`],i,[`bottom`,`top`]);return s&&(n===1?a.height-=s.snapOffset:n===-1&&(a.y-=s.snapOffset,a.height+=s.snapOffset)),a.x=Math.round(a.x),a.y=Math.round(a.y),a.height=Math.round(a.height),a.width=Math.round(a.width),{snappedFigure:a,verticalSnapLine:o,horizontalSnapLine:s}}function BI(e,t,n){return n.map(e=>GI(t,e)).filter(n=>HI(e,t,n)).map(n=>VI(e,t,n))}function VI(e,t,n){return GI(MI(e,t),n.axisType)}function HI(e,t,n){let{x:r,y:i}=e.getMainViewportCoordinates(),a=[];switch(n.axisType){case`top`:case`bottom`:case`vCenter`:if(t.y<i)return!0;a.push({x:t.x,y:n.position}),a.push({x:t.x+t.width,y:n.position});break;case`left`:case`right`:case`hCenter`:if(t.x<r)return!0;a.push({x:n.position,y:t.y}),a.push({x:n.position,y:t.y+t.height});break}return a.some(e.isPositionVisible)}function UI(e,t,n,r,i){let a=BI(e,t,n),o;for(let t of r){let n=BI(e,t,i);for(let e of a)for(let r of n){if(!WI(e.position,r.position))continue;let n=e.position-r.position;o&&n===o.snapOffset?o.matchedFigIds.push(t.id):(!o||Math.abs(n)<=Math.abs(o.snapOffset))&&(o={matchedFigIds:[t.id],snapOffset:n,snappedAxisType:e.axisType,position:r.position})}}return o}function WI(e,t){return Math.abs(e-t)<=5}function GI(e,t){let n=0;switch(t){case`top`:n=e.y;break;case`bottom`:n=e.y+e.height-1;break;case`vCenter`:n=e.y+Math.floor(e.height/2)-1;break;case`left`:n=e.x;break;case`right`:n=e.x+e.width-1;break;case`hCenter`:n=e.x+Math.floor(e.width/2)-1;break}return{position:n,axisType:t}}H`
1599
1599
  .o-figure-snap-line {
1600
1600
  position: relative;
1601
1601
  z-index: ${1001};
@@ -1612,7 +1612,7 @@ stores.inject(MyMetaStore, storeInstance);
1612
1612
  -webkit-user-select: none; // safari
1613
1613
  user-select: none;
1614
1614
  }
1615
- `;var qI=class extends t.Component{static template=`o-spreadsheet-FiguresContainer`;static props={};static components={FigureComponent:mI};dnd=(0,t.useState)({draggedFigure:void 0,horizontalSnap:void 0,verticalSnap:void 0,cancelDnd:void 0});setup(){(0,t.onMounted)(()=>{this.render()}),(0,t.onWillUpdateProps)(()=>{let 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.cancelDnd=void 0)})}getVisibleFigures(){let e=this.env.model.getters.getVisibleFigures();if(this.dnd.draggedFigure&&!e.some(e=>e.id===this.dnd.draggedFigure?.id)){let t=this.env.model.getters.getFigure(this.env.model.getters.getActiveSheetId(),this.dnd.draggedFigure?.id);t&&e.push(t)}return e}get containers(){let e=this.getVisibleFigures(),t=[];for(let n of[`topLeft`,`topRight`,`bottomLeft`,`bottomRight`]){let r=e.filter(e=>this.getFigureContainer(e)===n);r.length>0&&t.push({type:n,figures:r,style:this.getContainerStyle(n),inverseViewportStyle:this.getInverseViewportPositionStyle(n)})}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 U({left:`${e.x}px`,top:`${e.y}px`,width:`${e.width}px`,height:`${e.height}px`})}getContainerRect(e){let{width:t,height:n}=this.env.model.getters.getSheetViewDimension(),{x:r,y:i}=this.env.model.getters.getMainViewportCoordinates(),a=[`bottomRight`,`topRight`].includes(e)?r:0,o=t-a,s=[`bottomRight`,`bottomLeft`].includes(e)?i:0;return{x:a,y:s,width:o,height:n-s}}getInverseViewportPositionStyle(e){let{scrollX:t,scrollY:n}=this.env.model.getters.getActiveSheetScrollInfo(),{x:r,y:i}=this.env.model.getters.getMainViewportCoordinates(),a=[`bottomRight`,`topRight`].includes(e)?-(r+t):0,o=[`bottomRight`,`bottomLeft`].includes(e)?-(i+n):0;return U({left:`${a}px`,top:`${o}px`})}getFigureContainer(e){let{x:t,y:n}=this.env.model.getters.getMainViewportCoordinates();return e.id===this.dnd.draggedFigure?.id?`dnd`:e.x<t&&e.y<n?`topLeft`:e.x<t?`bottomLeft`:e.y<n?`topRight`:`bottomRight`}startDraggingFigure(e,t){if(t.button>0||this.env.model.getters.isReadonly()||!this.env.model.dispatch(`SELECT_FIGURE`,{id:e.id}).isSuccessful)return;let n=this.env.model.getters.getActiveSheetId(),r={x:t.clientX,y:t.clientY},i={maxX:this.env.model.getters.getColDimensions(n,this.env.model.getters.getNumberCols(n)-1).end,maxY:this.env.model.getters.getRowDimensions(n,this.env.model.getters.getNumberRows(n)-1).end},{x:a,y:o}=NI(this.env.model.getters,e),s={...e,x:a,y:o},c=t=>{let n=this.env.model.getters,a=LI({x:t.clientX,y:t.clientY},r,s,this.env.model.getters.getMainViewportCoordinates(),i,n.getActiveSheetScrollInfo()),o=this.getOtherFigures(e.id),c=zI(n,PI(n,a),o);this.dnd.draggedFigure=NI(n,c.snappedFigure),this.dnd.horizontalSnap=this.getSnap(c.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(c.verticalSnapLine)},l=t=>{if(!this.dnd.draggedFigure)return;let{x:r,y:i}=PI(this.env.model.getters,this.dnd.draggedFigure);this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.env.model.dispatch(`UPDATE_FIGURE`,{sheetId:n,id:e.id,x:r,y:i})};this.dnd.cancelDnd=RN(c,l)}startResize(e,t,n,r){r.stopPropagation();let i={x:r.clientX,y:r.clientY},{x:a,y:o}=NI(this.env.model.getters,e),s={...e,x:a,y:o},c=pO.get(e.tag).keepRatio||!1,l=pO.get(e.tag).minFigSize||80,u=r=>{let a=RI(s,t,n,{x:r.clientX,y:r.clientY},i,c,l,this.env.model.getters.getActiveSheetScrollInfo()),o=this.getOtherFigures(e.id),u=BI(this.env.model.getters,t,n,a,o);this.dnd.draggedFigure=u.snappedFigure,this.dnd.horizontalSnap=this.getSnap(u.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(u.verticalSnapLine)},d=r=>{if(!this.dnd.draggedFigure)return;let{x:i,y:a}=PI(this.env.model.getters,this.dnd.draggedFigure),o={x:i,y:a};t&&(o.width=this.dnd.draggedFigure.width),n&&(o.height=this.dnd.draggedFigure.height),this.env.model.dispatch(`UPDATE_FIGURE`,{sheetId:this.env.model.getters.getActiveSheetId(),id:e.id,...o}),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0};this.dnd.cancelDnd=RN(u,d)}getOtherFigures(e){return this.getVisibleFigures().filter(t=>t.id!==e)}getDndFigure(){let e=this.getVisibleFigures().find(e=>e.id===this.dnd.draggedFigure?.id);if(!e)throw Error(`Dnd figure not found`);return{...e,...this.dnd.draggedFigure}}getFigureStyle(e){return e.id===this.dnd.draggedFigure?.id?U({opacity:`0.9`,cursor:`grabbing`}):``}getSnap(e){if(!e||!this.dnd.draggedFigure)return;let t=e.matchedFigIds.map(e=>this.getVisibleFigures().find(t=>t.id===e)).filter(S).map(e=>{let t=NI(this.env.model.getters,e),n=this.getFigureContainer(e);return ak(t,this.getContainerRect(n))}).filter(S),n=ok(this.dnd.draggedFigure,...t);return{line:e,containerStyle:this.rectToCss(n),lineStyle:this.getSnapLineStyle(e,n)}}getSnapLineStyle(e,t){return e?[`top`,`vCenter`,`bottom`].includes(e.snappedAxisType)?U({top:`${e.position-t.y}px`,left:`0px`,width:`100%`}):U({top:`0px`,left:`${e.position-t.x}px`,height:`100%`}):``}};H`
1615
+ `;var KI=class extends t.Component{static template=`o-spreadsheet-FiguresContainer`;static props={};static components={FigureComponent:pI};dnd=(0,t.useState)({draggedFigure:void 0,horizontalSnap:void 0,verticalSnap:void 0,cancelDnd:void 0});setup(){(0,t.onMounted)(()=>{this.render()}),(0,t.onWillUpdateProps)(()=>{let 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.cancelDnd=void 0)})}getVisibleFigures(){let e=this.env.model.getters.getVisibleFigures();if(this.dnd.draggedFigure&&!e.some(e=>e.id===this.dnd.draggedFigure?.id)){let t=this.env.model.getters.getFigure(this.env.model.getters.getActiveSheetId(),this.dnd.draggedFigure?.id);t&&e.push(t)}return e}get containers(){let e=this.getVisibleFigures(),t=[];for(let n of[`topLeft`,`topRight`,`bottomLeft`,`bottomRight`]){let r=e.filter(e=>this.getFigureContainer(e)===n);r.length>0&&t.push({type:n,figures:r,style:this.getContainerStyle(n),inverseViewportStyle:this.getInverseViewportPositionStyle(n)})}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 U({left:`${e.x}px`,top:`${e.y}px`,width:`${e.width}px`,height:`${e.height}px`})}getContainerRect(e){let{width:t,height:n}=this.env.model.getters.getSheetViewDimension(),{x:r,y:i}=this.env.model.getters.getMainViewportCoordinates(),a=[`bottomRight`,`topRight`].includes(e)?r:0,o=t-a,s=[`bottomRight`,`bottomLeft`].includes(e)?i:0;return{x:a,y:s,width:o,height:n-s}}getInverseViewportPositionStyle(e){let{scrollX:t,scrollY:n}=this.env.model.getters.getActiveSheetScrollInfo(),{x:r,y:i}=this.env.model.getters.getMainViewportCoordinates(),a=[`bottomRight`,`topRight`].includes(e)?-(r+t):0,o=[`bottomRight`,`bottomLeft`].includes(e)?-(i+n):0;return U({left:`${a}px`,top:`${o}px`})}getFigureContainer(e){let{x:t,y:n}=this.env.model.getters.getMainViewportCoordinates();return e.id===this.dnd.draggedFigure?.id?`dnd`:e.x<t&&e.y<n?`topLeft`:e.x<t?`bottomLeft`:e.y<n?`topRight`:`bottomRight`}startDraggingFigure(e,t){if(t.button>0||this.env.model.getters.isReadonly()||!this.env.model.dispatch(`SELECT_FIGURE`,{id:e.id}).isSuccessful)return;let n=this.env.model.getters.getActiveSheetId(),r={x:t.clientX,y:t.clientY},i={maxX:this.env.model.getters.getColDimensions(n,this.env.model.getters.getNumberCols(n)-1).end,maxY:this.env.model.getters.getRowDimensions(n,this.env.model.getters.getNumberRows(n)-1).end},{x:a,y:o}=MI(this.env.model.getters,e),s={...e,x:a,y:o},c=t=>{let n=this.env.model.getters,a=II({x:t.clientX,y:t.clientY},r,s,this.env.model.getters.getMainViewportCoordinates(),i,n.getActiveSheetScrollInfo()),o=this.getOtherFigures(e.id),c=RI(n,NI(n,a),o);this.dnd.draggedFigure=MI(n,c.snappedFigure),this.dnd.horizontalSnap=this.getSnap(c.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(c.verticalSnapLine)},l=t=>{if(!this.dnd.draggedFigure)return;let{x:r,y:i}=NI(this.env.model.getters,this.dnd.draggedFigure);this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.env.model.dispatch(`UPDATE_FIGURE`,{sheetId:n,id:e.id,x:r,y:i})};this.dnd.cancelDnd=RN(c,l)}startResize(e,t,n,r){r.stopPropagation();let i={x:r.clientX,y:r.clientY},{x:a,y:o}=MI(this.env.model.getters,e),s={...e,x:a,y:o},c=pO.get(e.tag).keepRatio||!1,l=pO.get(e.tag).minFigSize||80,u=r=>{let a=LI(s,t,n,{x:r.clientX,y:r.clientY},i,c,l,this.env.model.getters.getActiveSheetScrollInfo()),o=this.getOtherFigures(e.id),u=zI(this.env.model.getters,t,n,a,o);this.dnd.draggedFigure=u.snappedFigure,this.dnd.horizontalSnap=this.getSnap(u.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(u.verticalSnapLine)},d=r=>{if(!this.dnd.draggedFigure)return;let{x:i,y:a}=NI(this.env.model.getters,this.dnd.draggedFigure),o={x:i,y:a};t&&(o.width=this.dnd.draggedFigure.width),n&&(o.height=this.dnd.draggedFigure.height),this.env.model.dispatch(`UPDATE_FIGURE`,{sheetId:this.env.model.getters.getActiveSheetId(),id:e.id,...o}),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0};this.dnd.cancelDnd=RN(u,d)}getOtherFigures(e){return this.getVisibleFigures().filter(t=>t.id!==e)}getDndFigure(){let e=this.getVisibleFigures().find(e=>e.id===this.dnd.draggedFigure?.id);if(!e)throw Error(`Dnd figure not found`);return{...e,...this.dnd.draggedFigure}}getFigureStyle(e){return e.id===this.dnd.draggedFigure?.id?U({opacity:`0.9`,cursor:`grabbing`}):``}getSnap(e){if(!e||!this.dnd.draggedFigure)return;let t=e.matchedFigIds.map(e=>this.getVisibleFigures().find(t=>t.id===e)).filter(S).map(e=>{let t=MI(this.env.model.getters,e),n=this.getFigureContainer(e);return ak(t,this.getContainerRect(n))}).filter(S),n=ok(this.dnd.draggedFigure,...t);return{line:e,containerStyle:this.rectToCss(n),lineStyle:this.getSnapLineStyle(e,n)}}getSnapLineStyle(e,t){return e?[`top`,`vCenter`,`bottom`].includes(e.snappedAxisType)?U({top:`${e.position-t.y}px`,left:`0px`,width:`100%`}):U({top:`0px`,left:`${e.position-t.x}px`,height:`100%`}):``}};H`
1616
1616
  .o-filter-icon {
1617
1617
  color: ${ue};
1618
1618
  display: flex;
@@ -1638,7 +1638,7 @@ stores.inject(MyMetaStore, storeInstance);
1638
1638
  background: ${ue};
1639
1639
  color: #fff;
1640
1640
  }
1641
- `;var JI=class extends t.Component{static template=`o-spreadsheet-FilterIcon`;static props={cellPosition:Object};cellPopovers;setup(){this.cellPopovers=V(GO)}onClick(){let e=this.props.cellPosition,t=this.cellPopovers.persistentCellPopover,{col:n,row:r}=e;if(t.isOpen&&t.col===n&&t.row===r&&t.type===`FilterMenu`){this.cellPopovers.close();return}this.cellPopovers.open({col:n,row:r},`FilterMenu`)}get isFilterActive(){return this.env.model.getters.isFilterActive(this.props.cellPosition)}get iconClass(){return on(this.env.model.getters.getCellComputedStyle(this.props.cellPosition).fillColor||`#fff`)<.45?`o-high-contrast`:``}},YI=class extends t.Component{static template=`o-spreadsheet-FilterIconsOverlay`;static props={};static components={GridCellIcon:kI,FilterIcon:JI};getFilterHeadersPositions(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getFilterHeaders(e)}};H`
1641
+ `;var qI=class extends t.Component{static template=`o-spreadsheet-FilterIcon`;static props={cellPosition:Object};cellPopovers;setup(){this.cellPopovers=V(GO)}onClick(){let e=this.props.cellPosition,t=this.cellPopovers.persistentCellPopover,{col:n,row:r}=e;if(t.isOpen&&t.col===n&&t.row===r&&t.type===`FilterMenu`){this.cellPopovers.close();return}this.cellPopovers.open({col:n,row:r},`FilterMenu`)}get isFilterActive(){return this.env.model.getters.isFilterActive(this.props.cellPosition)}get iconClass(){return on(this.env.model.getters.getCellComputedStyle(this.props.cellPosition).fillColor||`#fff`)<.45?`o-high-contrast`:``}},JI=class extends t.Component{static template=`o-spreadsheet-FilterIconsOverlay`;static props={};static components={GridCellIcon:OI,FilterIcon:qI};getFilterHeadersPositions(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getFilterHeaders(e)}};H`
1642
1642
  .o-grid-add-rows {
1643
1643
  input.o-input {
1644
1644
  box-sizing: border-box;
@@ -1652,11 +1652,11 @@ stores.inject(MyMetaStore, storeInstance);
1652
1652
  margin-left: 8px;
1653
1653
  }
1654
1654
  }
1655
- `;var XI=class extends t.Component{static template=`o-spreadsheet-GridAddRowsFooter`;static props={};static components={ValidationMessages:AN};DOMFocusableElementStore;inputRef=(0,t.useRef)(`inputRef`);state=(0,t.useState)({inputValue:`100`,errorFlag:!1});setup(){this.DOMFocusableElementStore=V(GT),(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0})}get addRowsPosition(){let e=this.env.model.getters.getActiveSheetId(),{numberOfRows:t}=this.env.model.getters.getSheetSize(e),{scrollY:n}=this.env.model.getters.getActiveSheetScrollInfo();return U({top:`${this.env.model.getters.getRowDimensions(e,t-1).end-n}px`})}get errorMessages(){return[E(`Please enter a number between 0 and 10000.`)]}onKeydown(e){e.key.toUpperCase()===`ESCAPE`?this.focusDefaultElement():e.key.toUpperCase()===`ENTER`&&this.onConfirm()}onInput(e){let t=e.target.value;this.state.inputValue=t;let n=Number(t);this.state.errorFlag=Number.isNaN(n)||n<=0||n>1e4}onConfirm(){if(this.state.errorFlag)return;let e=Number(this.state.inputValue),t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getNumberRows(t);this.env.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:t,position:`after`,base:n-1,quantity:e,dimension:`ROW`}),this.focusDefaultElement();let{scrollX:r}=this.env.model.getters.getActiveSheetDOMScrollInfo(),{end:i}=this.env.model.getters.getRowDimensions(t,n+e-1);this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:r,offsetY:i})}onExternalClick(e){this.inputRef.el!==document.activeElement||e.target===this.inputRef.el||this.focusDefaultElement()}focusDefaultElement(){document.activeElement===this.inputRef.el&&this.DOMFocusableElementStore.focus()}};let ZI=[`cell`,`border`,`table`,`conditionalFormat`,`merge`];var QI=class extends hd{mutators=[`activate`,`cancel`,`pasteFormat`];highlightStore=this.get(xN);status=`inactive`;copiedData;constructor(e){super(e),this.highlightStore.register(this),this.onDispose(()=>{this.highlightStore.unRegister(this)})}handle(e){switch(e.type){case`PAINT_FORMAT`:this.paintFormat(e.sheetId,e.target);break}}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 this.status!==`inactive`}get clipboardHandlers(){return ZI.map(e=>({handlerName:e,handler:new(ed.cellHandlers.get(e))(this.getters,this.model.dispatch)}))}copyFormats(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones(),n={zones:t,sheetId:e};for(let{handlerName:r,handler:i}of this.clipboardHandlers){let a=i.copy(Tc(e,t));a!==void 0&&(n[r]=a)}return n}paintFormat(e,t){if(!this.copiedData)return;let n={isCutOperation:!1,pasteOption:`onlyFormat`},{target:r,selectedZones:i}=jc(e,t,this.copiedData,this.clipboardHandlers,n);Ac(this.clipboardHandlers,this.copiedData,r,n),Mc(this.model.selection,t,i),this.status===`oneOff`&&this.cancel()}get highlights(){let e=this.copiedData;return e?e.zones.map(t=>({zone:t,color:ae,dashed:!0,sheetId:e.sheetId,noFill:!0,thinLine:!0,interactive:!1})):[]}};H`
1655
+ `;var YI=class extends t.Component{static template=`o-spreadsheet-GridAddRowsFooter`;static props={};static components={ValidationMessages:AN};DOMFocusableElementStore;inputRef=(0,t.useRef)(`inputRef`);state=(0,t.useState)({inputValue:`100`,errorFlag:!1});setup(){this.DOMFocusableElementStore=V(GT),(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0})}get addRowsPosition(){let e=this.env.model.getters.getActiveSheetId(),{numberOfRows:t}=this.env.model.getters.getSheetSize(e),{scrollY:n}=this.env.model.getters.getActiveSheetScrollInfo();return U({top:`${this.env.model.getters.getRowDimensions(e,t-1).end-n}px`})}get errorMessages(){return[E(`Please enter a number between 0 and 10000.`)]}onKeydown(e){e.key.toUpperCase()===`ESCAPE`?this.focusDefaultElement():e.key.toUpperCase()===`ENTER`&&this.onConfirm()}onInput(e){let t=e.target.value;this.state.inputValue=t;let n=Number(t);this.state.errorFlag=Number.isNaN(n)||n<=0||n>1e4}onConfirm(){if(this.state.errorFlag)return;let e=Number(this.state.inputValue),t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getNumberRows(t);this.env.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:t,position:`after`,base:n-1,quantity:e,dimension:`ROW`}),this.focusDefaultElement();let{scrollX:r}=this.env.model.getters.getActiveSheetDOMScrollInfo(),{end:i}=this.env.model.getters.getRowDimensions(t,n+e-1);this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:r,offsetY:i})}onExternalClick(e){this.inputRef.el!==document.activeElement||e.target===this.inputRef.el||this.focusDefaultElement()}focusDefaultElement(){document.activeElement===this.inputRef.el&&this.DOMFocusableElementStore.focus()}};let XI=[`cell`,`border`,`table`,`conditionalFormat`,`merge`];var ZI=class extends hd{mutators=[`activate`,`cancel`,`pasteFormat`];highlightStore=this.get(xN);status=`inactive`;copiedData;constructor(e){super(e),this.highlightStore.register(this),this.onDispose(()=>{this.highlightStore.unRegister(this)})}handle(e){switch(e.type){case`PAINT_FORMAT`:this.paintFormat(e.sheetId,e.target);break}}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 this.status!==`inactive`}get clipboardHandlers(){return XI.map(e=>({handlerName:e,handler:new(ed.cellHandlers.get(e))(this.getters,this.model.dispatch)}))}copyFormats(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones(),n={zones:t,sheetId:e};for(let{handlerName:r,handler:i}of this.clipboardHandlers){let a=i.copy(Tc(e,t));a!==void 0&&(n[r]=a)}return n}paintFormat(e,t){if(!this.copiedData)return;let n={isCutOperation:!1,pasteOption:`onlyFormat`},{target:r,selectedZones:i}=jc(e,t,this.copiedData,this.clipboardHandlers,n);Ac(this.clipboardHandlers,this.copiedData,r,n),Mc(this.model.selection,t,i),this.status===`oneOff`&&this.cancel()}get highlights(){let e=this.copiedData;return e?e.zones.map(t=>({zone:t,color:ae,dashed:!0,sheetId:e.sheetId,noFill:!0,thinLine:!0,interactive:!1})):[]}};H`
1656
1656
  .o-paint-format-cursor {
1657
1657
  cursor: url("data:image/svg+xml,${`%0A%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20width%3D%2214%22%20height%3D%2216%22%3E%3Cpath%20d%3D%22M6.5.4c1.3-.8%202.9-.1%203.8%201.4l2.9%205.1c.2.4.9%201.6-.4%202.3l-1.6.9%201.8%203.1c.2.4.1%201-.2%201.2l-1.6%201c-.3.1-.9%200-1.1-.4l-1.8-3.1-1.6%201c-.6.4-1.7%200-2.2-.8L0%204.3%22%2F%3E%3Cpath%20fill%3D%22%23fff%22%20d%3D%22M9.1%202a1.4%201.1%2060%200%200-1.7-.6L5.5%202.5l.9%201.6-1%20.6-.9-1.6-.6.4%201.8%203.1-1.3.7-1.8-3.1-1%20.6%203.8%206.6%206.8-3.98M3.9%208.8%2010.82%205l.795%201.4-6.81%203.96%22%2F%3E%3C%2Fsvg%3E%0A`}"), auto;
1658
1658
  }
1659
- `;function $I(e,n,r){let i={col:void 0,row:void 0},{Date:a}=window,o,s,c=0;function l(){return o===void 0||s===void 0?{col:-1,row:-1}:{col:e.model.getters.getColIndex(o),row:e.model.getters.getRowIndex(s)}}let{pause:u,resume:d}=rk(f,200);function f(){let{col:e,row:t}=l(),n=a.now()-c;if(n>300&&(e!==i.col||t!==i.row)&&_(void 0,void 0),n>300){if(e<0||t<0)return;_(e,t)}}function p(e){n.el===e.target&&(o=e.offsetX,s=e.offsetY,c=a.now())}function m(){let{col:e,row:t}=l();(e!==i.col||t!==i.row)&&_(void 0,void 0)}function h(e){let t=e.offsetX,r=e.offsetY,i=XT(n.el);return r<0||r>i.height||t<0||t>i.width?p(e):u()}_P(n,`pointermove`,p),_P(n,`mouseleave`,h),_P(n,`mouseenter`,d),_P(n,`pointerdown`,m),(0,t.useExternalListener)(window,`click`,g);function g(e){let t=e.target;n.el.contains(t)||_(void 0,void 0)}function _(e,t){(e!==i.col||t!==i.row)&&(i.col=e,i.row=t,r({col:e,row:t}))}return i}var eL=class extends t.Component{static template=`o-spreadsheet-GridOverlay`;static props={onCellHovered:{type:Function,optional:!0},onCellDoubleClicked:{type:Function,optional:!0},onCellClicked:{type:Function,optional:!0},onCellRightClicked:{type:Function,optional:!0},onGridResized:{type:Function,optional:!0},onGridMoved:Function,gridOverlayDimensions:String};static components={FiguresContainer:qI,DataValidationOverlay:MI,GridAddRowsFooter:XI,FilterIconsOverlay:YI};static defaultProps={onCellHovered:()=>{},onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{}};gridOverlay=(0,t.useRef)(`gridOverlay`);gridOverlayRect=iE(this.gridOverlay);cellPopovers;paintFormatStore;setup(){$I(this.env,this.gridOverlay,this.props.onCellHovered);let e=new ResizeObserver(()=>{let e=this.gridOverlayEl.getBoundingClientRect();this.props.onGridResized({x:e.left,y:e.top,height:this.gridOverlayEl.clientHeight,width:this.gridOverlayEl.clientWidth})});(0,t.onMounted)(()=>{e.observe(this.gridOverlayEl)}),(0,t.onWillUnmount)(()=>{e.disconnect()}),this.cellPopovers=V(GO),this.paintFormatStore=V(QI)}get gridOverlayEl(){if(!this.gridOverlay.el)throw Error(`GridOverlay el is not defined.`);return this.gridOverlay.el}get style(){return this.props.gridOverlayDimensions}get isPaintingFormat(){return this.paintFormatStore.isActive}onMouseDown(e){if(e.button>0)return;e.target===this.gridOverlay.el&&this.cellPopovers.isOpen&&this.cellPopovers.close();let[t,n]=this.getCartesianCoordinates(e);this.props.onCellClicked(t,n,{expandZone:e.shiftKey,addZone:nE(e)})}onDoubleClick(e){let[t,n]=this.getCartesianCoordinates(e);this.props.onCellDoubleClicked(t,n)}onContextMenu(e){let[t,n]=this.getCartesianCoordinates(e);this.props.onCellRightClicked(t,n,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){let t=e.clientX-this.gridOverlayRect.x,n=e.clientY-this.gridOverlayRect.y;return[this.env.model.getters.getColIndex(t),this.env.model.getters.getRowIndex(n)]}},tL=class extends t.Component{static template=`o-spreadsheet-GridPopover`;static props={onClosePopover:Function,onMouseWheel:Function,gridRect:Object};static components={Popover:lk};cellPopovers;zIndex=19;setup(){this.cellPopovers=V(GO)}get cellPopover(){let e=this.cellPopovers.cellPopover;if(!e.isOpen)return{isOpen:!1};let t=e.anchorRect;return{...e,anchorRect:{...t,x:t.x+this.props.gridRect.x,y:t.y+this.props.gridRect.y}}}},nL=class extends t.Component{static props={onOpenContextMenu:Function};composerFocusStore;PADDING=0;MAX_SIZE_MARGIN=0;MIN_ELEMENT_SIZE=0;lastSelectedElementIndex=null;state=(0,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`});setup(){this.composerFocusStore=V(_d)}_computeHandleDisplay(e){let t=this._getEvOffset(e),n=this._getElementIndex(t);if(n<0)return;let r=this._getDimensionsInViewport(n);t-r.start<this.PADDING&&n!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=r.start,this.state.activeElement=this._getPreviousVisibleElement(n)):r.end-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=r.end,this.state.activeElement=n):this.state.resizerIsActive=!1}_computeGrabDisplay(e){let t=this._getElementIndex(this._getEvOffset(e)),n=this._getActiveElements(),r=this._getSelectedZoneStart(),i=this._getSelectedZoneEnd();if(n.has(r)&&r<=t&&t<=i){this.state.waitingForMove=!0;return}this.state.waitingForMove=!1}onMouseMove(e){this.env.model.getters.isReadonly()||this.state.isResizing||this.state.isMoving||this.state.isSelecting||(this._computeHandleDisplay(e),this._computeGrabDisplay(e))}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(e){this._fitElementSize(this.state.activeElement),this.state.isResizing=!1,this._computeHandleDisplay(e),this._computeGrabDisplay(e)}onMouseDown(e){this.state.isResizing=!0,this.state.delta=0;let t=this._getClientPosition(e),n=this.state.draggerLinePosition,r=this._getElementSize(this.state.activeElement),i=n-r+this.MIN_ELEMENT_SIZE,a=this._getMaxSize();RN(e=>{this.state.delta=this._getClientPosition(e)-t,this.state.draggerLinePosition=n+this.state.delta,this.state.draggerLinePosition<i&&(this.state.draggerLinePosition=i,this.state.delta=this.MIN_ELEMENT_SIZE-r),this.state.draggerLinePosition>a&&(this.state.draggerLinePosition=a,this.state.delta=a-n)},e=>{this.state.isResizing=!1,this.state.delta!==0&&this._updateSize()})}select(e){if(e.button>0)return;let t=this._getElementIndex(this._getEvOffset(e));if(!(t<0)){if(this.env.model.getters.isReadonly()){this._selectElement(t,!1);return}if(this.state.waitingForMove===!0){this.env.model.getters.isGridSelectionActive()?this.startMovement(e):this._selectElement(t,!1);return}this.composerFocusStore.activeComposer.editionMode===`editing`&&this.env.model.selection.getBackToDefault(),this.startSelection(e,t)}}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;let t=this._getDimensionsInViewport(this._getSelectedZoneStart()),n=this._getDimensionsInViewport(this._getSelectedZoneEnd()),r=t.start;this.state.draggerLinePosition=r,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=r,this.state.draggerShadowThickness=n.end-t.start,zN(this.env,(e,n)=>{let r=this._getType()===`COL`?e:n;if(r>=0){let e=this._getDimensionsInViewport(r);r<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=e.start,this.state.draggerShadowPosition=e.start,this.state.base=r,this.state.position=`before`):this._getSelectedZoneEnd()<r?(this.state.draggerLinePosition=e.end,this.state.draggerShadowPosition=e.end-this.state.draggerShadowThickness,this.state.base=r,this.state.position=`after`):(this.state.draggerLinePosition=t.start,this.state.draggerShadowPosition=t.start,this.state.base=this._getSelectedZoneStart())}},()=>{this.state.isMoving=!1,this.state.base!==this._getSelectedZoneStart()&&this._moveElements(),this._computeGrabDisplay(e)})}startSelection(e,t){this.state.isSelecting=!0,e.shiftKey?this._increaseSelection(t):this._selectElement(t,nE(e)),this.lastSelectedElementIndex=t,zN(this.env,(e,t)=>{let n=this._getType()===`COL`?e:t;n!==this.lastSelectedElementIndex&&n!==-1&&(this._increaseSelection(n),this.lastSelectedElementIndex=n)},()=>{this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this._computeGrabDisplay(e)})}onMouseUp(e){this.lastSelectedElementIndex=null}onContextMenu(e){e.preventDefault();let t=this._getElementIndex(this._getEvOffset(e));if(t<0)return;this._getActiveElements().has(t)||this._selectElement(t,!1);let n=this._getType();this.props.onOpenContextMenu(n,e.clientX,e.clientY)}};H`
1659
+ `;function QI(e,n,r){let i={col:void 0,row:void 0},{Date:a}=window,o,s,c=0;function l(){return o===void 0||s===void 0?{col:-1,row:-1}:{col:e.model.getters.getColIndex(o),row:e.model.getters.getRowIndex(s)}}let{pause:u,resume:d}=rk(f,200);function f(){let{col:e,row:t}=l(),n=a.now()-c;if(n>300&&(e!==i.col||t!==i.row)&&_(void 0,void 0),n>300){if(e<0||t<0)return;_(e,t)}}function p(e){n.el===e.target&&(o=e.offsetX,s=e.offsetY,c=a.now())}function m(){let{col:e,row:t}=l();(e!==i.col||t!==i.row)&&_(void 0,void 0)}function h(e){let t=e.offsetX,r=e.offsetY,i=XT(n.el);return r<0||r>i.height||t<0||t>i.width?p(e):u()}_P(n,`pointermove`,p),_P(n,`mouseleave`,h),_P(n,`mouseenter`,d),_P(n,`pointerdown`,m),(0,t.useExternalListener)(window,`click`,g);function g(e){let t=e.target;n.el.contains(t)||_(void 0,void 0)}function _(e,t){(e!==i.col||t!==i.row)&&(i.col=e,i.row=t,r({col:e,row:t}))}return i}var $I=class extends t.Component{static template=`o-spreadsheet-GridOverlay`;static props={onCellHovered:{type:Function,optional:!0},onCellDoubleClicked:{type:Function,optional:!0},onCellClicked:{type:Function,optional:!0},onCellRightClicked:{type:Function,optional:!0},onGridResized:{type:Function,optional:!0},onGridMoved:Function,gridOverlayDimensions:String};static components={FiguresContainer:KI,DataValidationOverlay:jI,GridAddRowsFooter:YI,FilterIconsOverlay:JI};static defaultProps={onCellHovered:()=>{},onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{}};gridOverlay=(0,t.useRef)(`gridOverlay`);gridOverlayRect=iE(this.gridOverlay);cellPopovers;paintFormatStore;setup(){QI(this.env,this.gridOverlay,this.props.onCellHovered);let e=new ResizeObserver(()=>{let e=this.gridOverlayEl.getBoundingClientRect();this.props.onGridResized({x:e.left,y:e.top,height:this.gridOverlayEl.clientHeight,width:this.gridOverlayEl.clientWidth})});(0,t.onMounted)(()=>{e.observe(this.gridOverlayEl)}),(0,t.onWillUnmount)(()=>{e.disconnect()}),this.cellPopovers=V(GO),this.paintFormatStore=V(ZI)}get gridOverlayEl(){if(!this.gridOverlay.el)throw Error(`GridOverlay el is not defined.`);return this.gridOverlay.el}get style(){return this.props.gridOverlayDimensions}get isPaintingFormat(){return this.paintFormatStore.isActive}onMouseDown(e){if(e.button>0)return;e.target===this.gridOverlay.el&&this.cellPopovers.isOpen&&this.cellPopovers.close();let[t,n]=this.getCartesianCoordinates(e);this.props.onCellClicked(t,n,{expandZone:e.shiftKey,addZone:nE(e)})}onDoubleClick(e){let[t,n]=this.getCartesianCoordinates(e);this.props.onCellDoubleClicked(t,n)}onContextMenu(e){let[t,n]=this.getCartesianCoordinates(e);this.props.onCellRightClicked(t,n,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){let t=e.clientX-this.gridOverlayRect.x,n=e.clientY-this.gridOverlayRect.y;return[this.env.model.getters.getColIndex(t),this.env.model.getters.getRowIndex(n)]}},eL=class extends t.Component{static template=`o-spreadsheet-GridPopover`;static props={onClosePopover:Function,onMouseWheel:Function,gridRect:Object};static components={Popover:lk};cellPopovers;zIndex=19;setup(){this.cellPopovers=V(GO)}get cellPopover(){let e=this.cellPopovers.cellPopover;if(!e.isOpen)return{isOpen:!1};let t=e.anchorRect;return{...e,anchorRect:{...t,x:t.x+this.props.gridRect.x,y:t.y+this.props.gridRect.y}}}},tL=class extends t.Component{static props={onOpenContextMenu:Function};composerFocusStore;PADDING=0;MAX_SIZE_MARGIN=0;MIN_ELEMENT_SIZE=0;lastSelectedElementIndex=null;state=(0,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`});setup(){this.composerFocusStore=V(_d)}_computeHandleDisplay(e){let t=this._getEvOffset(e),n=this._getElementIndex(t);if(n<0)return;let r=this._getDimensionsInViewport(n);t-r.start<this.PADDING&&n!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=r.start,this.state.activeElement=this._getPreviousVisibleElement(n)):r.end-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=r.end,this.state.activeElement=n):this.state.resizerIsActive=!1}_computeGrabDisplay(e){let t=this._getElementIndex(this._getEvOffset(e)),n=this._getActiveElements(),r=this._getSelectedZoneStart(),i=this._getSelectedZoneEnd();if(n.has(r)&&r<=t&&t<=i){this.state.waitingForMove=!0;return}this.state.waitingForMove=!1}onMouseMove(e){this.env.model.getters.isReadonly()||this.state.isResizing||this.state.isMoving||this.state.isSelecting||(this._computeHandleDisplay(e),this._computeGrabDisplay(e))}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(e){this._fitElementSize(this.state.activeElement),this.state.isResizing=!1,this._computeHandleDisplay(e),this._computeGrabDisplay(e)}onMouseDown(e){this.state.isResizing=!0,this.state.delta=0;let t=this._getClientPosition(e),n=this.state.draggerLinePosition,r=this._getElementSize(this.state.activeElement),i=n-r+this.MIN_ELEMENT_SIZE,a=this._getMaxSize();RN(e=>{this.state.delta=this._getClientPosition(e)-t,this.state.draggerLinePosition=n+this.state.delta,this.state.draggerLinePosition<i&&(this.state.draggerLinePosition=i,this.state.delta=this.MIN_ELEMENT_SIZE-r),this.state.draggerLinePosition>a&&(this.state.draggerLinePosition=a,this.state.delta=a-n)},e=>{this.state.isResizing=!1,this.state.delta!==0&&this._updateSize()})}select(e){if(e.button>0)return;let t=this._getElementIndex(this._getEvOffset(e));if(!(t<0)){if(this.env.model.getters.isReadonly()){this._selectElement(t,!1);return}if(this.state.waitingForMove===!0){this.env.model.getters.isGridSelectionActive()?this.startMovement(e):this._selectElement(t,!1);return}this.composerFocusStore.activeComposer.editionMode===`editing`&&this.env.model.selection.getBackToDefault(),this.startSelection(e,t)}}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;let t=this._getDimensionsInViewport(this._getSelectedZoneStart()),n=this._getDimensionsInViewport(this._getSelectedZoneEnd()),r=t.start;this.state.draggerLinePosition=r,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=r,this.state.draggerShadowThickness=n.end-t.start,zN(this.env,(e,n)=>{let r=this._getType()===`COL`?e:n;if(r>=0){let e=this._getDimensionsInViewport(r);r<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=e.start,this.state.draggerShadowPosition=e.start,this.state.base=r,this.state.position=`before`):this._getSelectedZoneEnd()<r?(this.state.draggerLinePosition=e.end,this.state.draggerShadowPosition=e.end-this.state.draggerShadowThickness,this.state.base=r,this.state.position=`after`):(this.state.draggerLinePosition=t.start,this.state.draggerShadowPosition=t.start,this.state.base=this._getSelectedZoneStart())}},()=>{this.state.isMoving=!1,this.state.base!==this._getSelectedZoneStart()&&this._moveElements(),this._computeGrabDisplay(e)})}startSelection(e,t){this.state.isSelecting=!0,e.shiftKey?this._increaseSelection(t):this._selectElement(t,nE(e)),this.lastSelectedElementIndex=t,zN(this.env,(e,t)=>{let n=this._getType()===`COL`?e:t;n!==this.lastSelectedElementIndex&&n!==-1&&(this._increaseSelection(n),this.lastSelectedElementIndex=n)},()=>{this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this._computeGrabDisplay(e)})}onMouseUp(e){this.lastSelectedElementIndex=null}onContextMenu(e){e.preventDefault();let t=this._getElementIndex(this._getEvOffset(e));if(t<0)return;this._getActiveElements().has(t)||this._selectElement(t,!1);let n=this._getType();this.props.onOpenContextMenu(n,e.clientX,e.clientY)}};H`
1660
1660
  .o-col-resizer {
1661
1661
  position: absolute;
1662
1662
  top: 0;
@@ -1706,7 +1706,7 @@ stores.inject(MyMetaStore, storeInstance);
1706
1706
  background-color: lightgrey;
1707
1707
  }
1708
1708
  }
1709
- `;var rL=class extends nL{static props={onOpenContextMenu:Function};static template=`o-spreadsheet-ColResizer`;colResizerRef;setup(){super.setup(),this.colResizerRef=(0,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(){let e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),n=this.env.model.getters.getActiveCols();this.env.model.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:`COL`,sheetId:this.sheetId,elements:n.has(e)?[...n]:[e],size:t})}_moveElements(){let e=[],t=this._getSelectedZoneStart(),n=this._getSelectedZoneEnd();for(let r=t;r<=n;r++)e.push(r);let r=this.env.model.dispatch(`MOVE_COLUMNS_ROWS`,{sheetId:this.sheetId,dimension:`COL`,base:this.state.base,elements:e,position:this.state.position});!r.isSuccessful&&r.reasons.includes(`WillRemoveExistingMerge`)&&this.env.raiseError(sg)}_selectElement(e,t){this.env.model.selection.selectColumn(e,t?`newAnchor`:`overrideSelection`)}_increaseSelection(e){this.env.model.selection.selectColumn(e,`updateAnchor`)}_fitElementSize(e){let 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){let t=this.sheetId,n;for(n=e-1;n>=0&&this.env.model.getters.isColHidden(t,n);n--);return n}unhide(e){this.env.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:this.sheetId,elements:e,dimension:`COL`})}getUnhideButtonStyle(e){return U({left:this._getDimensionsInViewport(e).start+`px`})}};H`
1709
+ `;var nL=class extends tL{static props={onOpenContextMenu:Function};static template=`o-spreadsheet-ColResizer`;colResizerRef;setup(){super.setup(),this.colResizerRef=(0,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(){let e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),n=this.env.model.getters.getActiveCols();this.env.model.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:`COL`,sheetId:this.sheetId,elements:n.has(e)?[...n]:[e],size:t})}_moveElements(){let e=[],t=this._getSelectedZoneStart(),n=this._getSelectedZoneEnd();for(let r=t;r<=n;r++)e.push(r);let r=this.env.model.dispatch(`MOVE_COLUMNS_ROWS`,{sheetId:this.sheetId,dimension:`COL`,base:this.state.base,elements:e,position:this.state.position});!r.isSuccessful&&r.reasons.includes(`WillRemoveExistingMerge`)&&this.env.raiseError(sg)}_selectElement(e,t){this.env.model.selection.selectColumn(e,t?`newAnchor`:`overrideSelection`)}_increaseSelection(e){this.env.model.selection.selectColumn(e,`updateAnchor`)}_fitElementSize(e){let 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){let t=this.sheetId,n;for(n=e-1;n>=0&&this.env.model.getters.isColHidden(t,n);n--);return n}unhide(e){this.env.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:this.sheetId,elements:e,dimension:`COL`})}getUnhideButtonStyle(e){return U({left:this._getDimensionsInViewport(e).start+`px`})}};H`
1710
1710
  .o-row-resizer {
1711
1711
  position: absolute;
1712
1712
  top: ${26}px;
@@ -1756,7 +1756,7 @@ stores.inject(MyMetaStore, storeInstance);
1756
1756
  background-color: lightgrey;
1757
1757
  }
1758
1758
  }
1759
- `;var iL=class extends nL{static props={onOpenContextMenu:Function};static template=`o-spreadsheet-RowResizer`;setup(){super.setup(),this.rowResizerRef=(0,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(){let e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),n=this.env.model.getters.getActiveRows();this.env.model.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:`ROW`,sheetId:this.sheetId,elements:n.has(e)?[...n]:[e],size:t})}_moveElements(){let e=[],t=this._getSelectedZoneStart(),n=this._getSelectedZoneEnd();for(let r=t;r<=n;r++)e.push(r);let r=this.env.model.dispatch(`MOVE_COLUMNS_ROWS`,{sheetId:this.sheetId,dimension:`ROW`,base:this.state.base,elements:e,position:this.state.position});r.isSuccessful||(r.reasons.includes(`WillRemoveExistingMerge`)?this.env.raiseError(sg):r.reasons.includes(`CannotMoveTableHeader`)&&this.env.raiseError(cg))}_selectElement(e,t){this.env.model.selection.selectRow(e,t?`newAnchor`:`overrideSelection`)}_increaseSelection(e){this.env.model.selection.selectRow(e,`updateAnchor`)}_fitElementSize(e){let 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){let t=this.sheetId,n;for(n=e-1;n>=0&&this.env.model.getters.isRowHidden(t,n);n--);return n}unhide(e){this.env.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:this.sheetId,dimension:`ROW`,elements:e})}getUnhideButtonStyle(e){return U({top:this._getDimensionsInViewport(e).start+`px`})}};H`
1759
+ `;var rL=class extends tL{static props={onOpenContextMenu:Function};static template=`o-spreadsheet-RowResizer`;setup(){super.setup(),this.rowResizerRef=(0,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(){let e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),n=this.env.model.getters.getActiveRows();this.env.model.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:`ROW`,sheetId:this.sheetId,elements:n.has(e)?[...n]:[e],size:t})}_moveElements(){let e=[],t=this._getSelectedZoneStart(),n=this._getSelectedZoneEnd();for(let r=t;r<=n;r++)e.push(r);let r=this.env.model.dispatch(`MOVE_COLUMNS_ROWS`,{sheetId:this.sheetId,dimension:`ROW`,base:this.state.base,elements:e,position:this.state.position});r.isSuccessful||(r.reasons.includes(`WillRemoveExistingMerge`)?this.env.raiseError(sg):r.reasons.includes(`CannotMoveTableHeader`)&&this.env.raiseError(cg))}_selectElement(e,t){this.env.model.selection.selectRow(e,t?`newAnchor`:`overrideSelection`)}_increaseSelection(e){this.env.model.selection.selectRow(e,`updateAnchor`)}_fitElementSize(e){let 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){let t=this.sheetId,n;for(n=e-1;n>=0&&this.env.model.getters.isRowHidden(t,n);n--);return n}unhide(e){this.env.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:this.sheetId,dimension:`ROW`,elements:e})}getUnhideButtonStyle(e){return U({top:this._getDimensionsInViewport(e).start+`px`})}};H`
1760
1760
  .o-overlay {
1761
1761
  .all {
1762
1762
  position: absolute;
@@ -1767,7 +1767,7 @@ stores.inject(MyMetaStore, storeInstance);
1767
1767
  height: ${26}px;
1768
1768
  }
1769
1769
  }
1770
- `;var aL=class extends t.Component{static props={onOpenContextMenu:Function};static template=`o-spreadsheet-HeadersOverlay`;static components={ColResizer:rL,RowResizer:iL};selectAll(){this.env.model.selection.selectAll()}},oL=class{getters;renderer;constructor(e){this.getters=e(pd).getters,this.renderer=e(md),this.renderer.register(this)}get renderingLayers(){return[`Background`,`Headers`]}getHeaderOffset(e,t,n){let r=this.getters.getColRowOffsetInViewport(e,t,n);return this.getters.isDashboard()||(r+=e===`ROW`?26:48),r}drawLayer(e,t){switch(t){case`Background`:this.drawGlobalBackground(e);for(let{zone:t,rect:n}of this.getters.getAllActiveViewportsZonesAndRect()){let{ctx:r}=e;r.save(),r.beginPath(),r.rect(n.x,n.y,n.width,n.height),r.clip();let i=this.getGridBoxes(t);this.drawBackground(e,i),this.drawOverflowingCellBackground(e,i),this.drawCellBackground(e,i),this.drawBorders(e,i),this.drawTexts(e,i),this.drawIcon(e,i),r.restore()}this.drawFrozenPanes(e);break;case`Headers`:this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e));break}}drawGlobalBackground(e){let{ctx:t}=e,{width:n,height:r}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle=`#ffffff`,t.fillRect(0,0,n+g,r+g)}drawBackground(e,t){let{ctx:n,thinLineWidth:r}=e,i=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),a=i?.1*r:0;if(i)for(let e of t)n.strokeStyle=`#E2E3E3`,n.lineWidth=r,n.strokeRect(e.x+a,e.y+a,e.width-2*a,e.height-2*a)}drawCellBackground(e,t){let{ctx:n}=e;for(let e of t){let t=e.style;if(t.fillColor&&t.fillColor!==`#ffffff`&&(n.fillStyle=t.fillColor||`#ffffff`,n.fillRect(e.x,e.y,e.width,e.height)),e.dataBarFill){n.fillStyle=e.dataBarFill.color;let t=e.dataBarFill.percentage,r=e.width*(t/100);n.fillRect(e.x,e.y,r,e.height)}e.isError&&(n.fillStyle=`red`,n.beginPath(),n.moveTo(e.x+e.width-5,e.y),n.lineTo(e.x+e.width,e.y),n.lineTo(e.x+e.width,e.y+5),n.fill())}}drawOverflowingCellBackground(e,t){let{ctx:n,thinLineWidth:r}=e;for(let e of t)if(e.content&&e.isOverflow){let t=e.content.align||`left`,i,a,o=e.y+r/2,s=e.height-r,c=Math.min(e.clipRect?.width||1/0,e.content.width);t===`left`?(i=e.x+r/2,a=c-2*r):t===`right`?(i=e.x+e.width-r/2,a=-c+2*r):(i=(e.clipRect?.x||e.x+e.width/2-e.content.width/2)+r/2,a=c-2*r),n.fillStyle=`#ffffff`,n.fillRect(i,o,a,s)}}drawBorders(e,t){let{ctx:n}=e;for(let e of t){let t=e.border;if(t){let{x:n,y:i,width:a,height:o}=e;t.left&&r(t.left,n,i,n,i+o),t.top&&r(t.top,n,i,n+a,i),t.right&&r(t.right,n+a,i,n+a,i+o),t.bottom&&r(t.bottom,n,i+o,n+a,i+o)}}function r({style:e,color:t},r,i,a,o){switch(n.strokeStyle=t,e){case`medium`:n.lineWidth=2,r+=i===o?-.5:.5,a+=i===o?1.5:.5,i+=r===a?-.5:.5,o+=r===a?1.5:.5;break;case`thick`:n.lineWidth=3,i===o&&(r--,a++),r===a&&(i--,o++);break;case`dashed`:n.lineWidth=1,n.setLineDash([1,3]);break;case`dotted`:n.lineWidth=1,i===o&&(r+=.5,a+=.5),r===a&&(i+=.5,o+=.5),n.setLineDash([1,1]);break;default:n.lineWidth=1;break}n.beginPath(),n.moveTo(r,i),n.lineTo(a,o),n.stroke(),n.lineWidth=1,n.setLineDash([])}}drawTexts(e,t){let{ctx:n}=e;n.textBaseline=`top`;let r;for(let e of t)if(e.content){let t=e.style||{},i=e.content.align||`left`,a=pc(t);a!==r&&(r=a,n.font=a),n.fillStyle=t.textColor||`#000`;let o=e.x;if(i===`left`?o+=4+(e.image?e.image.size+4:0):i===`right`?o+=e.width-4-(e.hasIcon?19:0):o+=e.width/2,n.textAlign=i,e.clipRect){n.save(),n.beginPath();let{x:t,y:r,width:i,height:a}=e.clipRect;n.rect(t,r,i,a),n.clip()}let s=mc(t),c=e.content.textLines.length,l=this.computeTextYCoordinate(e,s,c);for(let r of e.content.textLines)Cc(n,r,{x:Math.round(o),y:Math.round(l)},t.underline,t.strikethrough),l+=4+s;e.clipRect&&n.restore()}}drawIcon(e,t){let{ctx:n}=e;for(let e of t)if(e.image){let t=e.image.image;if(e.image.clipIcon){n.save(),n.beginPath();let{x:t,y:r,width:i,height:a}=e.image.clipIcon;n.rect(t,r,i,a),n.clip()}let r=e.image.size,i=this.computeTextYCoordinate(e,r);n.drawImage(t,e.x+4,i,r,r),e.image.clipIcon&&n.restore()}}computeTextYCoordinate(e,t,n=1){let r=e.y+1,i=nc(t,n),a=e.height>i+8,o=e.verticalAlign||Ie;if(a){if(o===`middle`)return r+(e.height-i)/2;if(o===`bottom`)return r+e.height-i-4}return r+4}drawHeaders(e){let{ctx:t,thinLineWidth:n}=e,r=this.getters.getSheetViewVisibleCols(),i=r[0],a=this.getters.getSheetViewVisibleRows(),o=a[0],{width:s,height:c}=this.getters.getSheetViewDimensionWithHeaders(),l=this.getters.getSelectedZones(),u=Or(l),d=kr(l),f=this.getters.getActiveSheetId(),p=this.getters.getNumberCols(f),m=this.getters.getNumberRows(f),h=this.getters.getActiveCols(),g=this.getters.getActiveRows();t.font=`400 11px ${ze}`,t.textAlign=`center`,t.textBaseline=`middle`,t.lineWidth=n,t.strokeStyle=`#333`;for(let e of r){let n={left:e,right:e,top:0,bottom:m-1},{x:r,width:i}=this.getters.getVisibleRect(n),a=h.has(e),o=u.has(e);a?t.fillStyle=ne:o?t.fillStyle=te:t.fillStyle=ee,t.fillRect(r,0,i,26)}for(let e of a){let n={top:e,bottom:e,left:0,right:p-1},{y:r,height:i}=this.getters.getVisibleRect(n),a=g.has(e),o=d.has(e);a?t.fillStyle=ne:o?t.fillStyle=te:t.fillStyle=ee,t.fillRect(0,r,48,i)}t.beginPath(),t.moveTo(48,0),t.lineTo(48,c),t.moveTo(0,26),t.lineTo(s,26),t.strokeStyle=`#C0C0C0`,t.stroke(),t.beginPath();for(let e of r){let n=this.getters.getColSize(f,e),r=Tn(e);t.fillStyle=h.has(e)?`#fff`:re;let a=this.getHeaderOffset(`COL`,i,e);t.fillText(r,a+n/2,26/2),t.moveTo(a+n,0),t.lineTo(a+n,26)}for(let e of a){let n=this.getters.getRowSize(f,e);t.fillStyle=g.has(e)?`#fff`:re;let r=this.getHeaderOffset(`ROW`,o,e);t.fillText(String(e+1),48/2,r+n/2),t.moveTo(0,r+n),t.lineTo(48,r+n)}t.stroke()}drawFrozenPanesHeaders(e){let{ctx:t,thinLineWidth:n}=e,{x:r,y:i}=this.getters.getMainViewportCoordinates(),a=this.getters.isDashboard()?0:48,o=this.getters.isDashboard()?0:26;t.lineWidth=6*n,t.strokeStyle=he,t.beginPath(),r&&(t.moveTo(a+r,0),t.lineTo(a+r,o)),i&&(t.moveTo(0,o+i),t.lineTo(a,o+i)),t.stroke()}drawFrozenPanes(e){let{ctx:t,thinLineWidth:n}=e,{x:r,y:i}=this.getters.getMainViewportCoordinates(),a=this.getters.getSheetViewVisibleCols(),o=a[0],s=a[a.length-1],c=this.getters.getSheetViewVisibleRows(),l={left:o,right:s,top:c[0],bottom:c[c.length-1]},u=this.getters.getVisibleRect(l),d=this.getters.isDashboard()?0:48,f=this.getters.isDashboard()?0:26;t.lineWidth=6*n,t.strokeStyle=`#DADFE8`,t.beginPath(),r&&(t.moveTo(d+r,f),t.lineTo(d+r,u.height+f)),i&&(t.moveTo(d,f+i),t.lineTo(u.width+d,f+i)),t.stroke()}findNextEmptyCol(e,t,n){let r=this.getters.getActiveSheetId(),i=e;for(;i<t;){let e={sheetId:r,col:i+1,row:n},t=this.getters.getEvaluatedCell(e),a=this.getters.getCellComputedBorder(e),o=this.getters.doesCellHaveGridIcon(e),s=this.getters.isCellValidCheckbox(e);if(t.type!==`empty`||this.getters.isInMerge(e)||a?.left||o||s)return i;i++}return i}findPreviousEmptyCol(e,t,n){let r=this.getters.getActiveSheetId(),i=e;for(;i>t;){let e={sheetId:r,col:i-1,row:n},t=this.getters.getEvaluatedCell(e),a=this.getters.getCellComputedBorder(e),o=this.getters.doesCellHaveGridIcon(e),s=this.getters.isCellValidCheckbox(e);if(t.type!==`empty`||this.getters.isInMerge(e)||a?.right||o||s)return i;i--}return i}computeCellAlignment(e,t){if(this.getters.getCell(e)?.isFormula&&this.getters.shouldShowFormulas())return`left`;let{align:n}=this.getters.getCellStyle(e),r=this.getters.getEvaluatedCell(e);return t&&r.type===`number`?n===`center`?n:`left`:n||r.defaultAlign}createZoneBox(e,t,n){let{left:r,right:i}=n,a=t.left,o=t.top,s={sheetId:e,col:a,row:o},c=this.getters.getEvaluatedCell(s),l=this.getters.shouldShowFormulas(),{x:u,y:d,width:f,height:p}=this.getters.getRect(t),{verticalAlign:m}=this.getters.getCellStyle(s),h={x:u,y:d,width:f,height:p,border:this.getters.getCellComputedBorder(s)||void 0,style:this.getters.getCellComputedStyle(s),dataBarFill:this.getters.getConditionalDataBar(s),verticalAlign:m,isError:c.type===`error`&&!!c.message||this.getters.isDataValidationInvalid(s)},g=this.getters.getCellIconSrc(s),_=mc(h.style),v=g?4+_:0;if(g){let e=sL(g);h.image={type:`icon`,size:_,clipIcon:{x:h.x,y:h.y,width:Math.min(v,f),height:p},image:e}}if(c.type===`empty`||this.getters.isCellValidCheckbox(s))return h;h.hasIcon=this.getters.doesCellHaveGridIcon(s);let ee=h.hasIcon?19:0,te=this.getters.getCellComputedStyle(s),ne=te.wrapping||`overflow`,re=ne===`wrap`&&!l,ie=f-8,ae=te.align?0:ie,oe=this.getters.getCellMultiLineText(s,{maxWidth:ie,formatWidth:ae,wrapText:re}),se=Math.max(...oe.map(e=>this.getters.getTextWidth(e,te)+4)),ce=v+se+ee,le=this.computeCellAlignment(s,ce>f);h.content={textLines:oe,width:ne===`overflow`?se:f,align:le};let ue=ce>f||_>p;if(g||h.hasIcon)h.clipRect={x:h.x+v,y:h.y,width:Math.max(0,f-v-ee),height:p};else if(ue&&ne===`overflow`){let e,n;switch(this.getters.isInMerge(s)?(e=this.getters.getMerge(s).right,n=a):(e=this.findNextEmptyCol(a,i,o),n=this.findPreviousEmptyCol(a,r,o),h.isOverflow=!0),le){case`left`:{let n=D({col:e,row:o}),{x:r,y:i,width:a,height:s}=this.getters.getVisibleRect(or(t,n));(a<ce||_>s||oe.length>1)&&(h.clipRect={x:r,y:i,width:a,height:s});break}case`right`:{let e=D({col:n,row:o}),{x:r,y:i,width:a,height:s}=this.getters.getVisibleRect(or(t,e));(a<ce||_>s||oe.length>1)&&(h.clipRect={x:r,y:i,width:a,height:s});break}case`center`:{let r={...t,left:n,right:e},{x:i,y:a,height:o,width:s}=this.getters.getVisibleRect(r),c=ce/2,l=h.x+h.width/2;if(i+s<l+c||i>l-c||_>o||oe.length>1){let e=i>l-c?i:l-c;h.clipRect={x:e,y:a,width:i+s-e,height:o}}break}}}else (ne===`clip`||ne===`wrap`||oe.length>1)&&(h.clipRect={x:h.x,y:h.y,width:f,height:p});return h}getGridBoxes(e){let t=[],n=this.getters.getSheetViewVisibleCols().filter(t=>t>=e.left&&t<=e.right),r=n[0],i=n[n.length-1],a=this.getters.getSheetViewVisibleRows().filter(t=>t>=e.top&&t<=e.bottom),o={left:r,right:i,top:a[0],bottom:a[a.length-1]},s=this.getters.getActiveSheetId();for(let e of a)for(let r of n){let n={sheetId:s,col:r,row:e};this.getters.isInMerge(n)||t.push(this.createZoneBox(s,D(n),o))}for(let e of this.getters.getMerges(s))if(!this.getters.isMergeHidden(s,e)&&ur(e,o)){let n=this.createZoneBox(s,e,o),r=this.getters.getCellComputedBorder({sheetId:s,col:e.right,row:e.bottom});n.border={...n.border,bottom:r?r.bottom:void 0,right:r?r.right:void 0},n.isMerge=!0,t.push(n)}return t}};let sL=Rt(function(e){let t=new Image;return t.src=e,t});function cL(e,n,r){let i=(0,t.useRef)(e);(0,t.useEffect)(o);let a=V(md);V(oL);function o(){let e=i.el,t=window.devicePixelRatio||1,o=e.getContext(`2d`,{alpha:!1}),s={ctx:o,dpr:t,thinLineWidth:.4*t},{width:c,height:l}=r();if(e.style.width=`${c}px`,e.style.height=`${l}px`,e.width=c*t,e.height=l*t,e.setAttribute(`style`,`width:${c}px;height:${l}px;`),!(c===0||l===0)){o.translate(-g,-g),o.scale(t,t);for(let e of $i())n.drawLayer(s,e),a.drawLayer(s,e)}}}let lL=.95;function uL(e,t,n){let r=0,i=0,a=0,o=0,s=!1,c=0,l=null;_P(e,`touchstart`,u,{capture:!1}),_P(e,`touchmove`,d,{capture:!1}),_P(e,`touchend`,f,{capture:!1});function u(e){s=!0,{clientX:r,clientY:i}=e.touches[0],a=0,o=0}function d(e){if(!s)return;l&&=(clearTimeout(l),null);let u=Date.now(),{clientX:d,clientY:f}=e.touches[0],p=r-d,m=i-f,h=u-c;h&&(a=p/h,o=m/h,r=d,i=f,c=u,n()&&(e.cancelable&&e.preventDefault(),e.stopPropagation()),l=setTimeout(()=>{a=0,o=0},100),t(p*1,m*1))}function f(e){s=!1,r=i=0,l&&clearTimeout(l),a*=1.2,o*=1.2,requestAnimationFrame(p)}function p(){if(Math.abs(a)<.05&&(a=0),Math.abs(o)<.05&&(o=0),!a&&!o)return;let e=Date.now(),n=Math.abs(e-c),r=a*n,i=o*n;t(r*1,i*1),c=e,a*=lL,o*=lL,requestAnimationFrame(p)}}function dL(e){function t(e,t){return e*(t===0?1:23)}return n=>{e(t(n.shiftKey&&!tE()?n.deltaY:n.deltaX,n.deltaMode),t(n.shiftKey&&!tE()?n.deltaX:n.deltaY,n.deltaMode))}}H`
1770
+ `;var iL=class extends t.Component{static props={onOpenContextMenu:Function};static template=`o-spreadsheet-HeadersOverlay`;static components={ColResizer:nL,RowResizer:rL};selectAll(){this.env.model.selection.selectAll()}},aL=class{getters;renderer;constructor(e){this.getters=e(pd).getters,this.renderer=e(md),this.renderer.register(this)}get renderingLayers(){return[`Background`,`Headers`]}getHeaderOffset(e,t,n){let r=this.getters.getColRowOffsetInViewport(e,t,n);return this.getters.isDashboard()||(r+=e===`ROW`?26:48),r}drawLayer(e,t){switch(t){case`Background`:this.drawGlobalBackground(e);for(let{zone:t,rect:n}of this.getters.getAllActiveViewportsZonesAndRect()){let{ctx:r}=e;r.save(),r.beginPath(),r.rect(n.x,n.y,n.width,n.height),r.clip();let i=this.getGridBoxes(t);this.drawBackground(e,i),this.drawOverflowingCellBackground(e,i),this.drawCellBackground(e,i),this.drawBorders(e,i),this.drawTexts(e,i),this.drawIcon(e,i),r.restore()}this.drawFrozenPanes(e);break;case`Headers`:this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e));break}}drawGlobalBackground(e){let{ctx:t}=e,{width:n,height:r}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle=`#ffffff`,t.fillRect(0,0,n+g,r+g)}drawBackground(e,t){let{ctx:n,thinLineWidth:r}=e,i=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),a=i?.1*r:0;if(i)for(let e of t)n.strokeStyle=`#E2E3E3`,n.lineWidth=r,n.strokeRect(e.x+a,e.y+a,e.width-2*a,e.height-2*a)}drawCellBackground(e,t){let{ctx:n}=e;for(let e of t){let t=e.style;if(t.fillColor&&t.fillColor!==`#ffffff`&&(n.fillStyle=t.fillColor||`#ffffff`,n.fillRect(e.x,e.y,e.width,e.height)),e.dataBarFill){n.fillStyle=e.dataBarFill.color;let t=e.dataBarFill.percentage,r=e.width*(t/100);n.fillRect(e.x,e.y,r,e.height)}e.isError&&(n.fillStyle=`red`,n.beginPath(),n.moveTo(e.x+e.width-5,e.y),n.lineTo(e.x+e.width,e.y),n.lineTo(e.x+e.width,e.y+5),n.fill())}}drawOverflowingCellBackground(e,t){let{ctx:n,thinLineWidth:r}=e;for(let e of t)if(e.content&&e.isOverflow){let t=e.content.align||`left`,i,a,o=e.y+r/2,s=e.height-r,c=Math.min(e.clipRect?.width||1/0,e.content.width);t===`left`?(i=e.x+r/2,a=c-2*r):t===`right`?(i=e.x+e.width-r/2,a=-c+2*r):(i=(e.clipRect?.x||e.x+e.width/2-e.content.width/2)+r/2,a=c-2*r),n.fillStyle=`#ffffff`,n.fillRect(i,o,a,s)}}drawBorders(e,t){let{ctx:n}=e;for(let e of t){let t=e.border;if(t){let{x:n,y:i,width:a,height:o}=e;t.left&&r(t.left,n,i,n,i+o),t.top&&r(t.top,n,i,n+a,i),t.right&&r(t.right,n+a,i,n+a,i+o),t.bottom&&r(t.bottom,n,i+o,n+a,i+o)}}function r({style:e,color:t},r,i,a,o){switch(n.strokeStyle=t,e){case`medium`:n.lineWidth=2,r+=i===o?-.5:.5,a+=i===o?1.5:.5,i+=r===a?-.5:.5,o+=r===a?1.5:.5;break;case`thick`:n.lineWidth=3,i===o&&(r--,a++),r===a&&(i--,o++);break;case`dashed`:n.lineWidth=1,n.setLineDash([1,3]);break;case`dotted`:n.lineWidth=1,i===o&&(r+=.5,a+=.5),r===a&&(i+=.5,o+=.5),n.setLineDash([1,1]);break;default:n.lineWidth=1;break}n.beginPath(),n.moveTo(r,i),n.lineTo(a,o),n.stroke(),n.lineWidth=1,n.setLineDash([])}}drawTexts(e,t){let{ctx:n}=e;n.textBaseline=`top`;let r;for(let e of t)if(e.content){let t=e.style||{},i=e.content.align||`left`,a=pc(t);a!==r&&(r=a,n.font=a),n.fillStyle=t.textColor||`#000`;let o=e.x;if(i===`left`?o+=4+(e.image?e.image.size+4:0):i===`right`?o+=e.width-4-(e.hasIcon?19:0):o+=e.width/2,n.textAlign=i,e.clipRect){n.save(),n.beginPath();let{x:t,y:r,width:i,height:a}=e.clipRect;n.rect(t,r,i,a),n.clip()}let s=mc(t),c=e.content.textLines.length,l=this.computeTextYCoordinate(e,s,c);for(let r of e.content.textLines)Cc(n,r,{x:Math.round(o),y:Math.round(l)},t.underline,t.strikethrough),l+=4+s;e.clipRect&&n.restore()}}drawIcon(e,t){let{ctx:n}=e;for(let e of t)if(e.image){let t=e.image.image;if(e.image.clipIcon){n.save(),n.beginPath();let{x:t,y:r,width:i,height:a}=e.image.clipIcon;n.rect(t,r,i,a),n.clip()}let r=e.image.size,i=this.computeTextYCoordinate(e,r);n.drawImage(t,e.x+4,i,r,r),e.image.clipIcon&&n.restore()}}computeTextYCoordinate(e,t,n=1){let r=e.y+1,i=nc(t,n),a=e.height>i+8,o=e.verticalAlign||Ie;if(a){if(o===`middle`)return r+(e.height-i)/2;if(o===`bottom`)return r+e.height-i-4}return r+4}drawHeaders(e){let{ctx:t,thinLineWidth:n}=e,r=this.getters.getSheetViewVisibleCols(),i=r[0],a=this.getters.getSheetViewVisibleRows(),o=a[0],{width:s,height:c}=this.getters.getSheetViewDimensionWithHeaders(),l=this.getters.getSelectedZones(),u=Or(l),d=kr(l),f=this.getters.getActiveSheetId(),p=this.getters.getNumberCols(f),m=this.getters.getNumberRows(f),h=this.getters.getActiveCols(),g=this.getters.getActiveRows();t.font=`400 11px ${ze}`,t.textAlign=`center`,t.textBaseline=`middle`,t.lineWidth=n,t.strokeStyle=`#333`;for(let e of r){let n={left:e,right:e,top:0,bottom:m-1},{x:r,width:i}=this.getters.getVisibleRect(n),a=h.has(e),o=u.has(e);a?t.fillStyle=ne:o?t.fillStyle=te:t.fillStyle=ee,t.fillRect(r,0,i,26)}for(let e of a){let n={top:e,bottom:e,left:0,right:p-1},{y:r,height:i}=this.getters.getVisibleRect(n),a=g.has(e),o=d.has(e);a?t.fillStyle=ne:o?t.fillStyle=te:t.fillStyle=ee,t.fillRect(0,r,48,i)}t.beginPath(),t.moveTo(48,0),t.lineTo(48,c),t.moveTo(0,26),t.lineTo(s,26),t.strokeStyle=`#C0C0C0`,t.stroke(),t.beginPath();for(let e of r){let n=this.getters.getColSize(f,e),r=Tn(e);t.fillStyle=h.has(e)?`#fff`:re;let a=this.getHeaderOffset(`COL`,i,e);t.fillText(r,a+n/2,26/2),t.moveTo(a+n,0),t.lineTo(a+n,26)}for(let e of a){let n=this.getters.getRowSize(f,e);t.fillStyle=g.has(e)?`#fff`:re;let r=this.getHeaderOffset(`ROW`,o,e);t.fillText(String(e+1),48/2,r+n/2),t.moveTo(0,r+n),t.lineTo(48,r+n)}t.stroke()}drawFrozenPanesHeaders(e){let{ctx:t,thinLineWidth:n}=e,{x:r,y:i}=this.getters.getMainViewportCoordinates(),a=this.getters.isDashboard()?0:48,o=this.getters.isDashboard()?0:26;t.lineWidth=6*n,t.strokeStyle=he,t.beginPath(),r&&(t.moveTo(a+r,0),t.lineTo(a+r,o)),i&&(t.moveTo(0,o+i),t.lineTo(a,o+i)),t.stroke()}drawFrozenPanes(e){let{ctx:t,thinLineWidth:n}=e,{x:r,y:i}=this.getters.getMainViewportCoordinates(),a=this.getters.getSheetViewVisibleCols(),o=a[0],s=a[a.length-1],c=this.getters.getSheetViewVisibleRows(),l={left:o,right:s,top:c[0],bottom:c[c.length-1]},u=this.getters.getVisibleRect(l),d=this.getters.isDashboard()?0:48,f=this.getters.isDashboard()?0:26;t.lineWidth=6*n,t.strokeStyle=`#DADFE8`,t.beginPath(),r&&(t.moveTo(d+r,f),t.lineTo(d+r,u.height+f)),i&&(t.moveTo(d,f+i),t.lineTo(u.width+d,f+i)),t.stroke()}findNextEmptyCol(e,t,n){let r=this.getters.getActiveSheetId(),i=e;for(;i<t;){let e={sheetId:r,col:i+1,row:n},t=this.getters.getEvaluatedCell(e),a=this.getters.getCellComputedBorder(e),o=this.getters.doesCellHaveGridIcon(e),s=this.getters.isCellValidCheckbox(e);if(t.type!==`empty`||this.getters.isInMerge(e)||a?.left||o||s)return i;i++}return i}findPreviousEmptyCol(e,t,n){let r=this.getters.getActiveSheetId(),i=e;for(;i>t;){let e={sheetId:r,col:i-1,row:n},t=this.getters.getEvaluatedCell(e),a=this.getters.getCellComputedBorder(e),o=this.getters.doesCellHaveGridIcon(e),s=this.getters.isCellValidCheckbox(e);if(t.type!==`empty`||this.getters.isInMerge(e)||a?.right||o||s)return i;i--}return i}computeCellAlignment(e,t){if(this.getters.getCell(e)?.isFormula&&this.getters.shouldShowFormulas())return`left`;let{align:n}=this.getters.getCellStyle(e),r=this.getters.getEvaluatedCell(e);return t&&r.type===`number`?n===`center`?n:`left`:n||r.defaultAlign}createZoneBox(e,t,n){let{left:r,right:i}=n,a=t.left,o=t.top,s={sheetId:e,col:a,row:o},c=this.getters.getEvaluatedCell(s),l=this.getters.shouldShowFormulas(),{x:u,y:d,width:f,height:p}=this.getters.getRect(t),{verticalAlign:m}=this.getters.getCellStyle(s),h={x:u,y:d,width:f,height:p,border:this.getters.getCellComputedBorder(s)||void 0,style:this.getters.getCellComputedStyle(s),dataBarFill:this.getters.getConditionalDataBar(s),verticalAlign:m,isError:c.type===`error`&&!!c.message||this.getters.isDataValidationInvalid(s)},g=this.getters.getCellIconSrc(s),_=mc(h.style),v=g?4+_:0;if(g){let e=oL(g);h.image={type:`icon`,size:_,clipIcon:{x:h.x,y:h.y,width:Math.min(v,f),height:p},image:e}}if(c.type===`empty`||this.getters.isCellValidCheckbox(s))return h;h.hasIcon=this.getters.doesCellHaveGridIcon(s);let ee=h.hasIcon?19:0,te=this.getters.getCellComputedStyle(s),ne=te.wrapping||`overflow`,re=ne===`wrap`&&!l,ie=f-8,ae=te.align?0:ie,oe=this.getters.getCellMultiLineText(s,{maxWidth:ie,formatWidth:ae,wrapText:re}),se=Math.max(...oe.map(e=>this.getters.getTextWidth(e,te)+4)),ce=v+se+ee,le=this.computeCellAlignment(s,ce>f);h.content={textLines:oe,width:ne===`overflow`?se:f,align:le};let ue=ce>f||_>p;if(g||h.hasIcon)h.clipRect={x:h.x+v,y:h.y,width:Math.max(0,f-v-ee),height:p};else if(ue&&ne===`overflow`){let e,n;switch(this.getters.isInMerge(s)?(e=this.getters.getMerge(s).right,n=a):(e=this.findNextEmptyCol(a,i,o),n=this.findPreviousEmptyCol(a,r,o),h.isOverflow=!0),le){case`left`:{let n=D({col:e,row:o}),{x:r,y:i,width:a,height:s}=this.getters.getVisibleRect(or(t,n));(a<ce||_>s||oe.length>1)&&(h.clipRect={x:r,y:i,width:a,height:s});break}case`right`:{let e=D({col:n,row:o}),{x:r,y:i,width:a,height:s}=this.getters.getVisibleRect(or(t,e));(a<ce||_>s||oe.length>1)&&(h.clipRect={x:r,y:i,width:a,height:s});break}case`center`:{let r={...t,left:n,right:e},{x:i,y:a,height:o,width:s}=this.getters.getVisibleRect(r),c=ce/2,l=h.x+h.width/2;if(i+s<l+c||i>l-c||_>o||oe.length>1){let e=i>l-c?i:l-c;h.clipRect={x:e,y:a,width:i+s-e,height:o}}break}}}else(ne===`clip`||ne===`wrap`||oe.length>1)&&(h.clipRect={x:h.x,y:h.y,width:f,height:p});return h}getGridBoxes(e){let t=[],n=this.getters.getSheetViewVisibleCols().filter(t=>t>=e.left&&t<=e.right),r=n[0],i=n[n.length-1],a=this.getters.getSheetViewVisibleRows().filter(t=>t>=e.top&&t<=e.bottom),o={left:r,right:i,top:a[0],bottom:a[a.length-1]},s=this.getters.getActiveSheetId();for(let e of a)for(let r of n){let n={sheetId:s,col:r,row:e};this.getters.isInMerge(n)||t.push(this.createZoneBox(s,D(n),o))}for(let e of this.getters.getMerges(s))if(!this.getters.isMergeHidden(s,e)&&ur(e,o)){let n=this.createZoneBox(s,e,o),r=this.getters.getCellComputedBorder({sheetId:s,col:e.right,row:e.bottom});n.border={...n.border,bottom:r?r.bottom:void 0,right:r?r.right:void 0},n.isMerge=!0,t.push(n)}return t}};let oL=Rt(function(e){let t=new Image;return t.src=e,t});function sL(e,n,r){let i=(0,t.useRef)(e);(0,t.useEffect)(o);let a=V(md);V(aL);function o(){let e=i.el,t=window.devicePixelRatio||1,o=e.getContext(`2d`,{alpha:!1}),s={ctx:o,dpr:t,thinLineWidth:.4*t},{width:c,height:l}=r();if(e.style.width=`${c}px`,e.style.height=`${l}px`,e.width=c*t,e.height=l*t,e.setAttribute(`style`,`width:${c}px;height:${l}px;`),!(c===0||l===0)){o.translate(-.5,-.5),o.scale(t,t);for(let e of $i())n.drawLayer(s,e),a.drawLayer(s,e)}}}let cL=.95;function lL(e,t,n){let r=0,i=0,a=0,o=0,s=!1,c=0,l=null;_P(e,`touchstart`,u,{capture:!1}),_P(e,`touchmove`,d,{capture:!1}),_P(e,`touchend`,f,{capture:!1});function u(e){s=!0,{clientX:r,clientY:i}=e.touches[0],a=0,o=0}function d(e){if(!s)return;l&&=(clearTimeout(l),null);let u=Date.now(),{clientX:d,clientY:f}=e.touches[0],p=r-d,m=i-f,h=u-c;h&&(a=p/h,o=m/h,r=d,i=f,c=u,n()&&(e.cancelable&&e.preventDefault(),e.stopPropagation()),l=setTimeout(()=>{a=0,o=0},100),t(p*1,m*1))}function f(e){s=!1,r=i=0,l&&clearTimeout(l),a*=1.2,o*=1.2,requestAnimationFrame(p)}function p(){if(Math.abs(a)<.05&&(a=0),Math.abs(o)<.05&&(o=0),!a&&!o)return;let e=Date.now(),n=Math.abs(e-c),r=a*n,i=o*n;t(r*1,i*1),c=e,a*=cL,o*=cL,requestAnimationFrame(p)}}function uL(e){function t(e,t){return e*(t===0?1:23)}return n=>{e(t(n.shiftKey&&!tE()?n.deltaY:n.deltaX,n.deltaMode),t(n.shiftKey&&!tE()?n.deltaX:n.deltaY,n.deltaMode))}}H`
1771
1771
  .o-border {
1772
1772
  position: absolute;
1773
1773
  &:hover {
@@ -1777,7 +1777,7 @@ stores.inject(MyMetaStore, storeInstance);
1777
1777
  .o-moving {
1778
1778
  cursor: grabbing;
1779
1779
  }
1780
- `;var fL=class extends t.Component{static template=`o-spreadsheet-Border`;static props={zone:Object,orientation:String,isMoving:Boolean,onMoveHighlight:Function};get style(){let e=[`n`,`w`,`e`].includes(this.props.orientation),t=[`n`,`w`,`s`].includes(this.props.orientation),n=[`n`,`s`].includes(this.props.orientation),r=[`w`,`e`].includes(this.props.orientation),i=this.props.zone,a=this.env.model.getters.getVisibleRect(i),o=a.x,s=a.x+a.width-4,c=a.y,l=a.y+a.height-4,u=t?o:s,d=e?c:l,f=n?s-o:4,p=r?l-c:4;return U({left:`${u}px`,top:`${d}px`,width:`${f}px`,height:`${p}px`})}onMouseDown(e){this.props.onMoveHighlight(e.clientX,e.clientY)}};H`
1780
+ `;var dL=class extends t.Component{static template=`o-spreadsheet-Border`;static props={zone:Object,orientation:String,isMoving:Boolean,onMoveHighlight:Function};get style(){let e=[`n`,`w`,`e`].includes(this.props.orientation),t=[`n`,`w`,`s`].includes(this.props.orientation),n=[`n`,`s`].includes(this.props.orientation),r=[`w`,`e`].includes(this.props.orientation),i=this.props.zone,a=this.env.model.getters.getVisibleRect(i),o=a.x,s=a.x+a.width-4,c=a.y,l=a.y+a.height-4,u=t?o:s,d=e?c:l,f=n?s-o:4,p=r?l-c:4;return U({left:`${u}px`,top:`${d}px`,width:`${f}px`,height:`${p}px`})}onMouseDown(e){this.props.onMoveHighlight(e.clientX,e.clientY)}};H`
1781
1781
  .o-corner {
1782
1782
  position: absolute;
1783
1783
  height: 6px;
@@ -1799,11 +1799,11 @@ stores.inject(MyMetaStore, storeInstance);
1799
1799
  .o-resizing {
1800
1800
  cursor: grabbing;
1801
1801
  }
1802
- `;var pL=class extends t.Component{static template=`o-spreadsheet-Corner`;static props={zone:Object,color:String,orientation:String,isResizing:Boolean,onResizeHighlight:Function};isTop=this.props.orientation[0]===`n`;isLeft=this.props.orientation[1]===`w`;get style(){let e=this.props.zone,t=this.isLeft?e.left:e.right,n=this.isTop?e.top:e.bottom,r=this.env.model.getters.getVisibleRect({left:t,right:t,top:n,bottom:n});if(r.width*r.height===0)return`display:none`;let i=this.isLeft?r.x:r.x+r.width,a=this.isTop?r.y:r.y+r.height;return U({left:`${i-8/2}px`,top:`${a-8/2}px`,"background-color":this.props.color})}onMouseDown(e){this.props.onResizeHighlight(this.isLeft,this.isTop)}};H`
1802
+ `;var fL=class extends t.Component{static template=`o-spreadsheet-Corner`;static props={zone:Object,color:String,orientation:String,isResizing:Boolean,onResizeHighlight:Function};isTop=this.props.orientation[0]===`n`;isLeft=this.props.orientation[1]===`w`;get style(){let e=this.props.zone,t=this.isLeft?e.left:e.right,n=this.isTop?e.top:e.bottom,r=this.env.model.getters.getVisibleRect({left:t,right:t,top:n,bottom:n});if(r.width*r.height===0)return`display:none`;let i=this.isLeft?r.x:r.x+r.width,a=this.isTop?r.y:r.y+r.height;return U({left:`${i-8/2}px`,top:`${a-8/2}px`,"background-color":this.props.color})}onMouseDown(e){this.props.onResizeHighlight(this.isLeft,this.isTop)}};H`
1803
1803
  .o-highlight {
1804
1804
  z-index: ${5};
1805
1805
  }
1806
- `;var mL=class extends t.Component{static template=`o-spreadsheet-Highlight`;static props={zone:Object,color:String};static components={Corner:pL,Border:fL};highlightState=(0,t.useState)({shiftingMode:`none`});onResizeHighlight(e,t){let n=this.env.model.getters.getActiveSheetId();this.highlightState.shiftingMode=`isResizing`;let r=this.props.zone,i=e?r.right:r.left,a=t?r.bottom:r.top,o=e?r.left:r.right,s=t?r.top:r.bottom,c=r;this.env.model.dispatch(`START_CHANGE_HIGHLIGHT`,{zone:c}),zN(this.env,(e,t)=>{if(o!==e||s!==t){o=b(e===-1?o:e,0,this.env.model.getters.getNumberCols(n)-1),s=b(t===-1?s:t,0,this.env.model.getters.getNumberRows(n)-1);let r={left:Math.min(i,o),top:Math.min(a,s),right:Math.max(i,o),bottom:Math.max(a,s)};lr(r,c)||(this.env.model.selection.selectZone({cell:{col:r.left,row:r.top},zone:r},{unbounded:!0}),c=r)}},()=>{this.highlightState.shiftingMode=`none`})}onMoveHighlight(e,t){this.highlightState.shiftingMode=`isMoving`;let n=this.props.zone,r=YT(),i=this.env.model.getters.getActiveSheetId(),a=this.env.model.getters.getColIndex(e-r.left),o=this.env.model.getters.getRowIndex(t-r.top),s=-n.left,c=this.env.model.getters.getNumberCols(i)-n.right-1,l=-n.top,u=this.env.model.getters.getNumberRows(i)-n.bottom-1,d=n;this.env.model.dispatch(`START_CHANGE_HIGHLIGHT`,{zone:d});let f=a,p=o;zN(this.env,(e,t)=>{if(f!==e||p!==t){f=e===-1?f:e,p=t===-1?p:t;let r=b(f-a,s,c),i=b(p-o,l,u),m={left:n.left+r,top:n.top+i,right:n.right+r,bottom:n.bottom+i};lr(m,d)||(this.env.model.selection.selectZone({cell:{col:m.left,row:m.top},zone:m},{unbounded:!0}),d=m)}},()=>{this.highlightState.shiftingMode=`none`})}},hL=class{direction;el;constructor(e,t){this.el=e,this.direction=t}get scroll(){return this.direction===`horizontal`?this.el.scrollLeft:this.el.scrollTop}set scroll(e){this.direction===`horizontal`?this.el.scrollLeft=e:this.el.scrollTop=e}};H`
1806
+ `;var pL=class extends t.Component{static template=`o-spreadsheet-Highlight`;static props={zone:Object,color:String};static components={Corner:fL,Border:dL};highlightState=(0,t.useState)({shiftingMode:`none`});onResizeHighlight(e,t){let n=this.env.model.getters.getActiveSheetId();this.highlightState.shiftingMode=`isResizing`;let r=this.props.zone,i=e?r.right:r.left,a=t?r.bottom:r.top,o=e?r.left:r.right,s=t?r.top:r.bottom,c=r;this.env.model.dispatch(`START_CHANGE_HIGHLIGHT`,{zone:c}),zN(this.env,(e,t)=>{if(o!==e||s!==t){o=b(e===-1?o:e,0,this.env.model.getters.getNumberCols(n)-1),s=b(t===-1?s:t,0,this.env.model.getters.getNumberRows(n)-1);let r={left:Math.min(i,o),top:Math.min(a,s),right:Math.max(i,o),bottom:Math.max(a,s)};lr(r,c)||(this.env.model.selection.selectZone({cell:{col:r.left,row:r.top},zone:r},{unbounded:!0}),c=r)}},()=>{this.highlightState.shiftingMode=`none`})}onMoveHighlight(e,t){this.highlightState.shiftingMode=`isMoving`;let n=this.props.zone,r=YT(),i=this.env.model.getters.getActiveSheetId(),a=this.env.model.getters.getColIndex(e-r.left),o=this.env.model.getters.getRowIndex(t-r.top),s=-n.left,c=this.env.model.getters.getNumberCols(i)-n.right-1,l=-n.top,u=this.env.model.getters.getNumberRows(i)-n.bottom-1,d=n;this.env.model.dispatch(`START_CHANGE_HIGHLIGHT`,{zone:d});let f=a,p=o;zN(this.env,(e,t)=>{if(f!==e||p!==t){f=e===-1?f:e,p=t===-1?p:t;let r=b(f-a,s,c),i=b(p-o,l,u),m={left:n.left+r,top:n.top+i,right:n.right+r,bottom:n.bottom+i};lr(m,d)||(this.env.model.selection.selectZone({cell:{col:m.left,row:m.top},zone:m},{unbounded:!0}),d=m)}},()=>{this.highlightState.shiftingMode=`none`})}},mL=class{direction;el;constructor(e,t){this.el=e,this.direction=t}get scroll(){return this.direction===`horizontal`?this.el.scrollLeft:this.el.scrollTop}set scroll(e){this.direction===`horizontal`?this.el.scrollLeft=e:this.el.scrollTop=e}};H`
1807
1807
  .o-scrollbar {
1808
1808
  position: absolute;
1809
1809
  overflow: auto;
@@ -1819,7 +1819,7 @@ stores.inject(MyMetaStore, storeInstance);
1819
1819
  border-left: 1px solid #e2e3e3;
1820
1820
  }
1821
1821
  }
1822
- `;var gL=class 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`
1822
+ `;var hL=class 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`
1823
1823
  <div
1824
1824
  t-attf-class="o-scrollbar {{props.direction}}"
1825
1825
  t-on-scroll="onScroll"
@@ -1827,7 +1827,7 @@ stores.inject(MyMetaStore, storeInstance);
1827
1827
  t-att-style="positionCss">
1828
1828
  <div t-att-style="sizeCss"/>
1829
1829
  </div>
1830
- `;static defaultProps={width:1,height:1};scrollbarRef;scrollbar;setup(){this.scrollbarRef=(0,t.useRef)(`scrollbar`),this.scrollbar=new hL(this.scrollbarRef.el,this.props.direction),(0,t.onMounted)(()=>{this.scrollbar.el=this.scrollbarRef.el}),(0,t.useEffect)(()=>{this.scrollbar.scroll!==this.props.offset&&(this.scrollbar.scroll=this.props.offset)},()=>[this.scrollbar.scroll,this.props.offset])}get sizeCss(){return U({width:`${this.props.width}px`,height:`${this.props.height}px`})}get positionCss(){return U(this.props.position)}onScroll(e){this.props.offset!==this.scrollbar.scroll&&this.props.onScroll(this.scrollbar.scroll)}},_L=class extends t.Component{static props={leftOffset:{type:Number,optional:!0}};static components={ScrollBar:gL};static template=t.xml`
1830
+ `;static defaultProps={width:1,height:1};scrollbarRef;scrollbar;setup(){this.scrollbarRef=(0,t.useRef)(`scrollbar`),this.scrollbar=new mL(this.scrollbarRef.el,this.props.direction),(0,t.onMounted)(()=>{this.scrollbar.el=this.scrollbarRef.el}),(0,t.useEffect)(()=>{this.scrollbar.scroll!==this.props.offset&&(this.scrollbar.scroll=this.props.offset)},()=>[this.scrollbar.scroll,this.props.offset])}get sizeCss(){return U({width:`${this.props.width}px`,height:`${this.props.height}px`})}get positionCss(){return U(this.props.position)}onScroll(e){this.props.offset!==this.scrollbar.scroll&&this.props.onScroll(this.scrollbar.scroll)}},gL=class extends t.Component{static props={leftOffset:{type:Number,optional:!0}};static components={ScrollBar:hL};static template=t.xml`
1831
1831
  <ScrollBar
1832
1832
  t-if="isDisplayed"
1833
1833
  width="width"
@@ -1835,7 +1835,7 @@ stores.inject(MyMetaStore, storeInstance);
1835
1835
  offset="offset"
1836
1836
  direction="'horizontal'"
1837
1837
  onScroll.bind="onScroll"
1838
- />`;static defaultProps={leftOffset:0};get offset(){return this.env.model.getters.getActiveSheetDOMScrollInfo().scrollX}get width(){return this.env.model.getters.getMainViewportRect().width}get isDisplayed(){let{xRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){let{x:e}=this.env.model.getters.getMainViewportRect();return{left:`${this.props.leftOffset+e}px`,bottom:`0px`,height:`15px`,right:`0px`}}onScroll(e){let{scrollY:t}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:e,offsetY:t})}},vL=class extends t.Component{static props={topOffset:{type:Number,optional:!0}};static components={ScrollBar:gL};static template=t.xml`
1838
+ />`;static defaultProps={leftOffset:0};get offset(){return this.env.model.getters.getActiveSheetDOMScrollInfo().scrollX}get width(){return this.env.model.getters.getMainViewportRect().width}get isDisplayed(){let{xRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){let{x:e}=this.env.model.getters.getMainViewportRect();return{left:`${this.props.leftOffset+e}px`,bottom:`0px`,height:`15px`,right:`0px`}}onScroll(e){let{scrollY:t}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:e,offsetY:t})}},_L=class extends t.Component{static props={topOffset:{type:Number,optional:!0}};static components={ScrollBar:hL};static template=t.xml`
1839
1839
  <ScrollBar
1840
1840
  t-if="isDisplayed"
1841
1841
  height="height"
@@ -1843,15 +1843,15 @@ stores.inject(MyMetaStore, storeInstance);
1843
1843
  offset="offset"
1844
1844
  direction="'vertical'"
1845
1845
  onScroll.bind="onScroll"
1846
- />`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetDOMScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){let{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){let{y:e}=this.env.model.getters.getMainViewportRect();return{top:`${this.props.topOffset+e}px`,right:`0px`,width:`15px`,bottom:`0px`}}onScroll(e){let{scrollX:t}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:t,offsetY:e})}},yL=class extends hd{mutators=[`open`,`toggle`,`close`,`changePanelSize`,`resetPanelSize`];currentPanelProps={};componentTag=``;panelSize=350;get isOpen(){return this.componentTag?this.computeState(this.componentTag,this.currentPanelProps).isOpen:!1}get panelProps(){let e=this.computeState(this.componentTag,this.currentPanelProps);return e.isOpen?e.props??{}:{}}get panelKey(){let e=this.computeState(this.componentTag,this.currentPanelProps);if(e.isOpen)return e.key}open(e,t={}){let n=this.computeState(e,t);n.isOpen!==!1&&(this.isOpen&&e!==this.componentTag&&this.currentPanelProps?.onCloseSidePanel?.(),this.componentTag=e,this.currentPanelProps=n.props??{})}toggle(e,t){this.isOpen&&e===this.componentTag?this.close():this.open(e,t)}close(){this.currentPanelProps.onCloseSidePanel?.(),this.currentPanelProps={},this.componentTag=``}changePanelSize(e,t){e<350?this.panelSize=350:e>t-150?this.panelSize=Math.max(t-150,350):this.panelSize=e}resetPanelSize(){this.panelSize=350}computeState(e,t){let n=pI.get(e).computeState;if(n){let e=n(this.getters,t);return e.isOpen&&(this.currentPanelProps=e.props??this.currentPanelProps),e}else return{isOpen:!0,props:t}}};let bL=`#777`;H`
1846
+ />`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetDOMScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){let{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){let{y:e}=this.env.model.getters.getMainViewportRect();return{top:`${this.props.topOffset+e}px`,right:`0px`,width:`15px`,bottom:`0px`}}onScroll(e){let{scrollX:t}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:t,offsetY:e})}},vL=class extends hd{mutators=[`open`,`toggle`,`close`,`changePanelSize`,`resetPanelSize`];currentPanelProps={};componentTag=``;panelSize=350;get isOpen(){return this.componentTag?this.computeState(this.componentTag,this.currentPanelProps).isOpen:!1}get panelProps(){let e=this.computeState(this.componentTag,this.currentPanelProps);return e.isOpen?e.props??{}:{}}get panelKey(){let e=this.computeState(this.componentTag,this.currentPanelProps);if(e.isOpen)return e.key}open(e,t={}){let n=this.computeState(e,t);n.isOpen!==!1&&(this.isOpen&&e!==this.componentTag&&this.currentPanelProps?.onCloseSidePanel?.(),this.componentTag=e,this.currentPanelProps=n.props??{})}toggle(e,t){this.isOpen&&e===this.componentTag?this.close():this.open(e,t)}close(){this.currentPanelProps.onCloseSidePanel?.(),this.currentPanelProps={},this.componentTag=``}changePanelSize(e,t){e<350?this.panelSize=350:e>t-150?this.panelSize=Math.max(t-150,350):this.panelSize=e}resetPanelSize(){this.panelSize=350}computeState(e,t){let n=fI.get(e).computeState;if(n){let e=n(this.getters,t);return e.isOpen&&(this.currentPanelProps=e.props??this.currentPanelProps),e}else return{isOpen:!0,props:t}}};let yL=`#777`;H`
1847
1847
  .o-table-resizer {
1848
1848
  width: ${3}px;
1849
1849
  height: ${3}px;
1850
- border-bottom: ${3}px solid ${bL};
1851
- border-right: ${3}px solid ${bL};
1850
+ border-bottom: ${3}px solid ${yL};
1851
+ border-right: ${3}px solid ${yL};
1852
1852
  cursor: nwse-resize;
1853
1853
  }
1854
- `;var xL=class extends t.Component{static template=`o-spreadsheet-TableResizer`;static props={table:Object};state=(0,t.useState)({highlightZone:void 0});setup(){bP(this)}get containerStyle(){let e=this.props.table.range.zone,t={...e,left:e.right,top:e.bottom},n=this.env.model.getters.getVisibleRect(t);return n.height===0||n.width===0?U({display:`none`}):U({top:`${n.y+n.height-6}px`,left:`${n.x+n.width-6}px`})}onMouseDown(e){let t=this.props.table.range.zone,n={col:t.left,row:t.top};document.body.style.cursor=`nwse-resize`,zN(this.env,(e,t,r)=>{this.state.highlightZone={left:n.col,top:n.row,right:Math.max(e,n.col),bottom:Math.max(t,n.row)}},()=>{document.body.style.cursor=``;let e=this.state.highlightZone;if(!e)return;let 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?[{zone:this.state.highlightZone,sheetId:this.props.table.range.sheetId,color:bL,noFill:!0}]:[]}};let SL={ROW:gN,COL:dN,CELL:yj,GROUP_HEADERS:yI,UNGROUP_HEADERS:bI};var CL=class extends t.Component{static template=`o-spreadsheet-Grid`;static props={exposeFocus:Function};static components={GridComposer:OI,GridOverlay:eL,GridPopover:tL,HeadersOverlay:aL,Menu:pk,Autofill:SI,ClientTag:wI,Highlight:mL,Popover:lk,VerticalScrollBar:vL,HorizontalScrollBar:_L,TableResizer:xL};HEADER_HEIGHT=26;HEADER_WIDTH=48;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;onMouseWheel;canvasPosition;hoveredCell;sidePanel;setup(){this.highlightStore=V(xN),this.menuState=(0,t.useState)({isOpen:!1,position:null,menuItems:[]}),this.gridRef=(0,t.useRef)(`grid`),this.canvasPosition=iE(this.gridRef),this.hoveredCell=V(WO),this.composerFocusStore=V(_d),this.DOMFocusableElementStore=V(GT),this.sidePanel=V(yL),this.paintFormatStore=V(QI),V(xI),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>this.getGridRect()}),(0,t.useExternalListener)(document.body,`cut`,this.copy.bind(this,!0)),(0,t.useExternalListener)(document.body,`copy`,this.copy.bind(this,!1)),(0,t.useExternalListener)(document.body,`paste`,this.paste),(0,t.onMounted)(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),cL(`canvas`,this.env.model,()=>this.env.model.getters.getSheetViewDimensionWithHeaders()),this.onMouseWheel=dL((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=V(GO),(0,t.useEffect)(()=>{this.sidePanel.isOpen||this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isOpen]),uL(this.gridRef,this.moveCanvas.bind(this),()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0})}onCellHovered({col:e,row:t}){this.hoveredCell.hover({col:e,row:t})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){return U({top:`26px`,left:`48px`,height:`calc(100% - 41px)`,width:`calc(100% - 63px)`})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>{this.env.model.getters.getActiveCell().type===`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===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()},Delete:()=>{this.env.model.dispatch(`DELETE_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch(`DELETE_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":()=>Yk(this.env),"Alt+=":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:n}=this.env.model.getters.getSelection(),r=this.env.model.getters.getAutomaticSums(e,t,n.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&r.length<=1){let t=r[0]?.zone?this.env.model.getters.zoneToXC(e,r[0].zone):``,n=`=SUM(${t})`;this.onComposerCellFocused(n,{start:5,end:5+t.length})}else this.env.model.dispatch(`SUM_SELECTION`)},"Alt+Enter":()=>{let e=this.env.model.getters.getActiveCell();e.link&&to(e.link,this.env)},"Ctrl+Home":()=>{let e=this.env.model.getters.getActiveSheetId(),{col:t,row:n}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,n)},"Ctrl+End":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,`COL`,this.env.model.getters.getNumberCols(e)-1,0),n=this.env.model.getters.findVisibleHeader(e,`ROW`,this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,n)},"Shift+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,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+Shift+E":()=>this.setHorizontalAlign(`center`),"Ctrl+Shift+L":()=>this.setHorizontalAlign(`left`),"Ctrl+Shift+R":()=>this.setHorizontalAlign(`right`),"Ctrl+Shift+V":()=>wk(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{let e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),n=this.env.model.getters.getSelectedZones().length===1,r=e.size>0&&n,i=t.size>0&&n;r&&!i?Bk(this.env):i&&!r&&Rk(this.env)},"Ctrl+Alt+-":()=>{let e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&t.length===0?this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),dimension:`COL`,elements:e}):t.length>0&&e.length===0&&this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),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":()=>Qk(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()&&this.composerFocusStore.activeComposer.editionMode===`inactive`&&this.DOMFocusableElementStore.focus()}get gridEl(){if(!this.gridRef.el)throw Error(`Grid el is not defined.`);return this.gridRef.el}getAutofillPosition(){let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{left:t.x+t.width-8/2,top:t.y+t.height-8/2}}get isAutofillVisible(){let 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!(t.width===0||t.height===0)}onGridResized({height:e,width:t}){this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:t,height:e,gridOffsetX:48,gridOffsetY:26})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}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}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,n){this.composerFocusStore.activeComposer.editionMode===`editing`&&this.composerFocusStore.activeComposer.stopEdition(),n.expandZone?this.env.model.selection.setAnchorCorner(e,t):n.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t);let r=e,i=t;zN(this.env,(e,t,n)=>{n.preventDefault(),(e!==r&&e!==-1||t!==i&&t!==-1)&&(r=e===-1?r:e,i=t===-1?i:t,this.env.model.selection.setAnchorCorner(r,i))},()=>{this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())})}onCellDoubleClicked(e,t){let n=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:n,col:e,row:t})),this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t}).type===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),sE(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){let t=eE(e),n=this.keyDownMapping[t];if(n){e.preventDefault(),e.stopPropagation(),n();return}if(e.key.startsWith(`Arrow`)){this.processArrows(e);return}}onInputContextMenu(e){e.preventDefault();let t=this.env.model.getters.getSelectedZone(),{left:n,top:r}=t,i=`CELL`;this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(n)?i=`COL`:this.env.model.getters.getActiveRows().has(r)&&(i=`ROW`);let{x:a,y:o,width:s}=this.env.model.getters.getVisibleRect(t),c=this.getGridRect();this.toggleContextMenu(i,c.x+a+s,c.y+o)}onCellRightClicked(e,t,{x:n,y:r}){let i=this.env.model.getters.getSelectedZones(),a=i[i.length-1],o=`CELL`;dr(e,t,a)?this.env.model.getters.getActiveCols().has(e)?o=`COL`:this.env.model.getters.getActiveRows().has(t)&&(o=`ROW`):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(o,n,r)}toggleContextMenu(e,t,n){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:n},this.menuState.menuItems=SL[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement)||this.composerFocusStore.activeComposer.editionMode!==`inactive`)return;e?FO(this.env):this.env.model.dispatch(`COPY`);let n=this.env.model.getters.getClipboardContent(),r=t.clipboardData;for(let e in n)r?.setData(e,n[e]);t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();let t=e.clipboardData;if(!t)return;let n={content:{"text/plain":t?.getData(`text/plain`),"text/html":t?.getData(`text/html`)}},r=this.env.model.getters.getSelectedZones(),i=this.env.model.getters.isCutOperation(),a=Oc(n.content),o=a.data?.clipboardId;this.env.model.getters.getClipboardId()===o?tg(this.env,r):ng(this.env,r,a),i&&await this.env.clipboard.write({"text/plain":``})}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(this.env.model.getters.getSelectedZones().length!==1)return;let t=this.env.model.getters.getActiveRows().size>0,n=this.env.model.getters.getActiveCols().size>0;n&&t?this.processHeaderGroupingEventOnWholeSheet(e):n?this.processHeaderGroupingEventOnHeaders(e,`COL`):t?this.processHeaderGroupingEventOnHeaders(e,`ROW`):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){let n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone(),i=t===`COL`?r.left:r.top,a=t===`COL`?r.right:r.bottom;switch(e){case`right`:this.env.model.dispatch(`GROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`left`:this.env.model.dispatch(`UNGROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break}}processHeaderGroupingEventOnWholeSheet(e){let t=this.env.model.getters.getActiveSheetId();e===`up`?(this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`})):e===`down`&&(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){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSelectedZone();switch(e){case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`right`:{let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRect(n),i=this.getGridRect();this.toggleContextMenu(`GROUP_HEADERS`,e+r+i.x,t+i.y);break}case`left`:{if(!uN(this.env,`COL`)&&!uN(this.env,`ROW`))return;let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRect(n),i=this.getGridRect();this.toggleContextMenu(`UNGROUP_HEADERS`,e+r+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(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(YF)}},wL=class extends t.Component{static template=`o-spreadsheet-EditableName`;static props={name:String,displayName:String,onChanged:Function};state;setup(){this.state=(0,t.useState)({isEditing:!1,name:``})}rename(){this.state.isEditing=!0,this.state.name=this.props.name}save(){this.props.onChanged(this.state.name.trim()),this.state.isEditing=!1}};H`
1854
+ `;var bL=class extends t.Component{static template=`o-spreadsheet-TableResizer`;static props={table:Object};state=(0,t.useState)({highlightZone:void 0});setup(){bP(this)}get containerStyle(){let e=this.props.table.range.zone,t={...e,left:e.right,top:e.bottom},n=this.env.model.getters.getVisibleRect(t);return n.height===0||n.width===0?U({display:`none`}):U({top:`${n.y+n.height-6}px`,left:`${n.x+n.width-6}px`})}onMouseDown(e){let t=this.props.table.range.zone,n={col:t.left,row:t.top};document.body.style.cursor=`nwse-resize`,zN(this.env,(e,t,r)=>{this.state.highlightZone={left:n.col,top:n.row,right:Math.max(e,n.col),bottom:Math.max(t,n.row)}},()=>{document.body.style.cursor=``;let e=this.state.highlightZone;if(!e)return;let 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?[{zone:this.state.highlightZone,sheetId:this.props.table.range.sheetId,color:yL,noFill:!0}]:[]}};let xL={ROW:gN,COL:dN,CELL:yj,GROUP_HEADERS:vI,UNGROUP_HEADERS:yI};var SL=class extends t.Component{static template=`o-spreadsheet-Grid`;static props={exposeFocus:Function};static components={GridComposer:DI,GridOverlay:$I,GridPopover:eL,HeadersOverlay:iL,Menu:pk,Autofill:xI,ClientTag:CI,Highlight:pL,Popover:lk,VerticalScrollBar:_L,HorizontalScrollBar:gL,TableResizer:bL};HEADER_HEIGHT=26;HEADER_WIDTH=48;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;onMouseWheel;canvasPosition;hoveredCell;sidePanel;setup(){this.highlightStore=V(xN),this.menuState=(0,t.useState)({isOpen:!1,position:null,menuItems:[]}),this.gridRef=(0,t.useRef)(`grid`),this.canvasPosition=iE(this.gridRef),this.hoveredCell=V(WO),this.composerFocusStore=V(_d),this.DOMFocusableElementStore=V(GT),this.sidePanel=V(vL),this.paintFormatStore=V(ZI),V(bI),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>this.getGridRect()}),(0,t.useExternalListener)(document.body,`cut`,this.copy.bind(this,!0)),(0,t.useExternalListener)(document.body,`copy`,this.copy.bind(this,!1)),(0,t.useExternalListener)(document.body,`paste`,this.paste),(0,t.onMounted)(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),sL(`canvas`,this.env.model,()=>this.env.model.getters.getSheetViewDimensionWithHeaders()),this.onMouseWheel=uL((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=V(GO),(0,t.useEffect)(()=>{this.sidePanel.isOpen||this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isOpen]),lL(this.gridRef,this.moveCanvas.bind(this),()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0})}onCellHovered({col:e,row:t}){this.hoveredCell.hover({col:e,row:t})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){return U({top:`26px`,left:`48px`,height:`calc(100% - 41px)`,width:`calc(100% - 63px)`})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>{this.env.model.getters.getActiveCell().type===`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===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()},Delete:()=>{this.env.model.dispatch(`DELETE_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch(`DELETE_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":()=>Yk(this.env),"Alt+=":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:n}=this.env.model.getters.getSelection(),r=this.env.model.getters.getAutomaticSums(e,t,n.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&r.length<=1){let t=r[0]?.zone?this.env.model.getters.zoneToXC(e,r[0].zone):``,n=`=SUM(${t})`;this.onComposerCellFocused(n,{start:5,end:5+t.length})}else this.env.model.dispatch(`SUM_SELECTION`)},"Alt+Enter":()=>{let e=this.env.model.getters.getActiveCell();e.link&&to(e.link,this.env)},"Ctrl+Home":()=>{let e=this.env.model.getters.getActiveSheetId(),{col:t,row:n}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,n)},"Ctrl+End":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,`COL`,this.env.model.getters.getNumberCols(e)-1,0),n=this.env.model.getters.findVisibleHeader(e,`ROW`,this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,n)},"Shift+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,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+Shift+E":()=>this.setHorizontalAlign(`center`),"Ctrl+Shift+L":()=>this.setHorizontalAlign(`left`),"Ctrl+Shift+R":()=>this.setHorizontalAlign(`right`),"Ctrl+Shift+V":()=>wk(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{let e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),n=this.env.model.getters.getSelectedZones().length===1,r=e.size>0&&n,i=t.size>0&&n;r&&!i?Bk(this.env):i&&!r&&Rk(this.env)},"Ctrl+Alt+-":()=>{let e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&t.length===0?this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),dimension:`COL`,elements:e}):t.length>0&&e.length===0&&this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),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":()=>Qk(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()&&this.composerFocusStore.activeComposer.editionMode===`inactive`&&this.DOMFocusableElementStore.focus()}get gridEl(){if(!this.gridRef.el)throw Error(`Grid el is not defined.`);return this.gridRef.el}getAutofillPosition(){let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{left:t.x+t.width-8/2,top:t.y+t.height-8/2}}get isAutofillVisible(){let 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!(t.width===0||t.height===0)}onGridResized({height:e,width:t}){this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:t,height:e,gridOffsetX:48,gridOffsetY:26})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}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}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,n){this.composerFocusStore.activeComposer.editionMode===`editing`&&this.composerFocusStore.activeComposer.stopEdition(),n.expandZone?this.env.model.selection.setAnchorCorner(e,t):n.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t);let r=e,i=t;zN(this.env,(e,t,n)=>{n.preventDefault(),(e!==r&&e!==-1||t!==i&&t!==-1)&&(r=e===-1?r:e,i=t===-1?i:t,this.env.model.selection.setAnchorCorner(r,i))},()=>{this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())})}onCellDoubleClicked(e,t){let n=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:n,col:e,row:t})),this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t}).type===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),sE(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){let t=eE(e),n=this.keyDownMapping[t];if(n){e.preventDefault(),e.stopPropagation(),n();return}if(e.key.startsWith(`Arrow`)){this.processArrows(e);return}}onInputContextMenu(e){e.preventDefault();let t=this.env.model.getters.getSelectedZone(),{left:n,top:r}=t,i=`CELL`;this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(n)?i=`COL`:this.env.model.getters.getActiveRows().has(r)&&(i=`ROW`);let{x:a,y:o,width:s}=this.env.model.getters.getVisibleRect(t),c=this.getGridRect();this.toggleContextMenu(i,c.x+a+s,c.y+o)}onCellRightClicked(e,t,{x:n,y:r}){let i=this.env.model.getters.getSelectedZones(),a=i[i.length-1],o=`CELL`;dr(e,t,a)?this.env.model.getters.getActiveCols().has(e)?o=`COL`:this.env.model.getters.getActiveRows().has(t)&&(o=`ROW`):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(o,n,r)}toggleContextMenu(e,t,n){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:n},this.menuState.menuItems=xL[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement)||this.composerFocusStore.activeComposer.editionMode!==`inactive`)return;e?FO(this.env):this.env.model.dispatch(`COPY`);let n=this.env.model.getters.getClipboardContent(),r=t.clipboardData;for(let e in n)r?.setData(e,n[e]);t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();let t=e.clipboardData;if(!t)return;let n={content:{"text/plain":t?.getData(`text/plain`),"text/html":t?.getData(`text/html`)}},r=this.env.model.getters.getSelectedZones(),i=this.env.model.getters.isCutOperation(),a=Oc(n.content),o=a.data?.clipboardId;this.env.model.getters.getClipboardId()===o?tg(this.env,r):ng(this.env,r,a),i&&await this.env.clipboard.write({"text/plain":``})}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(this.env.model.getters.getSelectedZones().length!==1)return;let t=this.env.model.getters.getActiveRows().size>0,n=this.env.model.getters.getActiveCols().size>0;n&&t?this.processHeaderGroupingEventOnWholeSheet(e):n?this.processHeaderGroupingEventOnHeaders(e,`COL`):t?this.processHeaderGroupingEventOnHeaders(e,`ROW`):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){let n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone(),i=t===`COL`?r.left:r.top,a=t===`COL`?r.right:r.bottom;switch(e){case`right`:this.env.model.dispatch(`GROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`left`:this.env.model.dispatch(`UNGROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break}}processHeaderGroupingEventOnWholeSheet(e){let t=this.env.model.getters.getActiveSheetId();e===`up`?(this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`})):e===`down`&&(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){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSelectedZone();switch(e){case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`right`:{let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRect(n),i=this.getGridRect();this.toggleContextMenu(`GROUP_HEADERS`,e+r+i.x,t+i.y);break}case`left`:{if(!uN(this.env,`COL`)&&!uN(this.env,`ROW`))return;let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRect(n),i=this.getGridRect();this.toggleContextMenu(`UNGROUP_HEADERS`,e+r+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(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(JF)}},CL=class extends t.Component{static template=`o-spreadsheet-EditableName`;static props={name:String,displayName:String,onChanged:Function};state;setup(){this.state=(0,t.useState)({isEditing:!1,name:``})}rename(){this.state.isEditing=!0,this.state.name=this.props.name}save(){this.props.onChanged(this.state.name.trim()),this.state.isEditing=!1}};H`
1855
1855
  .o_pivot_html_renderer {
1856
1856
  width: 100%;
1857
1857
  border-collapse: collapse;
@@ -1887,15 +1887,15 @@ stores.inject(MyMetaStore, storeInstance);
1887
1887
  background: #e7f2f6;
1888
1888
  }
1889
1889
  }
1890
- `;var TL=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:TN};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(I(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${Nu(e,i).join(`,`)})`,value:B(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{let{value:r,format:o}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${Nu(e,i).join(`,`)})`,value:B(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}n.push(t)}let r=n[n.length-1];return n[n.length-1]=r.map(e=>(e.isMissing||(e.style=`color: #756f6f;`),e)),n}_buildRowHeaders(e,t){let n=[];for(let r of t.rows){let t=[];for(let e=0;e<r.fields.length;e++)t.push({value:r.fields[e]},{value:r.values[e]});let i=this.pivot.parseArgsToPivotDomain(t),{value:a,format:o}=this.pivot.getPivotHeaderValueAndFormat(i),s=this.env.model.getters.getLocale(),c={formula:`=PIVOT.HEADER(${Nu(e,i).join(`,`)})`,value:B(a,{format:o,locale:s}),isMissing:!this.tracker?.isHeaderPresent(i)};r.indent>1&&(c.style=`padding-left: ${r.indent-10}px`),n.push(c)}return n}_buildValues(e,t){let n=[];for(let r of t.columns.at(-1)||[]){let i=[],a=I(r.values[r.values.length-1]);for(let n of t.rows){let t=[];for(let e=0;e<n.fields.length;e++)t.push({value:n.fields[e]},{value:n.values[e]});for(let e=0;e<r.fields.length-1;e++)t.push({value:r.fields[e]},{value:r.values[e]});let o=this.pivot.parseArgsToPivotDomain(t),{value:s,format:c}=this.pivot.getPivotCellValueAndFormat(a,o),l=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${Nu(e,o,a).join(`,`)})`,value:B(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},EL=class{static getters=[];history;dispatch;canDispatch;constructor(e,t,n){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t,this.canDispatch=n}exportForExcel(e){}allowDispatch(e){return`Success`}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map(e=>e.call(this,t)).flat()}chainValidations(...e){return t=>{for(let n of e){let e=n.call(this,t);Array.isArray(e)||(e=[e]);let r=e.filter(e=>e!==`Success`);if(r.length)return r}return`Success`}}checkValidations(e,...t){return this.batchValidations(...t)(e)}},DL=class extends EL{getters;uuidGenerator;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i,uuidGenerator:a}){super(t,r,i),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=a}import(e){}export(e){}adaptRanges(e,t){}garbageCollectExternalResources(){}},OL=class extends DL{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return`Success`}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>({...e})));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Be.style,color:e.border.color||Be.color})}break;case`CLEAR_FORMATTING`:this.clearBorders(e.sheetId,e.target);break;case`REMOVE_COLUMNS_ROWS`:let r=[...e.elements].sort((e,t)=>t-e);for(let t of ct(r))if(e.dimension===`COL`){if(t[0]>=this.getters.getNumberCols(e.sheetId))for(let n=0;n<this.getters.getNumberRows(e.sheetId);n++)this.history.update(`borders`,e.sheetId,t[0]+1,n,`vertical`,void 0);if(t[t.length-1]===0)for(let t=0;t<this.getters.getNumberRows(e.sheetId);t++)this.history.update(`borders`,e.sheetId,0,t,`vertical`,void 0);let n=this.getters.getColsZone(e.sheetId,t[t.length-1]+1,t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{if(t[0]>=this.getters.getNumberRows(e.sheetId))for(let n=0;n<this.getters.getNumberCols(e.sheetId);n++)this.history.update(`borders`,e.sheetId,n,t[0]+1,`horizontal`,void 0);if(t[t.length-1]===0)for(let t=0;t<this.getters.getNumberCols(e.sheetId);t++)this.history.update(`borders`,e.sheetId,t,0,`horizontal`,void 0);let n=this.getters.getRowsZone(e.sheetId,t[t.length-1]+1,t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity,{moveFirstTopBorder:!0}),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity,{moveFirstTopBorder:!1}),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r={top:this.borders[e]?.[t]?.[n]?.horizontal,bottom:this.borders[e]?.[t]?.[n+1]?.horizontal,left:this.borders[e]?.[t]?.[n]?.vertical,right:this.borders[e]?.[t+1]?.[n]?.vertical};return!r.bottom&&!r.left&&!r.right&&!r.top?null:r}getBordersColors(e){let t=[],n=this.borders[e];if(n)for(let e of n.filter(S))for(let n of e)n?.horizontal&&t.push(n.horizontal.color),n?.vertical&&t.push(n.vertical.color);return t}ensureColumnBorderContinuity(e,t,n){let r=x(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=x(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&C(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(S);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?x(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n,{moveFirstLeftBorder:r}={}){this.borders[e]&&(n<0&&this.moveBordersOfColumn(e,t,n,`vertical`,{destructive:!1}),this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(i=>{(i===t&&r||i!==t)&&this.moveBordersOfColumn(e,i,n,`vertical`),this.moveBordersOfColumn(e,i,n,`horizontal`)}))}shiftBordersVertically(e,t,n,{moveFirstTopBorder:r}={}){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,`horizontal`,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(i=>{(i===t&&r||i!==t)&&this.moveBordersOfRow(e,i,n,`horizontal`),this.moveBordersOfRow(e,i,n,`vertical`)}))}moveBordersOfRow(e,t,n,r,{destructive:i}={destructive:!0}){let a=this.borders[e];a&&this.getColumnsWithBorders(e).forEach(o=>{let s=a[o]?.[t+n]?.[r],c=a[o]?.[t]?.[r];this.history.update(`borders`,e,o,t+n,r,i?c:c||s),this.history.update(`borders`,e,o,t,r,void 0)})}moveBordersOfColumn(e,t,n,r,{destructive:i}={destructive:!0}){let a=this.borders[e];a&&this.getRowsRange(e).forEach(o=>{let s=a[t+n]?.[o]?.[r],c=a[t]?.[o]?.[r];this.history.update(`borders`,e,t+n,o,r,i?c:c||s),this.history.update(`borders`,e,t,o,r,void 0)})}setBorder(e,t,n,r,i=!0){(i||!this.borders?.[e]?.[t]?.[n]?.vertical)&&this.history.update(`borders`,e,t,n,`vertical`,r?.left),(i||!this.borders?.[e]?.[t]?.[n]?.horizontal)&&this.history.update(`borders`,e,t,n,`horizontal`,r?.top),(i||!this.borders?.[e]?.[t+1]?.[n]?.vertical)&&this.history.update(`borders`,e,t+1,n,`vertical`,r?.right),(i||!this.borders?.[e]?.[t]?.[n+1]?.horizontal)&&this.history.update(`borders`,e,t,n+1,`horizontal`,r?.bottom)}clearBorders(e,t){for(let n of T(t)){for(let t=n.top;t<=n.bottom;t++){this.history.update(`borders`,e,n.right+1,t,`vertical`,void 0);for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}for(let t=n.left;t<=n.right;t++)this.history.update(`borders`,e,t,n.bottom+1,`horizontal`,void 0)}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t);for(let i of T(t)){if(n===`h`||n===`hv`||n===`all`)for(let t=i.top+1;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r});if(n===`v`||n===`hv`||n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left+1;n<=i.right;n++)this.addBorder(e,n,t,{left:r});if(n===`left`||n===`all`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`all`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right+1,t,{left:r});if(n===`top`||n===`all`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`all`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom+1,{top:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||C(t,e.border)?`NoChanges`:`Success`}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let n in t.borders){let r=t.borders[n],i=e.borders[r],a=Qn(n);for(let e=a.top;e<=a.bottom;e++)for(let n=a.left;n<=a.right;n++)this.setBorder(t.id,n,e,i,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Qn(e))}export(e){let t={};for(let n of e.sheets){let e={};for(let r=0;r<n.colNumber;r++)for(let i=0;i<n.rowNumber;i++){let a=this.getCellBorder({sheetId:n.id,col:r,row:i});if(a){let o=Pr(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=Fr(e)}e.borders=t}exportForExcel(e){for(let t of e.sheets)for(let n=0;n<t.colNumber;n++)for(let r=0;r<t.rowNumber;r++){let i=this.getCellBorder({sheetId:t.id,col:n,row:r});if(i){let a=w(n,r);t.cells[a]??={},t.cells[a].border=Pr(i,e.borders)}}}},kL=class{map={};set({sheetId:e,col:t,row:n},r){let i=this.map;i[e]||(i[e]={}),i[e][t]||(i[e][t]={}),i[e][t][n]=r}get({sheetId:e,col:t,row:n}){return this.map[e]?.[t]?.[n]}getSheet(e){return this.map[e]}has({sheetId:e,col:t,row:n}){return this.map[e]?.[t]?.[n]!==void 0}delete({sheetId:e,col:t,row:n}){delete this.map[e]?.[t]?.[n]}keys(){let e=this.map,t=[];for(let n in e)for(let r in e[n])for(let i in e[n][r])t.push({sheetId:n,col:parseInt(r),row:parseInt(i)});return t}keysForSheet(e){let t=this.map[e];if(!t)return[];let n=[];for(let r in t)for(let i in t[r])n.push({sheetId:e,col:parseInt(r),row:parseInt(i)});return n}},AL=class extends DL{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellStyle`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges(e,t){for(let n of Object.keys(this.cells))for(let r of Object.values(this.cells[n]||{}))if(r.isFormula){for(let i of r.compiledFormula.dependencies)if(!t||i.sheetId===t){let t=e(i);t.changeType!==`NONE`&&this.history.update(`cells`,n,r.id,`compiledFormula`,`dependencies`,r.compiledFormula.dependencies.indexOf(i),t.range)}}}allowDispatch(e){switch(e.type){case`UPDATE_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case`CLEAR_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case`UPDATE_CELL_POSITION`:return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?`Success`:`InvalidCellId`;default:return`Success`}}handle(e){switch(e.type){case`SET_FORMATTING`:`style`in e&&this.setStyle(e.sheetId,e.target,e.style),`format`in e&&e.format!==void 0&&this.setFormatter(e.sheetId,e.target,e.format);break;case`CLEAR_FORMATTING`:this.clearFormatting(e.sheetId,e.target);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,style:null,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of T(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.getters.getCell({sheetId:e,col:t,row:r})&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}setFormatter(e,t,n){for(let r of T(t))for(let t=r.top;t<=r.bottom;t++)for(let i=r.left;i<=r.right;i++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:i,row:t,format:n})}clearFormatting(e,t){for(let n of T(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,style:null,format:``})}clearCells(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:``,style:null,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=x(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=x(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){for(let t of e.sheets){let n=t.id,r=new kL;for(let e in t.cells)if(t.cells[e]?.content){let{col:n,row:i}=Pn(e),a={sheetId:t.id,col:n,row:i};r.set(a,{content:t.cells[e]?.content})}for(let[e,i]of[[`style`,t.styles],[`format`,t.formats]])for(let t in i){let a=i[t],o=Qn(t);for(let t=o.top;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++){let o={sheetId:n,col:i,row:t},s=r.get(o);s?s[e]=a:r.set(o,{[e]:a})}}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format||n?.style){let r=this.importCell(t.id,n?.content,n?.style?e.styles[n?.style]:void 0,n?.format?e.formats[n?.format]:void 0);this.history.update(`cells`,t.id,r.id,r),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:r.id,...i})}}}}export(e){let t={},n={};for(let r of e.sheets){let e=[],i=[],a={},o=Object.keys(this.cells[r.id]||{}).map(e=>this.getters.getCellPosition(e)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let r of o){let o=this.getters.getCell(r),s=w(r.col,r.row),c=this.extractCustomStyle(o);if(Object.keys(c).length){let n=Pr(c,t);e[n]??=[],e[n].push(r)}if(o.format){let e=Pr(o.format,n);i[e]??=[],i[e].push(r)}o.content&&(a[s]={content:o.content})}r.styles=Fr(e),r.formats=Fr(i),r.cells=a}e.styles=t,e.formats=n}importCell(e,t,n,r){let i=this.getNextUid();return this.createCell(i,t||``,r,n,e)}exportForExcel(e){this.export(e);for(let t of e.sheets)for(let n in this.getters.getCells(t.id)){let{col:r,row:i}=this.getters.getCellPosition(n),a=w(r,i),o=this.getCellById(n);t.cells[a]??={},o?.format&&(t.cells[a].format=Pr(o.format,e.formats)),o?.style&&(t.cells[a]??={},t.cells[a].style=Pr(this.extractCustomStyle(o),e.styles))}let t=[];for(let n in e.formats||[])fs(e.formats[n])||(t.push(n),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.cells){let r=n.cells[e],i=r?.format;i&&t.includes(i.toString())&&delete r.format}}extractCustomStyle(e){let t={...e.style},n=Oi(e.content,k)?Fe:Pe;for(let r in t)(r!==`align`||!e.isFormula)&&t[r]===n[r]&&delete t[r];return t}getCells(e){return this.cells[e]||{}}getCellById(e){let t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,n,r=!1){if(!n.length)return Tt(t.map(e=>e.value));let i=0;return Tt(t.map(t=>{if(t.type===`REFERENCE`){let t=n[i++];return this.getters.getRangeString(t,e,{useBoundedReference:r})}return t.value}))}getTranslatedCellFormula(e,t,n,r){let i=this.getters.createAdaptedRanges(kE(r).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t,n){let r=kE(n).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),i=this.getters.removeRangesSheetPrefix(t,r);return this.getFormulaString(t,n,i)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=w(t.left,t.top,n[0]),i=w(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}setStyle(e,t,n){for(let r of T(t))for(let t=r.left;t<=r.right;t++)for(let i=r.top;i<=r.bottom;i++){let r=this.getters.getCell({sheetId:e,col:t,row:i});this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:i,style:n?{...r?.style,...n}:void 0})}}copyColumnStyle(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowStyle(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:r,row:t,...i})}}getFormat(e,t,n){let r={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.getters.getCell(i);return a&&(a.style&&(r.style=a.style),a.format&&(r.format=a.format)),r}getNextUid(){let e=this.nextId.toString();return this.history.update(`nextId`,this.nextId+1),e}updateCell(e,t,n,r){let i=this.getters.getCell({sheetId:e,col:t,row:n}),a=r.content!==void 0||`formula`in r,o=a?It(r?.content||void 0):i?.content||``,s;s=r.style===void 0?i?i.style:void 0:r.style||void 0;let c=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||i.content===``))&&!s&&!c){i&&(this.history.update(`cells`,e,i.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let l=i?.id||this.getNextUid(),u=this.createCell(l,o,c,s,e);this.history.update(`cells`,e,u.id,u),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:u.id,col:t,row:n,sheetId:e})}createCell(e,t,n,r,i){return t.startsWith(`=`)?this.createFormulaCell(e,t,n,r,i):this.createLiteralCell(e,t,n,r)}createLiteralCell(e,t,n,r){let i=this.getters.getLocale(),a=hs(t,i);return n||=typeof a==`number`?Xo(t,i)||Zo(t):void 0,!ps(n)&&!P(t)&&(t=I(a)),{id:e,content:t,style:r,format:n,isFormula:!1,parsedValue:a}}createFormulaCell(e,t,n,r,i){let a=OE(t);return a.dependencies.length?this.createFormulaCellWithDependencies(e,a,n,r,i):{id:e,content:t,style:r,format:n,isFormula:!0,compiledFormula:{...a,dependencies:[]}}}createFormulaCellWithDependencies(e,t,n,r,i){let a=[];for(let e of t.dependencies)a.push(this.getters.getRangeFromSheetXC(i,e));return new jL(e,t,n,r,a,i,this.getters.getRangeString)}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?dr(n,r,this.getters.getSheetZone(t))?`Success`:`TargetOutOfSheet`:`InvalidSheetId`}checkUselessClearCell(e){let t=this.getters.getCell(e);return!t||!t.content&&!t.style&&!t.format?`NoChanges`:`Success`}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=`format`in e;return(!n||t?.content===e.content)&&(!r||C(t?.style,e.style))&&(!i||t?.format===e.format)?`NoChanges`:`Success`}},jL=class{id;format;style;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,n,r,i,a,o){this.id=e,this.format=n,this.style=r,this.sheetId=a,this.getRangeString=o;let s=0,c=t.tokens.map(e=>e.type===`REFERENCE`?new ML(i,s++,this.sheetId,this.getRangeString):e);this.compiledFormula={...t,dependencies:i,tokens:c}}get content(){return Tt(this.compiledFormula.tokens.map(e=>e.value))}get contentWithFixedReferences(){let e=0;return Tt(this.compiledFormula.tokens.map(t=>{if(t.type===`REFERENCE`){let t=e++;return this.getRangeString(this.compiledFormula.dependencies[t],this.sheetId,{useBoundedReference:!0})}return t.value}))}},ML=class{ranges;rangeIndex;sheetId;getRangeString;type=`REFERENCE`;constructor(e,t,n,r){this.ranges=e,this.rangeIndex=t,this.sheetId=n,this.getRangeString=r}get value(){let e=this.ranges[this.rangeIndex];return this.getRangeString(e,this.sheetId)}},NL=class extends DL{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getContextCreationChart`];charts={};createChart=hk(this.getters);validateChartDefinition=e=>_k(this,e.definition);adaptRanges(e){for(let[t,n]of Object.entries(this.charts))this.history.update(`charts`,t,n?.updateRanges(e))}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case`UPDATE_CHART`:return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists));default:return`Success`}}handle(e){switch(e.type){case`CREATE_CHART`:this.addFigure(e.id,e.sheetId,e.position,e.size),this.addChart(e.id,e.definition);break;case`UPDATE_CHART`:this.addChart(e.id,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`chart`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.charts[n.id]?.copyForSheetId(e.sheetIdTo);i&&this.dispatch(`CREATE_CHART`,{id:r,position:{x:n.x,y:n.y},size:{width:n.width,height:n.height},definition:i.getDefinition(),sheetId:e.sheetIdTo})}break}case`DELETE_FIGURE`:this.history.update(`charts`,e.id,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){let t=this.charts[e]?.type;if(!t)throw Error(`Chart not defined.`);return t}isChartDefined(e){return e in this.charts&&this.charts!==void 0}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.getDefinition();if(!t)throw Error(`There is no chart with the given figureId: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)e.tag===`chart`&&(this.charts[e.id]=this.createChart(e.id,e.data,t.id))}export(e){if(e.sheets)for(let t of e.sheets){let e=this.getters.getFigures(t.id),n=[];for(let t of e){let e=t;if(e&&e.tag===`chart`){let t=this.charts[e.id]?.getDefinition();t&&(e.data=t,n.push(e))}else n.push(e)}t.figures=n}}addFigure(e,t,n={x:0,y:0},r={width:536,height:335}){if(this.getters.getFigure(t,e))return;let i={id:e,x:n.x,y:n.y,width:r.width,height:r.height,tag:`chart`};this.dispatch(`CREATE_FIGURE`,{sheetId:t,figure:i})}addChart(e,t){let n=this.getters.getFigureSheetId(e);n&&this.history.update(`charts`,e,this.createChart(e,t,n))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.id)?`DuplicatedChartId`:`Success`}checkChartExists(e){return this.isChartDefined(e.id)?`Success`:`ChartDoesNotExist`}};function PL(e){return e===``?NaN:Number(e)}var FL=class extends DL{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};loopThroughRangesOfSheet(e,t){for(let n of this.cfRules[e]){if(n.rule.type===`DataBarRule`&&n.rule.rangeValues){let r=t(n.rule.rangeValues);switch(r.changeType){case`REMOVE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`rule`,`rangeValues`,r.range);break}}for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}}adaptRanges(e,t){if(t)this.loopThroughRangesOfSheet(t,e);else for(let t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return this.checkValidations(e,this.checkCFRule,this.checkEmptyRange);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)dr(t,n,e.zone)&&r.push(i);return new Set(r.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,n,r){if(n.length===0&&r.length===0)return;let i=this.getters.getConditionalFormats(e),a=i.findIndex(e=>e.id===t.id),o=[];a>-1&&(o=i[a].ranges.map(Zn));let s=T(o,r);return T([...n,...s],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:n}={useBoundedReference:!1}){let r=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:n}));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:n})},ranges:r}:{...t,rule:{...t.rule},ranges:r}}mapToConditionalFormatInternal(e,t){let n=t.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:n}:{...t,rule:{...t.rule},ranges:n}}addConditionalFormatting(e,t){let n=this.cfRules[t].slice(),r=n.findIndex(t=>t.id===e.id),i=this.mapToConditionalFormatInternal(t,e);r>-1?n.splice(r,1,i):n.push(i),this.history.update(`cfRules`,t,n)}checkValidPriorityChange(e,t,n){if(!this.cfRules[n])return`InvalidSheetId`;let r=this.cfRules[n].findIndex(t=>t.id===e);if(r===-1)return`InvalidConditionalFormatId`;let i=r-t;return i<0||i>=this.cfRules[n].length?`InvalidConditionalFormatId`:`Success`}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}checkCFRule(e){let t=e.cf.rule;switch(t.type){case`CellIsRule`:return ig[t.operator]?this.checkValidations(t,this.checkOperatorArgsNumber(2,[`Between`,`NotBetween`]),this.checkOperatorArgsNumber(1,[`BeginsWith`,`ContainsText`,`EndsWith`,`GreaterThan`,`GreaterThanOrEqual`,`LessThan`,`LessThanOrEqual`,`NotContains`,`Equal`,`NotEqual`]),this.checkOperatorArgsNumber(0,[`IsEmpty`,`IsNotEmpty`]),this.checkCFValues):`InvalidConditionalFormatType`;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return`Success`}return`InvalidConditionalFormatType`}checkOperatorArgsNumber(e,t){if(e>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);return n=>{if(t.includes(n.operator)){let t=[],r=e=>e===void 0||e===``;return e>=1&&r(n.values[0])&&t.push(`FirstArgMissing`),e>=2&&r(n.values[1])&&t.push(`SecondArgMissing`),t.length?t:`Success`}return`Success`}}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return`MinNaN`;case`max`:return`MaxNaN`;case`mid`:return`MidNaN`;case`upperInflectionPoint`:return`ValueUpperInflectionNaN`;case`lowerInflectionPoint`:return`ValueLowerInflectionNaN`}return`Success`}checkFormulaCompilation(e,t){if(e.type!==`formula`)return`Success`;if(OE(e.value||``).isBadExpression)switch(t){case`min`:return`MinInvalidFormula`;case`max`:return`MaxInvalidFormula`;case`mid`:return`MidInvalidFormula`;case`upperInflectionPoint`:return`ValueUpperInvalidFormula`;case`lowerInflectionPoint`:return`ValueLowerInvalidFormula`}return`Success`}checkThresholds(e){return this.batchValidations(t=>e(t.minimum,`min`),t=>e(t.maximum,`max`),t=>t.midpoint?e(t.midpoint,`mid`):`Success`)}checkInflectionPoints(e){return this.batchValidations(t=>e(t.lowerInflectionPoint,`lowerInflectionPoint`),t=>e(t.upperInflectionPoint,`upperInflectionPoint`))}checkLowerBiggerThanUpper(e){let t=e.lowerInflectionPoint.value,n=e.upperInflectionPoint.value;return[`number`,`percentage`,`percentile`].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(n)?`LowerBiggerThanUpper`:`Success`}checkMinBiggerThanMax(e){let t=e.minimum.value,n=e.maximum.value;return[`number`,`percentage`,`percentile`].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&PL(t)>=PL(n)?`MinBiggerThanMax`:`Success`}checkMidBiggerThanMax(e){let t=e.midpoint?.value,n=e.maximum.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&PL(t)>=PL(n)?`MidBiggerThanMax`:`Success`}checkMinBiggerThanMid(e){let t=e.minimum.value,n=e.midpoint?.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&PL(t)>=PL(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&OE(t||``).isBadExpression)return`ValueCellIsInvalidFormula`;return`Success`}removeConditionalFormatting(e,t){let n=this.cfRules[t].findIndex(t=>t.id===e);if(n!==-1){let e=this.cfRules[t].slice();e.splice(n,1),this.history.update(`cfRules`,t,e)}}changeCFPriority(e,t,n){let r=this.cfRules[n].findIndex(t=>t.id===e),i=this.cfRules[n][r],a=r-t,o=[...this.cfRules[n]];o.splice(r,1),o.splice(a,0,i),this.history.update(`cfRules`,n,o)}},IL=class extends DL{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e,t){let n=t?[t]:Object.keys(this.rules);for(let t of n)this.loopThroughRangesOfSheet(t,e)}loopThroughRangesOfSheet(e,t){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return this.getters.tryGetSheet(e.sheetId)?this.checkValidations(e,this.chainValidations(this.checkEmptyRange,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`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=y(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>Ws(e.sheetId,e.sheetIdTo,t))}));this.history.update(`rules`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.rules};delete t[e.sheetId],this.history.update(`rules`,t);break}case`REMOVE_DATA_VALIDATION_RULE`:this.removeDataValidationRule(e.sheetId,e.id);break;case`ADD_DATA_VALIDATION_RULE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case`DELETE_CONTENT`:{let t=T(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(e&&(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!this.getters.getCell({sheetId:n,col:r,row:t})?.content)){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,w(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(dr(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`arrow`:!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=y(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of qs(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:e?.style?.align??`center`,verticalAlign:e?.style?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...y(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return Q.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=Q.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=Q.get(t.type);return t.values.some(e=>e.startsWith(`=`)?n.allowedValues===`onlyLiterals`:n.allowedValues===`onlyFormulas`?!0:!n.isCriterionValueValid(e))?`InvalidDataValidationCriterionValue`:`Success`}},LL=class extends DL{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkFigureDuplicate(e.figure.id);case`UPDATE_FIGURE`:case`DELETE_FIGURE`:return this.checkFigureExists(e.sheetId,e.id);default:return`Success`}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{id:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:this.addFigure(e.figure,e.sheetId);break;case`UPDATE_FIGURE`:let{type:t,sheetId:n,...r}=e,i=r;this.updateFigure(n,i);break;case`DELETE_FIGURE`:this.removeFigure(e.id,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:this.onRowColDelete(e.sheetId,e.dimension)}}onRowColDelete(e,t){t===`ROW`?this.onRowDeletion(e):this.onColDeletion(e)}onRowDeletion(e){let t=this.getters.getNumberRows(e),n=0;for(let r=0;r<t;r++)n+=this.getters.getUserRowSize(e,r)||23;let r=this.getters.getFigures(e);for(let t of r){let r=Math.min(t.y,n-t.height);r!==t.y&&this.dispatch(`UPDATE_FIGURE`,{sheetId:e,id:t.id,y:r})}}onColDeletion(e){let t=this.getters.getNumberCols(e),n=0;for(let r=0;r<t;r++)n+=this.getters.getColSize(e,r);let r=this.getters.getFigures(e);for(let t of r){let r=Math.min(t.x,n-t.width);r!==t.x&&this.dispatch(`UPDATE_FIGURE`,{sheetId:e,id:t.id,x:r})}}updateFigure(e,t){if(`id`in t)for(let[n,r]of Object.entries(t))switch(n){case`x`:case`y`:r!==void 0&&this.history.update(`figures`,e,t.id,n,Math.max(r,0));break;case`width`:case`height`:r!==void 0&&this.history.update(`figures`,e,t.id,n,r);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e,t){return this.figures[e]?.[t]===void 0?`FigureDoesNotExist`:`Success`}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e])?`DuplicatedFigureId`:`Success`}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){this.export(e)}},RL=class extends DL{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,y(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=zt(t,e.elements);this.history.update(`sizes`,e.sheetId,e.dimension,n);break}case`ADD_COLUMNS_ROWS`:{let t=[...this.sizes[e.sheetId][e.dimension]],n=Ot(e.position,e.base),r=t[e.base];t=Bt(t,Array(e.quantity).fill(r),n),this.history.update(`sizes`,e.sheetId,e.dimension,t);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of x(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of x(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},zL=class extends DL{static getters=[`checkElementsIncludeAllVisibleHeaders`,`getHiddenColsGroups`,`getHiddenRowsGroups`,`isHeaderHiddenByUser`,`isRowHiddenByUser`,`isColHiddenByUser`];hiddenHeaders={};allowDispatch(e){switch(e.type){case`HIDE_COLUMNS_ROWS`:{if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=e.dimension===`COL`?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),n=e.dimension===`COL`?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=n?`TooManyHiddenElements`:Kt(e.elements)<0||Gt(e.elements)>n?`InvalidHeaderIndex`:`Success`}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`:`InvalidSheetId`}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,y(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=Ot(e.position,e.base),n=Bt([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,n);break}case`HIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!0);break;case`UNHIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!1);break}}checkElementsIncludeAllVisibleHeaders(e,t,n){return At(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=x(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...x(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},BL=class extends DL{static getters=[`getImage`,`getImagePath`,`getImageSize`];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){switch(e.type){case`CREATE_IMAGE`:return this.getters.getFigure(e.sheetId,e.figureId)?`InvalidFigureId`:`Success`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_IMAGE`:this.addImage(e.figureId,e.sheetId,e.position,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,position:{x:n.x,y:n.y},size:t,definition:y(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.id,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}garbageCollectExternalResources(){let e=new Set(this.getAllImages().map(e=>e.path));for(let t of this.syncedImages)e.has(t)||this.fileStore?.delete(t)}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addImage(e,t,n,r){let i={id:e,x:n.x,y:n.y,width:r.width,height:r.height,tag:`image`};this.dispatch(`CREATE_FIGURE`,{sheetId:t,figure:i})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:y(e)})}t.images=[...t.images,...n]}}getAllImages(){let e=[];for(let t in this.images)e.push(...Object.values(this.images[t]||{}).filter(S));return e}},VL=class extends DL{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`getSelectionRangeString`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(S))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e,t){let n=t?[t]:Object.keys(this.merges);for(let t of n)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(S)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(S)}getSelectionRangeString(e,t){let n=Us.fromRange(e,this.getters),r=this.getters.expandZone(n.sheetId,n.zone),i=n.clone({zone:{...r,bottom:n.isFullCol?void 0:r.bottom,right:n.isFullRow?void 0:r.right}}),a=this.getters.getRangeString(i,t);if(this.isSingleCellOrMerge(n.sheetId,n.zone)){let{sheetName:e,xc:t}=Vs(a);return Hs(e,t.split(`:`)[0])}return a}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(ur(t,n))return!0;return!1}doesColumnsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(r.id,t,i,n,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(r.id,i,t,i,n))return!0;return!1}expandZone(e,t){let{left:n,right:r,top:i,bottom:a}=t,o={left:n,right:r,top:i,bottom:a};for(let t in this.merges[e]){let n=this.getMergeById(e,parseInt(t));n&&ur(n,o)&&(o=or(n,o))}return lr(o,t)?o:this.expandZone(e,o)}isInSameMerge(e,t,n,r,i){let a=this.getMerge({sheetId:e,col:t,row:n}),o=this.getMerge({sheetId:e,col:r,row:i});return!a||!o?!1:lr(a,o)}isInMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e];return r?t in r&&!!r[t]?.[n]:!1}getMainCellPosition(e){let t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){let n=this.getters.getHiddenColsGroups(e),r=this.getters.getHiddenRowsGroups(e);for(let e of n)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of r)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){let n=this.getMerge({sheetId:e,col:t.left,row:t.top});if(n)return lr(t,n);let{numberOfCols:r,numberOfRows:i}=pr(t);return r===1&&i===1}isMainCellPosition(e){return C(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=b(r,0,this.getters.getNumberCols(e)-1),a=b(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&n.content!==``)return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:UL(t,n)}checkDestructiveMerge({sheetId:e,target:t}){return this.getters.tryGetSheet(e)&&t.some(t=>this.isMergeDestructive(e,t))?`MergeIsDestructive`:`Success`}checkOverlap({target:e}){for(let t of e)for(let n of e)if(t!==n&&ur(t,n))return`MergeOverlap`;return`Success`}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return`Success`;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);for(let e of t)if(e.left<n&&e.right>=n||e.top<r&&e.bottom>=r)return`FrozenPaneOverlap`;return`Success`}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return`Success`;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?`Success`:`CellIsMerged`}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!lr(e,i))return`InvalidTarget`}return`Success`}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=b(r,0,this.getters.getNumberCols(e)-1),a=b(a,0,this.getters.getNumberRows(e)-1),w(n,i)===w(r,a))return;let o=this.getters.getCell({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,tr({left:n,top:i,right:r,bottom:a})));let c=new Set;for(let t=i;t<=a;t++)for(let a=n;a<=r;a++){(a!==n||t!==i)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:t,style:o?o.style:null,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&c.add(r.id),this.history.update(`mergeCellMap`,e,a,t,s)}for(let t of c){let{top:n,bottom:r,left:i,right:a}=this.getMergeById(e,t);for(let t=n;t<=r;t++)for(let n=i;n<=a;n++){let r={sheetId:e,col:n,row:t},i=this.getMerge(r);(!i||i.id!==s)&&(this.history.update(`mergeCellMap`,e,n,t,void 0),this.dispatch(`CLEAR_CELL`,r))}this.history.update(`merges`,e,t,void 0)}}removeMerge(e,t){let{left:n,top:r,bottom:i,right:a}=t,o=this.getMerge({sheetId:e,col:n,row:r});if(!(o===void 0||!lr(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,t){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=pr(a.range.zone);t===1&&i===1?this.removeMerge(e,n):this.history.update(`merges`,e,parseInt(r,10),a.range);break}}this.history.update(`mergeCellMap`,e,{});for(let t of this.getMerges(e))for(let{col:n,row:r}of _r(t))this.history.update(`mergeCellMap`,e,n,r,t.id)}import(e){let t=e.sheets||[];for(let e of t)this.history.update(`merges`,e.id,{}),this.history.update(`mergeCellMap`,e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let n of t)this.addMerge(e,Qn(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...HL(e))}}exportForExcel(e){this.export(e)}};function HL(e){return Object.entries(e).map(([e,t])=>t?UL(parseInt(e,10),t):void 0).filter(S).map(e=>w(e.left,e.top)+`:`+w(e.right,e.bottom))}function UL(e,t){return{...t.zone,id:e}}var WL=class{getters;providers=[];isAdaptingRanges=!1;constructor(e){this.getters=e}static getters=[`extendRange`,`getRangeString`,`getRangeFromSheetXC`,`createAdaptedRanges`,`getRangeDataFromXc`,`getRangeDataFromZone`,`getRangeFromRangeData`,`getRangeFromZone`,`getRangesUnion`,`recomputeRanges`,`isRangeValid`,`removeRangesSheetPrefix`];allowDispatch(e){return e.type===`MOVE_RANGES`?e.target.length===1?`Success`:`InvalidZones`:`Success`}beforeHandle(e){}handle(e){if(this.isAdaptingRanges)throw Error(`Plugins cannot dispatch commands during adaptRanges phase`);switch(e.type){case`REMOVE_COLUMNS_ROWS`:{let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`,i=[...e.elements];i.sort((e,t)=>t-e);let a=ct(i);this.executeOnAllRanges(i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`};let o=i,s=`NONE`;for(let e of a){let a=Kt(e),c=Gt(e);if(i.zone[t]<=a&&a<=i.zone[n]){let e=Math.min(i.zone[n],c)-a+1;s=`RESIZE`,o=this.createAdaptedRange(o,r,s,-e)}else if(i.zone[t]>=a&&i.zone[n]<=c)s=`REMOVE`,o=i.clone({...this.getInvalidRange()});else if(i.zone[t]<=c&&i.zone[n]>=c){let e=c-i.zone[t]+1;s=`RESIZE`,o=this.createAdaptedRange(o,r,s,-e),o=this.createAdaptedRange(o,r,`MOVE`,-(i.zone[t]-a))}else a<i.zone[t]&&(s=`MOVE`,o=this.createAdaptedRange(o,r,s,-(c-a+1)))}return s===`NONE`?{changeType:`NONE`}:{changeType:s,range:o}},e.sheetId);break}case`ADD_COLUMNS_ROWS`:{let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`;this.executeOnAllRanges(i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`};if(e.position===`after`){if(i.zone[t]<=e.base&&e.base<i.zone[n])return{changeType:`RESIZE`,range:this.createAdaptedRange(i,r,`RESIZE`,e.quantity)};if(e.base<i.zone[t])return{changeType:`MOVE`,range:this.createAdaptedRange(i,r,`MOVE`,e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[n])return{changeType:`RESIZE`,range:this.createAdaptedRange(i,r,`RESIZE`,e.quantity)};if(e.base<=i.zone[t])return{changeType:`MOVE`,range:this.createAdaptedRange(i,r,`MOVE`,e.quantity)}}return{changeType:`NONE`}},e.sheetId);break}case`DELETE_SHEET`:this.executeOnAllRanges(t=>{if(t.sheetId!==e.sheetId)return{changeType:`NONE`};let n=this.getters.getSheetName(e.sheetId);return t=t.clone({...this.getInvalidRange(),invalidSheetName:n}),{changeType:`REMOVE`,range:t}},e.sheetId);break;case`RENAME_SHEET`:this.executeOnAllRanges(t=>{if(t.sheetId===e.sheetId)return{changeType:`CHANGE`,range:t};if(tc(t.invalidSheetName,e.name)){let n=e.sheetId;return{changeType:`CHANGE`,range:t.clone({sheetId:n,invalidSheetName:void 0})}}return{changeType:`NONE`}});break;case`MOVE_RANGES`:{let t=e.target[0];this.executeOnAllRanges(n=>{if(n.sheetId!==e.sheetId||!fr(n.zone,t))return{changeType:`NONE`};let r=e.targetSheetId,i=e.col-t.left,a=e.row-t.top,o=this.createAdaptedRange(n,`both`,`MOVE`,[i,a]),s=e.sheetId===r?o.prefixSheet:!0;return{changeType:`MOVE`,range:o.clone({sheetId:r,prefixSheet:s})}});break}}}finalize(){}verifyRangeRemoved(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!$n(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}createAdaptedRange(e,t,n,r){let i=yr(e.unboundedZone,t,n,r);return e.clone({zone:i})}executeOnAllRanges(e,t){this.isAdaptingRanges=!0;let n=this.verifyRangeRemoved(e);for(let e of this.providers)e(n,t);this.isAdaptingRanges=!1}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,n,r){return e.map(e=>Us.fromRange(e,this.getters)).map(e=>{if(!$n(e.zone))return e;let i=e.prefixSheet?e.sheetId:r,a={...e.unboundedZone,left:e.isFullRow&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:e.isFullRow?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.isFullCol&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:n),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:n)};return e.clone({sheetId:i,zone:a}).orderZone()})}removeRangesSheetPrefix(e,t){return t.map(t=>{let n=Us.fromRange(t,this.getters);return n.prefixSheet&&n.sheetId===e?n.clone({prefixSheet:!1}):n})}extendRange(e,t,n){let r=Us.fromRange(e,this.getters),i=t===`COL`?r.zone.right+n:r.zone.right,a=t===`ROW`?r.zone.bottom+n:r.zone.bottom,o={left:r.zone.left,top:r.zone.top,right:r.isFullRow?void 0:i,bottom:r.isFullCol?void 0:a};return new Us({...r,zone:o},this.getters.getSheetSize).orderZone()}getRangeFromSheetXC(e,t){if(!Fs.test(t)||!this.getters.tryGetSheet(e))return new Us({sheetId:``,zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let n,r=t,i=!1;t.includes(`!`)&&({xc:r,sheetName:n}=Vs(t),n&&(i=!0));let a=Zn(r),o=Us.getRangeParts(r,a),s=n&&!this.getters.getSheetIdByName(n)?n:void 0,c=this.getters.getSheetIdByName(n)||e;return new Us({prefixSheet:i,zone:a,sheetId:c,invalidSheetName:s,parts:o},this.getters.getSheetSize).orderZone()}getRangeString(e,t,n={useBoundedReference:!1,useFixedReference:!1}){if(!e)return j.InvalidReference;if(e.invalidXc)return e.invalidXc;if(!this.getters.tryGetSheet(e.sheetId)||e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0||e.zone.left<0||e.zone.top<0)return j.InvalidReference;let r=Us.fromRange(e,this.getters),i=r.sheetId!==t||r.invalidSheetName||r.prefixSheet,a=``;if(i&&(a=r.invalidSheetName?ot(r.invalidSheetName):ot(this.getters.getSheetName(r.sheetId))),i&&!a)return j.InvalidReference;let o=this.getRangePartString(r,0,n);return r.parts&&r.parts.length===2&&(r.zone.top!==r.zone.bottom||r.zone.left!==r.zone.right||r.parts[0].rowFixed||r.parts[0].colFixed||r.parts[1].rowFixed||r.parts[1].colFixed)&&(o+=`:`,o+=this.getRangePartString(r,1,n)),`${i?a+`!`:``}${o}`}getRangeDataFromXc(e,t){return this.getters.getRangeFromSheetXC(e,t).rangeData}getRangeDataFromZone(e,t){return t=this.getters.getUnboundedZone(e,t),{_sheetId:e,_zone:t}}getRangeFromZone(e,t){return new Us({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){return T(e.map(e=>Us.fromRange(e,this.getters).unboundedZone),t.map(e=>Us.fromRange(e,this.getters).unboundedZone)).map(t=>this.getRangeFromZone(e[0].sheetId,t))}getRangeFromRangeData(e){return new Us({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;let{xc:t,sheetName:n}=Vs(e);return t.match(Fs)!==null&&(!n||this.getters.getSheetIdByName(n)!==void 0)}getRangesUnion(e){let t=sr(...e.map(e=>Us.fromRange(e,this.getters).unboundedZone));return this.getRangeFromZone(e[0].sheetId,t)}getRangePartString(e,t,n={useBoundedReference:!1,useFixedReference:!1}){let r=e.parts[t]?.colFixed||n.useFixedReference?`$`:``,i=Tn(t===0?e.zone.left:e.zone.right),a=e.parts[t]?.rowFixed||n.useFixedReference?`$`:``,o=String(t===0?e.zone.top+1:e.zone.bottom+1),s=``;return s=e.isFullCol&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:r+i:e.isFullRow&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:a+o:r+i+a+o,s}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:``,invalidXc:j.InvalidReference}}},GL=class extends DL{static getters=`getSheetName.tryGetSheetName.getSheet.tryGetSheet.getSheetIdByName.getSheetIds.getVisibleSheetIds.isSheetVisible.doesHeaderExist.doesHeadersExist.getCell.getCellPosition.getColsZone.getRowCells.getRowsZone.getNumberCols.getNumberRows.getNumberHeaders.getGridLinesVisibility.getNextSheetName.getSheetSize.getSheetZone.getPaneDivisions.checkZonesExistInSheet.getCommandZones.getUnboundedZone.checkElementsIncludeAllNonFrozenHeaders.getDuplicateSheetName`.split(`.`);sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){let t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if(t!==`Success`)return t;switch(e.type){case`HIDE_SHEET`:return this.getVisibleSheetIds().length===1?`NotEnoughSheets`:`Success`;case`CREATE_SHEET`:return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case`DUPLICATE_SHEET`:return this.sheets[e.sheetIdTo]?`DuplicatedSheetId`:this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?`DuplicatedSheetName`:`Success`;case`MOVE_SHEET`:try{let t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),`Success`}catch{return`WrongSheetMove`}case`RENAME_SHEET`:return this.isRenameAllowed(e);case`COLOR_SHEET`:return!e.color||tn(e.color)?`Success`:`InvalidColor`;case`DELETE_SHEET`:return this.getVisibleSheetIds().length>1?`Success`:`NotEnoughSheets`;case`ADD_COLUMNS_ROWS`:return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?`InvalidQuantity`:`Success`:`InvalidHeaderIndex`;case`REMOVE_COLUMNS_ROWS`:{let t=Kt(e.elements),n=Gt(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,n)?`InvalidHeaderIndex`:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`}case`FREEZE_ROWS`:return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case`FREEZE_COLUMNS`:return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return`Success`}}handle(e){switch(e.type){case`SET_GRID_LINES_VISIBILITY`:this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case`CREATE_SHEET`:let t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update(`sheetIdsMapName`,t.name,t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.name);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case`UPDATE_CELL_POSITION`:this.updateCellPosition(e);break;case`FREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,e.quantity,`COL`);break;case`FREEZE_ROWS`:this.setPaneDivisions(e.sheetId,e.quantity,`ROW`);break;case`UNFREEZE_ROWS`:this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`UNFREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,0,`COL`);break;case`UNFREEZE_COLUMNS_ROWS`:this.setPaneDivisions(e.sheetId,0,`COL`),this.setPaneDivisions(e.sheetId,0,`ROW`)}}import(e){for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let t of e.sheets){let e=t.name||E(`Sheet`)+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:Xs(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(S).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e){let t=it(e);for(let e in this.sheetIdsMapName)if(tc(e,t))return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(S)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return $s(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(t.bottom===void 0||t.right===void 0)return t;let n=t.left===0&&t.right===this.getNumberCols(e)-1,r=t.top===0&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:r?void 0:t.bottom,right:n&&!r?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,n){let r={...this.getPaneDivisions(e)};n===`COL`?r.xSplit=t:n===`ROW`&&(r.ySplit=t),this.history.update(`sheets`,e,`panes`,r)}checkElementsIncludeAllNonFrozenHeaders(e,t,n){let r=this.getters.getPaneDivisions(e),i=t===`ROW`?r.ySplit:r.xSplit,a=this.getters.getNumberHeaders(e,t);return i?At(n,x(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&`row`in e&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every($n))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>fr(e,n))?`Success`:`TargetOutOfSheet`}return`Success`}updateCellPosition(e){let{sheetId:t,cellId:n,col:r,row:i}=e;n?this.setNewPosition(n,t,r,i):this.clearPosition(t,r,i)}setNewPosition(e,t,n,r){let i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update(`cellPosition`,e,{row:r,col:n,sheetId:t}),this.history.update(`sheets`,t,`rows`,r,`cells`,n,e)}clearPosition(e,t,n){let r=this.sheets[e]?.rows[n].cells[t];r&&(this.history.update(`cellPosition`,r,void 0),this.history.update(`sheets`,e,`rows`,n,`cells`,t,void 0))}setGridLinesVisibility(e,t){this.history.update(`sheets`,e,`areGridLinesVisible`,t)}createSheet(e,t,n,r,i){let a={id:e,name:t,numberOfCols:n,rows:Xs(r),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},o=this.orderedSheetIds.slice();o.splice(i,0,a.id);let s=this.sheets;return this.history.update(`orderedSheetIds`,o),this.history.update(`sheets`,Object.assign({},s,{[a.id]:a})),a}moveSheet(e,t){let n=this.orderedSheetIds.slice(),r=n.findIndex(t=>t===e),i=n.splice(r,1),a=this.findIndexOfTargetSheet(r,t);n.splice(a,0,i[0]),this.history.update(`orderedSheetIds`,n)}findIndexOfTargetSheet(e,t){for(;t!==0&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(t===0)return e;throw Error(E(`There is not enough visible sheets`))}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId);if(t!==void 0&&e.name===t)return`UnchangedSheetName`;let{orderedSheetIds:n,sheets:r}=this,i=e.name&&e.name.trim().toLowerCase();return n.find(t=>tc(r[t]?.name,i)&&t!==e.sheetId)?`DuplicatedSheetName`:Ke.test(i)?`ForbiddenCharactersInSheetName`:`Success`}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?`WrongSheetPosition`:`Success`}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return`MergeOverlap`;return`Success`}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return`MergeOverlap`;return`Success`}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):`MissingSheetName`}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[n],r[t]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=y(this.getSheet(e));r.id=t,r.name=n;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{col:e,row:n}=this.getCellPosition(t.id);this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:e,row:n,content:t.content,format:t.format,style:t.style})}let o=Object.assign({},this.sheetIdsMapName);o[r.name]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return ec(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){let t=e.name,n=Object.assign({},this.sheets);delete n[e.id],this.history.update(`sheets`,n);let r=this.orderedSheetIds.slice(),i=r.indexOf(e.id);r.splice(i,1),this.history.update(`orderedSheetIds`,r);let a=Object.assign({},this.sheetIdsMapName);delete a[t],this.history.update(`sheetIdsMapName`,a)}removeColumns(e,t){t.sort((e,t)=>t-e);for(let n of t)this.moveCellOnColumnsDeletion(e,n);let n=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,n-t.length);let r=t.filter(t=>t<e.panes.xSplit).length;r&&this.setPaneDivisions(e.id,e.panes.xSplit-r,`COL`)}removeRows(e,t){t.sort((e,t)=>t-e);for(let n of ct(t)){let t=n[n.length-1],r=n[0];this.moveCellOnRowsDeletion(e,t,r),this.updateRowsStructureOnDeletion(e,t,r)}let n=t.filter(t=>t<e.panes.ySplit).length;n&&this.setPaneDivisions(e.id,e.panes.ySplit-n,`ROW`)}addColumns(e,t,n,r){let i=n===`before`?t:t+1;this.moveCellsOnAddition(e,i,r,`columns`);let a=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,a+r),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+r,`COL`)}addRows(e,t,n,r){let i=n===`before`?t:t+1;this.addEmptyRows(e,r),this.moveCellsOnAddition(e,i,r,`rows`),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+r,`ROW`)}moveCellOnColumnsDeletion(e,t){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let n=0;n<e.rows.length;n++){let r=e.rows[n];for(let i in r.cells){let a=Number(i),o=r.cells[i];o&&a>t&&this.setNewPosition(o,e.id,a-1,n)}}}moveCellsOnAddition(e,t,n,r){let i=[];for(let a=0;a<e.rows.length;a++){let o=e.rows[a];if(r!==`rows`||a>=t)for(let s in o.cells){let c=Number(s),l=o.cells[s];l&&(r===`rows`||c>=t)&&i.push({sheetId:e.id,cellId:l,col:c+(r===`columns`?n:0),row:a+(r===`rows`?n:0),type:`UPDATE_CELL_POSITION`})}}for(let e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,n){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:n}]});let r=n-t+1;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(t>n)for(let n in i.cells){let a=Number(n),o=i.cells[n];o&&this.setNewPosition(o,e.id,a,t-r)}}}updateRowsStructureOnDeletion(e,t,n){let r=[],i=e.rows.map(e=>e.cells).reverse();for(let a in e.rows){let e=Number(a);e>=t&&e<=n||r.push({cells:i.pop()})}this.history.update(`sheets`,e.id,`rows`,r)}addEmptyRows(e,t){let n=e.rows.slice();for(let e=0;e<t;e++)n.push({cells:{}});this.history.update(`sheets`,e.id,`rows`,n)}getImportedSheetSize(e){let t=Object.keys(e.cells).map(Pn),n=e.rowNumber,r=e.colNumber;for(let{col:e,row:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?`InvalidSheetId`:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?`DuplicatedSheetId`:`Success`}checkZonesAreInSheet(e){return`sheetId`in e?`ranges`in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},KL=class extends DL{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};insertionOrders={};adaptRanges(e,t){let n=t?[t]:this.getters.getSheetIds();for(let t of n)for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return`InvalidSheetId`;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return Dr(t)?this.checkValidations(e,e=>this.getTablesOverlappingZones(e.sheetId,t).length?`TableOverlap`:`Success`,e=>this.checkTableConfigUpdateIsValid(e.config)):`NonContinuousTargets`;case`UPDATE_TABLE`:return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,e=>this.checkTableConfigUpdateIsValid(e.config)):`TableNotFound`;case`ADD_MERGE`:for(let t of this.getCoreTables(e.sheetId)){let n=t.range.zone;for(let t of e.target)if(ur(n,t))return`MergeInTable`}break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{}),this.history.update(`insertionOrders`,e.sheetId,[]);break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t),this.history.update(`insertionOrders`,e.sheetId,void 0);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t),this.history.update(`insertionOrders`,e.sheetIdTo,[...this.insertionOrders[e.sheetId]??[]]);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.uuidGenerator.smallUuid(),a=e.config||Om,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o),this.history.update(`insertionOrders`,e.sheetId,[...this.insertionOrders[e.sheetId]??[],o.id]);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!cr(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t),this.history.update(`insertionOrders`,e.sheetId,this.insertionOrders[e.sheetId]?.filter(e=>e in t));break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>fr(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){let t=[];for(let n of this.insertionOrders[e]||[]){let r=this.tables[e][n];r&&t.push(r)}return t}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>dr(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>ur(e.range.zone,t)))}extendTableDown(e,t){let n=this.getters.extendRange(t.range,`ROW`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}extendTableRight(e,t){let n=this.getters.extendRange(t.range,`COL`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:n,row:r},i){if(!e)return`none`;let a=i.range.zone,o=`none`;if(a.bottom+1===r&&n>=a.left&&n<=a.right?o=`down`:a.right+1===n&&r>=a.top&&r<=a.bottom&&(o=`right`),o===`none`)return`none`;let s=o===`down`?{...a,bottom:a.bottom+1,top:a.bottom+1}:{...a,right:a.right+1,left:a.right+1};for(let e=s.top;e<=s.bottom;e++)for(let n=s.left;n<=s.right;n++){let r={sheetId:t,col:n,row:e};if(this.getters.getCell(r)?.content||this.getters.isInMerge(r)||this.getTablesOverlappingZones(t,[D(r)]).length)return`none`}return o}getCoreTableMatchingTopLeft(e,t){for(let n of this.getCoreTables(e)){let e=n.range.zone;if(e.left===t.left&&e.top===t.top)return n}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return`Success`;let t=this.getters.getRangeFromRangeData(e.newTableRange).zone,n=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if(n!==`Success`)return n;let r=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);return r?this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==r.id).length?`TableOverlap`:`Success`:`TableNotFound`}checkTableConfigUpdateIsValid(e){return e&&(e.numberOfHeaders!==void 0&&e.numberOfHeaders<0||e.hasFilters&&e.numberOfHeaders===0)?`InvalidTableConfig`:`Success`}createStaticTable(e,t,n,r,i){let a=n.zone;if(!i){i=[];for(let e of x(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.uuidGenerator.smallUuid();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=Cr(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of x(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.uuidGenerator.smallUuid();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,Cr(t.zone)):e.range,i=n||e.config;return{...e,range:r,config:i}}updateTableConfig(e,t){if(!e)return t;let n={...t,...e};return e.numberOfHeaders===0?n.hasFilters=!1:e.hasFilters===!0&&(n.numberOfHeaders||=1),n}createFilterFromZone(e,t,n,r){return JF(e,this.getters.getRangeFromZone(t,n),r,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone),r=t.filters.map(n=>{let r=this.getters.getRangeFromZone(e,n.rangeWithHeaders.zone);return JF(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:y(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:y(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=JF(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<pr(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.uuidGenerator.smallUuid(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}import(e){for(let t of e.sheets){let e=[];for(let n of t.tables||[]){let r=this.uuidGenerator.uuidv4(),i=n.config||Om,a=this.getters.getRangeFromSheetXC(t.id,n.range),o=n.type||`static`,s=o===`dynamic`?this.createDynamicTable(r,a,i):this.createStaticTable(r,o,a,i);this.history.update(`tables`,t.id,s.id,s),e.push(s.id)}this.history.update(`insertionOrders`,t.id,e)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:tr(e.range.zone),type:e.type};C(e.config,Om)||(n.config=e.config),t.tables.push(n)}}exportForExcel(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n=tr(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},qL=class extends DL{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return`HeaderGroupAlreadyExists`;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return`UnknownHeaderGroup`;if(x(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return`NotEnoughElements`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=y(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=Ot(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&x(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Lt([t.end,e]))t.end++;else{let t={start:e,end:e};s[n].push(t)}}}for(let e of s)for(let t of e)t.isFolded=i[this.getGroupId(t)];return s}groupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}unGroupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,-1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}moveGroupsOnHeaderInsertion(e,t,n,r){let i=this.groups[e][t];for(let a=0;a<i.length;a++){let o=i[a],[s,c]=Zs(n,r,[o.start,o.end]);(s!==o.start||c!==o.end)&&this.history.update(`groups`,e,t,a,{...o,start:s,end:c})}}moveGroupsOnHeaderDeletion(e,t,n){let r=this.getHeaderGroups(e,t),i=[];for(let e of r){let t=Qs(n,x(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=kf(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=kf(t,e,n.end+1);r.collapsed=!0}}}}}},JL=class extends DL{static getters=[`getPivotCoreDefinition`,`getPivotDisplayName`,`getPivotId`,`getPivotFormulaId`,`getPivotIds`,`getMeasureCompiledFormula`,`getPivotName`,`isExistingPivot`,`getMeasureFullDependencies`];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case`ADD_PIVOT`:return this.checkDuplicatedMeasureIds(e.pivot);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?C(e.pivot,this.pivots[e.pivotId]?.definition)?`NoChanges`:e.pivot.name===``?`EmptyName`:this.checkDuplicatedMeasureIds(e.pivot):`PivotIdNotFound`;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;if(e.name===``)return`EmptyName`;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;break;case`DUPLICATE_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`}return`Success`}handle(e){switch(e.type){case`ADD_PIVOT`:{let{pivotId:t,pivot:n}=e;this.addPivot(t,n);break}case`INSERT_PIVOT`:{let{sheetId:t,col:n,row:r,pivotId:i,table:a}=e,o={sheetId:t,col:n,row:r},{cols:s,rows:c,measures:l,fieldsType:u}=a,d=new hF(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=y(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,y(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break}}adaptRanges(e){for(let t in this.pivots){let n=y(this.pivots[t]?.definition);if(!n)continue;let r=jF.get(n.type)?.adaptRanges?.(this.getters,n,e);r&&!C(n,r)&&this.history.update(`pivots`,t,`definition`,r)}for(let t in this.compiledMeasureFormulas)for(let n in this.compiledMeasureFormulas[t]){let r=this.pivots[t]?.definition.measures.find(e=>e.id===n);if(!r||!r.computedBy)continue;let i=r.computedBy.sheetId,a=this.compiledMeasureFormulas[t][n].formula,o=[];for(let t of a.dependencies){let n=e(t);n.changeType===`NONE`?o.push(t):o.push(n.range)}let s=this.getters.getFormulaString(i,a.tokens,o);s!==r.computedBy.formula&&this.replaceMeasureFormula(t,r,s)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:y(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=this.compileMeasureFormula(n.computedBy.sheetId,n.computedBy.formula);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.tokens){if(o.type!==`SYMBOL`)continue;let a=i.measures.find(e=>ot(e.id)===o.value&&t.id!==e.id);!a||n.has(a.id)||!a.computedBy||r.push(...this.computeMeasureFullDependencies(e,a,n))}return r.push(...a.dependencies.filter(e=>!e.invalidXc)),r}insertPivot(e,t,n){this.resizeSheet(e.sheetId,e,n);let r=n.getPivotCells();for(let n=0;n<r.length;n++)for(let i=0;i<r[n].length;i++){let a=r[n][i];this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col+n,row:e.row+i,content:Fu(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}compileMeasureFormula(e,t){let n=OE(t),r=n.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return{...n,dependencies:r}}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId}),this.compileCalculatedMeasures(e,r.definition.measures)}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?`Success`:`InvalidDefinition`}import(e){if(e.pivots)for(let[t,n]of Object.entries(e.pivots))this.addPivot(t,n,n.formulaId);this.history.update(`nextFormulaId`,e.pivotNextId||Ou(this.pivots)+1)}export(e){e.pivots={};for(let t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}},YL=class extends DL{static getters=[`getLocale`];locale=k;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return el(e.locale)?`Success`:`InvalidLocale`}return`Success`}handle(e){switch(e.type){case`UPDATE_LOCALE`:let t=this.locale,n=e.locale;this.history.update(`locale`,n),this.changeCellsDateFormatWithLocale(t,n);break}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(let n of this.getters.getSheetIds())for(let[r,i]of Object.entries(this.getters.getCells(n))){let n;if(i.format===e.dateFormat&&(n=t.dateFormat),i.format===e.timeFormat&&(n=t.timeFormat),i.format===_l(e)&&(n=_l(t)),n){let{col:e,row:t,sheetId:i}=this.getters.getCellPosition(r);this.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:i,format:n})}}}import(e){this.locale=e.settings?.locale??k}export(e){e.settings={locale:this.locale}}},XL=class extends DL{allowDispatch(e){switch(e.type){case`ADD_PIVOT`:case`UPDATE_PIVOT`:let t=e.pivot;return this.checkDataSetValidity(t)}return`Success`}checkDataSetValidity(e){if(e.type===`SPREADSHEET`&&e.dataSet){let{zone:t,sheetId:n}=e.dataSet;return!n||!this.getters.tryGetSheet(n)||!t||!$n(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},ZL=class extends DL{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(!Um[e.templateName])return`InvalidTableStyle`;try{en(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=Wm(e.tableStyleName,e.templateName,e.primaryColor);this.history.update(`styles`,e.tableStyleId,t);break;case`REMOVE_TABLE_STYLE`:let n={...this.styles};delete n[e.tableStyleId],this.history.update(`styles`,n);for(let t of this.getters.getSheetIds())for(let n of this.getters.getCoreTables(t))n.config.styleId===e.tableStyleId&&this.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{styleId:Om.styleId}});break}}getTableStyle(e){if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){let e=E(`Custom Table Style`),t=new Set(Object.values(this.styles).map(e=>e.displayName));if(!t.has(e))return e;let n=2;for(;t.has(`${e} ${n}`);)n++;return`${e} ${n}`}isTableStyleEditable(e){return!Hm[e]}import(e){for(let e in Hm)this.styles[e]=Hm[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=Wm(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)Hm[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},$=class extends EL{static layers=[];getters;ui;selection;constructor({getters:e,stateObserver:t,dispatch:n,canDispatch:r,uiActions:i,selection:a}){super(t,n,r),this.getters=e,this.ui=i,this.selection=a}drawLayer(e,t){}};let QL=new h;QL.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let $L=RT.mapping;function eR(e,t,n){return new tR(e,t,n).getParameters()}var tR=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create($L),e,{getters:this.getters,locale:this.getters.getLocale()})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e,t){let n=this.getRangeError(e);if(n)return n;if(t)return{value:Hs(this.getters.getSheetName(e.sheetId),tr(e.zone))};let r={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};return this.computeCell(r)}range(e){let t=this.getRangeError(e);if(t)return[[t]];let n=e.sheetId,r=e.zone,i=cr(r,this.getters.getSheetZone(n));if(!i)return[[]];let{top:a,left:o,bottom:s,right:c}=r,l=`${n}-${a}-${o}-${s}-${c}`;if(l in this.rangeCache)return this.rangeCache[l];let u=i.bottom-i.top+1,d=i.right-i.left+1,f=Array(d);for(let e=i.left;e<=i.right;e++){let t=e-i.left;f[t]=Array(u);for(let r=i.top;r<=i.bottom;r++){let a=r-i.top;f[t][a]=this.computeCell({sheetId:n,col:e,row:r})}}return this.rangeCache[l]=f,f}getRangeError(e){if(!$n(e.zone))return new ia;if(e.invalidSheetName)return new M(E(`Invalid sheet name: %s`,e.invalidSheetName))}},nR=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n||=self).RBush=r()})(e,function(){"use strict";function e(e,r,i,a,o){(function e(n,r,i,a,o){for(;a>i;){if(a-i>600){var s=a-i+1,c=r-i+1,l=Math.log(s),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(s-u)/s)*(c-s/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-c*u/s+d)),Math.min(a,Math.floor(r+(s-c)*u/s+d)),o)}var f=n[r],p=i,m=a;for(t(n,i,r),o(n[a],f)>0&&t(n,i,a);p<m;){for(t(n,p,m),p++,m--;o(n[p],f)<0;)p++;for(;o(n[m],f)>0;)m--}o(n[i],f)===0?t(n,i,m):t(n,++m,a),m<=r&&(i=m+1),r<=m&&(a=m-1)}})(e,r,i||0,a||e.length-1,o||n)}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:+(e>t)}var r=function(e){e===void 0&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function i(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1}function a(e,t){o(e,0,e.children.length,t,e)}function o(e,t,n,r,i){i||=m(null),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(var a=t;a<n;a++){var o=e.children[a];s(i,e.leaf?r(o):o)}return i}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function c(e,t){return e.minX-t.minX}function l(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function d(e){return e.maxX-e.minX+(e.maxY-e.minY)}function f(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function p(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function m(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function h(t,n,r,i,a){for(var o=[n,r];o.length;)if(!((r=o.pop())-(n=o.pop())<=i)){var s=n+Math.ceil((r-n)/i/2)*i;e(t,s,n,r,a),o.push(n,s,s,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(e){var t=this.data,n=[];if(!p(e,t))return n;for(var r=this.toBBox,i=[];t;){for(var a=0;a<t.children.length;a++){var o=t.children[a],s=t.leaf?r(o):o;p(e,s)&&(t.leaf?n.push(o):f(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n},r.prototype.collides=function(e){var t=this.data;if(!p(e,t))return!1;for(var n=[];t;){for(var r=0;r<t.children.length;r++){var i=t.children[r],a=t.leaf?this.toBBox(i):i;if(p(e,a)){if(t.leaf||f(e,a))return!0;n.push(i)}}t=n.pop()}return!1},r.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){var r=this.data;this.data=n,n=r}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this},r.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},r.prototype.clear=function(){return this.data=m([]),this},r.prototype.remove=function(e,t){if(!e)return this;for(var n,r,a,o=this.data,s=this.toBBox(e),c=[],l=[];o||c.length;){if(o||(o=c.pop(),r=c[c.length-1],n=l.pop(),a=!0),o.leaf){var u=i(e,o.children,t);if(u!==-1)return o.children.splice(u,1),c.push(o),this._condense(c),this}a||o.leaf||!f(o,s)?r?(n++,o=r.children[n],a=!1):o=null:(c.push(o),l.push(n),n=0,r=o,o=o.children[0])}return this},r.prototype.toBBox=function(e){return e},r.prototype.compareMinX=function(e,t){return e.minX-t.minX},r.prototype.compareMinY=function(e,t){return e.minY-t.minY},r.prototype.toJSON=function(){return this.data},r.prototype.fromJSON=function(e){return this.data=e,this},r.prototype._all=function(e,t){for(var n=[];e;)e.leaf?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},r.prototype._build=function(e,t,n,r){var i,o=n-t+1,s=this._maxEntries;if(o<=s)return a(i=m(e.slice(t,n+1)),this.toBBox),i;r||(r=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/s**(r-1))),(i=m([])).leaf=!1,i.height=r;var c=Math.ceil(o/s),l=c*Math.ceil(Math.sqrt(s));h(e,t,n,l,this.compareMinX);for(var u=t;u<=n;u+=l){var d=Math.min(u+l-1,n);h(e,u,d,c,this.compareMinY);for(var f=u;f<=d;f+=c){var p=Math.min(f+c-1,d);i.children.push(this._build(e,f,p,r-1))}}return a(i,this.toBBox),i},r.prototype._chooseSubtree=function(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){for(var i=1/0,a=1/0,o=void 0,s=0;s<t.children.length;s++){var c=t.children[s],l=u(c),d=(f=e,p=c,(Math.max(p.maxX,f.maxX)-Math.min(p.minX,f.minX))*(Math.max(p.maxY,f.maxY)-Math.min(p.minY,f.minY))-l);d<a?(a=d,i=l<i?l:i,o=c):d===a&&l<i&&(i=l,o=c)}t=o||t.children[0]}var f,p;return t},r.prototype._insert=function(e,t,n){var r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),s(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)},r.prototype._split=function(e,t){var n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=m(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,a(n,this.toBBox),a(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)},r.prototype._splitRoot=function(e,t){this.data=m([e,t]),this.data.height=e.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(e,t,n){for(var r,i,a,s,c,l,d,f=1/0,p=1/0,m=t;m<=n-t;m++){var h=o(e,0,m,this.toBBox),g=o(e,m,n,this.toBBox),_=(i=h,a=g,s=void 0,c=void 0,l=void 0,d=void 0,s=Math.max(i.minX,a.minX),c=Math.max(i.minY,a.minY),l=Math.min(i.maxX,a.maxX),d=Math.min(i.maxY,a.maxY),Math.max(0,l-s)*Math.max(0,d-c)),v=u(h)+u(g);_<f?(f=_,r=m,p=v<p?v:p):_===f&&v<p&&(p=v,r=m)}return r||n-t},r.prototype._chooseSplitAxis=function(e,t,n){var r=e.leaf?this.compareMinX:c,i=e.leaf?this.compareMinY:l;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)},r.prototype._allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=this.toBBox,a=o(e,0,t,i),c=o(e,n-t,n,i),l=d(a)+d(c),u=t;u<n-t;u++){var f=e.children[u];s(a,e.leaf?i(f):f),l+=d(a)}for(var p=n-t-1;p>=t;p--){var m=e.children[p];s(c,e.leaf?i(m):m),l+=d(c)}return l},r.prototype._adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)s(t[r],e)},r.prototype._condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)e[t].children.length===0?t>0?(n=e[t-1].children).splice(n.indexOf(e[t]),1):this.clear():a(e[t],this.toBBox)},r})}))(),1),rR=class{rTrees={};constructor(e=[]){let t={};for(let n of e){let e=n.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(n)}for(let e in t)this.rTrees[e]=new iR,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new iR),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&C(e.data,t.data)}},iR=class extends nR.default{toBBox({boundingBox:e}){let t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}},aR=class{createEmptyPositionSet;dependencies=new kL;rTree;constructor(e,t=[]){this.createEmptyPositionSet=e,this.rTree=new rR(t)}removeAllDependencies(e){let t=this.dependencies.get(e);if(t){for(let e of t)this.rTree.remove(e);this.dependencies.delete(e)}}addDependencies(e,t){let n=t.map(({sheetId:t,zone:n})=>({data:e,boundingBox:{zone:n,sheetId:t}}));for(let e of n)this.rTree.insert(e);let r=this.dependencies.get(e);r?r.push(...n):this.dependencies.set(e,n)}getCellsDependingOn(e,t){let n=this.createEmptyPositionSet(),r=Array.from(e).reverse();for(;r.length>0;){let e=r.pop(),i=e.zone,a=e.sheetId;for(let e=i.left;e<=i.right;e++)for(let t=i.top;t<=i.bottom;t++)n.add({sheetId:a,col:e,row:t});let o=this.rTree.search(e).map(e=>e.data),s={};for(let e of o)!n.has(e)&&!t.has(e)&&(s[e.sheetId]||(s[e.sheetId]=[]),s[e.sheetId].push(D(e)));for(let e in s){let t=T(s[e],[]);r.push(...t.map(t=>({sheetId:e,zone:t})))}}for(let t of e){let e=t.zone,r=t.sheetId;for(let t=e.left;t<=e.right;t++)for(let i=e.top;i<=e.bottom;i++)n.delete({sheetId:r,col:t,row:i})}return n}},oR=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=sR(t),r=e<<n>>5,i=new this(r+1);return i.columnOffset=n,i.cols=t,i.rows=e,i}getValue(e){let[t,n]=this.getCoordinates(e);return this[t]>>n&1}setValue(e,t){let[n,r]=this.getCoordinates(e),i=(this[n]>>r&1)==0&&t===1;return this[n]=this[n]&~(1<<r)|t<<r,i}isEmpty(){return!this.some(e=>e!==0)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){let{row:t,col:n}=e,r=(t<<this.columnOffset)+n,i=r>>5;return[i,r-(i<<5)]}};function sR(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var cR=class{sheets={};insertions=[];maxSize=0;constructor(e){for(let t in e){let n=e[t].cols,r=e[t].rows;this.maxSize+=n*r,this.sheets[t]=oR.create(r,n)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(let t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(let t of e)this.delete(t)}has(e){return this.sheets[e.sheetId].getValue(e)===1}clear(){let e=[...this];this.insertions=[];for(let e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(this.insertions.length===0)return!0;for(let e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=Array(this.maxSize);let e=0;for(let t in this.sheets){let n=this.sheets[t];n.fillAllPositions();for(let r=0;r<n.rows;r++)for(let i=0;i<n.cols;i++)this.insertions[e++]={sheetId:t,row:r,col:i}}}*[Symbol.iterator](){for(let e of this.insertions)this.sheets[e.sheetId].getValue(e)===1&&(yield e)}},lR=class{resultsToArrayFormulas=new rR;arrayFormulasToResults=new kL;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||uR}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){let t=this.arrayFormulasToResults.get(e);t&&(this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.delete(e))}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}};let uR=[],dR=Object.freeze(gs(new ra)),fR=Object.freeze(gs({value:null}));var pR=class{context;getters;compilationParams;evaluatedCells=new kL;formulaDependencies=Et(new aR(this.createEmptyPositionSet.bind(this)));blockedArrayFormulas=new cR({});spreadingRelations=new lR;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=eR(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||fR}getSpreadZone(e,t={ignoreSpillError:!1}){let n=this.spreadingRelations.getArrayResultZone(e);if(!n)return;let r=this.evaluatedCells.get(e);return r?.type===`error`&&!(t.ignoreSpillError&&r?.value===j.SpilledBlocked)?D(e):or(D(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type===`empty`)return;let t=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,D(e));return Array.from(t).find(e=>!this.blockedArrayFormulas.has(e))}isArrayFormulaSpillBlocked(e){return this.blockedArrayFormulas.has(e)}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);let t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t);for(let e of t)this.compilationParams.ensureRange(e)}updateCompilationParameters(e){this.compilationParams=eR(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParametersForGridEvaluation(){this.compilationParams=eR(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){let e={};for(let t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new cR(e)}evaluateCells(e){let t=performance.now(),n=this.createEmptyPositionSet();n.addMany(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(e)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=this.createEmptyPositionSet();for(let n of e){let e=this.getters.getCell(n)?.content,r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.add(r),e||t.add(n)}let n=gr(t);for(let e in n)for(let r of n[e])t.addMany(this.getArrayFormulasBlockedBy(e,r));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new lR,this.formulaDependencies=Et(()=>{let e=[...this.getAllCells()].flatMap(e=>this.getDirectDependencies(e).filter(e=>!e.invalidSheetName&&!e.invalidXc).map(t=>({data:e,boundingBox:{zone:t.zone,sheetId:t.sheetId}})));return new aR(this.createEmptyPositionSet.bind(this),e)})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new kL,this.evaluate(this.getAllCells()),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=OE(t),i=r.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return this.updateCompilationParameters(n),this.evaluateCompiledFormula(e,{...r,dependencies:i})}evaluateCompiledFormula(e,t,n){try{let r=gR(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return A(r)?Ma(r,hR):hR(r)}catch(e){return BT(e,``)}}getAllCells(){let e=this.createEmptyPositionSet();return e.fillAllPositions(),e}getArrayFormulasBlockedBy(e,t){let n=this.createEmptyPositionSet(),r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addMany(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteMany(i),n.addMany(this.getCellsDependingOn(n)),n}nextPositionsToUpdate=new cR({});cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextPositionsToUpdate=e;let t=0;for(;!this.nextPositionsToUpdate.isEmpty()&&t++<30;){this.updateCompilationParametersForGridEvaluation();let e=this.nextPositionsToUpdate.clear();for(let t=0;t<e.length;++t)this.evaluatedCells.delete(e[t]);for(let t=0;t<e.length;++t){let n=e[t];if(this.nextPositionsToUpdate.has(n))continue;let r=this.computeCell(n);r!==fR&&this.evaluatedCells.set(n,r)}QL.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}computeCell(e){let t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);let n=this.getters.getCell(e);if(n===void 0)return fR;let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?dR:(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):ms(n,i))}catch(e){return e.value=e?.value||j.GenericError,e.message=e?.message||UT,gs(e)}finally{this.cellsBeingComputed.delete(r)}}computeAndSave(e){let t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){let n=gR(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!A(n))return gs(hR(n),this.getters.getLocale(),t);this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return gs({value:0},this.getters.getLocale(),t);if(i===1&&r===1)return gs(hR(n[0][0]),this.getters.getLocale(),t);let a={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+r-1};return this.spreadingRelations.addRelation({resultZone:a,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),mR(r,i,this.checkCollision(e)),mR(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),gs(hR(n[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){let n=this.formulaDependencies().getCellsDependingOn(hr(t).map(t=>({sheetId:e,zone:t})),this.nextPositionsToUpdate);n.delete({sheetId:e,col:t.left,row:t.top}),this.nextPositionsToUpdate.addMany(n)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:n},r){let i=this.getters.getNumberCols(e),a=this.getters.getNumberRows(e),o=t+r.length<=i,s=n+r[0].length<=a;if(!(o&&s))throw o?new sa(E(`Result couldn't be automatically expanded. Please insert more rows.`)):s?new sa(E(`Result couldn't be automatically expanded. Please insert more columns.`)):new sa(E(`Result couldn't be automatically expanded. Please insert more columns and rows.`))}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:n},r){if(this.getters.getMergesInZone(e,{top:n,bottom:n+r[0].length-1,left:t,right:t+r.length-1}).length!==0)throw new sa(E(`Merged cells found in the spill zone. Please unmerge cells before using array formulas.`))}checkCollision(e){let{sheetId:t,col:n,row:r}=e;return(i,a)=>{let o={sheetId:t,col:i+n,row:a+r};if(this.getters.getCell(o)?.content||this.getters.getEvaluatedCell(o).type!==`empty`)throw this.blockedArrayFormulas.add(e),new sa(E(`Array result was not expanded because it would overwrite data in %s.`,w(o.col,o.row)));this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=gs(hR(r[i][a]),this.getters.getLocale(),s);this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r};this.getters.getCell(t)?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextPositionsToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return dR;this.symbolsBeingComputed.add(t);try{return e?.(t)||new na(E(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.dependencies:[]}getCellsDependingOn(e){let t=[],n=gr(e);for(let e in n)t.push(...n[e].map(t=>({sheetId:e,zone:t})));return this.formulaDependencies().getCellsDependingOn(t,this.nextPositionsToUpdate)}};function mR(e,t,n){for(let r=0;r<e;++r)for(let e=0;e<t;++e)r===0&&e===0||n(r,e)}function hR(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function gR(e,t,n,r,i){let a=t.evalContext,o=a.__originCellPosition,s=a.__originSheetId;a.__originCellPosition=i,a.__originSheetId=n;let c=e.execute(e.dependencies,t.referenceDenormalizer,t.ensureRange,r,a);return a.__originCellPosition=o,a.__originSheetId=s,c}var _R=class extends ${static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getRangeFormattedValues`,`getRangeValues`,`getRangeFormats`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new pR(e.custom,this.getters)}beforeHandle(e){(Ri.has(e.type)||Bi.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case`UPDATE_CELL`:if(!(`content`in e||`format`in e)||this.shouldRebuildDependenciesGraph)return;let t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),`content`in e&&this.evaluator.updateDependencies(t);break;case`EVALUATE_CELLS`:this.evaluator.evaluateAllCells();break}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t,n){let r=this.evaluateFormulaResult(e,t,n);return A(r)?Ma(r,e=>e.value):r.value}evaluateFormulaResult(e,t,n){return this.evaluator.evaluateFormulaResult(e,t,n)}evaluateCompiledFormula(e,t,n){return this.evaluator.evaluateCompiledFormula(e,t,n)}getRangeFormattedValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).formattedValue)}getRangeValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).value)}getRangeFormats(e){let t=this.getters.tryGetSheet(e.sheetId);return t===void 0?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map(e=>e.format)}getEvaluatedCell(e){return this.evaluator.getEvaluatedCell(e)}getEvaluatedCells(e){return this.evaluator.getEvaluatedPositionsInSheet(e).map(e=>this.getEvaluatedCell(e))}getEvaluatedCellsPositions(e){return this.evaluator.getEvaluatedPositionsInSheet(e)}getEvaluatedCellsInZone(e,t){return _r(t).map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return _r(t).map(({col:t,row:n})=>this.getEvaluatedCell({sheetId:e,col:t,row:n})).every(e=>e.type===`empty`)}mapVisiblePositions(e,t){let{sheetId:n,zone:r}=e;return _r(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=w(t.col,t.row),i=n.value,a=!1,o,s,c=!0,l=e.sheets.find(e=>e.id===t.sheetId),u=this.getCorrespondingFormulaCell(t);if(u){let e=this.getters.getCell(t);c=IE(u.compiledFormula.tokens),a=c&&e?.content===u.content,c||i!==``&&(o=(i??``).toString(),s=n.format)}let d=l.cells[r]||{},f=s?Pr(s,e.formats):d.format,p;p=c&&a&&u instanceof jL?u.contentWithFixedReferences:c?d.content:o,l.cells[r]={...d,value:i,isFormula:a,content:p,format:f};let m=this.getSpreadZone(t);m&&(l.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,m),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let vR=/"(#[0-9a-fA-F]{6})"/g;function yR(e){let t=[{leadColor:an(255,0,0),colors:[]},{leadColor:an(255,128,0),colors:[]},{leadColor:an(128,128,0),colors:[]},{leadColor:an(128,255,0),colors:[]},{leadColor:an(0,255,0),colors:[]},{leadColor:an(0,255,128),colors:[]},{leadColor:an(0,255,255),colors:[]},{leadColor:an(0,127,255),colors:[]},{leadColor:an(0,0,255),colors:[]},{leadColor:an(127,0,255),colors:[]},{leadColor:an(128,0,128),colors:[]},{leadColor:an(255,0,128),colors:[]}];for(let n of e.map(ln)){let e=500,r=0;t.forEach((t,i)=>{let a=bR(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>dn(e).s-dn(t).s)).flat().map(cn)}function bR(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var xR=class extends ${customColors={};shouldUpdateColors=!0;static getters=[`getCustomColors`];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds())for(let t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));break;case`UPDATE_CHART`:case`CREATE_CHART`:this.tryToAddColors(this.getChartColors(e.id));break;case`UPDATE_CELL`:case`ADD_CONDITIONAL_FORMAT`:case`SET_BORDER`:case`SET_ZONE_BORDERS`:case`SET_FORMATTING`:case`CREATE_TABLE`:case`UPDATE_TABLE`:this.history.update(`shouldUpdateColors`,!0);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return yR(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(let t of this.getters.getSheetIds())e=e.concat(this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=new Set;for(let e of t)e.style?.textColor&&n.add(e.style.textColor),e.style?.fillColor&&n.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))n.add(t);return[...n]}getFormattingColors(e){let t=this.getters.getConditionalFormats(e),n=[];for(let e of t){let t=e.rule;t.type===`CellIsRule`?(n.push(t.style.textColor),n.push(t.style.fillColor)):t.type===`ColorScaleRule`&&(n.push($t(t.minimum.color)),n.push(t.midpoint?$t(t.midpoint.color):void 0),n.push($t(t.maximum.color)))}return n.filter(S)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getDefinition()).matchAll(vR)].map(e=>e[1])}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(S):[]}tryToAddColors(e){for(let t of e){if(!tn(t))continue;let e=en(t);t&&!Ne.includes(e)&&this.history.update(`customColors`,e,!0)}}},SR=class extends ${static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};createRuntimeChart=gk(this.getters);handle(e){if(Ri.has(e.type)||Vi.has(e.type)||zi.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:case`DELETE_FIGURE`:this.charts[e.id]=void 0;break;case`DELETE_SHEET`:for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0);break}}getChartRuntime(e){if(!this.charts[e]){let t=this.getters.getChart(e);if(!t)throw Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:Dd(e)};if(!t)return{background:oe,fontColor:Dd(oe)};let n=t.zone.left,r=t.zone.top,i=t.sheetId,a=this.getters.getCellComputedStyle({sheetId:i,col:n,row:r}),o=a.fillColor||`#FFFFFF`;return{background:o,fontColor:a.textColor||Dd(o)}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let r of e){if(!r||r.tag!==`chart`)continue;let e=r.id,i=this.getters.getChart(e)?.getDefinitionForExcel();if(i)n.push({...r,data:i});else{if(!this.getters.getChart(e))continue;let n=this.getters.getChartType(e),i=n_(this.getters.getChartRuntime(e),r,n);i&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:i,size:{width:r.width,height:r.height}}})}}t.charts=n}}},CR=class extends ${static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(Ri.has(e.type)||Vi.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(let e of this.getters.getSheetIds())this.computedStyles[e]=Et(()=>this.getComputedStyles(e)),this.computedIcons[e]=Et(()=>this.getComputedIcons(e)),this.computedDataBars[e]=Et(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){let{sheetId:t,col:n,row:r}=e,i=this.computedStyles[t]();return i&&i[n]?.[r]}getConditionalIcon({sheetId:e,col:t,row:n}){let r=this.computedIcons[e]();return r&&r[t]?.[n]}getConditionalDataBar({sheetId:e,col:t,row:n}){let r=this.computedDataBars[e]();return r&&r[t]?.[n]}getComputedStyles(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())switch(n.rule.type){case`ColorScaleRule`:for(let r of n.ranges)this.applyColorScale(e,r,n.rule,t);break;case`CellIsRule`:let r=n.rule.values.map(e=>e.startsWith(`=`)?OE(e):void 0);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let s=this.rulePredicate[n.rule.type],c={sheetId:e,col:o,row:i},l=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s.tokens):t});s&&s(c,{...n.rule,values:l})&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getEvaluatedCellsInZone(e,this.getters.getRangeFromSheetXC(e,t).zone).filter(e=>e.type===`number`).map(e=>e.value);switch(n.type){case`value`:return r===`max`?Gt(i):Kt(i);case`number`:return Number(n.value);case`percentage`:let t=Kt(i);return t+(Gt(i)-t)*Number(n.value)/100;case`percentile`:return ji(i,Number(n.value)/100,!0);case`formula`:let a=n.value&&this.getters.evaluateFormula(e,n.value);return typeof a==`number`?a:null;default:return null}}applyIcon(e,t,n,r){let i=this.parsePoint(e,t,n.lowerInflectionPoint),a=this.parsePoint(e,t,n.upperInflectionPoint);if(i===null||a===null||i>a)return;let o=this.getters.getRangeFromSheetXC(e,t).zone,s=[n.icons.upper,n.icons.middle,n.icons.lower];for(let t=o.top;t<=o.bottom;t++)for(let c=o.left;c<=o.right;c++){let o=this.getters.getEvaluatedCell({sheetId:e,col:c,row:t});if(o.type!==`number`)continue;let l=this.computeIcon(o.value,a,n.upperInflectionPoint.operator,i,n.lowerInflectionPoint.operator,s);r[c]||(r[c]=[]),r[c][t]=l}}computeIcon(e,t,n,r,i,a){return n===`ge`&&e>=t||n===`gt`&&e>t?a[0]:i===`ge`&&e>=r||i===`gt`&&e>r?a[1]:a[2]}applyDataBar(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,n.rangeValues||t),a=Gt(this.getters.getEvaluatedCellsInZone(e,i.zone).filter(e=>e.type===`number`).map(e=>e.value));if(a<=0)return;let o=n.color,s=this.getters.getRangeFromSheetXC(e,t).zone,c=i.zone;for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let i=n-s.left+c.left,l=t-s.top+c.top,u=this.getters.getEvaluatedCell({sheetId:e,col:i,row:l});!dr(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:$t(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[];n.midpoint&&a?(c.push({minValue:i,minColor:n.minimum.color,colorDiffUnit:this.computeColorDiffUnits(i,a,n.minimum.color,n.midpoint.color)}),c.push({minValue:a,minColor:n.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(a,o,n.midpoint.color,n.maximum.color)})):c.push({minValue:i,minColor:n.minimum.color,colorDiffUnit:this.computeColorDiffUnits(i,o,n.minimum.color,n.maximum.color)});for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let s=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(s.type===`number`){let e=b(s.value,i,o),l;l=c.length===2&&a?e<=a?this.colorCell(e,c[0].minValue,c[0].minColor,c[0].colorDiffUnit):this.colorCell(e,c[1].minValue,c[1].minColor,c[1].colorDiffUnit):this.colorCell(e,c[0].minValue,c[0].minColor,c[0].colorDiffUnit),r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=$t(l)}}}computeColorDiffUnits(e,t,n,r){let i=t-e,a=(n>>16)%256-(r>>16)%256,o=(n>>8)%256-(r>>8)%256,s=n%256-r%256;return[a/i,o/i,s/i]}colorCell(e,t,n,r){let[i,a,o]=r,s=Math.round((n>>16)%256-i*(e-t)),c=Math.round((n>>8)%256-a*(e-t)),l=Math.round(n%256-o*(e-t));return s<<16|c<<8|l}rulePredicate={CellIsRule:(e,t)=>{let n=this.getters.getEvaluatedCell(e);if(n.type===`error`)return!1;let[r,i]=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(e.sheetId,t)??``:hs(t,k));if(A(r)||A(i))return!1;let a=n.value??``;switch(r??=``,i??=``,t.operator){case`IsEmpty`:return a.toString().trim()===``;case`IsNotEmpty`:return a.toString().trim()!==``;case`BeginsWith`:return r===``?!1:a.toString().startsWith(r.toString());case`EndsWith`:return r===``?!1:a.toString().endsWith(r.toString());case`Between`:return a>=r&&a<=i;case`NotBetween`:return!(a>=r&&a<=i);case`ContainsText`:return a.toString().indexOf(r.toString())>-1;case`NotContains`:return!a||a.toString().indexOf(r.toString())===-1;case`GreaterThan`:return a>r;case`GreaterThanOrEqual`:return a>=r;case`LessThan`:return a<r;case`LessThanOrEqual`:return a<=r;case`NotEqual`:return r===``?!1:a!==r;case`Equal`:return r===``?!0:a===r;default:console.warn(E(`Not implemented operator %s for kind of conditional formatting: %s`,t.operator,t.type))}return!1}}};let wR={isValid:!0};var TR=class extends ${static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`isCellValidCheckbox`,`isDataValidationInvalid`];validationResults={};handle(e){if(Ri.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=Q.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?E(`The value must not be a formula`):void 0:n.allowedValues===`onlyFormulas`?E(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return wR;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:wR}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||wR}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of qs(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=Et(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?wR:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=Q.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,o,i),c={...i,values:s};if(!a.isValueValid(e,c,this.getters,r))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>dr(e.col,e.row,t.zone));if(!n)throw Error(`The cell is not in any range of the rule`);return{col:e.col-n.zone.left,row:e.row-n.zone.top}}getEvaluatedCriterionValues(e,t,n){return n.values.map(n=>{if(!n.startsWith(`=`))return n;let r=OE(n),i=this.getters.getTranslatedCellFormula(e,t.col,t.row,r.tokens),a=this.getters.evaluateFormula(e,i);return a&&!A(a)?a.toString():``})}},ER=class extends ${static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(Ri.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tables={};return}switch(e.type){case`CREATE_TABLE`:case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`DELETE_CONTENT`:this.tables={};break}}finalize(){for(let e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){let t=[],n=this.getters.getCoreTables(e);for(let e of n)e.type!==`dynamic`&&t.push(e);let r=[...t];for(let i of n){if(i.type!==`dynamic`)continue;let n=this.coreTableToTable(e,i),a=n.range.zone;for(let e of r){let t=e.range.zone;ur(a,t)&&(a=t.left>a.left?{...a,right:Math.min(a.right,t.left-1)}:{...a,bottom:Math.min(a.bottom,t.top-1)})}t.push({...n,range:this.getters.getRangeFromZone(e,a)})}return t}getFilters(e){return this.getTables(e).filter(e=>e.config.hasFilters).map(e=>e.filters).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){let t=this.getTable(e);if(!(!t||!t.config.hasFilters))return t.filters.find(t=>t.col===e.col)}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:n}){return this.getTables(e).find(e=>dr(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>ur(e.range.zone,t)))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some(e=>e.config.hasFilters)}getFilterHeaders(e){let t=[];for(let n of this.getTables(e)){if(!n.config.hasFilters)continue;let r=n.range.zone,i=r.top;for(let n=r.left;n<=r.right;n++)t.push({sheetId:e,col:n,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:n}){return this.getFilterHeaders(e).some(e=>e.col===t&&e.row===n)}canCreateDynamicTableOnZones(e,t){if(!Dr(t))return!1;let n=or(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);return i?C(i,r)&&Er(n)===1?!0:C(n,this.getters.getSpreadZone(i)):!1}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=JF(this.getDynamicTableFilterId(t.id,s),this.getters.getRangeFromZone(e,c),t.config,this.getters.getRangeFromZone);r.push(l)}return r}getDynamicTableFilterId(e,t){return e+`_`+t}isTableExcelExportable(e,t){return t.type===`dynamic`?!1:!_r(t.range.zone).some(t=>this.getters.getArrayFormulaSpreadingOn({sheetId:e,...t}))}exportForExcel(e){for(let t of e.sheets){let n=[];for(let r of t.tables){let i=Qn(r.range),a={sheetId:t.id,col:i.left,row:i.top},o=this.getters.getCoreTable(a),s=this.getTable(a);if(!o||!s||this.isTableExcelExportable(t.id,o)){n.push(r);continue}t.styles=t.styles||{},t.borders=t.borders||{};for(let n of _r(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=w(n.col,n.row),s=t.cells?.[o]||{value:``,isFormula:!1};if(t.cells[o]||(t.cells[o]=s),!St(i)){let n=Pr(i,e.styles);t.styles[o]=n,s.style=n}if(a){let n=Pr(a,e.borders);t.borders[o]=n,s.border=n}}}t.tables=n}}},DR=class extends ${static getters=[`getRowSize`,`getHeaderSize`];tallestCellInRow={};ctx=document.createElement(`canvas`).getContext(`2d`);beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=Ot(e.position,e.base),n=Array(e.quantity).fill(void 0),r=Bt(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=y(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=zt(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of x(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of _r(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForCellChange(e,t,n){let r=this.tallestCellInRow[e]?.[t];if(r?.cell.col===n){let n=this.getRowTallestCell(e,t);this.history.update(`tallestCellInRow`,e,t,n)}let i=this.getCellHeight({sheetId:e,col:n,row:t});if(!(i<=23)&&(!r&&i>23||r&&i>r.size)){let r={cell:{sheetId:e,col:n,row:t},size:i};this.history.update(`tallestCellInRow`,e,t,r)}}initializeSheet(e){let t=[];for(let n=0;n<this.getters.getNumberRows(e);n++){let r=this.getRowTallestCell(e,n);t.push(r)}this.history.update(`tallestCellInRow`,e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return 23;let t=this.getters.getCell(e),n=this.getters.getColSize(e.sheetId,e.col);return rc(this.ctx,t,this.getters.getLocale(),n)}isInMultiRowMerge(e){let t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(this.getters.getUserRowSize(e,t)!==void 0)return;let n=this.getters.getRowCells(e,t),r=0,i;for(let e=0;e<n.length;e++){let t=this.getters.getCellById(n[e]);if(!t)continue;let a=this.getters.getCellPosition(t.id),o=this.getCellHeight(a);o>r&&o>23&&(r=o,i={cell:a,size:o})}if(i&&i.size>23)return i}};let OR=`0.00%`;function kR(e){class t extends e{getters;pivotId;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t,n){super(t,n),this.getters=n.getters,this.pivotId=e}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){let n=`${e}-${t.map(e=>e.field+`=`+e.value).join(`,`)}`;if(this.cache[n])return this.cache[n];let r=this.getMeasure(e),i=r.computedBy?this.computeMeasure(r,t):super.getPivotCellValueAndFormat(e,t);return r.format?this.cache[n]={...i,format:r.format}:this.cache[n]=i,this.cache[n]}computeMeasure(e,t){if(!e.computedBy)return{value:0};let{columns:n,rows:r}=super.definition;if(e.aggregator&&n.length+r.length!==t.length){let n=this.getValuesToAggregate(e,t),r=Du[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return BT(t,e.aggregator.toUpperCase())}}let i=this.getters.getMeasureCompiledFormula(this.pivotId,e),a=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,e=>{let{columns:n,rows:r}=this.definition;if(n.find(t=>t.nameWithGranularity===e)){let{colDomain:n}=Jl(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new aa:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=Jl(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new aa:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return A(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=Jl(this,t),i=this.getTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=Iu(this.definition.getDimension(r.field),t[n]?.value);if(r.field===t[n]?.field&&r.value===e)return this.getSubTreeMatchingDomain(r.children,t,n+1)}return[]}treeToLeafDomains(e,t=[]){let n=[];for(let r of e){let e=this.definition.getDimension(r.field),i=[...t,{field:r.field,value:r.value,type:e.type}];r.children.length===0?n.push(i):n.push(...this.treeToLeafDomains(r.children,i))}return n}getMeasureDisplayValue(e,t){let n=this.getMeasure(e),r=this._getPivotCellValueAndFormat(e,t);if(!n.display||n.display.type===`no_calculations`||r.message)return r;let i=n.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:j.NotAvailable,message:E(`Field "%s" not found in pivot for measure display calculation`,i)};try{let e=n.display;switch(e.type){case`%_of_grand_total`:return this.asPercentOfGrandTotal(r,n);case`%_of_col_total`:return this.asPercentOfColumnTotal(r,n,t);case`%_of_row_total`:return this.asPercentOfRowTotal(r,n,t);case`%_of_parent_row_total`:return this.asPercentOfParentRowTotal(r,n,t);case`%_of_parent_col_total`:return this.asPercentOfParentColumnTotal(r,n,t);case`index`:return this.asIndex(r,n,t);case`%_of_parent_total`:return this.asPercentOfParentTotal(r,n,t,e);case`running_total`:return this.asRunningTotal(r,n,t,e,`running_total`);case`%_running_total`:return this.asRunningTotal(r,n,t,e,`%_running_total`);case`rank_asc`:return this.asRank(r,n,t,e,`asc`);case`rank_desc`:return this.asRank(r,n,t,e,`desc`);case`%_of`:return this.asPercentOf(r,n,t,e);case`difference_from`:return this.asDifferenceFrom(r,n,t,e);case`%_difference_from`:return this.asDifferenceFromInPercent(r,n,t,e)}return r}catch(e){return BT(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:j.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:OR}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:j.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:OR}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:j.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:OR}}asPercentOfParentRowTotal(e,t,n){let r=Kl(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:OR}}asPercentOfParentColumnTotal(e,t,n){let r=ql(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:OR}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!nu(i,n))return{value:``};let a=eu(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:OR}}asIndex(e,t,n){let r=this.measureValueToNumber(e),i=this.getRowTotal(t.id,n),a=this.getColumnTotal(t.id,n),o=this.getGrandTotal(t.id);return i===0||a===0?{value:j.DivisionByZero}:{value:r*o/(a*i),format:void 0}}asRunningTotal(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;let o=i===`running_total`?this.runningTotal:this.runningTotalInPercent,s=o[t.id]?.[a];s||(s=this.computeRunningTotal(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=Jl(this,n),u=au(l),d=au(c);return{value:s[u]?.[d]??``,format:i===`running_total`?e.format:OR}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!nu(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:j.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:OR}:s===void 0?{value:j.NullError}:{value:s/o,format:OR}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!nu(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a)||0;return o===`sameValue`?{value:``}:{value:this.measureValueToNumber(e)-o,format:e.format}}asDifferenceFromInPercent(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!nu(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:j.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:j.NullError}:{value:(s-o)/o,format:OR}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!nu(a,n))return{value:``};let o=i===`asc`?this.rankAsc:this.rankDesc,s=o[t.id]?.[a];s||(s=this.computeRank(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=Jl(this,n),u=au(l),d=au(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=ru(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=Pa(o));for(let s of o){let o=au(Yl(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:Yl(this,i,t.domain)})).filter(e=>nu(t,e.rowDomain)),l=Object.groupBy(c,e=>su(e.rowDomain,t));for(let e in l)l[e]=Jt(l[e]||[],e=>e.value).filter(e=>e.value!==void 0).sort((e,t)=>n===`asc`?e.value-t.value:t.value-e.value);r[o]={};for(let e of c){let n=au(Yl(this,i,e.domain)),a=l[su(e.rowDomain,t)];if(!a)continue;let s=a.findIndex(t=>t.value===e.value);s!==-1&&(r[o][n]=s+1)}}return i===`row`?r:Yt(r)}computeRunningTotal(e,t,n){let r={},i=ru(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=Pa(o));for(let s of o){let o=au(Yl(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:Yl(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>nu(t,e.rowDomain));for(let e of l){let n=au(e.rowDomain),i=cu(e.rowDomain,t),a=(c[i]||0)+e.value;c[i]=a,r[o][n]=a}if(n===`%_running_total`)for(let e of l){let n=e.rowDomain,i=au(n),a=cu(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:Yt(r)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=Jl(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=Jl(this,t).colDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,n,r){let i=r===`(previous)`||r===`(next)`?iu(this,t,n,r):tu(t,n,r);if(C(i,t))return`sameValue`;if(!i||!Zl(this,i))throw new aa;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}}return t}let AR=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function jR(e){return AR.includes(e.type)}var MR=class extends ${static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotIdFromPosition`,`getPivotIdsFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`];pivots={};unusedPivots;custom;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){switch(e.type){case`START`:for(let e of this.getters.getPivotIds())this.setupPivot(e)}}handle(e){if(Ri.has(e.type))for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0});switch(e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.unusedPivots?.push(e.pivotId),this.setupPivot(e.pivotId);break;case`DUPLICATE_PIVOT`:this.unusedPivots?.push(e.newPivotId),this.setupPivot(e.newPivotId);break;case`UPDATE_PIVOT`:this.setupPivot(e.pivotId,{recreate:!0});break;case`DELETE_SHEET`:case`UPDATE_CELL`:this.unusedPivots=void 0;break;case`UNDO`:case`REDO`:{this.unusedPivots=void 0;let t=e.commands.filter(jR);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:kF();break}}getPivotIdFromPosition(e){return this.getPivotIdsFromPosition(e)[0]}getPivotIdsFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getPivotIdsFromFormula(e.sheetId,t.compiledFormula):[]}getPivotIdsFromFormula(e,t){return this.getPivotFunctions(e,t.tokens).map(e=>{let t=e.args[0]?.toString();return t&&this.getters.getPivotId(t)}).filter(S)}isSpillPivotFormula(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens)?.functionName===`PIVOT`:!1}getPivotFunctions(e,t){let n=KE(t);if(!n.length)return[];let r=[];for(let t of n){let{functionName:n,args:i}=t,a=i.map(t=>{if(t.type===`EMPTY`)return;if(t.type===`STRING`||t.type===`BOOLEAN`||t.type===`NUMBER`)return t.value;let n=bC(t);return this.getters.evaluateFormula(e,n)});r.push({functionName:n,args:a})}return r}getFirstPivotFunction(e,t){return this.getPivotFunctions(e,t)[0]}getPivotCellFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||qE(t.compiledFormula.tokens)===0)return gF;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!r)return gF;let{functionName:i,args:a}=r,o=a[0];if(!o)return gF;let s=this.getters.getPivotId(o.toString());if(!s)return gF;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!t.content.replaceAll(` `,``).toUpperCase().startsWith(`=PIVOT`))return gF;try{if(i===`PIVOT`){let t=El(a[2]),r=t===void 0?!0:L(t),i=El(a[3]),o=i===void 0?!0:L(i),s=c.getTableStructure().getPivotCells(r,o),l=e.col-n.col,u=e.row-n.row;return s[l][u]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>A(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`)return{type:`HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})))};let[o,...s]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(s.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return gF}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName),n=1,r=E(`Calculated measure %s`,n);for(;t.includes(r);)n++,r=E(`Calculated measure %s`,n);return r}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){return this._getUnusedPivots().includes(e)}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=y(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=kR(jF.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivots(){if(this.unusedPivots!==void 0)return this.unusedPivots;let e=new Set(this.getters.getPivotIds());for(let t of this.getters.getSheetIds())for(let n in this.getters.getCells(t)){let t=this.getters.getCellPosition(n),r=this.getPivotIdsFromPosition(t);for(let t of r)if(e.delete(t),!e.size)return this.unusedPivots=[],[]}for(let t of this.getters.getPivotIds()){let n=this.getters.getPivotCoreDefinition(t);for(let r of n.measures)if(r.computedBy){let{sheetId:n}=r.computedBy,i=this.getters.getMeasureCompiledFormula(t,r),a=this.getPivotIdsFromFormula(n,i);for(let t of a)if(e.delete(t),!e.size)return this.unusedPivots=[],[]}}return this.unusedPivots=[...e],this.unusedPivots}},NR=class{cells;getters;index=0;direction;constructor(e,t,n){this.cells=e,this.getters=t,this.direction=n}next(){let e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:n,tooltip:r}=$E.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:n,tooltip:r,origin:{col:e.data.col,row:e.data.row}}}},PR=class extends ${static layers=[`Autofill`];static getters=[`getAutofillTooltip`];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case`AUTOFILL_SELECT`:let t=this.getters.getActiveSheetId();return this.lastCellSelected.col=e.col===-1?this.lastCellSelected.col:b(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=e.row===-1?this.lastCellSelected.row:b(e.row,0,this.getters.getNumberRows(t)),this.lastCellSelected.col!==void 0&&this.lastCellSelected.row!==void 0?`Success`:`InvalidAutofillSelection`}return`Success`}handle(e){switch(e.type){case`AUTOFILL`:this.autofill(!0);break;case`AUTOFILL_SELECT`:this.select(e.col,e.row);break;case`AUTOFILL_AUTO`:this.autofillAuto();break}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||this.direction===void 0){this.tooltip=void 0;return}let t=this.getters.getSelectedZone(),n=this.autofillZone,r=[];switch(this.direction){case`down`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.top;n<=t.bottom;n++)i.push(w(e,n));let a=this.createGenerator(i);for(let t=n.top;t<=n.bottom;t++)r.push(this.computeNewCell(a,e,t))}break;case`up`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.bottom;n>=t.top;n--)i.push(w(e,n));let a=this.createGenerator(i);for(let t=n.bottom;t>=n.top;t--)r.push(this.computeNewCell(a,e,t))}break;case`left`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.right;n>=t.left;n--)i.push(w(n,e));let a=this.createGenerator(i);for(let t=n.right;t>=n.left;t--)r.push(this.computeNewCell(a,t,e))}break;case`right`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.left;n<=t.right;n++)i.push(w(n,e));let a=this.createGenerator(i);for(let t=n.left;t<=n.right;t++)r.push(this.computeNewCell(a,t,e))}break}if(e){let e={},t={},n={},i=this.getters.getActiveSheetId();for(let a of r)this.collectBordersData(a,e),this.autofillMerge(i,a),this.autofillCell(i,a),this.collectConditionalFormatsData(i,a,t),this.collectDataValidationsData(i,a,n);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,n),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){let n=JSON.stringify(e.border);n in t||(t[n]=[]),t[n].push(D({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s=this.getters.getRulesByCell(e,r,i),c=w(a,o);for(let e of s)e.id in n||(n[e.id]=[]),n[e.id].push(c)}collectDataValidationsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s={sheetId:e,col:r,row:i},c=this.getters.getValidationRuleForCell(s);c&&(c.id in n||(n[c.id]=[]),n[c.id].push(D({col:a,row:o})))}autofillCell(e,t){this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t.col,row:t.row,content:t.content||``,style:t.style||null,format:t.format||``}),this.dispatch(`AUTOFILL_CELL`,t)}autofillBorders(e,t){for(let n in t){let r=n===`undefined`?void 0:JSON.parse(n);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,border:r,target:T(t[n])})}}autofillConditionalFormats(e,t){for(let n in t){let r=t[n],i=this.getters.getConditionalFormats(e).find(e=>e.id===n);if(!i)continue;let a=this.getters.getAdaptedCfRanges(e,i,r.map(Qn),[]);a&&this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:i.id,rule:i.rule,stopIfTrue:i.stopIfTrue},ranges:a,sheetId:e})}}autofillDataValidations(e,t){for(let n in t){let r=t[n],i=this.getters.getDataValidationRule(e,n);if(!i)continue;let a=T(i.ranges.map(e=>e.zone).concat(r),[]);this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:i,ranges:a.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}select(e,t){let n=this.getters.getSelectedZone();if(dr(e,t,n)){this.autofillZone=void 0;return}switch(this.direction=this.getDirection(e,t),this.direction){case`up`:this.saveZone(t,n.top-1,n.left,n.right),this.steps=n.top-t;break;case`down`:this.saveZone(n.bottom+1,t,n.left,n.right),this.steps=t-n.bottom;break;case`left`:this.saveZone(n.top,n.bottom,e,n.left-1),this.steps=n.left-e;break;case`right`:this.saveZone(n.top,n.bottom,n.right+1,e),this.steps=e-n.right;break}this.autofill(!1)}autofillAuto(){let e=this.getters.getActivePosition(),t=this.getters.getTable(e),n=t?t.range.zone.bottom:this.getAutofillAutoLastRow(),r=this.getters.getSelectedZone();for(let t=r.bottom+1;t<=n;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==`empty`){n=t-1;break}n>r.bottom&&(this.select(e.col,n),this.autofill(!0))}getAutofillAutoLastRow(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId(),n=e.left,r=e.bottom;if(n>0){let e={sheetId:t,col:n-1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n-1,row:r}}if(r===e.bottom&&(n=e.right,n<=this.getters.getNumberCols(t))){let e={sheetId:t,col:n+1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n+1,row:r}}return r-1}computeNewCell(e,t,n){let{cellData:r,tooltip:i,origin:a}=e.next(),{content:o,style:s,border:c,format:l}=r;return this.tooltip=i,{originCol:a.col,originRow:a.row,col:t,row:n,content:o,style:s,border:c,format:l}}getRule(e,t){let n=eD.getAll().sort((e,t)=>e.sequence-t.sequence).find(n=>n.condition(e,t));return n&&this.direction&&n.generateRule(e,t,this.direction)}createGenerator(e){let t=[],n=[],r=this.getters.getActiveSheetId();for(let t of e){let{col:e,row:i}=Pn(t),a=this.getters.getCell({sheetId:r,col:e,row:i});n.push({col:e,row:i,cell:a,sheetId:r})}let i=n.map(e=>e.cell);for(let e of n){let n={type:`COPY_MODIFIER`};e&&e.cell&&(n=this.getRule(e.cell,i)||n);let r=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:r},rule:n})}return new NR(t,this.getters,this.direction)}saveZone(e,t,n,r){this.autofillZone={top:e,bottom:t,left:n,right:r}}getDirection(e,t){let n=this.getters.getSelectedZone(),r={up:{number:n.top-t,value:`up`},down:{number:t-n.bottom,value:`down`},left:{number:n.left-e,value:`left`},right:{number:e-n.right,value:`right`}};if(Object.values(r).map(e=>+(e.number>0)).reduce((e,t)=>e+t)===1)return Object.values(r).find(e=>+(e.number>0)).value;let i=r.up.number>0?`up`:`down`,a=r.left.number>0?`left`:`right`;return Math.abs(r[i].number)>=Math.abs(r[a].number)?r[i].value:r[a].value}autofillMerge(e,t){let{originCol:n,originRow:r,col:i,row:a}=t,o={sheetId:e,col:i,row:a},s={sheetId:e,col:n,row:r};if(this.getters.isInMerge(o)&&!this.getters.isInMerge(s)){let t=this.getters.getMerge(o);t&&this.dispatch(`REMOVE_MERGE`,{sheetId:e,target:[t]})}let c=this.getters.getMerge(s);c?.left===n&&c?.top===r&&this.dispatch(`ADD_MERGE`,{sheetId:e,target:[{top:a,bottom:a+c.bottom-c.top,left:i,right:i+c.right-c.left}]})}drawLayer(e){if(!this.autofillZone)return;let{ctx:t,thinLineWidth:n}=e,{x:r,y:i,width:a,height:o}=this.getters.getVisibleRect(this.autofillZone);a>0&&o>0&&(t.strokeStyle=`black`,t.lineWidth=n,t.setLineDash([3]),t.strokeRect(r,i,a,o),t.setLineDash([]))}},FR=class extends ${static getters=[`getAutomaticSums`];handle(e){switch(e.type){case`SUM_SELECTION`:let e=this.getters.getActiveSheetId(),{zones:t,anchor:n}=this.getters.getSelection();for(let r of t){let t=this.getAutomaticSums(e,r,n.cell);this.dispatchCellUpdates(e,t)}break}}getAutomaticSums(e,t,n){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,n):this.sumData(e,t)}sumData(e,t){let n=this.dimensionsToSum(e,t),r=this.sumDimensions(e,t,n).filter(({zone:t})=>!this.getters.isEmpty(e,t));return n.has(`ROW`)&&n.has(`COL`)&&r.push(this.sumTotal(t)),r}sumAdjacentData(e,t,n){let{col:r,row:i}=dr(n.col,n.row,t)?n:{col:t.left,row:t.top},a=this.findAdjacentData(e,r,i);return a?this.getters.isSingleCellOrMerge(e,t)||mr(or(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,or(a,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,n){let r=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.findSuitableZoneToSum(r,i.col,i.row);if(a)return this.getters.expandZone(e,a)}findSuitableZoneToSum(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:n-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:n});if(this.isNumber(i)&&!this.isNumber(r))return this.findHorizontalZone(e,t,n);let a=this.findVerticalZone(e,t,n);if(this.isZoneValid(a))return a;let o=this.findHorizontalZone(e,t,n);if(this.isZoneValid(o))return o}findVerticalZone(e,t,n){let r={top:0,bottom:n-1,left:t,right:t},i=this.reduceZoneStart(e,r,r.bottom);return{...r,top:i}}findHorizontalZone(e,t,n){let r={top:n,bottom:n,left:0,right:t-1},i=this.reduceZoneStart(e,r,r.right);return{...r,left:i}}reduceZoneStart(e,t,n){let r=this.getters.getEvaluatedCellsInZone(e.id,t),i=x(n,-1,-1),a=Gt(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=ct(i.filter(e=>this.isNumber(r[e])))[0]||[];return Gt(o)<a?1/0:Kt(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&Go(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){let n=new Set;return mr(t)?(n.add(pr(t).numberOfCols===1?`COL`:`ROW`),n):(this.lastColIsEmpty(e,t)&&n.add(`ROW`),this.lastRowIsEmpty(e,t)&&n.add(`COL`),n.size===0&&n.add(`COL`),n)}sumDimensions(e,t,n){return[...n.has(`COL`)?this.sumColumns(t,e):[],...n.has(`ROW`)?this.sumRows(t,e):[]]}sumTotal(e){let{bottom:t,right:n}=e;return{position:{col:n,row:t},zone:{...e,top:t,right:n-1}}}sumColumns(e,t){let n=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,n.bottom-1)},_r(n).map(t=>({position:t,zone:{...e,right:t.col,left:t.col}}))}sumRows(e,t){let n=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,n.right-1)},_r(n).map(t=>({position:t,zone:{...e,top:t.row,bottom:t.row}}))}dispatchCellUpdates(e,t){for(let n of t){let{col:t,row:r}=n.position;this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:`=SUM(${this.getters.zoneToXC(e,n.zone)})`})}}nextEmptyRow(e,t){let n=t.bottom+1,{left:r,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:n,top:n,left:r,right:i});)n++;return{...t,top:n,bottom:n}}nextEmptyCol(e,t){let n=t.right+1,{top:r,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:n,right:n,top:r,bottom:i});)n++;return{...t,left:n,right:n}}transpose(e){return new Set([...e.values()].map(e=>e===`COL`?`ROW`:`COL`))}};CN.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],qR),CN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],qR),CN.addTransformation(`ADD_COLUMNS_ROWS`,[`CREATE_CHART`,`UPDATE_CHART`],VR),CN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`CREATE_CHART`,`UPDATE_CHART`],VR),CN.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],zR),CN.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`],BR),CN.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],HR),CN.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],UR),CN.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],WR),CN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],WR),CN.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],GR),CN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],GR),CN.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],KR),CN.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],JR),CN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],JR),CN.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],RR),CN.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],LR),CN.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],IR),CN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],IR);function IR(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=td(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function LR(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function RR(e,t){if(e.pivotId!==t.pivotId)return e}function zR(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function BR(e,t){if(e.id!==t.id)return e}function VR(e,t){return{...e,definition:vk(e.definition,t)}}function HR(e,t){return e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`}),e.name===t.name?{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,e=>(parseInt(e)+1).toString()):`${e.name}~`,position:e.position+1}:e}function UR(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!ur(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function WR(e,t){if(e.sheetId!==t.sheetId||(e.type===`FREEZE_COLUMNS`?`COL`:`ROW`)!==t.dimension)return e;let n=e.quantity;if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);for(let t of e)n>t&&n--}if(t.type===`ADD_COLUMNS_ROWS`){let e=t.position===`before`?t.base-1:t.base;n=n>e?n+t.quantity:n}return n>0?{...e,quantity:n}:void 0}function GR(e,t){if(e.sheetId!==t.sheetId)return e;let n=td(e.zone,t);if(!n)return;let r=e.newTableRange?nd(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function KR(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:Om.styleId}}:e}function qR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=Qs(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=Zs(Ot(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function JR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n=x(e.start,e.end+1),r=[];if(t.type===`REMOVE_COLUMNS_ROWS`?r=Qs(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=Zs(Ot(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}let YR=[{match:Mi,fn:$R},{match:Pi,fn:ez},{match:Li,fn:tz},{match:Ii,fn:iz},{match:Ni,fn:rz},{match:Fi,fn:nz}];function XR(e,t){let n=CN.getTransformation(e.type,t.type);return n?n(e,t):QR(e,t)}function ZR(e,t){let n=[...e],r=new Set(CN.getKeys());for(let e of t)r.has(e.type)&&(n=n.reduce((t,n)=>{let r=XR(n,e);return r&&t.push(r),t},[]));return n}function QR(e,t){for(let{match:n,fn:r}of YR)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function $R(e,t){if(!(`sheetId`in t))return e;let n=t.type===`DELETE_SHEET`&&t.sheetId;return e.sheetId===n?`IGNORE_COMMAND`:e.type===`CREATE_SHEET`||t.type===`CREATE_SHEET`||e.sheetId!==t.sheetId?e:`SKIP_TRANSFORMATION`}function ez(e,t){let n=$R(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=td(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function tz(e,t){let n=$R(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=td(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function nz(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>nd(e,t)).filter(S);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function rz(e,t){let n=$R(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;if(t.type!==`ADD_COLUMNS_ROWS`&&t.type!==`REMOVE_COLUMNS_ROWS`)return`SKIP_TRANSFORMATION`;if(t.dimension!==e.dimension)return e;let r=[];return t.type===`REMOVE_COLUMNS_ROWS`?r=Qs(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=Zs(Ot(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function iz(e,t){let n=$R(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?az(e,t):t.type===`ADD_MERGE`?oz(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function az(e,t){let n=t.dimension===`COL`?`col`:`row`,r=e[n];if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);if(e.includes(r))return`IGNORE_COMMAND`;for(let t of e)r>=t&&r--}return t.type===`ADD_COLUMNS_ROWS`&&(r>t.base||r===t.base&&t.position===`before`)&&(r+=t.quantity),{...e,[n]:r}}function oz(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&dr(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var sz=class{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,n,r,i,a){this.rootCommand=r,this.timestamp=a,this.id=e,this.clientId=t,this._commands=[...n],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}},cz=class extends Error{},lz=class extends rd{revisions;transportService;serverRevisionId;clients={};clientId=`local`;debouncedMove;pendingMessages=[];waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new wc;lastLocalOperation;constructor(e,t,n=Ve){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.debouncedMove=Ct(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new sz(this.uuidGenerator.uuidv4(),this.clientId,t,e,n,Date.now());this.revisions.append(r.id,r),e.type!==`REQUEST_REDO`&&(this.lastLocalOperation=r),this.trigger(`new-local-state-update`,{id:r.id}),this.sendUpdateMessage({type:`REMOTE_REVISION`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:r.id,clientId:r.clientId,commands:r.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_UNDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:`local`,name:`local`},this.clientId=`local`),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this))}loadInitialMessages(e){let t=performance.now(),n=e.reduce((e,t)=>e+(t.type===`REMOTE_REVISION`?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(let t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug(`Replayed`,n,`commands in`,performance.now()-t,`ms`)}async leave(e){e&&Object.keys(this.clients).length===1&&this.lastRevisionMessage&&this.lastRevisionMessage?.type!==`SNAPSHOT_CREATED`&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:`CLIENT_LEFT`,clientId:this.clientId,version:1})}async snapshot(e){if(this.pendingMessages.length!==0)return;let t=this.uuidGenerator.uuidv4();await this.transportService.sendMessage({type:`SNAPSHOT`,nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){let e=this.clients[this.clientId];if(!e)throw new cz(`The client left the session`);return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(S))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return this.pendingMessages.length===0}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId])return;let t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;let n=t?`CLIENT_MOVED`:`CLIENT_JOINED`,r=this.getClient();this.clients[this.clientId]={...r,position:e},this.transportService.sendMessage({type:n,version:1,client:{...r,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){if(this.isWrongServerRevisionId(e)){this.trigger(`unexpected-revision-id`);return}switch(e.type){case`CLIENT_MOVED`:this.onClientMoved(e);break;case`CLIENT_JOINED`:this.onClientJoined(e);break;case`CLIENT_LEFT`:this.onClientLeft(e);break;case`REVISION_REDONE`:this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-redone`,{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case`REVISION_UNDONE`:this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-undone`,{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case`REMOTE_REVISION`:let{clientId:t,commands:n,timestamp:r}=e,i=new sz(e.nextRevisionId,t,n,void 0,void 0,r);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);let t=this.pendingMessages.filter(e=>e.type===`REMOTE_REVISION`).map(e=>e.commands).flat();this.trigger(`remote-revision-received`,{commands:ZR(n,t)})}break;case`SNAPSHOT_CREATED`:{let t=new sz(e.nextRevisionId,`server`,[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger(`snapshot`),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger(`collaborative-event-received`)}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;let t=this.clients[this.clientId];if(t){let{position:e}=t;e&&this.transportService.sendMessage({type:`CLIENT_MOVED`,version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),!this.waitingAck&&this.sendPendingMessage()}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if(e.type===`REMOTE_REVISION`){let t=this.revisions.get(e.nextRevisionId);t.commands.length===0&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.
1891
- ${JSON.stringify(e)}`);this.waitingAck=!0,this.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch((e.type===`REVISION_UNDONE`||e.type===`REVISION_REDONE`)&&(this.waitingUndoRedoAck=!1),e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`SNAPSHOT_CREATED`:this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.lastRevisionMessage=e,this.sendPendingMessage();break;case`REVISION_UNDONE`:{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId);let t=this.pendingMessages.findIndex(e=>e.type===`REMOTE_REVISION`);t!==-1&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}isAlreadyProcessed(e){if(e.type===`CLIENT_MOVED`&&e.client.id===this.clientId)return!0;switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter(({type:e})=>e!==`REVISION_REDONE`&&e!==`REVISION_UNDONE`)}};function uz(e){return e[Math.floor(Math.random()*e.length)]}let dz=[`#ff851b`,`#0074d9`,`#7fdbff`,`#b10dc9`,`#39cccc`,`#f012be`,`#3d9970`,`#111111`,`#ff4136`,`#aaaaaa`,`#85144b`,`#001f3f`];var fz=class extends ${static getters=[`getClientsToDisplay`,`getClient`,`getConnectedClients`,`isFullySynchronized`];static layers=[`Selection`];availableColors=new Set(dz);colors={};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)}chooseNewColor(){this.availableColors.size===0&&(this.availableColors=new Set(dz));let e=uz([...this.availableColors.values()]);return this.availableColors.delete(e),e}getClient(){return this.session.getClient()}getConnectedClients(){return this.session.getConnectedClients()}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getClient()}catch(e){if(e instanceof cz)return[];throw e}let e=this.getters.getActiveSheetId(),t=[];for(let n of this.getters.getConnectedClients())if(n.id!==this.getters.getClient().id&&n.position&&n.position.sheetId===e&&this.isPositionValid(n.position)){let e=n.position;this.colors[n.id]||(this.colors[n.id]=this.chooseNewColor());let r=this.colors[n.id];t.push({...n,position:e,color:r})}return t}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getters.getActiveSheetId();for(let e of this.getClientsToDisplay()){let{row:i,col:a}=e.position,o=this.getters.expandZone(r,{top:i,bottom:i,left:a,right:a}),{x:s,y:c,width:l,height:u}=this.getters.getVisibleRect(o);if(l<=0||u<=0)continue;let d=e.color;t.fillStyle=`${d}10`,t.lineWidth=4*n,t.strokeStyle=d,t.globalCompositeOperation=`multiply`,t.fillRect(s,c,l,u),t.globalCompositeOperation=`source-over`,t.strokeRect(s,c,l,u),t.font=`bold ${Re+1}px ${ze}`}}},pz=class extends ${allowDispatch(e){switch(e.type){case`REMOVE_DUPLICATES`:return this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique))}return`Success`}handle(e){switch(e.type){case`REMOVE_DUPLICATES`:this.removeDuplicates(e.columns,e.hasHeader);break;case`TRIM_WHITESPACE`:this.trimWhitespace();break}}removeDuplicates(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getSelectedZone();t&&(r.top+=1);let i=this.getUniqueRowsIndexes(n,r.top,r.bottom,e),a=i.length;if(a===pr(r).numberOfRows){this.notifyRowsRemovedAndRemaining(0,a);return}let o=i.map(e=>({left:r.left,top:e,right:r.right,bottom:e})),s=new Wu(this.getters,this.dispatch),c=s.copy(Tc(n,o));if(!c)return;this.dispatch(`CLEAR_CELLS`,{target:[r],sheetId:n});let l={left:r.left,top:r.top,right:r.left,bottom:r.top};s.paste({zones:[l],sheetId:n},c,{isCutOperation:!1});let u={left:r.left,top:r.top-+!!t,right:r.right,bottom:r.top+a-1};this.selection.selectZone({cell:{col:u.left,row:u.top},zone:u});let d=r.bottom-r.top+1-a;this.notifyRowsRemovedAndRemaining(d,a)}getUniqueRowsIndexes(e,t,n,r){let i=new Map;for(let a of x(t,n+1)){let t=r.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:a}).value);Object.values(i).some(e=>C(e,t))||(i[a]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:`info`,text:E(`%s duplicate rows found and removed.
1892
- %s unique rows remain.`,e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return this.getters.getSelectedZones().length===1?`Success`:`MoreThanOneRangeSelected`}checkNoMergeInZone(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?`WillRemoveExistingMerge`:`Success`}checkRangeContainsValues(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedZone();return e.hasHeader&&(n.top+=1),this.getters.getEvaluatedCellsInZone(t,n).every(e=>e.type===`empty`)?`EmptyTarget`:`Success`}checkNoColumnProvided(e){return e.columns.length===0?`NoColumnsProvided`:`Success`}checkColumnsIncludedInZone(e){let t=this.getters.getSelectedZone();return e.columns.some(e=>e<t.left||e>t.right)?`ColumnsNotIncludedInZone`:`Success`}checkColumnsAreUnique(e){return e.columns.length===new Set(e.columns).size?`Success`:`DuplicatesColumnsSelected`}trimWhitespace(){let e=T(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(_r).flat()){let e=this.getters.getCell({col:r,row:i,sheetId:t});if(!e)continue;let a=Ht(e.content);a!==e.content&&(n+=1,this.dispatch(`UPDATE_CELL`,{sheetId:t,col:r,row:i,content:a}))}let r=n?E(`Trimmed whitespace from %s cells.`,n):E(`No selected cells had whitespace trimmed.`);this.ui.notifyUI({type:`info`,text:r,sticky:!1})}},mz=class extends ${handle(e){switch(e.type){case`SET_DECIMAL`:this.setDecimal(e.sheetId,e.target,e.step);break;case`SET_FORMATTING_WITH_PIVOT`:this.setContextualFormat(e.sheetId,e.target,e.format);break}}setContextualFormat(e,t,n){let r=[],i={};for(let n of T(t))for(let t=n.left;t<=n.right;t++)for(let a=n.top;a<=n.bottom;a++){let n={sheetId:e,col:t,row:a},o=this.getters.getPivotCellFromPosition(n);if(this.isSpilledPivotValueFormula(n,o)){r.push(n);let e=this.getters.getPivotIdFromPosition(n)||``;i[e]??=new Set,i[e].add(o.measure)}}let a=T(r.map(D));for(let e in i){let t=i[e],r=this.getters.getPivotCoreDefinition(e);this.dispatch(`UPDATE_PIVOT`,{pivotId:e,pivot:{...r,measures:r.measures.map(e=>t.has(e.id)?{...e,format:n}:e)}})}this.dispatch(`SET_FORMATTING`,{sheetId:e,target:a,format:``}),this.dispatch(`SET_FORMATTING`,{sheetId:e,target:T(t,a),format:n})}isSpilledPivotValueFormula(e,t){let n=this.getters.getCell(e);return t.type===`VALUE`&&!n?.isFormula}setDecimal(e,t,n){let r={};for(let i of T(t))for(let t of _r(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=cs(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=T(r[t].map(e=>D(e)));this.setContextualFormat(e,n,t)}}getCellNumberFormat(e){for(let t of[e]){let e=this.getters.getEvaluatedCell(t);if(e.type===`number`&&!(e.format&&Go(e.format)))return e.format||Yo(e.value)}}},hz=class extends ${static getters=[`getNextVisibleCellPosition`,`findVisibleHeader`,`findLastVisibleColRowIndex`,`findFirstVisibleColRowIndex`,`isRowHidden`,`isColHidden`,`isHeaderHidden`];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,n){return t===`COL`?this.isColHidden(e,n):this.isRowHidden(e,n)}getNextVisibleCellPosition({sheetId:e,col:t,row:n}){return{sheetId:e,col:this.findVisibleHeader(e,`COL`,t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,`ROW`,n,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,n,r){if(n<=r){for(let i=n;i<=r;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}if(n>r){for(let i=n;i>=r;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}}findLastVisibleColRowIndex(e,t,{last:n,first:r}){return x(n,r,-1).find(n=>!this.isHeaderHidden(e,t,n))||r}findFirstVisibleColRowIndex(e,t){let n=this.getters.getNumberHeaders(e,t);for(let r=0;r<n;r++)if(t===`COL`&&!this.isColHidden(e,r)||t===`ROW`&&!this.isRowHidden(e,r))return r}exportForExcel(e){for(let t of e.sheets)for(let[e,n]of Object.entries(t.rows))n.isHidden=this.isRowHidden(t.id,Number(e))}},gz=class extends ${static getters=[];allowDispatch(e){switch(e.type){case`DUPLICATE_PIVOT_IN_NEW_SHEET`:if(!this.getters.isExistingPivot(e.pivotId))return`PivotIdNotFound`;if(!this.getters.getPivot(e.pivotId).isValid())return`PivotInError`;break}return`Success`}handle(e){switch(e.type){case`INSERT_NEW_PIVOT`:this.insertNewPivot(e.pivotId,e.newSheetId);break;case`DUPLICATE_PIVOT_IN_NEW_SHEET`:this.duplicatePivotInNewSheet(e.pivotId,e.newPivotId,e.newSheetId);break;case`INSERT_PIVOT_WITH_TABLE`:this.insertPivotWithTable(e.sheetId,e.col,e.row,e.pivotId,e.table,e.pivotMode);break;case`SPLIT_PIVOT_FORMULA`:this.splitPivotFormula(e.sheetId,e.col,e.row,e.pivotId)}}insertNewPivot(e,t){Er(this.getters.getSelectedZone())===1&&this.selection.selectTableAroundSelection();let n=this.getters.getActiveSheetId();this.dispatch(`ADD_PIVOT`,{pivotId:e,pivot:{dataSet:{zone:this.getters.getSelectedZone(),sheetId:n},columns:[],rows:[],measures:[],name:E(`New pivot`),type:`SPREADSHEET`}});let r=this.getters.getSheetIds().findIndex(e=>e===n)+1,i=this.getters.getPivotFormulaId(e);this.dispatch(`CREATE_SHEET`,{sheetId:t,name:E(`Pivot #%(formulaId)s`,{formulaId:i}),position:r}),this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:n,sheetIdTo:t});let a=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,a.getTableStructure().export(),`dynamic`)}duplicatePivotInNewSheet(e,t,n){this.dispatch(`DUPLICATE_PIVOT`,{pivotId:e,newPivotId:t,duplicatedPivotName:E(`%s (copy)`,this.getters.getPivotCoreDefinition(e).name)});let r=this.getters.getActiveSheetId(),i=this.getters.getSheetIds().indexOf(r)+1,a=this.getters.getPivotFormulaId(t),o=this.getters.getPivotName(t);if(this.dispatch(`CREATE_SHEET`,{sheetId:n,name:this.getPivotDuplicateSheetName(E(`%(newPivotName)s (Pivot #%(formulaId)s)`,{newPivotName:o,formulaId:a})),position:i}).isSuccessful){this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:r,sheetIdTo:n});let i=this.getters.getPivot(e);this.insertPivotWithTable(n,0,0,t,i.getTableStructure().export(),`dynamic`)}}getPivotDuplicateSheetName(e){let t=1,n=this.getters.getSheetIds().map(e=>this.getters.getSheetName(e)),r=st(e),i=r;for(;n.includes(i);)i=`${r} (${t})`,t++;return i}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new hF(o,s,c,l||{}),d=u.columns.length-1;this.resizeSheet(e,t,n,u);let f=this.getters.getPivotFormulaId(r),p;a===`dynamic`?(this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:n,content:`=PIVOT(${f})`}),p={left:t,right:t,top:n,bottom:n}):(this.dispatch(`INSERT_PIVOT`,{sheetId:e,col:t,row:n,pivotId:r,table:u.export()}),p={left:t,right:t+u.getNumberOfDataColumns(),top:n,bottom:n+d+u.rows.length}),this.dispatch(`CREATE_TABLE`,{tableType:a,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,p)],config:{...Ze,numberOfHeaders:d}})}resizeSheet(e,t,n,r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,quantity:s-l,position:`after`})}splitPivotFormula(e,t,n,r){let i=this.getters.getSpreadZone({sheetId:e,col:t,row:n});if(!i)return;let a=this.getters.getPivotFormulaId(r),o=new Map;for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++){let r={sheetId:e,col:t,row:n};o.set(r,this.getters.getPivotCellFromPosition(r))}for(let[e,t]of o)this.dispatch(`UPDATE_CELL`,{...e,content:Fu(a,t)});if(this.getters.getCoreTable({sheetId:e,col:t,row:n})?.type===`dynamic`){let r=D({col:t,row:n}),a=this.getters.getRangeDataFromZone(e,i);this.dispatch(`UPDATE_TABLE`,{sheetId:e,zone:r,newTableRange:a,tableType:`static`})}}},_z=class extends ${allowDispatch(e){switch(e.type){case`SORT_CELLS`:if(!dr(e.col,e.row,e.zone))throw Error(E(`The anchor must be part of the provided zone`));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return`Success`}handle(e){switch(e.type){case`SORT_CELLS`:this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{});break}}checkMerge({sheetId:e,zone:t}){return this.getters.doesIntersectMerge(e,t)&&_r(t).some(({col:t,row:n})=>!this.getters.isInMerge({sheetId:e,col:t,row:n}))?`InvalidSortZone`:`Success`}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return`Success`;let n=this.getters.getMerges(e).filter(e=>ur(e,t)),r=pr(n[0]),[i,a]=[r.numberOfCols,r.numberOfRows];return n.every(e=>{let[t,n]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&n===a})?`Success`:`InvalidSortZone`}hasHeader(e,t){if(t[0].length===1)return!1;let n=t.map(t=>t.map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).type));return n[0][0]===`empty`&&(n=n.slice(1)),n.some(e=>e[0]===`empty`)?!1:!!n.some(e=>e[1]!==`empty`&&e[0]!==e[1])}sortZone(e,t,n,r,i){let[a,o]=this.mainCellsSteps(e,n),s=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,c=Object.assign({},n),l=this.mainCells(e,n);!i.sortHeaders&&this.hasHeader(e,l)&&(c.top+=o),l=this.mainCells(e,c);let u=l[s-c.left],d=px(u.map(e=>this.getters.getEvaluatedCell(e)),r,!!i.emptyCellAsZero).map(e=>e.index),[f,p]=[l.length,l[0].length],m=[];for(let e=0;e<f;e++)for(let t=0;t<p;t++){let{col:n,row:r,sheetId:i}=l[e][d[t]],s=this.getters.getCell({sheetId:i,col:n,row:r}),u=c.left+e*a,f=c.top+t*o,p={sheetId:i,col:u,row:f,content:``};if(s){let e=s.content;if(s.isFormula){let t=this.getters.getCellPosition(s.id);e=this.getters.getTranslatedCellFormula(i,0,f-t.row,s.compiledFormula.tokens)}p.style=s.style,p.content=e,p.format=s.format}m.push(p)}m.forEach(e=>this.dispatch(`UPDATE_CELL`,e))}mainCellsSteps(e,t){let n=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[n?n.right-n.left+1:1,n?n.bottom-n.top+1:1]}mainCells(e,t){let[n,r]=this.mainCellsSteps(e,t),i=[],a=x(t.left,t.right+1,n),o=x(t.top,t.bottom+1,r);for(let t of a){let n=[];i.push(n);for(let r of o)n.push({sheetId:e,col:t,row:r})}return i}},vz=class extends ${static getters=[`shouldShowFormulas`];showFormulas=!1;handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.showFormulas=e.show;break}}shouldShowFormulas(){return this.showFormulas}},yz=class extends ${static getters=[`doesCellHaveGridIcon`,`getCellWidth`,`getCellIconSrc`,`getTextWidth`,`getCellText`,`getCellMultiLineText`,`getContiguousZone`];ctx=document.createElement(`canvas`).getContext(`2d`);allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case`AUTORESIZE_COLUMNS`:for(let t of e.cols){let n=this.getColMaxWidth(e.sheetId,t);n!==0&&this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:[t],dimension:`COL`,size:n,sheetId:e.sheetId})}break;case`AUTORESIZE_ROWS`:this.autoResizeRows(e.sheetId,e.rows);break}}getCellWidth(e){let t=this.getters.getCellComputedStyle(e),n=0,r=this.getters.getEvaluatedCell(e).formattedValue;if(r){let e=gc(this.ctx,r,t,void 0);n+=Math.max(...e.map(e=>sc(this.ctx,e,t)))}if(this.getters.getCellIconSrc(e)&&(n+=vc(t)),this.getters.doesCellHaveGridIcon(e)&&(n+=20),n===0)return 0;if(n+=8,t.wrapping===`wrap`){let t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,n)}return n}getCellIconSrc(e){let t=pf.getAll();for(let n of t){let t=n(this.getters,e);if(t)return t}}getTextWidth(e,t){return sc(this.ctx,e,t)}getCellText(e,t){let n=this.getters.getCell(e),r=this.getters.getLocale();if(t?.showFormula&&n?.isFormula)return ol(n.content,r);if(t?.showFormula&&!n?.content)return``;{let i=this.getters.getEvaluatedCell(e),a=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>sc(this.ctx,e,n?.style||{})}:void 0;return B(i.value,{format:i.format,locale:r,formatWidth:a})}}getCellMultiLineText(e,t){let n=this.getters.getCellStyle(e),r=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.formatWidth});return gc(this.ctx,r,n,t.wrapText?t.maxWidth:void 0)}doesCellHaveGridIcon(e){let t=this.getters.isFilterHeader(e),n=!this.getters.isReadonly()&&this.getters.cellHasListDataValidationIcon(e);return t||n}getContiguousZone(e,t){let n=t=>{for(let n of x(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:n,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:n,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(let n of x(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:n}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:n}))return{...t,right:t.right+1}}return t},r=!1,i=t;do{r=!1;let e=n(i);if(!lr(i,e)){r=!0,i=e;continue}}while(r);return i}isCellEmpty(e){let t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===`empty`}getColMaxWidth(e,t){let n=_r(this.getters.getColsZone(e,t,t)).map(t=>this.getCellWidth({sheetId:e,...t}));return Math.max(0,Gt(n))}checkSheetExists(e){return`sheetId`in e&&this.getters.tryGetSheet(e.sheetId)===void 0?`InvalidSheetId`:`Success`}checkZonesAreInSheet(e){let t=`sheetId`in e?e.sheetId:this.getters.tryGetActiveSheetId();if(`ranges`in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId)))return`InvalidSheetId`;let n=this.getters.getCommandZones(e);return!t&&n.length>0?`NoActiveSheet`:t&&n.length>0?this.getters.checkZonesExistInSheet(t,n):`Success`}autoResizeRows(e,t){let n=[];for(let r of t){let t=0;for(let n of this.getters.getRowCells(e,r)){let r=this.getters.getCellById(n);if(!r)continue;let i=this.getters.getCellPosition(r.id),a=this.getters.getColSize(e,i.col);if(r.isFormula||this.getters.getArrayFormulaSpreadingOn(i)){let e=this.getters.getEvaluatedCell(i).formattedValue,n=ic(this.ctx,e,r?.style,a);n>t&&n>23&&(t=n)}else{let e=r.content,n=ic(this.ctx,e,r?.style,a);n>=t&&n>23&&(t=0)}}n.push(t||null)}let r=new Map(n.map(e=>[e,[]]));for(let e=0;e<n.length;e++)r.get(n[e])?.push(t[e]);for(let[t,n]of r)this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:n,dimension:`ROW`,size:t,sheetId:e})}},bz=class extends ${static getters=[`getCellTableStyle`,`getCellTableBorder`];tableStyles={};handle(e){if(Ri.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(Sz(e)){`sheetId`in e?delete this.tableStyles[e.sheetId]:this.tableStyles={};return}}finalize(){for(let e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(let t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}getCellTableBorder(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}computeTableStyle(e,t){return Et(()=>{let{config:n,numberOfCols:r,numberOfRows:i}=this.getTableRuntimeConfig(e,t),a=XF(n,this.getters.getTableStyle(t.config.styleId),r,i),o=this.getTableMapping(e,t),s={borders:{},styles:{}};for(let e=0;e<r;e++){let t=o.colMapping[e];s.borders[t]={},s.styles[t]={};for(let n=0;n<i;n++){let r=o.rowMapping[n];s.borders[t][r]=a.borders[e][n],s.styles[t][r]=a.styles[e][n]}}return s})}getTableRuntimeConfig(e,t){let n=t.range.zone,r={...t.config},i=n.right-n.left+1,a=n.bottom-n.top+1;for(let i=n.top;i<=n.bottom;i++)this.getters.isRowHidden(e,i)&&(a--,i-n.top<t.config.numberOfHeaders&&(r.numberOfHeaders--,r.numberOfHeaders<0&&(r.numberOfHeaders=0)),i===n.bottom&&(r.totalRow=!1));for(let t=n.left;t<=n.right;t++)this.getters.isColHidden(e,t)&&(i--,t===n.left&&(r.firstColumn=!1),t===n.right&&(r.lastColumn=!1));return{config:r,numberOfCols:i,numberOfRows:a}}getTableMapping(e,t){let n={},r={},i=0,a=0,o=t.range.zone;for(let t=o.left;t<=o.right;t++)if(!this.getters.isColHidden(e,t)){n[i]=t,i++;for(let t=o.top;t<=o.bottom;t++)this.getters.isRowHidden(e,t)||(r[a]=t,a++)}return{colMapping:n,rowMapping:r}}};let xz=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 Sz(e){return xz.has(e.type)}var Cz=class extends ${static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles={};borders={};handle(e){if(Ri.has(e.type)||e.type===`UPDATE_CELL`||e.type===`SET_FORMATTING`||e.type===`CLEAR_FORMATTING`||e.type===`EVALUATE_CELLS`){this.styles={},this.borders={};return}if(Sz(e)){`sheetId`in e?(delete this.styles[e.sheetId],delete this.borders[e.sheetId]):(this.styles={},this.borders={});return}if(Vi.has(e.type)){this.styles={};return}if(Hi.has(e.type)){this.borders={};return}}getCellComputedBorder(e){let{sheetId:t,row:n,col:r}=e;return this.borders[t]?.[n]?.[r]===void 0?(this.borders[t]||(this.borders[t]={}),this.borders[t][n]||(this.borders[t][n]={}),this.borders[t][n][r]||(this.borders[t][n][r]=this.computeCellBorder(e)),this.borders[t][n][r]):this.borders[t][n][r]}getCellComputedStyle(e){let{sheetId:t,row:n,col:r}=e;return this.styles[t]?.[n]?.[r]===void 0?(this.styles[t]||(this.styles[t]={}),this.styles[t][n]||(this.styles[t][n]={}),this.styles[t][n][r]||(this.styles[t][n][r]=this.computeCellStyle(e)),this.styles[t][n][r]):this.styles[t][n][r]}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...jt(this.getters.getCellTableBorder(e)||{}),...jt(t)};return St(n)?null:n}computeCellStyle(e){let t=this.getters.getCell(e),n=this.getters.getCellConditionalFormatStyle(e),r={...jt(this.getters.getCellTableStyle(e)),...jt(t?.style),...jt(n)};return this.getters.getEvaluatedCell(e).link&&!r.textColor&&(r.textColor=le),r}},wz=class extends ${handle(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:if(e.rule.criterion.type===`isBoolean`){let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));for(let e of qs(t)){let t=this.getters.getCell(e),n=this.getters.getEvaluatedCell(e);if(!t?.content)this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`});else if(t?.content&&n.type===`empty`){let n;if(t.content.startsWith(`=`)){let r=this.getters.evaluateFormula(e.sheetId,t.content);n=(A(r)?r[0][0]:r)?.toString()}else n=t.content;(!n||!ut(n))&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}else n.type!==`boolean`&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}}}}};let Tz=[Ez,Dz,kz,Az];function Ez(e,t){return`sheetId`in t?{...y(t),sheetId:e.getActiveSheetId()}:t}function Dz(e,t){return!(`target`in t)||!Array.isArray(t.target)?t:{...y(t),target:e.getSelectedZones()}}function Oz(e,t){return`zone`in t?{...y(t),zone:e.getSelectedZone()}:t}function kz(e,t){if(!(`row`in t)||!(`col`in t))return t;let{col:n,row:r}=e.getActivePosition();return{...y(t),col:n,row:r}}function Az(e,t){return`ranges`in t?{...y(t),ranges:e.getSelectedZones().map(t=>e.getRangeDataFromZone(e.getActiveSheetId(),t))}:t}let jz=new wc;function Mz(e,t){return{...Ez(e,t),id:jz.smallUuid()}}function Nz(e,t){return{...Ez(e,t),figureId:jz.smallUuid()}}function Pz(e,t){let n=Ez(e,t);return n.figure.id=jz.smallUuid(),n}function Fz(e,t){let n=y(t);n.sheetId=jz.smallUuid();let r=t.name||e.getSheet(e.getActiveSheetId()).name,i=r.match(/(.+?)\d*$/)?.[1]||r;return n.name=e.getNextSheetName(i),n}function Iz(e,t){let n=e.getActivePosition();return{...Ez(e,t),base:t.dimension===`COL`?n.col:n.row}}function Lz(e,t){let n=e.getSelectedZone();return{...Ez(e,t),elements:t.dimension===`COL`?x(n.left,n.right+1):x(n.top,n.bottom+1)}}function Rz(e,t){let n=e.getSelectedZone();return{...y(t),zone:n}}function zz(e,t){let n=y(t),{top:r,bottom:i,left:a,right:o}=e.getSelectedZone();return`cols`in n?n.cols=x(a,o+1):`rows`in n&&(n.rows=x(r,i+1)),n}function Bz(e,t){let n=e.getSelectedZone();return{...Ez(e,t),col:n.left,row:n.top,zone:n}}function Vz(e,t){return{type:`REPEAT_PASTE`,pasteOption:y(t.pasteOption),target:e.getSelectedZones()}}function Hz(e,t){let n=e.getSelectedZone();return{...Ez(e,t),start:t.dimension===`COL`?n.left:n.top,end:t.dimension===`COL`?n.right:n.bottom}}let Uz=new h;Uz.add(`UPDATE_CELL`,Gz),Uz.add(`CLEAR_CELL`,Gz),Uz.add(`CLEAR_CELLS`,Gz),Uz.add(`DELETE_CONTENT`,Gz),Uz.add(`ADD_MERGE`,Gz),Uz.add(`REMOVE_MERGE`,Gz),Uz.add(`SET_FORMATTING`,Gz),Uz.add(`CLEAR_FORMATTING`,Gz),Uz.add(`SET_BORDER`,Gz),Uz.add(`CREATE_TABLE`,Gz),Uz.add(`REMOVE_TABLE`,Gz),Uz.add(`HIDE_SHEET`,Gz),Uz.add(`ADD_COLUMNS_ROWS`,Iz),Uz.add(`REMOVE_COLUMNS_ROWS`,Lz),Uz.add(`HIDE_COLUMNS_ROWS`,Lz),Uz.add(`RESIZE_COLUMNS_ROWS`,Lz),Uz.add(`CREATE_SHEET`,Fz),Uz.add(`CREATE_FIGURE`,Pz),Uz.add(`CREATE_CHART`,Mz),Uz.add(`CREATE_IMAGE`,Nz),Uz.add(`GROUP_HEADERS`,Hz),Uz.add(`UNGROUP_HEADERS`,Hz),Uz.add(`UNGROUP_HEADERS`,Hz),Uz.add(`UNFOLD_HEADER_GROUPS_IN_ZONE`,Oz),Uz.add(`FOLD_HEADER_GROUPS_IN_ZONE`,Oz);let Wz=new h;Wz.add(`PASTE`,Vz),Wz.add(`INSERT_CELL`,Rz),Wz.add(`DELETE_CELL`,Rz),Wz.add(`AUTORESIZE_COLUMNS`,zz),Wz.add(`AUTORESIZE_ROWS`,zz),Wz.add(`SORT_CELLS`,Bz),Wz.add(`SUM_SELECTION`,Gz),Wz.add(`SET_DECIMAL`,Gz);function Gz(e,t){let n=y(t);for(let t of Tz)n=t(e,n);return n}function Kz(e,t){if(t&&Uz.contains(t.type))return Uz.get(t.type)(e,t)}function qz(e,t,n){if(Wz.contains(t.type))return Wz.get(t.type)(e,t,n)}function Jz(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:Gi(e.rootCommand)?Uz.contains(e.rootCommand.type):Wz.contains(e.rootCommand.type)}function Yz(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return Gi(e.rootCommand)?Kz(t,e.rootCommand):qz(t,e.rootCommand,e.commands)}var Xz=class extends ${static getters=[`canUndo`,`canRedo`];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on(`new-local-state-update`,this,this.onNewLocalStateUpdate),this.session.on(`snapshot`,this,()=>{this.undoStack=[],this.redoStack=[]})}allowDispatch(e){switch(e.type){case`REQUEST_UNDO`:if(!this.canUndo())return`EmptyUndoStack`;break;case`REQUEST_REDO`:if(!this.canRedo())return`EmptyRedoStack`;break}return`Success`}handle(e){switch(e.type){case`REQUEST_UNDO`:case`REQUEST_REDO`:this.requestHistoryChange(e.type===`REQUEST_UNDO`?`UNDO`:`REDO`)}}finalize(){}requestHistoryChange(e){let t=e===`UNDO`?this.undoStack.pop():this.redoStack.pop();if(!t){let e=this.getPossibleRevisionToRepeat();if(!e)return;let t=Yz(e,this.getters);if(!t)return;if(!Array.isArray(t)){this.dispatch(t.type,t);return}for(let e of t)this.dispatch(e.type,e);return}e===`UNDO`?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0?!0:Jz(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},Zz=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,I(e.value)])}isValuePresent(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(n)}isHeaderPresent(e){let t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(n)}trackHeader(e){let t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}},Qz=class extends ${static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new Zz,this.trackPresencePivotId=e.pivotId;break;case`PIVOT_STOP_PRESENCE_TRACKING`:this.trackPresencePivotId=void 0;break}}getPivotPresenceTracker(e){if(this.trackPresencePivotId===e){if(!this.tracker)throw Error(`Tracker not initialized`);return this.tracker}}},$z=class extends ${static getters=[`getAutomaticSeparator`];allowDispatch(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:return this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e)}return`Success`}handle(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:this.splitIntoColumns(e);break}}getAutomaticSeparator(){let e=this.getters.getSelectedCells();for(let t of e)if(t.value&&t.type===`text`){let e=this.getAutoSeparatorForString(t.value);if(e)return e}return` `}getAutoSeparatorForString(e){for(let t of[`
1893
- `,`;`,`,`,` `,`.`])if(e.includes(t))return t}splitIntoColumns({separator:e,addNewColumns:t}){let n=this.getters.getSelectedZone(),r=this.getters.getActiveSheetId(),i=this.getSplittedCols(n,e);t&&this.addColsToAvoidCollisions(n,i),this.removeMergesInSplitZone(n,i),this.addColumnsToNotOverflowSheet(n,i);for(let e=0;e<i.length;e++){let t=n.top+e,a=i[e],o=n.left,s=this.getters.getCell({sheetId:r,col:o,row:t});if(!(a.length===1&&a[0]===s?.content))for(let[e,n]of a.entries())this.dispatch(`UPDATE_CELL`,{sheetId:r,col:o+e,row:t,content:tl(n,this.getters.getLocale()),format:``,style:s?.style||null})}}getSplittedCols(e,t){if(!t)throw Error(`Separator cannot be empty`);let n=this.getters.getActiveSheetId(),r=[];for(let i of x(e.top,e.bottom+1)){let a=this.getters.getEvaluatedCell({sheetId:n,col:e.left,row:i}).formattedValue;r.push(this.splitAndRemoveTrailingEmpty(a,t))}return r}splitAndRemoveTrailingEmpty(e,t){let n=e.split(t);for(;n.length>1&&n[n.length-1]===``;)n.pop();return n}willSplittedColsOverwriteContent(e,t){let n=this.getters.getActiveSheetId();for(let r of x(e.top,e.bottom+1)){let i=t[r-e.top];for(let t=1;t<i.length;t++){let i=this.getters.getCell({sheetId:n,col:e.left+t,row:r});if(i&&i.content)return!0}}return!1}removeMergesInSplitZone(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length)),i={...e,right:e.left+r-1},a=this.getters.getMergesInZone(n,i);this.dispatch(`REMOVE_MERGE`,{sheetId:n,target:a})}addColsToAvoidCollisions(e,t){let n=this.getters.getActiveSheetId(),r=0;for(let i of x(e.top,e.bottom+1)){let a={sheetId:n,col:e.left,row:i},o=t[i-e.top],s=this.getColsToAddToAvoidCollision(a,o);r=Math.max(r,s)}r&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:e.left,sheetId:n,quantity:r,position:`after`})}getColsToAddToAvoidCollision(e,t){let n=t.length;for(let t=1;t<n;t++){let r=e.col+t,i=this.getters.getCell({...e,col:r});if(i&&i.content)return n-t}return 0}addColumnsToNotOverflowSheet(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length-1)),i=this.getters.getNumberCols(n)-1;e.left+r>i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:i,sheetId:n,quantity:e.left+r-i,position:`after`})}checkSingleColSelected(){return this.getters.isSingleColSelected()?`Success`:`MoreThanOneColumnSelected`}checkNonEmptySelector(e){return e.separator===``?`EmptySplitSeparator`:`Success`}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return`Success`;let t=this.getters.getSelectedZones()[0],n=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,n)?`SplitWillOverwriteContent`:`Success`}checkSeparatorInSelection({separator:e}){let t=this.getters.getSelectedCells();for(let n of t)if(n.formattedValue.includes(e))return`Success`;return`NoSplitSeparatorInSelection`}},eB=class extends ${handle(e){switch(e.type){case`AUTOFILL_TABLE_COLUMN`:let t=this.getters.getCoreTable(e),n=this.getters.getCell(e);if(!t?.config.automaticAutofill||t.type===`dynamic`||!n?.isFormula)return;let{col:r,row:i}=e,a=KF(t.range.zone,t.config);if(a&&dr(r,i,a)){let t=e.autofillRowStart??a.top,n=e.autofillRowEnd??a.bottom,r={...a,top:t,bottom:n};this.autofillTableZone(e,r)}break}}autofillTableZone(e,t){if(t.top===t.bottom)return;let{col:n,row:r,sheetId:i}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==r&&this.getters.getEvaluatedCell({col:n,row:e,sheetId:i}).type!==`empty`)return;let a={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.bottom}),this.dispatch(`AUTOFILL`),this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.top}),this.dispatch(`AUTOFILL`),this.selection.selectZone(a)}},tB=class extends ${allowDispatch(e){switch(e.type){case`RESIZE_TABLE`:let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return`TableNotFound`;let n=t.range.zone,r=this.getters.getRangeFromRangeData(e.newTableRange).zone;return r.top!==n.top||r.left!==n.left?`InvalidTableResize`:this.canDispatch(`UPDATE_TABLE`,{...e}).reasons}return`Success`}handle(e){switch(e.type){case`RESIZE_TABLE`:{let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch(`UPDATE_TABLE`,{...e}),!t||!t.config.automaticAutofill)return;let n=t.range.zone,r=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(r.bottom>=n.bottom){for(let t=r.left;t<=r.right;t++){let i={col:t,row:n.bottom,sheetId:e.sheetId};this.getters.getCell(i)?.content.startsWith(`=`)&&this.dispatch(`AUTOFILL_TABLE_COLUMN`,{...i,autofillRowStart:n.bottom,autofillRowEnd:r.bottom})}break}}}}},nB=class extends ${static layers=[`Clipboard`];static getters=[`getClipboardContent`,`getClipboardId`,`getClipboardTextContent`,`isCutOperation`];status=`invisible`;originSheetId;copiedData;_isCutOperation=!1;clipboardId=new wc().uuidv4();allowDispatch(e){switch(e.type){case`CUT`:let t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case`PASTE_FROM_OS_CLIPBOARD`:{let t=this.convertTextToClipboardData(e.clipboardContent.text??``),n=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:n,isCutOperation:!1})}case`PASTE`:{if(!this.copiedData)return`EmptyClipboard`;let t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].top===0&&e[0].bottom===0)return`InvalidCopyPasteSelection`;break}case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].left===0&&e[0].right===0)return`InvalidCopyPasteSelection`;break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}}return`Success`}handle(e){switch(e.type){case`COPY`:case`CUT`:let t=this.getters.getSelectedZones();this.status=`visible`,this.originSheetId=this.getters.getActiveSheetId(),this.copiedData=this.copy(t),this._isCutOperation=e.type===`CUT`;break;case`PASTE_FROM_OS_CLIPBOARD`:{this._isCutOperation=!1;let t=e.clipboardContent;t.data?.version!==22&&(t={...t},delete t.data),this.copiedData=t.data||this.convertTextToClipboardData(t.text??``);let n=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:n,selectTarget:!0,isCutOperation:!1}),this.status=`invisible`;break}case`PASTE`:{let t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status=`invisible`,this._isCutOperation&&=(this.copiedData=void 0,!1);break}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZone(),t=e.top!==e.bottom,n={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};this.originSheetId=this.getters.getActiveSheetId();let r=this.copy([n]);this.paste([e],r,{isCutOperation:!1,selectTarget:!0})}break;case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZone(),t=e.left!==e.right,n={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};this.originSheetId=this.getters.getActiveSheetId();let r=this.copy([n]);this.paste([e],r,{isCutOperation:!1,selectTarget:!0})}break;case`CLEAN_CLIPBOARD_HIGHLIGHT`:this.status=`invisible`;break;case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!$n(t[0])){this.dispatch(`CLEAR_CELLS`,{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}let r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`ADD_COLUMNS_ROWS`:if(this.status=`invisible`,this._isCutOperation!==!0||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard(e.position===`before`?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case`REMOVE_COLUMNS_ROWS`:if(this.status=`invisible`,this._isCutOperation!==!0||e.sheetId!==this.copiedData?.sheetId)return;for(let t of e.elements)if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}this.status=`invisible`;break;case`REPEAT_PASTE`:this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case`DELETE_SHEET`:if(this._isCutOperation!==!0)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status=`invisible`);break;default:Gi(e)&&(this.status=`invisible`)}}convertTextToClipboardData(e){let t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({})),n={};for(let{handlerName:r,handler:i}of t){let t=i.convertTextToClipboardData(e);n[r]=t;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])t&&e in t&&(n[e]=t[e])}return n}selectClipboardHandlers(e){let t=`figureId`in e?ed.figureHandlers:ed.cellHandlers;return t.getKeys().map(e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)}))}isCutAllowedOn(e){let t=this.getClipboardData(e);for(let{handler:e}of this.selectClipboardHandlers(t)){let n=e.isCutAllowed(t);if(n!==`Success`)return n}return`Success`}isPasteAllowed(e,t,n){for(let{handler:r}of this.selectClipboardHandlers(t)){let i=r.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...n});if(i!==`Success`)return i}return`Success`}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;let{zones:n}=this.copiedData;for(let r of n)if(t===`COL`&&e<=r.right||t===`ROW`&&e<=r.bottom)return!0;return!1}copy(e,t=`copyPaste`){let n={},r=this.getClipboardData(e);for(let{handlerName:e,handler:i}of this.selectClipboardHandlers(r)){let a=i.copy(r,t);n[e]=a;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])a&&e in a&&(n[e]=a[e])}return n}paste(e,t,n){if(!t)return;let r=this.getters.getActiveSheetId(),i=this.selectClipboardHandlers(t),{target:a,zone:o,selectedZones:s}=jc(r,e,t,i,n);o!==void 0&&this.addMissingDimensions(r,o.right-o.left+1,o.bottom-o.top+1,o.left,o.top),Ac(i,t,a,n),n?.selectTarget&&Mc(this.selection,e,s)}addMissingDimensions(e,t,n,r,i){let a=n+i-this.getters.getNumberRows(e);a>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:this.getters.getNumberRows(e)-1,sheetId:e,quantity:a,position:`after`});let o=t+r-this.getters.getNumberCols(e);o>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:this.getters.getNumberCols(e)-1,sheetId:e,quantity:o,position:`after`})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}getClipboardContent(){return{"text/plain":this.getPlainTextContent(),"text/html":this.getHTMLContent()}}getSheetData(){let e={version:22,clipboardId:this.clipboardId};return this.copiedData&&`figureId`in this.copiedData?e:{...e,...this.copiedData}}getPlainTextContent(){return this.copiedData?.cells&&this.copiedData.cells.map(e=>e.map(e=>this.getters.shouldShowFormulas()&&e?.tokens?.length?e?.content||``:e.evaluatedCell?.formattedValue||``).join(` `)).join(`
1894
- `)||` `}getHTMLContent(){let e=``,t=this.copiedData?.cells;if(!t)e=` `;else if(t.length===1&&t[0].length===1)e=`${this.getters.getCellText(t[0][0].position)}`;else if(t[0][0]){let n=`<table border="1" style="border-collapse:collapse">`;for(let e of t){n+=`<tr>`;for(let t of e){if(!t)continue;let e=U(bf(this.getters.getCellComputedStyle(t.position))),r=this.getters.getCellText(t.position);n+=`<td style="${e}">`+eh(r)+`</td>`}n+=`</tr>`}n+=`</table>`,e=n}else return``;return`<div data-osheet-clipboard='${eh(JSON.stringify(this.getSheetData()))}'>${e}</div>`}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r;return r=t===`COL`?{...e,left:e.right+1,right:this.getters.getNumberCols(n)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1},{cut:[r],paste:[e]}}getInsertCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r,i;return t===`COL`?(r={...e,right:this.getters.getNumberCols(n)-1},i={...e,left:e.right+1,right:e.right+1}):(r={...e,bottom:this.getters.getNumberRows(n)-1},i={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1}),{cut:[r],paste:[i]}}getClipboardData(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedFigureId();return n?{figureId:n,sheetId:t}:Tc(t,e)}drawLayer(e){if(this.status!==`visible`||!this.copiedData)return;let{sheetId:t,zones:n}=this.copiedData;if(t!==this.getters.getActiveSheetId()||!n||!n.length)return;let{ctx:r,thinLineWidth:i}=e;r.setLineDash([8,5]),r.strokeStyle=ae,r.lineWidth=3.3*i;for(let e of n){let{x:t,y:n,width:i,height:a}=this.getters.getVisibleRect(e);i>0&&a>0&&r.strokeRect(t,n,i,a)}}},rB=class extends ${static getters=[`getFilterHiddenValues`,`getFirstTableInSelection`,`isRowFiltered`,`isFilterActive`];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){switch(e.type){case`UPDATE_FILTER`:if(!this.getters.getFilterId(e))return`FilterNotFound`;break}return`Success`}handle(e){switch(e.type){case`UNDO`:case`REDO`:case`UPDATE_CELL`:case`EVALUATE_CELLS`:case`ACTIVATE_SHEET`:case`REMOVE_TABLE`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`UPDATE_TABLE`:this.isEvaluationDirty=!0;break;case`START`:for(let e of this.getters.getSheetIds())this.filterValues[e]={};break;case`CREATE_SHEET`:this.filterValues[e.sheetId]={};break;case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`GROUP_HEADERS`:case`UNGROUP_HEADERS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_ALL_HEADER_GROUPS`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:this.updateHiddenRows(e.sheetId);break;case`UPDATE_FILTER`:this.updateFilter(e),this.updateHiddenRows(e.sheetId);break;case`DUPLICATE_SHEET`:this.filterValues[e.sheetIdTo]=y(this.filterValues[e.sheetId]);break}}finalize(){if(this.isEvaluationDirty){for(let e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterHiddenValues(e){let t=this.getters.getFilterId(e),n=e.sheetId;return!t||!this.filterValues[n]?[]:this.filterValues[n][t]||[]}isFilterActive(e){let t=this.getters.getFilterId(e),n=e.sheetId;return!!(t&&this.filterValues[n]?.[t]?.length)}getFirstTableInSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,hiddenValues:n,sheetId:r}){let i=this.getters.getFilterId({sheetId:r,col:e,row:t});i&&(this.filterValues[r]||(this.filterValues[r]={}),this.filterValues[r][i]=n)}updateHiddenRows(e){let t=this.getters.getFilters(e).sort((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top),n=new Set;for(let r of t){if(n.has(r.rangeWithHeaders.zone.top)||this.getters.isRowHiddenByUser(e,r.rangeWithHeaders.zone.top))continue;let t=this.filterValues[e]?.[r.id]?.map(yc),i=r.filteredRange?.zone;if(!t||!i)continue;let a=new Set(t);for(let t=i.top;t<=i.bottom;t++){let i=this.getCellValueAsString(e,r.col,t);a.has(i)&&n.add(t)}}this.hiddenRows[e]=n}getCellValueAsString(e,t,n){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).formattedValue.toLowerCase()}exportForExcel(e){for(let t of e.sheets){let e=t.id;for(let n of t.tables){let r=Qn(n.range),i=[],a=[];for(let n of x(0,pr(r).numberOfCols)){let o={sheetId:t.id,col:r.left+n,row:r.top},s=this.getFilterHiddenValues(o),c=this.getters.getFilter(o),l=c?.filteredRange?_r(c.filteredRange.zone).map(t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue):[];if(s.length){let e=l.filter(e=>e).filter(e=>!s.includes(e));i.push({colId:n,displayedValues:[...new Set(e)],displayBlanks:!s.includes(``)&&l.some(e=>!e)})}let u=this.getters.getEvaluatedCell(o).formattedValue,d=this.getUniqueColNameForExcel(n,u,a);a.push(d),t.cells[w(o.col,o.row)]={...t.cells[w(o.col,o.row)],content:d,value:d,isFormula:!1}}n.filters=i}}}getUniqueColNameForExcel(e,t,n){t||=`Column${e}`;let r=t,i=2;for(;n.includes(r);)r=t+String(i),i++;return r}},iB=class extends ${static layers=[`Selection`];static getters=[`getActiveSheet`,`getActiveSheetId`,`getActiveCell`,`getActiveCols`,`getActiveRows`,`getCurrentStyle`,`getSelectedZones`,`getSelectedZone`,`getSelectedCells`,`getSelectedFigureId`,`getSelection`,`getActivePosition`,`getSheetPosition`,`isSingleColSelected`,`getElementsFromSelection`,`tryGetActiveSheetId`,`isGridSelectionActive`];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;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient}allowDispatch(e){switch(e.type){case`ACTIVATE_SHEET`:try{if(!this.getters.getSheet(e.sheetIdTo).isVisible)return`SheetIsHidden`;break}catch{return`InvalidSheetId`}case`MOVE_COLUMNS_ROWS`:return this.isMoveElementAllowed(e)}return`Success`}handleEvent(e){let t=e.anchor,n=[];switch(e.mode){case`overrideSelection`:n=[t.zone];break;case`updateAnchor`:n=[...this.gridSelection.zones];let r=n.findIndex(t=>lr(t,e.previousAnchor.zone));r>=0&&(n[r]=t.zone);break;case`newAnchor`:n=[...this.gridSelection.zones,t.zone];break}this.setSelectionMixin(e.anchor,n),this.selection.resetDefaultAnchor(this,y(this.gridSelection.anchor));let{col:r,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:r,row:i}),this.selectedFigureId=null}handle(e){switch(e.type){case`ACTIVATE_SHEET`:this.selectedFigureId=null;break;case`DELETE_FIGURE`:this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;case`DELETE_SHEET`:this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null);break}switch(e.type){case`START`:let t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);let{col:n,row:r}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(n,r),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case`ACTIVATE_SHEET`:this.activateSheet(e.sheetIdFrom,e.sheetIdTo);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){e.dimension===`COL`?this.onColumnsRemoved(e):this.onRowsRemoved(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`ADD_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`MOVE_COLUMNS_ROWS`:e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case`SELECT_FIGURE`:this.selectedFigureId=e.id;break;case`ACTIVATE_NEXT_SHEET`:this.activateNextSheet(`right`);break;case`ACTIVATE_PREVIOUS_SHEET`:this.activateNextSheet(`left`);break;case`HIDE_SHEET`:e.sheetId===this.getActiveSheetId()&&this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case`UNDO`:case`REDO`:case`DELETE_SHEET`:let i=Object.keys(this.sheetsData).filter(e=>!this.getters.tryGetSheet(e));for(let e of i)delete this.sheetsData[e];for(let e in this.sheetsData){let t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:y(t)}}this.fallbackToVisibleSheet();let a=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map(e=>this.getters.expandZone(a,e)),this.gridSelection.anchor.zone=this.getters.expandZone(a,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null;break}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,y(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){let e=new Set;for(let t of this.gridSelection.zones)if(t.top===0&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let n=t.left;n<=t.right;n++)e.add(n);return e}getActiveRows(){let e=new Set,t=this.getters.getActiveSheetId();for(let n of this.gridSelection.zones)if(n.left===0&&n.right===this.getters.getNumberCols(t)-1)for(let t=n.top;t<=n.bottom;t++)e.add(t);return e}getCurrentStyle(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return y(this.gridSelection.zones)}getSelectedZone(){return y(this.gridSelection.anchor.zone)}getSelection(){return y(this.gridSelection)}getSelectedCells(){let e=this.getters.getActiveSheetId(),t=[];for(let n of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,n));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{let t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}isSingleColSelected(){let e=this.getters.getSelectedZones();return!(e.length!==1||e[0].left!==e[0].right)}getElementsFromSelection(e){if(e===`COL`&&this.getters.getActiveCols().size===0||e===`ROW`&&this.getters.getActiveRows().size===0)return[];let t=this.getters.getSelectedZones(),n=[],r=e===`COL`?`left`:`top`,i=e===`COL`?`right`:`bottom`;for(let e of t){let t=Array.from({length:e[i]-e[r]+1},(t,n)=>e[r]+n);n=n.concat(t)}return[...new Set(n)].sort()}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:y(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,y(this.gridSelection.anchor));else{let{col:e,row:n}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,n)}let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:n,row:r})}setSelectionMixin(e,t){let{anchor:n,zones:r}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=n,this.gridSelection.zones=br(r)}selectCell(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.expandZone(n,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:r,cell:{col:e,row:t}},[r])}setActiveSheet(e){let t=this.getters.getSheet(e);this.activeSheet=t}activateNextSheet(e){let t=this.getters.getSheetIds(),n=(t.findIndex(e=>e===this.activeSheet.id)+(e===`left`?t.length-1:1))%t.length;this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[n]})}onColumnsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=ir(n,`left`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=ir(i,`left`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>ir(t,`left`,[...e.elements]));this.setSelectionMixin(a,o)}onRowsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=ir(n,`top`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=ir(i,`top`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>ir(t,`top`,[...e.elements]));this.setSelectionMixin(a,o)}onAddElements(e){let t=e.dimension===`COL`?`left`:`top`,n=rr(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),r=this.gridSelection.zones.map(n=>rr(n,t,e.base,e.position,e.quantity)),i={cell:{col:n.left,row:n.top},zone:n};this.setSelectionMixin(i,r)}onMoveElements(e){let t=e.elements.length;this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:e.position});let n=e.dimension===`COL`,r=e.elements[0],i=e.elements[t-1],a=e.base<r,o=a&&n?t:0,s=a&&!n?t:0,c=a?e.elements.map(e=>e+t):e.elements,l=Object.fromEntries(c.map(t=>{let r=n?this.getters.getColSize(e.sheetId,t):this.getters.getUserRowSize(e.sheetId,t);return[t,n&&r===96||r===void 0?null:r]})),u=[{left:n?r+o:0,right:n?i+o:this.getters.getNumberCols(e.sheetId)-1,top:n?0:r+s,bottom:n?this.getters.getNumberRows(e.sheetId)-1:i+s}],d=this.getActiveSheetId(),f=a?e.base:e.base+1,p=[{left:n?f:0,right:n?f+t-1:this.getters.getNumberCols(e.sheetId)-1,top:n?0:f,bottom:n?this.getters.getNumberRows(e.sheetId)-1:f+t-1}];for(let e of ed.cellHandlers.getAll()){let t=new e(this.getters,this.dispatch),n=t.copy(Tc(d,u),`shiftCells`);n&&t.paste({zones:p,sheetId:d},n,{isCutOperation:!0})}let m=p[0],h=m.left,g=m.top;this.setSelectionMixin({zone:m,cell:{col:h,row:g}},[m]);let _=a?e.base:e.base+1;for(let t of c)this.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,size:l[t],elements:[_]}),_+=1;this.dispatch(`REMOVE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,elements:c})}isMoveElementAllowed(e){let t=e.dimension===`COL`,n=e.elements[0],r=e.elements[e.elements.length-1],i=e.sheetId,a=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(a(i,n-1,n)||a(i,r,r+1)||a(i,e.base-1,e.base))return`WillRemoveExistingMerge`;let o=[e.base,...e.elements],s=t?this.getters.getNumberCols(i):this.getters.getNumberRows(i);return o.some(e=>e<0||e>=s)?`InvalidHeaderIndex`:!t&&!this.isTableRowMoveAllowed(i,e.elements)?`CannotMoveTableHeader`:`Success`}isTableRowMoveAllowed(e,t){let n=this.getters.getCoreTables(e);if(n.length===0)return!0;let r=new Set(t);return n.every(({range:{zone:e},config:n})=>{let{top:i,bottom:a}=e;if(n.numberOfHeaders===0)return!0;let o=i+n.numberOfHeaders-1;return t.some(e=>e>=i&&e<=o)?x(i,a+1).every(e=>r.has(e)):!0})}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){let e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){let{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);let{col:t,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:n})}}clipSelection(e,t){let n=this.getters.getNumberCols(e)-1,r=this.getters.getNumberRows(e)-1,i=t.zones.map(e=>({left:b(e.left,0,n),right:b(e.right,0,n),top:b(e.top,0,r),bottom:b(e.bottom,0,r)})),a=b(t.anchor.cell.col,0,n),o=b(t.anchor.cell.row,0,r),s={left:b(t.anchor.zone.left,0,n),right:b(t.anchor.zone.right,0,n),top:b(t.anchor.zone.top,0,r),bottom:b(t.anchor.zone.bottom,0,r)};return{zones:i,anchor:{cell:{col:a,row:o},zone:s}}}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getSelectedZones();t.fillStyle=`#f3f7fe`,t.fillStyle=r.length===1&&r[0].left===r[0].right&&r[0].top===r[0].bottom?`#f3f7fe`:`#e9f0ff`,t.strokeStyle=ae,t.lineWidth=1.5*n;for(let e of r){let{x:n,y:r,width:i,height:a}=this.getters.getVisibleRect(e);t.globalCompositeOperation=`multiply`,t.fillRect(n,r,i,a),t.globalCompositeOperation=`source-over`,t.strokeRect(n,r,i,a)}t.globalCompositeOperation=`source-over`;let i=this.getActivePosition();t.strokeStyle=ae,t.lineWidth=3*n;let a;a=this.getters.isInMerge(i)?this.getters.getMerge(i):D(i);let{x:o,y:s,width:c,height:l}=this.getters.getVisibleRect(a);c>0&&l>0&&t.strokeRect(o,s,c,l)}},aB=class{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;offsetScrollbarX;offsetScrollbarY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,n,r,i,a){if(this.getters=e,this.sheetId=t,this.boundaries=n,r.width<0||r.height<0)throw Error(`Viewport size cannot be negative`);this.viewportWidth=r.height&&r.width,this.viewportHeight=r.width&&r.height,this.top=n.top,this.bottom=n.bottom,this.left=n.left,this.right=n.right,this.offsetX=a.x,this.offsetY=a.y,this.offsetScrollbarX=a.x,this.offsetScrollbarY=a.y,this.canScrollVertically=i.canScrollVertically,this.canScrollHorizontally=i.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){let e=this.getters.findLastVisibleColRowIndex(this.sheetId,`COL`,{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,`ROW`,{first:this.boundaries.top,last:this.boundaries.bottom}),{end:n,size:r}=this.getters.getColDimensions(this.sheetId,e),{end:i,size:a}=this.getters.getRowDimensions(this.sheetId,t),o=this.searchHeaderIndex(`COL`,n-this.viewportWidth,0),s=this.getters.getColSize(this.sheetId,o),c=this.searchHeaderIndex(`ROW`,i-this.viewportHeight,0),l=this.getters.getRowSize(this.sheetId,c),u=n-this.offsetCorrectionX;this.canScrollHorizontally&&(u+=Math.max(96,Math.min(s,this.viewportWidth-r)),u=Math.max(u,this.viewportWidth));let d=i-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(28,Math.min(l,this.viewportHeight-a)),d=Math.max(d,this.viewportHeight),i+46>d&&!this.getters.isReadonly()&&(d+=46)),{width:u,height:d}}getColIndex(e){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex(`COL`,e-this.offsetCorrectionX,this.left)}getRowIndex(e){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex(`ROW`,e-this.offsetCorrectionY,this.top)}adjustPosition(e){let t=this.sheetId,n=this.getters.getMainCellPosition({sheetId:t,...e}),{col:r,row:i}=this.getters.getNextVisibleCellPosition(n);dr(r,this.boundaries.top,this.boundaries)&&this.adjustPositionX(r),dr(this.boundaries.left,i,this.boundaries)&&this.adjustPositionY(i)}adjustPositionX(e){let t=this.sheetId,{end:n}=this.getters.getColDimensions(t,e);if(this.offsetX+this.offsetCorrectionX+this.viewportWidth<n){let n=this.getters.getNumberCols(t),r=e;for(;this.getters.isColHidden(t,r)&&r<n;)r++;let i=this.getters.getColDimensions(t,r).end,a=this.searchHeaderIndex(`COL`,i-this.viewportWidth-this.offsetCorrectionX,this.boundaries.left);this.offsetScrollbarX=this.getters.getColDimensions(t,a).end-this.offsetCorrectionX}else if(this.left>e){let n=e;for(;this.getters.isColHidden(t,n)&&n>0;)n--;this.offsetScrollbarX=this.getters.getColDimensions(t,n).start-this.offsetCorrectionX}this.adjustViewportZoneX()}adjustPositionY(e){let t=this.sheetId,{end:n}=this.getters.getRowDimensions(t,e);if(this.offsetY+this.viewportHeight+this.offsetCorrectionY<n){let n=this.getters.getNumberRows(t),r=e;for(;this.getters.isRowHidden(t,r)&&r<n;)r++;let i=this.getters.getRowDimensions(t,r).end,a=this.searchHeaderIndex(`ROW`,i-this.viewportHeight-this.offsetCorrectionY,this.boundaries.top);this.offsetScrollbarY=this.getters.getRowDimensions(t,a).end-this.offsetCorrectionY}else if(this.top>e){let n=e;for(;this.getters.isRowHidden(t,n)&&n>0;)n--;this.offsetScrollbarY=this.getters.getRowDimensions(t,n).start-this.offsetCorrectionY}this.adjustViewportZoneY()}willNewOffsetScrollViewport(e,t){return this.canScrollHorizontally&&this.offsetScrollbarX!==e||this.canScrollVertically&&this.offsetScrollbarY!==t}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getVisibleRect(e){let t=cr(e,this);if(t)return{x:this.getters.getColRowOffset(`COL`,this.left,t.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset(`ROW`,this.top,t.top)+this.offsetCorrectionY,width:Math.min(this.getters.getColRowOffset(`COL`,t.left,t.right+1),this.viewportWidth),height:Math.min(this.getters.getColRowOffset(`ROW`,t.top,t.bottom+1),this.viewportHeight)}}getFullRect(e){if(cr(e,this))return{x:this.getters.getColRowOffset(`COL`,this.left,e.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset(`ROW`,this.top,e.top)+this.offsetCorrectionY,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,n=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;let r=this.sheetId,i=this.getters.getNumberHeaders(r,e),a=n,o=i;for(;a<=o&&a!==i&&o!==-1;){let i=Math.floor((a+o)/2),s=this.getters.getColRowOffset(e,n,i),c=this.getters.getHeaderSize(r,e,i);if(t>=s&&t<s+c)return i;t>=s+c?a=i+1:o=i-1}return-1}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetScrollbarX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetScrollbarY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){let{width:e}=this.getMaxSize();this.viewportWidth+this.offsetScrollbarX>e&&(this.offsetScrollbarX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){let{height:e}=this.getMaxSize();this.viewportHeight+this.offsetScrollbarY>e&&(this.offsetScrollbarY=Math.max(0,e-this.viewportHeight))}this.adjustViewportZoneY()}adjustViewportZoneX(){let e=this.sheetId;this.left=this.searchHeaderIndex(`COL`,this.offsetScrollbarX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex(`COL`,this.viewportWidth,this.left)),this.viewportWidth&&(this.left===-1&&(this.left=this.boundaries.left),this.right===-1&&(this.right=this.boundaries.right),this.offsetX=this.getters.getColDimensions(e,this.left).start-this.getters.getColDimensions(e,this.boundaries.left).start)}adjustViewportZoneY(){let e=this.sheetId;this.top=this.searchHeaderIndex(`ROW`,this.offsetScrollbarY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex(`ROW`,this.viewportHeight,this.top)),this.viewportHeight&&(this.top===-1&&(this.top=this.boundaries.top),this.bottom===-1&&(this.bottom=this.boundaries.bottom),this.offsetY=this.getters.getRowDimensions(e,this.top).start-this.getters.getRowDimensions(e,this.boundaries.top).start)}},oB=class extends ${static getters=[`getColIndex`,`getRowIndex`,`getActiveMainViewport`,`getSheetViewDimension`,`getSheetViewDimensionWithHeaders`,`getMainViewportRect`,`isVisibleInViewport`,`getEdgeScrollCol`,`getEdgeScrollRow`,`getVisibleFigures`,`getVisibleRect`,`getVisibleRectWithoutHeaders`,`getVisibleCellPositions`,`getColRowOffsetInViewport`,`getMainViewportCoordinates`,`getActiveSheetScrollInfo`,`getActiveSheetDOMScrollInfo`,`getSheetViewVisibleCols`,`getSheetViewVisibleRows`,`getFrozenSheetViewRatio`,`isPositionVisible`,`getColDimensionsInViewport`,`getRowDimensionsInViewport`,`getAllActiveViewportsZonesAndRect`,`getRect`];viewports={};sheetViewWidth=Je();sheetViewHeight=Je();gridOffsetX=0;gridOffsetY=0;sheetsWithDirtyViewports=new Set;shouldAdjustViewports=!1;allowDispatch(e){switch(e.type){case`SET_VIEWPORT_OFFSET`:return this.chainValidations(this.checkScrollingDirection,this.checkIfViewportsWillChange)(e);case`RESIZE_SHEETVIEW`:return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return`Success`}}handleEvent(e){let t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let{col:n,row:r}=Sr(e.previousAnchor.zone,e.anchor.zone);if(e.mode===`updateAnchor`){let i=e.previousAnchor.zone,a=e.anchor.zone,{top:o,bottom:s,left:c,right:l}=this.getMainInternalViewport(t);i.left===a.left&&i.right===a.right&&(n=c>n||n>l?c:n),i.top===a.top&&i.bottom===a.bottom&&(r=o>r||r>s?o:r)}n=Math.min(n,this.getters.getNumberCols(t)-1),r=Math.min(r,this.getters.getNumberRows(t)-1),this.sheetsWithDirtyViewports.has(t)||this.refreshViewport(this.getters.getActiveSheetId(),{col:n,row:r})}}handle(e){if(Ri.has(e.type))for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);switch(e.type){case`START`:this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case`UNDO`:case`REDO`:this.cleanViewports();for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);this.shouldAdjustViewports=!0;break;case`RESIZE_SHEETVIEW`:this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case`SET_VIEWPORT_OFFSET`:this.setSheetViewOffset(e.offsetX,e.offsetY);break;case`SHIFT_VIEWPORT_DOWN`:let t=this.getters.getActiveSheetId(),{top:n,viewportHeight:r,offsetCorrectionY:i}=this.getMainInternalViewport(t),a=this.getters.getRowDimensions(t,n);this.shiftVertically(a.start+r-i);break;case`SHIFT_VIEWPORT_UP`:{let e=this.getters.getActiveSheetId(),{top:t,viewportHeight:n,offsetCorrectionY:r}=this.getMainInternalViewport(e),i=this.getters.getRowDimensions(e,t);this.shiftVertically(i.end-r-n);break}case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`UPDATE_FILTER`:case`UNFREEZE_ROWS`:case`UNFREEZE_COLUMNS`:case`FREEZE_COLUMNS`:case`FREEZE_ROWS`:case`UNFREEZE_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`RESIZE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`UNGROUP_HEADERS`:case`GROUP_HEADERS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_ALL_HEADER_GROUPS`:this.sheetsWithDirtyViewports.add(e.sheetId);break;case`UPDATE_CELL`:for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);break;case`DELETE_SHEET`:this.cleanViewports(),this.sheetsWithDirtyViewports.delete(e.sheetId);break;case`ACTIVATE_SHEET`:this.sheetsWithDirtyViewports.add(e.sheetIdTo);break;case`DELETE_SHEET`:this.sheetsWithDirtyViewports.delete(e.sheetId);break;case`SCROLL_TO_CELL`:this.refreshViewport(this.getters.getActiveSheetId(),{col:e.col,row:e.row});break}}finalize(){for(let e of this.sheetsWithDirtyViewports)if(this.resetViewports(e),this.shouldAdjustViewports){let t=this.getters.getSheetPosition(e);this.getSubViewports(e).forEach(e=>{e.adjustPosition(t)})}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){let e=this.getters.getSheetIds();for(let t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getColIndex(e)))}getRowIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getRowIndex(e)))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getActiveMainViewport(){let e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getActiveSheetDOMScrollInfo(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetScrollbarX,scrollY:t.offsetScrollbarY}}getSheetViewVisibleCols(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>x(e.left,e.right+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`COL`,t))}getSheetViewVisibleRows(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>x(e.top,e.bottom+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`ROW`,t))}getVisibleCellPositions(){let e=this.getSheetViewVisibleCols(),t=this.getSheetViewVisibleRows(),n=this.getters.getActiveSheetId(),r=[];for(let i of e)for(let e of t){let t={sheetId:n,col:i,row:e},a=this.getters.getMainCellPosition(t);a.row!==e||a.col!==i||r.push(t)}return r}getMainViewportRect(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e),{width:i,height:a}=t.getMaxSize();return{x:this.getters.getColDimensions(e,n).start,y:this.getters.getRowDimensions(e,r).start,width:i,height:a}}getMaximumSheetOffset(){let e=this.getters.getActiveSheetId(),{width:t,height:n}=this.getMainViewportRect(),r=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-r.viewportWidth+1),maxOffsetY:Math.max(0,n-r.viewportHeight+1)}}getColRowOffsetInViewport(e,t,n){if(n<t)return-this.getColRowOffsetInViewport(e,n,t);let r=this.getters.getActiveSheetId(),i=e===`COL`?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),a=i.findIndex(e=>t>=e),o=i.findIndex(e=>n<=e);o=o===-1?i.length:o;let s=i.slice(a,o),c=0;for(let t of s)c+=this.getters.getHeaderSize(r,e,t);return c}isVisibleInViewport({sheetId:e,col:t,row:n}){return this.getSubViewports(e).some(e=>e.isVisible(t,n))}getEdgeScrollCol(e,t,n){let r=!1,i=0,a=0,{xSplit:o}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:s}=this.getSheetViewDimension(),{x:c}=this.getMainViewportCoordinates(),l=this.getActiveSheetScrollInfo().scrollX;return e>s?(r=!0,a=Os(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=Os(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=Os(e),i=`reset`),{canEdgeScroll:r,direction:i,delay:a}}getEdgeScrollRow(e,t,n){let r=!1,i=0,a=0,{ySplit:o}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:s}=this.getSheetViewDimension(),{y:c}=this.getMainViewportCoordinates(),l=this.getActiveSheetScrollInfo().scrollY;return e>s?(r=!0,a=Os(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=Os(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=Os(e),i=`reset`),{canEdgeScroll:r,direction:i,delay:a}}getVisibleRect(e){let t=this.getVisibleRectWithoutHeaders(e);return{...t,x:t.x+this.gridOffsetX,y:t.y+this.gridOffsetY}}getVisibleRectWithoutHeaders(e){let t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getVisibleRect(e))}getRect(e){let t=this.getters.getActiveSheetId(),n=this.mapViewportsToRect(t,t=>t.getFullRect(e));return{...n,x:n.x+this.gridOffsetX,y:n.y+this.gridOffsetY}}getMainViewportCoordinates(){let e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,n).start}}getColDimensionsInViewport(e,t){let n=Kt(this.getters.getSheetViewVisibleCols()),r=this.getters.getColRowOffsetInViewport(`COL`,n,t),i=this.getters.getColSize(e,t);return{start:r,size:i,end:r+(this.getters.isColHidden(e,t)?0:i)}}getRowDimensionsInViewport(e,t){let n=Kt(this.getters.getSheetViewVisibleRows()),r=this.getters.getColRowOffsetInViewport(`ROW`,n,t),i=this.getters.getRowSize(e,t);return{start:r,size:i,end:r+(this.getters.isRowHidden(e,t)?0:i)}}getAllActiveViewportsZonesAndRect(){let e=this.getters.getActiveSheetId();return this.getSubViewports(e).map(e=>({zone:e,rect:{x:e.offsetCorrectionX+this.gridOffsetX,y:e.offsetCorrectionY+this.gridOffsetY,...e.getMaxSize()}}))}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(S)}checkPositiveDimension(e){return e.width<0||e.height<0?`InvalidViewportSize`:`Success`}checkValuesAreDifferent(e){let{height:t,width:n}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===n&&e.height===t?`ValuesNotChanged`:`Success`}checkScrollingDirection({offsetX:e,offsetY:t}){let n=this.getMainInternalViewport(this.getters.getActiveSheetId());return!n.canScrollHorizontally&&e>0||!n.canScrollVertically&&t>0?`InvalidScrollingDirection`:`Success`}checkIfViewportsWillChange({offsetX:e,offsetY:t}){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();return this.getSubViewports(n).some(n=>n.willNewOffsetScrollViewport(b(e,0,r),b(t,0,i)))?`Success`:`ViewportScrollLimitsReached`}getMainViewport(e){let t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){let e={};for(let t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,n=0,r=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=n,this.gridOffsetY=r,this.recomputeViewports()}recomputeViewports(){for(let e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();this.getSubViewports(n).forEach(n=>n.setViewportOffset(b(e,0,r),b(t,0,i)))}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetScrollbarX||0,y:this.viewports[e]?.bottomRight.offsetScrollbarY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getNumberCols(e),i=this.getters.getNumberRows(e),a=Math.min(this.getters.getColRowOffset(`COL`,0,t,e),this.sheetViewWidth),o=Math.min(this.getters.getColRowOffset(`ROW`,0,n,e),this.sheetViewHeight),s=Math.max(this.sheetViewWidth-a,0),c=Math.max(this.sheetViewHeight-o,0),{xRatio:l,yRatio:u}=this.getFrozenSheetViewRatio(e),d=l<1,f=u<1,p=this.getViewportOffset(e),m={topLeft:n&&t&&new aB(this.getters,e,{left:0,right:t-1,top:0,bottom:n-1},{width:a,height:o},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:n&&new aB(this.getters,e,{left:t,right:r-1,top:0,bottom:n-1},{width:s,height:o},{canScrollHorizontally:d,canScrollVertically:!1},{x:d?p.x:0,y:0})||void 0,bottomLeft:t&&new aB(this.getters,e,{left:0,right:t-1,top:n,bottom:i-1},{width:a,height:c},{canScrollHorizontally:!1,canScrollVertically:f},{x:0,y:f?p.y:0})||void 0,bottomRight:new aB(this.getters,e,{left:t,right:r-1,top:n,bottom:i-1},{width:s,height:c},{canScrollHorizontally:d,canScrollVertically:f},{x:d?p.x:0,y:f?p.y:0})};this.viewports[e]=m}refreshViewport(e,t){this.getSubViewports(e).forEach(e=>{e.adjustViewportZone(),e.adjustPosition(t)})}shiftVertically(e){let t=this.getters.getActiveSheetId(),{top:n}=this.getMainInternalViewport(t),{scrollX:r}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(r,e);let{anchor:i}=this.getters.getSelection();if(i.cell.row>=this.getters.getPaneDivisions(t).ySplit){let e=this.getMainInternalViewport(t).top-n;this.selection.selectCell(i.cell.col,i.cell.row+e)}}getVisibleFigures(){let e=this.getters.getActiveSheetId(),t=[],n=this.getters.getFigures(e),{scrollX:r,scrollY:i}=this.getActiveSheetScrollInfo(),{x:a,y:o}=this.getters.getMainViewportCoordinates(),{width:s,height:c}=this.getters.getSheetViewDimensionWithHeaders();for(let e of n)e.x>=a&&(e.x+e.width<=a+r||e.x>=s+r+a)||e.y>=o&&(e.y+e.height<=o+i||e.y>=c+i+o)||t.push(e);return t}isPositionVisible(e){let{scrollX:t,scrollY:n}=this.getters.getActiveSheetScrollInfo(),{x:r,y:i}=this.getters.getMainViewportCoordinates(),{width:a,height:o}=this.getters.getSheetViewDimension();return!(e.x>=r&&(e.x<r+t||e.x>a+t+r)||e.y>=i&&(e.y<i+n||e.y>o+n+i))}getFrozenSheetViewRatio(e){let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getColDimensions(e,t).start,i=this.getters.getRowDimensions(e,n).start,a=this.sheetViewWidth+this.gridOffsetX,o=this.sheetViewHeight+this.gridOffsetY;return{xRatio:r/a,yRatio:i/o}}mapViewportsToRect(e,t){let n=1/0,r=1/0,i=0,a=0,o=!1;for(let s of this.getSubViewports(e)){let e=t(s);e&&(o=!0,n=Math.min(n,e.x),r=Math.min(r,e.y),i=Math.max(i,e.x+e.width),a=Math.max(a,e.y+e.height))}return o?{x:n,y:r,width:i-n,height:a-r}:{x:0,y:0,width:0,height:0}}},sB=class extends ${static getters=[`getColDimensions`,`getRowDimensions`,`getColRowOffset`];headerPositions={};isDirty=!0;handle(e){switch(Ri.has(e.type)&&(this.headerPositions={},this.isDirty=!0),e.type){case`START`:for(let e of this.getters.getSheetIds())this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e);break;case`UPDATE_CELL`:this.headerPositions={},this.isDirty=!0;break;case`UPDATE_FILTER`:case`UPDATE_TABLE`:case`REMOVE_TABLE`:this.headerPositions={},this.isDirty=!0;break;case`REMOVE_COLUMNS_ROWS`:case`RESIZE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_ALL_HEADER_GROUPS`:case`UNGROUP_HEADERS`:case`GROUP_HEADERS`:case`CREATE_SHEET`:this.getters.tryGetSheet(e.sheetId)&&(this.headerPositions[e.sheetId]=this.computeHeaderPositionsOfSheet(e.sheetId));break;case`DUPLICATE_SHEET`:this.headerPositions[e.sheetIdTo]=y(this.headerPositions[e.sheetId]);break}}finalize(){for(let e of this.getters.getSheetIds())(this.isDirty||!this.headerPositions[e])&&(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){let n=this.headerPositions[e].COL[t],r=this.getters.getColSize(e,t);return{start:n,size:r,end:n+(this.getters.isColHidden(e,t)?0:r)}}getRowDimensions(e,t){let n=this.headerPositions[e].ROW[t],r=this.getters.getRowSize(e,t);return{start:n,size:r,end:n+(this.getters.isRowHidden(e,t)?0:r)}}getColRowOffset(e,t,n,r=this.getters.getActiveSheetId()){let i=this.headerPositions[r][e][t];return this.headerPositions[r][e][n]-i}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,`COL`),ROW:this.computePositions(e,`ROW`)}}computePositions(e,t){let n={},r=0;for(let i=0;i<this.getters.getNumberHeaders(e,t)+1;i++)n[i]=r,!this.getters.isHeaderHidden(e,t,i)&&(r+=this.getters.getHeaderSize(e,t,i));return n}};let cB=new h().add(`settings`,YL).add(`sheet`,GL).add(`header grouping`,qL).add(`header visibility`,zL).add(`tables`,KL).add(`dataValidation`,IL).add(`cell`,AL).add(`merge`,VL).add(`headerSize`,RL).add(`borders`,OL).add(`conditional formatting`,FL).add(`figures`,LL).add(`chart`,NL).add(`image`,BL).add(`pivot_core`,JL).add(`spreadsheet_pivot_core`,XL).add(`tableStyle`,ZL),lB=new h().add(`ui_sheet`,yz).add(`ui_options`,vz).add(`autofill`,PR).add(`sort`,_z).add(`automatic_sum`,FR).add(`format`,mz).add(`insert_pivot`,gz).add(`pivot_presence`,Qz).add(`split_to_columns`,$z).add(`collaborative`,fz).add(`history`,Xz).add(`data_cleanup`,pz).add(`table_autofill`,eB).add(`table_ui_resize`,tB).add(`datavalidation_insert`,wz),uB=new h().add(`selection`,iB).add(`evaluation_filter`,rB).add(`header_visibility_ui`,hz).add(`cell_computed_style`,Cz).add(`table_computed_style`,bz).add(`header_positions`,sB).add(`viewport`,oB).add(`clipboard`,nB),dB=new h().add(`evaluation`,_R).add(`evaluation_chart`,SR).add(`evaluation_cf`,CR).add(`row_size`,DR).add(`data_validation_ui`,TR).add(`dynamic_tables`,ER).add(`custom_colors`,xR).add(`pivot_ui`,MR),fB=new h;fB.add(`link`,{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t)=>to(t.model.getters.getEvaluatedCell(e).link,t),sequence:5});var pB=class{fileStore;constructor(e){this.fileStore=e}async requestImage(){let e=await this.getImageFromUser(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}getImageFromUser(){return new Promise((e,t)=>{let n=document.createElement(`input`);n.setAttribute(`type`,`file`),n.setAttribute(`accept`,`image/*`),n.addEventListener(`change`,async()=>{n.files===null||n.files.length!==1?t():e(n.files[0])}),n.click()})}getImageOriginalSize(e){return new Promise((t,n)=>{let r=new Image;r.src=e,r.addEventListener(`load`,()=>{t({width:r.width,height:r.height})}),r.addEventListener(`error`,n)})}};let mB=[{transform:`scale(0)`},{transform:`scale(0.8)`,offset:.33},{opacity:`0`,transform:`scale(1)`,offset:1}];H`
1890
+ `;var wL=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:TN};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(I(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${Nu(e,i).join(`,`)})`,value:B(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{let{value:r,format:o}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${Nu(e,i).join(`,`)})`,value:B(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}n.push(t)}let r=n[n.length-1];return n[n.length-1]=r.map(e=>(e.isMissing||(e.style=`color: #756f6f;`),e)),n}_buildRowHeaders(e,t){let n=[];for(let r of t.rows){let t=[];for(let e=0;e<r.fields.length;e++)t.push({value:r.fields[e]},{value:r.values[e]});let i=this.pivot.parseArgsToPivotDomain(t),{value:a,format:o}=this.pivot.getPivotHeaderValueAndFormat(i),s=this.env.model.getters.getLocale(),c={formula:`=PIVOT.HEADER(${Nu(e,i).join(`,`)})`,value:B(a,{format:o,locale:s}),isMissing:!this.tracker?.isHeaderPresent(i)};r.indent>1&&(c.style=`padding-left: ${r.indent-10}px`),n.push(c)}return n}_buildValues(e,t){let n=[];for(let r of t.columns.at(-1)||[]){let i=[],a=I(r.values[r.values.length-1]);for(let n of t.rows){let t=[];for(let e=0;e<n.fields.length;e++)t.push({value:n.fields[e]},{value:n.values[e]});for(let e=0;e<r.fields.length-1;e++)t.push({value:r.fields[e]},{value:r.values[e]});let o=this.pivot.parseArgsToPivotDomain(t),{value:s,format:c}=this.pivot.getPivotCellValueAndFormat(a,o),l=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${Nu(e,o,a).join(`,`)})`,value:B(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},TL=class{static getters=[];history;dispatch;canDispatch;constructor(e,t,n){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t,this.canDispatch=n}exportForExcel(e){}allowDispatch(e){return`Success`}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map(e=>e.call(this,t)).flat()}chainValidations(...e){return t=>{for(let n of e){let e=n.call(this,t);Array.isArray(e)||(e=[e]);let r=e.filter(e=>e!==`Success`);if(r.length)return r}return`Success`}}checkValidations(e,...t){return this.batchValidations(...t)(e)}},EL=class extends TL{getters;uuidGenerator;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i,uuidGenerator:a}){super(t,r,i),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=a}import(e){}export(e){}adaptRanges(e,t){}garbageCollectExternalResources(){}},DL=class extends EL{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return`Success`}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>({...e})));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Be.style,color:e.border.color||Be.color})}break;case`CLEAR_FORMATTING`:this.clearBorders(e.sheetId,e.target);break;case`REMOVE_COLUMNS_ROWS`:let r=[...e.elements].sort((e,t)=>t-e);for(let t of ct(r))if(e.dimension===`COL`){if(t[0]>=this.getters.getNumberCols(e.sheetId))for(let n=0;n<this.getters.getNumberRows(e.sheetId);n++)this.history.update(`borders`,e.sheetId,t[0]+1,n,`vertical`,void 0);if(t[t.length-1]===0)for(let t=0;t<this.getters.getNumberRows(e.sheetId);t++)this.history.update(`borders`,e.sheetId,0,t,`vertical`,void 0);let n=this.getters.getColsZone(e.sheetId,t[t.length-1]+1,t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{if(t[0]>=this.getters.getNumberRows(e.sheetId))for(let n=0;n<this.getters.getNumberCols(e.sheetId);n++)this.history.update(`borders`,e.sheetId,n,t[0]+1,`horizontal`,void 0);if(t[t.length-1]===0)for(let t=0;t<this.getters.getNumberCols(e.sheetId);t++)this.history.update(`borders`,e.sheetId,t,0,`horizontal`,void 0);let n=this.getters.getRowsZone(e.sheetId,t[t.length-1]+1,t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity,{moveFirstTopBorder:!0}),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity,{moveFirstTopBorder:!1}),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r={top:this.borders[e]?.[t]?.[n]?.horizontal,bottom:this.borders[e]?.[t]?.[n+1]?.horizontal,left:this.borders[e]?.[t]?.[n]?.vertical,right:this.borders[e]?.[t+1]?.[n]?.vertical};return!r.bottom&&!r.left&&!r.right&&!r.top?null:r}getBordersColors(e){let t=[],n=this.borders[e];if(n)for(let e of n.filter(S))for(let n of e)n?.horizontal&&t.push(n.horizontal.color),n?.vertical&&t.push(n.vertical.color);return t}ensureColumnBorderContinuity(e,t,n){let r=x(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=x(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&C(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(S);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?x(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n,{moveFirstLeftBorder:r}={}){this.borders[e]&&(n<0&&this.moveBordersOfColumn(e,t,n,`vertical`,{destructive:!1}),this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(i=>{(i===t&&r||i!==t)&&this.moveBordersOfColumn(e,i,n,`vertical`),this.moveBordersOfColumn(e,i,n,`horizontal`)}))}shiftBordersVertically(e,t,n,{moveFirstTopBorder:r}={}){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,`horizontal`,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(i=>{(i===t&&r||i!==t)&&this.moveBordersOfRow(e,i,n,`horizontal`),this.moveBordersOfRow(e,i,n,`vertical`)}))}moveBordersOfRow(e,t,n,r,{destructive:i}={destructive:!0}){let a=this.borders[e];a&&this.getColumnsWithBorders(e).forEach(o=>{let s=a[o]?.[t+n]?.[r],c=a[o]?.[t]?.[r];this.history.update(`borders`,e,o,t+n,r,i?c:c||s),this.history.update(`borders`,e,o,t,r,void 0)})}moveBordersOfColumn(e,t,n,r,{destructive:i}={destructive:!0}){let a=this.borders[e];a&&this.getRowsRange(e).forEach(o=>{let s=a[t+n]?.[o]?.[r],c=a[t]?.[o]?.[r];this.history.update(`borders`,e,t+n,o,r,i?c:c||s),this.history.update(`borders`,e,t,o,r,void 0)})}setBorder(e,t,n,r,i=!0){(i||!this.borders?.[e]?.[t]?.[n]?.vertical)&&this.history.update(`borders`,e,t,n,`vertical`,r?.left),(i||!this.borders?.[e]?.[t]?.[n]?.horizontal)&&this.history.update(`borders`,e,t,n,`horizontal`,r?.top),(i||!this.borders?.[e]?.[t+1]?.[n]?.vertical)&&this.history.update(`borders`,e,t+1,n,`vertical`,r?.right),(i||!this.borders?.[e]?.[t]?.[n+1]?.horizontal)&&this.history.update(`borders`,e,t,n+1,`horizontal`,r?.bottom)}clearBorders(e,t){for(let n of T(t)){for(let t=n.top;t<=n.bottom;t++){this.history.update(`borders`,e,n.right+1,t,`vertical`,void 0);for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}for(let t=n.left;t<=n.right;t++)this.history.update(`borders`,e,t,n.bottom+1,`horizontal`,void 0)}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t);for(let i of T(t)){if(n===`h`||n===`hv`||n===`all`)for(let t=i.top+1;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r});if(n===`v`||n===`hv`||n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left+1;n<=i.right;n++)this.addBorder(e,n,t,{left:r});if(n===`left`||n===`all`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`all`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right+1,t,{left:r});if(n===`top`||n===`all`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`all`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom+1,{top:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||C(t,e.border)?`NoChanges`:`Success`}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let n in t.borders){let r=t.borders[n],i=e.borders[r],a=Qn(n);for(let e=a.top;e<=a.bottom;e++)for(let n=a.left;n<=a.right;n++)this.setBorder(t.id,n,e,i,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Qn(e))}export(e){let t={};for(let n of e.sheets){let e={};for(let r=0;r<n.colNumber;r++)for(let i=0;i<n.rowNumber;i++){let a=this.getCellBorder({sheetId:n.id,col:r,row:i});if(a){let o=Pr(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=Fr(e)}e.borders=t}exportForExcel(e){for(let t of e.sheets)for(let n=0;n<t.colNumber;n++)for(let r=0;r<t.rowNumber;r++){let i=this.getCellBorder({sheetId:t.id,col:n,row:r});if(i){let a=w(n,r);t.cells[a]??={},t.cells[a].border=Pr(i,e.borders)}}}},OL=class{map={};set({sheetId:e,col:t,row:n},r){let i=this.map;i[e]||(i[e]={}),i[e][t]||(i[e][t]={}),i[e][t][n]=r}get({sheetId:e,col:t,row:n}){return this.map[e]?.[t]?.[n]}getSheet(e){return this.map[e]}has({sheetId:e,col:t,row:n}){return this.map[e]?.[t]?.[n]!==void 0}delete({sheetId:e,col:t,row:n}){delete this.map[e]?.[t]?.[n]}keys(){let e=this.map,t=[];for(let n in e)for(let r in e[n])for(let i in e[n][r])t.push({sheetId:n,col:parseInt(r),row:parseInt(i)});return t}keysForSheet(e){let t=this.map[e];if(!t)return[];let n=[];for(let r in t)for(let i in t[r])n.push({sheetId:e,col:parseInt(r),row:parseInt(i)});return n}},kL=class extends EL{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellStyle`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges(e,t){for(let n of Object.keys(this.cells))for(let r of Object.values(this.cells[n]||{}))if(r.isFormula){for(let i of r.compiledFormula.dependencies)if(!t||i.sheetId===t){let t=e(i);t.changeType!==`NONE`&&this.history.update(`cells`,n,r.id,`compiledFormula`,`dependencies`,r.compiledFormula.dependencies.indexOf(i),t.range)}}}allowDispatch(e){switch(e.type){case`UPDATE_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case`CLEAR_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case`UPDATE_CELL_POSITION`:return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?`Success`:`InvalidCellId`;default:return`Success`}}handle(e){switch(e.type){case`SET_FORMATTING`:`style`in e&&this.setStyle(e.sheetId,e.target,e.style),`format`in e&&e.format!==void 0&&this.setFormatter(e.sheetId,e.target,e.format);break;case`CLEAR_FORMATTING`:this.clearFormatting(e.sheetId,e.target);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,style:null,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of T(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.getters.getCell({sheetId:e,col:t,row:r})&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}setFormatter(e,t,n){for(let r of T(t))for(let t=r.top;t<=r.bottom;t++)for(let i=r.left;i<=r.right;i++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:i,row:t,format:n})}clearFormatting(e,t){for(let n of T(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,style:null,format:``})}clearCells(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:``,style:null,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=x(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=x(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){for(let t of e.sheets){let n=t.id,r=new OL;for(let e in t.cells)if(t.cells[e]?.content){let{col:n,row:i}=Pn(e),a={sheetId:t.id,col:n,row:i};r.set(a,{content:t.cells[e]?.content})}for(let[e,i]of[[`style`,t.styles],[`format`,t.formats]])for(let t in i){let a=i[t],o=Qn(t);for(let t=o.top;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++){let o={sheetId:n,col:i,row:t},s=r.get(o);s?s[e]=a:r.set(o,{[e]:a})}}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format||n?.style){let r=this.importCell(t.id,n?.content,n?.style?e.styles[n?.style]:void 0,n?.format?e.formats[n?.format]:void 0);this.history.update(`cells`,t.id,r.id,r),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:r.id,...i})}}}}export(e){let t={},n={};for(let r of e.sheets){let e=[],i=[],a={},o=Object.keys(this.cells[r.id]||{}).map(e=>this.getters.getCellPosition(e)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let r of o){let o=this.getters.getCell(r),s=w(r.col,r.row),c=this.extractCustomStyle(o);if(Object.keys(c).length){let n=Pr(c,t);e[n]??=[],e[n].push(r)}if(o.format){let e=Pr(o.format,n);i[e]??=[],i[e].push(r)}o.content&&(a[s]={content:o.content})}r.styles=Fr(e),r.formats=Fr(i),r.cells=a}e.styles=t,e.formats=n}importCell(e,t,n,r){let i=this.getNextUid();return this.createCell(i,t||``,r,n,e)}exportForExcel(e){this.export(e);for(let t of e.sheets)for(let n in this.getters.getCells(t.id)){let{col:r,row:i}=this.getters.getCellPosition(n),a=w(r,i),o=this.getCellById(n);t.cells[a]??={},o?.format&&(t.cells[a].format=Pr(o.format,e.formats)),o?.style&&(t.cells[a]??={},t.cells[a].style=Pr(this.extractCustomStyle(o),e.styles))}let t=[];for(let n in e.formats||[])fs(e.formats[n])||(t.push(n),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.cells){let r=n.cells[e],i=r?.format;i&&t.includes(i.toString())&&delete r.format}}extractCustomStyle(e){let t={...e.style},n=Oi(e.content,k)?Fe:Pe;for(let r in t)(r!==`align`||!e.isFormula)&&t[r]===n[r]&&delete t[r];return t}getCells(e){return this.cells[e]||{}}getCellById(e){let t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,n,r=!1){if(!n.length)return Tt(t.map(e=>e.value));let i=0;return Tt(t.map(t=>{if(t.type===`REFERENCE`){let t=n[i++];return this.getters.getRangeString(t,e,{useBoundedReference:r})}return t.value}))}getTranslatedCellFormula(e,t,n,r){let i=this.getters.createAdaptedRanges(kE(r).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t,n){let r=kE(n).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),i=this.getters.removeRangesSheetPrefix(t,r);return this.getFormulaString(t,n,i)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=w(t.left,t.top,n[0]),i=w(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}setStyle(e,t,n){for(let r of T(t))for(let t=r.left;t<=r.right;t++)for(let i=r.top;i<=r.bottom;i++){let r=this.getters.getCell({sheetId:e,col:t,row:i});this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:i,style:n?{...r?.style,...n}:void 0})}}copyColumnStyle(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowStyle(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:r,row:t,...i})}}getFormat(e,t,n){let r={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.getters.getCell(i);return a&&(a.style&&(r.style=a.style),a.format&&(r.format=a.format)),r}getNextUid(){let e=this.nextId.toString();return this.history.update(`nextId`,this.nextId+1),e}updateCell(e,t,n,r){let i=this.getters.getCell({sheetId:e,col:t,row:n}),a=r.content!==void 0||`formula`in r,o=a?It(r?.content||void 0):i?.content||``,s;s=r.style===void 0?i?i.style:void 0:r.style||void 0;let c=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||i.content===``))&&!s&&!c){i&&(this.history.update(`cells`,e,i.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let l=i?.id||this.getNextUid(),u=this.createCell(l,o,c,s,e);this.history.update(`cells`,e,u.id,u),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:u.id,col:t,row:n,sheetId:e})}createCell(e,t,n,r,i){return t.startsWith(`=`)?this.createFormulaCell(e,t,n,r,i):this.createLiteralCell(e,t,n,r)}createLiteralCell(e,t,n,r){let i=this.getters.getLocale(),a=hs(t,i);return n||=typeof a==`number`?Xo(t,i)||Zo(t):void 0,!ps(n)&&!P(t)&&(t=I(a)),{id:e,content:t,style:r,format:n,isFormula:!1,parsedValue:a}}createFormulaCell(e,t,n,r,i){let a=OE(t);return a.dependencies.length?this.createFormulaCellWithDependencies(e,a,n,r,i):{id:e,content:t,style:r,format:n,isFormula:!0,compiledFormula:{...a,dependencies:[]}}}createFormulaCellWithDependencies(e,t,n,r,i){let a=[];for(let e of t.dependencies)a.push(this.getters.getRangeFromSheetXC(i,e));return new AL(e,t,n,r,a,i,this.getters.getRangeString)}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?dr(n,r,this.getters.getSheetZone(t))?`Success`:`TargetOutOfSheet`:`InvalidSheetId`}checkUselessClearCell(e){let t=this.getters.getCell(e);return!t||!t.content&&!t.style&&!t.format?`NoChanges`:`Success`}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=`format`in e;return(!n||t?.content===e.content)&&(!r||C(t?.style,e.style))&&(!i||t?.format===e.format)?`NoChanges`:`Success`}},AL=class{id;format;style;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,n,r,i,a,o){this.id=e,this.format=n,this.style=r,this.sheetId=a,this.getRangeString=o;let s=0,c=t.tokens.map(e=>e.type===`REFERENCE`?new jL(i,s++,this.sheetId,this.getRangeString):e);this.compiledFormula={...t,dependencies:i,tokens:c}}get content(){return Tt(this.compiledFormula.tokens.map(e=>e.value))}get contentWithFixedReferences(){let e=0;return Tt(this.compiledFormula.tokens.map(t=>{if(t.type===`REFERENCE`){let t=e++;return this.getRangeString(this.compiledFormula.dependencies[t],this.sheetId,{useBoundedReference:!0})}return t.value}))}},jL=class{ranges;rangeIndex;sheetId;getRangeString;type=`REFERENCE`;constructor(e,t,n,r){this.ranges=e,this.rangeIndex=t,this.sheetId=n,this.getRangeString=r}get value(){let e=this.ranges[this.rangeIndex];return this.getRangeString(e,this.sheetId)}},ML=class extends EL{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getContextCreationChart`];charts={};createChart=hk(this.getters);validateChartDefinition=e=>_k(this,e.definition);adaptRanges(e){for(let[t,n]of Object.entries(this.charts))this.history.update(`charts`,t,n?.updateRanges(e))}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case`UPDATE_CHART`:return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists));default:return`Success`}}handle(e){switch(e.type){case`CREATE_CHART`:this.addFigure(e.id,e.sheetId,e.position,e.size),this.addChart(e.id,e.definition);break;case`UPDATE_CHART`:this.addChart(e.id,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`chart`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.charts[n.id]?.copyForSheetId(e.sheetIdTo);i&&this.dispatch(`CREATE_CHART`,{id:r,position:{x:n.x,y:n.y},size:{width:n.width,height:n.height},definition:i.getDefinition(),sheetId:e.sheetIdTo})}break}case`DELETE_FIGURE`:this.history.update(`charts`,e.id,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){let t=this.charts[e]?.type;if(!t)throw Error(`Chart not defined.`);return t}isChartDefined(e){return e in this.charts&&this.charts!==void 0}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.getDefinition();if(!t)throw Error(`There is no chart with the given figureId: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)e.tag===`chart`&&(this.charts[e.id]=this.createChart(e.id,e.data,t.id))}export(e){if(e.sheets)for(let t of e.sheets){let e=this.getters.getFigures(t.id),n=[];for(let t of e){let e=t;if(e&&e.tag===`chart`){let t=this.charts[e.id]?.getDefinition();t&&(e.data=t,n.push(e))}else n.push(e)}t.figures=n}}addFigure(e,t,n={x:0,y:0},r={width:536,height:335}){if(this.getters.getFigure(t,e))return;let i={id:e,x:n.x,y:n.y,width:r.width,height:r.height,tag:`chart`};this.dispatch(`CREATE_FIGURE`,{sheetId:t,figure:i})}addChart(e,t){let n=this.getters.getFigureSheetId(e);n&&this.history.update(`charts`,e,this.createChart(e,t,n))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.id)?`DuplicatedChartId`:`Success`}checkChartExists(e){return this.isChartDefined(e.id)?`Success`:`ChartDoesNotExist`}};function NL(e){return e===``?NaN:Number(e)}var PL=class extends EL{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};loopThroughRangesOfSheet(e,t){for(let n of this.cfRules[e]){if(n.rule.type===`DataBarRule`&&n.rule.rangeValues){let r=t(n.rule.rangeValues);switch(r.changeType){case`REMOVE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`rule`,`rangeValues`,r.range);break}}for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}}adaptRanges(e,t){if(t)this.loopThroughRangesOfSheet(t,e);else for(let t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return this.checkValidations(e,this.checkCFRule,this.checkEmptyRange);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)dr(t,n,e.zone)&&r.push(i);return new Set(r.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,n,r){if(n.length===0&&r.length===0)return;let i=this.getters.getConditionalFormats(e),a=i.findIndex(e=>e.id===t.id),o=[];a>-1&&(o=i[a].ranges.map(Zn));let s=T(o,r);return T([...n,...s],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:n}={useBoundedReference:!1}){let r=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:n}));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:n})},ranges:r}:{...t,rule:{...t.rule},ranges:r}}mapToConditionalFormatInternal(e,t){let n=t.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:n}:{...t,rule:{...t.rule},ranges:n}}addConditionalFormatting(e,t){let n=this.cfRules[t].slice(),r=n.findIndex(t=>t.id===e.id),i=this.mapToConditionalFormatInternal(t,e);r>-1?n.splice(r,1,i):n.push(i),this.history.update(`cfRules`,t,n)}checkValidPriorityChange(e,t,n){if(!this.cfRules[n])return`InvalidSheetId`;let r=this.cfRules[n].findIndex(t=>t.id===e);if(r===-1)return`InvalidConditionalFormatId`;let i=r-t;return i<0||i>=this.cfRules[n].length?`InvalidConditionalFormatId`:`Success`}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}checkCFRule(e){let t=e.cf.rule;switch(t.type){case`CellIsRule`:return ig[t.operator]?this.checkValidations(t,this.checkOperatorArgsNumber(2,[`Between`,`NotBetween`]),this.checkOperatorArgsNumber(1,[`BeginsWith`,`ContainsText`,`EndsWith`,`GreaterThan`,`GreaterThanOrEqual`,`LessThan`,`LessThanOrEqual`,`NotContains`,`Equal`,`NotEqual`]),this.checkOperatorArgsNumber(0,[`IsEmpty`,`IsNotEmpty`]),this.checkCFValues):`InvalidConditionalFormatType`;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return`Success`}return`InvalidConditionalFormatType`}checkOperatorArgsNumber(e,t){if(e>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);return n=>{if(t.includes(n.operator)){let t=[],r=e=>e===void 0||e===``;return e>=1&&r(n.values[0])&&t.push(`FirstArgMissing`),e>=2&&r(n.values[1])&&t.push(`SecondArgMissing`),t.length?t:`Success`}return`Success`}}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return`MinNaN`;case`max`:return`MaxNaN`;case`mid`:return`MidNaN`;case`upperInflectionPoint`:return`ValueUpperInflectionNaN`;case`lowerInflectionPoint`:return`ValueLowerInflectionNaN`}return`Success`}checkFormulaCompilation(e,t){if(e.type!==`formula`)return`Success`;if(OE(e.value||``).isBadExpression)switch(t){case`min`:return`MinInvalidFormula`;case`max`:return`MaxInvalidFormula`;case`mid`:return`MidInvalidFormula`;case`upperInflectionPoint`:return`ValueUpperInvalidFormula`;case`lowerInflectionPoint`:return`ValueLowerInvalidFormula`}return`Success`}checkThresholds(e){return this.batchValidations(t=>e(t.minimum,`min`),t=>e(t.maximum,`max`),t=>t.midpoint?e(t.midpoint,`mid`):`Success`)}checkInflectionPoints(e){return this.batchValidations(t=>e(t.lowerInflectionPoint,`lowerInflectionPoint`),t=>e(t.upperInflectionPoint,`upperInflectionPoint`))}checkLowerBiggerThanUpper(e){let t=e.lowerInflectionPoint.value,n=e.upperInflectionPoint.value;return[`number`,`percentage`,`percentile`].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(n)?`LowerBiggerThanUpper`:`Success`}checkMinBiggerThanMax(e){let t=e.minimum.value,n=e.maximum.value;return[`number`,`percentage`,`percentile`].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&NL(t)>=NL(n)?`MinBiggerThanMax`:`Success`}checkMidBiggerThanMax(e){let t=e.midpoint?.value,n=e.maximum.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&NL(t)>=NL(n)?`MidBiggerThanMax`:`Success`}checkMinBiggerThanMid(e){let t=e.minimum.value,n=e.midpoint?.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&NL(t)>=NL(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&OE(t||``).isBadExpression)return`ValueCellIsInvalidFormula`;return`Success`}removeConditionalFormatting(e,t){let n=this.cfRules[t].findIndex(t=>t.id===e);if(n!==-1){let e=this.cfRules[t].slice();e.splice(n,1),this.history.update(`cfRules`,t,e)}}changeCFPriority(e,t,n){let r=this.cfRules[n].findIndex(t=>t.id===e),i=this.cfRules[n][r],a=r-t,o=[...this.cfRules[n]];o.splice(r,1),o.splice(a,0,i),this.history.update(`cfRules`,n,o)}},FL=class extends EL{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e,t){let n=t?[t]:Object.keys(this.rules);for(let t of n)this.loopThroughRangesOfSheet(t,e)}loopThroughRangesOfSheet(e,t){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return this.getters.tryGetSheet(e.sheetId)?this.checkValidations(e,this.chainValidations(this.checkEmptyRange,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`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=y(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>Ws(e.sheetId,e.sheetIdTo,t))}));this.history.update(`rules`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.rules};delete t[e.sheetId],this.history.update(`rules`,t);break}case`REMOVE_DATA_VALIDATION_RULE`:this.removeDataValidationRule(e.sheetId,e.id);break;case`ADD_DATA_VALIDATION_RULE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case`DELETE_CONTENT`:{let t=T(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(e&&(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!this.getters.getCell({sheetId:n,col:r,row:t})?.content)){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,w(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(dr(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`arrow`:!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=y(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of qs(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:e?.style?.align??`center`,verticalAlign:e?.style?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...y(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return Q.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=Q.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=Q.get(t.type);return t.values.some(e=>e.startsWith(`=`)?n.allowedValues===`onlyLiterals`:n.allowedValues===`onlyFormulas`?!0:!n.isCriterionValueValid(e))?`InvalidDataValidationCriterionValue`:`Success`}},IL=class extends EL{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkFigureDuplicate(e.figure.id);case`UPDATE_FIGURE`:case`DELETE_FIGURE`:return this.checkFigureExists(e.sheetId,e.id);default:return`Success`}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{id:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:this.addFigure(e.figure,e.sheetId);break;case`UPDATE_FIGURE`:let{type:t,sheetId:n,...r}=e,i=r;this.updateFigure(n,i);break;case`DELETE_FIGURE`:this.removeFigure(e.id,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:this.onRowColDelete(e.sheetId,e.dimension)}}onRowColDelete(e,t){t===`ROW`?this.onRowDeletion(e):this.onColDeletion(e)}onRowDeletion(e){let t=this.getters.getNumberRows(e),n=0;for(let r=0;r<t;r++)n+=this.getters.getUserRowSize(e,r)||23;let r=this.getters.getFigures(e);for(let t of r){let r=Math.min(t.y,n-t.height);r!==t.y&&this.dispatch(`UPDATE_FIGURE`,{sheetId:e,id:t.id,y:r})}}onColDeletion(e){let t=this.getters.getNumberCols(e),n=0;for(let r=0;r<t;r++)n+=this.getters.getColSize(e,r);let r=this.getters.getFigures(e);for(let t of r){let r=Math.min(t.x,n-t.width);r!==t.x&&this.dispatch(`UPDATE_FIGURE`,{sheetId:e,id:t.id,x:r})}}updateFigure(e,t){if(`id`in t)for(let[n,r]of Object.entries(t))switch(n){case`x`:case`y`:r!==void 0&&this.history.update(`figures`,e,t.id,n,Math.max(r,0));break;case`width`:case`height`:r!==void 0&&this.history.update(`figures`,e,t.id,n,r);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e,t){return this.figures[e]?.[t]===void 0?`FigureDoesNotExist`:`Success`}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e])?`DuplicatedFigureId`:`Success`}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){this.export(e)}},LL=class extends EL{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,y(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=zt(t,e.elements);this.history.update(`sizes`,e.sheetId,e.dimension,n);break}case`ADD_COLUMNS_ROWS`:{let t=[...this.sizes[e.sheetId][e.dimension]],n=Ot(e.position,e.base),r=t[e.base];t=Bt(t,Array(e.quantity).fill(r),n),this.history.update(`sizes`,e.sheetId,e.dimension,t);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of x(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of x(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},RL=class extends EL{static getters=[`checkElementsIncludeAllVisibleHeaders`,`getHiddenColsGroups`,`getHiddenRowsGroups`,`isHeaderHiddenByUser`,`isRowHiddenByUser`,`isColHiddenByUser`];hiddenHeaders={};allowDispatch(e){switch(e.type){case`HIDE_COLUMNS_ROWS`:{if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=e.dimension===`COL`?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),n=e.dimension===`COL`?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=n?`TooManyHiddenElements`:Kt(e.elements)<0||Gt(e.elements)>n?`InvalidHeaderIndex`:`Success`}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`:`InvalidSheetId`}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,y(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=Ot(e.position,e.base),n=Bt([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,n);break}case`HIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!0);break;case`UNHIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!1);break}}checkElementsIncludeAllVisibleHeaders(e,t,n){return At(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=x(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...x(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},zL=class extends EL{static getters=[`getImage`,`getImagePath`,`getImageSize`];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){switch(e.type){case`CREATE_IMAGE`:return this.getters.getFigure(e.sheetId,e.figureId)?`InvalidFigureId`:`Success`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_IMAGE`:this.addImage(e.figureId,e.sheetId,e.position,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,position:{x:n.x,y:n.y},size:t,definition:y(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.id,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}garbageCollectExternalResources(){let e=new Set(this.getAllImages().map(e=>e.path));for(let t of this.syncedImages)e.has(t)||this.fileStore?.delete(t)}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addImage(e,t,n,r){let i={id:e,x:n.x,y:n.y,width:r.width,height:r.height,tag:`image`};this.dispatch(`CREATE_FIGURE`,{sheetId:t,figure:i})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:y(e)})}t.images=[...t.images,...n]}}getAllImages(){let e=[];for(let t in this.images)e.push(...Object.values(this.images[t]||{}).filter(S));return e}},BL=class extends EL{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`getSelectionRangeString`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(S))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e,t){let n=t?[t]:Object.keys(this.merges);for(let t of n)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(S)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(S)}getSelectionRangeString(e,t){let n=Us.fromRange(e,this.getters),r=this.getters.expandZone(n.sheetId,n.zone),i=n.clone({zone:{...r,bottom:n.isFullCol?void 0:r.bottom,right:n.isFullRow?void 0:r.right}}),a=this.getters.getRangeString(i,t);if(this.isSingleCellOrMerge(n.sheetId,n.zone)){let{sheetName:e,xc:t}=Vs(a);return Hs(e,t.split(`:`)[0])}return a}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(ur(t,n))return!0;return!1}doesColumnsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(r.id,t,i,n,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(r.id,i,t,i,n))return!0;return!1}expandZone(e,t){let{left:n,right:r,top:i,bottom:a}=t,o={left:n,right:r,top:i,bottom:a};for(let t in this.merges[e]){let n=this.getMergeById(e,parseInt(t));n&&ur(n,o)&&(o=or(n,o))}return lr(o,t)?o:this.expandZone(e,o)}isInSameMerge(e,t,n,r,i){let a=this.getMerge({sheetId:e,col:t,row:n}),o=this.getMerge({sheetId:e,col:r,row:i});return!a||!o?!1:lr(a,o)}isInMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e];return r?t in r&&!!r[t]?.[n]:!1}getMainCellPosition(e){let t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){let n=this.getters.getHiddenColsGroups(e),r=this.getters.getHiddenRowsGroups(e);for(let e of n)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of r)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){let n=this.getMerge({sheetId:e,col:t.left,row:t.top});if(n)return lr(t,n);let{numberOfCols:r,numberOfRows:i}=pr(t);return r===1&&i===1}isMainCellPosition(e){return C(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=b(r,0,this.getters.getNumberCols(e)-1),a=b(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&n.content!==``)return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:HL(t,n)}checkDestructiveMerge({sheetId:e,target:t}){return this.getters.tryGetSheet(e)&&t.some(t=>this.isMergeDestructive(e,t))?`MergeIsDestructive`:`Success`}checkOverlap({target:e}){for(let t of e)for(let n of e)if(t!==n&&ur(t,n))return`MergeOverlap`;return`Success`}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return`Success`;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);for(let e of t)if(e.left<n&&e.right>=n||e.top<r&&e.bottom>=r)return`FrozenPaneOverlap`;return`Success`}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return`Success`;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?`Success`:`CellIsMerged`}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!lr(e,i))return`InvalidTarget`}return`Success`}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=b(r,0,this.getters.getNumberCols(e)-1),a=b(a,0,this.getters.getNumberRows(e)-1),w(n,i)===w(r,a))return;let o=this.getters.getCell({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,tr({left:n,top:i,right:r,bottom:a})));let c=new Set;for(let t=i;t<=a;t++)for(let a=n;a<=r;a++){(a!==n||t!==i)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:t,style:o?o.style:null,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&c.add(r.id),this.history.update(`mergeCellMap`,e,a,t,s)}for(let t of c){let{top:n,bottom:r,left:i,right:a}=this.getMergeById(e,t);for(let t=n;t<=r;t++)for(let n=i;n<=a;n++){let r={sheetId:e,col:n,row:t},i=this.getMerge(r);(!i||i.id!==s)&&(this.history.update(`mergeCellMap`,e,n,t,void 0),this.dispatch(`CLEAR_CELL`,r))}this.history.update(`merges`,e,t,void 0)}}removeMerge(e,t){let{left:n,top:r,bottom:i,right:a}=t,o=this.getMerge({sheetId:e,col:n,row:r});if(!(o===void 0||!lr(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,t){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=pr(a.range.zone);t===1&&i===1?this.removeMerge(e,n):this.history.update(`merges`,e,parseInt(r,10),a.range);break}}this.history.update(`mergeCellMap`,e,{});for(let t of this.getMerges(e))for(let{col:n,row:r}of _r(t))this.history.update(`mergeCellMap`,e,n,r,t.id)}import(e){let t=e.sheets||[];for(let e of t)this.history.update(`merges`,e.id,{}),this.history.update(`mergeCellMap`,e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let n of t)this.addMerge(e,Qn(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...VL(e))}}exportForExcel(e){this.export(e)}};function VL(e){return Object.entries(e).map(([e,t])=>t?HL(parseInt(e,10),t):void 0).filter(S).map(e=>w(e.left,e.top)+`:`+w(e.right,e.bottom))}function HL(e,t){return{...t.zone,id:e}}var UL=class{getters;providers=[];isAdaptingRanges=!1;constructor(e){this.getters=e}static getters=[`extendRange`,`getRangeString`,`getRangeFromSheetXC`,`createAdaptedRanges`,`getRangeDataFromXc`,`getRangeDataFromZone`,`getRangeFromRangeData`,`getRangeFromZone`,`getRangesUnion`,`recomputeRanges`,`isRangeValid`,`removeRangesSheetPrefix`];allowDispatch(e){return e.type===`MOVE_RANGES`?e.target.length===1?`Success`:`InvalidZones`:`Success`}beforeHandle(e){}handle(e){if(this.isAdaptingRanges)throw Error(`Plugins cannot dispatch commands during adaptRanges phase`);switch(e.type){case`REMOVE_COLUMNS_ROWS`:{let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`,i=[...e.elements];i.sort((e,t)=>t-e);let a=ct(i);this.executeOnAllRanges(i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`};let o=i,s=`NONE`;for(let e of a){let a=Kt(e),c=Gt(e);if(i.zone[t]<=a&&a<=i.zone[n]){let e=Math.min(i.zone[n],c)-a+1;s=`RESIZE`,o=this.createAdaptedRange(o,r,s,-e)}else if(i.zone[t]>=a&&i.zone[n]<=c)s=`REMOVE`,o=i.clone({...this.getInvalidRange()});else if(i.zone[t]<=c&&i.zone[n]>=c){let e=c-i.zone[t]+1;s=`RESIZE`,o=this.createAdaptedRange(o,r,s,-e),o=this.createAdaptedRange(o,r,`MOVE`,-(i.zone[t]-a))}else a<i.zone[t]&&(s=`MOVE`,o=this.createAdaptedRange(o,r,s,-(c-a+1)))}return s===`NONE`?{changeType:`NONE`}:{changeType:s,range:o}},e.sheetId);break}case`ADD_COLUMNS_ROWS`:{let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`;this.executeOnAllRanges(i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`};if(e.position===`after`){if(i.zone[t]<=e.base&&e.base<i.zone[n])return{changeType:`RESIZE`,range:this.createAdaptedRange(i,r,`RESIZE`,e.quantity)};if(e.base<i.zone[t])return{changeType:`MOVE`,range:this.createAdaptedRange(i,r,`MOVE`,e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[n])return{changeType:`RESIZE`,range:this.createAdaptedRange(i,r,`RESIZE`,e.quantity)};if(e.base<=i.zone[t])return{changeType:`MOVE`,range:this.createAdaptedRange(i,r,`MOVE`,e.quantity)}}return{changeType:`NONE`}},e.sheetId);break}case`DELETE_SHEET`:this.executeOnAllRanges(t=>{if(t.sheetId!==e.sheetId)return{changeType:`NONE`};let n=this.getters.getSheetName(e.sheetId);return t=t.clone({...this.getInvalidRange(),invalidSheetName:n}),{changeType:`REMOVE`,range:t}},e.sheetId);break;case`RENAME_SHEET`:this.executeOnAllRanges(t=>{if(t.sheetId===e.sheetId)return{changeType:`CHANGE`,range:t};if(tc(t.invalidSheetName,e.name)){let n=e.sheetId;return{changeType:`CHANGE`,range:t.clone({sheetId:n,invalidSheetName:void 0})}}return{changeType:`NONE`}});break;case`MOVE_RANGES`:{let t=e.target[0];this.executeOnAllRanges(n=>{if(n.sheetId!==e.sheetId||!fr(n.zone,t))return{changeType:`NONE`};let r=e.targetSheetId,i=e.col-t.left,a=e.row-t.top,o=this.createAdaptedRange(n,`both`,`MOVE`,[i,a]),s=e.sheetId===r?o.prefixSheet:!0;return{changeType:`MOVE`,range:o.clone({sheetId:r,prefixSheet:s})}});break}}}finalize(){}verifyRangeRemoved(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!$n(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}createAdaptedRange(e,t,n,r){let i=yr(e.unboundedZone,t,n,r);return e.clone({zone:i})}executeOnAllRanges(e,t){this.isAdaptingRanges=!0;let n=this.verifyRangeRemoved(e);for(let e of this.providers)e(n,t);this.isAdaptingRanges=!1}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,n,r){return e.map(e=>Us.fromRange(e,this.getters)).map(e=>{if(!$n(e.zone))return e;let i=e.prefixSheet?e.sheetId:r,a={...e.unboundedZone,left:e.isFullRow&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:e.isFullRow?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.isFullCol&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:n),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:n)};return e.clone({sheetId:i,zone:a}).orderZone()})}removeRangesSheetPrefix(e,t){return t.map(t=>{let n=Us.fromRange(t,this.getters);return n.prefixSheet&&n.sheetId===e?n.clone({prefixSheet:!1}):n})}extendRange(e,t,n){let r=Us.fromRange(e,this.getters),i=t===`COL`?r.zone.right+n:r.zone.right,a=t===`ROW`?r.zone.bottom+n:r.zone.bottom,o={left:r.zone.left,top:r.zone.top,right:r.isFullRow?void 0:i,bottom:r.isFullCol?void 0:a};return new Us({...r,zone:o},this.getters.getSheetSize).orderZone()}getRangeFromSheetXC(e,t){if(!Fs.test(t)||!this.getters.tryGetSheet(e))return new Us({sheetId:``,zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let n,r=t,i=!1;t.includes(`!`)&&({xc:r,sheetName:n}=Vs(t),n&&(i=!0));let a=Zn(r),o=Us.getRangeParts(r,a),s=n&&!this.getters.getSheetIdByName(n)?n:void 0,c=this.getters.getSheetIdByName(n)||e;return new Us({prefixSheet:i,zone:a,sheetId:c,invalidSheetName:s,parts:o},this.getters.getSheetSize).orderZone()}getRangeString(e,t,n={useBoundedReference:!1,useFixedReference:!1}){if(!e)return j.InvalidReference;if(e.invalidXc)return e.invalidXc;if(!this.getters.tryGetSheet(e.sheetId)||e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0||e.zone.left<0||e.zone.top<0)return j.InvalidReference;let r=Us.fromRange(e,this.getters),i=r.sheetId!==t||r.invalidSheetName||r.prefixSheet,a=``;if(i&&(a=r.invalidSheetName?ot(r.invalidSheetName):ot(this.getters.getSheetName(r.sheetId))),i&&!a)return j.InvalidReference;let o=this.getRangePartString(r,0,n);return r.parts&&r.parts.length===2&&(r.zone.top!==r.zone.bottom||r.zone.left!==r.zone.right||r.parts[0].rowFixed||r.parts[0].colFixed||r.parts[1].rowFixed||r.parts[1].colFixed)&&(o+=`:`,o+=this.getRangePartString(r,1,n)),`${i?a+`!`:``}${o}`}getRangeDataFromXc(e,t){return this.getters.getRangeFromSheetXC(e,t).rangeData}getRangeDataFromZone(e,t){return t=this.getters.getUnboundedZone(e,t),{_sheetId:e,_zone:t}}getRangeFromZone(e,t){return new Us({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){return T(e.map(e=>Us.fromRange(e,this.getters).unboundedZone),t.map(e=>Us.fromRange(e,this.getters).unboundedZone)).map(t=>this.getRangeFromZone(e[0].sheetId,t))}getRangeFromRangeData(e){return new Us({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;let{xc:t,sheetName:n}=Vs(e);return t.match(Fs)!==null&&(!n||this.getters.getSheetIdByName(n)!==void 0)}getRangesUnion(e){let t=sr(...e.map(e=>Us.fromRange(e,this.getters).unboundedZone));return this.getRangeFromZone(e[0].sheetId,t)}getRangePartString(e,t,n={useBoundedReference:!1,useFixedReference:!1}){let r=e.parts[t]?.colFixed||n.useFixedReference?`$`:``,i=Tn(t===0?e.zone.left:e.zone.right),a=e.parts[t]?.rowFixed||n.useFixedReference?`$`:``,o=String(t===0?e.zone.top+1:e.zone.bottom+1),s=``;return s=e.isFullCol&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:r+i:e.isFullRow&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:a+o:r+i+a+o,s}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:``,invalidXc:j.InvalidReference}}},WL=class extends EL{static getters=`getSheetName.tryGetSheetName.getSheet.tryGetSheet.getSheetIdByName.getSheetIds.getVisibleSheetIds.isSheetVisible.doesHeaderExist.doesHeadersExist.getCell.getCellPosition.getColsZone.getRowCells.getRowsZone.getNumberCols.getNumberRows.getNumberHeaders.getGridLinesVisibility.getNextSheetName.getSheetSize.getSheetZone.getPaneDivisions.checkZonesExistInSheet.getCommandZones.getUnboundedZone.checkElementsIncludeAllNonFrozenHeaders.getDuplicateSheetName`.split(`.`);sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){let t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if(t!==`Success`)return t;switch(e.type){case`HIDE_SHEET`:return this.getVisibleSheetIds().length===1?`NotEnoughSheets`:`Success`;case`CREATE_SHEET`:return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case`DUPLICATE_SHEET`:return this.sheets[e.sheetIdTo]?`DuplicatedSheetId`:this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?`DuplicatedSheetName`:`Success`;case`MOVE_SHEET`:try{let t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),`Success`}catch{return`WrongSheetMove`}case`RENAME_SHEET`:return this.isRenameAllowed(e);case`COLOR_SHEET`:return!e.color||tn(e.color)?`Success`:`InvalidColor`;case`DELETE_SHEET`:return this.getVisibleSheetIds().length>1?`Success`:`NotEnoughSheets`;case`ADD_COLUMNS_ROWS`:return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?`InvalidQuantity`:`Success`:`InvalidHeaderIndex`;case`REMOVE_COLUMNS_ROWS`:{let t=Kt(e.elements),n=Gt(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,n)?`InvalidHeaderIndex`:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`}case`FREEZE_ROWS`:return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case`FREEZE_COLUMNS`:return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return`Success`}}handle(e){switch(e.type){case`SET_GRID_LINES_VISIBILITY`:this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case`CREATE_SHEET`:let t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update(`sheetIdsMapName`,t.name,t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.name);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case`UPDATE_CELL_POSITION`:this.updateCellPosition(e);break;case`FREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,e.quantity,`COL`);break;case`FREEZE_ROWS`:this.setPaneDivisions(e.sheetId,e.quantity,`ROW`);break;case`UNFREEZE_ROWS`:this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`UNFREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,0,`COL`);break;case`UNFREEZE_COLUMNS_ROWS`:this.setPaneDivisions(e.sheetId,0,`COL`),this.setPaneDivisions(e.sheetId,0,`ROW`)}}import(e){for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let t of e.sheets){let e=t.name||E(`Sheet`)+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:Xs(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(S).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e){let t=it(e);for(let e in this.sheetIdsMapName)if(tc(e,t))return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(S)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return $s(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(t.bottom===void 0||t.right===void 0)return t;let n=t.left===0&&t.right===this.getNumberCols(e)-1,r=t.top===0&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:r?void 0:t.bottom,right:n&&!r?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,n){let r={...this.getPaneDivisions(e)};n===`COL`?r.xSplit=t:n===`ROW`&&(r.ySplit=t),this.history.update(`sheets`,e,`panes`,r)}checkElementsIncludeAllNonFrozenHeaders(e,t,n){let r=this.getters.getPaneDivisions(e),i=t===`ROW`?r.ySplit:r.xSplit,a=this.getters.getNumberHeaders(e,t);return i?At(n,x(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&`row`in e&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every($n))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>fr(e,n))?`Success`:`TargetOutOfSheet`}return`Success`}updateCellPosition(e){let{sheetId:t,cellId:n,col:r,row:i}=e;n?this.setNewPosition(n,t,r,i):this.clearPosition(t,r,i)}setNewPosition(e,t,n,r){let i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update(`cellPosition`,e,{row:r,col:n,sheetId:t}),this.history.update(`sheets`,t,`rows`,r,`cells`,n,e)}clearPosition(e,t,n){let r=this.sheets[e]?.rows[n].cells[t];r&&(this.history.update(`cellPosition`,r,void 0),this.history.update(`sheets`,e,`rows`,n,`cells`,t,void 0))}setGridLinesVisibility(e,t){this.history.update(`sheets`,e,`areGridLinesVisible`,t)}createSheet(e,t,n,r,i){let a={id:e,name:t,numberOfCols:n,rows:Xs(r),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},o=this.orderedSheetIds.slice();o.splice(i,0,a.id);let s=this.sheets;return this.history.update(`orderedSheetIds`,o),this.history.update(`sheets`,Object.assign({},s,{[a.id]:a})),a}moveSheet(e,t){let n=this.orderedSheetIds.slice(),r=n.findIndex(t=>t===e),i=n.splice(r,1),a=this.findIndexOfTargetSheet(r,t);n.splice(a,0,i[0]),this.history.update(`orderedSheetIds`,n)}findIndexOfTargetSheet(e,t){for(;t!==0&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(t===0)return e;throw Error(E(`There is not enough visible sheets`))}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId);if(t!==void 0&&e.name===t)return`UnchangedSheetName`;let{orderedSheetIds:n,sheets:r}=this,i=e.name&&e.name.trim().toLowerCase();return n.find(t=>tc(r[t]?.name,i)&&t!==e.sheetId)?`DuplicatedSheetName`:Ke.test(i)?`ForbiddenCharactersInSheetName`:`Success`}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?`WrongSheetPosition`:`Success`}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return`MergeOverlap`;return`Success`}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return`MergeOverlap`;return`Success`}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):`MissingSheetName`}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[n],r[t]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=y(this.getSheet(e));r.id=t,r.name=n;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{col:e,row:n}=this.getCellPosition(t.id);this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:e,row:n,content:t.content,format:t.format,style:t.style})}let o=Object.assign({},this.sheetIdsMapName);o[r.name]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return ec(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){let t=e.name,n=Object.assign({},this.sheets);delete n[e.id],this.history.update(`sheets`,n);let r=this.orderedSheetIds.slice(),i=r.indexOf(e.id);r.splice(i,1),this.history.update(`orderedSheetIds`,r);let a=Object.assign({},this.sheetIdsMapName);delete a[t],this.history.update(`sheetIdsMapName`,a)}removeColumns(e,t){t.sort((e,t)=>t-e);for(let n of t)this.moveCellOnColumnsDeletion(e,n);let n=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,n-t.length);let r=t.filter(t=>t<e.panes.xSplit).length;r&&this.setPaneDivisions(e.id,e.panes.xSplit-r,`COL`)}removeRows(e,t){t.sort((e,t)=>t-e);for(let n of ct(t)){let t=n[n.length-1],r=n[0];this.moveCellOnRowsDeletion(e,t,r),this.updateRowsStructureOnDeletion(e,t,r)}let n=t.filter(t=>t<e.panes.ySplit).length;n&&this.setPaneDivisions(e.id,e.panes.ySplit-n,`ROW`)}addColumns(e,t,n,r){let i=n===`before`?t:t+1;this.moveCellsOnAddition(e,i,r,`columns`);let a=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,a+r),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+r,`COL`)}addRows(e,t,n,r){let i=n===`before`?t:t+1;this.addEmptyRows(e,r),this.moveCellsOnAddition(e,i,r,`rows`),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+r,`ROW`)}moveCellOnColumnsDeletion(e,t){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let n=0;n<e.rows.length;n++){let r=e.rows[n];for(let i in r.cells){let a=Number(i),o=r.cells[i];o&&a>t&&this.setNewPosition(o,e.id,a-1,n)}}}moveCellsOnAddition(e,t,n,r){let i=[];for(let a=0;a<e.rows.length;a++){let o=e.rows[a];if(r!==`rows`||a>=t)for(let s in o.cells){let c=Number(s),l=o.cells[s];l&&(r===`rows`||c>=t)&&i.push({sheetId:e.id,cellId:l,col:c+(r===`columns`?n:0),row:a+(r===`rows`?n:0),type:`UPDATE_CELL_POSITION`})}}for(let e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,n){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:n}]});let r=n-t+1;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(t>n)for(let n in i.cells){let a=Number(n),o=i.cells[n];o&&this.setNewPosition(o,e.id,a,t-r)}}}updateRowsStructureOnDeletion(e,t,n){let r=[],i=e.rows.map(e=>e.cells).reverse();for(let a in e.rows){let e=Number(a);e>=t&&e<=n||r.push({cells:i.pop()})}this.history.update(`sheets`,e.id,`rows`,r)}addEmptyRows(e,t){let n=e.rows.slice();for(let e=0;e<t;e++)n.push({cells:{}});this.history.update(`sheets`,e.id,`rows`,n)}getImportedSheetSize(e){let t=Object.keys(e.cells).map(Pn),n=e.rowNumber,r=e.colNumber;for(let{col:e,row:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?`InvalidSheetId`:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?`DuplicatedSheetId`:`Success`}checkZonesAreInSheet(e){return`sheetId`in e?`ranges`in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},GL=class extends EL{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};insertionOrders={};adaptRanges(e,t){let n=t?[t]:this.getters.getSheetIds();for(let t of n)for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return`InvalidSheetId`;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return Dr(t)?this.checkValidations(e,e=>this.getTablesOverlappingZones(e.sheetId,t).length?`TableOverlap`:`Success`,e=>this.checkTableConfigUpdateIsValid(e.config)):`NonContinuousTargets`;case`UPDATE_TABLE`:return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,e=>this.checkTableConfigUpdateIsValid(e.config)):`TableNotFound`;case`ADD_MERGE`:for(let t of this.getCoreTables(e.sheetId)){let n=t.range.zone;for(let t of e.target)if(ur(n,t))return`MergeInTable`}break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{}),this.history.update(`insertionOrders`,e.sheetId,[]);break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t),this.history.update(`insertionOrders`,e.sheetId,void 0);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t),this.history.update(`insertionOrders`,e.sheetIdTo,[...this.insertionOrders[e.sheetId]??[]]);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.uuidGenerator.smallUuid(),a=e.config||Om,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o),this.history.update(`insertionOrders`,e.sheetId,[...this.insertionOrders[e.sheetId]??[],o.id]);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!cr(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t),this.history.update(`insertionOrders`,e.sheetId,this.insertionOrders[e.sheetId]?.filter(e=>e in t));break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>fr(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){let t=[];for(let n of this.insertionOrders[e]||[]){let r=this.tables[e][n];r&&t.push(r)}return t}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>dr(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>ur(e.range.zone,t)))}extendTableDown(e,t){let n=this.getters.extendRange(t.range,`ROW`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}extendTableRight(e,t){let n=this.getters.extendRange(t.range,`COL`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:n,row:r},i){if(!e)return`none`;let a=i.range.zone,o=`none`;if(a.bottom+1===r&&n>=a.left&&n<=a.right?o=`down`:a.right+1===n&&r>=a.top&&r<=a.bottom&&(o=`right`),o===`none`)return`none`;let s=o===`down`?{...a,bottom:a.bottom+1,top:a.bottom+1}:{...a,right:a.right+1,left:a.right+1};for(let e=s.top;e<=s.bottom;e++)for(let n=s.left;n<=s.right;n++){let r={sheetId:t,col:n,row:e};if(this.getters.getCell(r)?.content||this.getters.isInMerge(r)||this.getTablesOverlappingZones(t,[D(r)]).length)return`none`}return o}getCoreTableMatchingTopLeft(e,t){for(let n of this.getCoreTables(e)){let e=n.range.zone;if(e.left===t.left&&e.top===t.top)return n}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return`Success`;let t=this.getters.getRangeFromRangeData(e.newTableRange).zone,n=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if(n!==`Success`)return n;let r=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);return r?this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==r.id).length?`TableOverlap`:`Success`:`TableNotFound`}checkTableConfigUpdateIsValid(e){return e&&(e.numberOfHeaders!==void 0&&e.numberOfHeaders<0||e.hasFilters&&e.numberOfHeaders===0)?`InvalidTableConfig`:`Success`}createStaticTable(e,t,n,r,i){let a=n.zone;if(!i){i=[];for(let e of x(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.uuidGenerator.smallUuid();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=Cr(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of x(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.uuidGenerator.smallUuid();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,Cr(t.zone)):e.range,i=n||e.config;return{...e,range:r,config:i}}updateTableConfig(e,t){if(!e)return t;let n={...t,...e};return e.numberOfHeaders===0?n.hasFilters=!1:e.hasFilters===!0&&(n.numberOfHeaders||=1),n}createFilterFromZone(e,t,n,r){return qF(e,this.getters.getRangeFromZone(t,n),r,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone),r=t.filters.map(n=>{let r=this.getters.getRangeFromZone(e,n.rangeWithHeaders.zone);return qF(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:y(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:y(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=qF(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<pr(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.uuidGenerator.smallUuid(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}import(e){for(let t of e.sheets){let e=[];for(let n of t.tables||[]){let r=this.uuidGenerator.uuidv4(),i=n.config||Om,a=this.getters.getRangeFromSheetXC(t.id,n.range),o=n.type||`static`,s=o===`dynamic`?this.createDynamicTable(r,a,i):this.createStaticTable(r,o,a,i);this.history.update(`tables`,t.id,s.id,s),e.push(s.id)}this.history.update(`insertionOrders`,t.id,e)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:tr(e.range.zone),type:e.type};C(e.config,Om)||(n.config=e.config),t.tables.push(n)}}exportForExcel(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n=tr(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},KL=class extends EL{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return`HeaderGroupAlreadyExists`;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return`UnknownHeaderGroup`;if(x(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return`NotEnoughElements`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=y(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=Ot(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&x(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Lt([t.end,e]))t.end++;else{let t={start:e,end:e};s[n].push(t)}}}for(let e of s)for(let t of e)t.isFolded=i[this.getGroupId(t)];return s}groupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}unGroupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,-1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}moveGroupsOnHeaderInsertion(e,t,n,r){let i=this.groups[e][t];for(let a=0;a<i.length;a++){let o=i[a],[s,c]=Zs(n,r,[o.start,o.end]);(s!==o.start||c!==o.end)&&this.history.update(`groups`,e,t,a,{...o,start:s,end:c})}}moveGroupsOnHeaderDeletion(e,t,n){let r=this.getHeaderGroups(e,t),i=[];for(let e of r){let t=Qs(n,x(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=kf(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=kf(t,e,n.end+1);r.collapsed=!0}}}}}},qL=class extends EL{static getters=[`getPivotCoreDefinition`,`getPivotDisplayName`,`getPivotId`,`getPivotFormulaId`,`getPivotIds`,`getMeasureCompiledFormula`,`getPivotName`,`isExistingPivot`,`getMeasureFullDependencies`];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case`ADD_PIVOT`:return this.checkDuplicatedMeasureIds(e.pivot);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?C(e.pivot,this.pivots[e.pivotId]?.definition)?`NoChanges`:e.pivot.name===``?`EmptyName`:this.checkDuplicatedMeasureIds(e.pivot):`PivotIdNotFound`;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;if(e.name===``)return`EmptyName`;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;break;case`DUPLICATE_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`}return`Success`}handle(e){switch(e.type){case`ADD_PIVOT`:{let{pivotId:t,pivot:n}=e;this.addPivot(t,n);break}case`INSERT_PIVOT`:{let{sheetId:t,col:n,row:r,pivotId:i,table:a}=e,o={sheetId:t,col:n,row:r},{cols:s,rows:c,measures:l,fieldsType:u}=a,d=new mF(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=y(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,y(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break}}adaptRanges(e){for(let t in this.pivots){let n=y(this.pivots[t]?.definition);if(!n)continue;let r=AF.get(n.type)?.adaptRanges?.(this.getters,n,e);r&&!C(n,r)&&this.history.update(`pivots`,t,`definition`,r)}for(let t in this.compiledMeasureFormulas)for(let n in this.compiledMeasureFormulas[t]){let r=this.pivots[t]?.definition.measures.find(e=>e.id===n);if(!r||!r.computedBy)continue;let i=r.computedBy.sheetId,a=this.compiledMeasureFormulas[t][n].formula,o=[];for(let t of a.dependencies){let n=e(t);n.changeType===`NONE`?o.push(t):o.push(n.range)}let s=this.getters.getFormulaString(i,a.tokens,o);s!==r.computedBy.formula&&this.replaceMeasureFormula(t,r,s)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:y(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=this.compileMeasureFormula(n.computedBy.sheetId,n.computedBy.formula);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.tokens){if(o.type!==`SYMBOL`)continue;let a=i.measures.find(e=>ot(e.id)===o.value&&t.id!==e.id);!a||n.has(a.id)||!a.computedBy||r.push(...this.computeMeasureFullDependencies(e,a,n))}return r.push(...a.dependencies.filter(e=>!e.invalidXc)),r}insertPivot(e,t,n){this.resizeSheet(e.sheetId,e,n);let r=n.getPivotCells();for(let n=0;n<r.length;n++)for(let i=0;i<r[n].length;i++){let a=r[n][i];this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col+n,row:e.row+i,content:Fu(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}compileMeasureFormula(e,t){let n=OE(t),r=n.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return{...n,dependencies:r}}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId}),this.compileCalculatedMeasures(e,r.definition.measures)}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?`Success`:`InvalidDefinition`}import(e){if(e.pivots)for(let[t,n]of Object.entries(e.pivots))this.addPivot(t,n,n.formulaId);this.history.update(`nextFormulaId`,e.pivotNextId||Ou(this.pivots)+1)}export(e){e.pivots={};for(let t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}},JL=class extends EL{static getters=[`getLocale`];locale=k;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return el(e.locale)?`Success`:`InvalidLocale`}return`Success`}handle(e){switch(e.type){case`UPDATE_LOCALE`:let t=this.locale,n=e.locale;this.history.update(`locale`,n),this.changeCellsDateFormatWithLocale(t,n);break}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(let n of this.getters.getSheetIds())for(let[r,i]of Object.entries(this.getters.getCells(n))){let n;if(i.format===e.dateFormat&&(n=t.dateFormat),i.format===e.timeFormat&&(n=t.timeFormat),i.format===_l(e)&&(n=_l(t)),n){let{col:e,row:t,sheetId:i}=this.getters.getCellPosition(r);this.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:i,format:n})}}}import(e){this.locale=e.settings?.locale??k}export(e){e.settings={locale:this.locale}}},YL=class extends EL{allowDispatch(e){switch(e.type){case`ADD_PIVOT`:case`UPDATE_PIVOT`:let t=e.pivot;return this.checkDataSetValidity(t)}return`Success`}checkDataSetValidity(e){if(e.type===`SPREADSHEET`&&e.dataSet){let{zone:t,sheetId:n}=e.dataSet;return!n||!this.getters.tryGetSheet(n)||!t||!$n(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},XL=class extends EL{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(!Um[e.templateName])return`InvalidTableStyle`;try{en(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=Wm(e.tableStyleName,e.templateName,e.primaryColor);this.history.update(`styles`,e.tableStyleId,t);break;case`REMOVE_TABLE_STYLE`:let n={...this.styles};delete n[e.tableStyleId],this.history.update(`styles`,n);for(let t of this.getters.getSheetIds())for(let n of this.getters.getCoreTables(t))n.config.styleId===e.tableStyleId&&this.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{styleId:Om.styleId}});break}}getTableStyle(e){if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){let e=E(`Custom Table Style`),t=new Set(Object.values(this.styles).map(e=>e.displayName));if(!t.has(e))return e;let n=2;for(;t.has(`${e} ${n}`);)n++;return`${e} ${n}`}isTableStyleEditable(e){return!Hm[e]}import(e){for(let e in Hm)this.styles[e]=Hm[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=Wm(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)Hm[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},$=class extends TL{static layers=[];getters;ui;selection;constructor({getters:e,stateObserver:t,dispatch:n,canDispatch:r,uiActions:i,selection:a}){super(t,n,r),this.getters=e,this.ui=i,this.selection=a}drawLayer(e,t){}};let ZL=new h;ZL.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let QL=RT.mapping;function $L(e,t,n){return new eR(e,t,n).getParameters()}var eR=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(QL),e,{getters:this.getters,locale:this.getters.getLocale()})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e,t){let n=this.getRangeError(e);if(n)return n;if(t)return{value:Hs(this.getters.getSheetName(e.sheetId),tr(e.zone))};let r={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};return this.computeCell(r)}range(e){let t=this.getRangeError(e);if(t)return[[t]];let n=e.sheetId,r=e.zone,i=cr(r,this.getters.getSheetZone(n));if(!i)return[[]];let{top:a,left:o,bottom:s,right:c}=r,l=`${n}-${a}-${o}-${s}-${c}`;if(l in this.rangeCache)return this.rangeCache[l];let u=i.bottom-i.top+1,d=i.right-i.left+1,f=Array(d);for(let e=i.left;e<=i.right;e++){let t=e-i.left;f[t]=Array(u);for(let r=i.top;r<=i.bottom;r++){let a=r-i.top;f[t][a]=this.computeCell({sheetId:n,col:e,row:r})}}return this.rangeCache[l]=f,f}getRangeError(e){if(!$n(e.zone))return new ia;if(e.invalidSheetName)return new M(E(`Invalid sheet name: %s`,e.invalidSheetName))}},tR=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n||=self).RBush=r()})(e,function(){"use strict";function e(e,r,i,a,o){(function e(n,r,i,a,o){for(;a>i;){if(a-i>600){var s=a-i+1,c=r-i+1,l=Math.log(s),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(s-u)/s)*(c-s/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-c*u/s+d)),Math.min(a,Math.floor(r+(s-c)*u/s+d)),o)}var f=n[r],p=i,m=a;for(t(n,i,r),o(n[a],f)>0&&t(n,i,a);p<m;){for(t(n,p,m),p++,m--;o(n[p],f)<0;)p++;for(;o(n[m],f)>0;)m--}o(n[i],f)===0?t(n,i,m):t(n,++m,a),m<=r&&(i=m+1),r<=m&&(a=m-1)}})(e,r,i||0,a||e.length-1,o||n)}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:+(e>t)}var r=function(e){e===void 0&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function i(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1}function a(e,t){o(e,0,e.children.length,t,e)}function o(e,t,n,r,i){i||=m(null),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(var a=t;a<n;a++){var o=e.children[a];s(i,e.leaf?r(o):o)}return i}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function c(e,t){return e.minX-t.minX}function l(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function d(e){return e.maxX-e.minX+(e.maxY-e.minY)}function f(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function p(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function m(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function h(t,n,r,i,a){for(var o=[n,r];o.length;)if(!((r=o.pop())-(n=o.pop())<=i)){var s=n+Math.ceil((r-n)/i/2)*i;e(t,s,n,r,a),o.push(n,s,s,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(e){var t=this.data,n=[];if(!p(e,t))return n;for(var r=this.toBBox,i=[];t;){for(var a=0;a<t.children.length;a++){var o=t.children[a],s=t.leaf?r(o):o;p(e,s)&&(t.leaf?n.push(o):f(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n},r.prototype.collides=function(e){var t=this.data;if(!p(e,t))return!1;for(var n=[];t;){for(var r=0;r<t.children.length;r++){var i=t.children[r],a=t.leaf?this.toBBox(i):i;if(p(e,a)){if(t.leaf||f(e,a))return!0;n.push(i)}}t=n.pop()}return!1},r.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){var r=this.data;this.data=n,n=r}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this},r.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},r.prototype.clear=function(){return this.data=m([]),this},r.prototype.remove=function(e,t){if(!e)return this;for(var n,r,a,o=this.data,s=this.toBBox(e),c=[],l=[];o||c.length;){if(o||(o=c.pop(),r=c[c.length-1],n=l.pop(),a=!0),o.leaf){var u=i(e,o.children,t);if(u!==-1)return o.children.splice(u,1),c.push(o),this._condense(c),this}a||o.leaf||!f(o,s)?r?(n++,o=r.children[n],a=!1):o=null:(c.push(o),l.push(n),n=0,r=o,o=o.children[0])}return this},r.prototype.toBBox=function(e){return e},r.prototype.compareMinX=function(e,t){return e.minX-t.minX},r.prototype.compareMinY=function(e,t){return e.minY-t.minY},r.prototype.toJSON=function(){return this.data},r.prototype.fromJSON=function(e){return this.data=e,this},r.prototype._all=function(e,t){for(var n=[];e;)e.leaf?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},r.prototype._build=function(e,t,n,r){var i,o=n-t+1,s=this._maxEntries;if(o<=s)return a(i=m(e.slice(t,n+1)),this.toBBox),i;r||(r=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/s**(r-1))),(i=m([])).leaf=!1,i.height=r;var c=Math.ceil(o/s),l=c*Math.ceil(Math.sqrt(s));h(e,t,n,l,this.compareMinX);for(var u=t;u<=n;u+=l){var d=Math.min(u+l-1,n);h(e,u,d,c,this.compareMinY);for(var f=u;f<=d;f+=c){var p=Math.min(f+c-1,d);i.children.push(this._build(e,f,p,r-1))}}return a(i,this.toBBox),i},r.prototype._chooseSubtree=function(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){for(var i=1/0,a=1/0,o=void 0,s=0;s<t.children.length;s++){var c=t.children[s],l=u(c),d=(f=e,p=c,(Math.max(p.maxX,f.maxX)-Math.min(p.minX,f.minX))*(Math.max(p.maxY,f.maxY)-Math.min(p.minY,f.minY))-l);d<a?(a=d,i=l<i?l:i,o=c):d===a&&l<i&&(i=l,o=c)}t=o||t.children[0]}var f,p;return t},r.prototype._insert=function(e,t,n){var r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),s(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)},r.prototype._split=function(e,t){var n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=m(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,a(n,this.toBBox),a(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)},r.prototype._splitRoot=function(e,t){this.data=m([e,t]),this.data.height=e.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(e,t,n){for(var r,i,a,s,c,l,d,f=1/0,p=1/0,m=t;m<=n-t;m++){var h=o(e,0,m,this.toBBox),g=o(e,m,n,this.toBBox),_=(i=h,a=g,s=void 0,c=void 0,l=void 0,d=void 0,s=Math.max(i.minX,a.minX),c=Math.max(i.minY,a.minY),l=Math.min(i.maxX,a.maxX),d=Math.min(i.maxY,a.maxY),Math.max(0,l-s)*Math.max(0,d-c)),v=u(h)+u(g);_<f?(f=_,r=m,p=v<p?v:p):_===f&&v<p&&(p=v,r=m)}return r||n-t},r.prototype._chooseSplitAxis=function(e,t,n){var r=e.leaf?this.compareMinX:c,i=e.leaf?this.compareMinY:l;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)},r.prototype._allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=this.toBBox,a=o(e,0,t,i),c=o(e,n-t,n,i),l=d(a)+d(c),u=t;u<n-t;u++){var f=e.children[u];s(a,e.leaf?i(f):f),l+=d(a)}for(var p=n-t-1;p>=t;p--){var m=e.children[p];s(c,e.leaf?i(m):m),l+=d(c)}return l},r.prototype._adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)s(t[r],e)},r.prototype._condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)e[t].children.length===0?t>0?(n=e[t-1].children).splice(n.indexOf(e[t]),1):this.clear():a(e[t],this.toBBox)},r})}))(),1),nR=class{rTrees={};constructor(e=[]){let t={};for(let n of e){let e=n.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(n)}for(let e in t)this.rTrees[e]=new rR,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new rR),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&C(e.data,t.data)}},rR=class extends tR.default{toBBox({boundingBox:e}){let t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}},iR=class{createEmptyPositionSet;dependencies=new OL;rTree;constructor(e,t=[]){this.createEmptyPositionSet=e,this.rTree=new nR(t)}removeAllDependencies(e){let t=this.dependencies.get(e);if(t){for(let e of t)this.rTree.remove(e);this.dependencies.delete(e)}}addDependencies(e,t){let n=t.map(({sheetId:t,zone:n})=>({data:e,boundingBox:{zone:n,sheetId:t}}));for(let e of n)this.rTree.insert(e);let r=this.dependencies.get(e);r?r.push(...n):this.dependencies.set(e,n)}getCellsDependingOn(e,t){let n=this.createEmptyPositionSet(),r=Array.from(e).reverse();for(;r.length>0;){let e=r.pop(),i=e.zone,a=e.sheetId;for(let e=i.left;e<=i.right;e++)for(let t=i.top;t<=i.bottom;t++)n.add({sheetId:a,col:e,row:t});let o=this.rTree.search(e).map(e=>e.data),s={};for(let e of o)!n.has(e)&&!t.has(e)&&(s[e.sheetId]||(s[e.sheetId]=[]),s[e.sheetId].push(D(e)));for(let e in s){let t=T(s[e],[]);r.push(...t.map(t=>({sheetId:e,zone:t})))}}for(let t of e){let e=t.zone,r=t.sheetId;for(let t=e.left;t<=e.right;t++)for(let i=e.top;i<=e.bottom;i++)n.delete({sheetId:r,col:t,row:i})}return n}},aR=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=oR(t),r=e<<n>>5,i=new this(r+1);return i.columnOffset=n,i.cols=t,i.rows=e,i}getValue(e){let[t,n]=this.getCoordinates(e);return this[t]>>n&1}setValue(e,t){let[n,r]=this.getCoordinates(e),i=(this[n]>>r&1)==0&&t===1;return this[n]=this[n]&~(1<<r)|t<<r,i}isEmpty(){return!this.some(e=>e!==0)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){let{row:t,col:n}=e,r=(t<<this.columnOffset)+n,i=r>>5;return[i,r-(i<<5)]}};function oR(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var sR=class{sheets={};insertions=[];maxSize=0;constructor(e){for(let t in e){let n=e[t].cols,r=e[t].rows;this.maxSize+=n*r,this.sheets[t]=aR.create(r,n)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(let t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(let t of e)this.delete(t)}has(e){return this.sheets[e.sheetId].getValue(e)===1}clear(){let e=[...this];this.insertions=[];for(let e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(this.insertions.length===0)return!0;for(let e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=Array(this.maxSize);let e=0;for(let t in this.sheets){let n=this.sheets[t];n.fillAllPositions();for(let r=0;r<n.rows;r++)for(let i=0;i<n.cols;i++)this.insertions[e++]={sheetId:t,row:r,col:i}}}*[Symbol.iterator](){for(let e of this.insertions)this.sheets[e.sheetId].getValue(e)===1&&(yield e)}},cR=class{resultsToArrayFormulas=new nR;arrayFormulasToResults=new OL;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||lR}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){let t=this.arrayFormulasToResults.get(e);t&&(this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.delete(e))}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}};let lR=[],uR=Object.freeze(gs(new ra)),dR=Object.freeze(gs({value:null}));var fR=class{context;getters;compilationParams;evaluatedCells=new OL;formulaDependencies=Et(new iR(this.createEmptyPositionSet.bind(this)));blockedArrayFormulas=new sR({});spreadingRelations=new cR;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=$L(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||dR}getSpreadZone(e,t={ignoreSpillError:!1}){let n=this.spreadingRelations.getArrayResultZone(e);if(!n)return;let r=this.evaluatedCells.get(e);return r?.type===`error`&&!(t.ignoreSpillError&&r?.value===j.SpilledBlocked)?D(e):or(D(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type===`empty`)return;let t=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,D(e));return Array.from(t).find(e=>!this.blockedArrayFormulas.has(e))}isArrayFormulaSpillBlocked(e){return this.blockedArrayFormulas.has(e)}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);let t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t);for(let e of t)this.compilationParams.ensureRange(e)}updateCompilationParameters(e){this.compilationParams=$L(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParametersForGridEvaluation(){this.compilationParams=$L(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){let e={};for(let t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new sR(e)}evaluateCells(e){let t=performance.now(),n=this.createEmptyPositionSet();n.addMany(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(e)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=this.createEmptyPositionSet();for(let n of e){let e=this.getters.getCell(n)?.content,r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.add(r),e||t.add(n)}let n=gr(t);for(let e in n)for(let r of n[e])t.addMany(this.getArrayFormulasBlockedBy(e,r));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new cR,this.formulaDependencies=Et(()=>{let e=[...this.getAllCells()].flatMap(e=>this.getDirectDependencies(e).filter(e=>!e.invalidSheetName&&!e.invalidXc).map(t=>({data:e,boundingBox:{zone:t.zone,sheetId:t.sheetId}})));return new iR(this.createEmptyPositionSet.bind(this),e)})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new OL,this.evaluate(this.getAllCells()),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=OE(t),i=r.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return this.updateCompilationParameters(n),this.evaluateCompiledFormula(e,{...r,dependencies:i})}evaluateCompiledFormula(e,t,n){try{let r=hR(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return A(r)?Ma(r,mR):mR(r)}catch(e){return BT(e,``)}}getAllCells(){let e=this.createEmptyPositionSet();return e.fillAllPositions(),e}getArrayFormulasBlockedBy(e,t){let n=this.createEmptyPositionSet(),r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addMany(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteMany(i),n.addMany(this.getCellsDependingOn(n)),n}nextPositionsToUpdate=new sR({});cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextPositionsToUpdate=e;let t=0;for(;!this.nextPositionsToUpdate.isEmpty()&&t++<30;){this.updateCompilationParametersForGridEvaluation();let e=this.nextPositionsToUpdate.clear();for(let t=0;t<e.length;++t)this.evaluatedCells.delete(e[t]);for(let t=0;t<e.length;++t){let n=e[t];if(this.nextPositionsToUpdate.has(n))continue;let r=this.computeCell(n);r!==dR&&this.evaluatedCells.set(n,r)}ZL.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}computeCell(e){let t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);let n=this.getters.getCell(e);if(n===void 0)return dR;let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?uR:(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):ms(n,i))}catch(e){return e.value=e?.value||j.GenericError,e.message=e?.message||UT,gs(e)}finally{this.cellsBeingComputed.delete(r)}}computeAndSave(e){let t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){let n=hR(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!A(n))return gs(mR(n),this.getters.getLocale(),t);this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return gs({value:0},this.getters.getLocale(),t);if(i===1&&r===1)return gs(mR(n[0][0]),this.getters.getLocale(),t);let a={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+r-1};return this.spreadingRelations.addRelation({resultZone:a,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),pR(r,i,this.checkCollision(e)),pR(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),gs(mR(n[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){let n=this.formulaDependencies().getCellsDependingOn(hr(t).map(t=>({sheetId:e,zone:t})),this.nextPositionsToUpdate);n.delete({sheetId:e,col:t.left,row:t.top}),this.nextPositionsToUpdate.addMany(n)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:n},r){let i=this.getters.getNumberCols(e),a=this.getters.getNumberRows(e),o=t+r.length<=i,s=n+r[0].length<=a;if(!(o&&s))throw o?new sa(E(`Result couldn't be automatically expanded. Please insert more rows.`)):s?new sa(E(`Result couldn't be automatically expanded. Please insert more columns.`)):new sa(E(`Result couldn't be automatically expanded. Please insert more columns and rows.`))}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:n},r){if(this.getters.getMergesInZone(e,{top:n,bottom:n+r[0].length-1,left:t,right:t+r.length-1}).length!==0)throw new sa(E(`Merged cells found in the spill zone. Please unmerge cells before using array formulas.`))}checkCollision(e){let{sheetId:t,col:n,row:r}=e;return(i,a)=>{let o={sheetId:t,col:i+n,row:a+r};if(this.getters.getCell(o)?.content||this.getters.getEvaluatedCell(o).type!==`empty`)throw this.blockedArrayFormulas.add(e),new sa(E(`Array result was not expanded because it would overwrite data in %s.`,w(o.col,o.row)));this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=gs(mR(r[i][a]),this.getters.getLocale(),s);this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r};this.getters.getCell(t)?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextPositionsToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return uR;this.symbolsBeingComputed.add(t);try{return e?.(t)||new na(E(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.dependencies:[]}getCellsDependingOn(e){let t=[],n=gr(e);for(let e in n)t.push(...n[e].map(t=>({sheetId:e,zone:t})));return this.formulaDependencies().getCellsDependingOn(t,this.nextPositionsToUpdate)}};function pR(e,t,n){for(let r=0;r<e;++r)for(let e=0;e<t;++e)r===0&&e===0||n(r,e)}function mR(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function hR(e,t,n,r,i){let a=t.evalContext,o=a.__originCellPosition,s=a.__originSheetId;a.__originCellPosition=i,a.__originSheetId=n;let c=e.execute(e.dependencies,t.referenceDenormalizer,t.ensureRange,r,a);return a.__originCellPosition=o,a.__originSheetId=s,c}var gR=class extends ${static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getRangeFormattedValues`,`getRangeValues`,`getRangeFormats`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new fR(e.custom,this.getters)}beforeHandle(e){(Ri.has(e.type)||Bi.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case`UPDATE_CELL`:if(!(`content`in e||`format`in e)||this.shouldRebuildDependenciesGraph)return;let t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),`content`in e&&this.evaluator.updateDependencies(t);break;case`EVALUATE_CELLS`:this.evaluator.evaluateAllCells();break}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t,n){let r=this.evaluateFormulaResult(e,t,n);return A(r)?Ma(r,e=>e.value):r.value}evaluateFormulaResult(e,t,n){return this.evaluator.evaluateFormulaResult(e,t,n)}evaluateCompiledFormula(e,t,n){return this.evaluator.evaluateCompiledFormula(e,t,n)}getRangeFormattedValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).formattedValue)}getRangeValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).value)}getRangeFormats(e){let t=this.getters.tryGetSheet(e.sheetId);return t===void 0?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map(e=>e.format)}getEvaluatedCell(e){return this.evaluator.getEvaluatedCell(e)}getEvaluatedCells(e){return this.evaluator.getEvaluatedPositionsInSheet(e).map(e=>this.getEvaluatedCell(e))}getEvaluatedCellsPositions(e){return this.evaluator.getEvaluatedPositionsInSheet(e)}getEvaluatedCellsInZone(e,t){return _r(t).map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return _r(t).map(({col:t,row:n})=>this.getEvaluatedCell({sheetId:e,col:t,row:n})).every(e=>e.type===`empty`)}mapVisiblePositions(e,t){let{sheetId:n,zone:r}=e;return _r(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=w(t.col,t.row),i=n.value,a=!1,o,s,c=!0,l=e.sheets.find(e=>e.id===t.sheetId),u=this.getCorrespondingFormulaCell(t);if(u){let e=this.getters.getCell(t);c=IE(u.compiledFormula.tokens),a=c&&e?.content===u.content,c||i!==``&&(o=(i??``).toString(),s=n.format)}let d=l.cells[r]||{},f=s?Pr(s,e.formats):d.format,p;p=c&&a&&u instanceof AL?u.contentWithFixedReferences:c?d.content:o,l.cells[r]={...d,value:i,isFormula:a,content:p,format:f};let m=this.getSpreadZone(t);m&&(l.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,m),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let _R=/"(#[0-9a-fA-F]{6})"/g;function vR(e){let t=[{leadColor:an(255,0,0),colors:[]},{leadColor:an(255,128,0),colors:[]},{leadColor:an(128,128,0),colors:[]},{leadColor:an(128,255,0),colors:[]},{leadColor:an(0,255,0),colors:[]},{leadColor:an(0,255,128),colors:[]},{leadColor:an(0,255,255),colors:[]},{leadColor:an(0,127,255),colors:[]},{leadColor:an(0,0,255),colors:[]},{leadColor:an(127,0,255),colors:[]},{leadColor:an(128,0,128),colors:[]},{leadColor:an(255,0,128),colors:[]}];for(let n of e.map(ln)){let e=500,r=0;t.forEach((t,i)=>{let a=yR(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>dn(e).s-dn(t).s)).flat().map(cn)}function yR(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var bR=class extends ${customColors={};shouldUpdateColors=!0;static getters=[`getCustomColors`];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds())for(let t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));break;case`UPDATE_CHART`:case`CREATE_CHART`:this.tryToAddColors(this.getChartColors(e.id));break;case`COLOR_SHEET`:e.color&&this.tryToAddColors([e.color]);break;case`UPDATE_CELL`:case`ADD_CONDITIONAL_FORMAT`:case`SET_BORDER`:case`SET_ZONE_BORDERS`:case`SET_FORMATTING`:case`CREATE_TABLE`:case`UPDATE_TABLE`:this.history.update(`shouldUpdateColors`,!0);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return vR(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(let t of this.getters.getSheetIds())e=e.concat(this.getSheetColors(t),this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getSheetColors(e){let t=this.getters.getSheet(e);return t.color?[t.color]:[]}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=new Set;for(let e of t)e.style?.textColor&&n.add(e.style.textColor),e.style?.fillColor&&n.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))n.add(t);return[...n]}getFormattingColors(e){let t=this.getters.getConditionalFormats(e),n=[];for(let e of t){let t=e.rule;t.type===`CellIsRule`?(n.push(t.style.textColor),n.push(t.style.fillColor)):t.type===`ColorScaleRule`&&(n.push($t(t.minimum.color)),n.push(t.midpoint?$t(t.midpoint.color):void 0),n.push($t(t.maximum.color)))}return n.filter(S)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getDefinition()).matchAll(_R)].map(e=>e[1])}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(S):[]}tryToAddColors(e){for(let t of e){if(!tn(t))continue;let e=en(t);t&&!Ne.includes(e)&&this.history.update(`customColors`,e,!0)}}},xR=class extends ${static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};createRuntimeChart=gk(this.getters);handle(e){if(Ri.has(e.type)||Vi.has(e.type)||zi.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:case`DELETE_FIGURE`:this.charts[e.id]=void 0;break;case`DELETE_SHEET`:for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0);break}}getChartRuntime(e){if(!this.charts[e]){let t=this.getters.getChart(e);if(!t)throw Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:Dd(e)};if(!t)return{background:oe,fontColor:Dd(oe)};let n=t.zone.left,r=t.zone.top,i=t.sheetId,a=this.getters.getCellComputedStyle({sheetId:i,col:n,row:r}),o=a.fillColor||`#FFFFFF`;return{background:o,fontColor:a.textColor||Dd(o)}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let r of e){if(!r||r.tag!==`chart`)continue;let e=r.id,i=this.getters.getChart(e)?.getDefinitionForExcel();if(i)n.push({...r,data:i});else{if(!this.getters.getChart(e))continue;let n=this.getters.getChartType(e),i=n_(this.getters.getChartRuntime(e),r,n);i&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:i,size:{width:r.width,height:r.height}}})}}t.charts=n}}},SR=class extends ${static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(Ri.has(e.type)||Vi.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(let e of this.getters.getSheetIds())this.computedStyles[e]=Et(()=>this.getComputedStyles(e)),this.computedIcons[e]=Et(()=>this.getComputedIcons(e)),this.computedDataBars[e]=Et(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){let{sheetId:t,col:n,row:r}=e,i=this.computedStyles[t]();return i&&i[n]?.[r]}getConditionalIcon({sheetId:e,col:t,row:n}){let r=this.computedIcons[e]();return r&&r[t]?.[n]}getConditionalDataBar({sheetId:e,col:t,row:n}){let r=this.computedDataBars[e]();return r&&r[t]?.[n]}getComputedStyles(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())switch(n.rule.type){case`ColorScaleRule`:for(let r of n.ranges)this.applyColorScale(e,r,n.rule,t);break;case`CellIsRule`:let r=n.rule.values.map(e=>e.startsWith(`=`)?OE(e):void 0);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let s=this.rulePredicate[n.rule.type],c={sheetId:e,col:o,row:i},l=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s.tokens):t});s&&s(c,{...n.rule,values:l})&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getEvaluatedCellsInZone(e,this.getters.getRangeFromSheetXC(e,t).zone).filter(e=>e.type===`number`).map(e=>e.value);switch(n.type){case`value`:return r===`max`?Gt(i):Kt(i);case`number`:return Number(n.value);case`percentage`:let t=Kt(i);return t+(Gt(i)-t)*Number(n.value)/100;case`percentile`:return ji(i,Number(n.value)/100,!0);case`formula`:let a=n.value&&this.getters.evaluateFormula(e,n.value);return typeof a==`number`?a:null;default:return null}}applyIcon(e,t,n,r){let i=this.parsePoint(e,t,n.lowerInflectionPoint),a=this.parsePoint(e,t,n.upperInflectionPoint);if(i===null||a===null||i>a)return;let o=this.getters.getRangeFromSheetXC(e,t).zone,s=[n.icons.upper,n.icons.middle,n.icons.lower];for(let t=o.top;t<=o.bottom;t++)for(let c=o.left;c<=o.right;c++){let o=this.getters.getEvaluatedCell({sheetId:e,col:c,row:t});if(o.type!==`number`)continue;let l=this.computeIcon(o.value,a,n.upperInflectionPoint.operator,i,n.lowerInflectionPoint.operator,s);r[c]||(r[c]=[]),r[c][t]=l}}computeIcon(e,t,n,r,i,a){return n===`ge`&&e>=t||n===`gt`&&e>t?a[0]:i===`ge`&&e>=r||i===`gt`&&e>r?a[1]:a[2]}applyDataBar(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,n.rangeValues||t),a=Gt(this.getters.getEvaluatedCellsInZone(e,i.zone).filter(e=>e.type===`number`).map(e=>e.value));if(a<=0)return;let o=n.color,s=this.getters.getRangeFromSheetXC(e,t).zone,c=i.zone;for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let i=n-s.left+c.left,l=t-s.top+c.top,u=this.getters.getEvaluatedCell({sheetId:e,col:i,row:l});!dr(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:$t(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[];n.midpoint&&a?(c.push({minValue:i,minColor:n.minimum.color,colorDiffUnit:this.computeColorDiffUnits(i,a,n.minimum.color,n.midpoint.color)}),c.push({minValue:a,minColor:n.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(a,o,n.midpoint.color,n.maximum.color)})):c.push({minValue:i,minColor:n.minimum.color,colorDiffUnit:this.computeColorDiffUnits(i,o,n.minimum.color,n.maximum.color)});for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let s=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(s.type===`number`){let e=b(s.value,i,o),l;l=c.length===2&&a?e<=a?this.colorCell(e,c[0].minValue,c[0].minColor,c[0].colorDiffUnit):this.colorCell(e,c[1].minValue,c[1].minColor,c[1].colorDiffUnit):this.colorCell(e,c[0].minValue,c[0].minColor,c[0].colorDiffUnit),r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=$t(l)}}}computeColorDiffUnits(e,t,n,r){let i=t-e,a=(n>>16)%256-(r>>16)%256,o=(n>>8)%256-(r>>8)%256,s=n%256-r%256;return[a/i,o/i,s/i]}colorCell(e,t,n,r){let[i,a,o]=r,s=Math.round((n>>16)%256-i*(e-t)),c=Math.round((n>>8)%256-a*(e-t)),l=Math.round(n%256-o*(e-t));return s<<16|c<<8|l}rulePredicate={CellIsRule:(e,t)=>{let n=this.getters.getEvaluatedCell(e);if(n.type===`error`)return!1;let[r,i]=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(e.sheetId,t)??``:hs(t,k));if(A(r)||A(i))return!1;let a=n.value??``;switch(r??=``,i??=``,t.operator){case`IsEmpty`:return a.toString().trim()===``;case`IsNotEmpty`:return a.toString().trim()!==``;case`BeginsWith`:return r===``?!1:a.toString().startsWith(r.toString());case`EndsWith`:return r===``?!1:a.toString().endsWith(r.toString());case`Between`:return a>=r&&a<=i;case`NotBetween`:return!(a>=r&&a<=i);case`ContainsText`:return a.toString().indexOf(r.toString())>-1;case`NotContains`:return!a||a.toString().indexOf(r.toString())===-1;case`GreaterThan`:return a>r;case`GreaterThanOrEqual`:return a>=r;case`LessThan`:return a<r;case`LessThanOrEqual`:return a<=r;case`NotEqual`:return r===``?!1:a!==r;case`Equal`:return r===``?!0:a===r;default:console.warn(E(`Not implemented operator %s for kind of conditional formatting: %s`,t.operator,t.type))}return!1}}};let CR={isValid:!0};var wR=class extends ${static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`isCellValidCheckbox`,`isDataValidationInvalid`];validationResults={};handle(e){if(Ri.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=Q.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?E(`The value must not be a formula`):void 0:n.allowedValues===`onlyFormulas`?E(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return CR;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:CR}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||CR}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of qs(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=Et(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?CR:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=Q.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,o,i),c={...i,values:s};if(!a.isValueValid(e,c,this.getters,r))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>dr(e.col,e.row,t.zone));if(!n)throw Error(`The cell is not in any range of the rule`);return{col:e.col-n.zone.left,row:e.row-n.zone.top}}getEvaluatedCriterionValues(e,t,n){return n.values.map(n=>{if(!n.startsWith(`=`))return n;let r=OE(n),i=this.getters.getTranslatedCellFormula(e,t.col,t.row,r.tokens),a=this.getters.evaluateFormula(e,i);return a&&!A(a)?a.toString():``})}},TR=class extends ${static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(Ri.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tables={};return}switch(e.type){case`CREATE_TABLE`:case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`DELETE_CONTENT`:this.tables={};break}}finalize(){for(let e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){let t=[],n=this.getters.getCoreTables(e);for(let e of n)e.type!==`dynamic`&&t.push(e);let r=[...t];for(let i of n){if(i.type!==`dynamic`)continue;let n=this.coreTableToTable(e,i),a=n.range.zone;for(let e of r){let t=e.range.zone;ur(a,t)&&(a=t.left>a.left?{...a,right:Math.min(a.right,t.left-1)}:{...a,bottom:Math.min(a.bottom,t.top-1)})}t.push({...n,range:this.getters.getRangeFromZone(e,a)})}return t}getFilters(e){return this.getTables(e).filter(e=>e.config.hasFilters).map(e=>e.filters).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){let t=this.getTable(e);if(!(!t||!t.config.hasFilters))return t.filters.find(t=>t.col===e.col)}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:n}){return this.getTables(e).find(e=>dr(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>ur(e.range.zone,t)))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some(e=>e.config.hasFilters)}getFilterHeaders(e){let t=[];for(let n of this.getTables(e)){if(!n.config.hasFilters)continue;let r=n.range.zone,i=r.top;for(let n=r.left;n<=r.right;n++)t.push({sheetId:e,col:n,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:n}){return this.getFilterHeaders(e).some(e=>e.col===t&&e.row===n)}canCreateDynamicTableOnZones(e,t){if(!Dr(t))return!1;let n=or(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);return i?C(i,r)&&Er(n)===1?!0:C(n,this.getters.getSpreadZone(i)):!1}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=qF(this.getDynamicTableFilterId(t.id,s),this.getters.getRangeFromZone(e,c),t.config,this.getters.getRangeFromZone);r.push(l)}return r}getDynamicTableFilterId(e,t){return e+`_`+t}isTableExcelExportable(e,t){return t.type===`dynamic`?!1:!_r(t.range.zone).some(t=>this.getters.getArrayFormulaSpreadingOn({sheetId:e,...t}))}exportForExcel(e){for(let t of e.sheets){let n=[];for(let r of t.tables){let i=Qn(r.range),a={sheetId:t.id,col:i.left,row:i.top},o=this.getters.getCoreTable(a),s=this.getTable(a);if(!o||!s||this.isTableExcelExportable(t.id,o)){n.push(r);continue}t.styles=t.styles||{},t.borders=t.borders||{};for(let n of _r(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=w(n.col,n.row),s=t.cells?.[o]||{value:``,isFormula:!1};if(t.cells[o]||(t.cells[o]=s),!St(i)){let n=Pr(i,e.styles);t.styles[o]=n,s.style=n}if(a){let n=Pr(a,e.borders);t.borders[o]=n,s.border=n}}}t.tables=n}}},ER=class extends ${static getters=[`getRowSize`,`getHeaderSize`];tallestCellInRow={};ctx=document.createElement(`canvas`).getContext(`2d`);beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=Ot(e.position,e.base),n=Array(e.quantity).fill(void 0),r=Bt(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=y(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=zt(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of x(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of _r(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForCellChange(e,t,n){let r=this.tallestCellInRow[e]?.[t];if(r?.cell.col===n){let n=this.getRowTallestCell(e,t);this.history.update(`tallestCellInRow`,e,t,n)}let i=this.getCellHeight({sheetId:e,col:n,row:t});if(!(i<=23)&&(!r&&i>23||r&&i>r.size)){let r={cell:{sheetId:e,col:n,row:t},size:i};this.history.update(`tallestCellInRow`,e,t,r)}}initializeSheet(e){let t=[];for(let n=0;n<this.getters.getNumberRows(e);n++){let r=this.getRowTallestCell(e,n);t.push(r)}this.history.update(`tallestCellInRow`,e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return 23;let t=this.getters.getCell(e),n=this.getters.getColSize(e.sheetId,e.col);return rc(this.ctx,t,this.getters.getLocale(),n)}isInMultiRowMerge(e){let t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(this.getters.getUserRowSize(e,t)!==void 0)return;let n=this.getters.getRowCells(e,t),r=0,i;for(let e=0;e<n.length;e++){let t=this.getters.getCellById(n[e]);if(!t)continue;let a=this.getters.getCellPosition(t.id),o=this.getCellHeight(a);o>r&&o>23&&(r=o,i={cell:a,size:o})}if(i&&i.size>23)return i}};let DR=`0.00%`;function OR(e){class t extends e{getters;pivotId;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t,n){super(t,n),this.getters=n.getters,this.pivotId=e}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){let n=`${e}-${t.map(e=>e.field+`=`+e.value).join(`,`)}`;if(this.cache[n])return this.cache[n];let r=this.getMeasure(e),i=r.computedBy?this.computeMeasure(r,t):super.getPivotCellValueAndFormat(e,t);return r.format?this.cache[n]={...i,format:r.format}:this.cache[n]=i,this.cache[n]}computeMeasure(e,t){if(!e.computedBy)return{value:0};let{columns:n,rows:r}=super.definition;if(e.aggregator&&n.length+r.length!==t.length){let n=this.getValuesToAggregate(e,t),r=Du[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return BT(t,e.aggregator.toUpperCase())}}let i=this.getters.getMeasureCompiledFormula(this.pivotId,e),a=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,e=>{let{columns:n,rows:r}=this.definition;if(n.find(t=>t.nameWithGranularity===e)){let{colDomain:n}=Jl(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new aa:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=Jl(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new aa:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return A(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=Jl(this,t),i=this.getTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=Iu(this.definition.getDimension(r.field),t[n]?.value);if(r.field===t[n]?.field&&r.value===e)return this.getSubTreeMatchingDomain(r.children,t,n+1)}return[]}treeToLeafDomains(e,t=[]){let n=[];for(let r of e){let e=this.definition.getDimension(r.field),i=[...t,{field:r.field,value:r.value,type:e.type}];r.children.length===0?n.push(i):n.push(...this.treeToLeafDomains(r.children,i))}return n}getMeasureDisplayValue(e,t){let n=this.getMeasure(e),r=this._getPivotCellValueAndFormat(e,t);if(!n.display||n.display.type===`no_calculations`||r.message)return r;let i=n.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:j.NotAvailable,message:E(`Field "%s" not found in pivot for measure display calculation`,i)};try{let e=n.display;switch(e.type){case`%_of_grand_total`:return this.asPercentOfGrandTotal(r,n);case`%_of_col_total`:return this.asPercentOfColumnTotal(r,n,t);case`%_of_row_total`:return this.asPercentOfRowTotal(r,n,t);case`%_of_parent_row_total`:return this.asPercentOfParentRowTotal(r,n,t);case`%_of_parent_col_total`:return this.asPercentOfParentColumnTotal(r,n,t);case`index`:return this.asIndex(r,n,t);case`%_of_parent_total`:return this.asPercentOfParentTotal(r,n,t,e);case`running_total`:return this.asRunningTotal(r,n,t,e,`running_total`);case`%_running_total`:return this.asRunningTotal(r,n,t,e,`%_running_total`);case`rank_asc`:return this.asRank(r,n,t,e,`asc`);case`rank_desc`:return this.asRank(r,n,t,e,`desc`);case`%_of`:return this.asPercentOf(r,n,t,e);case`difference_from`:return this.asDifferenceFrom(r,n,t,e);case`%_difference_from`:return this.asDifferenceFromInPercent(r,n,t,e)}return r}catch(e){return BT(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:j.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:DR}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:j.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:DR}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:j.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:DR}}asPercentOfParentRowTotal(e,t,n){let r=Kl(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:DR}}asPercentOfParentColumnTotal(e,t,n){let r=ql(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:DR}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!nu(i,n))return{value:``};let a=eu(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:DR}}asIndex(e,t,n){let r=this.measureValueToNumber(e),i=this.getRowTotal(t.id,n),a=this.getColumnTotal(t.id,n),o=this.getGrandTotal(t.id);return i===0||a===0?{value:j.DivisionByZero}:{value:r*o/(a*i),format:void 0}}asRunningTotal(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;let o=i===`running_total`?this.runningTotal:this.runningTotalInPercent,s=o[t.id]?.[a];s||(s=this.computeRunningTotal(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=Jl(this,n),u=au(l),d=au(c);return{value:s[u]?.[d]??``,format:i===`running_total`?e.format:DR}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!nu(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:j.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:DR}:s===void 0?{value:j.NullError}:{value:s/o,format:DR}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!nu(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a)||0;return o===`sameValue`?{value:``}:{value:this.measureValueToNumber(e)-o,format:e.format}}asDifferenceFromInPercent(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!nu(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:j.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:j.NullError}:{value:(s-o)/o,format:DR}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!nu(a,n))return{value:``};let o=i===`asc`?this.rankAsc:this.rankDesc,s=o[t.id]?.[a];s||(s=this.computeRank(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=Jl(this,n),u=au(l),d=au(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=ru(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=Pa(o));for(let s of o){let o=au(Yl(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:Yl(this,i,t.domain)})).filter(e=>nu(t,e.rowDomain)),l=Object.groupBy(c,e=>su(e.rowDomain,t));for(let e in l)l[e]=Jt(l[e]||[],e=>e.value).filter(e=>e.value!==void 0).sort((e,t)=>n===`asc`?e.value-t.value:t.value-e.value);r[o]={};for(let e of c){let n=au(Yl(this,i,e.domain)),a=l[su(e.rowDomain,t)];if(!a)continue;let s=a.findIndex(t=>t.value===e.value);s!==-1&&(r[o][n]=s+1)}}return i===`row`?r:Yt(r)}computeRunningTotal(e,t,n){let r={},i=ru(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=Pa(o));for(let s of o){let o=au(Yl(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:Yl(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>nu(t,e.rowDomain));for(let e of l){let n=au(e.rowDomain),i=cu(e.rowDomain,t),a=(c[i]||0)+e.value;c[i]=a,r[o][n]=a}if(n===`%_running_total`)for(let e of l){let n=e.rowDomain,i=au(n),a=cu(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:Yt(r)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=Jl(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=Jl(this,t).colDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,n,r){let i=r===`(previous)`||r===`(next)`?iu(this,t,n,r):tu(t,n,r);if(C(i,t))return`sameValue`;if(!i||!Zl(this,i))throw new aa;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}}return t}let kR=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function AR(e){return kR.includes(e.type)}var jR=class extends ${static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotIdFromPosition`,`getPivotIdsFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`];pivots={};unusedPivots;custom;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){switch(e.type){case`START`:for(let e of this.getters.getPivotIds())this.setupPivot(e)}}handle(e){if(Ri.has(e.type))for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0});switch(e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.unusedPivots?.push(e.pivotId),this.setupPivot(e.pivotId);break;case`DUPLICATE_PIVOT`:this.unusedPivots?.push(e.newPivotId),this.setupPivot(e.newPivotId);break;case`UPDATE_PIVOT`:this.setupPivot(e.pivotId,{recreate:!0});break;case`DELETE_SHEET`:case`UPDATE_CELL`:this.unusedPivots=void 0;break;case`UNDO`:case`REDO`:{this.unusedPivots=void 0;let t=e.commands.filter(AR);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:OF();break}}getPivotIdFromPosition(e){return this.getPivotIdsFromPosition(e)[0]}getPivotIdsFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getPivotIdsFromFormula(e.sheetId,t.compiledFormula):[]}getPivotIdsFromFormula(e,t){return this.getPivotFunctions(e,t.tokens).map(e=>{let t=e.args[0]?.toString();return t&&this.getters.getPivotId(t)}).filter(S)}isSpillPivotFormula(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens)?.functionName===`PIVOT`:!1}getPivotFunctions(e,t){let n=KE(t);if(!n.length)return[];let r=[];for(let t of n){let{functionName:n,args:i}=t,a=i.map(t=>{if(t.type===`EMPTY`)return;if(t.type===`STRING`||t.type===`BOOLEAN`||t.type===`NUMBER`)return t.value;let n=bC(t);return this.getters.evaluateFormula(e,n)});r.push({functionName:n,args:a})}return r}getFirstPivotFunction(e,t){return this.getPivotFunctions(e,t)[0]}getPivotCellFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||qE(t.compiledFormula.tokens)===0)return hF;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!r)return hF;let{functionName:i,args:a}=r,o=a[0];if(!o)return hF;let s=this.getters.getPivotId(o.toString());if(!s)return hF;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!t.content.replaceAll(` `,``).toUpperCase().startsWith(`=PIVOT`))return hF;try{if(i===`PIVOT`){let t=El(a[2]),r=t===void 0?!0:L(t),i=El(a[3]),o=i===void 0?!0:L(i),s=c.getTableStructure().getPivotCells(r,o),l=e.col-n.col,u=e.row-n.row;return s[l][u]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>A(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`)return{type:`HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})))};let[o,...s]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(s.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return hF}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName),n=1,r=E(`Calculated measure %s`,n);for(;t.includes(r);)n++,r=E(`Calculated measure %s`,n);return r}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){return this._getUnusedPivots().includes(e)}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=y(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=OR(AF.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivots(){if(this.unusedPivots!==void 0)return this.unusedPivots;let e=new Set(this.getters.getPivotIds());for(let t of this.getters.getSheetIds())for(let n in this.getters.getCells(t)){let t=this.getters.getCellPosition(n),r=this.getPivotIdsFromPosition(t);for(let t of r)if(e.delete(t),!e.size)return this.unusedPivots=[],[]}for(let t of this.getters.getPivotIds()){let n=this.getters.getPivotCoreDefinition(t);for(let r of n.measures)if(r.computedBy){let{sheetId:n}=r.computedBy,i=this.getters.getMeasureCompiledFormula(t,r),a=this.getPivotIdsFromFormula(n,i);for(let t of a)if(e.delete(t),!e.size)return this.unusedPivots=[],[]}}return this.unusedPivots=[...e],this.unusedPivots}},MR=class{cells;getters;index=0;direction;constructor(e,t,n){this.cells=e,this.getters=t,this.direction=n}next(){let e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:n,tooltip:r}=$E.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:n,tooltip:r,origin:{col:e.data.col,row:e.data.row}}}},NR=class extends ${static layers=[`Autofill`];static getters=[`getAutofillTooltip`];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case`AUTOFILL_SELECT`:let t=this.getters.getActiveSheetId();return this.lastCellSelected.col=e.col===-1?this.lastCellSelected.col:b(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=e.row===-1?this.lastCellSelected.row:b(e.row,0,this.getters.getNumberRows(t)),this.lastCellSelected.col!==void 0&&this.lastCellSelected.row!==void 0?`Success`:`InvalidAutofillSelection`}return`Success`}handle(e){switch(e.type){case`AUTOFILL`:this.autofill(!0);break;case`AUTOFILL_SELECT`:this.select(e.col,e.row);break;case`AUTOFILL_AUTO`:this.autofillAuto();break}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||this.direction===void 0){this.tooltip=void 0;return}let t=this.getters.getSelectedZone(),n=this.autofillZone,r=[];switch(this.direction){case`down`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.top;n<=t.bottom;n++)i.push(w(e,n));let a=this.createGenerator(i);for(let t=n.top;t<=n.bottom;t++)r.push(this.computeNewCell(a,e,t))}break;case`up`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.bottom;n>=t.top;n--)i.push(w(e,n));let a=this.createGenerator(i);for(let t=n.bottom;t>=n.top;t--)r.push(this.computeNewCell(a,e,t))}break;case`left`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.right;n>=t.left;n--)i.push(w(n,e));let a=this.createGenerator(i);for(let t=n.right;t>=n.left;t--)r.push(this.computeNewCell(a,t,e))}break;case`right`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.left;n<=t.right;n++)i.push(w(n,e));let a=this.createGenerator(i);for(let t=n.left;t<=n.right;t++)r.push(this.computeNewCell(a,t,e))}break}if(e){let e={},t={},n={},i=this.getters.getActiveSheetId();for(let a of r)this.collectBordersData(a,e),this.autofillMerge(i,a),this.autofillCell(i,a),this.collectConditionalFormatsData(i,a,t),this.collectDataValidationsData(i,a,n);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,n),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){let n=JSON.stringify(e.border);n in t||(t[n]=[]),t[n].push(D({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s=this.getters.getRulesByCell(e,r,i),c=w(a,o);for(let e of s)e.id in n||(n[e.id]=[]),n[e.id].push(c)}collectDataValidationsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s={sheetId:e,col:r,row:i},c=this.getters.getValidationRuleForCell(s);c&&(c.id in n||(n[c.id]=[]),n[c.id].push(D({col:a,row:o})))}autofillCell(e,t){this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t.col,row:t.row,content:t.content||``,style:t.style||null,format:t.format||``}),this.dispatch(`AUTOFILL_CELL`,t)}autofillBorders(e,t){for(let n in t){let r=n===`undefined`?void 0:JSON.parse(n);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,border:r,target:T(t[n])})}}autofillConditionalFormats(e,t){for(let n in t){let r=t[n],i=this.getters.getConditionalFormats(e).find(e=>e.id===n);if(!i)continue;let a=this.getters.getAdaptedCfRanges(e,i,r.map(Qn),[]);a&&this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:i.id,rule:i.rule,stopIfTrue:i.stopIfTrue},ranges:a,sheetId:e})}}autofillDataValidations(e,t){for(let n in t){let r=t[n],i=this.getters.getDataValidationRule(e,n);if(!i)continue;let a=T(i.ranges.map(e=>e.zone).concat(r),[]);this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:i,ranges:a.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}select(e,t){let n=this.getters.getSelectedZone();if(dr(e,t,n)){this.autofillZone=void 0;return}switch(this.direction=this.getDirection(e,t),this.direction){case`up`:this.saveZone(t,n.top-1,n.left,n.right),this.steps=n.top-t;break;case`down`:this.saveZone(n.bottom+1,t,n.left,n.right),this.steps=t-n.bottom;break;case`left`:this.saveZone(n.top,n.bottom,e,n.left-1),this.steps=n.left-e;break;case`right`:this.saveZone(n.top,n.bottom,n.right+1,e),this.steps=e-n.right;break}this.autofill(!1)}autofillAuto(){let e=this.getters.getActivePosition(),t=this.getters.getTable(e),n=t?t.range.zone.bottom:this.getAutofillAutoLastRow(),r=this.getters.getSelectedZone();for(let t=r.bottom+1;t<=n;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==`empty`){n=t-1;break}n>r.bottom&&(this.select(e.col,n),this.autofill(!0))}getAutofillAutoLastRow(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId(),n=e.left,r=e.bottom;if(n>0){let e={sheetId:t,col:n-1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n-1,row:r}}if(r===e.bottom&&(n=e.right,n<=this.getters.getNumberCols(t))){let e={sheetId:t,col:n+1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n+1,row:r}}return r-1}computeNewCell(e,t,n){let{cellData:r,tooltip:i,origin:a}=e.next(),{content:o,style:s,border:c,format:l}=r;return this.tooltip=i,{originCol:a.col,originRow:a.row,col:t,row:n,content:o,style:s,border:c,format:l}}getRule(e,t){let n=eD.getAll().sort((e,t)=>e.sequence-t.sequence).find(n=>n.condition(e,t));return n&&this.direction&&n.generateRule(e,t,this.direction)}createGenerator(e){let t=[],n=[],r=this.getters.getActiveSheetId();for(let t of e){let{col:e,row:i}=Pn(t),a=this.getters.getCell({sheetId:r,col:e,row:i});n.push({col:e,row:i,cell:a,sheetId:r})}let i=n.map(e=>e.cell);for(let e of n){let n={type:`COPY_MODIFIER`};e&&e.cell&&(n=this.getRule(e.cell,i)||n);let r=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:r},rule:n})}return new MR(t,this.getters,this.direction)}saveZone(e,t,n,r){this.autofillZone={top:e,bottom:t,left:n,right:r}}getDirection(e,t){let n=this.getters.getSelectedZone(),r={up:{number:n.top-t,value:`up`},down:{number:t-n.bottom,value:`down`},left:{number:n.left-e,value:`left`},right:{number:e-n.right,value:`right`}};if(Object.values(r).map(e=>+(e.number>0)).reduce((e,t)=>e+t)===1)return Object.values(r).find(e=>+(e.number>0)).value;let i=r.up.number>0?`up`:`down`,a=r.left.number>0?`left`:`right`;return Math.abs(r[i].number)>=Math.abs(r[a].number)?r[i].value:r[a].value}autofillMerge(e,t){let{originCol:n,originRow:r,col:i,row:a}=t,o={sheetId:e,col:i,row:a},s={sheetId:e,col:n,row:r};if(this.getters.isInMerge(o)&&!this.getters.isInMerge(s)){let t=this.getters.getMerge(o);t&&this.dispatch(`REMOVE_MERGE`,{sheetId:e,target:[t]})}let c=this.getters.getMerge(s);c?.left===n&&c?.top===r&&this.dispatch(`ADD_MERGE`,{sheetId:e,target:[{top:a,bottom:a+c.bottom-c.top,left:i,right:i+c.right-c.left}]})}drawLayer(e){if(!this.autofillZone)return;let{ctx:t,thinLineWidth:n}=e,{x:r,y:i,width:a,height:o}=this.getters.getVisibleRect(this.autofillZone);a>0&&o>0&&(t.strokeStyle=`black`,t.lineWidth=n,t.setLineDash([3]),t.strokeRect(r,i,a,o),t.setLineDash([]))}},PR=class extends ${static getters=[`getAutomaticSums`];handle(e){switch(e.type){case`SUM_SELECTION`:let e=this.getters.getActiveSheetId(),{zones:t,anchor:n}=this.getters.getSelection();for(let r of t){let t=this.getAutomaticSums(e,r,n.cell);this.dispatchCellUpdates(e,t)}break}}getAutomaticSums(e,t,n){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,n):this.sumData(e,t)}sumData(e,t){let n=this.dimensionsToSum(e,t),r=this.sumDimensions(e,t,n).filter(({zone:t})=>!this.getters.isEmpty(e,t));return n.has(`ROW`)&&n.has(`COL`)&&r.push(this.sumTotal(t)),r}sumAdjacentData(e,t,n){let{col:r,row:i}=dr(n.col,n.row,t)?n:{col:t.left,row:t.top},a=this.findAdjacentData(e,r,i);return a?this.getters.isSingleCellOrMerge(e,t)||mr(or(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,or(a,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,n){let r=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.findSuitableZoneToSum(r,i.col,i.row);if(a)return this.getters.expandZone(e,a)}findSuitableZoneToSum(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:n-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:n});if(this.isNumber(i)&&!this.isNumber(r))return this.findHorizontalZone(e,t,n);let a=this.findVerticalZone(e,t,n);if(this.isZoneValid(a))return a;let o=this.findHorizontalZone(e,t,n);if(this.isZoneValid(o))return o}findVerticalZone(e,t,n){let r={top:0,bottom:n-1,left:t,right:t},i=this.reduceZoneStart(e,r,r.bottom);return{...r,top:i}}findHorizontalZone(e,t,n){let r={top:n,bottom:n,left:0,right:t-1},i=this.reduceZoneStart(e,r,r.right);return{...r,left:i}}reduceZoneStart(e,t,n){let r=this.getters.getEvaluatedCellsInZone(e.id,t),i=x(n,-1,-1),a=Gt(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=ct(i.filter(e=>this.isNumber(r[e])))[0]||[];return Gt(o)<a?1/0:Kt(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&Go(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){let n=new Set;return mr(t)?(n.add(pr(t).numberOfCols===1?`COL`:`ROW`),n):(this.lastColIsEmpty(e,t)&&n.add(`ROW`),this.lastRowIsEmpty(e,t)&&n.add(`COL`),n.size===0&&n.add(`COL`),n)}sumDimensions(e,t,n){return[...n.has(`COL`)?this.sumColumns(t,e):[],...n.has(`ROW`)?this.sumRows(t,e):[]]}sumTotal(e){let{bottom:t,right:n}=e;return{position:{col:n,row:t},zone:{...e,top:t,right:n-1}}}sumColumns(e,t){let n=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,n.bottom-1)},_r(n).map(t=>({position:t,zone:{...e,right:t.col,left:t.col}}))}sumRows(e,t){let n=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,n.right-1)},_r(n).map(t=>({position:t,zone:{...e,top:t.row,bottom:t.row}}))}dispatchCellUpdates(e,t){for(let n of t){let{col:t,row:r}=n.position;this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:`=SUM(${this.getters.zoneToXC(e,n.zone)})`})}}nextEmptyRow(e,t){let n=t.bottom+1,{left:r,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:n,top:n,left:r,right:i});)n++;return{...t,top:n,bottom:n}}nextEmptyCol(e,t){let n=t.right+1,{top:r,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:n,right:n,top:r,bottom:i});)n++;return{...t,left:n,right:n}}transpose(e){return new Set([...e.values()].map(e=>e===`COL`?`ROW`:`COL`))}};CN.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],KR),CN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],KR),CN.addTransformation(`ADD_COLUMNS_ROWS`,[`CREATE_CHART`,`UPDATE_CHART`],BR),CN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`CREATE_CHART`,`UPDATE_CHART`],BR),CN.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],RR),CN.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`],zR),CN.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],VR),CN.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],HR),CN.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],UR),CN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],UR),CN.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],WR),CN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],WR),CN.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],GR),CN.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],qR),CN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],qR),CN.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],LR),CN.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],IR),CN.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],FR),CN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],FR);function FR(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=td(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function IR(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function LR(e,t){if(e.pivotId!==t.pivotId)return e}function RR(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function zR(e,t){if(e.id!==t.id)return e}function BR(e,t){return{...e,definition:vk(e.definition,t)}}function VR(e,t){return e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`}),e.name===t.name?{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,e=>(parseInt(e)+1).toString()):`${e.name}~`,position:e.position+1}:e}function HR(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!ur(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function UR(e,t){if(e.sheetId!==t.sheetId||(e.type===`FREEZE_COLUMNS`?`COL`:`ROW`)!==t.dimension)return e;let n=e.quantity;if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);for(let t of e)n>t&&n--}if(t.type===`ADD_COLUMNS_ROWS`){let e=t.position===`before`?t.base-1:t.base;n=n>e?n+t.quantity:n}return n>0?{...e,quantity:n}:void 0}function WR(e,t){if(e.sheetId!==t.sheetId)return e;let n=td(e.zone,t);if(!n)return;let r=e.newTableRange?nd(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function GR(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:Om.styleId}}:e}function KR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=Qs(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=Zs(Ot(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function qR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n=x(e.start,e.end+1),r=[];if(t.type===`REMOVE_COLUMNS_ROWS`?r=Qs(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=Zs(Ot(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}let JR=[{match:Mi,fn:QR},{match:Pi,fn:$R},{match:Li,fn:ez},{match:Ii,fn:rz},{match:Ni,fn:nz},{match:Fi,fn:tz}];function YR(e,t){let n=CN.getTransformation(e.type,t.type);return n?n(e,t):ZR(e,t)}function XR(e,t){let n=[...e],r=new Set(CN.getKeys());for(let e of t)r.has(e.type)&&(n=n.reduce((t,n)=>{let r=YR(n,e);return r&&t.push(r),t},[]));return n}function ZR(e,t){for(let{match:n,fn:r}of JR)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function QR(e,t){if(!(`sheetId`in t))return e;let n=t.type===`DELETE_SHEET`&&t.sheetId;return e.sheetId===n?`IGNORE_COMMAND`:e.type===`CREATE_SHEET`||t.type===`CREATE_SHEET`||e.sheetId!==t.sheetId?e:`SKIP_TRANSFORMATION`}function $R(e,t){let n=QR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=td(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function ez(e,t){let n=QR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=td(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function tz(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>nd(e,t)).filter(S);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function nz(e,t){let n=QR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;if(t.type!==`ADD_COLUMNS_ROWS`&&t.type!==`REMOVE_COLUMNS_ROWS`)return`SKIP_TRANSFORMATION`;if(t.dimension!==e.dimension)return e;let r=[];return t.type===`REMOVE_COLUMNS_ROWS`?r=Qs(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=Zs(Ot(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function rz(e,t){let n=QR(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?iz(e,t):t.type===`ADD_MERGE`?az(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function iz(e,t){let n=t.dimension===`COL`?`col`:`row`,r=e[n];if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);if(e.includes(r))return`IGNORE_COMMAND`;for(let t of e)r>=t&&r--}return t.type===`ADD_COLUMNS_ROWS`&&(r>t.base||r===t.base&&t.position===`before`)&&(r+=t.quantity),{...e,[n]:r}}function az(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&dr(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var oz=class{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,n,r,i,a){this.rootCommand=r,this.timestamp=a,this.id=e,this.clientId=t,this._commands=[...n],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}},sz=class extends Error{},cz=class extends rd{revisions;transportService;serverRevisionId;clients={};clientId=`local`;debouncedMove;pendingMessages=[];waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new wc;lastLocalOperation;constructor(e,t,n=Ve){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.debouncedMove=Ct(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new oz(this.uuidGenerator.uuidv4(),this.clientId,t,e,n,Date.now());this.revisions.append(r.id,r),e.type!==`REQUEST_REDO`&&(this.lastLocalOperation=r),this.trigger(`new-local-state-update`,{id:r.id}),this.sendUpdateMessage({type:`REMOTE_REVISION`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:r.id,clientId:r.clientId,commands:r.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_UNDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:`local`,name:`local`},this.clientId=`local`),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this))}loadInitialMessages(e){let t=performance.now(),n=e.reduce((e,t)=>e+(t.type===`REMOTE_REVISION`?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(let t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug(`Replayed`,n,`commands in`,performance.now()-t,`ms`)}async leave(e){e&&Object.keys(this.clients).length===1&&this.lastRevisionMessage&&this.lastRevisionMessage?.type!==`SNAPSHOT_CREATED`&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:`CLIENT_LEFT`,clientId:this.clientId,version:1})}async snapshot(e){if(this.pendingMessages.length!==0)return;let t=this.uuidGenerator.uuidv4();await this.transportService.sendMessage({type:`SNAPSHOT`,nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){let e=this.clients[this.clientId];if(!e)throw new sz(`The client left the session`);return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(S))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return this.pendingMessages.length===0}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId])return;let t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;let n=t?`CLIENT_MOVED`:`CLIENT_JOINED`,r=this.getClient();this.clients[this.clientId]={...r,position:e},this.transportService.sendMessage({type:n,version:1,client:{...r,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){if(this.isWrongServerRevisionId(e)){this.trigger(`unexpected-revision-id`);return}switch(e.type){case`CLIENT_MOVED`:this.onClientMoved(e);break;case`CLIENT_JOINED`:this.onClientJoined(e);break;case`CLIENT_LEFT`:this.onClientLeft(e);break;case`REVISION_REDONE`:this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-redone`,{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case`REVISION_UNDONE`:this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-undone`,{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case`REMOTE_REVISION`:let{clientId:t,commands:n,timestamp:r}=e,i=new oz(e.nextRevisionId,t,n,void 0,void 0,r);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);let t=this.pendingMessages.filter(e=>e.type===`REMOTE_REVISION`).map(e=>e.commands).flat();this.trigger(`remote-revision-received`,{commands:XR(n,t)})}break;case`SNAPSHOT_CREATED`:{let t=new oz(e.nextRevisionId,`server`,[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger(`snapshot`),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger(`collaborative-event-received`)}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;let t=this.clients[this.clientId];if(t){let{position:e}=t;e&&this.transportService.sendMessage({type:`CLIENT_MOVED`,version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),!this.waitingAck&&this.sendPendingMessage()}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if(e.type===`REMOTE_REVISION`){let t=this.revisions.get(e.nextRevisionId);t.commands.length===0&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.
1891
+ ${JSON.stringify(e)}`);this.waitingAck=!0,this.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch((e.type===`REVISION_UNDONE`||e.type===`REVISION_REDONE`)&&(this.waitingUndoRedoAck=!1),e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`SNAPSHOT_CREATED`:this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.lastRevisionMessage=e,this.sendPendingMessage();break;case`REVISION_UNDONE`:{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId);let t=this.pendingMessages.findIndex(e=>e.type===`REMOTE_REVISION`);t!==-1&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}isAlreadyProcessed(e){if(e.type===`CLIENT_MOVED`&&e.client.id===this.clientId)return!0;switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter(({type:e})=>e!==`REVISION_REDONE`&&e!==`REVISION_UNDONE`)}};function lz(e){return e[Math.floor(Math.random()*e.length)]}let uz=[`#ff851b`,`#0074d9`,`#7fdbff`,`#b10dc9`,`#39cccc`,`#f012be`,`#3d9970`,`#111111`,`#ff4136`,`#aaaaaa`,`#85144b`,`#001f3f`];var dz=class extends ${static getters=[`getClientsToDisplay`,`getClient`,`getConnectedClients`,`isFullySynchronized`];static layers=[`Selection`];availableColors=new Set(uz);colors={};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)}chooseNewColor(){this.availableColors.size===0&&(this.availableColors=new Set(uz));let e=lz([...this.availableColors.values()]);return this.availableColors.delete(e),e}getClient(){return this.session.getClient()}getConnectedClients(){return this.session.getConnectedClients()}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getClient()}catch(e){if(e instanceof sz)return[];throw e}let e=this.getters.getActiveSheetId(),t=[];for(let n of this.getters.getConnectedClients())if(n.id!==this.getters.getClient().id&&n.position&&n.position.sheetId===e&&this.isPositionValid(n.position)){let e=n.position;this.colors[n.id]||(this.colors[n.id]=this.chooseNewColor());let r=this.colors[n.id];t.push({...n,position:e,color:r})}return t}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getters.getActiveSheetId();for(let e of this.getClientsToDisplay()){let{row:i,col:a}=e.position,o=this.getters.expandZone(r,{top:i,bottom:i,left:a,right:a}),{x:s,y:c,width:l,height:u}=this.getters.getVisibleRect(o);if(l<=0||u<=0)continue;let d=e.color;t.fillStyle=`${d}10`,t.lineWidth=4*n,t.strokeStyle=d,t.globalCompositeOperation=`multiply`,t.fillRect(s,c,l,u),t.globalCompositeOperation=`source-over`,t.strokeRect(s,c,l,u),t.font=`bold ${Re+1}px ${ze}`}}},fz=class extends ${allowDispatch(e){switch(e.type){case`REMOVE_DUPLICATES`:return this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique))}return`Success`}handle(e){switch(e.type){case`REMOVE_DUPLICATES`:this.removeDuplicates(e.columns,e.hasHeader);break;case`TRIM_WHITESPACE`:this.trimWhitespace();break}}removeDuplicates(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getSelectedZone();t&&(r.top+=1);let i=this.getUniqueRowsIndexes(n,r.top,r.bottom,e),a=i.length;if(a===pr(r).numberOfRows){this.notifyRowsRemovedAndRemaining(0,a);return}let o=i.map(e=>({left:r.left,top:e,right:r.right,bottom:e})),s=new Wu(this.getters,this.dispatch),c=s.copy(Tc(n,o));if(!c)return;this.dispatch(`CLEAR_CELLS`,{target:[r],sheetId:n});let l={left:r.left,top:r.top,right:r.left,bottom:r.top};s.paste({zones:[l],sheetId:n},c,{isCutOperation:!1});let u={left:r.left,top:r.top-+!!t,right:r.right,bottom:r.top+a-1};this.selection.selectZone({cell:{col:u.left,row:u.top},zone:u});let d=r.bottom-r.top+1-a;this.notifyRowsRemovedAndRemaining(d,a)}getUniqueRowsIndexes(e,t,n,r){let i=new Map;for(let a of x(t,n+1)){let t=r.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:a}).value);Object.values(i).some(e=>C(e,t))||(i[a]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:`info`,text:E(`%s duplicate rows found and removed.
1892
+ %s unique rows remain.`,e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return this.getters.getSelectedZones().length===1?`Success`:`MoreThanOneRangeSelected`}checkNoMergeInZone(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?`WillRemoveExistingMerge`:`Success`}checkRangeContainsValues(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedZone();return e.hasHeader&&(n.top+=1),this.getters.getEvaluatedCellsInZone(t,n).every(e=>e.type===`empty`)?`EmptyTarget`:`Success`}checkNoColumnProvided(e){return e.columns.length===0?`NoColumnsProvided`:`Success`}checkColumnsIncludedInZone(e){let t=this.getters.getSelectedZone();return e.columns.some(e=>e<t.left||e>t.right)?`ColumnsNotIncludedInZone`:`Success`}checkColumnsAreUnique(e){return e.columns.length===new Set(e.columns).size?`Success`:`DuplicatesColumnsSelected`}trimWhitespace(){let e=T(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(_r).flat()){let e=this.getters.getCell({col:r,row:i,sheetId:t});if(!e)continue;let a=Ht(e.content);a!==e.content&&(n+=1,this.dispatch(`UPDATE_CELL`,{sheetId:t,col:r,row:i,content:a}))}let r=n?E(`Trimmed whitespace from %s cells.`,n):E(`No selected cells had whitespace trimmed.`);this.ui.notifyUI({type:`info`,text:r,sticky:!1})}},pz=class extends ${handle(e){switch(e.type){case`SET_DECIMAL`:this.setDecimal(e.sheetId,e.target,e.step);break;case`SET_FORMATTING_WITH_PIVOT`:this.setContextualFormat(e.sheetId,e.target,e.format);break}}setContextualFormat(e,t,n){let r=[],i={};for(let n of T(t))for(let t=n.left;t<=n.right;t++)for(let a=n.top;a<=n.bottom;a++){let n={sheetId:e,col:t,row:a},o=this.getters.getPivotCellFromPosition(n);if(this.isSpilledPivotValueFormula(n,o)){r.push(n);let e=this.getters.getPivotIdFromPosition(n)||``;i[e]??=new Set,i[e].add(o.measure)}}let a=T(r.map(D));for(let e in i){let t=i[e],r=this.getters.getPivotCoreDefinition(e);this.dispatch(`UPDATE_PIVOT`,{pivotId:e,pivot:{...r,measures:r.measures.map(e=>t.has(e.id)?{...e,format:n}:e)}})}this.dispatch(`SET_FORMATTING`,{sheetId:e,target:a,format:``}),this.dispatch(`SET_FORMATTING`,{sheetId:e,target:T(t,a),format:n})}isSpilledPivotValueFormula(e,t){let n=this.getters.getCell(e);return t.type===`VALUE`&&!n?.isFormula}setDecimal(e,t,n){let r={};for(let i of T(t))for(let t of _r(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=cs(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=T(r[t].map(e=>D(e)));this.setContextualFormat(e,n,t)}}getCellNumberFormat(e){for(let t of[e]){let e=this.getters.getEvaluatedCell(t);if(e.type===`number`&&!(e.format&&Go(e.format)))return e.format||Yo(e.value)}}},mz=class extends ${static getters=[`getNextVisibleCellPosition`,`findVisibleHeader`,`findLastVisibleColRowIndex`,`findFirstVisibleColRowIndex`,`isRowHidden`,`isColHidden`,`isHeaderHidden`];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,n){return t===`COL`?this.isColHidden(e,n):this.isRowHidden(e,n)}getNextVisibleCellPosition({sheetId:e,col:t,row:n}){return{sheetId:e,col:this.findVisibleHeader(e,`COL`,t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,`ROW`,n,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,n,r){if(n<=r){for(let i=n;i<=r;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}if(n>r){for(let i=n;i>=r;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}}findLastVisibleColRowIndex(e,t,{last:n,first:r}){return x(n,r,-1).find(n=>!this.isHeaderHidden(e,t,n))||r}findFirstVisibleColRowIndex(e,t){let n=this.getters.getNumberHeaders(e,t);for(let r=0;r<n;r++)if(t===`COL`&&!this.isColHidden(e,r)||t===`ROW`&&!this.isRowHidden(e,r))return r}exportForExcel(e){for(let t of e.sheets)for(let[e,n]of Object.entries(t.rows))n.isHidden=this.isRowHidden(t.id,Number(e))}},hz=class extends ${static getters=[];allowDispatch(e){switch(e.type){case`DUPLICATE_PIVOT_IN_NEW_SHEET`:if(!this.getters.isExistingPivot(e.pivotId))return`PivotIdNotFound`;if(!this.getters.getPivot(e.pivotId).isValid())return`PivotInError`;break}return`Success`}handle(e){switch(e.type){case`INSERT_NEW_PIVOT`:this.insertNewPivot(e.pivotId,e.newSheetId);break;case`DUPLICATE_PIVOT_IN_NEW_SHEET`:this.duplicatePivotInNewSheet(e.pivotId,e.newPivotId,e.newSheetId);break;case`INSERT_PIVOT_WITH_TABLE`:this.insertPivotWithTable(e.sheetId,e.col,e.row,e.pivotId,e.table,e.pivotMode);break;case`SPLIT_PIVOT_FORMULA`:this.splitPivotFormula(e.sheetId,e.col,e.row,e.pivotId)}}insertNewPivot(e,t){Er(this.getters.getSelectedZone())===1&&this.selection.selectTableAroundSelection();let n=this.getters.getActiveSheetId();this.dispatch(`ADD_PIVOT`,{pivotId:e,pivot:{dataSet:{zone:this.getters.getSelectedZone(),sheetId:n},columns:[],rows:[],measures:[],name:E(`New pivot`),type:`SPREADSHEET`}});let r=this.getters.getSheetIds().findIndex(e=>e===n)+1,i=this.getters.getPivotFormulaId(e);this.dispatch(`CREATE_SHEET`,{sheetId:t,name:E(`Pivot #%(formulaId)s`,{formulaId:i}),position:r}),this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:n,sheetIdTo:t});let a=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,a.getTableStructure().export(),`dynamic`)}duplicatePivotInNewSheet(e,t,n){this.dispatch(`DUPLICATE_PIVOT`,{pivotId:e,newPivotId:t,duplicatedPivotName:E(`%s (copy)`,this.getters.getPivotCoreDefinition(e).name)});let r=this.getters.getActiveSheetId(),i=this.getters.getSheetIds().indexOf(r)+1,a=this.getters.getPivotFormulaId(t),o=this.getters.getPivotName(t);if(this.dispatch(`CREATE_SHEET`,{sheetId:n,name:this.getPivotDuplicateSheetName(E(`%(newPivotName)s (Pivot #%(formulaId)s)`,{newPivotName:o,formulaId:a})),position:i}).isSuccessful){this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:r,sheetIdTo:n});let i=this.getters.getPivot(e);this.insertPivotWithTable(n,0,0,t,i.getTableStructure().export(),`dynamic`)}}getPivotDuplicateSheetName(e){let t=1,n=this.getters.getSheetIds().map(e=>this.getters.getSheetName(e)),r=st(e),i=r;for(;n.includes(i);)i=`${r} (${t})`,t++;return i}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new mF(o,s,c,l||{}),d=u.columns.length-1;this.resizeSheet(e,t,n,u);let f=this.getters.getPivotFormulaId(r),p;a===`dynamic`?(this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:n,content:`=PIVOT(${f})`}),p={left:t,right:t,top:n,bottom:n}):(this.dispatch(`INSERT_PIVOT`,{sheetId:e,col:t,row:n,pivotId:r,table:u.export()}),p={left:t,right:t+u.getNumberOfDataColumns(),top:n,bottom:n+d+u.rows.length}),this.dispatch(`CREATE_TABLE`,{tableType:a,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,p)],config:{...Ze,numberOfHeaders:d}})}resizeSheet(e,t,n,r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,quantity:s-l,position:`after`})}splitPivotFormula(e,t,n,r){let i=this.getters.getSpreadZone({sheetId:e,col:t,row:n});if(!i)return;let a=this.getters.getPivotFormulaId(r),o=new Map;for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++){let r={sheetId:e,col:t,row:n};o.set(r,this.getters.getPivotCellFromPosition(r))}for(let[e,t]of o)this.dispatch(`UPDATE_CELL`,{...e,content:Fu(a,t)});if(this.getters.getCoreTable({sheetId:e,col:t,row:n})?.type===`dynamic`){let r=D({col:t,row:n}),a=this.getters.getRangeDataFromZone(e,i);this.dispatch(`UPDATE_TABLE`,{sheetId:e,zone:r,newTableRange:a,tableType:`static`})}}},gz=class extends ${allowDispatch(e){switch(e.type){case`SORT_CELLS`:if(!dr(e.col,e.row,e.zone))throw Error(E(`The anchor must be part of the provided zone`));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return`Success`}handle(e){switch(e.type){case`SORT_CELLS`:this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{});break}}checkMerge({sheetId:e,zone:t}){return this.getters.doesIntersectMerge(e,t)&&_r(t).some(({col:t,row:n})=>!this.getters.isInMerge({sheetId:e,col:t,row:n}))?`InvalidSortZone`:`Success`}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return`Success`;let n=this.getters.getMerges(e).filter(e=>ur(e,t)),r=pr(n[0]),[i,a]=[r.numberOfCols,r.numberOfRows];return n.every(e=>{let[t,n]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&n===a})?`Success`:`InvalidSortZone`}hasHeader(e,t){if(t[0].length===1)return!1;let n=t.map(t=>t.map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).type));return n[0][0]===`empty`&&(n=n.slice(1)),n.some(e=>e[0]===`empty`)?!1:!!n.some(e=>e[1]!==`empty`&&e[0]!==e[1])}sortZone(e,t,n,r,i){let[a,o]=this.mainCellsSteps(e,n),s=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,c=Object.assign({},n),l=this.mainCells(e,n);!i.sortHeaders&&this.hasHeader(e,l)&&(c.top+=o),l=this.mainCells(e,c);let u=l[s-c.left],d=px(u.map(e=>this.getters.getEvaluatedCell(e)),r,!!i.emptyCellAsZero).map(e=>e.index),[f,p]=[l.length,l[0].length],m=[];for(let e=0;e<f;e++)for(let t=0;t<p;t++){let{col:n,row:r,sheetId:i}=l[e][d[t]],s=this.getters.getCell({sheetId:i,col:n,row:r}),u=c.left+e*a,f=c.top+t*o,p={sheetId:i,col:u,row:f,content:``};if(s){let e=s.content;if(s.isFormula){let t=this.getters.getCellPosition(s.id);e=this.getters.getTranslatedCellFormula(i,0,f-t.row,s.compiledFormula.tokens)}p.style=s.style,p.content=e,p.format=s.format}m.push(p)}m.forEach(e=>this.dispatch(`UPDATE_CELL`,e))}mainCellsSteps(e,t){let n=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[n?n.right-n.left+1:1,n?n.bottom-n.top+1:1]}mainCells(e,t){let[n,r]=this.mainCellsSteps(e,t),i=[],a=x(t.left,t.right+1,n),o=x(t.top,t.bottom+1,r);for(let t of a){let n=[];i.push(n);for(let r of o)n.push({sheetId:e,col:t,row:r})}return i}},_z=class extends ${static getters=[`shouldShowFormulas`];showFormulas=!1;handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.showFormulas=e.show;break}}shouldShowFormulas(){return this.showFormulas}},vz=class extends ${static getters=[`doesCellHaveGridIcon`,`getCellWidth`,`getCellIconSrc`,`getTextWidth`,`getCellText`,`getCellMultiLineText`,`getContiguousZone`];ctx=document.createElement(`canvas`).getContext(`2d`);allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case`AUTORESIZE_COLUMNS`:for(let t of e.cols){let n=this.getColMaxWidth(e.sheetId,t);n!==0&&this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:[t],dimension:`COL`,size:n,sheetId:e.sheetId})}break;case`AUTORESIZE_ROWS`:this.autoResizeRows(e.sheetId,e.rows);break}}getCellWidth(e){let t=this.getters.getCellComputedStyle(e),n=0,r=this.getters.getEvaluatedCell(e).formattedValue;if(r){let e=gc(this.ctx,r,t,void 0);n+=Math.max(...e.map(e=>sc(this.ctx,e,t)))}if(this.getters.getCellIconSrc(e)&&(n+=vc(t)),this.getters.doesCellHaveGridIcon(e)&&(n+=20),n===0)return 0;if(n+=8,t.wrapping===`wrap`){let t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,n)}return n}getCellIconSrc(e){let t=pf.getAll();for(let n of t){let t=n(this.getters,e);if(t)return t}}getTextWidth(e,t){return sc(this.ctx,e,t)}getCellText(e,t){let n=this.getters.getCell(e),r=this.getters.getLocale();if(t?.showFormula&&n?.isFormula)return ol(n.content,r);if(t?.showFormula&&!n?.content)return``;{let i=this.getters.getEvaluatedCell(e),a=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>sc(this.ctx,e,n?.style||{})}:void 0;return B(i.value,{format:i.format,locale:r,formatWidth:a})}}getCellMultiLineText(e,t){let n=this.getters.getCellStyle(e),r=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.formatWidth});return gc(this.ctx,r,n,t.wrapText?t.maxWidth:void 0)}doesCellHaveGridIcon(e){let t=this.getters.isFilterHeader(e),n=!this.getters.isReadonly()&&this.getters.cellHasListDataValidationIcon(e);return t||n}getContiguousZone(e,t){let n=t=>{for(let n of x(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:n,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:n,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(let n of x(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:n}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:n}))return{...t,right:t.right+1}}return t},r=!1,i=t;do{r=!1;let e=n(i);if(!lr(i,e)){r=!0,i=e;continue}}while(r);return i}isCellEmpty(e){let t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===`empty`}getColMaxWidth(e,t){let n=_r(this.getters.getColsZone(e,t,t)).map(t=>this.getCellWidth({sheetId:e,...t}));return Math.max(0,Gt(n))}checkSheetExists(e){return`sheetId`in e&&this.getters.tryGetSheet(e.sheetId)===void 0?`InvalidSheetId`:`Success`}checkZonesAreInSheet(e){let t=`sheetId`in e?e.sheetId:this.getters.tryGetActiveSheetId();if(`ranges`in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId)))return`InvalidSheetId`;let n=this.getters.getCommandZones(e);return!t&&n.length>0?`NoActiveSheet`:t&&n.length>0?this.getters.checkZonesExistInSheet(t,n):`Success`}autoResizeRows(e,t){let n=[];for(let r of t){let t=0;for(let n of this.getters.getRowCells(e,r)){let r=this.getters.getCellById(n);if(!r)continue;let i=this.getters.getCellPosition(r.id),a=this.getters.getColSize(e,i.col);if(r.isFormula||this.getters.getArrayFormulaSpreadingOn(i)){let e=this.getters.getEvaluatedCell(i).formattedValue,n=ic(this.ctx,e,r?.style,a);n>t&&n>23&&(t=n)}else{let e=r.content,n=ic(this.ctx,e,r?.style,a);n>=t&&n>23&&(t=0)}}n.push(t||null)}let r=new Map(n.map(e=>[e,[]]));for(let e=0;e<n.length;e++)r.get(n[e])?.push(t[e]);for(let[t,n]of r)this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:n,dimension:`ROW`,size:t,sheetId:e})}},yz=class extends ${static getters=[`getCellTableStyle`,`getCellTableBorder`];tableStyles={};handle(e){if(Ri.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(xz(e)){`sheetId`in e?delete this.tableStyles[e.sheetId]:this.tableStyles={};return}}finalize(){for(let e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(let t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}getCellTableBorder(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}computeTableStyle(e,t){return Et(()=>{let{config:n,numberOfCols:r,numberOfRows:i}=this.getTableRuntimeConfig(e,t),a=YF(n,this.getters.getTableStyle(t.config.styleId),r,i),o=this.getTableMapping(e,t),s={borders:{},styles:{}};for(let e=0;e<r;e++){let t=o.colMapping[e];s.borders[t]={},s.styles[t]={};for(let n=0;n<i;n++){let r=o.rowMapping[n];s.borders[t][r]=a.borders[e][n],s.styles[t][r]=a.styles[e][n]}}return s})}getTableRuntimeConfig(e,t){let n=t.range.zone,r={...t.config},i=n.right-n.left+1,a=n.bottom-n.top+1;for(let i=n.top;i<=n.bottom;i++)this.getters.isRowHidden(e,i)&&(a--,i-n.top<t.config.numberOfHeaders&&(r.numberOfHeaders--,r.numberOfHeaders<0&&(r.numberOfHeaders=0)),i===n.bottom&&(r.totalRow=!1));for(let t=n.left;t<=n.right;t++)this.getters.isColHidden(e,t)&&(i--,t===n.left&&(r.firstColumn=!1),t===n.right&&(r.lastColumn=!1));return{config:r,numberOfCols:i,numberOfRows:a}}getTableMapping(e,t){let n={},r={},i=0,a=0,o=t.range.zone;for(let t=o.left;t<=o.right;t++)if(!this.getters.isColHidden(e,t)){n[i]=t,i++;for(let t=o.top;t<=o.bottom;t++)this.getters.isRowHidden(e,t)||(r[a]=t,a++)}return{colMapping:n,rowMapping:r}}};let bz=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 xz(e){return bz.has(e.type)}var Sz=class extends ${static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles={};borders={};handle(e){if(Ri.has(e.type)||e.type===`UPDATE_CELL`||e.type===`SET_FORMATTING`||e.type===`CLEAR_FORMATTING`||e.type===`EVALUATE_CELLS`){this.styles={},this.borders={};return}if(xz(e)){`sheetId`in e?(delete this.styles[e.sheetId],delete this.borders[e.sheetId]):(this.styles={},this.borders={});return}if(Vi.has(e.type)){this.styles={};return}if(Hi.has(e.type)){this.borders={};return}}getCellComputedBorder(e){let{sheetId:t,row:n,col:r}=e;return this.borders[t]?.[n]?.[r]===void 0?(this.borders[t]||(this.borders[t]={}),this.borders[t][n]||(this.borders[t][n]={}),this.borders[t][n][r]||(this.borders[t][n][r]=this.computeCellBorder(e)),this.borders[t][n][r]):this.borders[t][n][r]}getCellComputedStyle(e){let{sheetId:t,row:n,col:r}=e;return this.styles[t]?.[n]?.[r]===void 0?(this.styles[t]||(this.styles[t]={}),this.styles[t][n]||(this.styles[t][n]={}),this.styles[t][n][r]||(this.styles[t][n][r]=this.computeCellStyle(e)),this.styles[t][n][r]):this.styles[t][n][r]}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...jt(this.getters.getCellTableBorder(e)||{}),...jt(t)};return St(n)?null:n}computeCellStyle(e){let t=this.getters.getCell(e),n=this.getters.getCellConditionalFormatStyle(e),r={...jt(this.getters.getCellTableStyle(e)),...jt(t?.style),...jt(n)};return this.getters.getEvaluatedCell(e).link&&!r.textColor&&(r.textColor=le),r}},Cz=class extends ${handle(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:if(e.rule.criterion.type===`isBoolean`){let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));for(let e of qs(t)){let t=this.getters.getCell(e),n=this.getters.getEvaluatedCell(e);if(!t?.content)this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`});else if(t?.content&&n.type===`empty`){let n;if(t.content.startsWith(`=`)){let r=this.getters.evaluateFormula(e.sheetId,t.content);n=(A(r)?r[0][0]:r)?.toString()}else n=t.content;(!n||!ut(n))&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}else n.type!==`boolean`&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}}}}};let wz=[Tz,Ez,Oz,kz];function Tz(e,t){return`sheetId`in t?{...y(t),sheetId:e.getActiveSheetId()}:t}function Ez(e,t){return!(`target`in t)||!Array.isArray(t.target)?t:{...y(t),target:e.getSelectedZones()}}function Dz(e,t){return`zone`in t?{...y(t),zone:e.getSelectedZone()}:t}function Oz(e,t){if(!(`row`in t)||!(`col`in t))return t;let{col:n,row:r}=e.getActivePosition();return{...y(t),col:n,row:r}}function kz(e,t){return`ranges`in t?{...y(t),ranges:e.getSelectedZones().map(t=>e.getRangeDataFromZone(e.getActiveSheetId(),t))}:t}let Az=new wc;function jz(e,t){return{...Tz(e,t),id:Az.smallUuid()}}function Mz(e,t){return{...Tz(e,t),figureId:Az.smallUuid()}}function Nz(e,t){let n=Tz(e,t);return n.figure.id=Az.smallUuid(),n}function Pz(e,t){let n=y(t);n.sheetId=Az.smallUuid();let r=t.name||e.getSheet(e.getActiveSheetId()).name,i=r.match(/(.+?)\d*$/)?.[1]||r;return n.name=e.getNextSheetName(i),n}function Fz(e,t){let n=e.getActivePosition();return{...Tz(e,t),base:t.dimension===`COL`?n.col:n.row}}function Iz(e,t){let n=e.getSelectedZone();return{...Tz(e,t),elements:t.dimension===`COL`?x(n.left,n.right+1):x(n.top,n.bottom+1)}}function Lz(e,t){let n=e.getSelectedZone();return{...y(t),zone:n}}function Rz(e,t){let n=y(t),{top:r,bottom:i,left:a,right:o}=e.getSelectedZone();return`cols`in n?n.cols=x(a,o+1):`rows`in n&&(n.rows=x(r,i+1)),n}function zz(e,t){let n=e.getSelectedZone();return{...Tz(e,t),col:n.left,row:n.top,zone:n}}function Bz(e,t){return{type:`REPEAT_PASTE`,pasteOption:y(t.pasteOption),target:e.getSelectedZones()}}function Vz(e,t){let n=e.getSelectedZone();return{...Tz(e,t),start:t.dimension===`COL`?n.left:n.top,end:t.dimension===`COL`?n.right:n.bottom}}let Hz=new h;Hz.add(`UPDATE_CELL`,Wz),Hz.add(`CLEAR_CELL`,Wz),Hz.add(`CLEAR_CELLS`,Wz),Hz.add(`DELETE_CONTENT`,Wz),Hz.add(`ADD_MERGE`,Wz),Hz.add(`REMOVE_MERGE`,Wz),Hz.add(`SET_FORMATTING`,Wz),Hz.add(`CLEAR_FORMATTING`,Wz),Hz.add(`SET_BORDER`,Wz),Hz.add(`CREATE_TABLE`,Wz),Hz.add(`REMOVE_TABLE`,Wz),Hz.add(`HIDE_SHEET`,Wz),Hz.add(`ADD_COLUMNS_ROWS`,Fz),Hz.add(`REMOVE_COLUMNS_ROWS`,Iz),Hz.add(`HIDE_COLUMNS_ROWS`,Iz),Hz.add(`RESIZE_COLUMNS_ROWS`,Iz),Hz.add(`CREATE_SHEET`,Pz),Hz.add(`CREATE_FIGURE`,Nz),Hz.add(`CREATE_CHART`,jz),Hz.add(`CREATE_IMAGE`,Mz),Hz.add(`GROUP_HEADERS`,Vz),Hz.add(`UNGROUP_HEADERS`,Vz),Hz.add(`UNGROUP_HEADERS`,Vz),Hz.add(`UNFOLD_HEADER_GROUPS_IN_ZONE`,Dz),Hz.add(`FOLD_HEADER_GROUPS_IN_ZONE`,Dz);let Uz=new h;Uz.add(`PASTE`,Bz),Uz.add(`INSERT_CELL`,Lz),Uz.add(`DELETE_CELL`,Lz),Uz.add(`AUTORESIZE_COLUMNS`,Rz),Uz.add(`AUTORESIZE_ROWS`,Rz),Uz.add(`SORT_CELLS`,zz),Uz.add(`SUM_SELECTION`,Wz),Uz.add(`SET_DECIMAL`,Wz);function Wz(e,t){let n=y(t);for(let t of wz)n=t(e,n);return n}function Gz(e,t){if(t&&Hz.contains(t.type))return Hz.get(t.type)(e,t)}function Kz(e,t,n){if(Uz.contains(t.type))return Uz.get(t.type)(e,t,n)}function qz(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:Gi(e.rootCommand)?Hz.contains(e.rootCommand.type):Uz.contains(e.rootCommand.type)}function Jz(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return Gi(e.rootCommand)?Gz(t,e.rootCommand):Kz(t,e.rootCommand,e.commands)}var Yz=class extends ${static getters=[`canUndo`,`canRedo`];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on(`new-local-state-update`,this,this.onNewLocalStateUpdate),this.session.on(`snapshot`,this,()=>{this.undoStack=[],this.redoStack=[]})}allowDispatch(e){switch(e.type){case`REQUEST_UNDO`:if(!this.canUndo())return`EmptyUndoStack`;break;case`REQUEST_REDO`:if(!this.canRedo())return`EmptyRedoStack`;break}return`Success`}handle(e){switch(e.type){case`REQUEST_UNDO`:case`REQUEST_REDO`:this.requestHistoryChange(e.type===`REQUEST_UNDO`?`UNDO`:`REDO`)}}finalize(){}requestHistoryChange(e){let t=e===`UNDO`?this.undoStack.pop():this.redoStack.pop();if(!t){let e=this.getPossibleRevisionToRepeat();if(!e)return;let t=Jz(e,this.getters);if(!t)return;if(!Array.isArray(t)){this.dispatch(t.type,t);return}for(let e of t)this.dispatch(e.type,e);return}e===`UNDO`?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0?!0:qz(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},Xz=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,I(e.value)])}isValuePresent(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(n)}isHeaderPresent(e){let t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(n)}trackHeader(e){let t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}},Zz=class extends ${static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new Xz,this.trackPresencePivotId=e.pivotId;break;case`PIVOT_STOP_PRESENCE_TRACKING`:this.trackPresencePivotId=void 0;break}}getPivotPresenceTracker(e){if(this.trackPresencePivotId===e){if(!this.tracker)throw Error(`Tracker not initialized`);return this.tracker}}},Qz=class extends ${static getters=[`getAutomaticSeparator`];allowDispatch(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:return this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e)}return`Success`}handle(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:this.splitIntoColumns(e);break}}getAutomaticSeparator(){let e=this.getters.getSelectedCells();for(let t of e)if(t.value&&t.type===`text`){let e=this.getAutoSeparatorForString(t.value);if(e)return e}return` `}getAutoSeparatorForString(e){for(let t of[`
1893
+ `,`;`,`,`,` `,`.`])if(e.includes(t))return t}splitIntoColumns({separator:e,addNewColumns:t}){let n=this.getters.getSelectedZone(),r=this.getters.getActiveSheetId(),i=this.getSplittedCols(n,e);t&&this.addColsToAvoidCollisions(n,i),this.removeMergesInSplitZone(n,i),this.addColumnsToNotOverflowSheet(n,i);for(let e=0;e<i.length;e++){let t=n.top+e,a=i[e],o=n.left,s=this.getters.getCell({sheetId:r,col:o,row:t});if(!(a.length===1&&a[0]===s?.content))for(let[e,n]of a.entries())this.dispatch(`UPDATE_CELL`,{sheetId:r,col:o+e,row:t,content:tl(n,this.getters.getLocale()),format:``,style:s?.style||null})}}getSplittedCols(e,t){if(!t)throw Error(`Separator cannot be empty`);let n=this.getters.getActiveSheetId(),r=[];for(let i of x(e.top,e.bottom+1)){let a=this.getters.getEvaluatedCell({sheetId:n,col:e.left,row:i}).formattedValue;r.push(this.splitAndRemoveTrailingEmpty(a,t))}return r}splitAndRemoveTrailingEmpty(e,t){let n=e.split(t);for(;n.length>1&&n[n.length-1]===``;)n.pop();return n}willSplittedColsOverwriteContent(e,t){let n=this.getters.getActiveSheetId();for(let r of x(e.top,e.bottom+1)){let i=t[r-e.top];for(let t=1;t<i.length;t++){let i=this.getters.getCell({sheetId:n,col:e.left+t,row:r});if(i&&i.content)return!0}}return!1}removeMergesInSplitZone(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length)),i={...e,right:e.left+r-1},a=this.getters.getMergesInZone(n,i);this.dispatch(`REMOVE_MERGE`,{sheetId:n,target:a})}addColsToAvoidCollisions(e,t){let n=this.getters.getActiveSheetId(),r=0;for(let i of x(e.top,e.bottom+1)){let a={sheetId:n,col:e.left,row:i},o=t[i-e.top],s=this.getColsToAddToAvoidCollision(a,o);r=Math.max(r,s)}r&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:e.left,sheetId:n,quantity:r,position:`after`})}getColsToAddToAvoidCollision(e,t){let n=t.length;for(let t=1;t<n;t++){let r=e.col+t,i=this.getters.getCell({...e,col:r});if(i&&i.content)return n-t}return 0}addColumnsToNotOverflowSheet(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length-1)),i=this.getters.getNumberCols(n)-1;e.left+r>i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:i,sheetId:n,quantity:e.left+r-i,position:`after`})}checkSingleColSelected(){return this.getters.isSingleColSelected()?`Success`:`MoreThanOneColumnSelected`}checkNonEmptySelector(e){return e.separator===``?`EmptySplitSeparator`:`Success`}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return`Success`;let t=this.getters.getSelectedZones()[0],n=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,n)?`SplitWillOverwriteContent`:`Success`}checkSeparatorInSelection({separator:e}){let t=this.getters.getSelectedCells();for(let n of t)if(n.formattedValue.includes(e))return`Success`;return`NoSplitSeparatorInSelection`}},$z=class extends ${handle(e){switch(e.type){case`AUTOFILL_TABLE_COLUMN`:let t=this.getters.getCoreTable(e),n=this.getters.getCell(e);if(!t?.config.automaticAutofill||t.type===`dynamic`||!n?.isFormula)return;let{col:r,row:i}=e,a=GF(t.range.zone,t.config);if(a&&dr(r,i,a)){let t=e.autofillRowStart??a.top,n=e.autofillRowEnd??a.bottom,r={...a,top:t,bottom:n};this.autofillTableZone(e,r)}break}}autofillTableZone(e,t){if(t.top===t.bottom)return;let{col:n,row:r,sheetId:i}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==r&&this.getters.getEvaluatedCell({col:n,row:e,sheetId:i}).type!==`empty`)return;let a={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.bottom}),this.dispatch(`AUTOFILL`),this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.top}),this.dispatch(`AUTOFILL`),this.selection.selectZone(a)}},eB=class extends ${allowDispatch(e){switch(e.type){case`RESIZE_TABLE`:let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return`TableNotFound`;let n=t.range.zone,r=this.getters.getRangeFromRangeData(e.newTableRange).zone;return r.top!==n.top||r.left!==n.left?`InvalidTableResize`:this.canDispatch(`UPDATE_TABLE`,{...e}).reasons}return`Success`}handle(e){switch(e.type){case`RESIZE_TABLE`:{let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch(`UPDATE_TABLE`,{...e}),!t||!t.config.automaticAutofill)return;let n=t.range.zone,r=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(r.bottom>=n.bottom){for(let t=r.left;t<=r.right;t++){let i={col:t,row:n.bottom,sheetId:e.sheetId};this.getters.getCell(i)?.content.startsWith(`=`)&&this.dispatch(`AUTOFILL_TABLE_COLUMN`,{...i,autofillRowStart:n.bottom,autofillRowEnd:r.bottom})}break}}}}},tB=class extends ${static layers=[`Clipboard`];static getters=[`getClipboardContent`,`getClipboardId`,`getClipboardTextContent`,`isCutOperation`];status=`invisible`;originSheetId;copiedData;_isCutOperation=!1;clipboardId=new wc().uuidv4();allowDispatch(e){switch(e.type){case`CUT`:let t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case`PASTE_FROM_OS_CLIPBOARD`:{let t=this.convertTextToClipboardData(e.clipboardContent.text??``),n=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:n,isCutOperation:!1})}case`PASTE`:{if(!this.copiedData)return`EmptyClipboard`;let t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].top===0&&e[0].bottom===0)return`InvalidCopyPasteSelection`;break}case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].left===0&&e[0].right===0)return`InvalidCopyPasteSelection`;break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}}return`Success`}handle(e){switch(e.type){case`COPY`:case`CUT`:let t=this.getters.getSelectedZones();this.status=`visible`,this.originSheetId=this.getters.getActiveSheetId(),this.copiedData=this.copy(t),this._isCutOperation=e.type===`CUT`;break;case`PASTE_FROM_OS_CLIPBOARD`:{this._isCutOperation=!1;let t=e.clipboardContent;t.data?.version!==22&&(t={...t},delete t.data),this.copiedData=t.data||this.convertTextToClipboardData(t.text??``);let n=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:n,selectTarget:!0,isCutOperation:!1}),this.status=`invisible`;break}case`PASTE`:{let t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status=`invisible`,this._isCutOperation&&=(this.copiedData=void 0,!1);break}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZone(),t=e.top!==e.bottom,n={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};this.originSheetId=this.getters.getActiveSheetId();let r=this.copy([n]);this.paste([e],r,{isCutOperation:!1,selectTarget:!0})}break;case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZone(),t=e.left!==e.right,n={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};this.originSheetId=this.getters.getActiveSheetId();let r=this.copy([n]);this.paste([e],r,{isCutOperation:!1,selectTarget:!0})}break;case`CLEAN_CLIPBOARD_HIGHLIGHT`:this.status=`invisible`;break;case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!$n(t[0])){this.dispatch(`CLEAR_CELLS`,{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}let r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`ADD_COLUMNS_ROWS`:if(this.status=`invisible`,this._isCutOperation!==!0||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard(e.position===`before`?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case`REMOVE_COLUMNS_ROWS`:if(this.status=`invisible`,this._isCutOperation!==!0||e.sheetId!==this.copiedData?.sheetId)return;for(let t of e.elements)if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}this.status=`invisible`;break;case`REPEAT_PASTE`:this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case`DELETE_SHEET`:if(this._isCutOperation!==!0)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status=`invisible`);break;default:Gi(e)&&(this.status=`invisible`)}}convertTextToClipboardData(e){let t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({})),n={};for(let{handlerName:r,handler:i}of t){let t=i.convertTextToClipboardData(e);n[r]=t;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])t&&e in t&&(n[e]=t[e])}return n}selectClipboardHandlers(e){let t=`figureId`in e?ed.figureHandlers:ed.cellHandlers;return t.getKeys().map(e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)}))}isCutAllowedOn(e){let t=this.getClipboardData(e);for(let{handler:e}of this.selectClipboardHandlers(t)){let n=e.isCutAllowed(t);if(n!==`Success`)return n}return`Success`}isPasteAllowed(e,t,n){for(let{handler:r}of this.selectClipboardHandlers(t)){let i=r.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...n});if(i!==`Success`)return i}return`Success`}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;let{zones:n}=this.copiedData;for(let r of n)if(t===`COL`&&e<=r.right||t===`ROW`&&e<=r.bottom)return!0;return!1}copy(e,t=`copyPaste`){let n={},r=this.getClipboardData(e);for(let{handlerName:e,handler:i}of this.selectClipboardHandlers(r)){let a=i.copy(r,t);n[e]=a;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])a&&e in a&&(n[e]=a[e])}return n}paste(e,t,n){if(!t)return;let r=this.getters.getActiveSheetId(),i=this.selectClipboardHandlers(t),{target:a,zone:o,selectedZones:s}=jc(r,e,t,i,n);o!==void 0&&this.addMissingDimensions(r,o.right-o.left+1,o.bottom-o.top+1,o.left,o.top),Ac(i,t,a,n),n?.selectTarget&&Mc(this.selection,e,s)}addMissingDimensions(e,t,n,r,i){let a=n+i-this.getters.getNumberRows(e);a>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:this.getters.getNumberRows(e)-1,sheetId:e,quantity:a,position:`after`});let o=t+r-this.getters.getNumberCols(e);o>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:this.getters.getNumberCols(e)-1,sheetId:e,quantity:o,position:`after`})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}getClipboardContent(){return{"text/plain":this.getPlainTextContent(),"text/html":this.getHTMLContent()}}getSheetData(){let e={version:22,clipboardId:this.clipboardId};return this.copiedData&&`figureId`in this.copiedData?e:{...e,...this.copiedData}}getPlainTextContent(){return this.copiedData?.cells&&this.copiedData.cells.map(e=>e.map(e=>this.getters.shouldShowFormulas()&&e?.tokens?.length?e?.content||``:e.evaluatedCell?.formattedValue||``).join(` `)).join(`
1894
+ `)||` `}getHTMLContent(){let e=``,t=this.copiedData?.cells;if(!t)e=` `;else if(t.length===1&&t[0].length===1)e=`${this.getters.getCellText(t[0][0].position)}`;else if(t[0][0]){let n=`<table border="1" style="border-collapse:collapse">`;for(let e of t){n+=`<tr>`;for(let t of e){if(!t)continue;let e=U(bf(this.getters.getCellComputedStyle(t.position))),r=this.getters.getCellText(t.position);n+=`<td style="${e}">`+eh(r)+`</td>`}n+=`</tr>`}n+=`</table>`,e=n}else return``;return`<div data-osheet-clipboard='${eh(JSON.stringify(this.getSheetData()))}'>${e}</div>`}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r;return r=t===`COL`?{...e,left:e.right+1,right:this.getters.getNumberCols(n)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1},{cut:[r],paste:[e]}}getInsertCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r,i;return t===`COL`?(r={...e,right:this.getters.getNumberCols(n)-1},i={...e,left:e.right+1,right:e.right+1}):(r={...e,bottom:this.getters.getNumberRows(n)-1},i={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1}),{cut:[r],paste:[i]}}getClipboardData(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedFigureId();return n?{figureId:n,sheetId:t}:Tc(t,e)}drawLayer(e){if(this.status!==`visible`||!this.copiedData)return;let{sheetId:t,zones:n}=this.copiedData;if(t!==this.getters.getActiveSheetId()||!n||!n.length)return;let{ctx:r,thinLineWidth:i}=e;r.setLineDash([8,5]),r.strokeStyle=ae,r.lineWidth=3.3*i;for(let e of n){let{x:t,y:n,width:i,height:a}=this.getters.getVisibleRect(e);i>0&&a>0&&r.strokeRect(t,n,i,a)}}},nB=class extends ${static getters=[`getFilterHiddenValues`,`getFirstTableInSelection`,`isRowFiltered`,`isFilterActive`];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){switch(e.type){case`UPDATE_FILTER`:if(!this.getters.getFilterId(e))return`FilterNotFound`;break}return`Success`}handle(e){switch(e.type){case`UNDO`:case`REDO`:case`UPDATE_CELL`:case`EVALUATE_CELLS`:case`ACTIVATE_SHEET`:case`REMOVE_TABLE`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`UPDATE_TABLE`:this.isEvaluationDirty=!0;break;case`START`:for(let e of this.getters.getSheetIds())this.filterValues[e]={};break;case`CREATE_SHEET`:this.filterValues[e.sheetId]={};break;case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`GROUP_HEADERS`:case`UNGROUP_HEADERS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_ALL_HEADER_GROUPS`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:this.updateHiddenRows(e.sheetId);break;case`UPDATE_FILTER`:this.updateFilter(e),this.updateHiddenRows(e.sheetId);break;case`DUPLICATE_SHEET`:this.filterValues[e.sheetIdTo]=y(this.filterValues[e.sheetId]);break}}finalize(){if(this.isEvaluationDirty){for(let e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterHiddenValues(e){let t=this.getters.getFilterId(e),n=e.sheetId;return!t||!this.filterValues[n]?[]:this.filterValues[n][t]||[]}isFilterActive(e){let t=this.getters.getFilterId(e),n=e.sheetId;return!!(t&&this.filterValues[n]?.[t]?.length)}getFirstTableInSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,hiddenValues:n,sheetId:r}){let i=this.getters.getFilterId({sheetId:r,col:e,row:t});i&&(this.filterValues[r]||(this.filterValues[r]={}),this.filterValues[r][i]=n)}updateHiddenRows(e){let t=this.getters.getFilters(e).sort((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top),n=new Set;for(let r of t){if(n.has(r.rangeWithHeaders.zone.top)||this.getters.isRowHiddenByUser(e,r.rangeWithHeaders.zone.top))continue;let t=this.filterValues[e]?.[r.id]?.map(yc),i=r.filteredRange?.zone;if(!t||!i)continue;let a=new Set(t);for(let t=i.top;t<=i.bottom;t++){let i=this.getCellValueAsString(e,r.col,t);a.has(i)&&n.add(t)}}this.hiddenRows[e]=n}getCellValueAsString(e,t,n){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).formattedValue.toLowerCase()}exportForExcel(e){for(let t of e.sheets){let e=t.id;for(let n of t.tables){let r=Qn(n.range),i=[],a=[];for(let n of x(0,pr(r).numberOfCols)){let o={sheetId:t.id,col:r.left+n,row:r.top},s=this.getFilterHiddenValues(o),c=this.getters.getFilter(o),l=c?.filteredRange?_r(c.filteredRange.zone).map(t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue):[];if(s.length){let e=l.filter(e=>e).filter(e=>!s.includes(e));i.push({colId:n,displayedValues:[...new Set(e)],displayBlanks:!s.includes(``)&&l.some(e=>!e)})}let u=this.getters.getEvaluatedCell(o).formattedValue,d=this.getUniqueColNameForExcel(n,u,a);a.push(d),t.cells[w(o.col,o.row)]={...t.cells[w(o.col,o.row)],content:d,value:d,isFormula:!1}}n.filters=i}}}getUniqueColNameForExcel(e,t,n){t||=`Column${e}`;let r=t,i=2;for(;n.includes(r);)r=t+String(i),i++;return r}},rB=class extends ${static layers=[`Selection`];static getters=[`getActiveSheet`,`getActiveSheetId`,`getActiveCell`,`getActiveCols`,`getActiveRows`,`getCurrentStyle`,`getSelectedZones`,`getSelectedZone`,`getSelectedCells`,`getSelectedFigureId`,`getSelection`,`getActivePosition`,`getSheetPosition`,`isSingleColSelected`,`getElementsFromSelection`,`tryGetActiveSheetId`,`isGridSelectionActive`];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;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient}allowDispatch(e){switch(e.type){case`ACTIVATE_SHEET`:try{if(!this.getters.getSheet(e.sheetIdTo).isVisible)return`SheetIsHidden`;break}catch{return`InvalidSheetId`}case`MOVE_COLUMNS_ROWS`:return this.isMoveElementAllowed(e)}return`Success`}handleEvent(e){let t=e.anchor,n=[];switch(e.mode){case`overrideSelection`:n=[t.zone];break;case`updateAnchor`:n=[...this.gridSelection.zones];let r=n.findIndex(t=>lr(t,e.previousAnchor.zone));r>=0&&(n[r]=t.zone);break;case`newAnchor`:n=[...this.gridSelection.zones,t.zone];break}this.setSelectionMixin(e.anchor,n),this.selection.resetDefaultAnchor(this,y(this.gridSelection.anchor));let{col:r,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:r,row:i}),this.selectedFigureId=null}handle(e){switch(e.type){case`ACTIVATE_SHEET`:this.selectedFigureId=null;break;case`DELETE_FIGURE`:this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;case`DELETE_SHEET`:this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null);break}switch(e.type){case`START`:let t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);let{col:n,row:r}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(n,r),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case`ACTIVATE_SHEET`:this.activateSheet(e.sheetIdFrom,e.sheetIdTo);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){e.dimension===`COL`?this.onColumnsRemoved(e):this.onRowsRemoved(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`ADD_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`MOVE_COLUMNS_ROWS`:e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case`SELECT_FIGURE`:this.selectedFigureId=e.id;break;case`ACTIVATE_NEXT_SHEET`:this.activateNextSheet(`right`);break;case`ACTIVATE_PREVIOUS_SHEET`:this.activateNextSheet(`left`);break;case`HIDE_SHEET`:e.sheetId===this.getActiveSheetId()&&this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case`UNDO`:case`REDO`:case`DELETE_SHEET`:let i=Object.keys(this.sheetsData).filter(e=>!this.getters.tryGetSheet(e));for(let e of i)delete this.sheetsData[e];for(let e in this.sheetsData){let t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:y(t)}}this.fallbackToVisibleSheet();let a=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map(e=>this.getters.expandZone(a,e)),this.gridSelection.anchor.zone=this.getters.expandZone(a,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null;break}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,y(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){let e=new Set;for(let t of this.gridSelection.zones)if(t.top===0&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let n=t.left;n<=t.right;n++)e.add(n);return e}getActiveRows(){let e=new Set,t=this.getters.getActiveSheetId();for(let n of this.gridSelection.zones)if(n.left===0&&n.right===this.getters.getNumberCols(t)-1)for(let t=n.top;t<=n.bottom;t++)e.add(t);return e}getCurrentStyle(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return y(this.gridSelection.zones)}getSelectedZone(){return y(this.gridSelection.anchor.zone)}getSelection(){return y(this.gridSelection)}getSelectedCells(){let e=this.getters.getActiveSheetId(),t=[];for(let n of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,n));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{let t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}isSingleColSelected(){let e=this.getters.getSelectedZones();return!(e.length!==1||e[0].left!==e[0].right)}getElementsFromSelection(e){if(e===`COL`&&this.getters.getActiveCols().size===0||e===`ROW`&&this.getters.getActiveRows().size===0)return[];let t=this.getters.getSelectedZones(),n=[],r=e===`COL`?`left`:`top`,i=e===`COL`?`right`:`bottom`;for(let e of t){let t=Array.from({length:e[i]-e[r]+1},(t,n)=>e[r]+n);n=n.concat(t)}return[...new Set(n)].sort()}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:y(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,y(this.gridSelection.anchor));else{let{col:e,row:n}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,n)}let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:n,row:r})}setSelectionMixin(e,t){let{anchor:n,zones:r}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=n,this.gridSelection.zones=br(r)}selectCell(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.expandZone(n,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:r,cell:{col:e,row:t}},[r])}setActiveSheet(e){let t=this.getters.getSheet(e);this.activeSheet=t}activateNextSheet(e){let t=this.getters.getSheetIds(),n=(t.findIndex(e=>e===this.activeSheet.id)+(e===`left`?t.length-1:1))%t.length;this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[n]})}onColumnsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=ir(n,`left`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=ir(i,`left`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>ir(t,`left`,[...e.elements]));this.setSelectionMixin(a,o)}onRowsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=ir(n,`top`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=ir(i,`top`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>ir(t,`top`,[...e.elements]));this.setSelectionMixin(a,o)}onAddElements(e){let t=e.dimension===`COL`?`left`:`top`,n=rr(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),r=this.gridSelection.zones.map(n=>rr(n,t,e.base,e.position,e.quantity)),i={cell:{col:n.left,row:n.top},zone:n};this.setSelectionMixin(i,r)}onMoveElements(e){let t=e.elements.length;this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:e.position});let n=e.dimension===`COL`,r=e.elements[0],i=e.elements[t-1],a=e.base<r,o=a&&n?t:0,s=a&&!n?t:0,c=a?e.elements.map(e=>e+t):e.elements,l=Object.fromEntries(c.map(t=>{let r=n?this.getters.getColSize(e.sheetId,t):this.getters.getUserRowSize(e.sheetId,t);return[t,n&&r===96||r===void 0?null:r]})),u=[{left:n?r+o:0,right:n?i+o:this.getters.getNumberCols(e.sheetId)-1,top:n?0:r+s,bottom:n?this.getters.getNumberRows(e.sheetId)-1:i+s}],d=this.getActiveSheetId(),f=a?e.base:e.base+1,p=[{left:n?f:0,right:n?f+t-1:this.getters.getNumberCols(e.sheetId)-1,top:n?0:f,bottom:n?this.getters.getNumberRows(e.sheetId)-1:f+t-1}];for(let e of ed.cellHandlers.getAll()){let t=new e(this.getters,this.dispatch),n=t.copy(Tc(d,u),`shiftCells`);n&&t.paste({zones:p,sheetId:d},n,{isCutOperation:!0})}let m=p[0],h=m.left,g=m.top;this.setSelectionMixin({zone:m,cell:{col:h,row:g}},[m]);let _=a?e.base:e.base+1;for(let t of c)this.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,size:l[t],elements:[_]}),_+=1;this.dispatch(`REMOVE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,elements:c})}isMoveElementAllowed(e){let t=e.dimension===`COL`,n=e.elements[0],r=e.elements[e.elements.length-1],i=e.sheetId,a=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(a(i,n-1,n)||a(i,r,r+1)||a(i,e.base-1,e.base))return`WillRemoveExistingMerge`;let o=[e.base,...e.elements],s=t?this.getters.getNumberCols(i):this.getters.getNumberRows(i);return o.some(e=>e<0||e>=s)?`InvalidHeaderIndex`:!t&&!this.isTableRowMoveAllowed(i,e.elements)?`CannotMoveTableHeader`:`Success`}isTableRowMoveAllowed(e,t){let n=this.getters.getCoreTables(e);if(n.length===0)return!0;let r=new Set(t);return n.every(({range:{zone:e},config:n})=>{let{top:i,bottom:a}=e;if(n.numberOfHeaders===0)return!0;let o=i+n.numberOfHeaders-1;return t.some(e=>e>=i&&e<=o)?x(i,a+1).every(e=>r.has(e)):!0})}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){let e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){let{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);let{col:t,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:n})}}clipSelection(e,t){let n=this.getters.getNumberCols(e)-1,r=this.getters.getNumberRows(e)-1,i=t.zones.map(e=>({left:b(e.left,0,n),right:b(e.right,0,n),top:b(e.top,0,r),bottom:b(e.bottom,0,r)})),a=b(t.anchor.cell.col,0,n),o=b(t.anchor.cell.row,0,r),s={left:b(t.anchor.zone.left,0,n),right:b(t.anchor.zone.right,0,n),top:b(t.anchor.zone.top,0,r),bottom:b(t.anchor.zone.bottom,0,r)};return{zones:i,anchor:{cell:{col:a,row:o},zone:s}}}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getSelectedZones();t.fillStyle=`#f3f7fe`,t.fillStyle=r.length===1&&r[0].left===r[0].right&&r[0].top===r[0].bottom?`#f3f7fe`:`#e9f0ff`,t.strokeStyle=ae,t.lineWidth=1.5*n;for(let e of r){let{x:n,y:r,width:i,height:a}=this.getters.getVisibleRect(e);t.globalCompositeOperation=`multiply`,t.fillRect(n,r,i,a),t.globalCompositeOperation=`source-over`,t.strokeRect(n,r,i,a)}t.globalCompositeOperation=`source-over`;let i=this.getActivePosition();t.strokeStyle=ae,t.lineWidth=3*n;let a;a=this.getters.isInMerge(i)?this.getters.getMerge(i):D(i);let{x:o,y:s,width:c,height:l}=this.getters.getVisibleRect(a);c>0&&l>0&&t.strokeRect(o,s,c,l)}},iB=class{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;offsetScrollbarX;offsetScrollbarY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,n,r,i,a){if(this.getters=e,this.sheetId=t,this.boundaries=n,r.width<0||r.height<0)throw Error(`Viewport size cannot be negative`);this.viewportWidth=r.height&&r.width,this.viewportHeight=r.width&&r.height,this.top=n.top,this.bottom=n.bottom,this.left=n.left,this.right=n.right,this.offsetX=a.x,this.offsetY=a.y,this.offsetScrollbarX=a.x,this.offsetScrollbarY=a.y,this.canScrollVertically=i.canScrollVertically,this.canScrollHorizontally=i.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){let e=this.getters.findLastVisibleColRowIndex(this.sheetId,`COL`,{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,`ROW`,{first:this.boundaries.top,last:this.boundaries.bottom}),{end:n,size:r}=this.getters.getColDimensions(this.sheetId,e),{end:i,size:a}=this.getters.getRowDimensions(this.sheetId,t),o=this.searchHeaderIndex(`COL`,n-this.viewportWidth,0),s=this.getters.getColSize(this.sheetId,o),c=this.searchHeaderIndex(`ROW`,i-this.viewportHeight,0),l=this.getters.getRowSize(this.sheetId,c),u=n-this.offsetCorrectionX;this.canScrollHorizontally&&(u+=Math.max(96,Math.min(s,this.viewportWidth-r)),u=Math.max(u,this.viewportWidth));let d=i-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(28,Math.min(l,this.viewportHeight-a)),d=Math.max(d,this.viewportHeight),i+46>d&&!this.getters.isReadonly()&&(d+=46)),{width:u,height:d}}getColIndex(e){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex(`COL`,e-this.offsetCorrectionX,this.left)}getRowIndex(e){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex(`ROW`,e-this.offsetCorrectionY,this.top)}adjustPosition(e){let t=this.sheetId,n=this.getters.getMainCellPosition({sheetId:t,...e}),{col:r,row:i}=this.getters.getNextVisibleCellPosition(n);dr(r,this.boundaries.top,this.boundaries)&&this.adjustPositionX(r),dr(this.boundaries.left,i,this.boundaries)&&this.adjustPositionY(i)}adjustPositionX(e){let t=this.sheetId,{end:n}=this.getters.getColDimensions(t,e);if(this.offsetX+this.offsetCorrectionX+this.viewportWidth<n){let n=this.getters.getNumberCols(t),r=e;for(;this.getters.isColHidden(t,r)&&r<n;)r++;let i=this.getters.getColDimensions(t,r).end,a=this.searchHeaderIndex(`COL`,i-this.viewportWidth-this.offsetCorrectionX,this.boundaries.left);this.offsetScrollbarX=this.getters.getColDimensions(t,a).end-this.offsetCorrectionX}else if(this.left>e){let n=e;for(;this.getters.isColHidden(t,n)&&n>0;)n--;this.offsetScrollbarX=this.getters.getColDimensions(t,n).start-this.offsetCorrectionX}this.adjustViewportZoneX()}adjustPositionY(e){let t=this.sheetId,{end:n}=this.getters.getRowDimensions(t,e);if(this.offsetY+this.viewportHeight+this.offsetCorrectionY<n){let n=this.getters.getNumberRows(t),r=e;for(;this.getters.isRowHidden(t,r)&&r<n;)r++;let i=this.getters.getRowDimensions(t,r).end,a=this.searchHeaderIndex(`ROW`,i-this.viewportHeight-this.offsetCorrectionY,this.boundaries.top);this.offsetScrollbarY=this.getters.getRowDimensions(t,a).end-this.offsetCorrectionY}else if(this.top>e){let n=e;for(;this.getters.isRowHidden(t,n)&&n>0;)n--;this.offsetScrollbarY=this.getters.getRowDimensions(t,n).start-this.offsetCorrectionY}this.adjustViewportZoneY()}willNewOffsetScrollViewport(e,t){return this.canScrollHorizontally&&this.offsetScrollbarX!==e||this.canScrollVertically&&this.offsetScrollbarY!==t}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getVisibleRect(e){let t=cr(e,this);if(t)return{x:this.getters.getColRowOffset(`COL`,this.left,t.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset(`ROW`,this.top,t.top)+this.offsetCorrectionY,width:Math.min(this.getters.getColRowOffset(`COL`,t.left,t.right+1),this.viewportWidth),height:Math.min(this.getters.getColRowOffset(`ROW`,t.top,t.bottom+1),this.viewportHeight)}}getFullRect(e){if(cr(e,this))return{x:this.getters.getColRowOffset(`COL`,this.left,e.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset(`ROW`,this.top,e.top)+this.offsetCorrectionY,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,n=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;let r=this.sheetId,i=this.getters.getNumberHeaders(r,e),a=n,o=i;for(;a<=o&&a!==i&&o!==-1;){let i=Math.floor((a+o)/2),s=this.getters.getColRowOffset(e,n,i),c=this.getters.getHeaderSize(r,e,i);if(t>=s&&t<s+c)return i;t>=s+c?a=i+1:o=i-1}return-1}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetScrollbarX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetScrollbarY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){let{width:e}=this.getMaxSize();this.viewportWidth+this.offsetScrollbarX>e&&(this.offsetScrollbarX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){let{height:e}=this.getMaxSize();this.viewportHeight+this.offsetScrollbarY>e&&(this.offsetScrollbarY=Math.max(0,e-this.viewportHeight))}this.adjustViewportZoneY()}adjustViewportZoneX(){let e=this.sheetId;this.left=this.searchHeaderIndex(`COL`,this.offsetScrollbarX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex(`COL`,this.viewportWidth,this.left)),this.viewportWidth&&(this.left===-1&&(this.left=this.boundaries.left),this.right===-1&&(this.right=this.boundaries.right),this.offsetX=this.getters.getColDimensions(e,this.left).start-this.getters.getColDimensions(e,this.boundaries.left).start)}adjustViewportZoneY(){let e=this.sheetId;this.top=this.searchHeaderIndex(`ROW`,this.offsetScrollbarY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex(`ROW`,this.viewportHeight,this.top)),this.viewportHeight&&(this.top===-1&&(this.top=this.boundaries.top),this.bottom===-1&&(this.bottom=this.boundaries.bottom),this.offsetY=this.getters.getRowDimensions(e,this.top).start-this.getters.getRowDimensions(e,this.boundaries.top).start)}},aB=class extends ${static getters=[`getColIndex`,`getRowIndex`,`getActiveMainViewport`,`getSheetViewDimension`,`getSheetViewDimensionWithHeaders`,`getMainViewportRect`,`isVisibleInViewport`,`getEdgeScrollCol`,`getEdgeScrollRow`,`getVisibleFigures`,`getVisibleRect`,`getVisibleRectWithoutHeaders`,`getVisibleCellPositions`,`getColRowOffsetInViewport`,`getMainViewportCoordinates`,`getActiveSheetScrollInfo`,`getActiveSheetDOMScrollInfo`,`getSheetViewVisibleCols`,`getSheetViewVisibleRows`,`getFrozenSheetViewRatio`,`isPositionVisible`,`getColDimensionsInViewport`,`getRowDimensionsInViewport`,`getAllActiveViewportsZonesAndRect`,`getRect`];viewports={};sheetViewWidth=Je();sheetViewHeight=Je();gridOffsetX=0;gridOffsetY=0;sheetsWithDirtyViewports=new Set;shouldAdjustViewports=!1;allowDispatch(e){switch(e.type){case`SET_VIEWPORT_OFFSET`:return this.chainValidations(this.checkScrollingDirection,this.checkIfViewportsWillChange)(e);case`RESIZE_SHEETVIEW`:return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return`Success`}}handleEvent(e){let t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let{col:n,row:r}=Sr(e.previousAnchor.zone,e.anchor.zone);if(e.mode===`updateAnchor`){let i=e.previousAnchor.zone,a=e.anchor.zone,{top:o,bottom:s,left:c,right:l}=this.getMainInternalViewport(t);i.left===a.left&&i.right===a.right&&(n=c>n||n>l?c:n),i.top===a.top&&i.bottom===a.bottom&&(r=o>r||r>s?o:r)}n=Math.min(n,this.getters.getNumberCols(t)-1),r=Math.min(r,this.getters.getNumberRows(t)-1),this.sheetsWithDirtyViewports.has(t)||this.refreshViewport(this.getters.getActiveSheetId(),{col:n,row:r})}}handle(e){if(Ri.has(e.type))for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);switch(e.type){case`START`:this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case`UNDO`:case`REDO`:this.cleanViewports();for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);this.shouldAdjustViewports=!0;break;case`RESIZE_SHEETVIEW`:this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case`SET_VIEWPORT_OFFSET`:this.setSheetViewOffset(e.offsetX,e.offsetY);break;case`SHIFT_VIEWPORT_DOWN`:let t=this.getters.getActiveSheetId(),{top:n,viewportHeight:r,offsetCorrectionY:i}=this.getMainInternalViewport(t),a=this.getters.getRowDimensions(t,n);this.shiftVertically(a.start+r-i);break;case`SHIFT_VIEWPORT_UP`:{let e=this.getters.getActiveSheetId(),{top:t,viewportHeight:n,offsetCorrectionY:r}=this.getMainInternalViewport(e),i=this.getters.getRowDimensions(e,t);this.shiftVertically(i.end-r-n);break}case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`UPDATE_FILTER`:case`UNFREEZE_ROWS`:case`UNFREEZE_COLUMNS`:case`FREEZE_COLUMNS`:case`FREEZE_ROWS`:case`UNFREEZE_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`RESIZE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`UNGROUP_HEADERS`:case`GROUP_HEADERS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_ALL_HEADER_GROUPS`:this.sheetsWithDirtyViewports.add(e.sheetId);break;case`UPDATE_CELL`:for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);break;case`DELETE_SHEET`:this.cleanViewports(),this.sheetsWithDirtyViewports.delete(e.sheetId);break;case`ACTIVATE_SHEET`:this.sheetsWithDirtyViewports.add(e.sheetIdTo);break;case`DELETE_SHEET`:this.sheetsWithDirtyViewports.delete(e.sheetId);break;case`SCROLL_TO_CELL`:this.refreshViewport(this.getters.getActiveSheetId(),{col:e.col,row:e.row});break}}finalize(){for(let e of this.sheetsWithDirtyViewports)if(this.resetViewports(e),this.shouldAdjustViewports){let t=this.getters.getSheetPosition(e);this.getSubViewports(e).forEach(e=>{e.adjustPosition(t)})}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){let e=this.getters.getSheetIds();for(let t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getColIndex(e)))}getRowIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getRowIndex(e)))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getActiveMainViewport(){let e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getActiveSheetDOMScrollInfo(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetScrollbarX,scrollY:t.offsetScrollbarY}}getSheetViewVisibleCols(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>x(e.left,e.right+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`COL`,t))}getSheetViewVisibleRows(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>x(e.top,e.bottom+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`ROW`,t))}getVisibleCellPositions(){let e=this.getSheetViewVisibleCols(),t=this.getSheetViewVisibleRows(),n=this.getters.getActiveSheetId(),r=[];for(let i of e)for(let e of t){let t={sheetId:n,col:i,row:e},a=this.getters.getMainCellPosition(t);a.row!==e||a.col!==i||r.push(t)}return r}getMainViewportRect(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e),{width:i,height:a}=t.getMaxSize();return{x:this.getters.getColDimensions(e,n).start,y:this.getters.getRowDimensions(e,r).start,width:i,height:a}}getMaximumSheetOffset(){let e=this.getters.getActiveSheetId(),{width:t,height:n}=this.getMainViewportRect(),r=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-r.viewportWidth+1),maxOffsetY:Math.max(0,n-r.viewportHeight+1)}}getColRowOffsetInViewport(e,t,n){if(n<t)return-this.getColRowOffsetInViewport(e,n,t);let r=this.getters.getActiveSheetId(),i=e===`COL`?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),a=i.findIndex(e=>t>=e),o=i.findIndex(e=>n<=e);o=o===-1?i.length:o;let s=i.slice(a,o),c=0;for(let t of s)c+=this.getters.getHeaderSize(r,e,t);return c}isVisibleInViewport({sheetId:e,col:t,row:n}){return this.getSubViewports(e).some(e=>e.isVisible(t,n))}getEdgeScrollCol(e,t,n){let r=!1,i=0,a=0,{xSplit:o}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:s}=this.getSheetViewDimension(),{x:c}=this.getMainViewportCoordinates(),l=this.getActiveSheetScrollInfo().scrollX;return e>s?(r=!0,a=Os(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=Os(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=Os(e),i=`reset`),{canEdgeScroll:r,direction:i,delay:a}}getEdgeScrollRow(e,t,n){let r=!1,i=0,a=0,{ySplit:o}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:s}=this.getSheetViewDimension(),{y:c}=this.getMainViewportCoordinates(),l=this.getActiveSheetScrollInfo().scrollY;return e>s?(r=!0,a=Os(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=Os(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=Os(e),i=`reset`),{canEdgeScroll:r,direction:i,delay:a}}getVisibleRect(e){let t=this.getVisibleRectWithoutHeaders(e);return{...t,x:t.x+this.gridOffsetX,y:t.y+this.gridOffsetY}}getVisibleRectWithoutHeaders(e){let t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getVisibleRect(e))}getRect(e){let t=this.getters.getActiveSheetId(),n=this.mapViewportsToRect(t,t=>t.getFullRect(e));return{...n,x:n.x+this.gridOffsetX,y:n.y+this.gridOffsetY}}getMainViewportCoordinates(){let e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,n).start}}getColDimensionsInViewport(e,t){let n=Kt(this.getters.getSheetViewVisibleCols()),r=this.getters.getColRowOffsetInViewport(`COL`,n,t),i=this.getters.getColSize(e,t);return{start:r,size:i,end:r+(this.getters.isColHidden(e,t)?0:i)}}getRowDimensionsInViewport(e,t){let n=Kt(this.getters.getSheetViewVisibleRows()),r=this.getters.getColRowOffsetInViewport(`ROW`,n,t),i=this.getters.getRowSize(e,t);return{start:r,size:i,end:r+(this.getters.isRowHidden(e,t)?0:i)}}getAllActiveViewportsZonesAndRect(){let e=this.getters.getActiveSheetId();return this.getSubViewports(e).map(e=>({zone:e,rect:{x:e.offsetCorrectionX+this.gridOffsetX,y:e.offsetCorrectionY+this.gridOffsetY,...e.getMaxSize()}}))}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(S)}checkPositiveDimension(e){return e.width<0||e.height<0?`InvalidViewportSize`:`Success`}checkValuesAreDifferent(e){let{height:t,width:n}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===n&&e.height===t?`ValuesNotChanged`:`Success`}checkScrollingDirection({offsetX:e,offsetY:t}){let n=this.getMainInternalViewport(this.getters.getActiveSheetId());return!n.canScrollHorizontally&&e>0||!n.canScrollVertically&&t>0?`InvalidScrollingDirection`:`Success`}checkIfViewportsWillChange({offsetX:e,offsetY:t}){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();return this.getSubViewports(n).some(n=>n.willNewOffsetScrollViewport(b(e,0,r),b(t,0,i)))?`Success`:`ViewportScrollLimitsReached`}getMainViewport(e){let t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){let e={};for(let t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,n=0,r=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=n,this.gridOffsetY=r,this.recomputeViewports()}recomputeViewports(){for(let e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();this.getSubViewports(n).forEach(n=>n.setViewportOffset(b(e,0,r),b(t,0,i)))}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetScrollbarX||0,y:this.viewports[e]?.bottomRight.offsetScrollbarY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getNumberCols(e),i=this.getters.getNumberRows(e),a=Math.min(this.getters.getColRowOffset(`COL`,0,t,e),this.sheetViewWidth),o=Math.min(this.getters.getColRowOffset(`ROW`,0,n,e),this.sheetViewHeight),s=Math.max(this.sheetViewWidth-a,0),c=Math.max(this.sheetViewHeight-o,0),{xRatio:l,yRatio:u}=this.getFrozenSheetViewRatio(e),d=l<1,f=u<1,p=this.getViewportOffset(e),m={topLeft:n&&t&&new iB(this.getters,e,{left:0,right:t-1,top:0,bottom:n-1},{width:a,height:o},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:n&&new iB(this.getters,e,{left:t,right:r-1,top:0,bottom:n-1},{width:s,height:o},{canScrollHorizontally:d,canScrollVertically:!1},{x:d?p.x:0,y:0})||void 0,bottomLeft:t&&new iB(this.getters,e,{left:0,right:t-1,top:n,bottom:i-1},{width:a,height:c},{canScrollHorizontally:!1,canScrollVertically:f},{x:0,y:f?p.y:0})||void 0,bottomRight:new iB(this.getters,e,{left:t,right:r-1,top:n,bottom:i-1},{width:s,height:c},{canScrollHorizontally:d,canScrollVertically:f},{x:d?p.x:0,y:f?p.y:0})};this.viewports[e]=m}refreshViewport(e,t){this.getSubViewports(e).forEach(e=>{e.adjustViewportZone(),e.adjustPosition(t)})}shiftVertically(e){let t=this.getters.getActiveSheetId(),{top:n}=this.getMainInternalViewport(t),{scrollX:r}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(r,e);let{anchor:i}=this.getters.getSelection();if(i.cell.row>=this.getters.getPaneDivisions(t).ySplit){let e=this.getMainInternalViewport(t).top-n;this.selection.selectCell(i.cell.col,i.cell.row+e)}}getVisibleFigures(){let e=this.getters.getActiveSheetId(),t=[],n=this.getters.getFigures(e),{scrollX:r,scrollY:i}=this.getActiveSheetScrollInfo(),{x:a,y:o}=this.getters.getMainViewportCoordinates(),{width:s,height:c}=this.getters.getSheetViewDimensionWithHeaders();for(let e of n)e.x>=a&&(e.x+e.width<=a+r||e.x>=s+r+a)||e.y>=o&&(e.y+e.height<=o+i||e.y>=c+i+o)||t.push(e);return t}isPositionVisible(e){let{scrollX:t,scrollY:n}=this.getters.getActiveSheetScrollInfo(),{x:r,y:i}=this.getters.getMainViewportCoordinates(),{width:a,height:o}=this.getters.getSheetViewDimension();return!(e.x>=r&&(e.x<r+t||e.x>a+t+r)||e.y>=i&&(e.y<i+n||e.y>o+n+i))}getFrozenSheetViewRatio(e){let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getColDimensions(e,t).start,i=this.getters.getRowDimensions(e,n).start,a=this.sheetViewWidth+this.gridOffsetX,o=this.sheetViewHeight+this.gridOffsetY;return{xRatio:r/a,yRatio:i/o}}mapViewportsToRect(e,t){let n=1/0,r=1/0,i=0,a=0,o=!1;for(let s of this.getSubViewports(e)){let e=t(s);e&&(o=!0,n=Math.min(n,e.x),r=Math.min(r,e.y),i=Math.max(i,e.x+e.width),a=Math.max(a,e.y+e.height))}return o?{x:n,y:r,width:i-n,height:a-r}:{x:0,y:0,width:0,height:0}}},oB=class extends ${static getters=[`getColDimensions`,`getRowDimensions`,`getColRowOffset`];headerPositions={};isDirty=!0;handle(e){switch(Ri.has(e.type)&&(this.headerPositions={},this.isDirty=!0),e.type){case`START`:for(let e of this.getters.getSheetIds())this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e);break;case`UPDATE_CELL`:this.headerPositions={},this.isDirty=!0;break;case`UPDATE_FILTER`:case`UPDATE_TABLE`:case`REMOVE_TABLE`:this.headerPositions={},this.isDirty=!0;break;case`REMOVE_COLUMNS_ROWS`:case`RESIZE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_ALL_HEADER_GROUPS`:case`UNGROUP_HEADERS`:case`GROUP_HEADERS`:case`CREATE_SHEET`:this.getters.tryGetSheet(e.sheetId)&&(this.headerPositions[e.sheetId]=this.computeHeaderPositionsOfSheet(e.sheetId));break;case`DUPLICATE_SHEET`:this.headerPositions[e.sheetIdTo]=y(this.headerPositions[e.sheetId]);break}}finalize(){for(let e of this.getters.getSheetIds())(this.isDirty||!this.headerPositions[e])&&(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){let n=this.headerPositions[e].COL[t],r=this.getters.getColSize(e,t);return{start:n,size:r,end:n+(this.getters.isColHidden(e,t)?0:r)}}getRowDimensions(e,t){let n=this.headerPositions[e].ROW[t],r=this.getters.getRowSize(e,t);return{start:n,size:r,end:n+(this.getters.isRowHidden(e,t)?0:r)}}getColRowOffset(e,t,n,r=this.getters.getActiveSheetId()){let i=this.headerPositions[r][e][t];return this.headerPositions[r][e][n]-i}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,`COL`),ROW:this.computePositions(e,`ROW`)}}computePositions(e,t){let n={},r=0;for(let i=0;i<this.getters.getNumberHeaders(e,t)+1;i++)n[i]=r,!this.getters.isHeaderHidden(e,t,i)&&(r+=this.getters.getHeaderSize(e,t,i));return n}};let sB=new h().add(`settings`,JL).add(`sheet`,WL).add(`header grouping`,KL).add(`header visibility`,RL).add(`tables`,GL).add(`dataValidation`,FL).add(`cell`,kL).add(`merge`,BL).add(`headerSize`,LL).add(`borders`,DL).add(`conditional formatting`,PL).add(`figures`,IL).add(`chart`,ML).add(`image`,zL).add(`pivot_core`,qL).add(`spreadsheet_pivot_core`,YL).add(`tableStyle`,XL),cB=new h().add(`ui_sheet`,vz).add(`ui_options`,_z).add(`autofill`,NR).add(`sort`,gz).add(`automatic_sum`,PR).add(`format`,pz).add(`insert_pivot`,hz).add(`pivot_presence`,Zz).add(`split_to_columns`,Qz).add(`collaborative`,dz).add(`history`,Yz).add(`data_cleanup`,fz).add(`table_autofill`,$z).add(`table_ui_resize`,eB).add(`datavalidation_insert`,Cz),lB=new h().add(`selection`,rB).add(`evaluation_filter`,nB).add(`header_visibility_ui`,mz).add(`cell_computed_style`,Sz).add(`table_computed_style`,yz).add(`header_positions`,oB).add(`viewport`,aB).add(`clipboard`,tB),uB=new h().add(`evaluation`,gR).add(`evaluation_chart`,xR).add(`evaluation_cf`,SR).add(`row_size`,ER).add(`data_validation_ui`,wR).add(`dynamic_tables`,TR).add(`custom_colors`,bR).add(`pivot_ui`,jR),dB=new h;dB.add(`link`,{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t)=>to(t.model.getters.getEvaluatedCell(e).link,t),sequence:5});var fB=class{fileStore;constructor(e){this.fileStore=e}async requestImage(){let e=await this.getImageFromUser(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}getImageFromUser(){return new Promise((e,t)=>{let n=document.createElement(`input`);n.setAttribute(`type`,`file`),n.setAttribute(`accept`,`image/*`),n.addEventListener(`change`,async()=>{n.files===null||n.files.length!==1?t():e(n.files[0])}),n.click()})}getImageOriginalSize(e){return new Promise((t,n)=>{let r=new Image;r.src=e,r.addEventListener(`load`,()=>{t({width:r.width,height:r.height})}),r.addEventListener(`error`,n)})}};let pB=[{transform:`scale(0)`},{transform:`scale(0.8)`,offset:.33},{opacity:`0`,transform:`scale(1)`,offset:1}];H`
1895
1895
  .o-ripple {
1896
1896
  z-index: 1;
1897
1897
  }
1898
- `;var hB=class 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=(0,t.useRef)(`ripple`);setup(){let e;(0,t.onMounted)(()=>{let t=this.rippleRef.el;!t||!t.animate||(e=t.animate(mB,{duration:this.props.duration,easing:`ease-out`}),e.addEventListener(`finish`,this.props.onAnimationEnd))}),(0,t.onWillUnmount)(()=>{e?.removeEventListener(`finish`,this.props.onAnimationEnd)})}get rippleStyle(){let{x:e,y:t,width:n,height:r}=this.props,i=this.props.offsetX||0,a=this.props.offsetY||0;return U({transform:`scale(0)`,left:e,top:t,"margin-left":`${-n/2+i}px`,"margin-top":`${-r/2+a}px`,width:`${n}px`,height:`${r}px`,background:this.props.color,"border-radius":`100%`,opacity:`${this.props.opacity}`})}},gB=class 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:hB};static defaultProps={color:`#aaaaaa`,opacity:.4,duration:800,enabled:!0,onAnimationEnd:()=>{},class:``};childContainer=(0,t.useRef)(`childContainer`);state=(0,t.useState)({ripples:[]});currentId=1;onClick(e){if(!this.props.enabled||!this.childContainer.el)return;let{x:t,y:n,width:r,height:i}=this.getRippleChildRectInfo(),a=Math.max(r,i),o={x:e.clientX-t,y:e.clientY-n,width:this.props.width||a*2.85,height:this.props.height||a*2.85};this.state.ripples.push({rippleRect:o,id:this.currentId++})}getRippleStyle(){let e=this.childContainer.el;if(!e||e.childElementCount!==1||!e.firstElementChild)return``;let t=this.getRippleChildRectInfo();return U({top:t.marginTop+`px`,left:t.marginLeft+`px`,width:t.width+`px`,height:t.height+`px`})}getRippleChildRectInfo(){let e=this.childContainer.el;if(!e)throw Error(`No child container element found`);if(e.childElementCount!==1||!e.firstElementChild)return{...XT(e),marginLeft:0,marginTop:0};let t=e.firstElementChild,n=Sf(t);return{...XT(t),marginLeft:n.left,marginTop:n.top}}removeRipple(e){let t=this.state.ripples.findIndex(t=>t.id===e);t!==-1&&this.state.ripples.splice(t,1)}getRippleEffectProps(e){let t=this.state.ripples.find(t=>t.id===e)?.rippleRect;if(!t)throw 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)}}};function _B(e,t,n,r){let i=e.model.dispatch(`RENAME_SHEET`,{sheetId:t,name:n});i.reasons.includes(`MissingSheetName`)?e.raiseError(E(`The sheet name cannot be empty.`),r):i.reasons.includes(`DuplicatedSheetName`)?e.raiseError(E(`A sheet with the name %s already exists. Please select another name.`,n),r):i.reasons.includes(`ForbiddenCharactersInSheetName`)&&e.raiseError(E(`Some used characters are not allowed in a sheet name (Forbidden characters are %s).`,Ge.join(` `)),r)}H`
1898
+ `;var mB=class 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=(0,t.useRef)(`ripple`);setup(){let e;(0,t.onMounted)(()=>{let t=this.rippleRef.el;!t||!t.animate||(e=t.animate(pB,{duration:this.props.duration,easing:`ease-out`}),e.addEventListener(`finish`,this.props.onAnimationEnd))}),(0,t.onWillUnmount)(()=>{e?.removeEventListener(`finish`,this.props.onAnimationEnd)})}get rippleStyle(){let{x:e,y:t,width:n,height:r}=this.props,i=this.props.offsetX||0,a=this.props.offsetY||0;return U({transform:`scale(0)`,left:e,top:t,"margin-left":`${-n/2+i}px`,"margin-top":`${-r/2+a}px`,width:`${n}px`,height:`${r}px`,background:this.props.color,"border-radius":`100%`,opacity:`${this.props.opacity}`})}},hB=class 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:mB};static defaultProps={color:`#aaaaaa`,opacity:.4,duration:800,enabled:!0,onAnimationEnd:()=>{},class:``};childContainer=(0,t.useRef)(`childContainer`);state=(0,t.useState)({ripples:[]});currentId=1;onClick(e){if(!this.props.enabled||!this.childContainer.el)return;let{x:t,y:n,width:r,height:i}=this.getRippleChildRectInfo(),a=Math.max(r,i),o={x:e.clientX-t,y:e.clientY-n,width:this.props.width||a*2.85,height:this.props.height||a*2.85};this.state.ripples.push({rippleRect:o,id:this.currentId++})}getRippleStyle(){let e=this.childContainer.el;if(!e||e.childElementCount!==1||!e.firstElementChild)return``;let t=this.getRippleChildRectInfo();return U({top:t.marginTop+`px`,left:t.marginLeft+`px`,width:t.width+`px`,height:t.height+`px`})}getRippleChildRectInfo(){let e=this.childContainer.el;if(!e)throw Error(`No child container element found`);if(e.childElementCount!==1||!e.firstElementChild)return{...XT(e),marginLeft:0,marginTop:0};let t=e.firstElementChild,n=Sf(t);return{...XT(t),marginLeft:n.left,marginTop:n.top}}removeRipple(e){let t=this.state.ripples.findIndex(t=>t.id===e);t!==-1&&this.state.ripples.splice(t,1)}getRippleEffectProps(e){let t=this.state.ripples.find(t=>t.id===e)?.rippleRect;if(!t)throw 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)}}};function gB(e,t,n,r){let i=e.model.dispatch(`RENAME_SHEET`,{sheetId:t,name:n});i.reasons.includes(`MissingSheetName`)?e.raiseError(E(`The sheet name cannot be empty.`),r):i.reasons.includes(`DuplicatedSheetName`)?e.raiseError(E(`A sheet with the name %s already exists. Please select another name.`,n),r):i.reasons.includes(`ForbiddenCharactersInSheetName`)&&e.raiseError(E(`Some used characters are not allowed in a sheet name (Forbidden characters are %s).`,Ge.join(` `)),r)}H`
1899
1899
  .o-sheet {
1900
1900
  padding: 0 15px;
1901
1901
  padding-right: 10px;
@@ -1943,7 +1943,7 @@ stores.inject(MyMetaStore, storeInstance);
1943
1943
  width: calc(100% - 1px);
1944
1944
  }
1945
1945
  }
1946
- `;var vB=class 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:gB,ColorPicker:BN};static defaultProps={onMouseDown:()=>{},style:``};state=(0,t.useState)({isEditing:!1,pickerOpened:!1});sheetDivRef=(0,t.useRef)(`sheetDiv`);sheetNameRef=(0,t.useRef)(`sheetNameSpan`);editionState=`initializing`;DOMFocusableElementStore;setup(){(0,t.onPatched)(()=>{this.sheetNameRef.el&&this.state.isEditing&&this.editionState===`initializing`&&(this.editionState=`editing`,this.focusInputAndSelectContent())}),this.DOMFocusableElementStore=V(GT),(0,t.useExternalListener)(window,`click`,()=>this.state.pickerOpened=!1),(0,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();let 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&&this.editionState!==`initializing`&&this.stopEdition()}onMouseDown(e){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&&(e.key===`Enter`&&(e.preventDefault(),this.stopEdition(),this.DOMFocusableElementStore.focus()),e.key===`Escape`&&(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();let e=this.getInputContent()||``;_B(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(){let e=this.sheetDivRef.el;return XT(e)}get contextMenuRegistry(){return _N({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 U({background:this.env.model.getters.getSheet(this.props.sheetId).color||``})}};let yB=[{name:E(`Sum`),types:[`number`],compute:(e,t)=>bl([[e]],t)},{name:E(`Avg`),types:[`number`],compute:(e,t)=>Al([[e]],t)},{name:E(`Min`),types:[`number`],compute:(e,t)=>Pl([[e]],t).value},{name:E(`Max`),types:[`number`],compute:(e,t)=>Nl([[e]],t).value},{name:E(`Count`),types:[`number`,`text`,`boolean`,`error`],compute:e=>Ml([[e]])},{name:E(`Count Numbers`),types:[`number`,`text`,`boolean`,`error`],compute:(e,t)=>jl([[e]],t)}];var bB=class extends hd{statisticFnResults=this._computeStatisticFnResults();isDirty=!1;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.handleEvent.bind(this)})}handle(e){switch((Ri.has(e.type)||e.type===`UPDATE_CELL`&&(`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(){let e=this.getters,t=e.getActiveSheetId(),n=[],r=T(e.getSelectedZones(),[]),i=this.getters.getSheetSize(t).numberOfRows-1,a=this.getters.getSheetSize(t).numberOfCols-1;for(let o of r)for(let r=o.left;r<=(o.right??a);r++)for(let a=o.top;a<=(o.bottom??i);a++){if(e.isRowHidden(t,a)||e.isColHidden(t,r))continue;let i=e.getEvaluatedCell({sheetId:t,col:r,row:a});i.type!==`empty`&&n.push(i)}let o=e.getLocale(),s={},c=Rt(e=>{let t=e.split(`,`);return n.filter(e=>t.includes(e.type))});for(let e of yB){let t,n=c(e.types.sort().join(`,`));n.length&&(t=Et(()=>e.compute(n,o))),s[e.name]=t}return s}};H`
1946
+ `;var _B=class 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:hB,ColorPicker:BN};static defaultProps={onMouseDown:()=>{},style:``};state=(0,t.useState)({isEditing:!1,pickerOpened:!1});sheetDivRef=(0,t.useRef)(`sheetDiv`);sheetNameRef=(0,t.useRef)(`sheetNameSpan`);editionState=`initializing`;DOMFocusableElementStore;setup(){(0,t.onPatched)(()=>{this.sheetNameRef.el&&this.state.isEditing&&this.editionState===`initializing`&&(this.editionState=`editing`,this.focusInputAndSelectContent())}),this.DOMFocusableElementStore=V(GT),(0,t.useExternalListener)(window,`click`,this.onExternalClick.bind(this),{capture:!0}),(0,t.useEffect)(e=>{this.props.sheetId===e&&this.scrollToSheet()},()=>[this.env.model.getters.getActiveSheetId()])}onExternalClick(e){e.target.closest(`.o-color-picker`)||(this.state.pickerOpened=!1)}focusInputAndSelectContent(){if(!this.state.isEditing||!this.sheetNameRef.el)return;this.sheetNameRef.el.focus();let 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&&this.editionState!==`initializing`&&this.stopEdition()}onMouseDown(e){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&&(e.key===`Enter`&&(e.preventDefault(),this.stopEdition(),this.DOMFocusableElementStore.focus()),e.key===`Escape`&&(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();let e=this.getInputContent()||``;gB(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(){let e=this.sheetDivRef.el;return XT(e)}get contextMenuRegistry(){return _N({renameSheetCallback:()=>{this.scrollToSheet(),this.startEdition()},openSheetColorPickerCallback:()=>{this.state.pickerOpened=!0;let e=this.env.model.getters.getSheet(this.props.sheetId);this.state.currentPickerColor=e.color}})}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 U({background:this.env.model.getters.getSheet(this.props.sheetId).color||``})}};let vB=[{name:E(`Sum`),types:[`number`],compute:(e,t)=>bl([[e]],t)},{name:E(`Avg`),types:[`number`],compute:(e,t)=>Al([[e]],t)},{name:E(`Min`),types:[`number`],compute:(e,t)=>Pl([[e]],t).value},{name:E(`Max`),types:[`number`],compute:(e,t)=>Nl([[e]],t).value},{name:E(`Count`),types:[`number`,`text`,`boolean`,`error`],compute:e=>Ml([[e]])},{name:E(`Count Numbers`),types:[`number`,`text`,`boolean`,`error`],compute:(e,t)=>jl([[e]],t)}];var yB=class extends hd{statisticFnResults=this._computeStatisticFnResults();isDirty=!1;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.handleEvent.bind(this)})}handle(e){switch((Ri.has(e.type)||e.type===`UPDATE_CELL`&&(`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(){let e=this.getters,t=e.getActiveSheetId(),n=[],r=T(e.getSelectedZones(),[]),i=this.getters.getSheetSize(t).numberOfRows-1,a=this.getters.getSheetSize(t).numberOfCols-1;for(let o of r)for(let r=o.left;r<=(o.right??a);r++)for(let a=o.top;a<=(o.bottom??i);a++){if(e.isRowHidden(t,a)||e.isColHidden(t,r))continue;let i=e.getEvaluatedCell({sheetId:t,col:r,row:a});i.type!==`empty`&&n.push(i)}let o=e.getLocale(),s={},c=Rt(e=>{let t=e.split(`,`);return n.filter(e=>t.includes(e.type))});for(let e of vB){let t,n=c(e.types.sort().join(`,`));n.length&&(t=Et(()=>e.compute(n,o))),s[e.name]=t}return s}};H`
1947
1947
  .o-selection-statistic {
1948
1948
  margin-right: 20px;
1949
1949
  padding: 4px 4px 4px 8px;
@@ -1953,7 +1953,7 @@ stores.inject(MyMetaStore, storeInstance);
1953
1953
  background-color: rgba(0, 0, 0, 0.08) !important;
1954
1954
  }
1955
1955
  }
1956
- `;var xB=class extends t.Component{static template=`o-spreadsheet-BottomBarStatistic`;static props={openContextMenu:Function,closeContextMenu:Function};static components={Ripple:gB};selectedStatisticFn=``;store;setup(){this.store=V(bB),(0,t.onWillUpdateProps)(()=>{Object.values(this.store.statisticFnResults).every(e=>e===void 0)&&this.props.closeContextMenu()})}getSelectedStatistic(){if(!Object.values(this.store.statisticFnResults).every(e=>e===void 0))return this.selectedStatisticFn===``&&(this.selectedStatisticFn=Object.keys(this.store.statisticFnResults)[0]),this.getComposedFnName(this.selectedStatisticFn)}listSelectionStatistics(e){let t=new PO,n=0;for(let[e]of Object.entries(this.store.statisticFnResults))t.add(e,{name:()=>this.getComposedFnName(e),sequence:n,isReadonlyAllowed:!0,execute:()=>{this.selectedStatisticFn=e}}),n++;let{top:r,left:i,width:a}=e.currentTarget.getBoundingClientRect();this.props.openContextMenu(i+a,r,t)}getComposedFnName(e){let t=this.env.model.getters.getLocale(),n=this.store.statisticFnResults[e];return e+`: `+(n===void 0?`__`:B(n(),{locale:t}))}};H`
1956
+ `;var bB=class extends t.Component{static template=`o-spreadsheet-BottomBarStatistic`;static props={openContextMenu:Function,closeContextMenu:Function};static components={Ripple:hB};selectedStatisticFn=``;store;setup(){this.store=V(yB),(0,t.onWillUpdateProps)(()=>{Object.values(this.store.statisticFnResults).every(e=>e===void 0)&&this.props.closeContextMenu()})}getSelectedStatistic(){if(!Object.values(this.store.statisticFnResults).every(e=>e===void 0))return this.selectedStatisticFn===``&&(this.selectedStatisticFn=Object.keys(this.store.statisticFnResults)[0]),this.getComposedFnName(this.selectedStatisticFn)}listSelectionStatistics(e){let t=new PO,n=0;for(let[e]of Object.entries(this.store.statisticFnResults))t.add(e,{name:()=>this.getComposedFnName(e),sequence:n,isReadonlyAllowed:!0,execute:()=>{this.selectedStatisticFn=e}}),n++;let{top:r,left:i,width:a}=e.currentTarget.getBoundingClientRect();this.props.openContextMenu(i+a,r,t)}getComposedFnName(e){let t=this.env.model.getters.getLocale(),n=this.store.statisticFnResults[e];return e+`: `+(n===void 0?`__`:B(n(),{locale:t}))}};H`
1957
1957
  .o-spreadsheet-bottom-bar {
1958
1958
  background-color: ${v};
1959
1959
  padding-left: ${48}px;
@@ -2006,12 +2006,12 @@ stores.inject(MyMetaStore, storeInstance);
2006
2006
  }
2007
2007
  }
2008
2008
  }
2009
- `;var SB=class extends t.Component{static template=`o-spreadsheet-BottomBar`;static props={onClick:Function};static components={Menu:pk,Ripple:gB,BottomBarSheet:vB,BottomBarStatistic:xB};bottomBarRef=(0,t.useRef)(`bottomBar`);sheetListRef=(0,t.useRef)(`sheetList`);dragAndDrop=fP();targetScroll=void 0;state=(0,t.useState)({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1});menuMaxHeight=250;menuState=(0,t.useState)({isOpen:!1,menuId:void 0,position:null,menuItems:[]});sheetList=this.getVisibleSheets();setup(){(0,t.onWillUpdateProps)(()=>{this.updateScrollState();let e=this.getVisibleSheets();C(this.sheetList,e)||this.dragAndDrop.cancel(),this.sheetList=e})}clickAddSheet(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSheetIds().findIndex(e=>e===t)+1,r=this.env.model.uuidGenerator.smallUuid(),i=this.env.model.getters.getNextSheetName(E(`Sheet`));this.env.model.dispatch(`CREATE_SHEET`,{sheetId:r,position:n,name:i}),this.env.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t,sheetIdTo:r})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map(e=>{let t=this.env.model.getters.getSheet(e);return{id:t.id,name:t.name}})}clickListSheets(e){let t=new PO,n=this.env.model.getters.getActiveSheetId(),r=0;for(let e of this.env.model.getters.getSheetIds()){let i=this.env.model.getters.getSheet(e);t.add(e,{name:i.name,sequence:r,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:n,sheetIdTo:e})},isEnabled:e=>e.model.getters.isReadonly()?i.isVisible:!0,icon:i.color?`o-spreadsheet-Icon.SMALL_DOT_RIGHT_ALIGN`:void 0,iconColor:i.color}),r++}let{left:i}=e.currentTarget.getBoundingClientRect(),a=this.bottomBarRef.el.getBoundingClientRect().top;this.openContextMenu(i,a,`listSheets`,t)}openContextMenu(e,t,n,r){this.menuState.isOpen=!0,this.menuState.menuId=n,this.menuState.menuItems=r.getMenuItems(),this.menuState.position={x:e,y:t}}onSheetContextMenu(e,t,n){let{top:r,left:i}=n.currentTarget.getBoundingClientRect();if(n.closedMenuId===e){this.closeMenu();return}this.openContextMenu(i,r,e,t)}closeMenu(){this.menuState.isOpen=!1,this.menuState.menuId=void 0,this.menuState.menuItems=[],this.menuState.position=null}closeContextMenuWithId(e){this.menuState.menuId===e&&this.closeMenu()}onWheel(e){this.targetScroll=void 0;let t=e.currentTarget;t.scrollLeft+=e.deltaY*.5}onScroll(){this.updateScrollState(),this.targetScroll===this.sheetListCurrentScroll&&(this.targetScroll=void 0)}onArrowLeft(e){if(!this.state.isSheetListScrollableLeft)return;this.targetScroll||=this.sheetListCurrentScroll;let t=this.targetScroll-this.sheetListWidth;this.scrollSheetListTo(Math.max(0,t))}onArrowRight(e){if(!this.state.isSheetListScrollableRight)return;this.targetScroll||=this.sheetListCurrentScroll;let 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(t.button!==0||this.env.model.getters.isReadonly())return;this.closeMenu();let n=this.getVisibleSheets(),r=this.getSheetItemRects(),i=n.map((e,t)=>({id:e.id,size:r[t].width,position:r[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){let n=t-this.getVisibleSheets().findIndex(t=>t.id===e);e&&n!==0&&this.env.model.dispatch(`MOVE_SHEET`,{sheetId:e,delta:n})}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}},CB=class extends hd{_clickableCells=(0,t.markRaw)({});_registryItems=(0,t.markRaw)(fB.getAll().sort((e,t)=>e.sequence-t.sequence));handle(e){(Ri.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this._clickableCells=(0,t.markRaw)({}),this._registryItems=(0,t.markRaw)(fB.getAll().sort((e,t)=>e.sequence-t.sequence)))}getClickableAction(e){let{sheetId:t,col:n,row:r}=e,i=this._clickableCells,a=w(n,r);return i[t]||(i[t]={}),a in i[t]||(i[t][a]=this.findClickableAction(e)),i[t][a]}findClickableAction(e){let t=this.getters;for(let n of this._registryItems)if(n.condition(e,t))return n.execute;return!1}get clickableCells(){let e=[],t=this.getters,n=t.getActiveSheetId();for(let r of t.getSheetViewVisibleCols())for(let i of t.getSheetViewVisibleRows()){let a={sheetId:n,col:r,row:i};if(!t.isMainCellPosition(a))continue;let o=this.getClickableAction(a);if(!o)continue;let s=t.expandZone(n,D(a));e.push({coordinates:t.getVisibleRect(s),position:a,action:o})}return e}};H`
2009
+ `;var xB=class extends t.Component{static template=`o-spreadsheet-BottomBar`;static props={onClick:Function};static components={Menu:pk,Ripple:hB,BottomBarSheet:_B,BottomBarStatistic:bB};bottomBarRef=(0,t.useRef)(`bottomBar`);sheetListRef=(0,t.useRef)(`sheetList`);dragAndDrop=fP();targetScroll=void 0;state=(0,t.useState)({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1});menuMaxHeight=250;menuState=(0,t.useState)({isOpen:!1,menuId:void 0,position:null,menuItems:[]});sheetList=this.getVisibleSheets();setup(){(0,t.onWillUpdateProps)(()=>{this.updateScrollState();let e=this.getVisibleSheets();C(this.sheetList,e)||this.dragAndDrop.cancel(),this.sheetList=e})}clickAddSheet(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSheetIds().findIndex(e=>e===t)+1,r=this.env.model.uuidGenerator.smallUuid(),i=this.env.model.getters.getNextSheetName(E(`Sheet`));this.env.model.dispatch(`CREATE_SHEET`,{sheetId:r,position:n,name:i}),this.env.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t,sheetIdTo:r})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map(e=>{let t=this.env.model.getters.getSheet(e);return{id:t.id,name:t.name}})}clickListSheets(e){let t=new PO,n=this.env.model.getters.getActiveSheetId(),r=0;for(let e of this.env.model.getters.getSheetIds()){let i=this.env.model.getters.getSheet(e);t.add(e,{name:i.name,sequence:r,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:n,sheetIdTo:e})},isEnabled:e=>e.model.getters.isReadonly()?i.isVisible:!0,icon:i.color?`o-spreadsheet-Icon.SMALL_DOT_RIGHT_ALIGN`:void 0,iconColor:i.color}),r++}let{left:i}=e.currentTarget.getBoundingClientRect(),a=this.bottomBarRef.el.getBoundingClientRect().top;this.openContextMenu(i,a,`listSheets`,t)}openContextMenu(e,t,n,r){this.menuState.isOpen=!0,this.menuState.menuId=n,this.menuState.menuItems=r.getMenuItems(),this.menuState.position={x:e,y:t}}onSheetContextMenu(e,t,n){let{top:r,left:i}=n.currentTarget.getBoundingClientRect();if(n.closedMenuId===e){this.closeMenu();return}this.openContextMenu(i,r,e,t)}closeMenu(){this.menuState.isOpen=!1,this.menuState.menuId=void 0,this.menuState.menuItems=[],this.menuState.position=null}closeContextMenuWithId(e){this.menuState.menuId===e&&this.closeMenu()}onWheel(e){this.targetScroll=void 0;let t=e.currentTarget;t.scrollLeft+=e.deltaY*.5}onScroll(){this.updateScrollState(),this.targetScroll===this.sheetListCurrentScroll&&(this.targetScroll=void 0)}onArrowLeft(e){if(!this.state.isSheetListScrollableLeft)return;this.targetScroll||=this.sheetListCurrentScroll;let t=this.targetScroll-this.sheetListWidth;this.scrollSheetListTo(Math.max(0,t))}onArrowRight(e){if(!this.state.isSheetListScrollableRight)return;this.targetScroll||=this.sheetListCurrentScroll;let 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(t.button!==0||this.env.model.getters.isReadonly())return;this.closeMenu();let n=this.getVisibleSheets(),r=this.getSheetItemRects(),i=n.map((e,t)=>({id:e.id,size:r[t].width,position:r[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){let n=t-this.getVisibleSheets().findIndex(t=>t.id===e);e&&n!==0&&this.env.model.dispatch(`MOVE_SHEET`,{sheetId:e,delta:n})}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}},SB=class extends hd{_clickableCells=(0,t.markRaw)({});_registryItems=(0,t.markRaw)(dB.getAll().sort((e,t)=>e.sequence-t.sequence));handle(e){(Ri.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this._clickableCells=(0,t.markRaw)({}),this._registryItems=(0,t.markRaw)(dB.getAll().sort((e,t)=>e.sequence-t.sequence)))}getClickableAction(e){let{sheetId:t,col:n,row:r}=e,i=this._clickableCells,a=w(n,r);return i[t]||(i[t]={}),a in i[t]||(i[t][a]=this.findClickableAction(e)),i[t][a]}findClickableAction(e){let t=this.getters;for(let n of this._registryItems)if(n.condition(e,t))return n.execute;return!1}get clickableCells(){let e=[],t=this.getters,n=t.getActiveSheetId();for(let r of t.getSheetViewVisibleCols())for(let i of t.getSheetViewVisibleRows()){let a={sheetId:n,col:r,row:i};if(!t.isMainCellPosition(a))continue;let o=this.getClickableAction(a);if(!o)continue;let s=t.expandZone(n,D(a));e.push({coordinates:t.getVisibleRect(s),position:a,action:o})}return e}};H`
2010
2010
  .o-dashboard-clickable-cell {
2011
2011
  position: absolute;
2012
2012
  cursor: pointer;
2013
2013
  }
2014
- `;var wB=class extends t.Component{static template=`o-spreadsheet-SpreadsheetDashboard`;static props={};static components={GridOverlay:eL,GridPopover:tL,Popover:lk,VerticalScrollBar:vL,HorizontalScrollBar:_L};cellPopovers;onMouseWheel;canvasPosition;hoveredCell;clickableCellsStore;setup(){let e=(0,t.useRef)(`grid`);this.canvasPosition=iE(e),this.hoveredCell=V(WO),this.clickableCellsStore=V(CB),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>this.getGridRect()}),cL(`canvas`,this.env.model,()=>this.env.model.getters.getSheetViewDimension()),this.onMouseWheel=dL((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=V(GO),uL(e,this.moveCanvas.bind(this),()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0})}onCellHovered({col:e,row:t}){this.hoveredCell.hover({col:e,row:t})}get gridContainer(){let e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e),{end:n}=this.env.model.getters.getColDimensions(e,t);return U({"max-width":`${n}px`})}get gridOverlayDimensions(){return U({height:`100%`,width:`100%`})}getCellClickableStyle(e){return U({top:`${e.y}px`,left:`${e.x}px`,width:`${e.width}px`,height:`${e.height}px`})}getClickableCells(){return(0,t.toRaw)(this.clickableCellsStore.clickableCells)}selectClickableCell(e){let{position:t,action:n}=e;n(t,this.env)}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){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}};H`
2014
+ `;var CB=class extends t.Component{static template=`o-spreadsheet-SpreadsheetDashboard`;static props={};static components={GridOverlay:$I,GridPopover:eL,Popover:lk,VerticalScrollBar:_L,HorizontalScrollBar:gL};cellPopovers;onMouseWheel;canvasPosition;hoveredCell;clickableCellsStore;setup(){let e=(0,t.useRef)(`grid`);this.canvasPosition=iE(e),this.hoveredCell=V(WO),this.clickableCellsStore=V(SB),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>this.getGridRect()}),sL(`canvas`,this.env.model,()=>this.env.model.getters.getSheetViewDimension()),this.onMouseWheel=uL((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=V(GO),lL(e,this.moveCanvas.bind(this),()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0})}onCellHovered({col:e,row:t}){this.hoveredCell.hover({col:e,row:t})}get gridContainer(){let e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e),{end:n}=this.env.model.getters.getColDimensions(e,t);return U({"max-width":`${n}px`})}get gridOverlayDimensions(){return U({height:`100%`,width:`100%`})}getCellClickableStyle(e){return U({top:`${e.y}px`,left:`${e.x}px`,width:`${e.width}px`,height:`${e.height}px`})}getClickableCells(){return(0,t.toRaw)(this.clickableCellsStore.clickableCells)}selectClickableCell(e){let{position:t,action:n}=e;n(t,this.env)}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){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}};H`
2015
2015
  .o-header-group {
2016
2016
  .o-header-group-header {
2017
2017
  z-index: ${6};
@@ -2034,7 +2034,7 @@ stores.inject(MyMetaStore, storeInstance);
2034
2034
  box-sizing: border-box;
2035
2035
  }
2036
2036
  }
2037
- `;var TB=class extends t.Component{static template=`o-spreadsheet-HeaderGroup`;static props={group:Object,layerOffset:Number,openContextMenu:Function};toggleGroup(){let e=this.env.model.getters.getActiveSheetId(),{start:t,end:n}=this.props.group;gI(this.env,e,this.dimension,t,n)}get groupBoxStyle(){let e=this.groupBox;return U({top:`${e.groupRect.y}px`,left:`${e.groupRect.x}px`,width:`${e.groupRect.width}px`,height:`${e.groupRect.height}px`})}get groupButtonStyle(){return U({"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(){let 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){let t=this.env.model.getters.getActiveSheetId(),n={x:e.clientX,y:e.clientY},r=this.props.group,i=vI(t,this.dimension,r.start,r.end);this.props.openContextMenu(n,i)}},EB=class extends TB{dimension=`ROW`;get groupBorderStyle(){let e=this.groupBox;return this.groupBox.groupRect.height===0?``:U({top:`${e.headerRect.height/2}px`,left:`calc(50% - 1px)`,width:`30%`,height:`calc(100% - ${e.headerRect.height/2}px)`,"border-left":`1px solid ${pe}`,"border-bottom":e.isEndHidden?``:`1px solid ${pe}`})}get groupHeaderStyle(){return U({width:`100%`,height:`${this.groupBox.headerRect.height}px`})}get groupBox(){let e=this.env.model.getters.getActiveSheetId(),{start:t,end:n}=this.props.group,r=this.env.model.getters.getRowDimensions(e,t).start,i=this.env.model.getters.getRowDimensions(e,n).end,a=0,o=26;if(t!==0){let n=this.env.model.getters.getRowDimensions(e,t-1);a=26+n.start,o=n.end-n.start}let s={x:this.props.layerOffset,y:a,width:21,height:o};return{headerRect:s,groupRect:{x:this.props.layerOffset,y:s.y,width:21,height:s.height+(i-r)},isEndHidden:this.env.model.getters.isRowHidden(e,n)}}},DB=class extends TB{dimension=`COL`;get groupBorderStyle(){let e=this.groupBox;return e.groupRect.width===0?``:U({top:`calc(50% - 1px)`,left:`${e.headerRect.width/2}px`,width:`calc(100% - ${e.headerRect.width/2}px)`,height:`30%`,"border-top":`1px solid ${pe}`,"border-right":e.isEndHidden?``:`1px solid ${pe}`})}get groupHeaderStyle(){return U({width:`${this.groupBox.headerRect.width}px`,height:`100%`})}get groupBox(){let e=this.env.model.getters.getActiveSheetId(),{start:t,end:n}=this.props.group,r=this.env.model.getters.getColDimensions(e,t).start,i=this.env.model.getters.getColDimensions(e,n).end,a=0,o=48;if(t!==0){let n=this.env.model.getters.getColDimensions(e,t-1);a=48+n.start,o=n.end-n.start}let s={x:a,y:this.props.layerOffset,width:o,height:21};return{headerRect:s,groupRect:{x:s.x,y:this.props.layerOffset,width:s.width+(i-r),height:21},isEndHidden:this.env.model.getters.isColHidden(e,n)}}};H`
2037
+ `;var wB=class extends t.Component{static template=`o-spreadsheet-HeaderGroup`;static props={group:Object,layerOffset:Number,openContextMenu:Function};toggleGroup(){let e=this.env.model.getters.getActiveSheetId(),{start:t,end:n}=this.props.group;hI(this.env,e,this.dimension,t,n)}get groupBoxStyle(){let e=this.groupBox;return U({top:`${e.groupRect.y}px`,left:`${e.groupRect.x}px`,width:`${e.groupRect.width}px`,height:`${e.groupRect.height}px`})}get groupButtonStyle(){return U({"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(){let 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){let t=this.env.model.getters.getActiveSheetId(),n={x:e.clientX,y:e.clientY},r=this.props.group,i=_I(t,this.dimension,r.start,r.end);this.props.openContextMenu(n,i)}},TB=class extends wB{dimension=`ROW`;get groupBorderStyle(){let e=this.groupBox;return this.groupBox.groupRect.height===0?``:U({top:`${e.headerRect.height/2}px`,left:`calc(50% - 1px)`,width:`30%`,height:`calc(100% - ${e.headerRect.height/2}px)`,"border-left":`1px solid ${pe}`,"border-bottom":e.isEndHidden?``:`1px solid ${pe}`})}get groupHeaderStyle(){return U({width:`100%`,height:`${this.groupBox.headerRect.height}px`})}get groupBox(){let e=this.env.model.getters.getActiveSheetId(),{start:t,end:n}=this.props.group,r=this.env.model.getters.getRowDimensions(e,t).start,i=this.env.model.getters.getRowDimensions(e,n).end,a=0,o=26;if(t!==0){let n=this.env.model.getters.getRowDimensions(e,t-1);a=26+n.start,o=n.end-n.start}let s={x:this.props.layerOffset,y:a,width:21,height:o};return{headerRect:s,groupRect:{x:this.props.layerOffset,y:s.y,width:21,height:s.height+(i-r)},isEndHidden:this.env.model.getters.isRowHidden(e,n)}}},EB=class extends wB{dimension=`COL`;get groupBorderStyle(){let e=this.groupBox;return e.groupRect.width===0?``:U({top:`calc(50% - 1px)`,left:`${e.headerRect.width/2}px`,width:`calc(100% - ${e.headerRect.width/2}px)`,height:`30%`,"border-top":`1px solid ${pe}`,"border-right":e.isEndHidden?``:`1px solid ${pe}`})}get groupHeaderStyle(){return U({width:`${this.groupBox.headerRect.width}px`,height:`100%`})}get groupBox(){let e=this.env.model.getters.getActiveSheetId(),{start:t,end:n}=this.props.group,r=this.env.model.getters.getColDimensions(e,t).start,i=this.env.model.getters.getColDimensions(e,n).end,a=0,o=48;if(t!==0){let n=this.env.model.getters.getColDimensions(e,t-1);a=48+n.start,o=n.end-n.start}let s={x:a,y:this.props.layerOffset,width:o,height:21};return{headerRect:s,groupRect:{x:s.x,y:this.props.layerOffset,width:s.width+(i-r),height:21},isEndHidden:this.env.model.getters.isColHidden(e,n)}}};H`
2038
2038
  .o-header-group-frozen-pane-border {
2039
2039
  &.o-group-rows {
2040
2040
  margin-top: -1px;
@@ -2054,7 +2054,7 @@ stores.inject(MyMetaStore, storeInstance);
2054
2054
  margin-left: -2px;
2055
2055
  }
2056
2056
  }
2057
- `;var OB=class extends t.Component{static template=`o-spreadsheet-HeaderGroupContainer`;static props={dimension:String,layers:Array};static components={RowGroup:EB,ColGroup:DB,Menu:pk};menu=(0,t.useState)({isOpen:!1,position:null,menuItems:[]});getLayerOffset(e){return e*21}onContextMenu(e){let t=this.env.model.getters.getActiveSheetId(),n={x:e.clientX,y:e.clientY},r=_I(t,this.props.dimension);this.openContextMenu(n,r)}openContextMenu(e,t){this.menu.isOpen=!0,this.menu.position=e,this.menu.menuItems=t}closeMenu(){this.menu.isOpen=!1,this.menu.position=null,this.menu.menuItems=[]}get groupComponent(){return this.props.dimension===`ROW`?EB:DB}get hasFrozenPane(){let e=this.env.model.getters.getMainViewportCoordinates();return this.props.dimension===`COL`?e.x>0:e.y>0}get scrollContainerStyle(){let{scrollX:e,scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo(),n={};return this.props.dimension===`COL`?n.left=`${-e-this.frozenPaneContainerSize}px`:n.top=`${-t-this.frozenPaneContainerSize}px`,U(n)}get frozenPaneContainerStyle(){let e={};return this.props.dimension===`COL`?e.width=`${this.frozenPaneContainerSize}px`:e.height=`${this.frozenPaneContainerSize}px`,U(e)}get frozenPaneContainerSize(){if(!this.hasFrozenPane)return 0;let e=this.env.model.getters.getMainViewportCoordinates();return this.props.dimension===`COL`?48+e.x:26+e.y}};H`
2057
+ `;var DB=class extends t.Component{static template=`o-spreadsheet-HeaderGroupContainer`;static props={dimension:String,layers:Array};static components={RowGroup:TB,ColGroup:EB,Menu:pk};menu=(0,t.useState)({isOpen:!1,position:null,menuItems:[]});getLayerOffset(e){return e*21}onContextMenu(e){let t=this.env.model.getters.getActiveSheetId(),n={x:e.clientX,y:e.clientY},r=gI(t,this.props.dimension);this.openContextMenu(n,r)}openContextMenu(e,t){this.menu.isOpen=!0,this.menu.position=e,this.menu.menuItems=t}closeMenu(){this.menu.isOpen=!1,this.menu.position=null,this.menu.menuItems=[]}get groupComponent(){return this.props.dimension===`ROW`?TB:EB}get hasFrozenPane(){let e=this.env.model.getters.getMainViewportCoordinates();return this.props.dimension===`COL`?e.x>0:e.y>0}get scrollContainerStyle(){let{scrollX:e,scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo(),n={};return this.props.dimension===`COL`?n.left=`${-e-this.frozenPaneContainerSize}px`:n.top=`${-t-this.frozenPaneContainerSize}px`,U(n)}get frozenPaneContainerStyle(){let e={};return this.props.dimension===`COL`?e.width=`${this.frozenPaneContainerSize}px`:e.height=`${this.frozenPaneContainerSize}px`,U(e)}get frozenPaneContainerSize(){if(!this.hasFrozenPane)return 0;let e=this.env.model.getters.getMainViewportCoordinates();return this.props.dimension===`COL`?48+e.x:26+e.y}};H`
2058
2058
  .o-sidePanel {
2059
2059
  display: flex;
2060
2060
  flex-direction: column;
@@ -2156,7 +2156,7 @@ stores.inject(MyMetaStore, storeInstance);
2156
2156
  .o-fw-bold {
2157
2157
  font-weight: 500;
2158
2158
  }
2159
- `;var kB=class extends t.Component{static template=`o-spreadsheet-SidePanel`;static props={};sidePanelStore;spreadsheetRect=rE();setup(){this.sidePanelStore=V(yL),(0,t.useEffect)(e=>{e||this.sidePanelStore.close()},()=>[this.sidePanelStore.isOpen])}get panel(){return pI.get(this.sidePanelStore.componentTag)}close(){this.sidePanelStore.close()}getTitle(){let e=this.panel;return typeof e.title==`function`?e.title(this.env,this.sidePanelStore.panelProps):e.title}startHandleDrag(e){let t=document.body.style.cursor,n=this.sidePanelStore.panelSize,r=e.clientX;RN(e=>{document.body.style.cursor=`col-resize`;let t=n+r-e.clientX;this.sidePanelStore.changePanelSize(t,this.spreadsheetRect.width)},()=>{document.body.style.cursor=t})}};H`
2159
+ `;var OB=class extends t.Component{static template=`o-spreadsheet-SidePanel`;static props={};sidePanelStore;spreadsheetRect=rE();setup(){this.sidePanelStore=V(vL),(0,t.useEffect)(e=>{e||this.sidePanelStore.close()},()=>[this.sidePanelStore.isOpen])}get panel(){return fI.get(this.sidePanelStore.componentTag)}close(){this.sidePanelStore.close()}getTitle(){let e=this.panel;return typeof e.title==`function`?e.title(this.env,this.sidePanelStore.panelProps):e.title}startHandleDrag(e){let t=document.body.style.cursor,n=this.sidePanelStore.panelSize,r=e.clientX;RN(e=>{document.body.style.cursor=`col-resize`;let t=n+r-e.clientX;this.sidePanelStore.changePanelSize(t,this.spreadsheetRect.width)},()=>{document.body.style.cursor=t})}};H`
2160
2160
  .o-menu-item-button {
2161
2161
  display: flex;
2162
2162
  justify-content: center;
@@ -2170,7 +2170,7 @@ stores.inject(MyMetaStore, storeInstance);
2170
2170
  opacity: 0.6;
2171
2171
  cursor: default;
2172
2172
  }
2173
- `;var AB=class 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=m(this.props.action);setup(){(0,t.onWillUpdateProps)(e=>{e.action!==this.props.action&&(this.actionButton=m(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(){let 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?U({"border-bottom":`4px solid ${this.props.selectedColor}`,height:`16px`,"margin-top":`2px`}):``}};let jB=[[[`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`]]];H`
2173
+ `;var kB=class 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=m(this.props.action);setup(){(0,t.onWillUpdateProps)(e=>{e.action!==this.props.action&&(this.actionButton=m(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(){let 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?U({"border-bottom":`4px solid ${this.props.selectedColor}`,height:`16px`,"margin-top":`2px`}):``}};let AB=[[[`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`]]];H`
2174
2174
  .o-border-selector {
2175
2175
  padding: 4px;
2176
2176
  background-color: white;
@@ -2242,7 +2242,7 @@ stores.inject(MyMetaStore, storeInstance);
2242
2242
  height: 25px !important;
2243
2243
  }
2244
2244
  }
2245
- `;var MB=class 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:VN,Popover:lk};BORDER_POSITIONS=jB;lineStyleButtonRef=(0,t.useRef)(`lineStyleButton`);borderStyles=Zi;state=(0,t.useState)({activeTool:void 0});toggleDropdownTool(e){let 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:`BottomLeft`,verticalOffset:0}}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:`BottomLeft`,verticalOffset:0}}get lineStylePickerAnchorRect(){let e=this.lineStyleButtonRef.el;if(e===null)return{x:0,y:0,width:0,height:0};let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}},NB=class extends t.Component{static template=`o-spreadsheet-BorderEditorWidget`;static props={toggleBorderEditor:Function,showBorderEditor:Boolean,disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={BorderEditor:MB};borderEditorButtonRef=(0,t.useRef)(`borderEditorButton`);state=(0,t.useState)({currentColor:Be.color,currentStyle:Be.style,currentPosition:void 0});get borderEditorAnchorRect(){let 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()}updateBorder(){this.state.currentPosition!==void 0&&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}})}};H`
2245
+ `;var jB=class 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:VN,Popover:lk};BORDER_POSITIONS=AB;lineStyleButtonRef=(0,t.useRef)(`lineStyleButton`);borderStyles=Zi;state=(0,t.useState)({activeTool:void 0});toggleDropdownTool(e){let 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:`BottomLeft`,verticalOffset:0}}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:`BottomLeft`,verticalOffset:0}}get lineStylePickerAnchorRect(){let e=this.lineStyleButtonRef.el;if(e===null)return{x:0,y:0,width:0,height:0};let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}},MB=class extends t.Component{static template=`o-spreadsheet-BorderEditorWidget`;static props={toggleBorderEditor:Function,showBorderEditor:Boolean,disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={BorderEditor:jB};borderEditorButtonRef=(0,t.useRef)(`borderEditorButton`);state=(0,t.useState)({currentColor:Be.color,currentStyle:Be.style,currentPosition:void 0});get borderEditorAnchorRect(){let 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()}updateBorder(){this.state.currentPosition!==void 0&&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}})}};H`
2246
2246
  .o-topbar-composer {
2247
2247
  height: fit-content;
2248
2248
  margin-top: -1px;
@@ -2261,7 +2261,7 @@ stores.inject(MyMetaStore, storeInstance);
2261
2261
  .user-select-text {
2262
2262
  user-select: text;
2263
2263
  }
2264
- `;var PB=class extends t.Component{static template=`o-spreadsheet-TopBarComposer`;static props={};static components={Composer:vE};composerFocusStore;composerStore;composerInterface;setup(){this.composerFocusStore=V(_d);let e=V(EI);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 composerStyle(){let e={padding:`5px 0px 5px 8px`,"max-height":`100px`,"line-height":`24px`};return e.height=this.focus===`inactive`?`34px`:`fit-content`,U(e)}get containerStyle(){return this.focus===`inactive`?U({"border-color":de,"border-right":`none`}):U({"border-color":ae,"z-index":`30`})}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}};H`
2264
+ `;var NB=class extends t.Component{static template=`o-spreadsheet-TopBarComposer`;static props={};static components={Composer:vE};composerFocusStore;composerStore;composerInterface;setup(){this.composerFocusStore=V(_d);let e=V(TI);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 composerStyle(){let e={padding:`5px 0px 5px 8px`,"max-height":`100px`,"line-height":`24px`};return e.height=this.focus===`inactive`?`34px`:`fit-content`,U(e)}get containerStyle(){return this.focus===`inactive`?U({"border-color":de,"border-right":`none`}):U({"border-color":ae,"z-index":`30`})}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}};H`
2265
2265
  .o-font-size-editor {
2266
2266
  height: calc(100% - 4px);
2267
2267
  input.o-font-size {
@@ -2278,7 +2278,7 @@ stores.inject(MyMetaStore, storeInstance);
2278
2278
  background-color: rgba(0, 0, 0, 0.08);
2279
2279
  }
2280
2280
  }
2281
- `;var FB=class extends t.Component{static template=`o-spreadsheet-FontSizeEditor`;static props={onToggle:Function,dropdownStyle:String,class:String};static components={};fontSizes=Xe;dropdown=(0,t.useState)({isOpen:!1});inputRef=(0,t.useRef)(`inputFontSize`);rootEditorRef=(0,t.useRef)(`FontSizeEditor`);setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0})}onExternalClick(e){JT(this.rootEditorRef.el,e)||this.closeFontList()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||Re}toggleFontList(){this.dropdown.isOpen?this.closeFontList():(this.props.onToggle(),this.inputRef.el.focus())}closeFontList(){this.dropdown.isOpen=!1}setSize(e){let t=b(Math.floor(parseFloat(e)),1,400);Sk(this.env,{fontSize:t}),this.closeFontList()}setSizeFromInput(e){this.setSize(e.target.value)}setSizeFromList(e){this.setSize(e)}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if(e.key===`Enter`||e.key===`Escape`){this.closeFontList();let t=e.target;e.key===`Escape`&&(t.value=`${this.currentFontSize}`),this.props.onToggle()}}},IB=class extends t.Component{static template=`o-spreadsheet-TableDropdownButton`;static components={TableStylesPopover:cI,ActionButton:AB};static props={};state=(0,t.useState)({popoverProps:void 0});onStylePicked(e){let t=this.env.model.getters.getActiveSheetId(),n={...this.tableConfig,styleId:e};bk(this.env,t,n).isSuccessful&&this.env.openSidePanel(`TableSidePanel`,{}),this.closePopover()}onClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps){this.closePopover();return}if(this.env.model.getters.getFirstTableInSelection()){this.env.toggleSidePanel(`TableSidePanel`,{});return}let{bottom:t,left:n}=e.currentTarget.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:n,y:t,width:0,height:0},positioning:`BottomLeft`,verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}get action(){return{name:e=>this.env.model.getters.getFirstTableInSelection()?E(`Edit table`):E(`Insert table`),icon:e=>this.env.model.getters.getFirstTableInSelection()?`o-spreadsheet-Icon.EDIT_TABLE`:`o-spreadsheet-Icon.PAINT_TABLE`}}get tableConfig(){return{...Om,numberOfHeaders:1,bandedRows:!0}}},LB=class extends t.Component{static template=`o-spreadsheet-PaintFormatButton`;static props={class:{type:String,optional:!0}};paintFormatStore;setup(){this.paintFormatStore=V(QI)}get isActive(){return this.paintFormatStore.isActive}onDblClick(){this.paintFormatStore.activate({persistent:!0})}togglePaintFormat(){this.isActive?this.paintFormatStore.cancel():this.paintFormatStore.activate({persistent:!1})}};H`
2281
+ `;var PB=class extends t.Component{static template=`o-spreadsheet-FontSizeEditor`;static props={onToggle:Function,dropdownStyle:String,class:String};static components={};fontSizes=Xe;dropdown=(0,t.useState)({isOpen:!1});inputRef=(0,t.useRef)(`inputFontSize`);rootEditorRef=(0,t.useRef)(`FontSizeEditor`);setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0})}onExternalClick(e){JT(this.rootEditorRef.el,e)||this.closeFontList()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||Re}toggleFontList(){this.dropdown.isOpen?this.closeFontList():(this.props.onToggle(),this.inputRef.el.focus())}closeFontList(){this.dropdown.isOpen=!1}setSize(e){let t=b(Math.floor(parseFloat(e)),1,400);Sk(this.env,{fontSize:t}),this.closeFontList()}setSizeFromInput(e){this.setSize(e.target.value)}setSizeFromList(e){this.setSize(e)}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if(e.key===`Enter`||e.key===`Escape`){this.closeFontList();let t=e.target;e.key===`Escape`&&(t.value=`${this.currentFontSize}`),this.props.onToggle()}}},FB=class extends t.Component{static template=`o-spreadsheet-TableDropdownButton`;static components={TableStylesPopover:sI,ActionButton:kB};static props={};state=(0,t.useState)({popoverProps:void 0});onStylePicked(e){let t=this.env.model.getters.getActiveSheetId(),n={...this.tableConfig,styleId:e};bk(this.env,t,n).isSuccessful&&this.env.openSidePanel(`TableSidePanel`,{}),this.closePopover()}onClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps){this.closePopover();return}if(this.env.model.getters.getFirstTableInSelection()){this.env.toggleSidePanel(`TableSidePanel`,{});return}let{bottom:t,left:n}=e.currentTarget.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:n,y:t,width:0,height:0},positioning:`BottomLeft`,verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}get action(){return{name:e=>this.env.model.getters.getFirstTableInSelection()?E(`Edit table`):E(`Insert table`),icon:e=>this.env.model.getters.getFirstTableInSelection()?`o-spreadsheet-Icon.EDIT_TABLE`:`o-spreadsheet-Icon.PAINT_TABLE`}}get tableConfig(){return{...Om,numberOfHeaders:1,bandedRows:!0}}},IB=class extends t.Component{static template=`o-spreadsheet-PaintFormatButton`;static props={class:{type:String,optional:!0}};paintFormatStore;setup(){this.paintFormatStore=V(ZI)}get isActive(){return this.paintFormatStore.isActive}onDblClick(){this.paintFormatStore.activate({persistent:!0})}togglePaintFormat(){this.isActive?this.paintFormatStore.cancel():this.paintFormatStore.activate({persistent:!1})}};H`
2282
2282
  .o-spreadsheet-topbar {
2283
2283
  line-height: 1.2;
2284
2284
  font-size: 13px;
@@ -2363,7 +2363,7 @@ stores.inject(MyMetaStore, storeInstance);
2363
2363
  }
2364
2364
  }
2365
2365
  }
2366
- `;var RB=class extends t.Component{static template=`o-spreadsheet-TopBar`;static props={onClick:Function,dropdownMaxHeight:Number};get dropdownStyle(){return`max-height:${this.props.dropdownMaxHeight}px`}static components={ColorPickerWidget:VN,ColorPicker:BN,Menu:pk,TopBarComposer:PB,FontSizeEditor:FB,ActionButton:AB,PaintFormatButton:LB,BorderEditorWidget:NB,TableDropdownButton:IB};state=(0,t.useState)({menuState:{isOpen:!1,position:null,menuItems:[]},activeTool:``,fillColor:`#ffffff`,textColor:`#000000`});isSelectingMenu=!1;openedEl=null;menus=[];EDIT=uA;FORMAT=Mj;DATA=bj;formatNumberMenuItemSpec=hN;isntToolbarMenu=!1;composerFocusStore;setup(){this.composerFocusStore=V(_d),(0,t.useExternalListener)(window,`click`,this.onExternalClick),(0,t.onWillStart)(()=>this.updateCellState()),(0,t.onWillUpdateProps)(()=>this.updateCellState())}get topbarComponents(){return wN.getAllOrdered().filter(e=>!e.isVisible||e.isVisible(this.env))}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)}toggleDropdownTool(e,t){let n=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=n?``:e,this.openedEl=n?null:t.target}toggleContextMenu(e,t){this.state.menuState.isOpen&&this.isntToolbarMenu?this.closeMenus():(this.openMenu(e,t),this.isntToolbarMenu=!0)}toggleToolbarContextMenu(e,t){if(this.state.menuState.isOpen&&!this.isntToolbarMenu)this.closeMenus();else{let n=m(e);this.openMenu(n,t),this.isntToolbarMenu=!1}}openMenu(e,t){let{left:n,top:r,height:i}=t.currentTarget.getBoundingClientRect();this.state.activeTool=``,this.state.menuState.isOpen=!0,this.state.menuState.position={x:n,y:r+i},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.state.activeTool=``,this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){let e=this.env.model.getters.getCurrentStyle();this.state.fillColor=e.fillColor||`#ffffff`,this.state.textColor=e.textColor||`#000000`,this.menus=SN.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){Sk(this.env,{[e]:t}),this.onClick()}};function zB(){return new BB(navigator.clipboard)}var BB=class{clipboard;constructor(e){this.clipboard=e}async write(e){if(this.clipboard?.write)try{await this.clipboard?.write(this.getClipboardItems(e))}catch{try{await this.clipboard?.write([new ClipboardItem({"text/plain":this.getBlob(e,`text/plain`),"text/html":this.getBlob(e,`text/html`)})])}catch{}}else await this.writeText(e[`text/plain`]??``)}async writeText(e){try{this.clipboard?.writeText(e)}catch{}}async read(){let e;try{e=await navigator.permissions.query({name:`clipboard-read`})}catch{}if(this.clipboard?.read)try{let e=await this.clipboard.read(),t={};for(let n of e)for(let e of n.types)t[e]=await(await n.getType(e)).text();return{status:`ok`,content:t}}catch{return{status:e?.state===`denied`?`permissionDenied`:`notImplemented`}}else return{status:`ok`,content:{"text/plain":await this.clipboard?.readText()}}}getClipboardItems(e){let t={"text/plain":this.getBlob(e,`text/plain`),"text/html":this.getBlob(e,`text/html`)};return[new ClipboardItem(t)]}getBlob(e,t){return new Blob([e[t]||``],{type:t})}};H`
2366
+ `;var LB=class extends t.Component{static template=`o-spreadsheet-TopBar`;static props={onClick:Function,dropdownMaxHeight:Number};get dropdownStyle(){return`max-height:${this.props.dropdownMaxHeight}px`}static components={ColorPickerWidget:VN,ColorPicker:BN,Menu:pk,TopBarComposer:NB,FontSizeEditor:PB,ActionButton:kB,PaintFormatButton:IB,BorderEditorWidget:MB,TableDropdownButton:FB};state=(0,t.useState)({menuState:{isOpen:!1,position:null,menuItems:[]},activeTool:``,fillColor:`#ffffff`,textColor:`#000000`});isSelectingMenu=!1;openedEl=null;menus=[];EDIT=uA;FORMAT=Mj;DATA=bj;formatNumberMenuItemSpec=hN;isntToolbarMenu=!1;composerFocusStore;setup(){this.composerFocusStore=V(_d),(0,t.useExternalListener)(window,`click`,this.onExternalClick),(0,t.onWillStart)(()=>this.updateCellState()),(0,t.onWillUpdateProps)(()=>this.updateCellState())}get topbarComponents(){return wN.getAllOrdered().filter(e=>!e.isVisible||e.isVisible(this.env))}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)}toggleDropdownTool(e,t){let n=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=n?``:e,this.openedEl=n?null:t.target}toggleContextMenu(e,t){this.state.menuState.isOpen&&this.isntToolbarMenu?this.closeMenus():(this.openMenu(e,t),this.isntToolbarMenu=!0)}toggleToolbarContextMenu(e,t){if(this.state.menuState.isOpen&&!this.isntToolbarMenu)this.closeMenus();else{let n=m(e);this.openMenu(n,t),this.isntToolbarMenu=!1}}openMenu(e,t){let{left:n,top:r,height:i}=t.currentTarget.getBoundingClientRect();this.state.activeTool=``,this.state.menuState.isOpen=!0,this.state.menuState.position={x:n,y:r+i},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.state.activeTool=``,this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){let e=this.env.model.getters.getCurrentStyle();this.state.fillColor=e.fillColor||`#ffffff`,this.state.textColor=e.textColor||`#000000`,this.menus=SN.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){Sk(this.env,{[e]:t}),this.onClick()}};function RB(){return new zB(navigator.clipboard)}var zB=class{clipboard;constructor(e){this.clipboard=e}async write(e){if(this.clipboard?.write)try{await this.clipboard?.write(this.getClipboardItems(e))}catch{try{await this.clipboard?.write([new ClipboardItem({"text/plain":this.getBlob(e,`text/plain`),"text/html":this.getBlob(e,`text/html`)})])}catch{}}else await this.writeText(e[`text/plain`]??``)}async writeText(e){try{this.clipboard?.writeText(e)}catch{}}async read(){let e;try{e=await navigator.permissions.query({name:`clipboard-read`})}catch{}if(this.clipboard?.read)try{let e=await this.clipboard.read(),t={};for(let n of e)for(let e of n.types)t[e]=await(await n.getType(e)).text();return{status:`ok`,content:t}}catch{return{status:e?.state===`denied`?`permissionDenied`:`notImplemented`}}else return{status:`ok`,content:{"text/plain":await this.clipboard?.readText()}}}getClipboardItems(e){let t={"text/plain":this.getBlob(e,`text/plain`),"text/html":this.getBlob(e,`text/html`)};return[new ClipboardItem(t)]}getBlob(e,t){return new Blob([e[t]||``],{type:t})}};H`
2367
2367
  .o-spreadsheet {
2368
2368
  position: relative;
2369
2369
  display: grid;
@@ -2605,12 +2605,12 @@ stores.inject(MyMetaStore, storeInstance);
2605
2605
  color: ${xe};
2606
2606
  }
2607
2607
  }
2608
- `;var VB=class extends t.Component{static template=`o-spreadsheet-Spreadsheet`;static props={model:Object,notifyUser:{type:Function,optional:!0},raiseError:{type:Function,optional:!0},askConfirmation:{type:Function,optional:!0}};static components={TopBar:RB,Grid:CL,BottomBar:SB,SidePanel:kB,SpreadsheetDashboard:wB,HeaderGroupContainer:OB};sidePanel;spreadsheetRef=(0,t.useRef)(`spreadsheet`);spreadsheetRect=rE();_focusGrid;keyDownMapping;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){let e={};return this.env.isDashboard()?e[`grid-template-rows`]=`auto`:e[`grid-template-rows`]=`63px auto 37px`,e[`grid-template-columns`]=`auto ${this.sidePanel.panelSize}px`,U(e)}setup(){let e=cd();e.inject(pd,this.model),this.notificationStore=V(sP),this.composerFocusStore=V(_d),this.sidePanel=V(yL),this.keyDownMapping={"CTRL+H":()=>this.sidePanel.toggle(`FindAndReplace`,{}),"CTRL+F":()=>this.sidePanel.toggle(`FindAndReplace`,{})};let n=this.model.config.external.fileStore;(0,t.useSubEnv)({model:this.model,imageProvider:n?new pB(n):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),toggleSidePanel:this.sidePanel.toggle.bind(this.sidePanel),clipboard:this.env.clipboard||zB(),startCellEdition:e=>this.composerFocusStore.focusActiveComposer({content:e}),notifyUser:e=>this.notificationStore.notifyUser(e),askConfirmation:(e,t,n)=>this.notificationStore.askConfirmation(e,t,n),raiseError:(e,t)=>this.notificationStore.raiseError(e,t)}),this.notificationStore.updateNotificationCallbacks({...this.props}),(0,t.useEffect)(()=>{!this.spreadsheetRef.el.contains(document.activeElement)&&document.activeElement?.contains(this.spreadsheetRef.el)&&this.focusGrid()}),(0,t.useExternalListener)(window,`resize`,()=>this.render(!0)),(0,t.useExternalListener)(document.body,`wheel`,()=>{}),this.bindModelEvents(),(0,t.onWillUpdateProps)(e=>{if(e.model!==this.props.model)throw Error(`Changing the props model is not supported at the moment.`);(e.notifyUser!==this.props.notifyUser||e.askConfirmation!==this.props.askConfirmation||e.raiseError!==this.props.raiseError)&&this.notificationStore.updateNotificationCallbacks({...e})});let r=wt(this.render.bind(this,!0));(0,t.onMounted)(()=>{this.checkViewportSize(),e.on(`store-updated`,this,r),i.observe(this.spreadsheetRef.el)}),(0,t.onWillUnmount)(()=>{this.unbindModelEvents(),e.off(`store-updated`,this),i.disconnect()}),(0,t.onPatched)(()=>{this.checkViewportSize()});let i=new ResizeObserver(()=>{this.sidePanel.changePanelSize(this.sidePanel.panelSize,this.spreadsheetRect.width)})}bindModelEvents(){this.model.on(`update`,this,()=>this.render(!0)),this.model.on(`notify-ui`,this,e=>this.notificationStore.notifyUser(e)),this.model.on(`raise-error-ui`,this,({text:e})=>this.notificationStore.raiseError(e))}unbindModelEvents(){this.model.off(`update`,this),this.model.off(`notify-ui`,this),this.model.off(`raise-error-ui`,this)}checkViewportSize(){let{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(!(!isFinite(e)||!isFinite(t)))if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.notificationStore.notifyUser({text:E(`The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns.`),type:`warning`,sticky:!1}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}focusGrid(){this._focusGrid&&this._focusGrid()}onKeydown(e){let t=``;nE(e)&&(t+=`CTRL+`),t+=e.key.toUpperCase();let n=this.keyDownMapping[t];if(n){e.preventDefault(),e.stopPropagation(),n();return}}get gridHeight(){let{height:e}=this.env.model.getters.getSheetViewDimension();return e}get gridContainerStyle(){let e=21*this.rowLayers.length,t=21*this.colLayers.length;return U({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`})}get rowLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`ROW`)}get colLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`COL`)}},HB=class{listeners=[];async sendMessage(e){for(let{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter(t=>t.id!==e)}};function UB(e){return yO.get(e.type)(e)}var WB=class e{buildTransformation;operations;constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){let t=this.operations.find(t=>t.id===e);if(!t)throw Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(let n of this.operations){if(n.id===e)return e;if(n.id===t)return t}throw Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find(t=>t.id===e)}prepend(e){let t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map(e=>e.transformed(t))]}insert(e,t){let n=this.buildTransformation.with(e.data),{before:r,operation:i,after:a}=this.locateOperation(t);this.operations=[...r,i,e,...a.map(e=>e.transformed(n))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(t){let{after:n}=this.locateOperation(t);return new e(this.buildTransformation,n)}transform(e){this.operations=this.operations.map(t=>t.transformed(e))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){let{before:t,operation:n}=this.locateOperation(e);this.operations=t.concat([n])}locateOperation(e){let t=this.operations.findIndex(t=>t.id===e);if(t===-1)throw Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}},GB=class{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new KB(this.id,Et(()=>e(this.data)))}},KB=class e{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(t){return new e(this.id,this.lazyData.map(t))}},qB=class e{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(t){function*n(e,t){for(let n of e)if(yield n,n.operation.id===t)return}return new e(n(this.operations,t))}stopBefore(t){function*n(e,t){for(let n of e){if(n.operation.id===t)return;yield n}}return new e(n(this.operations,t))}startAfter(t){function*n(e,t){let n=!0;for(let r of e)n||(yield r),r.operation.id===t&&(n=!1)}return new e(n(this.operations,t))}},JB=class{buildTransformation;branches;branchingOperationIds=new Map;constructor(e,t){this.buildTransformation=e,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new qB(lt(this._execution(e),this._execution(e)))}revertedExecution(e){return new qB(lt(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){let n=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),n&&this.insertPrevious(e,t,n)}insertOperationAfter(e,t,n){e.insert(t,n),this.updateNextWith(e,t,n),this.insertPrevious(e,t,n)}undo(e,t){let n=this.buildTransformation.without(t.data),r=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);let i=e.fork(t.id);r&&this.branchingOperationIds.set(i,r),this.insertBranchAfter(e,i),this.transform(i,n)}redo(e){let t=this.nextBranch(e);if(!t)return;let n=this.nextBranch(t);this.removeBranchFromTree(t);let r=this.branchingOperationIds.get(t);r?this.branchingOperationIds.set(e,r):this.branchingOperationIds.delete(e),n&&this.rebaseUp(n)}drop(e){for(let t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(let n of this.revertedExecution(e))if(n.operation.id===t)return n;throw Error(`Operation ${t} not found`)}rebaseUp(e){let{previousBranch:t,branchingOperation:n}=this.findPreviousBranchingOperation(e);if(!t||!n)return;let r=this.buildTransformation.without(n.data),i=t.fork(n.id);this.branchingOperationIds.set(i,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,i),i.transform(r);let a=this.nextBranch(i);a&&this.rebaseUp(a)}removeBranchFromTree(e){let t=this.branches.findIndex(t=>t===e);this.branches.splice(t,1)}insertBranchAfter(e,t){let n=this.branches.findIndex(t=>t===e);this.branches.splice(n+1,0,t)}updateNextWith(e,t,n){let r=this.branchingOperationIds.get(e),i=this.nextBranch(e);if(!(!r||!i))if(e.getFirstOperationAmong(n,r)===r){let a=this.addToNextBranch(e,i,r,t,n);this.updateNextWith(i,a,n)}else{let e=this.buildTransformation.with(t.data);this.transform(i,e)}}addToNextBranch(e,t,n,r,i){let a=r;return i===n?(a=this.getTransformedOperation(e,n,r),t.prepend(a)):t.contains(i)?(a=this.getTransformedOperation(e,n,r),t.insert(a,i)):t.append(r),a}getTransformedOperation(e,t,n){let r=e.getOperation(t),i=this.buildTransformation.without(r.data);return n.transformed(i)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);let n=this.nextBranch(e);n&&this.transform(n,t)}insertPrevious(e,t,n){let{previousBranch:r,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!r||!i)return;let a=this.buildTransformation.with(i.data),o=e.fork(n);o.transform(a),r.cutAfter(n),r.appendBranch(o);let s=t.transformed(a);this.insertPrevious(r,s,n)}findPreviousBranchingOperation(e){let t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};let n=this.branchingOperationIds.get(t);return n?{previousBranch:t,branchingOperation:t.getOperation(n)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){let t=this.branches.findIndex(t=>t===e);if(t!==-1)return this.branches[t+1]}previousBranch(e){let t=this.branches.findIndex(t=>t===e);if(t!==-1)return this.branches[t-1]}*_revertedExecution(e){let t=this.branchingOperationIds.get(e),n=!!t,r=e.getOperations();for(let i=r.length-1;i>=0;i--){let a=r[i];a.id===t&&(n=!1),n||(yield{operation:a,branch:e,isCancelled:!this.shouldExecute(e,a)})}let i=this.previousBranch(e);yield*i?this._revertedExecution(i):[]}*_execution(e){for(let t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){let t=this.nextBranch(e);yield*t?this._execution(t):[];return}if(!this.branchingOperationIds.get(e)){let t=this.nextBranch(e);yield*t?this._execution(t):[]}}},YB=class{HEAD_BRANCH;HEAD_OPERATION;tree;applyOperation;revertOperation;buildEmpty;buildTransformation;constructor(e){this.applyOperation=e.applyOperation,this.revertOperation=e.revertOperation,this.buildEmpty=e.buildEmpty,this.buildTransformation=e.buildTransformation,this.HEAD_BRANCH=new WB(this.buildTransformation),this.tree=new JB(this.buildTransformation,this.HEAD_BRANCH);let t=e.initialOperationId,n=new GB(t,this.buildEmpty(t));this.tree.insertOperationLast(this.HEAD_BRANCH,n),this.HEAD_OPERATION=n}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){let n=new GB(e,t),r=this.tree.getLastBranch();this.tree.insertOperationLast(r,n),this.HEAD_BRANCH=r,this.HEAD_OPERATION=n}insert(e,t,n){let r=new GB(e,t);this.revertTo(n),this.tree.insertOperationAfter(this.HEAD_BRANCH,r,n),this.fastForward()}undo(e,t,n){let{branch:r,operation:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(r,i),this.fastForward(),this.insert(t,this.buildEmpty(t),n)}redo(e,t,n){let{branch:r}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(r),this.fastForward(),this.insert(t,this.buildEmpty(t),n)}rebase(e){let t=this.get(e),n=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);let r=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,r);for(let{operation:e}of n)this.insert(e.id,e.data,this.HEAD_OPERATION.id)}revertBefore(e){let t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){let t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(let{next:t,operation:n,isCancelled:r}of e)r||this.revertOperation(n.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){let e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(let{operation:t,branch:n,isCancelled:r}of e)r||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=n}};function XB(e){return new YB({initialOperationId:e.initialRevisionId,applyOperation:t=>{let n=t.commands.slice(),{changes:r}=e.recordChanges(()=>{for(let t of n)e.dispatch(t)});t.setChanges(r)},revertOperation:e=>ZB([e]),buildEmpty:e=>new sz(e,`empty`,[]),buildTransformation:{with:e=>t=>new sz(t.id,t.clientId,ZR(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new sz(t.id,t.clientId,ZR(t.commands,e.commands.map(UB).flat()),t.rootCommand,void 0,t.timestamp)}})}function ZB(e){for(let t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){let n=t.changes[e];QB(n)}}function QB(e){let t=e.target,n=e.key,r=e.before;r===void 0?delete t[n]:t[n]=r}var $B=class{observers=new Map;defaultSubscription;mainSubscription;registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||=this.defaultSubscription}observe(e,t){this.observers.set(e,{owner:e,callbacks:t})}detachObserver(e){this.observers.delete(e)}capture(e,t){if(this.observers.get(e))throw Error(`You are already subscribed forever`);this.mainSubscription?.owner&&this.mainSubscription.owner!==e&&this.mainSubscription.callbacks.release?.(),this.mainSubscription={owner:e,callbacks:t}}release(e){this.mainSubscription?.owner!==e||this.observers.get(e)||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){this.mainSubscription!==this.defaultSubscription&&(this.mainSubscription?.callbacks.release?.(),this.mainSubscription=this.defaultSubscription)}isListening(e){return this.mainSubscription?.owner===e}send(e){this.mainSubscription?.callbacks.handleEvent(e),this.observers.forEach(t=>t.callbacks.handleEvent(e))}},eV=class{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new $B,this.anchor={cell:{col:0,row:0},zone:D({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,n){this.stream.capture(e,n),this.anchor=t}registerAsDefault(e,t,n){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,n),this.defaultAnchor=t,this.capture(e,t,n)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}detachObserver(e){this.stream.detachObserver(e)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}modifyAnchor(e,t,n){let r=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(r,e.zone)},this.processEvent({options:n,anchor:e,mode:t})}selectZone(e,t={scrollIntoView:!0}){return this.modifyAnchor(e,`overrideSelection`,t)}selectCell(e,t){let n=D({col:e,row:t});return this.selectZone({zone:n,cell:{col:e,row:t}},{scrollIntoView:!0})}moveAnchorCell(e,t=1){if(t!==`end`&&t<=0)return new qi(`InvalidSelectionStep`);let{col:n,row:r}=this.getNextAvailablePosition(e,t);return this.selectCell(n,r)}setAnchorCorner(e,t){let n=this.getters.getActiveSheetId(),{col:r,row:i}=this.anchor.cell,a={left:Math.min(r,e),top:Math.min(i,t),right:Math.max(r,e),bottom:Math.max(i,t)},o={zone:this.getters.expandZone(n,a),cell:{col:r,row:i}};return this.processEvent({mode:`updateAnchor`,anchor:o,options:{scrollIntoView:!1}})}addCellToSelection(e,t){let n=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:n,col:e,row:t}));let r=this.getters.expandZone(n,D({col:e,row:t}));return this.processEvent({options:{scrollIntoView:!0},anchor:{zone:r,cell:{col:e,row:t}},mode:`newAnchor`})}resizeAnchorZone(e,t=1){if(t!==`end`&&t<=0)return new qi(`InvalidSelectionStep`);let n=this.getters.getActiveSheetId(),r=this.anchor,{col:i,row:a}=r.cell,{left:o,right:s,top:c,bottom:l}=r.zone,u=this.getStartingPosition(e),[d,f]=this.deltaToTarget(u,e,t);if(d===0&&f===0)return qi.Success;let p=r.zone,m=e=>{e=vr(e);let{left:t,right:r,top:i,bottom:a}=this.getters.expandZone(n,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(n)-1,r),top:Math.max(0,i),bottom:Math.min(this.getters.getNumberRows(n)-1,a)}},{cell:h,zone:g}=this.getReferenceAnchor(),{col:_,row:v}=h,ee=0;for(;p!==null;){if(ee++,d<0){let e=this.getNextAvailableCol(d,s-(ee-1),v);p=g.right<=s-ee?m({top:c,left:o,bottom:l,right:e}):null}if(d>0){let e=this.getNextAvailableCol(d,o+(ee-1),v);p=o+ee<=g.left?m({top:c,left:e,bottom:l,right:s}):null}if(f<0){let e=this.getNextAvailableRow(f,_,l-(ee-1));p=g.bottom<=l-ee?m({top:c,left:o,bottom:e,right:s}):null}if(f>0){let e=this.getNextAvailableRow(f,_,c+(ee-1));p=c+ee<=g.top?m({top:e,left:o,bottom:l,right:s}):null}if(p&&=vr(p),p&&!lr(p,r.zone))return this.processEvent({options:{scrollIntoView:!0},mode:`updateAnchor`,anchor:{zone:p,cell:{col:i,row:a}}})}p=m(or({top:a,bottom:a,left:i,right:i},vr({top:this.getNextAvailableRow(f,_,c),left:this.getNextAvailableCol(d,o,v),bottom:this.getNextAvailableRow(f,_,l),right:this.getNextAvailableCol(d,s,v)})));let te={zone:p,cell:{col:i,row:a}};return this.processEvent({anchor:te,mode:`updateAnchor`,options:{scrollIntoView:!0}})}selectColumn(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getNumberRows(n)-1,i={left:e,right:e,top:0,bottom:r},a=this.getters.findFirstVisibleColRowIndex(n,`ROW`),o,s;switch(t){case`overrideSelection`:case`newAnchor`:o=e,s=a;break;case`updateAnchor`:({col:o,row:s}=this.anchor.cell),i=or(i,{left:o,right:o,top:a,bottom:r});break}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:o,row:s}},mode:t})}selectRow(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getNumberCols(n)-1,i={top:e,bottom:e,left:0,right:r},a=this.getters.findFirstVisibleColRowIndex(n,`COL`),o,s;switch(t){case`overrideSelection`:case`newAnchor`:o=a,s=e;break;case`updateAnchor`:({col:o,row:s}=this.anchor.cell),i=or(i,{left:a,right:r,top:s,bottom:s});break}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:o,row:s}},mode:t})}loopSelection(){let e=this.getters.getActiveSheetId(),t=this.anchor;if(lr(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:D(t.cell)},`updateAnchor`,{scrollIntoView:!1});let n=this.getters.getContiguousZone(e,t.zone);return C(n,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:n},`updateAnchor`,{scrollIntoView:!1})}selectTableAroundSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getContiguousZone(e,this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:t},`updateAnchor`,{scrollIntoView:!1})}selectAll(){let e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({mode:`overrideSelection`,anchor:{zone:t,cell:this.anchor.cell},options:{scrollIntoView:!1}})}isListening(e){return this.stream.isListening(e)}processEvent(e){let t={...e,previousAnchor:y(this.anchor)},n=this.checkEventAnchorZone(t);return n===`Success`?(this.anchor=t.anchor,this.stream.send(t),qi.Success):new qi(n)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){let{cell:t,zone:n}=e;if(!dr(t.col,t.row,n))return`InvalidAnchorZone`;let{left:r,right:i,top:a,bottom:o}=n,s=this.getters.getActiveSheetId(),c=this.getters.findVisibleHeader(s,`COL`,r,i);return this.getters.findVisibleHeader(s,`ROW`,a,o)===void 0||c===void 0?`SelectionOutOfBound`:`Success`}checkAnchorZoneOrThrow(e){if(this.checkAnchorZone(e)===`InvalidAnchorZone`)throw Error(E(`The provided anchor is invalid. The cell must be part of the zone.`))}getNextAvailablePosition(e,t=1){let{col:n,row:r}=this.anchor.cell,i=this.deltaToTarget({col:n,row:r},e,t);return{col:this.getNextAvailableCol(i[0],n,r),row:this.getNextAvailableRow(i[1],n,r)}}getNextAvailableCol(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`COL`,t,i,e=>this.getters.isInSameMerge(r,t,n,e,n))}getNextAvailableRow(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`ROW`,n,i,e=>this.getters.isInSameMerge(r,t,n,t,e))}getNextAvailableHeader(e,t,n,r,i){let a=this.getters.getActiveSheetId();if(e===0)return n;let o=Math.sign(e),s=n+e;for(;i(s);)s+=o;for(;this.getters.isHeaderHidden(a,t,s);)s+=o;return s<0||s>this.getters.getNumberHeaders(a,t)-1?this.getters.isHeaderHidden(a,t,n)?this.getNextAvailableHeader(-o,t,n,r,i):n:s}getReferenceAnchor(){let e=this.getters.getActiveSheetId(),t=this.anchor,{left:n,right:r,top:i,bottom:a}=t.zone,{col:o,row:s}=t.cell,c=this.getters.isColHidden(e,o)&&this.getters.findVisibleHeader(e,`COL`,n,r)||o,l=this.getters.isRowHidden(e,s)&&this.getters.findVisibleHeader(e,`ROW`,i,a)||s,u=this.getters.expandZone(e,{left:c,right:c,top:l,bottom:l});return{cell:{col:c,row:l},zone:u}}deltaToTarget(e,t,n){switch(t){case`up`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,-1)-e.row]:[0,-n];case`down`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,1)-e.row]:[0,n];case`left`:return n===`end`?[this.getEndOfCluster(e,`cols`,-1)-e.col,0]:[-n,0];case`right`:return n===`end`?[this.getEndOfCluster(e,`cols`,1)-e.col,0]:[n,0]}}getStartingPosition(e){let{col:t,row:n}=this.getPosition(),r=this.anchor.zone;switch(e){case`down`:case`up`:n=n===r.top?r.bottom:r.top;break;case`left`:case`right`:t=t===r.right?r.left:r.right;break}return{col:t,row:n}}getEndOfCluster(e,t,n){let r=this.getters.getActiveSheetId(),i=e,a=this.getNextCellPosition(e,t,n),o=!this.isCellSkippableInCluster({...i,sheetId:r})&&!this.isCellSkippableInCluster({...a,sheetId:r})?`endOfCluster`:`nextCluster`;for(;;){let e=this.getNextCellPosition(i,t,n);if(i.col===e.col&&i.row===e.row)break;let a=this.isCellSkippableInCluster({...e,sheetId:r});if(o===`endOfCluster`&&a)break;if(o===`nextCluster`&&!a){i=e;break}i=e}return t===`cols`?i.col:i.row}getNextCellPosition(e,t,n){let r=t===`cols`?`col`:`row`,i={...e};return i[r]=t===`cols`?this.getNextAvailableCol(n,i.col,i.row):this.getNextAvailableRow(n,i.col,i.row),{col:i.col,row:i.row}}getPosition(){return{...this.anchor.cell}}isCellSkippableInCluster(e){let t=this.getters.getMainCellPosition(e),n=this.getters.getEvaluatedCell(t);return n.type===`empty`||n.type===`text`&&n.value===``}};function tV(e){if(typeof e==`string`)return{};if(typeof e==`number`)return[];throw Error(`Cannot create new node`)}var nV=class{changes;commands=[];recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){let t=e.pop(),n=e[0],r=e.at(-1),i=e.length-2;for(let t=1;t<=i;t++){let r=e[t];if(n[r]===void 0){let i=e[t+1];n[r]=tV(i)}n=n[r]}n[r]!==t&&(this.changes?.push({key:r,target:n,before:n[r]}),t===void 0?delete n[r]:n[r]=t)}};let rV=17781237,iV=17781238,aV=88853993,oV=88853994;function sV(e,t,n){let r=[[`xmlns:r`,of],[`xmlns:a`,tf],[`xmlns:c`,nf]],i=cV({backgroundColor:e.data.backgroundColor,line:{color:`000000`}}),a=J``;if(e.data.title?.text){let t=e.data.title.color?fD(e.data.title.color):e.data.fontColor;a=J`
2608
+ `;var BB=class extends t.Component{static template=`o-spreadsheet-Spreadsheet`;static props={model:Object,notifyUser:{type:Function,optional:!0},raiseError:{type:Function,optional:!0},askConfirmation:{type:Function,optional:!0}};static components={TopBar:LB,Grid:SL,BottomBar:xB,SidePanel:OB,SpreadsheetDashboard:CB,HeaderGroupContainer:DB};sidePanel;spreadsheetRef=(0,t.useRef)(`spreadsheet`);spreadsheetRect=rE();_focusGrid;keyDownMapping;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){let e={};return this.env.isDashboard()?e[`grid-template-rows`]=`auto`:e[`grid-template-rows`]=`63px auto 37px`,e[`grid-template-columns`]=`auto ${this.sidePanel.panelSize}px`,U(e)}setup(){let e=cd();e.inject(pd,this.model),this.notificationStore=V(sP),this.composerFocusStore=V(_d),this.sidePanel=V(vL),this.keyDownMapping={"CTRL+H":()=>this.sidePanel.toggle(`FindAndReplace`,{}),"CTRL+F":()=>this.sidePanel.toggle(`FindAndReplace`,{})};let n=this.model.config.external.fileStore;(0,t.useSubEnv)({model:this.model,imageProvider:n?new fB(n):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),toggleSidePanel:this.sidePanel.toggle.bind(this.sidePanel),clipboard:this.env.clipboard||RB(),startCellEdition:e=>this.composerFocusStore.focusActiveComposer({content:e}),notifyUser:e=>this.notificationStore.notifyUser(e),askConfirmation:(e,t,n)=>this.notificationStore.askConfirmation(e,t,n),raiseError:(e,t)=>this.notificationStore.raiseError(e,t)}),this.notificationStore.updateNotificationCallbacks({...this.props}),(0,t.useEffect)(()=>{!this.spreadsheetRef.el.contains(document.activeElement)&&document.activeElement?.contains(this.spreadsheetRef.el)&&this.focusGrid()}),(0,t.useExternalListener)(window,`resize`,()=>this.render(!0)),(0,t.useExternalListener)(document.body,`wheel`,()=>{}),this.bindModelEvents(),(0,t.onWillUpdateProps)(e=>{if(e.model!==this.props.model)throw Error(`Changing the props model is not supported at the moment.`);(e.notifyUser!==this.props.notifyUser||e.askConfirmation!==this.props.askConfirmation||e.raiseError!==this.props.raiseError)&&this.notificationStore.updateNotificationCallbacks({...e})});let r=wt(this.render.bind(this,!0));(0,t.onMounted)(()=>{this.checkViewportSize(),e.on(`store-updated`,this,r),i.observe(this.spreadsheetRef.el)}),(0,t.onWillUnmount)(()=>{this.unbindModelEvents(),e.off(`store-updated`,this),i.disconnect()}),(0,t.onPatched)(()=>{this.checkViewportSize()});let i=new ResizeObserver(()=>{this.sidePanel.changePanelSize(this.sidePanel.panelSize,this.spreadsheetRect.width)})}bindModelEvents(){this.model.on(`update`,this,()=>this.render(!0)),this.model.on(`notify-ui`,this,e=>this.notificationStore.notifyUser(e)),this.model.on(`raise-error-ui`,this,({text:e})=>this.notificationStore.raiseError(e))}unbindModelEvents(){this.model.off(`update`,this),this.model.off(`notify-ui`,this),this.model.off(`raise-error-ui`,this)}checkViewportSize(){let{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(!(!isFinite(e)||!isFinite(t)))if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.notificationStore.notifyUser({text:E(`The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns.`),type:`warning`,sticky:!1}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}focusGrid(){this._focusGrid&&this._focusGrid()}onKeydown(e){let t=``;nE(e)&&(t+=`CTRL+`),t+=e.key.toUpperCase();let n=this.keyDownMapping[t];if(n){e.preventDefault(),e.stopPropagation(),n();return}}get gridHeight(){let{height:e}=this.env.model.getters.getSheetViewDimension();return e}get gridContainerStyle(){let e=21*this.rowLayers.length,t=21*this.colLayers.length;return U({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`})}get rowLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`ROW`)}get colLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`COL`)}},VB=class{listeners=[];async sendMessage(e){for(let{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter(t=>t.id!==e)}};function HB(e){return yO.get(e.type)(e)}var UB=class e{buildTransformation;operations;constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){let t=this.operations.find(t=>t.id===e);if(!t)throw Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(let n of this.operations){if(n.id===e)return e;if(n.id===t)return t}throw Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find(t=>t.id===e)}prepend(e){let t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map(e=>e.transformed(t))]}insert(e,t){let n=this.buildTransformation.with(e.data),{before:r,operation:i,after:a}=this.locateOperation(t);this.operations=[...r,i,e,...a.map(e=>e.transformed(n))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(t){let{after:n}=this.locateOperation(t);return new e(this.buildTransformation,n)}transform(e){this.operations=this.operations.map(t=>t.transformed(e))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){let{before:t,operation:n}=this.locateOperation(e);this.operations=t.concat([n])}locateOperation(e){let t=this.operations.findIndex(t=>t.id===e);if(t===-1)throw Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}},WB=class{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new GB(this.id,Et(()=>e(this.data)))}},GB=class e{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(t){return new e(this.id,this.lazyData.map(t))}},KB=class e{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(t){function*n(e,t){for(let n of e)if(yield n,n.operation.id===t)return}return new e(n(this.operations,t))}stopBefore(t){function*n(e,t){for(let n of e){if(n.operation.id===t)return;yield n}}return new e(n(this.operations,t))}startAfter(t){function*n(e,t){let n=!0;for(let r of e)n||(yield r),r.operation.id===t&&(n=!1)}return new e(n(this.operations,t))}},qB=class{buildTransformation;branches;branchingOperationIds=new Map;constructor(e,t){this.buildTransformation=e,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new KB(lt(this._execution(e),this._execution(e)))}revertedExecution(e){return new KB(lt(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){let n=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),n&&this.insertPrevious(e,t,n)}insertOperationAfter(e,t,n){e.insert(t,n),this.updateNextWith(e,t,n),this.insertPrevious(e,t,n)}undo(e,t){let n=this.buildTransformation.without(t.data),r=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);let i=e.fork(t.id);r&&this.branchingOperationIds.set(i,r),this.insertBranchAfter(e,i),this.transform(i,n)}redo(e){let t=this.nextBranch(e);if(!t)return;let n=this.nextBranch(t);this.removeBranchFromTree(t);let r=this.branchingOperationIds.get(t);r?this.branchingOperationIds.set(e,r):this.branchingOperationIds.delete(e),n&&this.rebaseUp(n)}drop(e){for(let t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(let n of this.revertedExecution(e))if(n.operation.id===t)return n;throw Error(`Operation ${t} not found`)}rebaseUp(e){let{previousBranch:t,branchingOperation:n}=this.findPreviousBranchingOperation(e);if(!t||!n)return;let r=this.buildTransformation.without(n.data),i=t.fork(n.id);this.branchingOperationIds.set(i,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,i),i.transform(r);let a=this.nextBranch(i);a&&this.rebaseUp(a)}removeBranchFromTree(e){let t=this.branches.findIndex(t=>t===e);this.branches.splice(t,1)}insertBranchAfter(e,t){let n=this.branches.findIndex(t=>t===e);this.branches.splice(n+1,0,t)}updateNextWith(e,t,n){let r=this.branchingOperationIds.get(e),i=this.nextBranch(e);if(!(!r||!i))if(e.getFirstOperationAmong(n,r)===r){let a=this.addToNextBranch(e,i,r,t,n);this.updateNextWith(i,a,n)}else{let e=this.buildTransformation.with(t.data);this.transform(i,e)}}addToNextBranch(e,t,n,r,i){let a=r;return i===n?(a=this.getTransformedOperation(e,n,r),t.prepend(a)):t.contains(i)?(a=this.getTransformedOperation(e,n,r),t.insert(a,i)):t.append(r),a}getTransformedOperation(e,t,n){let r=e.getOperation(t),i=this.buildTransformation.without(r.data);return n.transformed(i)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);let n=this.nextBranch(e);n&&this.transform(n,t)}insertPrevious(e,t,n){let{previousBranch:r,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!r||!i)return;let a=this.buildTransformation.with(i.data),o=e.fork(n);o.transform(a),r.cutAfter(n),r.appendBranch(o);let s=t.transformed(a);this.insertPrevious(r,s,n)}findPreviousBranchingOperation(e){let t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};let n=this.branchingOperationIds.get(t);return n?{previousBranch:t,branchingOperation:t.getOperation(n)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){let t=this.branches.findIndex(t=>t===e);if(t!==-1)return this.branches[t+1]}previousBranch(e){let t=this.branches.findIndex(t=>t===e);if(t!==-1)return this.branches[t-1]}*_revertedExecution(e){let t=this.branchingOperationIds.get(e),n=!!t,r=e.getOperations();for(let i=r.length-1;i>=0;i--){let a=r[i];a.id===t&&(n=!1),n||(yield{operation:a,branch:e,isCancelled:!this.shouldExecute(e,a)})}let i=this.previousBranch(e);yield*i?this._revertedExecution(i):[]}*_execution(e){for(let t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){let t=this.nextBranch(e);yield*t?this._execution(t):[];return}if(!this.branchingOperationIds.get(e)){let t=this.nextBranch(e);yield*t?this._execution(t):[]}}},JB=class{HEAD_BRANCH;HEAD_OPERATION;tree;applyOperation;revertOperation;buildEmpty;buildTransformation;constructor(e){this.applyOperation=e.applyOperation,this.revertOperation=e.revertOperation,this.buildEmpty=e.buildEmpty,this.buildTransformation=e.buildTransformation,this.HEAD_BRANCH=new UB(this.buildTransformation),this.tree=new qB(this.buildTransformation,this.HEAD_BRANCH);let t=e.initialOperationId,n=new WB(t,this.buildEmpty(t));this.tree.insertOperationLast(this.HEAD_BRANCH,n),this.HEAD_OPERATION=n}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){let n=new WB(e,t),r=this.tree.getLastBranch();this.tree.insertOperationLast(r,n),this.HEAD_BRANCH=r,this.HEAD_OPERATION=n}insert(e,t,n){let r=new WB(e,t);this.revertTo(n),this.tree.insertOperationAfter(this.HEAD_BRANCH,r,n),this.fastForward()}undo(e,t,n){let{branch:r,operation:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(r,i),this.fastForward(),this.insert(t,this.buildEmpty(t),n)}redo(e,t,n){let{branch:r}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(r),this.fastForward(),this.insert(t,this.buildEmpty(t),n)}rebase(e){let t=this.get(e),n=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);let r=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,r);for(let{operation:e}of n)this.insert(e.id,e.data,this.HEAD_OPERATION.id)}revertBefore(e){let t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){let t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(let{next:t,operation:n,isCancelled:r}of e)r||this.revertOperation(n.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){let e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(let{operation:t,branch:n,isCancelled:r}of e)r||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=n}};function YB(e){return new JB({initialOperationId:e.initialRevisionId,applyOperation:t=>{let n=t.commands.slice(),{changes:r}=e.recordChanges(()=>{for(let t of n)e.dispatch(t)});t.setChanges(r)},revertOperation:e=>XB([e]),buildEmpty:e=>new oz(e,`empty`,[]),buildTransformation:{with:e=>t=>new oz(t.id,t.clientId,XR(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new oz(t.id,t.clientId,XR(t.commands,e.commands.map(HB).flat()),t.rootCommand,void 0,t.timestamp)}})}function XB(e){for(let t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){let n=t.changes[e];ZB(n)}}function ZB(e){let t=e.target,n=e.key,r=e.before;r===void 0?delete t[n]:t[n]=r}var QB=class{observers=new Map;defaultSubscription;mainSubscription;registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||=this.defaultSubscription}observe(e,t){this.observers.set(e,{owner:e,callbacks:t})}detachObserver(e){this.observers.delete(e)}capture(e,t){if(this.observers.get(e))throw Error(`You are already subscribed forever`);this.mainSubscription?.owner&&this.mainSubscription.owner!==e&&this.mainSubscription.callbacks.release?.(),this.mainSubscription={owner:e,callbacks:t}}release(e){this.mainSubscription?.owner!==e||this.observers.get(e)||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){this.mainSubscription!==this.defaultSubscription&&(this.mainSubscription?.callbacks.release?.(),this.mainSubscription=this.defaultSubscription)}isListening(e){return this.mainSubscription?.owner===e}send(e){this.mainSubscription?.callbacks.handleEvent(e),this.observers.forEach(t=>t.callbacks.handleEvent(e))}},$B=class{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new QB,this.anchor={cell:{col:0,row:0},zone:D({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,n){this.stream.capture(e,n),this.anchor=t}registerAsDefault(e,t,n){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,n),this.defaultAnchor=t,this.capture(e,t,n)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}detachObserver(e){this.stream.detachObserver(e)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}modifyAnchor(e,t,n){let r=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(r,e.zone)},this.processEvent({options:n,anchor:e,mode:t})}selectZone(e,t={scrollIntoView:!0}){return this.modifyAnchor(e,`overrideSelection`,t)}selectCell(e,t){let n=D({col:e,row:t});return this.selectZone({zone:n,cell:{col:e,row:t}},{scrollIntoView:!0})}moveAnchorCell(e,t=1){if(t!==`end`&&t<=0)return new qi(`InvalidSelectionStep`);let{col:n,row:r}=this.getNextAvailablePosition(e,t);return this.selectCell(n,r)}setAnchorCorner(e,t){let n=this.getters.getActiveSheetId(),{col:r,row:i}=this.anchor.cell,a={left:Math.min(r,e),top:Math.min(i,t),right:Math.max(r,e),bottom:Math.max(i,t)},o={zone:this.getters.expandZone(n,a),cell:{col:r,row:i}};return this.processEvent({mode:`updateAnchor`,anchor:o,options:{scrollIntoView:!1}})}addCellToSelection(e,t){let n=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:n,col:e,row:t}));let r=this.getters.expandZone(n,D({col:e,row:t}));return this.processEvent({options:{scrollIntoView:!0},anchor:{zone:r,cell:{col:e,row:t}},mode:`newAnchor`})}resizeAnchorZone(e,t=1){if(t!==`end`&&t<=0)return new qi(`InvalidSelectionStep`);let n=this.getters.getActiveSheetId(),r=this.anchor,{col:i,row:a}=r.cell,{left:o,right:s,top:c,bottom:l}=r.zone,u=this.getStartingPosition(e),[d,f]=this.deltaToTarget(u,e,t);if(d===0&&f===0)return qi.Success;let p=r.zone,m=e=>{e=vr(e);let{left:t,right:r,top:i,bottom:a}=this.getters.expandZone(n,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(n)-1,r),top:Math.max(0,i),bottom:Math.min(this.getters.getNumberRows(n)-1,a)}},{cell:h,zone:g}=this.getReferenceAnchor(),{col:_,row:v}=h,ee=0;for(;p!==null;){if(ee++,d<0){let e=this.getNextAvailableCol(d,s-(ee-1),v);p=g.right<=s-ee?m({top:c,left:o,bottom:l,right:e}):null}if(d>0){let e=this.getNextAvailableCol(d,o+(ee-1),v);p=o+ee<=g.left?m({top:c,left:e,bottom:l,right:s}):null}if(f<0){let e=this.getNextAvailableRow(f,_,l-(ee-1));p=g.bottom<=l-ee?m({top:c,left:o,bottom:e,right:s}):null}if(f>0){let e=this.getNextAvailableRow(f,_,c+(ee-1));p=c+ee<=g.top?m({top:e,left:o,bottom:l,right:s}):null}if(p&&=vr(p),p&&!lr(p,r.zone))return this.processEvent({options:{scrollIntoView:!0},mode:`updateAnchor`,anchor:{zone:p,cell:{col:i,row:a}}})}p=m(or({top:a,bottom:a,left:i,right:i},vr({top:this.getNextAvailableRow(f,_,c),left:this.getNextAvailableCol(d,o,v),bottom:this.getNextAvailableRow(f,_,l),right:this.getNextAvailableCol(d,s,v)})));let te={zone:p,cell:{col:i,row:a}};return this.processEvent({anchor:te,mode:`updateAnchor`,options:{scrollIntoView:!0}})}selectColumn(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getNumberRows(n)-1,i={left:e,right:e,top:0,bottom:r},a=this.getters.findFirstVisibleColRowIndex(n,`ROW`),o,s;switch(t){case`overrideSelection`:case`newAnchor`:o=e,s=a;break;case`updateAnchor`:({col:o,row:s}=this.anchor.cell),i=or(i,{left:o,right:o,top:a,bottom:r});break}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:o,row:s}},mode:t})}selectRow(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getNumberCols(n)-1,i={top:e,bottom:e,left:0,right:r},a=this.getters.findFirstVisibleColRowIndex(n,`COL`),o,s;switch(t){case`overrideSelection`:case`newAnchor`:o=a,s=e;break;case`updateAnchor`:({col:o,row:s}=this.anchor.cell),i=or(i,{left:a,right:r,top:s,bottom:s});break}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:o,row:s}},mode:t})}loopSelection(){let e=this.getters.getActiveSheetId(),t=this.anchor;if(lr(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:D(t.cell)},`updateAnchor`,{scrollIntoView:!1});let n=this.getters.getContiguousZone(e,t.zone);return C(n,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:n},`updateAnchor`,{scrollIntoView:!1})}selectTableAroundSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getContiguousZone(e,this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:t},`updateAnchor`,{scrollIntoView:!1})}selectAll(){let e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({mode:`overrideSelection`,anchor:{zone:t,cell:this.anchor.cell},options:{scrollIntoView:!1}})}isListening(e){return this.stream.isListening(e)}processEvent(e){let t={...e,previousAnchor:y(this.anchor)},n=this.checkEventAnchorZone(t);return n===`Success`?(this.anchor=t.anchor,this.stream.send(t),qi.Success):new qi(n)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){let{cell:t,zone:n}=e;if(!dr(t.col,t.row,n))return`InvalidAnchorZone`;let{left:r,right:i,top:a,bottom:o}=n,s=this.getters.getActiveSheetId(),c=this.getters.findVisibleHeader(s,`COL`,r,i);return this.getters.findVisibleHeader(s,`ROW`,a,o)===void 0||c===void 0?`SelectionOutOfBound`:`Success`}checkAnchorZoneOrThrow(e){if(this.checkAnchorZone(e)===`InvalidAnchorZone`)throw Error(E(`The provided anchor is invalid. The cell must be part of the zone.`))}getNextAvailablePosition(e,t=1){let{col:n,row:r}=this.anchor.cell,i=this.deltaToTarget({col:n,row:r},e,t);return{col:this.getNextAvailableCol(i[0],n,r),row:this.getNextAvailableRow(i[1],n,r)}}getNextAvailableCol(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`COL`,t,i,e=>this.getters.isInSameMerge(r,t,n,e,n))}getNextAvailableRow(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`ROW`,n,i,e=>this.getters.isInSameMerge(r,t,n,t,e))}getNextAvailableHeader(e,t,n,r,i){let a=this.getters.getActiveSheetId();if(e===0)return n;let o=Math.sign(e),s=n+e;for(;i(s);)s+=o;for(;this.getters.isHeaderHidden(a,t,s);)s+=o;return s<0||s>this.getters.getNumberHeaders(a,t)-1?this.getters.isHeaderHidden(a,t,n)?this.getNextAvailableHeader(-o,t,n,r,i):n:s}getReferenceAnchor(){let e=this.getters.getActiveSheetId(),t=this.anchor,{left:n,right:r,top:i,bottom:a}=t.zone,{col:o,row:s}=t.cell,c=this.getters.isColHidden(e,o)&&this.getters.findVisibleHeader(e,`COL`,n,r)||o,l=this.getters.isRowHidden(e,s)&&this.getters.findVisibleHeader(e,`ROW`,i,a)||s,u=this.getters.expandZone(e,{left:c,right:c,top:l,bottom:l});return{cell:{col:c,row:l},zone:u}}deltaToTarget(e,t,n){switch(t){case`up`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,-1)-e.row]:[0,-n];case`down`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,1)-e.row]:[0,n];case`left`:return n===`end`?[this.getEndOfCluster(e,`cols`,-1)-e.col,0]:[-n,0];case`right`:return n===`end`?[this.getEndOfCluster(e,`cols`,1)-e.col,0]:[n,0]}}getStartingPosition(e){let{col:t,row:n}=this.getPosition(),r=this.anchor.zone;switch(e){case`down`:case`up`:n=n===r.top?r.bottom:r.top;break;case`left`:case`right`:t=t===r.right?r.left:r.right;break}return{col:t,row:n}}getEndOfCluster(e,t,n){let r=this.getters.getActiveSheetId(),i=e,a=this.getNextCellPosition(e,t,n),o=!this.isCellSkippableInCluster({...i,sheetId:r})&&!this.isCellSkippableInCluster({...a,sheetId:r})?`endOfCluster`:`nextCluster`;for(;;){let e=this.getNextCellPosition(i,t,n);if(i.col===e.col&&i.row===e.row)break;let a=this.isCellSkippableInCluster({...e,sheetId:r});if(o===`endOfCluster`&&a)break;if(o===`nextCluster`&&!a){i=e;break}i=e}return t===`cols`?i.col:i.row}getNextCellPosition(e,t,n){let r=t===`cols`?`col`:`row`,i={...e};return i[r]=t===`cols`?this.getNextAvailableCol(n,i.col,i.row):this.getNextAvailableRow(n,i.col,i.row),{col:i.col,row:i.row}}getPosition(){return{...this.anchor.cell}}isCellSkippableInCluster(e){let t=this.getters.getMainCellPosition(e),n=this.getters.getEvaluatedCell(t);return n.type===`empty`||n.type===`text`&&n.value===``}};function eV(e){if(typeof e==`string`)return{};if(typeof e==`number`)return[];throw Error(`Cannot create new node`)}var tV=class{changes;commands=[];recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){let t=e.pop(),n=e[0],r=e.at(-1),i=e.length-2;for(let t=1;t<=i;t++){let r=e[t];if(n[r]===void 0){let i=e[t+1];n[r]=eV(i)}n=n[r]}n[r]!==t&&(this.changes?.push({key:r,target:n,before:n[r]}),t===void 0?delete n[r]:n[r]=t)}};let nV=17781237,rV=17781238,iV=88853993,aV=88853994;function oV(e,t,n){let r=[[`xmlns:r`,of],[`xmlns:a`,tf],[`xmlns:c`,nf]],i=sV({backgroundColor:e.data.backgroundColor,line:{color:`000000`}}),a=J``;if(e.data.title?.text){let t=e.data.title.color?fD(e.data.title.color):e.data.fontColor;a=J`
2609
2609
  <c:title>
2610
- ${dV(e.data.title.text,t,22,e.data.title)}
2610
+ ${uV(e.data.title.text,t,22,e.data.title)}
2611
2611
  <c:overlay val="0" />
2612
2612
  </c:title>
2613
- `}let o=J``;switch(e.data.type){case`bar`:o=mV(e.data);break;case`combo`:o=hV(e.data);break;case`line`:o=gV(e.data);break;case`scatter`:o=_V(e.data);break;case`pie`:o=vV(e.data,t,n,{holeSize:0});break}let s=`t`;switch(e.data.legendPosition){case`bottom`:s=`b`;break;case`left`:s=`l`;break;case`right`:s=`r`;break;case`top`:s=`t`;break}let c=e.data.fontColor;return th(J`
2613
+ `}let o=J``;switch(e.data.type){case`bar`:o=pV(e.data);break;case`combo`:o=mV(e.data);break;case`line`:o=hV(e.data);break;case`scatter`:o=gV(e.data);break;case`pie`:o=_V(e.data,t,n,{holeSize:0});break}let s=`t`;switch(e.data.legendPosition){case`bottom`:s=`b`;break;case`left`:s=`l`;break;case`right`:s=`r`;break;case`top`:s=`t`;break}let c=e.data.fontColor;return th(J`
2614
2614
  <c:chartSpace ${K(r)}>
2615
2615
  <c:roundedCorners val="0" />
2616
2616
  <!-- <manualLayout/> to manually position the chart in the figure container -->
@@ -2622,26 +2622,26 @@ stores.inject(MyMetaStore, storeInstance);
2622
2622
  <!-- how the chart element is placed on the chart -->
2623
2623
  <c:layout />
2624
2624
  ${o}
2625
- ${cV({backgroundColor:e.data.backgroundColor})}
2625
+ ${sV({backgroundColor:e.data.backgroundColor})}
2626
2626
  </c:plotArea>
2627
- ${xV(s,c)}
2627
+ ${bV(s,c)}
2628
2628
  </c:chart>
2629
2629
  </c:chartSpace>
2630
- `)}function cV(e){return J`
2630
+ `)}function sV(e){return J`
2631
2631
  <c:spPr>
2632
- ${e.backgroundColor?lV(e.backgroundColor):``}
2633
- ${e.line?uV(e.line):``}
2632
+ ${e.backgroundColor?cV(e.backgroundColor):``}
2633
+ ${e.line?lV(e.line):``}
2634
2634
  </c:spPr>
2635
- `}function lV(e){return J`
2635
+ `}function cV(e){return J`
2636
2636
  <a:solidFill>
2637
2637
  <a:srgbClr val="${e}"/>
2638
2638
  </a:solidFill>
2639
- `}function uV(e){let t=[[`cmpd`,`sng`]];e.width&&t.push([`w`,Wp(e.width)]);let n=e.style?J`<a:prstDash val="${e.style}"/>`:``;return J`
2639
+ `}function lV(e){let t=[[`cmpd`,`sng`]];e.width&&t.push([`w`,Wp(e.width)]);let n=e.style?J`<a:prstDash val="${e.style}"/>`:``;return J`
2640
2640
  <a:ln ${K(t)}>
2641
- ${lV(e.color)}
2641
+ ${cV(e.color)}
2642
2642
  ${n}
2643
2643
  </a:ln>
2644
- `}function dV(e,t=`000000`,n=22,r={}){return J`
2644
+ `}function uV(e,t=`000000`,n=22,r={}){return J`
2645
2645
  <c:tx>
2646
2646
  <c:rich>
2647
2647
  <a:bodyPr />
@@ -2649,7 +2649,7 @@ stores.inject(MyMetaStore, storeInstance);
2649
2649
  <a:p>
2650
2650
  <a:pPr lvl="0">
2651
2651
  <a:defRPr b="${+!!r?.bold}" i="${+!!r?.italic}">
2652
- ${lV(t)}
2652
+ ${cV(t)}
2653
2653
  <a:latin typeface="+mn-lt"/>
2654
2654
  </a:defRPr>
2655
2655
  </a:pPr>
@@ -2660,34 +2660,34 @@ stores.inject(MyMetaStore, storeInstance);
2660
2660
  </a:p>
2661
2661
  </c:rich>
2662
2662
  </c:tx>
2663
- `}function fV(e=12,t=`000000`,n=!1,r=!1){return J`
2663
+ `}function dV(e=12,t=`000000`,n=!1,r=!1){return J`
2664
2664
  <c:txPr>
2665
2665
  <a:bodyPr/>
2666
2666
  <a:lstStyle/>
2667
2667
  <a:p>
2668
2668
  <a:pPr lvl="0">
2669
2669
  <a:defRPr ${K([[`b`,n?`1`:`0`],[`i`,r?`1`:`0`],[`sz`,e*100]])}>
2670
- ${lV(t)}
2670
+ ${cV(t)}
2671
2671
  <a:latin typeface="+mn-lt"/>
2672
2672
  </a:defRPr>
2673
2673
  </a:pPr>
2674
2674
  </a:p>
2675
2675
  </c:txPr>
2676
- `}function pV(e){return e?`text`in e&&e.text?J`
2676
+ `}function fV(e){return e?`text`in e&&e.text?J`
2677
2677
  <c:tx><c:v>${e.text}</c:v></c:tx>
2678
2678
  `:`reference`in e&&e.reference?J`
2679
2679
  <c:tx>
2680
- ${CV(e.reference)}
2680
+ ${SV(e.reference)}
2681
2681
  </c:tx>
2682
- `:J``:J``}function mV(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new wn(e.dataSets.length,t),r=[],i=[];for(let[t,a]of Object.entries(e.dataSets)){let o=fD(n.next()),s=cV({backgroundColor:o,line:{color:o}}),c=J`
2682
+ `:J``:J``}function pV(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new wn(e.dataSets.length,t),r=[],i=[];for(let[t,a]of Object.entries(e.dataSets)){let o=fD(n.next()),s=sV({backgroundColor:o,line:{color:o}}),c=J`
2683
2683
  <c:ser>
2684
2684
  <c:idx val="${t}"/>
2685
2685
  <c:order val="${t}"/>
2686
- ${pV(a.label)}
2686
+ ${fV(a.label)}
2687
2687
  ${s}
2688
- ${e.labelRange?J`<c:cat>${CV(e.labelRange)}</c:cat>`:``} <!-- x-coordinate values -->
2688
+ ${e.labelRange?J`<c:cat>${SV(e.labelRange)}</c:cat>`:``} <!-- x-coordinate values -->
2689
2689
  <c:val> <!-- x-coordinate values -->
2690
- ${wV(a.range)}
2690
+ ${CV(a.range)}
2691
2691
  </c:val>
2692
2692
  </c:ser>
2693
2693
  `;a.rightYAxis?i.push(c):r.push(c)}let a=e.stacked?`stacked`:`clustered`,o=e.stacked?100:-20;return J`
@@ -2700,11 +2700,11 @@ stores.inject(MyMetaStore, storeInstance);
2700
2700
  <!-- each data marker in the series does not have a different color -->
2701
2701
  <c:varyColors val="0"/>
2702
2702
  ${q(r)}
2703
- <c:axId val="${rV}" />
2704
- <c:axId val="${aV}" />
2703
+ <c:axId val="${nV}" />
2704
+ <c:axId val="${iV}" />
2705
2705
  </c:barChart>
2706
- ${bV(`b`,`c:catAx`,rV,aV,e.axesDesign?.x?.title,e.fontColor)}
2707
- ${bV(`l`,`c:valAx`,aV,rV,e.axesDesign?.y?.title,e.fontColor)}
2706
+ ${yV(`b`,`c:catAx`,nV,iV,e.axesDesign?.x?.title,e.fontColor)}
2707
+ ${yV(`l`,`c:valAx`,iV,nV,e.axesDesign?.y?.title,e.fontColor)}
2708
2708
  `:``}
2709
2709
  ${i.length?J`
2710
2710
  <c:barChart>
@@ -2715,24 +2715,24 @@ stores.inject(MyMetaStore, storeInstance);
2715
2715
  <!-- each data marker in the series does not have a different color -->
2716
2716
  <c:varyColors val="0"/>
2717
2717
  ${q(i)}
2718
- <c:axId val="${rV+1}" />
2719
- <c:axId val="${aV+1}" />
2718
+ <c:axId val="${17781238}" />
2719
+ <c:axId val="${88853994}" />
2720
2720
  </c:barChart>
2721
- ${bV(`b`,`c:catAx`,rV+1,aV+1,e.axesDesign?.x?.title,e.fontColor,+!!r.length)}
2722
- ${bV(`r`,`c:valAx`,aV+1,rV+1,e.axesDesign?.y1?.title,e.fontColor)}
2723
- `:``}`}function hV(e){let t=e.dataSets,n=t.map(e=>e.backgroundColor??``),r=new wn(t.length,n),i=t[0],a=fD(r.next()),o=i.rightYAxis??!1,s=J`
2721
+ ${yV(`b`,`c:catAx`,17781238,88853994,e.axesDesign?.x?.title,e.fontColor,+!!r.length)}
2722
+ ${yV(`r`,`c:valAx`,88853994,17781238,e.axesDesign?.y1?.title,e.fontColor)}
2723
+ `:``}`}function mV(e){let t=e.dataSets,n=t.map(e=>e.backgroundColor??``),r=new wn(t.length,n),i=t[0],a=fD(r.next()),o=i.rightYAxis??!1,s=J`
2724
2724
  <c:ser>
2725
2725
  <c:idx val="0"/>
2726
2726
  <c:order val="0"/>
2727
- ${pV(i.label)}
2728
- ${cV({backgroundColor:a,line:{color:a}})}
2729
- ${e.labelRange?J`<c:cat>${CV(e.labelRange)}</c:cat>`:``}
2727
+ ${fV(i.label)}
2728
+ ${sV({backgroundColor:a,line:{color:a}})}
2729
+ ${e.labelRange?J`<c:cat>${SV(e.labelRange)}</c:cat>`:``}
2730
2730
  <!-- x-coordinate values -->
2731
2731
  <c:val>
2732
- ${wV(i.range)}
2732
+ ${CV(i.range)}
2733
2733
  </c:val>
2734
2734
  </c:ser>
2735
- `,c=[],l=[];for(let n=1;n<t.length;n++){i=t[n];let a=fD(r.next()),o=cV({backgroundColor:a,line:{color:a}}),s=J`
2735
+ `,c=[],l=[];for(let n=1;n<t.length;n++){i=t[n];let a=fD(r.next()),o=sV({backgroundColor:a,line:{color:a}}),s=J`
2736
2736
  <c:ser>
2737
2737
  <c:idx val="${n}"/>
2738
2738
  <c:order val="${n}"/>
@@ -2742,12 +2742,12 @@ stores.inject(MyMetaStore, storeInstance);
2742
2742
  <c:size val="5"/>
2743
2743
  ${o}
2744
2744
  </c:marker>
2745
- ${pV(i.label)}
2745
+ ${fV(i.label)}
2746
2746
  ${o}
2747
- ${e.labelRange?J`<c:cat>${CV(e.labelRange)}</c:cat>`:``}
2747
+ ${e.labelRange?J`<c:cat>${SV(e.labelRange)}</c:cat>`:``}
2748
2748
  <!-- x-coordinate values -->
2749
2749
  <c:val>
2750
- ${wV(i.range)}
2750
+ ${CV(i.range)}
2751
2751
  </c:val>
2752
2752
  </c:ser>
2753
2753
  `;i.rightYAxis?l.push(s):c.push(s)}return J`
@@ -2759,8 +2759,8 @@ stores.inject(MyMetaStore, storeInstance);
2759
2759
  <!-- each data marker in the series does not have a different color -->
2760
2760
  <c:varyColors val="0"/>
2761
2761
  ${s}
2762
- <c:axId val="${o?iV:rV}" />
2763
- <c:axId val="${o?oV:aV}" />
2762
+ <c:axId val="${o?rV:nV}" />
2763
+ <c:axId val="${o?aV:iV}" />
2764
2764
  </c:barChart>
2765
2765
  ${c.length?J`
2766
2766
  <c:lineChart>
@@ -2768,8 +2768,8 @@ stores.inject(MyMetaStore, storeInstance);
2768
2768
  <!-- each data marker in the series does not have a different color -->
2769
2769
  <c:varyColors val="0"/>
2770
2770
  ${q(c)}
2771
- <c:axId val="${rV}" />
2772
- <c:axId val="${aV}" />
2771
+ <c:axId val="${nV}" />
2772
+ <c:axId val="${iV}" />
2773
2773
  </c:lineChart>
2774
2774
  `:``}
2775
2775
  ${l.length?J`
@@ -2778,19 +2778,19 @@ stores.inject(MyMetaStore, storeInstance);
2778
2778
  <!-- each data marker in the series does not have a different color -->
2779
2779
  <c:varyColors val="0"/>
2780
2780
  ${q(l)}
2781
- <c:axId val="${iV}" />
2782
- <c:axId val="${oV}" />
2781
+ <c:axId val="${rV}" />
2782
+ <c:axId val="${aV}" />
2783
2783
  </c:lineChart>
2784
2784
  `:``}
2785
2785
  ${!o||c.length?J`
2786
- ${bV(`b`,`c:catAx`,rV,aV,e.axesDesign?.x?.title,e.fontColor,+!!c.length)}
2787
- ${bV(`l`,`c:valAx`,aV,rV,e.axesDesign?.y?.title,e.fontColor)}
2786
+ ${yV(`b`,`c:catAx`,nV,iV,e.axesDesign?.x?.title,e.fontColor,+!!c.length)}
2787
+ ${yV(`l`,`c:valAx`,iV,nV,e.axesDesign?.y?.title,e.fontColor)}
2788
2788
  `:``}
2789
2789
  ${o||l.length?J`
2790
- ${bV(`b`,`c:catAx`,iV,oV,e.axesDesign?.x?.title,e.fontColor,c.length||!o?1:0)}
2791
- ${bV(`r`,`c:valAx`,oV,iV,e.axesDesign?.y1?.title,e.fontColor)}
2790
+ ${yV(`b`,`c:catAx`,rV,aV,e.axesDesign?.x?.title,e.fontColor,c.length||!o?1:0)}
2791
+ ${yV(`r`,`c:valAx`,aV,rV,e.axesDesign?.y1?.title,e.fontColor)}
2792
2792
  `:``}
2793
- `}function gV(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new wn(e.dataSets.length,t),r=[],i=[];for(let[t,a]of Object.entries(e.dataSets)){let o=fD(n.next()),s=cV({line:{width:2.5,style:`solid`,color:o}}),c=J`
2793
+ `}function hV(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new wn(e.dataSets.length,t),r=[],i=[];for(let[t,a]of Object.entries(e.dataSets)){let o=fD(n.next()),s=sV({line:{width:2.5,style:`solid`,color:o}}),c=J`
2794
2794
  <c:ser>
2795
2795
  <c:idx val="${t}"/>
2796
2796
  <c:order val="${t}"/>
@@ -2798,13 +2798,13 @@ stores.inject(MyMetaStore, storeInstance);
2798
2798
  <c:marker>
2799
2799
  <c:symbol val="circle" />
2800
2800
  <c:size val="5"/>
2801
- ${cV({backgroundColor:o,line:{color:o}})}
2801
+ ${sV({backgroundColor:o,line:{color:o}})}
2802
2802
  </c:marker>
2803
- ${pV(a.label)}
2803
+ ${fV(a.label)}
2804
2804
  ${s}
2805
- ${e.labelRange?J`<c:cat>${CV(e.labelRange)}</c:cat>`:``} <!-- x-coordinate values -->
2805
+ ${e.labelRange?J`<c:cat>${SV(e.labelRange)}</c:cat>`:``} <!-- x-coordinate values -->
2806
2806
  <c:val> <!-- x-coordinate values -->
2807
- ${wV(a.range)}
2807
+ ${CV(a.range)}
2808
2808
  </c:val>
2809
2809
  </c:ser>
2810
2810
  `;a.rightYAxis?i.push(c):r.push(c)}let a=e.stacked?`stacked`:`standard`;return J`
@@ -2814,11 +2814,11 @@ stores.inject(MyMetaStore, storeInstance);
2814
2814
  <!-- each data marker in the series does not have a different color -->
2815
2815
  <c:varyColors val="0"/>
2816
2816
  ${q(r)}
2817
- <c:axId val="${rV}" />
2818
- <c:axId val="${aV}" />
2817
+ <c:axId val="${nV}" />
2818
+ <c:axId val="${iV}" />
2819
2819
  </c:lineChart>
2820
- ${bV(`b`,`c:catAx`,rV,aV,e.axesDesign?.x?.title,e.fontColor)}
2821
- ${bV(`l`,`c:valAx`,aV,rV,e.axesDesign?.y?.title,e.fontColor)}
2820
+ ${yV(`b`,`c:catAx`,nV,iV,e.axesDesign?.x?.title,e.fontColor)}
2821
+ ${yV(`l`,`c:valAx`,iV,nV,e.axesDesign?.y?.title,e.fontColor)}
2822
2822
  `:``}
2823
2823
  ${i.length?J`
2824
2824
  <c:lineChart>
@@ -2826,13 +2826,13 @@ stores.inject(MyMetaStore, storeInstance);
2826
2826
  <!-- each data marker in the series does not have a different color -->
2827
2827
  <c:varyColors val="0"/>
2828
2828
  ${q(i)}
2829
- <c:axId val="${rV+1}" />
2830
- <c:axId val="${aV+1}" />
2829
+ <c:axId val="${17781238}" />
2830
+ <c:axId val="${88853994}" />
2831
2831
  </c:lineChart>
2832
- ${bV(`b`,`c:catAx`,rV+1,aV+1,e.axesDesign?.x?.title,e.fontColor,+!!r.length)}
2833
- ${bV(`r`,`c:valAx`,aV+1,rV+1,e.axesDesign?.y1?.title,e.fontColor)}
2832
+ ${yV(`b`,`c:catAx`,17781238,88853994,e.axesDesign?.x?.title,e.fontColor,+!!r.length)}
2833
+ ${yV(`r`,`c:valAx`,88853994,17781238,e.axesDesign?.y1?.title,e.fontColor)}
2834
2834
  `:``}
2835
- `}function _V(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new wn(e.dataSets.length,t),r=[],i=[];for(let[t,a]of Object.entries(e.dataSets)){let o=fD(n.next()),s=J`
2835
+ `}function gV(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new wn(e.dataSets.length,t),r=[],i=[];for(let[t,a]of Object.entries(e.dataSets)){let o=fD(n.next()),s=J`
2836
2836
  <c:ser>
2837
2837
  <c:idx val="${t}"/>
2838
2838
  <c:order val="${t}"/>
@@ -2847,14 +2847,14 @@ stores.inject(MyMetaStore, storeInstance);
2847
2847
  <c:marker>
2848
2848
  <c:symbol val="circle" />
2849
2849
  <c:size val="5"/>
2850
- ${cV({backgroundColor:o,line:{color:o}})}
2850
+ ${sV({backgroundColor:o,line:{color:o}})}
2851
2851
  </c:marker>
2852
- ${pV(a.label)}
2852
+ ${fV(a.label)}
2853
2853
  ${e.labelRange?J`<c:xVal> <!-- x-coordinate values -->
2854
- ${wV(e.labelRange)}
2854
+ ${CV(e.labelRange)}
2855
2855
  </c:xVal>`:``}
2856
2856
  <c:yVal> <!-- y-coordinate values -->
2857
- ${wV(a.range)}
2857
+ ${CV(a.range)}
2858
2858
  </c:yVal>
2859
2859
  </c:ser>
2860
2860
  `;a.rightYAxis?i.push(s):r.push(s)}return J`
@@ -2864,11 +2864,11 @@ stores.inject(MyMetaStore, storeInstance);
2864
2864
  <c:varyColors val="0"/>
2865
2865
  <c:scatterStyle val="lineMarker"/>
2866
2866
  ${q(r)}
2867
- <c:axId val="${rV}" />
2868
- <c:axId val="${aV}" />
2867
+ <c:axId val="${nV}" />
2868
+ <c:axId val="${iV}" />
2869
2869
  </c:scatterChart>
2870
- ${bV(`b`,`c:valAx`,rV,aV,e.axesDesign?.x?.title,e.fontColor)}
2871
- ${bV(`l`,`c:valAx`,aV,rV,e.axesDesign?.y?.title,e.fontColor)}
2870
+ ${yV(`b`,`c:valAx`,nV,iV,e.axesDesign?.x?.title,e.fontColor)}
2871
+ ${yV(`l`,`c:valAx`,iV,nV,e.axesDesign?.y?.title,e.fontColor)}
2872
2872
  `:``}
2873
2873
  ${i.length?J`
2874
2874
  <c:scatterChart>
@@ -2876,12 +2876,12 @@ stores.inject(MyMetaStore, storeInstance);
2876
2876
  <c:varyColors val="0"/>
2877
2877
  <c:scatterStyle val="lineMarker"/>
2878
2878
  ${q(i)}
2879
- <c:axId val="${rV+1}" />
2880
- <c:axId val="${aV+1}" />
2879
+ <c:axId val="${17781238}" />
2880
+ <c:axId val="${88853994}" />
2881
2881
  </c:scatterChart>
2882
- ${bV(`b`,`c:valAx`,rV+1,aV+1,e.axesDesign?.x?.title,e.fontColor,+!!r.length)}
2883
- ${bV(`r`,`c:valAx`,aV+1,rV+1,e.axesDesign?.y1?.title,e.fontColor)}
2884
- `:``}`}function vV(e,t,n,{holeSize:r}={holeSize:50}){let i=Gt(e.dataSets.map(e=>Gp(e.range,t,n))),a=new wn(i),o=x(0,i).map(()=>fD(a.next())),s=[];for(let[r,i]of Object.entries(e.dataSets).reverse()){let a=Gp(i.range,t,n),c=[];for(let e of x(0,a)){let t=cV({backgroundColor:o[e],line:{color:`FFFFFF`,width:1.5}});c.push(J`
2882
+ ${yV(`b`,`c:valAx`,17781238,88853994,e.axesDesign?.x?.title,e.fontColor,+!!r.length)}
2883
+ ${yV(`r`,`c:valAx`,88853994,17781238,e.axesDesign?.y1?.title,e.fontColor)}
2884
+ `:``}`}function _V(e,t,n,{holeSize:r}={holeSize:50}){let i=Gt(e.dataSets.map(e=>Gp(e.range,t,n))),a=new wn(i),o=x(0,i).map(()=>fD(a.next())),s=[];for(let[r,i]of Object.entries(e.dataSets).reverse()){let a=Gp(i.range,t,n),c=[];for(let e of x(0,a)){let t=sV({backgroundColor:o[e],line:{color:`FFFFFF`,width:1.5}});c.push(J`
2885
2885
  <c:dPt>
2886
2886
  <c:idx val="${e}"/>
2887
2887
  ${t}
@@ -2890,22 +2890,22 @@ stores.inject(MyMetaStore, storeInstance);
2890
2890
  <c:ser>
2891
2891
  <c:idx val="${r}"/>
2892
2892
  <c:order val="${r}"/>
2893
- ${pV(i.label)}
2893
+ ${fV(i.label)}
2894
2894
  ${q(c)}
2895
- ${yV({showLeaderLines:!0})}
2896
- ${e.labelRange?J`<c:cat>${CV(e.labelRange)}</c:cat>`:``}
2895
+ ${vV({showLeaderLines:!0})}
2896
+ ${e.labelRange?J`<c:cat>${SV(e.labelRange)}</c:cat>`:``}
2897
2897
  <c:val>
2898
- ${wV(i.range)}
2898
+ ${CV(i.range)}
2899
2899
  </c:val>
2900
2900
  </c:ser>
2901
2901
  `)}return J`
2902
2902
  <c:doughnutChart>
2903
2903
  <c:varyColors val="1" />
2904
2904
  <c:holeSize val="${r}" />
2905
- ${yV()}
2905
+ ${vV()}
2906
2906
  ${q(s)}
2907
2907
  </c:doughnutChart>
2908
- `}function yV({showLeaderLines:e}={showLeaderLines:!1}){return J`
2908
+ `}function vV({showLeaderLines:e}={showLeaderLines:!1}){return J`
2909
2909
  <dLbls>
2910
2910
  <c:showLegendKey val="0"/>
2911
2911
  <c:showVal val="0"/>
@@ -2915,7 +2915,7 @@ stores.inject(MyMetaStore, storeInstance);
2915
2915
  <c:showBubbleSize val="0"/>
2916
2916
  <c:showLeaderLines val="${e?`1`:`0`}"/>
2917
2917
  </dLbls>
2918
- `}function bV(e,t,n,r,i,a,o=0){let s=i?.color?fD(i.color):a;return J`
2918
+ `}function yV(e,t,n,r,i,a,o=0){let s=i?.color?fD(i.color):a;return J`
2919
2919
  <${t}>
2920
2920
  <c:axId val="${n}"/>
2921
2921
  <c:crossAx val="${r}"/> <!-- reference to the other axe of the chart -->
@@ -2925,42 +2925,42 @@ stores.inject(MyMetaStore, storeInstance);
2925
2925
  <c:orientation val="minMax" />
2926
2926
  </c:scaling>
2927
2927
  <c:axPos val="${e}" />
2928
- ${SV()}
2928
+ ${xV()}
2929
2929
  <c:majorTickMark val="out" />
2930
2930
  <c:minorTickMark val="none" />
2931
2931
  <c:numFmt formatCode="General" sourceLinked="1" />
2932
2932
  <c:title>
2933
- ${dV(i?.text??``,s,10,i)}
2933
+ ${uV(i?.text??``,s,10,i)}
2934
2934
  </c:title>
2935
- ${fV(10,a)}
2935
+ ${dV(10,a)}
2936
2936
  </${t}>
2937
2937
  <!-- <tickLblPos/> omitted -->
2938
- `}function xV(e,t){return J`
2938
+ `}function bV(e,t){return J`
2939
2939
  <c:legend>
2940
2940
  <c:legendPos val="${e}"/>
2941
2941
  <c:overlay val="0"/>
2942
- ${fV(10,t)}
2942
+ ${dV(10,t)}
2943
2943
  </c:legend>
2944
- `}function SV(e=`B7B7B7`){return J`
2944
+ `}function xV(e=`B7B7B7`){return J`
2945
2945
  <c:majorGridlines>
2946
- ${cV({line:{color:e}})}
2946
+ ${sV({line:{color:e}})}
2947
2947
  </c:majorGridlines>
2948
- `}function CV(e){return J`
2948
+ `}function SV(e){return J`
2949
2949
  <c:strRef>
2950
2950
  <c:f>${e}</c:f>
2951
2951
  </c:strRef>
2952
- `}function wV(e){return J`
2952
+ `}function CV(e){return J`
2953
2953
  <c:numRef>
2954
2954
  <c:f>${e}</c:f>
2955
2955
  <c:numCache />
2956
2956
  </c:numRef>
2957
- `}function TV(e,t){let n=e.content;if(!n)return{attrs:[],node:J``};let r=Op(e.value);return r===void 0?{attrs:[],node:J``}:{attrs:[[`cm`,`1`],[`t`,r]],node:J`<f t="array" ref="${t}">${DV(n)}</f><v>${OV(e.value)}</v>`}}function EV(e,t,n=!1){let r=e,i=[],a=r.trim().toUpperCase();return!n&&[`TRUE`,`FALSE`].includes(a)?(r=a===`TRUE`?`1`:`0`,i.push([`t`,`b`])):(n||!Oi(r,k))&&(r=zp(e,t),i.push([`t`,`s`])),{attrs:i,node:J`<v>${r}</v>`}}function DV(e){e[0]===`=`&&(e=e.slice(1));let t;try{t=mC(e)}catch{return e}return t=gC(t,`STRING`,jV),t=gC(t,`FUNCALL`,e=>(e={...e,value:e.value.toUpperCase()},e=AV(e),e=kV(e),e)),t=gC(t,`REFERENCE`,e=>e.value===j.InvalidReference?{...e,value:`#REF!`}:e),t?bC(t):e}function OV(e){return e===j.InvalidReference?`#REF!`:e}function kV(e){let t=e.value.toUpperCase(),n=e.args,r=df[t];if(r){let i=RT.content[t].args.filter(e=>!e.optional),a=i.length-e.args.length;if(a)for(let t=e.args.length;t<i.length;t++){let e=r[t-a];n.push({type:e.type,value:e.value})}}return{...e,args:n}}function AV(e){let t=e.value.toUpperCase();return{...e,value:ff.includes(t)?`_xlfn.${t}`:t}}function jV(e){let t=e.value.replace(RegExp(`"`,`g`),``),n=Qr(t,k);if(n){let r=[];return(Ur.test(t)||Wr.test(t))&&r.push(`yyyy-mm-dd`),Jr.test(t)&&r.push(`hh:mm:ss`),{...e,value:B(n.value,{format:r.join(` `),locale:k})}}else return{...e,value:e.value.replace(/\\"/g,`""`)}}function MV(e,t){let n=[];for(let r of t)switch(r.rule.type){case`CellIsRule`:n.push(NV(r,r.rule,e));break;case`ColorScaleRule`:n.push(IV(r,r.rule));break;case`IconSetRule`:n.push(LV(r,r.rule));break;default:console.warn(`Conditional formatting ${r.rule.type} not implemented`);break}return n}function NV(e,t,n){let r=RV(e),i=Dp(t.operator);r.push(...FV(t),[`operator`,i]);let a=PV(e.ranges,t).map(e=>J`<formula>${e}</formula>`),o={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&&(o.fill={fgColor:{rgb:t.style.fillColor}}),r.push([`dxfId`,zp(o,n)]),J`
2957
+ `}function wV(e,t){let n=e.content;if(!n)return{attrs:[],node:J``};let r=Op(e.value);return r===void 0?{attrs:[],node:J``}:{attrs:[[`cm`,`1`],[`t`,r]],node:J`<f t="array" ref="${t}">${EV(n)}</f><v>${DV(e.value)}</v>`}}function TV(e,t,n=!1){let r=e,i=[],a=r.trim().toUpperCase();return!n&&[`TRUE`,`FALSE`].includes(a)?(r=a===`TRUE`?`1`:`0`,i.push([`t`,`b`])):(n||!Oi(r,k))&&(r=zp(e,t),i.push([`t`,`s`])),{attrs:i,node:J`<v>${r}</v>`}}function EV(e){e[0]===`=`&&(e=e.slice(1));let t;try{t=mC(e)}catch{return e}return t=gC(t,`STRING`,AV),t=gC(t,`FUNCALL`,e=>(e={...e,value:e.value.toUpperCase()},e=kV(e),e=OV(e),e)),t=gC(t,`REFERENCE`,e=>e.value===j.InvalidReference?{...e,value:`#REF!`}:e),t?bC(t):e}function DV(e){return e===j.InvalidReference?`#REF!`:e}function OV(e){let t=e.value.toUpperCase(),n=e.args,r=df[t];if(r){let i=RT.content[t].args.filter(e=>!e.optional),a=i.length-e.args.length;if(a)for(let t=e.args.length;t<i.length;t++){let e=r[t-a];n.push({type:e.type,value:e.value})}}return{...e,args:n}}function kV(e){let t=e.value.toUpperCase();return{...e,value:ff.includes(t)?`_xlfn.${t}`:t}}function AV(e){let t=e.value.replace(RegExp(`"`,`g`),``),n=Qr(t,k);if(n){let r=[];return(Ur.test(t)||Wr.test(t))&&r.push(`yyyy-mm-dd`),Jr.test(t)&&r.push(`hh:mm:ss`),{...e,value:B(n.value,{format:r.join(` `),locale:k})}}else return{...e,value:e.value.replace(/\\"/g,`""`)}}function jV(e,t){let n=[];for(let r of t)switch(r.rule.type){case`CellIsRule`:n.push(MV(r,r.rule,e));break;case`ColorScaleRule`:n.push(FV(r,r.rule));break;case`IconSetRule`:n.push(IV(r,r.rule));break;default:console.warn(`Conditional formatting ${r.rule.type} not implemented`);break}return n}function MV(e,t,n){let r=LV(e),i=Dp(t.operator);r.push(...PV(t),[`operator`,i]);let a=NV(e.ranges,t).map(e=>J`<formula>${e}</formula>`),o={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&&(o.fill={fgColor:{rgb:t.style.fillColor}}),r.push([`dxfId`,zp(o,n)]),J`
2958
2958
  <conditionalFormatting sqref="${e.ranges.join(` `)}">
2959
2959
  <cfRule ${K(r)}>
2960
2960
  ${q(a)}
2961
2961
  </cfRule>
2962
2962
  </conditionalFormatting>
2963
- `}function PV(e,t){let n=e[0].split(`:`)[0],r=t.values;switch(t.operator){case`ContainsText`:return[`NOT(ISERROR(SEARCH("${r[0]}",${n})))`];case`NotContains`:return[`ISERROR(SEARCH("${r[0]}",${n}))`];case`BeginsWith`:return[`LEFT(${n},LEN("${r[0]}"))="${r[0]}"`];case`EndsWith`:return[`RIGHT(${n},LEN("${r[0]}"))="${r[0]}"`];case`IsEmpty`:return[`LEN(TRIM(${n}))=0`];case`IsNotEmpty`:return[`LEN(TRIM(${n}))>0`];case`Equal`:case`NotEqual`:case`GreaterThan`:case`GreaterThanOrEqual`:case`LessThan`:case`LessThanOrEqual`:return[r[0]];case`Between`:case`NotBetween`:return[r[0],r[1]]}}function FV(e){let t=Dp(e.operator);switch(e.operator){case`ContainsText`:case`NotContains`:case`BeginsWith`:case`EndsWith`:return[[`type`,t],[`text`,e.values[0]]];case`IsEmpty`:case`IsNotEmpty`:return[[`type`,t]];case`Equal`:case`NotEqual`:case`GreaterThan`:case`GreaterThanOrEqual`:case`LessThan`:case`LessThanOrEqual`:case`Between`:case`NotBetween`:return[[`type`,`cellIs`]]}}function IV(e,t){let n=RV(e);n.push([`type`,`colorScale`]);let r=[];for(let i of e.ranges){let e=[],a=[],o=!0;for(let n of[`minimum`,`midpoint`,`maximum`]){let r=t[n];if(r){if(r.type===`formula`){o=!1;continue}e.push(HV(r,n)),a.push([[`rgb`,fD($t(r.color))]])}}if(!o){console.warn(`Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.`);continue}let s=e.map(e=>J`<cfvo ${K(e)}/>`),c=a.map(e=>J`<color ${K(e)}/>`);r.push(J`
2963
+ `}function NV(e,t){let n=e[0].split(`:`)[0],r=t.values;switch(t.operator){case`ContainsText`:return[`NOT(ISERROR(SEARCH("${r[0]}",${n})))`];case`NotContains`:return[`ISERROR(SEARCH("${r[0]}",${n}))`];case`BeginsWith`:return[`LEFT(${n},LEN("${r[0]}"))="${r[0]}"`];case`EndsWith`:return[`RIGHT(${n},LEN("${r[0]}"))="${r[0]}"`];case`IsEmpty`:return[`LEN(TRIM(${n}))=0`];case`IsNotEmpty`:return[`LEN(TRIM(${n}))>0`];case`Equal`:case`NotEqual`:case`GreaterThan`:case`GreaterThanOrEqual`:case`LessThan`:case`LessThanOrEqual`:return[r[0]];case`Between`:case`NotBetween`:return[r[0],r[1]]}}function PV(e){let t=Dp(e.operator);switch(e.operator){case`ContainsText`:case`NotContains`:case`BeginsWith`:case`EndsWith`:return[[`type`,t],[`text`,e.values[0]]];case`IsEmpty`:case`IsNotEmpty`:return[[`type`,t]];case`Equal`:case`NotEqual`:case`GreaterThan`:case`GreaterThanOrEqual`:case`LessThan`:case`LessThanOrEqual`:case`Between`:case`NotBetween`:return[[`type`,`cellIs`]]}}function FV(e,t){let n=LV(e);n.push([`type`,`colorScale`]);let r=[];for(let i of e.ranges){let e=[],a=[],o=!0;for(let n of[`minimum`,`midpoint`,`maximum`]){let r=t[n];if(r){if(r.type===`formula`){o=!1;continue}e.push(VV(r,n)),a.push([[`rgb`,fD($t(r.color))]])}}if(!o){console.warn(`Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.`);continue}let s=e.map(e=>J`<cfvo ${K(e)}/>`),c=a.map(e=>J`<color ${K(e)}/>`);r.push(J`
2964
2964
  <conditionalFormatting sqref="${i}">
2965
2965
  <cfRule ${K(n)}>
2966
2966
  <colorScale>
@@ -2969,7 +2969,7 @@ stores.inject(MyMetaStore, storeInstance);
2969
2969
  </colorScale>
2970
2970
  </cfRule>
2971
2971
  </conditionalFormatting>
2972
- `)}return q(r)}function LV(e,t){let n=RV(e);n.push([`type`,`iconSet`]);let r=[];for(let i of e.ranges){let e=[[[`type`,`percent`],[`val`,0]]],a=!0;for(let n of[`lowerInflectionPoint`,`upperInflectionPoint`]){if(t[n].type===`formula`){a=!1;continue}let r=t[n];e.push([...HV(r,n),[`gte`,r.operator===`ge`?`1`:`0`]])}if(!a){console.warn(`Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.`);continue}let o=e.map(e=>J`<cfvo ${K(e)} />`),s=[[`iconSet`,BV(t.icons)]];zV(t.icons)&&s.push([`reverse`,`1`]),r.push(J`
2972
+ `)}return q(r)}function IV(e,t){let n=LV(e);n.push([`type`,`iconSet`]);let r=[];for(let i of e.ranges){let e=[[[`type`,`percent`],[`val`,0]]],a=!0;for(let n of[`lowerInflectionPoint`,`upperInflectionPoint`]){if(t[n].type===`formula`){a=!1;continue}let r=t[n];e.push([...VV(r,n),[`gte`,r.operator===`ge`?`1`:`0`]])}if(!a){console.warn(`Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.`);continue}let o=e.map(e=>J`<cfvo ${K(e)} />`),s=[[`iconSet`,zV(t.icons)]];RV(t.icons)&&s.push([`reverse`,`1`]),r.push(J`
2973
2973
  <conditionalFormatting sqref="${i}">
2974
2974
  <cfRule ${K(n)}>
2975
2975
  <iconSet ${K(s)}>
@@ -2977,7 +2977,7 @@ stores.inject(MyMetaStore, storeInstance);
2977
2977
  </iconSet>
2978
2978
  </cfRule>
2979
2979
  </conditionalFormatting>
2980
- `)}return q(r)}function RV(e){return[[`priority`,1],[`stopIfTrue`,+!!e.stopIfTrue]]}function zV(e){let t=Tf[VV(e)];return e.upper===t.bad&&e.lower===t.good}function BV(e){return $d[VV(e)]}function VV(e){return Object.keys(Tf).find(t=>Object.values(Tf[t]).includes(e.upper))||`dots`}function HV(e,t){let n=UV(e.type,t),r=[[`type`,n]];if(n!==`min`&&n!==`max`){let t=e.value;if(n===`formula`)try{t=DV(e.value)}catch{t=e.value}r.push([`val`,t])}return r}function UV(e,t){switch(e){case`value`:return t===`minimum`?`min`:`max`;case`number`:return`num`;case`percentage`:return`percent`;default:return e}}function WV(e){let t=e.length;if(t===0)return[];let n=[new Xd(`<dataValidations count="${t}">`)];for(let t of e)switch(t.criterion.type){case`dateIs`:case`dateIsBefore`:case`dateIsOnOrBefore`:case`dateIsAfter`:case`dateIsOnOrAfter`:case`dateIsBetween`:case`dateIsNotBetween`:n.push(GV(t));break;case`isEqual`:case`isNotEqual`:case`isGreaterThan`:case`isGreaterOrEqualTo`:case`isLessThan`:case`isLessOrEqualTo`:case`isBetween`:case`isNotBetween`:n.push(KV(t));break;case`isValueInRange`:case`isValueInList`:n.push(qV(t));break;case`customFormula`:n.push(JV(t));break;default:console.warn(`Data validation ${t.criterion.type} is not supported in xlsx.`);break}return n.push(new Xd(`</dataValidations>`)),n}function GV(e){let t=e.criterion,n=DV(t.values[0]),r=t.values[1]?DV(t.values[1]):void 0,i=Xp(e.criterion.type),a=YV(e);return a.push([`type`,`date`],[`operator`,i]),r?J`
2980
+ `)}return q(r)}function LV(e){return[[`priority`,1],[`stopIfTrue`,+!!e.stopIfTrue]]}function RV(e){let t=Tf[BV(e)];return e.upper===t.bad&&e.lower===t.good}function zV(e){return $d[BV(e)]}function BV(e){return Object.keys(Tf).find(t=>Object.values(Tf[t]).includes(e.upper))||`dots`}function VV(e,t){let n=HV(e.type,t),r=[[`type`,n]];if(n!==`min`&&n!==`max`){let t=e.value;if(n===`formula`)try{t=EV(e.value)}catch{t=e.value}r.push([`val`,t])}return r}function HV(e,t){switch(e){case`value`:return t===`minimum`?`min`:`max`;case`number`:return`num`;case`percentage`:return`percent`;default:return e}}function UV(e){let t=e.length;if(t===0)return[];let n=[new Xd(`<dataValidations count="${t}">`)];for(let t of e)switch(t.criterion.type){case`dateIs`:case`dateIsBefore`:case`dateIsOnOrBefore`:case`dateIsAfter`:case`dateIsOnOrAfter`:case`dateIsBetween`:case`dateIsNotBetween`:n.push(WV(t));break;case`isEqual`:case`isNotEqual`:case`isGreaterThan`:case`isGreaterOrEqualTo`:case`isLessThan`:case`isLessOrEqualTo`:case`isBetween`:case`isNotBetween`:n.push(GV(t));break;case`isValueInRange`:case`isValueInList`:n.push(KV(t));break;case`customFormula`:n.push(qV(t));break;default:console.warn(`Data validation ${t.criterion.type} is not supported in xlsx.`);break}return n.push(new Xd(`</dataValidations>`)),n}function WV(e){let t=e.criterion,n=EV(t.values[0]),r=t.values[1]?EV(t.values[1]):void 0,i=Xp(e.criterion.type),a=JV(e);return a.push([`type`,`date`],[`operator`,i]),r?J`
2981
2981
  <dataValidation ${K(a)}>
2982
2982
  <formula1>${F(n,k)}</formula1>
2983
2983
  <formula2>${F(r,k)}</formula2>
@@ -2986,7 +2986,7 @@ stores.inject(MyMetaStore, storeInstance);
2986
2986
  <dataValidation ${K(a)}>
2987
2987
  <formula1>${F(n,k)}</formula1>
2988
2988
  </dataValidation>
2989
- `}function KV(e){let t=e.criterion,n=DV(t.values[0]),r=t.values[1]?DV(t.values[1]):void 0,i=Yp(e.criterion.type),a=YV(e);return a.push([`type`,`decimal`],[`operator`,i]),r?J`
2989
+ `}function GV(e){let t=e.criterion,n=EV(t.values[0]),r=t.values[1]?EV(t.values[1]):void 0,i=Yp(e.criterion.type),a=JV(e);return a.push([`type`,`decimal`],[`operator`,i]),r?J`
2990
2990
  <dataValidation ${K(a)}>
2991
2991
  <formula1>${n}</formula1>
2992
2992
  <formula2>${r}</formula2>
@@ -2995,19 +2995,19 @@ stores.inject(MyMetaStore, storeInstance);
2995
2995
  <dataValidation ${K(a)}>
2996
2996
  <formula1>${n}</formula1>
2997
2997
  </dataValidation>
2998
- `}function qV(e){let t=e.criterion,n=e.criterion.type===`isValueInRange`?DV(t.values[0]):`"${t.values.join(`,`)}"`,r=YV(e);return r.push([`type`,`list`]),J`
2998
+ `}function KV(e){let t=e.criterion,n=e.criterion.type===`isValueInRange`?EV(t.values[0]):`"${t.values.join(`,`)}"`,r=JV(e);return r.push([`type`,`list`]),J`
2999
2999
  <dataValidation ${K(r)}>
3000
3000
  <formula1>${n}</formula1>
3001
3001
  </dataValidation>
3002
- `}function JV(e){let t=e.criterion,n=DV(t.values[0]),r=YV(e);return r.push([`type`,`custom`]),J`
3002
+ `}function qV(e){let t=e.criterion,n=EV(t.values[0]),r=JV(e);return r.push([`type`,`custom`]),J`
3003
3003
  <dataValidation ${K(r)}>
3004
3004
  <formula1>${n}</formula1>
3005
3005
  </dataValidation>
3006
- `}function YV(e){return[[`allowBlank`,`1`],[`showInputMessage`,`1`],[`showErrorMessage`,`1`],[`errorStyle`,e.isBlocking?``:`warning`],[`sqref`,e.ranges.join(` `)]]}function XV(e,t,n){let r=[[`xmlns:xdr`,ef.drawing],[`xmlns:r`,of],[`xmlns:a`,tf],[`xmlns:c`,nf]],i=[];for(let[r,a]of Object.entries(n))switch(a?.tag){case`chart`:i.push($V(a,t,e[r]));break;case`image`:i.push(eH(a,t,e[r]));break}return th(J`
3006
+ `}function JV(e){return[[`allowBlank`,`1`],[`showInputMessage`,`1`],[`showErrorMessage`,`1`],[`errorStyle`,e.isBlocking?``:`warning`],[`sqref`,e.ranges.join(` `)]]}function YV(e,t,n){let r=[[`xmlns:xdr`,ef.drawing],[`xmlns:r`,of],[`xmlns:a`,tf],[`xmlns:c`,nf]],i=[];for(let[r,a]of Object.entries(n))switch(a?.tag){case`chart`:i.push(QV(a,t,e[r]));break;case`image`:i.push($V(a,t,e[r]));break}return th(J`
3007
3007
  <xdr:wsDr ${K(r)}>
3008
3008
  ${q(i)}
3009
3009
  </xdr:wsDr>
3010
- `)}function ZV(e,t){let{x:n,y:r,height:i,width:a}=e,o=Object.values(t.cols),s=Object.values(t.rows),{index:c,offset:l}=QV(o,n),{index:u,offset:d}=QV(o,n+a),{index:f,offset:p}=QV(s,r),{index:m,offset:h}=QV(s,r+i);return{from:{col:c,colOff:l,row:f,rowOff:p},to:{col:u,colOff:d,row:m,rowOff:h}}}function QV(e,t){let n=0;for(let[r,i]of e.entries())if(n<=t&&t<n+i.size)return{index:r,offset:Wp(t-n+1)};else r<e.length-1&&(n+=i.size);return{index:e.length-1,offset:Wp(t-n+1)}}function $V(e,t,n){let{from:r,to:i}=ZV(e,t),a=Vp(e.id),o=[[`id`,a],[`name`,`Chart ${a}`],[`title`,`Chart`]];return J`
3010
+ `)}function XV(e,t){let{x:n,y:r,height:i,width:a}=e,o=Object.values(t.cols),s=Object.values(t.rows),{index:c,offset:l}=ZV(o,n),{index:u,offset:d}=ZV(o,n+a),{index:f,offset:p}=ZV(s,r),{index:m,offset:h}=ZV(s,r+i);return{from:{col:c,colOff:l,row:f,rowOff:p},to:{col:u,colOff:d,row:m,rowOff:h}}}function ZV(e,t){let n=0;for(let[r,i]of e.entries())if(n<=t&&t<n+i.size)return{index:r,offset:Wp(t-n+1)};else r<e.length-1&&(n+=i.size);return{index:e.length-1,offset:Wp(t-n+1)}}function QV(e,t,n){let{from:r,to:i}=XV(e,t),a=Vp(e.id),o=[[`id`,a],[`name`,`Chart ${a}`],[`title`,`Chart`]];return J`
3011
3011
  <xdr:twoCellAnchor>
3012
3012
  <xdr:from>
3013
3013
  <xdr:col>${r.col}</xdr:col>
@@ -3038,7 +3038,7 @@ stores.inject(MyMetaStore, storeInstance);
3038
3038
  </xdr:graphicFrame>
3039
3039
  <xdr:clientData fLocksWithSheet="0"/>
3040
3040
  </xdr:twoCellAnchor>
3041
- `}function eH(e,t,n){let{from:r,to:i}=ZV(e,t),a=Up(e.id),o=[[`id`,a],[`name`,`Image ${a}`],[`title`,`Image`]],s=Wp(e.width),c=Wp(e.height);return J`
3041
+ `}function $V(e,t,n){let{from:r,to:i}=XV(e,t),a=Up(e.id),o=[[`id`,a],[`name`,`Image ${a}`],[`title`,`Image`]],s=Wp(e.width),c=Wp(e.height);return J`
3042
3042
  <xdr:twoCellAnchor editAs="oneCell">
3043
3043
  <xdr:from>
3044
3044
  <xdr:col>${r.col}</xdr:col>
@@ -3075,13 +3075,13 @@ stores.inject(MyMetaStore, storeInstance);
3075
3075
  </xdr:pic>
3076
3076
  <xdr:clientData fLocksWithSheet="0"/>
3077
3077
  </xdr:twoCellAnchor>
3078
- `}function tH(e){let t=[];for(let[n,r]of Object.entries(e)){let e=[[`numFmtId`,parseInt(n)+164],[`formatCode`,r.format]];t.push(J`
3078
+ `}function eH(e){let t=[];for(let[n,r]of Object.entries(e)){let e=[[`numFmtId`,parseInt(n)+164],[`formatCode`,r.format]];t.push(J`
3079
3079
  <numFmt ${K(e)}/>
3080
3080
  `)}return J`
3081
3081
  <numFmts count="${e.length}">
3082
3082
  ${q(t)}
3083
3083
  </numFmts>
3084
- `}function nH(e){return St(e)?J``:J`
3084
+ `}function tH(e){return St(e)?J``:J`
3085
3085
  <font>
3086
3086
  ${e.bold?J`<b />`:``}
3087
3087
  ${e.italic?J`<i />`:``}
@@ -3091,11 +3091,11 @@ stores.inject(MyMetaStore, storeInstance);
3091
3091
  ${e.color&&e.color.rgb?J`<color rgb="${fD(e.color.rgb)}" />`:``}
3092
3092
  ${e.name?J`<name val="${e.name}" />`:``}
3093
3093
  </font>
3094
- `}function rH(e){return J`
3094
+ `}function nH(e){return J`
3095
3095
  <fonts count="${e.length}">
3096
- ${q(Object.values(e).map(nH))}
3096
+ ${q(Object.values(e).map(tH))}
3097
3097
  </fonts>
3098
- `}function iH(e){let t=[];for(let n of Object.values(e))n.reservedAttribute===void 0?t.push(J`
3098
+ `}function rH(e){let t=[];for(let n of Object.values(e))n.reservedAttribute===void 0?t.push(J`
3099
3099
  <fill>
3100
3100
  <patternFill patternType="solid">
3101
3101
  <fgColor rgb="${fD(n.fgColor.rgb)}" />
@@ -3110,35 +3110,35 @@ stores.inject(MyMetaStore, storeInstance);
3110
3110
  <fills count="${e.length}">
3111
3111
  ${q(t)}
3112
3112
  </fills>
3113
- `}function aH(e){let t=[];for(let n of Object.values(e))t.push(J`
3113
+ `}function iH(e){let t=[];for(let n of Object.values(e))t.push(J`
3114
3114
  <border>
3115
- <left ${oH(n.left)}>
3116
- ${sH(n.left)}
3115
+ <left ${aH(n.left)}>
3116
+ ${oH(n.left)}
3117
3117
  </left>
3118
- <right ${oH(n.right)}>
3119
- ${sH(n.right)}
3118
+ <right ${aH(n.right)}>
3119
+ ${oH(n.right)}
3120
3120
  </right>
3121
- <top ${oH(n.top)}>
3122
- ${sH(n.top)}
3121
+ <top ${aH(n.top)}>
3122
+ ${oH(n.top)}
3123
3123
  </top>
3124
- <bottom ${oH(n.bottom)}>
3125
- ${sH(n.bottom)}
3124
+ <bottom ${aH(n.bottom)}>
3125
+ ${oH(n.bottom)}
3126
3126
  </bottom>
3127
- <diagonal ${oH(n.diagonal)}>
3128
- ${sH(n.diagonal)}
3127
+ <diagonal ${aH(n.diagonal)}>
3128
+ ${oH(n.diagonal)}
3129
3129
  </diagonal>
3130
3130
  </border>
3131
3131
  `);return J`
3132
3132
  <borders count="${e.length}">
3133
3133
  ${q(t)}
3134
3134
  </borders>
3135
- `}function oH(e){return e?K([[`style`,e.style]]):J``}function sH(e){return e?J`
3135
+ `}function aH(e){return e?K([[`style`,e.style]]):J``}function oH(e){return e?J`
3136
3136
  <color ${K([[`rgb`,fD(e.color.rgb)]])}/>
3137
- `:J``}function cH(e){let t=[];for(let n of e){let e=[[`numFmtId`,n.numFmtId],[`fillId`,n.fillId],[`fontId`,n.fontId],[`borderId`,n.borderId]],r=[];n.alignment&&n.alignment.vertical&&r.push([`vertical`,n.alignment.vertical]),n.alignment&&n.alignment.horizontal&&r.push([`horizontal`,n.alignment.horizontal]),n.alignment&&n.alignment.wrapText&&r.push([`wrapText`,`1`]),n.alignment&&n.alignment.shrinkToFit&&r.push([`shrinkToFit`,`1`]),r.length>0?(e.push([`applyAlignment`,`1`]),t.push(J`<xf ${K(e)}><alignment ${K(r)} /></xf> `)):t.push(J`<xf ${K(e)} />`)}return J`
3137
+ `:J``}function sH(e){let t=[];for(let n of e){let e=[[`numFmtId`,n.numFmtId],[`fillId`,n.fillId],[`fontId`,n.fontId],[`borderId`,n.borderId]],r=[];n.alignment&&n.alignment.vertical&&r.push([`vertical`,n.alignment.vertical]),n.alignment&&n.alignment.horizontal&&r.push([`horizontal`,n.alignment.horizontal]),n.alignment&&n.alignment.wrapText&&r.push([`wrapText`,`1`]),n.alignment&&n.alignment.shrinkToFit&&r.push([`shrinkToFit`,`1`]),r.length>0?(e.push([`applyAlignment`,`1`]),t.push(J`<xf ${K(e)}><alignment ${K(r)} /></xf> `)):t.push(J`<xf ${K(e)} />`)}return J`
3138
3138
  <cellXfs count="${e.length}">
3139
3139
  ${q(t)}
3140
3140
  </cellXfs>
3141
- `}function lH(e){let t=[];for(let n of e){let e=J``;n.font&&(e=nH(n.font));let r=J``;n.fill&&(r=J`
3141
+ `}function cH(e){let t=[];for(let n of e){let e=J``;n.font&&(e=tH(n.font));let r=J``;n.fill&&(r=J`
3142
3142
  <fill>
3143
3143
  <patternFill>
3144
3144
  <bgColor rgb="${fD(n.fill.fgColor.rgb)}" />
@@ -3153,35 +3153,35 @@ stores.inject(MyMetaStore, storeInstance);
3153
3153
  <dxfs count="${e.length}">
3154
3154
  ${q(t)}
3155
3155
  </dxfs>
3156
- `}function uH(e,t,n){return th(J`
3156
+ `}function lH(e,t,n){return th(J`
3157
3157
  <table ${K([[`id`,t],[`name`,`Table${t}`],[`displayName`,`Table${t}`],[`ref`,e.range],[`headerRowCount`,e.config.numberOfHeaders],[`totalsRowCount`,+!!e.config.totalRow],[`xmlns`,ef.table],[`xmlns:xr`,ef.revision],[`xmlns:xr3`,ef.revision3],[`xmlns:mc`,ef.markupCompatibility]])}>
3158
- ${e.config.hasFilters?dH(e):``}
3159
- ${mH(e,n)}
3160
- ${hH(e)}
3158
+ ${e.config.hasFilters?uH(e):``}
3159
+ ${pH(e,n)}
3160
+ ${mH(e)}
3161
3161
  </table>
3162
- `)}function dH(e){return J`
3162
+ `)}function uH(e){return J`
3163
3163
  <autoFilter ${K([[`ref`,e.range]])}>
3164
- ${q(fH(e))}
3164
+ ${q(dH(e))}
3165
3165
  </autoFilter>
3166
- `}function fH(e){let t=[];for(let n of e.filters){let e=J`
3166
+ `}function dH(e){let t=[];for(let n of e.filters){let e=J`
3167
3167
  <filterColumn ${K([[`colId`,n.colId]])}>
3168
- ${pH(n)}
3168
+ ${fH(n)}
3169
3169
  </filterColumn>
3170
- `;t.push(e)}return t}function pH(e){let t=e.displayedValues.map(e=>J`<filter ${K([[`val`,e]])}/>`);return J`
3170
+ `;t.push(e)}return t}function fH(e){let t=e.displayedValues.map(e=>J`<filter ${K([[`val`,e]])}/>`);return J`
3171
3171
  <filters ${K(e.displayBlanks?[[`blank`,1]]:[])}>
3172
3172
  ${q(t)}
3173
3173
  </filters>
3174
- `}function mH(e,t){let n=Qn(e.range),r=[];for(let i of x(0,pr(n).numberOfCols)){let a=w(n.left+i,n.top),o=t.cells[a]?.content||`col${i}`,s=[[`id`,i+1],[`name`,o]];if(e.config.totalRow){let e=w(n.left+i,n.bottom);(t.cells[e]?.content)?.startsWith(`=`)&&s.push([`totalsRowFunction`,`custom`])}r.push(J`<tableColumn ${K(s)}/>`)}return J`
3174
+ `}function pH(e,t){let n=Qn(e.range),r=[];for(let i of x(0,pr(n).numberOfCols)){let a=w(n.left+i,n.top),o=t.cells[a]?.content||`col${i}`,s=[[`id`,i+1],[`name`,o]];if(e.config.totalRow){let e=w(n.left+i,n.bottom);(t.cells[e]?.content)?.startsWith(`=`)&&s.push([`totalsRowFunction`,`custom`])}r.push(J`<tableColumn ${K(s)}/>`)}return J`
3175
3175
  <tableColumns ${K([[`count`,r.length]])}>
3176
3176
  ${q(r)}
3177
3177
  </tableColumns>
3178
- `}function hH(e){return J`<tableStyleInfo ${K([[`name`,e.config.styleId],[`showFirstColumn`,+!!e.config.firstColumn],[`showLastColumn`,+!!e.config.lastColumn],[`showRowStripes`,+!!e.config.bandedRows],[`showColumnStripes`,+!!e.config.bandedColumns]])}/>`}function gH(e){if(!Object.values(e).length)return J``;let t=[];for(let[n,r]of Object.entries(e)){let e=[[`min`,parseInt(n)+1],[`max`,parseInt(n)+1],[`width`,Ap(r.size||96)],[`customWidth`,1],[`hidden`,+!!r.isHidden]];r.outlineLevel&&e.push([`outlineLevel`,r.outlineLevel]),r.collapsed&&e.push([`collapsed`,1]),t.push(J`
3178
+ `}function mH(e){return J`<tableStyleInfo ${K([[`name`,e.config.styleId],[`showFirstColumn`,+!!e.config.firstColumn],[`showLastColumn`,+!!e.config.lastColumn],[`showRowStripes`,+!!e.config.bandedRows],[`showColumnStripes`,+!!e.config.bandedColumns]])}/>`}function hH(e){if(!Object.values(e).length)return J``;let t=[];for(let[n,r]of Object.entries(e)){let e=[[`min`,parseInt(n)+1],[`max`,parseInt(n)+1],[`width`,Ap(r.size||96)],[`customWidth`,1],[`hidden`,+!!r.isHidden]];r.outlineLevel&&e.push([`outlineLevel`,r.outlineLevel]),r.collapsed&&e.push([`collapsed`,1]),t.push(J`
3179
3179
  <col ${K(e)}/>
3180
3180
  `)}return J`
3181
3181
  <cols>
3182
3182
  ${q(t)}
3183
3183
  </cols>
3184
- `}function _H(e,t,n){let r=[];for(let i=0;i<n.rowNumber;i++){let a=[[`r`,i+1]],o=n.rows[i]||{};o.size&&o.size!==23&&a.push([`ht`,kp(o.size)],[`customHeight`,1]),o.isHidden&&a.push([`hidden`,1]),o.outlineLevel&&a.push([`outlineLevel`,o.outlineLevel]),o.collapsed&&a.push([`collapsed`,1]);let s=[];for(let r=0;r<n.colNumber;r++){let a=w(r,i),o=n.cells[a];if(o){let c=[[`r`,a]],l=Fp(e,Np(o,t));l&&c.push([`s`,l]);let u=[],d=J``;if(o.isFormula){let e=TV(o,n.formulaSpillRanges[a]??a);if(!e)continue;({attrs:u,node:d}=e)}else if(o.content&&pt(o.content)){let{label:t}=gt(o.content);({attrs:u,node:d}=EV(t,e.sharedStrings))}else if(o.content&&o.content!==``){let a=vH(r,i,n),s=yH(r,i,n),c=!!(o.format&&ps(t.formats[o.format]));({attrs:u,node:d}=EV(o.content,e.sharedStrings,a||s||c))}c.push(...u),s.push(J`<c ${K(c)}>
3184
+ `}function gH(e,t,n){let r=[];for(let i=0;i<n.rowNumber;i++){let a=[[`r`,i+1]],o=n.rows[i]||{};o.size&&o.size!==23&&a.push([`ht`,kp(o.size)],[`customHeight`,1]),o.isHidden&&a.push([`hidden`,1]),o.outlineLevel&&a.push([`outlineLevel`,o.outlineLevel]),o.collapsed&&a.push([`collapsed`,1]);let s=[];for(let r=0;r<n.colNumber;r++){let a=w(r,i),o=n.cells[a];if(o){let c=[[`r`,a]],l=Fp(e,Np(o,t));l&&c.push([`s`,l]);let u=[],d=J``;if(o.isFormula){let e=wV(o,n.formulaSpillRanges[a]??a);if(!e)continue;({attrs:u,node:d}=e)}else if(o.content&&pt(o.content)){let{label:t}=gt(o.content);({attrs:u,node:d}=TV(t,e.sharedStrings))}else if(o.content&&o.content!==``){let a=_H(r,i,n),s=vH(r,i,n),c=!!(o.format&&ps(t.formats[o.format]));({attrs:u,node:d}=TV(o.content,e.sharedStrings,a||s||c))}c.push(...u),s.push(J`<c ${K(c)}>
3185
3185
  ${d}
3186
3186
  </c>`)}}(s.length||o.size!==23||o.isHidden||o.outlineLevel||o.collapsed)&&r.push(J`
3187
3187
  <row ${K(a)}>
@@ -3191,7 +3191,7 @@ stores.inject(MyMetaStore, storeInstance);
3191
3191
  <sheetData>
3192
3192
  ${q(r)}
3193
3193
  </sheetData>
3194
- `}function vH(e,t,n){return n.tables.some(n=>{let r=Qn(n.range);return dr(e,t,{...r,bottom:r.top})})}function yH(e,t,n){return n.tables.some(n=>{if(!n.config.totalRow)return!1;let r=Qn(n.range);return dr(e,t,{...r,top:r.bottom})})}function bH(e,t,n){let r=t.sheets[n].cells,i=[];for(let a in r){let o=r[a]?.content;if(o&&pt(o)){let{label:r,url:s}=gt(o);if(vt(s)){let e=bt(s),n=t.sheets.find(t=>t.id===e),o=n?`${n.name}!A1`:j.InvalidReference,c=[[`display`,r],[`location`,o],[`ref`,a]];i.push(J`
3194
+ `}function _H(e,t,n){return n.tables.some(n=>{let r=Qn(n.range);return dr(e,t,{...r,bottom:r.top})})}function vH(e,t,n){return n.tables.some(n=>{if(!n.config.totalRow)return!1;let r=Qn(n.range);return dr(e,t,{...r,top:r.bottom})})}function yH(e,t,n){let r=t.sheets[n].cells,i=[];for(let a in r){let o=r[a]?.content;if(o&&pt(o)){let{label:r,url:s}=gt(o);if(vt(s)){let e=bt(s),n=t.sheets.find(t=>t.id===e),o=n?`${n.name}!A1`:j.InvalidReference,c=[[`display`,r],[`location`,o],[`ref`,a]];i.push(J`
3195
3195
  <hyperlink ${K(c)}/>
3196
3196
  `)}else{let t=[[`r:id`,Lp(e.relsFiles,`xl/worksheets/_rels/sheet${n}.xml.rels`,{target:Ya(s),type:af.hyperlink,targetMode:`External`})],[`ref`,a]];i.push(J`
3197
3197
  <hyperlink ${K(t)}/>
@@ -3199,11 +3199,11 @@ stores.inject(MyMetaStore, storeInstance);
3199
3199
  <hyperlinks>
3200
3200
  ${q(i)}
3201
3201
  </hyperlinks>
3202
- `:J``}function xH(e){if(e.length){let t=e.map(e=>J`<mergeCell ref="${e}" />`);return J`
3202
+ `:J``}function bH(e){if(e.length){let t=e.map(e=>J`<mergeCell ref="${e}" />`);return J`
3203
3203
  <mergeCells count="${e.length}">
3204
3204
  ${q(t)}
3205
3205
  </mergeCells>
3206
- `}else return J``}function SH(e){let t=e.panes,n=J``;if(t&&(t.xSplit||t.ySplit)){let e=w(t.xSplit,t.ySplit),r=t.xSplit?J`xSplit="${t.xSplit}"`:``,i=t.ySplit?J`ySplit="${t.ySplit}"`:``,a=t.xSplit?J`<selection pane="topRight"/>`:``,o=t.ySplit?J`<selection pane="bottomLeft"/>`:``,s=t.xSplit&&t.ySplit?J`<selection pane="bottomRight"/>`:``;n=J`
3206
+ `}else return J``}function xH(e){let t=e.panes,n=J``;if(t&&(t.xSplit||t.ySplit)){let e=w(t.xSplit,t.ySplit),r=t.xSplit?J`xSplit="${t.xSplit}"`:``,i=t.ySplit?J`ySplit="${t.ySplit}"`:``,a=t.xSplit?J`<selection pane="topRight"/>`:``,o=t.ySplit?J`<selection pane="bottomLeft"/>`:``,s=t.xSplit&&t.ySplit?J`<selection pane="bottomRight"/>`:``;n=J`
3207
3207
  <pane
3208
3208
  ${r}
3209
3209
  ${i}
@@ -3219,11 +3219,11 @@ stores.inject(MyMetaStore, storeInstance);
3219
3219
  ${n}
3220
3220
  </sheetView>
3221
3221
  </sheetViews>
3222
- `}function CH(e){return e.color?J`
3222
+ `}function SH(e){return e.color?J`
3223
3223
  <sheetPr>
3224
3224
  <tabColor ${K([[`rgb`,fD(e.color)]])} />
3225
3225
  </sheetPr>
3226
- `:``}function wH(e){e=NH(e),e=PH(e);let t=[],n=rh(e);return t.push(TH(e,n)),t.push(...EH(e,n)),t.push(OH(n)),t.push(kH(n.sharedStrings)),t.push(...AH(n.relsFiles)),t.push(jH(t)),t.push(MH()),{name:`my_spreadsheet.xlsx`,files:t}}function TH(e,t){let n=[[`xmlns`,ef.workbook],[`xmlns:r`,of]],r=[];for(let[n,i]of Object.entries(e.sheets)){let e=[[`state`,i.isVisible?`visible`:`hidden`],[`name`,i.name],[`sheetId`,parseInt(n)+1],[`r:id`,`rId${parseInt(n)+1}`]];r.push(J`
3226
+ `:``}function CH(e){e=MH(e),e=NH(e);let t=[],n=rh(e);return t.push(wH(e,n)),t.push(...TH(e,n)),t.push(DH(n)),t.push(OH(n.sharedStrings)),t.push(...kH(n.relsFiles)),t.push(AH(t)),t.push(jH()),{name:`my_spreadsheet.xlsx`,files:t}}function wH(e,t){let n=[[`xmlns`,ef.workbook],[`xmlns:r`,of]],r=[];for(let[n,i]of Object.entries(e.sheets)){let e=[[`state`,i.isVisible?`visible`:`hidden`],[`name`,i.name],[`sheetId`,parseInt(n)+1],[`r:id`,`rId${parseInt(n)+1}`]];r.push(J`
3227
3227
  <sheet ${K(e)} />
3228
3228
  `),Lp(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:af.sheet,target:`worksheets/sheet${n}.xml`})}return $m(th(J`
3229
3229
  <workbook ${K(n)}>
@@ -3231,17 +3231,17 @@ stores.inject(MyMetaStore, storeInstance);
3231
3231
  ${q(r)}
3232
3232
  </sheets>
3233
3233
  </workbook>
3234
- `),`xl/workbook.xml`,`workbook`)}function EH(e,t){let n=[],r=1;for(let[i,a]of Object.entries(e.sheets)){let o=[[`xmlns`,ef.worksheet],[`xmlns:r`,of]],s=[[`defaultRowHeight`,kp(23)],[`defaultColWidth`,Ap(96)]],c=DH(a,i,r,t,n);r+=a.tables.length;let l=J``,u=[];for(let r of a.charts){let a=Vp(r.id),o=Lp(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../charts/chart${a}.xml`,type:af.chart});u.push(o),n.push($m(sV(r,i,e),`xl/charts/chart${a}.xml`,`chart`))}for(let e of a.images){let r=e.data.mimetype;if(r===void 0)continue;let a=$f[r];if(a===void 0)continue;let o=`image${Up(e.id)}.${a}`,s=Lp(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../media/${o}`,type:af.image});u.push(s),n.push({path:`xl/media/${o}`,imageSrc:e.data.path})}let d=[...a.charts,...a.images];if(d.length){let e=Lp(t.relsFiles,`xl/worksheets/_rels/sheet${i}.xml.rels`,{target:`../drawings/drawing${i}.xml`,type:af.drawing});n.push($m(XV(u,a,d),`xl/drawings/drawing${i}.xml`,`drawing`)),l=J`<drawing r:id="${e}" />`}let f=J`
3234
+ `),`xl/workbook.xml`,`workbook`)}function TH(e,t){let n=[],r=1;for(let[i,a]of Object.entries(e.sheets)){let o=[[`xmlns`,ef.worksheet],[`xmlns:r`,of]],s=[[`defaultRowHeight`,kp(23)],[`defaultColWidth`,Ap(96)]],c=EH(a,i,r,t,n);r+=a.tables.length;let l=J``,u=[];for(let r of a.charts){let a=Vp(r.id),o=Lp(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../charts/chart${a}.xml`,type:af.chart});u.push(o),n.push($m(oV(r,i,e),`xl/charts/chart${a}.xml`,`chart`))}for(let e of a.images){let r=e.data.mimetype;if(r===void 0)continue;let a=$f[r];if(a===void 0)continue;let o=`image${Up(e.id)}.${a}`,s=Lp(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../media/${o}`,type:af.image});u.push(s),n.push({path:`xl/media/${o}`,imageSrc:e.data.path})}let d=[...a.charts,...a.images];if(d.length){let e=Lp(t.relsFiles,`xl/worksheets/_rels/sheet${i}.xml.rels`,{target:`../drawings/drawing${i}.xml`,type:af.drawing});n.push($m(YV(u,a,d),`xl/drawings/drawing${i}.xml`,`drawing`)),l=J`<drawing r:id="${e}" />`}let f=J`
3235
3235
  <worksheet ${K(o)}>
3236
- ${CH(a)}
3237
3236
  ${SH(a)}
3237
+ ${xH(a)}
3238
3238
  <sheetFormatPr ${K(s)} />
3239
- ${gH(a.cols)}
3240
- ${_H(t,e,a)}
3241
- ${xH(a.merges)}
3242
- ${q(MV(t.dxfs,a.conditionalFormats))}
3243
- ${q(WV(a.dataValidationRules))}
3244
- ${bH(t,e,i)}
3239
+ ${hH(a.cols)}
3240
+ ${gH(t,e,a)}
3241
+ ${bH(a.merges)}
3242
+ ${q(jV(t.dxfs,a.conditionalFormats))}
3243
+ ${q(UV(a.dataValidationRules))}
3244
+ ${yH(t,e,i)}
3245
3245
  ${l}
3246
3246
  ${c}
3247
3247
  </worksheet>
@@ -3267,38 +3267,38 @@ stores.inject(MyMetaStore, storeInstance);
3267
3267
  </bk>
3268
3268
  </cellMetadata>
3269
3269
  </metadata>
3270
- `;return n.push($m(th(i),`xl/metadata.xml`,`metadata`)),Lp(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:af.sharedStrings,target:`sharedStrings.xml`}),Lp(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:af.styles,target:`styles.xml`}),Lp(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:af.metadata,target:`metadata.xml`}),n}function DH(e,t,n,r,i){let a=n;if(!e.tables.length)return new Xd(``);let o=`xl/worksheets/_rels/sheet${t}.xml.rels`,s=[];for(let t of e.tables){let n=Lp(r.relsFiles,o,{target:`../tables/table${a}.xml`,type:af.table});i.push($m(uH(t,a,e),`xl/tables/table${a}.xml`,`table`)),s.push(J`<tablePart r:id="${n}" />`),a++}return J`
3270
+ `;return n.push($m(th(i),`xl/metadata.xml`,`metadata`)),Lp(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:af.sharedStrings,target:`sharedStrings.xml`}),Lp(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:af.styles,target:`styles.xml`}),Lp(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:af.metadata,target:`metadata.xml`}),n}function EH(e,t,n,r,i){let a=n;if(!e.tables.length)return new Xd(``);let o=`xl/worksheets/_rels/sheet${t}.xml.rels`,s=[];for(let t of e.tables){let n=Lp(r.relsFiles,o,{target:`../tables/table${a}.xml`,type:af.table});i.push($m(lH(t,a,e),`xl/tables/table${a}.xml`,`table`)),s.push(J`<tablePart r:id="${n}" />`),a++}return J`
3271
3271
  <tableParts count="${e.tables.length}">
3272
3272
  ${q(s)}
3273
3273
  </tableParts>
3274
- `}function OH(e){return $m(th(J`
3274
+ `}function DH(e){return $m(th(J`
3275
3275
  <styleSheet ${K([[`xmlns`,ef.styleSheet],[`xmlns:r`,of]])}>
3276
- ${tH(e.numFmts)}
3277
- ${rH(e.fonts)}
3278
- ${iH(e.fills)}
3279
- ${aH(e.borders)}
3280
- ${cH(e.styles)}
3281
- ${lH(e.dxfs)}
3276
+ ${eH(e.numFmts)}
3277
+ ${nH(e.fonts)}
3278
+ ${rH(e.fills)}
3279
+ ${iH(e.borders)}
3280
+ ${sH(e.styles)}
3281
+ ${cH(e.dxfs)}
3282
3282
  </styleSheet>
3283
- `),`xl/styles.xml`,`styles`)}function kH(e){let t=[[`xmlns`,ef.sst],[`count`,e.length],[`uniqueCount`,e.length]],n=e.map(e=>e.trim()===e?J`<si><t>${e}</t></si>`:J`<si><t xml:space="preserve">${e}</t></si>`);return $m(th(J`
3283
+ `),`xl/styles.xml`,`styles`)}function OH(e){let t=[[`xmlns`,ef.sst],[`count`,e.length],[`uniqueCount`,e.length]],n=e.map(e=>e.trim()===e?J`<si><t>${e}</t></si>`:J`<si><t xml:space="preserve">${e}</t></si>`);return $m(th(J`
3284
3284
  <sst ${K(t)}>
3285
3285
  ${q(n)}
3286
3286
  </sst>
3287
- `),`xl/sharedStrings.xml`,`sharedStrings`)}function AH(e){let t=[];for(let n of e){let e=[];for(let t of n.rels){let n=[[`Id`,t.id],[`Target`,t.target],[`Type`,t.type]];t.targetMode&&n.push([`TargetMode`,t.targetMode]),e.push(J`
3287
+ `),`xl/sharedStrings.xml`,`sharedStrings`)}function kH(e){let t=[];for(let n of e){let e=[];for(let t of n.rels){let n=[[`Id`,t.id],[`Target`,t.target],[`Type`,t.type]];t.targetMode&&n.push([`TargetMode`,t.targetMode]),e.push(J`
3288
3288
  <Relationship ${K(n)} />
3289
3289
  `)}let r=J`
3290
3290
  <Relationships xmlns="${ef.Relationships}">
3291
3291
  ${q(e)}
3292
3292
  </Relationships>
3293
- `;t.push($m(th(r),n.path))}return t}function jH(e){let t=[],n=Object.entries($f).map(([e,t])=>ah(t,e));for(let n of e)`contentType`in n&&n.contentType&&t.push(ih(`/`+n.path,rf[n.contentType]));return $m(th(J`
3293
+ `;t.push($m(th(r),n.path))}return t}function AH(e){let t=[],n=Object.entries($f).map(([e,t])=>ah(t,e));for(let n of e)`contentType`in n&&n.contentType&&t.push(ih(`/`+n.path,rf[n.contentType]));return $m(th(J`
3294
3294
  <Types xmlns="${ef.Types}">
3295
3295
  ${q(Object.values(n))}
3296
3296
  <Default ${K([[`Extension`,`rels`],[`ContentType`,`application/vnd.openxmlformats-package.relationships+xml`]])} />
3297
3297
  <Default ${K([[`Extension`,`xml`],[`ContentType`,`application/xml`]])} />
3298
3298
  ${q(t)}
3299
3299
  </Types>
3300
- `),`[Content_Types].xml`)}function MH(){let e=[[`Id`,`rId1`],[`Type`,af.document],[`Target`,`xl/workbook.xml`]];return $m(th(J`
3300
+ `),`[Content_Types].xml`)}function jH(){let e=[[`Id`,`rId1`],[`Type`,af.document],[`Target`,`xl/workbook.xml`]];return $m(th(J`
3301
3301
  <Relationships xmlns="${ef.Relationships}">
3302
3302
  <Relationship ${K(e)} />
3303
3303
  </Relationships>
3304
- `),`_rels/.rels`)}function NH(e){let t={},n=new Set;for(let r of e.sheets){let e=r.name.slice(0,31),i=1;for(;n.has(e);)e=e.slice(0,31-String(i).length)+ i++;n.add(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${nt(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function PH(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>pr(Qn(e.range)).numberOfRows>1);return e}var FH=class extends rd{corePlugins=[];featurePlugins=[];statefulUIPlugins=[];coreViewsPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},n={},r=[],i=new wc,a=!1){let o=performance.now();console.debug(`##### Model creation #####`),super(),Jn(),r=Wh(e,r);let s=Rh(e,a);this.state=new nV,this.uuidGenerator=i,this.config=this.setupConfig(n),this.session=this.setupSession(s.revisionId),this.coreGetters={},this.range=new WL(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.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.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.selection=new eV(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of cB.getAll())this.setupCorePlugin(e,s);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(r);for(let e of dB.getAll()){let t=this.setupUiPlugin(e);this.coreViewsPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of uB.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of lB.getAll()){let t=this.setupUiPlugin(e);this.featurePlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}if(this.uuidGenerator.setIsFastStrategy(!1),this.dispatch(`START`),this.selection.observe(this,{handleEvent:()=>this.trigger(`update`)}),this.setupSessionEvents(),this.joinSession(),n.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly()){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),this.garbageCollectExternalResources(),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}(0,t.markRaw)(this),console.debug(`Model created in`,performance.now()-o,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:Et(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new lz(XB({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{if(!this.checkDispatchAllowed(e).isSuccessful){this.dispatchToHandlers(this.coreHandlers,{type:`UNDO`,commands:[e]});return}this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1}}),this.config.transportService,e)}setupSessionEvents(){this.session.on(`remote-revision-received`,this,this.onRemoteRevisionReceived),this.session.on(`revision-undone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`UNDO`,{commands:e}),this.finalize()}),this.session.on(`revision-redone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`REDO`,{commands:e}),this.finalize()}),this.session.on(`unexpected-revision-id`,this,()=>this.trigger(`unexpected-revision-id`)),this.session.on(`collaborative-event-received`,this,()=>{this.trigger(`update`)})}setupConfig(e){let t=e.client||{id:this.uuidGenerator.smallUuid(),name:E(`Anonymous`).toString()},n=e.transportService||new HB;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:n,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger(`notify-ui`,e),raiseBlockingErrorUI:e=>this.trigger(`raise-error-ui`,{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){let t=e.loadLocales||(()=>Promise.resolve(Xi));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,uuidGenerator:this.uuidGenerator,custom:this.config.custom,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||[]}}checkDispatchAllowed(e){let t=Gi(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>e!==`Success`)?new qi(t.flat()):qi.Success}checkDispatchAllowedCoreCommand(e){let t=this.corePlugins.map(t=>t.allowDispatch(e));return t.push(this.range.allowDispatch(e)),t}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(let e of this.handlers)e.finalize();this.status=0,this.trigger(`command-finalized`)}canDispatch=(e,t)=>this.checkDispatchAllowed(IH(e,t));dispatch=(e,t)=>{let n=IH(e,t),r=this.status;if(this.getters.isReadonly()&&!Ki(n))return new qi(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new qi(`WaitingSessionConfirmation`);switch(r){case 0:let t=this.checkDispatchAllowed(n);if(!t.isSuccessful)return this.trigger(`update`),t;this.status=1;let{changes:r,commands:i}=this.state.recordChanges(()=>{let t=performance.now();Gi(n)&&this.state.addCommand(n),this.dispatchToHandlers(this.handlers,n),this.finalize();let r=performance.now()-t;r>5&&console.debug(e,r,`ms`)});this.session.save(n,i,r),this.status=0,this.trigger(`update`);break;case 1:if(Gi(n)){let e=this.checkDispatchAllowed(n);if(!e.isSuccessful)return e;this.state.addCommand(n)}this.dispatchToHandlers(this.handlers,n);break;case 3:throw Error(`Cannot dispatch commands in the finalize state`);case 2:if(Gi(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return qi.Success};dispatchFromCorePlugin=(e,t)=>{let n=IH(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,qi.Success};dispatchToHandlers(e,t){let n=Gi(t);for(let r of e)!n&&r instanceof DL||r.beforeHandle(t);for(let r of e)!n&&r instanceof DL||r.handle(t);this.trigger(`command-dispatched`,t)}drawLayer(e,t){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore()}exportData(){let e=Xh();for(let t of this.handlers)t instanceof DL&&t.export(e);return e.revisionId=this.session.getRevisionId()||`START_REVISION`,e=y(e),e}updateMode(e){this.config.mode=e,this.trigger(`update`)}exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=Qh();for(let t of this.handlers)t instanceof EL&&t.exportForExcel(e);return e=y(e),wH(e)}garbageCollectExternalResources(){for(let e of this.corePlugins)e.garbageCollectExternalResources()}};function IH(e,t={}){let n=y(t);return n.type=e,n}let LH={},RH={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,TOPBAR_HEIGHT:63,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},zH={autoCompleteProviders:c_,autofillModifiersRegistry:$E,autofillRulesRegistry:eD,cellMenuRegistry:yj,colMenuRegistry:dN,errorTypes:ta,linkMenuRegistry:nk,functionRegistry:RT,featurePluginRegistry:lB,iconsOnCellRegistry:pf,statefulUIPluginRegistry:uB,coreViewsPluginRegistry:dB,corePluginRegistry:cB,rowMenuRegistry:gN,sidePanelRegistry:pI,figureRegistry:pO,chartSidePanelComponentRegistry:rP,chartComponentRegistry:aO,chartRegistry:iO,chartSubtypeRegistry:sO,topbarMenuRegistry:SN,topbarComponentRegistry:wN,clickableCellRegistry:fB,otRegistry:CN,inverseCommandRegistry:yO,urlRegistry:Xa,cellPopoverRegistry:uD,numberFormatMenuRegistry:fN,repeatLocalCommandTransformRegistry:Wz,repeatCommandTransformRegistry:Uz,clipboardHandlersRegistries:ed,pivotRegistry:jF,pivotTimeAdapterRegistry:lu,pivotSidePanelRegistry:LF,pivotNormalizationValueRegistry:Bu,supportedPivotPositionalFormulaRegistry:JE,pivotToFunctionValueRegistry:Vu,migrationStepRegistry:Fh},BH={arg:Y,isEvaluationError:P,toBoolean:L,toJsDate:R,toNumber:F,toString:I,toNormalizedPivotValue:Iu,toXC:w,toZone:Qn,toUnboundedZone:Zn,toCartesian:Pn,numberToLetters:Tn,lettersToNumber:En,UuidGenerator:wc,formatValue:B,createCurrencyFormat:Qo,ColorGenerator:wn,computeTextWidth:sc,createEmptyWorkbookData:Xh,createEmptySheet:Yh,createEmptyExcelSheet:Zh,getDefaultChartJsRuntime:Xg,chartFontColor:Dd,getChartAxisTitleRuntime:Md,getChartAxisType:wD,getTrendDatasetForBarChart:Fd,getTrendDatasetForLineChart:jD,getFillingMode:t_,rgbaToHex:cn,colorToRGBA:ln,positionToZone:D,isDefined:S,isMatrix:A,lazy:Et,genericRepeat:Gz,createAction:m,createActions:f,transformRangeData:nd,deepEquals:C,overlap:ur,union:or,isInside:dr,deepCopy:y,expandZoneOnInsertion:nr,reduceZoneOnDeletion:ar,unquote:at,getMaxObjectId:Ou,getFunctionsFromTokens:LE,getFirstPivotFunction:GE,getNumberOfPivotFunctions:qE,parseDimension:ju,isDateOrDatetimeField:Mu,makeFieldProposal:BE,insertTokenAfterArgSeparator:HE,insertTokenAfterLeftParenthesis:UE,mergeContiguousZones:jr,getPivotHighlights:vN,pivotTimeAdapter:uu,UNDO_REDO_PIVOT_COMMANDS:AR,createPivotFormula:Fu,areDomainArgsFieldsValid:Pu,splitReference:Vs,formatTickValue:zd,sanitizeSheetName:st,isNumber:Oi,isDateTime:Xr},VH={isMarkdownLink:pt,parseMarkdownLink:gt,markdownLink:ht,openLink:to,urlRepresentation:eo},HH={Checkbox:TN,Section:Z,RoundColorPicker:HN,ChartDataSeries:kN,ChartErrorSection:jN,ChartLabelRange:MN,ChartTitle:WN,ChartPanel:oP,ChartFigure:lO,ChartJsComponent:o_,Grid:CL,GridOverlay:eL,ScorecardChart:s_,LineConfigPanel:ZN,BarConfigPanel:PN,PieChartDesignPanel:QN,GenericChartConfigPanel:NN,ChartWithAxisDesignPanel:qN,GaugeChartConfigPanel:YN,GaugeChartDesignPanel:XN,ScorecardChartConfigPanel:eP,ScorecardChartDesignPanel:tP,ChartTypePicker:iP,FigureComponent:mI,Menu:pk,Popover:lk,SelectionInput:ON,ValidationMessages:AN,AddDimensionButton:tF,PivotDimensionGranularity:aF,PivotDimensionOrder:oF,PivotDimension:iF,PivotLayoutConfigurator:lF,PivotHTMLRenderer:TL,EditableName:wL,PivotDeferUpdate:$P,PivotTitleSection:uF,CogWheelMenu:rF,TextInput:nF,SidePanelCollapsible:IN},UH={useDragAndDropListItems:fP,useHighlights:bP,useHighlightsOnHover:yP},WH={useStoreProvider:cd,DependencyContainer:id,CellPopoverStore:GO,ComposerFocusStore:_d,CellComposerStore:EI,FindAndReplaceStore:qP,HighlightStore:xN,HoveredCellStore:WO,ModelStore:pd,NotificationStore:sP,RendererStore:md,SelectionInputStore:DN,SpreadsheetStore:hd,useStore:V,useLocalStore:ld,SidePanelStore:yL,PivotSidePanelStore:FF,PivotMeasureDisplayPanelStore:ZP};function GH(e,t){return RT.add(e,t),{addFunction:(e,t)=>GH(e,t)}}let KH={DEFAULT_LOCALE:k,HIGHLIGHT_COLOR:_,PIVOT_TABLE_CONFIG:Ze,TREND_LINE_XAXIS_ID:`x1`,CHART_AXIS_CHOICES:Vd,ChartTerms:ag};e.AbstractCellClipboardHandler=Pc,e.AbstractChart=Ag,e.AbstractFigureClipboardHandler=Gu,e.CellErrorType=j,e.CommandResult=Yi,e.CorePlugin=DL,e.DispatchResult=qi,e.EvaluationError=M,e.Model=FH,e.PivotRuntimeDefinition=dF,e.Registry=h,e.Revision=sz,e.SPREADSHEET_DIMENSIONS=RH,e.Spreadsheet=VB,e.SpreadsheetPivotTable=hF,e.UIPlugin=$,e.__info__=LH,e.addFunction=GH,e.addRenderingLayer=ea,e.astToFormula=bC,e.compile=OE,e.compileTokens=kE,e.components=HH,e.constants=KH,e.convertAstNodes=gC,e.coreTypes=Wi,e.findCellInNewZone=Sr,e.functionCache=DE,e.helpers=BH,e.hooks=UH,e.invalidateCFEvaluationCommands=Vi,e.invalidateDependenciesCommands=Bi,e.invalidateEvaluationCommands=Ri,e.iterateAstNodes=_C,e.links=VH,e.load=Rh,e.parse=mC,e.parseTokens=hC,e.readonlyAllowedCommands=Ui,e.registries=zH,e.setDefaultSheetViewSize=Ye,e.setTranslationMethod=qn,e.stores=WH,e.tokenColors=_E,e.tokenize=Rc,LH.version=`18.0.70`,LH.date=`2026-06-06T06:20:39.985Z`,LH.hash=`3ff29f6`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);
3304
+ `),`_rels/.rels`)}function MH(e){let t={},n=new Set;for(let r of e.sheets){let e=r.name.slice(0,31),i=1;for(;n.has(e);)e=e.slice(0,31-String(i).length)+i++;n.add(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${nt(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function NH(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>pr(Qn(e.range)).numberOfRows>1);return e}var PH=class extends rd{corePlugins=[];featurePlugins=[];statefulUIPlugins=[];coreViewsPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},n={},r=[],i=new wc,a=!1){let o=performance.now();console.debug(`##### Model creation #####`),super(),Jn(),r=Wh(e,r);let s=Rh(e,a);this.state=new tV,this.uuidGenerator=i,this.config=this.setupConfig(n),this.session=this.setupSession(s.revisionId),this.coreGetters={},this.range=new UL(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.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.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.selection=new $B(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of sB.getAll())this.setupCorePlugin(e,s);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(r);for(let e of uB.getAll()){let t=this.setupUiPlugin(e);this.coreViewsPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of lB.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of cB.getAll()){let t=this.setupUiPlugin(e);this.featurePlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}if(this.uuidGenerator.setIsFastStrategy(!1),this.dispatch(`START`),this.selection.observe(this,{handleEvent:()=>this.trigger(`update`)}),this.setupSessionEvents(),this.joinSession(),n.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly()){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),this.garbageCollectExternalResources(),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}(0,t.markRaw)(this),console.debug(`Model created in`,performance.now()-o,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:Et(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new cz(YB({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{if(!this.checkDispatchAllowed(e).isSuccessful){this.dispatchToHandlers(this.coreHandlers,{type:`UNDO`,commands:[e]});return}this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1}}),this.config.transportService,e)}setupSessionEvents(){this.session.on(`remote-revision-received`,this,this.onRemoteRevisionReceived),this.session.on(`revision-undone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`UNDO`,{commands:e}),this.finalize()}),this.session.on(`revision-redone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`REDO`,{commands:e}),this.finalize()}),this.session.on(`unexpected-revision-id`,this,()=>this.trigger(`unexpected-revision-id`)),this.session.on(`collaborative-event-received`,this,()=>{this.trigger(`update`)})}setupConfig(e){let t=e.client||{id:this.uuidGenerator.smallUuid(),name:E(`Anonymous`).toString()},n=e.transportService||new VB;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:n,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger(`notify-ui`,e),raiseBlockingErrorUI:e=>this.trigger(`raise-error-ui`,{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){let t=e.loadLocales||(()=>Promise.resolve(Xi));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,uuidGenerator:this.uuidGenerator,custom:this.config.custom,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||[]}}checkDispatchAllowed(e){let t=Gi(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>e!==`Success`)?new qi(t.flat()):qi.Success}checkDispatchAllowedCoreCommand(e){let t=this.corePlugins.map(t=>t.allowDispatch(e));return t.push(this.range.allowDispatch(e)),t}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(let e of this.handlers)e.finalize();this.status=0,this.trigger(`command-finalized`)}canDispatch=(e,t)=>this.checkDispatchAllowed(FH(e,t));dispatch=(e,t)=>{let n=FH(e,t),r=this.status;if(this.getters.isReadonly()&&!Ki(n))return new qi(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new qi(`WaitingSessionConfirmation`);switch(r){case 0:let t=this.checkDispatchAllowed(n);if(!t.isSuccessful)return this.trigger(`update`),t;this.status=1;let{changes:r,commands:i}=this.state.recordChanges(()=>{let t=performance.now();Gi(n)&&this.state.addCommand(n),this.dispatchToHandlers(this.handlers,n),this.finalize();let r=performance.now()-t;r>5&&console.debug(e,r,`ms`)});this.session.save(n,i,r),this.status=0,this.trigger(`update`);break;case 1:if(Gi(n)){let e=this.checkDispatchAllowed(n);if(!e.isSuccessful)return e;this.state.addCommand(n)}this.dispatchToHandlers(this.handlers,n);break;case 3:throw Error(`Cannot dispatch commands in the finalize state`);case 2:if(Gi(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return qi.Success};dispatchFromCorePlugin=(e,t)=>{let n=FH(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,qi.Success};dispatchToHandlers(e,t){let n=Gi(t);for(let r of e)!n&&r instanceof EL||r.beforeHandle(t);for(let r of e)!n&&r instanceof EL||r.handle(t);this.trigger(`command-dispatched`,t)}drawLayer(e,t){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore()}exportData(){let e=Xh();for(let t of this.handlers)t instanceof EL&&t.export(e);return e.revisionId=this.session.getRevisionId()||`START_REVISION`,e=y(e),e}updateMode(e){this.config.mode=e,this.trigger(`update`)}exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=Qh();for(let t of this.handlers)t instanceof TL&&t.exportForExcel(e);return e=y(e),CH(e)}garbageCollectExternalResources(){for(let e of this.corePlugins)e.garbageCollectExternalResources()}};function FH(e,t={}){let n=y(t);return n.type=e,n}let IH={},LH={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,TOPBAR_HEIGHT:63,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},RH={autoCompleteProviders:c_,autofillModifiersRegistry:$E,autofillRulesRegistry:eD,cellMenuRegistry:yj,colMenuRegistry:dN,errorTypes:ta,linkMenuRegistry:nk,functionRegistry:RT,featurePluginRegistry:cB,iconsOnCellRegistry:pf,statefulUIPluginRegistry:lB,coreViewsPluginRegistry:uB,corePluginRegistry:sB,rowMenuRegistry:gN,sidePanelRegistry:fI,figureRegistry:pO,chartSidePanelComponentRegistry:rP,chartComponentRegistry:aO,chartRegistry:iO,chartSubtypeRegistry:sO,topbarMenuRegistry:SN,topbarComponentRegistry:wN,clickableCellRegistry:dB,otRegistry:CN,inverseCommandRegistry:yO,urlRegistry:Xa,cellPopoverRegistry:uD,numberFormatMenuRegistry:fN,repeatLocalCommandTransformRegistry:Uz,repeatCommandTransformRegistry:Hz,clipboardHandlersRegistries:ed,pivotRegistry:AF,pivotTimeAdapterRegistry:lu,pivotSidePanelRegistry:IF,pivotNormalizationValueRegistry:Bu,supportedPivotPositionalFormulaRegistry:JE,pivotToFunctionValueRegistry:Vu,migrationStepRegistry:Fh},zH={arg:Y,isEvaluationError:P,toBoolean:L,toJsDate:R,toNumber:F,toString:I,toNormalizedPivotValue:Iu,toXC:w,toZone:Qn,toUnboundedZone:Zn,toCartesian:Pn,numberToLetters:Tn,lettersToNumber:En,UuidGenerator:wc,formatValue:B,createCurrencyFormat:Qo,ColorGenerator:wn,computeTextWidth:sc,createEmptyWorkbookData:Xh,createEmptySheet:Yh,createEmptyExcelSheet:Zh,getDefaultChartJsRuntime:Xg,chartFontColor:Dd,getChartAxisTitleRuntime:Md,getChartAxisType:wD,getTrendDatasetForBarChart:Fd,getTrendDatasetForLineChart:jD,getFillingMode:t_,rgbaToHex:cn,colorToRGBA:ln,positionToZone:D,isDefined:S,isMatrix:A,lazy:Et,genericRepeat:Wz,createAction:m,createActions:f,transformRangeData:nd,deepEquals:C,overlap:ur,union:or,isInside:dr,deepCopy:y,expandZoneOnInsertion:nr,reduceZoneOnDeletion:ar,unquote:at,getMaxObjectId:Ou,getFunctionsFromTokens:LE,getFirstPivotFunction:GE,getNumberOfPivotFunctions:qE,parseDimension:ju,isDateOrDatetimeField:Mu,makeFieldProposal:BE,insertTokenAfterArgSeparator:HE,insertTokenAfterLeftParenthesis:UE,mergeContiguousZones:jr,getPivotHighlights:vN,pivotTimeAdapter:uu,UNDO_REDO_PIVOT_COMMANDS:kR,createPivotFormula:Fu,areDomainArgsFieldsValid:Pu,splitReference:Vs,formatTickValue:zd,sanitizeSheetName:st,isNumber:Oi,isDateTime:Xr},BH={isMarkdownLink:pt,parseMarkdownLink:gt,markdownLink:ht,openLink:to,urlRepresentation:eo},VH={Checkbox:TN,Section:Z,RoundColorPicker:HN,ChartDataSeries:kN,ChartErrorSection:jN,ChartLabelRange:MN,ChartTitle:WN,ChartPanel:oP,ChartFigure:lO,ChartJsComponent:o_,Grid:SL,GridOverlay:$I,ScorecardChart:s_,LineConfigPanel:ZN,BarConfigPanel:PN,PieChartDesignPanel:QN,GenericChartConfigPanel:NN,ChartWithAxisDesignPanel:qN,GaugeChartConfigPanel:YN,GaugeChartDesignPanel:XN,ScorecardChartConfigPanel:eP,ScorecardChartDesignPanel:tP,ChartTypePicker:iP,FigureComponent:pI,Menu:pk,Popover:lk,SelectionInput:ON,ValidationMessages:AN,AddDimensionButton:tF,PivotDimensionGranularity:aF,PivotDimensionOrder:oF,PivotDimension:iF,PivotLayoutConfigurator:lF,PivotHTMLRenderer:wL,EditableName:CL,PivotDeferUpdate:$P,PivotTitleSection:uF,CogWheelMenu:rF,TextInput:nF,SidePanelCollapsible:IN},HH={useDragAndDropListItems:fP,useHighlights:bP,useHighlightsOnHover:yP},UH={useStoreProvider:cd,DependencyContainer:id,CellPopoverStore:GO,ComposerFocusStore:_d,CellComposerStore:TI,FindAndReplaceStore:qP,HighlightStore:xN,HoveredCellStore:WO,ModelStore:pd,NotificationStore:sP,RendererStore:md,SelectionInputStore:DN,SpreadsheetStore:hd,useStore:V,useLocalStore:ld,SidePanelStore:vL,PivotSidePanelStore:PF,PivotMeasureDisplayPanelStore:ZP};function WH(e,t){return RT.add(e,t),{addFunction:(e,t)=>WH(e,t)}}let GH={DEFAULT_LOCALE:k,HIGHLIGHT_COLOR:_,PIVOT_TABLE_CONFIG:Ze,TREND_LINE_XAXIS_ID:`x1`,CHART_AXIS_CHOICES:Vd,ChartTerms:ag};e.AbstractCellClipboardHandler=Pc,e.AbstractChart=Ag,e.AbstractFigureClipboardHandler=Gu,e.CellErrorType=j,e.CommandResult=Yi,e.CorePlugin=EL,e.DispatchResult=qi,e.EvaluationError=M,e.Model=PH,e.PivotRuntimeDefinition=dF,e.Registry=h,e.Revision=oz,e.SPREADSHEET_DIMENSIONS=LH,e.Spreadsheet=BB,e.SpreadsheetPivotTable=mF,e.UIPlugin=$,e.__info__=IH,e.addFunction=WH,e.addRenderingLayer=ea,e.astToFormula=bC,e.compile=OE,e.compileTokens=kE,e.components=VH,e.constants=GH,e.convertAstNodes=gC,e.coreTypes=Wi,e.findCellInNewZone=Sr,e.functionCache=DE,e.helpers=zH,e.hooks=HH,e.invalidateCFEvaluationCommands=Vi,e.invalidateDependenciesCommands=Bi,e.invalidateEvaluationCommands=Ri,e.iterateAstNodes=_C,e.links=BH,e.load=Rh,e.parse=mC,e.parseTokens=hC,e.readonlyAllowedCommands=Ui,e.registries=RH,e.setDefaultSheetViewSize=Ye,e.setTranslationMethod=qn,e.stores=UH,e.tokenColors=_E,e.tokenize=Rc,IH.version=`18.0.73`,IH.date=`2026-07-01T05:00:54.172Z`,IH.hash=`1a9c761`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);